问:
TestNG parallel Execution with DataProvider
I have a single test which receives data from data provider. I would like this test to run in parallel with different values from data provider .

I tried an approach like :

```<code>public class IndependentTest
{
@Test(dataProvider = "dp1" ,threadPoolSize=3,invocationCount=1)

public void testMethod(int number)
{
    Long id = Thread.currentThread().getId();
    System.out.println("HELLO :  " + id);
}

@DataProvider(name = "dp1",parallel=true)
public Object[][] dp1() {
  return new Object[][] {
      new Object[] { 1 },
      new Object[] { 2 },
      new Object[] { 3 },
      new Object[] { 4 },
      new Object[] { 5 },
      new Object[] { 6 },
      new Object[] { 7 },
      new Object[] { 8 }

  };
}
</code>```

}

The output i received is :

HELLO :  10

HELLO :  12

HELLO :  17

HELLO :  11

HELLO :  16

HELLO :  14

HELLO :  13

HELLO :  15

Spawned 10 threads while i specified 5 in the thread pool size .
Could you please tell what has to be added to the above snippet to control the data provider thread pool size .

答:
hi I am getting below error when i am trying to handle with data provider thread count .How to resolve the issue

java.lang.IllegalStateException: Invalid use of
  BasicClientConnManager: connection still allocated. Make sure to
  release the connection before allocating another one.

Body:
I have a single test which receives data from data provider. I would like this test to run in parallel with different values from data provider .

I tried an approach like :

public class IndependentTest
{
@Test(dataProvider = "dp1" ,threadPoolSize=3,invocationCount=1)

public void testMethod(int number)
{
    Long id = Thread.currentThread().getId();
    System.out.println("HELLO :  " + id);
}

@DataProvider(name = "dp1",parallel=true)
public Object[][] dp1() {
  return new Object[][] {
      new Object[] { 1 },
      new Object[] { 2 },
      new Object[] { 3 },
      new Object[] { 4 },
      new Object[] { 5 },
      new Object[] { 6 },
      new Object[] { 7 },
      new Object[] { 8 }

  };
}

}

The output i received is :

HELLO :  10

HELLO :  12

HELLO :  17

HELLO :  11

HELLO :  16

HELLO :  14

HELLO :  13

HELLO :  15

Spawned 10 threads while i specified 5 in the thread pool size .
Could you please tell what has to be added to the above snippet to control the data provider thread pool size .


来源: stackexchange

问:
Getting data from elasticsearch based on query using java
I have got the data from Elasticsearch index by using the below code:

```<code>SearchRequest request = new SearchRequest("football_sum_csv").scroll(new TimeValue(60000));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//    searchSourceBuilder.query(matchQuery("multi", "test"));
searchSourceBuilder.size(10000);
searchSourceBuilder.sort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC);
request.source(searchSourceBuilder);
SearchResponse scrollResp = client.search(request, RequestOptions.DEFAULT);
System.out.println(scrollResp);
</code>```

This will return all the data from my index of ElasticSearch.

In here, I want to filter some data based on my query. In my case, I want to manually enter query and get results from ElasticSearch.

For example:

This below query will return all the data as like above

```<code>query = {'query': {'bool': {'must': [{'match_all': {}}], 'must_not': [], 'should': []}} }
</code>```

This below query will return all the data in the Country named Spain

```<code>query = {"query": {"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}}
</code>```

This below query will return all the data in the os named Windows and sessionTime between 1000 and 5000

```<code>{"query": {"bool": {"must": [{"range": {"sessionTime": {"gte": 1000, "lt": 5000}}}, {"match_phrase": {"os": "Windows"}}], "must_not": [], "should": []}}}
</code>```

In the above three queries, they perform the different operations in ElasticSearch. I want to use this like queries to get my data.

If I put query inside here in above java code,

```<code>searchSourceBuilder.query({"query": {"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}});
</code>```

It gives me an error.
I know Querybuilders has lots of query options such as range, match and so on. But I want to manually enter query like the listed above and get my data from ElasticSearch. I don't know how to make it. Please help me with some solutions.

答:
Found the Answer from the comment of alexgids :

wrapperQuery needs to be used for passing query as json

```<code>String query = "{"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}";
QueryBuilder qb = QueryBuilders.wrapperQuery(query);
SearchSourceBuilder searchSourceBuilder1 = new SearchSourceBuilder();
searchSourceBuilder1.query(qb);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(searchSourceBuilder1);
SearchResponse scrollResp1 = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(scrollResp1);
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I have got the data from Elasticsearch index by using the below code:

SearchRequest request = new SearchRequest("football_sum_csv").scroll(new TimeValue(60000));
SearchSourceBuilder searchSourceBuilder = new SearchSourceBuilder();
//    searchSourceBuilder.query(matchQuery("multi", "test"));
searchSourceBuilder.size(10000);
searchSourceBuilder.sort(FieldSortBuilder.DOC_FIELD_NAME, SortOrder.ASC);
request.source(searchSourceBuilder);
SearchResponse scrollResp = client.search(request, RequestOptions.DEFAULT);
System.out.println(scrollResp);

This will return all the data from my index of ElasticSearch.

In here, I want to filter some data based on my query. In my case, I want to manually enter query and get results from ElasticSearch.

For example:

This below query will return all the data as like above

query = {'query': {'bool': {'must': [{'match_all': {}}], 'must_not': [], 'should': []}} }

This below query will return all the data in the Country named Spain

query = {"query": {"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}}

This below query will return all the data in the os named Windows and sessionTime between 1000 and 5000

{"query": {"bool": {"must": [{"range": {"sessionTime": {"gte": 1000, "lt": 5000}}}, {"match_phrase": {"os": "Windows"}}], "must_not": [], "should": []}}}

In the above three queries, they perform the different operations in ElasticSearch. I want to use this like queries to get my data.

If I put query inside here in above java code,

searchSourceBuilder.query({"query": {"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}});

It gives me an error.
I know Querybuilders has lots of query options such as range, match and so on. But I want to manually enter query like the listed above and get my data from ElasticSearch. I don't know how to make it. Please help me with some solutions.

Body:
Found the Answer from the comment of alexgids :

wrapperQuery needs to be used for passing query as json

String query = "{"bool": {"must": [{"match_phrase": {"countryName": "Spain"}}], "must_not": [], "should": []}}";
QueryBuilder qb = QueryBuilders.wrapperQuery(query);
SearchSourceBuilder searchSourceBuilder1 = new SearchSourceBuilder();
searchSourceBuilder1.query(qb);
SearchRequest searchRequest = new SearchRequest("index_name");
searchRequest.source(searchSourceBuilder1);
SearchResponse scrollResp1 = client.search(searchRequest, RequestOptions.DEFAULT);
System.out.println(scrollResp1);


问:
Request.CreateResponse in asp.net core
Below is my code (Partial code) and I want to migrate it into asp.net core.
My problem is "Request.CreateResponse" is not working in below code. I google it a lot but unable to find any solution. How can I solve it? Package Microsoft.AspNet.WebApi.Core is also not working.

```<code>    [HttpPost]
    public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
    {
        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }
</code>```

Thanks in advance.

答:
Instead of returning Request.Create Response, Latest version allows to return Ok for 200 http status code & add a model on your response if you want to
Also Return IActionResult instead of HttpResponseMessage</p>

```<code>public IActionResult Method()
{
  try
  {
     return Ok(new TokenResponseModel { Status = "ok", Message = "valid token" });
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Title: Request.CreateResponse in asp.net core

Body:
Below is my code (Partial code) and I want to migrate it into asp.net core.
My problem is "Request.CreateResponse" is not working in below code. I google it a lot but unable to find any solution. How can I solve it? Package Microsoft.AspNet.WebApi.Core is also not working.

    [HttpPost]
    public HttpResponseMessage AddBusinessUsersToBusinessUnit(MyObject request)
    {
        return Request.CreateResponse(HttpStatusCode.Unauthorized);
    }

Thanks in advance.

Body:
Instead of returning Request.Create Response, Latest version allows to return Ok for 200 http status code & add a model on your response if you want to
Also Return IActionResult instead of HttpResponseMessage

public IActionResult Method()
{
  try
  {
     return Ok(new TokenResponseModel { Status = "ok", Message = "valid token" });
  }
}


问:
java.lang.Exception: No runnable methods exception in running JUnits
I am trying to run the JUnit on my Linux command prompt /opt/junit/ contains the necessary JARS(hamcrest-core-1.3.jar and junit.jar) and class files and I am using the following command to run the JUnit:

```<code>java -cp hamcrest-core-1.3.jar:junit.jar:. org.junit.runner.JUnitCore  TestRunner
</code>```

TestJunit class:

```<code>import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
   @Test
   public void testAdd() {
      String str= "Junit is working fine";
      assertEquals("Junit is working fine",str);
   }
}
</code>```

TestRunner:

```<code>import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println("fail ho gaya"+failure.toString());
      }
      System.out.println("passed:"+result.wasSuccessful());
   }
}
</code>```

I am getting the following exception on running this

```<code>JUnit version 4.11
.E
Time: 0.003
There was 1 failure:
1) initializationError(TestRunner)
java.lang.Exception: No runnable methods
    at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:169)
    at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:104)
    at org.junit.runners.ParentRunner.validate(ParentRunner.java:355)
    at org.junit.runners.ParentRunner.<init>(ParentRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:57)
    at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runner.Computer.getRunner(Computer.java:40)
    at org.junit.runner.Computer$1.runnerForClass(Computer.java:31)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:101)
    at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:87)
    at org.junit.runners.Suite.<init>(Suite.java:80)
    at org.junit.runner.Computer.getSuite(Computer.java:28)
    at org.junit.runner.Request.classes(Request.java:75)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
    at org.junit.runner.JUnitCore.runMain(JUnitCore.java:96)
    at org.junit.runner.JUnitCore.runMainAndExit(JUnitCore.java:47)
    at org.junit.runner.JUnitCore.main(JUnitCore.java:40)

FAILURES!!!
Tests run: 1,  Failures: 1
</code>```

答:
I faced the same with my parent test setUp class which has annotation @RunWith(SpringRunner.class) and was being extended by other testClasses.
As there was not test in the setUpclass , and Junit was trying to find one due to annotation @RunWith(SpringRunner.class) ,it didn't find one and threw exception

No runnable methods exception in running JUnits

I made my parent class as abstract and it worked like a charm .

I took help from here https://stackoverflow.com/a/10699141/8029525 .
Thanks for help @froh42.

Body:
I am trying to run the JUnit on my Linux command prompt /opt/junit/ contains the necessary JARS(hamcrest-core-1.3.jar and junit.jar) and class files and I am using the following command to run the JUnit:

java -cp hamcrest-core-1.3.jar:junit.jar:. org.junit.runner.JUnitCore  TestRunner

TestJunit class:

import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TestJunit {
   @Test
   public void testAdd() {
      String str= "Junit is working fine";
      assertEquals("Junit is working fine",str);
   }
}

TestRunner:

import org.junit.runner.JUnitCore;
import org.junit.runner.Result;
import org.junit.runner.notification.Failure;

public class TestRunner {
   public static void main(String[] args) {
      Result result = JUnitCore.runClasses(TestJunit.class);
      for (Failure failure : result.getFailures()) {
         System.out.println("fail ho gaya"+failure.toString());
      }
      System.out.println("passed:"+result.wasSuccessful());
   }
}

I am getting the following exception on running this

JUnit version 4.11
.E
Time: 0.003
There was 1 failure:
1) initializationError(TestRunner)
java.lang.Exception: No runnable methods
    at org.junit.runners.BlockJUnit4ClassRunner.validateInstanceMethods(BlockJUnit4ClassRunner.java:169)
    at org.junit.runners.BlockJUnit4ClassRunner.collectInitializationErrors(BlockJUnit4ClassRunner.java:104)
    at org.junit.runners.ParentRunner.validate(ParentRunner.java:355)
    at org.junit.runners.ParentRunner.<init>(ParentRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.<init>(BlockJUnit4ClassRunner.java:57)
    at org.junit.internal.builders.JUnit4Builder.runnerForClass(JUnit4Builder.java:10)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.internal.builders.AllDefaultPossibilitiesBuilder.runnerForClass(AllDefaultPossibilitiesBuilder.java:26)
    at org.junit.runner.Computer.getRunner(Computer.java:40)
    at org.junit.runner.Computer$1.runnerForClass(Computer.java:31)
    at org.junit.runners.model.RunnerBuilder.safeRunnerForClass(RunnerBuilder.java:59)
    at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:101)
    at org.junit.runners.model.RunnerBuilder.runners(RunnerBuilder.java:87)
    at org.junit.runners.Suite.<init>(Suite.java:80)
    at org.junit.runner.Computer.getSuite(Computer.java:28)
    at org.junit.runner.Request.classes(Request.java:75)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:117)
    at org.junit.runner.JUnitCore.runMain(JUnitCore.java:96)
    at org.junit.runner.JUnitCore.runMainAndExit(JUnitCore.java:47)
    at org.junit.runner.JUnitCore.main(JUnitCore.java:40)

FAILURES!!!
Tests run: 1,  Failures: 1


问:
Remove duplicate dict in list in Python
I have a list of dicts, and I'd like to remove the dicts with identical key and value pairs.

For this list: [{'a': 123}, {'b': 123}, {'a': 123}]

I'd like to return this: [{'a': 123}, {'b': 123}]

Another example:

For this list: [{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}, {'a': 123, 'b': 1234}]

I'd like to return this: [{'a': 123, 'b': 1234}, {'a': 3222, 'b': 1234}]

答:
Here's a quick one-line solution with a doubly-nested list comprehension (based on @Emmanuel 's solution).

This uses a single key (for example, a) in each dict as the primary key, rather than checking if the entire dict matches

```<code>[i for n, i in enumerate(list_of_dicts) if i.get(primary_key) not in [y.get(primary_key) for y in list_of_dicts[n + 1:]]]
</code>```

It's not what OP asked for, but it's what brought me to this thread, so I figured I'd post the solution I ended up with

Title: Remove duplicate dict in list in Python

Body:
Here's a quick one-line solution with a doubly-nested list comprehension (based on @Emmanuel 's solution).

This uses a single key (for example, a) in each dict as the primary key, rather than checking if the entire dict matches

[i for n, i in enumerate(list_of_dicts) if i.get(primary_key) not in [y.get(primary_key) for y in list_of_dicts[n + 1:]]]

It's not what OP asked for, but it's what brought me to this thread, so I figured I'd post the solution I ended up with


问:
If my interface must return Task what is the best way to have a no-operation implementation?
In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument's sake can't be changed). If LazyBars implementation is unusual in that it happens to run quickly and synchronously - what is the best way to return a No-Operation task from the method?

I have gone with Task.Delay(0) below, however I would like to know if this has any performance side-effects if the function is called a lot (for argument's sake, say hundreds of times a second):

Does this syntactic sugar un-wind to something big?

Does it start clogging up my application's thread pool?

Is the compiler cleaver enough to deal with Delay(0) differently?

Would return Task.Run(() => { }); be any different?

Is there a better way?

```<code>using System.Threading.Tasks;

namespace MyAsyncTest
{
    internal interface IFooFace
    {
        Task WillBeLongRunningAsyncInTheMajorityOfImplementations();
    }

    /// <summary>
    /// An implementation, that unlike most cases, will not have a long-running
    /// operation in 'WillBeLongRunningAsyncInTheMajorityOfImplementations'
    /// </summary>
    internal class LazyBar : IFooFace
    {
        #region IFooFace Members

        public Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
        {
            // First, do something really quick
            var x = 1;

            // Can't return 'null' here! Does 'Task.Delay(0)' have any performance considerations?
            // Is it a real no-op, or if I call this a lot, will it adversely affect the
            // underlying thread-pool? Better way?
            return Task.Delay(0);

            // Any different?
            // return Task.Run(() => { });

            // If my task returned something, I would do:
            // return Task.FromResult<int>(12345);
        }

        #endregion
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Test();
        }

        private static async void Test()
        {
            IFooFace foo = FactoryCreate();
            await foo.WillBeLongRunningAsyncInTheMajorityOfImplementations();
            return;
        }

        private static IFooFace FactoryCreate()
        {
            return new LazyBar();
        }
    }
}
</code>```

答:
If you are using generics, all answer will give us compile error. You can use return default(T);. Sample below to explain further.

```<code>public async Task<T> GetItemAsync<T>(string id)
            {
                try
                {
                    var response = await this._container.ReadItemAsync<T>(id, new PartitionKey(id));
                    return response.Resource;
                }
                catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {

                    return default(T);
                }

            }
</code>```

Body:
In the code below, due to the interface, the class LazyBar must return a task from its method (and for argument's sake can't be changed). If LazyBars implementation is unusual in that it happens to run quickly and synchronously - what is the best way to return a No-Operation task from the method?

I have gone with Task.Delay(0) below, however I would like to know if this has any performance side-effects if the function is called a lot (for argument's sake, say hundreds of times a second):

Does this syntactic sugar un-wind to something big?

Does it start clogging up my application's thread pool?

Is the compiler cleaver enough to deal with Delay(0) differently?

Would return Task.Run(() => { }); be any different?

Is there a better way?

using System.Threading.Tasks;

namespace MyAsyncTest
{
    internal interface IFooFace
    {
        Task WillBeLongRunningAsyncInTheMajorityOfImplementations();
    }

    ///
    /// An implementation, that unlike most cases, will not have a long-running
    /// operation in 'WillBeLongRunningAsyncInTheMajorityOfImplementations'
    ///
    internal class LazyBar : IFooFace
    {
        #region IFooFace Members

        public Task WillBeLongRunningAsyncInTheMajorityOfImplementations()
        {
            // First, do something really quick
            var x = 1;

            // Can't return 'null' here! Does 'Task.Delay(0)' have any performance considerations?
            // Is it a real no-op, or if I call this a lot, will it adversely affect the
            // underlying thread-pool? Better way?
            return Task.Delay(0);

            // Any different?
            // return Task.Run(() => { });

            // If my task returned something, I would do:
            // return Task.FromResult<int>(12345);
        }

        #endregion
    }

    internal class Program
    {
        private static void Main(string[] args)
        {
            Test();
        }

        private static async void Test()
        {
            IFooFace foo = FactoryCreate();
            await foo.WillBeLongRunningAsyncInTheMajorityOfImplementations();
            return;
        }

        private static IFooFace FactoryCreate()
        {
            return new LazyBar();
        }
    }
}

Body:
If you are using generics, all answer will give us compile error. You can use return default(T);. Sample below to explain further.

public async Task<T> GetItemAsync<T>(string id)
            {
                try
                {
                    var response = await this._container.ReadItemAsync<T>(id, new PartitionKey(id));
                    return response.Resource;
                }
                catch (CosmosException ex) when (ex.StatusCode == System.Net.HttpStatusCode.NotFound)
                {

                    return default(T);
                }

            }


问:
Creating an HTTPS proxy server in Python
I am trying to create an HTTPS proxy server in python, I created the following script that works with HTTP.

#!/usr/bin/env python3
# coding=utf-8

import socket
from threading import Thread

class Proxy:
    def __init__(self, port=3000):
        self.port = port
        self.proxy = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.proxy.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.buffer_size = 4096

    def run(self):
        self.proxy.bind(("0.0.0.0", self.port))
        self.proxy.listen(100)
        print("  * Proxy server is running on port {}".format(self.port))

        while True:
            client, addr = self.proxy.accept()
            print(" => {}:{}".format(addr[0], addr[1]))
            Thread(target=self.handle_request, args=(client,)).start()

    def handle_request(self, client):
        head = self.parse_head(client.recv(self.buffer_size))
        headers = head["headers"]
        request = "{}\r\n".format(head["meta"])
        for key, value in headers.items():
            request += "{}: {}\r\n".format(key, value)
        request += "\r\n"
        if "content-length" in headers:
            while len(head["chunk"]) < int(headers["content-length"]):
                head["chunk"] += client.recv(self.buffer_size)

        request = request.encode() + head["chunk"]
        port = 80
        try:
            tmp = head["meta"].split(" ")[1].split("://")[1].split("/")[0]
        except IndexError:
            client.close()
            return
        if tmp.find(":") > -1:
            port = int(tmp.split(":")[1])

        response = self.send_to_server(headers["host"], port, request)
        client.sendall(response)
        client.close()

    def send_to_server(self, host, port, data):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.connect((socket.gethostbyname(host), port))
        server.sendall(data)

        head = self.parse_head(server.recv(4096))
        headers = head["headers"]
        response = "{}\r\n".format(head["meta"])
        for key, value in headers.items():
            response += "{}: {}\r\n".format(key, value)
        response += "\r\n"

        if "content-length" in headers:
            while len(head["chunk"]) < int(headers["content-length"]):
                head["chunk"] += server.recv(self.buffer_size)

        response = response.encode() + head["chunk"]
        server.close()
        return response

    def parse_head(self, head_request):
        nodes = head_request.split(b"\r\n\r\n")
        heads = nodes[0].split(b"\r\n")
        meta = heads.pop(0).decode("utf-8")
        data = {
            "meta": meta,
            "headers": {},
            "chunk": b""
        }

        if len(nodes) >= 2:
            data["chunk"] = nodes[1]

        for head in heads:
            pieces = head.split(b": ")
            key = pieces.pop(0).decode("utf-8")
            if key.startswith("Connection: "):
                data["headers"][key.lower()] = "close"
            else:
                data["headers"][key.lower()] = b": ".join(pieces).decode("utf-8")
        return data

if __name__ == "__main__":
    proxy = Proxy(3001)
    proxy.run()
```

<p>I never worked with SSL stuff in Python, so I used the <code>ssl</code> module to create an HTTPS socket.</p>

<pre class="lang-py prettyprint-override"><code>#!/usr/bin/env python3
# coding=utf-8

import socket
import ssl
from threading import Thread

class Proxy:
    def __init__(self, port=3000):
        self.port = port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.proxy = ssl.wrap_socket(self.s, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
        self.buffer_size = 4096

    def run(self):
        self.proxy.bind(("0.0.0.0", self.port))
        self.proxy.listen(100)
        print("  * Proxy server is running on port {}".format(self.port))

        while True:
            client, addr = self.proxy.accept()
            print(" => {}:{}".format(addr[0], addr[1]))
            Thread(target=self.handle_request, args=(client,)).start()

    def handle_request(self, client):
        head = self.parse_head(client.recv(self.buffer_size))
        headers = head["headers"]
        request = "{}\r\n".format(head["meta"])
        for key, value in headers.items():
            request += "{}: {}\r\n".format(key, value)
        request += "\r\n"
        if "content-length" in headers:
            while len(head["chunk"]) < int(headers["content-length"]):
                head["chunk"] += client.recv(self.buffer_size)

        request = request.encode() + head["chunk"]
        port = 80
        try:
            tmp = head["meta"].split(" ")[1].split("://")[1].split("/")[0]
        except IndexError:
            client.close()
            return
        if tmp.find(":") > -1:
            port = int(tmp.split(":")[1])

        response = self.send_to_server(headers["host"], port, request)
        client.sendall(response)
        client.close()

    def send_to_server(self, host, port, data):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.connect((socket.gethostbyname(host), port))
        server.sendall(data)

        head = self.parse_head(server.recv(4096))
        headers = head["headers"]
        response = "{}\r\n".format(head["meta"])
        for key, value in headers.items():
            response += "{}: {}\r\n".format(key, value)
        response += "\r\n"

        if "content-length" in headers:
            while len(head["chunk"]) < int(headers["content-length"]):
                head["chunk"] += server.recv(self.buffer_size)

        response = response.encode() + head["chunk"]
        server.close()
        return response

    def parse_head(self, head_request):
        nodes = head_request.split(b"\r\n\r\n")
        heads = nodes[0].split(b"\r\n")
        meta = heads.pop(0).decode("utf-8")
        data = {
            "meta": meta,
            "headers": {},
            "chunk": b""
        }

        if len(nodes) >= 2:
            data["chunk"] = nodes[1]

        for head in heads:
            pieces = head.split(b": ")
            key = pieces.pop(0).decode("utf-8")
            if key.startswith("Connection: "):
                data["headers"][key.lower()] = "close"
            else:
                data["headers"][key.lower()] = b": ".join(pieces).decode("utf-8")
        return data

if __name__ == "__main__":
    proxy = Proxy(3001)
    proxy.run()
</code>```

But I get the following error.

  * Proxy server is running on port 3001
Traceback (most recent call last):
  File ".\proxy.py", line 98, in <module>
    proxy.run()
  File ".\proxy.py", line 22, in run
    client, addr = self.proxy.accept()
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1355, in accept
    newsock = self.context.wrap_socket(newsock,
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: HTTPS_PROXY_REQUEST] https proxy request (_ssl.c:1108)
```

答:
The problem is actually not related to SSL at all but caused by a misunderstanding of how a HTTP proxy for HTTPS works. Such a proxy is not doing SSL at all. It is instead just used to create a tunnel to the final server and the client then creates the HTTPS connection trough this tunnel, keeping the end-to-end encryption this way.

The tunnel itself is created using the HTTP CONNECT method. And this is exactly what you are getting here on your SSL socket:

```<code> ssl.SSLError: [SSL: HTTPS_PROXY_REQUEST] https proxy request (_ssl.c:1108)
                                          ^^^^^^^^^^^^^^^^^^^
</code>```

Body:
I am trying to create an HTTPS proxy server in python, I created the following script that works with HTTP.

#!/usr/bin/env python3
# coding=utf-8

import socket
from threading import Thread

class Proxy:
    def __init__(self, port=3000):
        self.port = port
        self.proxy = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.proxy.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
        self.buffer_size = 4096

    def run(self):
        self.proxy.bind(("0.0.0.0", self.port))
        self.proxy.listen(100)
        print("  * Proxy server is running on port {}".format(self.port))

        while True:
            client, addr = self.proxy.accept()
            print(" => {}:{}".format(addr[0], addr[1]))
            Thread(target=self.handle_request, args=(client,)).start()

    def handle_request(self, client):
        head = self.parse_head(client.recv(self.buffer_size))
        headers = head["headers"]
        request = "{}\r\n".format(head["meta"])
        for key, value in headers.items():
            request += "{}: {}\r\n".format(key, value)
        request += "\r\n"
        if "content-length" in headers:
            while len(head["chunk"]) < int(headers["content-length"]):
                head["chunk"] += client.recv(self.buffer_size)

        request = request.encode() + head["chunk"]
        port = 80
        try:
            tmp = head["meta"].split(" ")[1].split("://")[1].split("/")[0]
        except IndexError:
            client.close()
            return
        if tmp.find(":") > -1:
            port = int(tmp.split(":")[1])

        response = self.send_to_server(headers["host"], port, request)
        client.sendall(response)
        client.close()

    def send_to_server(self, host, port, data):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.connect((socket.gethostbyname(host), port))
        server.sendall(data)

        head = self.parse_head(server.recv(4096))
        headers = head["headers"]
        response = "{}\r\n".format(head["meta"])
        for key, value in headers.items():
            response += "{}: {}\r\n".format(key, value)
        response += "\r\n"

        if "content-length" in headers:
            while len(head["chunk"]) < int(headers["content-length"]):
                head["chunk"] += server.recv(self.buffer_size)

        response = response.encode() + head["chunk"]
        server.close()
        return response

    def parse_head(self, head_request):
        nodes = head_request.split(b"\r\n\r\n")
        heads = nodes[0].split(b"\r\n")
        meta = heads.pop(0).decode("utf-8")
        data = {
            "meta": meta,
            "headers": {},
            "chunk": b""
        }

        if len(nodes) >= 2:
            data["chunk"] = nodes[1]

        for head in heads:
            pieces = head.split(b": ")
            key = pieces.pop(0).decode("utf-8")
            if key.startswith("Connection: "):
                data["headers"][key.lower()] = "close"
            else:
                data["headers"][key.lower()] = b": ".join(pieces).decode("utf-8")
        return data

if __name__ == "__main__":
    proxy = Proxy(3001)
    proxy.run()

I never worked with SSL stuff in Python, so I used the ssl module to create an HTTPS socket.

#!/usr/bin/env python3
# coding=utf-8

import socket
import ssl
from threading import Thread

class Proxy:
    def __init__(self, port=3000):
        self.port = port
        self.s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        self.proxy = ssl.wrap_socket(self.s, ssl_version=ssl.PROTOCOL_TLSv1, ciphers="ADH-AES256-SHA")
        self.buffer_size = 4096

    def run(self):
        self.proxy.bind(("0.0.0.0", self.port))
        self.proxy.listen(100)
        print("  * Proxy server is running on port {}".format(self.port))

        while True:
            client, addr = self.proxy.accept()
            print(" => {}:{}".format(addr[0], addr[1]))
            Thread(target=self.handle_request, args=(client,)).start()

    def handle_request(self, client):
        head = self.parse_head(client.recv(self.buffer_size))
        headers = head["headers"]
        request = "{}\r\n".format(head["meta"])
        for key, value in headers.items():
            request += "{}: {}\r\n".format(key, value)
        request += "\r\n"
        if "content-length" in headers:
            while len(head["chunk"]) < int(headers["content-length"]):
                head["chunk"] += client.recv(self.buffer_size)

        request = request.encode() + head["chunk"]
        port = 80
        try:
            tmp = head["meta"].split(" ")[1].split("://")[1].split("/")[0]
        except IndexError:
            client.close()
            return
        if tmp.find(":") > -1:
            port = int(tmp.split(":")[1])

        response = self.send_to_server(headers["host"], port, request)
        client.sendall(response)
        client.close()

    def send_to_server(self, host, port, data):
        server = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        server.connect((socket.gethostbyname(host), port))
        server.sendall(data)

        head = self.parse_head(server.recv(4096))
        headers = head["headers"]
        response = "{}\r\n".format(head["meta"])
        for key, value in headers.items():
            response += "{}: {}\r\n".format(key, value)
        response += "\r\n"

        if "content-length" in headers:
            while len(head["chunk"]) < int(headers["content-length"]):
                head["chunk"] += server.recv(self.buffer_size)

        response = response.encode() + head["chunk"]
        server.close()
        return response

    def parse_head(self, head_request):
        nodes = head_request.split(b"\r\n\r\n")
        heads = nodes[0].split(b"\r\n")
        meta = heads.pop(0).decode("utf-8")
        data = {
            "meta": meta,
            "headers": {},
            "chunk": b""
        }

        if len(nodes) >= 2:
            data["chunk"] = nodes[1]

        for head in heads:
            pieces = head.split(b": ")
            key = pieces.pop(0).decode("utf-8")
            if key.startswith("Connection: "):
                data["headers"][key.lower()] = "close"
            else:
                data["headers"][key.lower()] = b": ".join(pieces).decode("utf-8")
        return data

if __name__ == "__main__":
    proxy = Proxy(3001)
    proxy.run()

But I get the following error.

  * Proxy server is running on port 3001
Traceback (most recent call last):
  File ".\proxy.py", line 98, in <module>
    proxy.run()
  File ".\proxy.py", line 22, in run
    client, addr = self.proxy.accept()
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1355, in accept
    newsock = self.context.wrap_socket(newsock,
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 500, in wrap_socket
    return self.sslsocket_class._create(
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1040, in _create
    self.do_handshake()
  File "C:\Users\anyms\AppData\Local\Programs\Python\Python38-32\lib\ssl.py", line 1309, in do_handshake
    self._sslobj.do_handshake()
ssl.SSLError: [SSL: HTTPS_PROXY_REQUEST] https proxy request (_ssl.c:1108)

Body:
The problem is actually not related to SSL at all but caused by a misunderstanding of how a HTTP proxy for HTTPS works. Such a proxy is not doing SSL at all. It is instead just used to create a tunnel to the final server and the client then creates the HTTPS connection trough this tunnel, keeping the end-to-end encryption this way.

The tunnel itself is created using the HTTP CONNECT method. And this is exactly what you are getting here on your SSL socket:

 ssl.SSLError: [SSL: HTTPS_PROXY_REQUEST] https proxy request (_ssl.c:1108)
                                          ^^^^^^^^^^^^^^^^^^^


问:
How do I install the Splunk Mint Gradle plugin?
According to the Splunk MINT documentation (https://docs.splunk.com/Documentation/MintAndroidSDK/5.2.x/DevGuide/Requirementsandinstallation) you must manually download the Gradle plugin artifact and include it in your project.

I successfully downloaded and deployed this artifact to a local instance of Artifactory, since it's already archived in a maven repo format.

To test the integration, I simply created a brand new project and added/applied the mint plugin. From here, Gradle sync fails with the following error:

```<code>Caused by: java.lang.NoSuchFieldError: javacTask
 at com.splunk.mint.gradle.android.plugin.utils.VariantUtilsKt.getJavaTask(VariantUtils.kt:13)
 at com.splunk.mint.gradle.android.plugin.api.AspectJTransform.setupVariant(AspectJTransform.kt:81)
 at com.splunk.mint.gradle.android.plugin.api.AspectJTransform$prepareProject$1.execute(AspectJTransform.kt:57)
 at com.splunk.mint.gradle.android.plugin.api.AspectJTransform$prepareProject$1.execute(AspectJTransform.kt:43)
 at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1$1.run(DefaultListenerBuildOperationDecorator.java:150)
 at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.reapply(DefaultUserCodeApplicationContext.java:58)
 at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1.run(DefaultListenerBuildOperationDecorator.java:147)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
 at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction.execute(DefaultListenerBuildOperationDecorator.java:144)
 at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
 at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
 at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
 at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
 at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
 at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
 ... 126 more
</code>```

Environment:

Android Studio 3.4

Gradle 5.2

Android Gradle Plugin 3.4.0

Splunk Mint Plugin 5.2.5

I suspect the Splunk team needs to update this plugin to support newer versions of Gradle. Unfortunately I'm unable to downgrade to a previous 4.x version since that is below the minumum supported version for Android Studio.

答:
Thankfully I got 5.2.5 working - was about to give up and use another crash reporting tool.

This is how I did it.

Step 1: Download the MINT plugin repository for Gradle (mint-android-repo-5.2.5.zip).

Step 2: Extract zip file into your Android project's "app" folder

Step 3: Modify your app Gradle build file (app/build.gradle) as follows:

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "org.example"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    ...
}

buildscript {
    repositories {
        maven {
            url uri('mint-plugin-repo-5.2.5')
        }
        mavenCentral()
    }
    dependencies {
        classpath 'com.splunk:mint-gradle-android-plugin:5.2.5'
    }
}

repositories {
    maven {
        url uri('mint-plugin-repo-5.2.5')
    }
}

dependencies {
    ...
    implementation 'com.splunk:mint-android-sdk:5.2.5'
}
</code>```

Thanks for the other answers which helped.

I watched the video suggested (important installation information starts at 3:21) ... I also read their Android documentation ... and finally the solution was to remove their plugin!

As I am new to Mint/Splunk (at least in this decade) I am unsure of the impacts of this, but I tested and an app crash came through and appeared in my dashboard.

Body:
According to the Splunk MINT documentation (https://docs.splunk.com/Documentation/MintAndroidSDK/5.2.x/DevGuide/Requirementsandinstallation) you must manually download the Gradle plugin artifact and include it in your project.

I successfully downloaded and deployed this artifact to a local instance of Artifactory, since it's already archived in a maven repo format.

To test the integration, I simply created a brand new project and added/applied the mint plugin. From here, Gradle sync fails with the following error:

Caused by: java.lang.NoSuchFieldError: javacTask
 at com.splunk.mint.gradle.android.plugin.utils.VariantUtilsKt.getJavaTask(VariantUtils.kt:13)
 at com.splunk.mint.gradle.android.plugin.api.AspectJTransform.setupVariant(AspectJTransform.kt:81)
 at com.splunk.mint.gradle.android.plugin.api.AspectJTransform$prepareProject$1.execute(AspectJTransform.kt:57)
 at com.splunk.mint.gradle.android.plugin.api.AspectJTransform$prepareProject$1.execute(AspectJTransform.kt:43)
 at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1$1.run(DefaultListenerBuildOperationDecorator.java:150)
 at org.gradle.configuration.internal.DefaultUserCodeApplicationContext.reapply(DefaultUserCodeApplicationContext.java:58)
 at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction$1.run(DefaultListenerBuildOperationDecorator.java:147)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:402)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor$RunnableBuildOperationWorker.execute(DefaultBuildOperationExecutor.java:394)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor$1.execute(DefaultBuildOperationExecutor.java:165)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:250)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor.execute(DefaultBuildOperationExecutor.java:158)
 at org.gradle.internal.operations.DefaultBuildOperationExecutor.run(DefaultBuildOperationExecutor.java:92)
 at org.gradle.configuration.internal.DefaultListenerBuildOperationDecorator$BuildOperationEmittingAction.execute(DefaultListenerBuildOperationDecorator.java:144)
 at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:91)
 at org.gradle.internal.event.BroadcastDispatch$ActionInvocationHandler.dispatch(BroadcastDispatch.java:80)
 at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:42)
 at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:230)
 at org.gradle.internal.event.BroadcastDispatch$SingletonDispatch.dispatch(BroadcastDispatch.java:149)
 at org.gradle.internal.event.AbstractBroadcastDispatch.dispatch(AbstractBroadcastDispatch.java:58)
 ... 126 more

Environment:

Android Studio 3.4

Gradle 5.2

Android Gradle Plugin 3.4.0

Splunk Mint Plugin 5.2.5

I suspect the Splunk team needs to update this plugin to support newer versions of Gradle. Unfortunately I'm unable to downgrade to a previous 4.x version since that is below the minumum supported version for Android Studio.

Body:
Thankfully I got 5.2.5 working - was about to give up and use another crash reporting tool.

This is how I did it.

Step 1: Download the MINT plugin repository for Gradle (mint-android-repo-5.2.5.zip).

Step 2: Extract zip file into your Android project's "app" folder

Step 3: Modify your app Gradle build file (app/build.gradle) as follows:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "org.example"
        minSdkVersion 24
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    ...
}

buildscript {
    repositories {
        maven {
            url uri('mint-plugin-repo-5.2.5')
        }
        mavenCentral()
    }
    dependencies {
        classpath 'com.splunk:mint-gradle-android-plugin:5.2.5'
    }
}

repositories {
    maven {
        url uri('mint-plugin-repo-5.2.5')
    }
}

dependencies {
    ...
    implementation 'com.splunk:mint-android-sdk:5.2.5'
}

Thanks for the other answers which helped.

I watched the video suggested (important installation information starts at 3:21) ... I also read their Android documentation ... and finally the solution was to remove their plugin!

As I am new to Mint/Splunk (at least in this decade) I am unsure of the impacts of this, but I tested and an app crash came through and appeared in my dashboard.


问:
Convert String into a BigDecimal in Android
The data returned from my application API contains the product price stored as a String for example:

```<code>{
   price:"1500"
}
</code>```

This causes a NumberFormatException because the data type used in the Product model is a BigDecimal. How do I parse this string from the database into a BigDecimal before using it within the application?

I am using Retrofit and GSON, and have tried the solutions here:

NumberFormatException in GSON when converting String to double

Solution 1:

```<code>GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(Float.class, new TypeAdapter<Float>() {

        @Override
        public Float read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String stringValue = reader.nextString();
            try {
                Float value = Float.valueOf(stringValue);
                return value;
            } catch (NumberFormatException e) {
                return null;
            }
        }

        @Override
        public void write(JsonWriter writer, Float value) throws IOException {
            if (value == null) {
                writer.nullValue();
                return;
            }
            writer.value(value);
        }

    });
</code>```

This solution seems correct but I failed to return the parsed value when the exception occurs, instead of returning null.

Solution 2:

```<code>.registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
            public JsonElement serialize(Double number, Type type, JsonSerializationContext context) {
                return new JsonPrimitive(Double.valueOf(number));
            }
        })
</code>```

For this solution, BigDecimal isn't a supported JsonPrimitive datatype.

答:
Try this</p>

```<code>GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(String.class, new TypeAdapter<String>() {

    @Override
    public String read(JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
        }
        String stringValue = reader.nextString();
        try {
            BigDecimal value = new BigDecimal(stringValue);
            globalVariable = value;  //globalVariable must be of type BigDecimal OR provide some callback mechanism here
            return stringValue;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public void write(JsonWriter writer, Float value) throws IOException {
        if (value == null) {
            writer.nullValue();
            return;
        }
        writer.value(value);
    }

});
</code>```

Body:
The data returned from my application API contains the product price stored as a String for example:

{
   price:"1500"
}

This causes a NumberFormatException because the data type used in the Product model is a BigDecimal. How do I parse this string from the database into a BigDecimal before using it within the application?

I am using Retrofit and GSON, and have tried the solutions here:

NumberFormatException in GSON when converting String to double

Solution 1:

GsonBuilder gb = new GsonBuilder();
    gb.registerTypeAdapter(Float.class, new TypeAdapter<Float>() {

        @Override
        public Float read(JsonReader reader) throws IOException {
            if (reader.peek() == JsonToken.NULL) {
                reader.nextNull();
                return null;
            }
            String stringValue = reader.nextString();
            try {
                Float value = Float.valueOf(stringValue);
                return value;
            } catch (NumberFormatException e) {
                return null;
            }
        }

        @Override
        public void write(JsonWriter writer, Float value) throws IOException {
            if (value == null) {
                writer.nullValue();
                return;
            }
            writer.value(value);
        }

    });

This solution seems correct but I failed to return the parsed value when the exception occurs, instead of returning null.

Solution 2:

.registerTypeAdapter(Double.class, new JsonSerializer<Double>() {
            public JsonElement serialize(Double number, Type type, JsonSerializationContext context) {
                return new JsonPrimitive(Double.valueOf(number));
            }
        })

For this solution, BigDecimal isn't a supported JsonPrimitive datatype.

Body:
Try this

GsonBuilder gb = new GsonBuilder();
gb.registerTypeAdapter(String.class, new TypeAdapter<String>() {

    @Override
    public String read(JsonReader reader) throws IOException {
        if (reader.peek() == JsonToken.NULL) {
            reader.nextNull();
            return null;
        }
        String stringValue = reader.nextString();
        try {
            BigDecimal value = new BigDecimal(stringValue);
            globalVariable = value;  //globalVariable must be of type BigDecimal OR provide some callback mechanism here
            return stringValue;
        } catch (NumberFormatException e) {
            return null;
        }
    }

    @Override
    public void write(JsonWriter writer, Float value) throws IOException {
        if (value == null) {
            writer.nullValue();
            return;
        }
        writer.value(value);
    }

});


问:
the server responded with a status of 403 (Forbidden) angular
When I try to call with this.http.get and @GetMapping I am able to send the call to spring controller,

When I try to change from this.http.get to this.http.post and from  @GetMapping to  @PostMapping I am not able to call the spring controller /api/v1/basicauth method.

As I am having username and password I want to use PostMapping only

My code as below:-

Angular

```<code>var formData: any = new FormData();
formData.append("userName", username);
formData.append("password", password);

let params = new HttpParams();
params = params.append('username', username);
params = params.append('password', password);
return this.http.post<any>('/api/v1/basicauth', { formData }).pipe(map((res) => {
    this.username = username;
    this.password = password;
}));
</code>```

Spring boot:-

```<code>@PostMapping(path = "/basicauth")
public AuthenticationBean helloWorldBean(@RequestBody UserDetails user) {
log.info("Start helloWorldBean method");
</code>```

UserDetails.java

```<code>    public class UserDetails {

        private int userId;
        private String userName;
        private String password;
   }
</code>```

答:
Client side

```<code>login(username: string, password: string) {
        return this.http.post<any>('/api/v1/basicauth', { username, password })
            .pipe(map(user => {
                // eg.
                // localStorage.setItem('currentUser', JSON.stringify(user));
                return user;
            }));
</code>```

Example from: https://jasonwatmore.com/post/2019/06/22/angular-8-jwt-authentication-example-tutorial

Server side

You are retrieving paramaters with @RequestParam, which means you're expeting parametes as http://host:8080/api/auth?password=abc&....

Please check https://www.baeldung.com/spring-request-response-body

Body:
When I try to call with this.http.get and @GetMapping I am able to send the call to spring controller,

When I try to change from this.http.get to this.http.post and from  @GetMapping to  @PostMapping I am not able to call the spring controller /api/v1/basicauth method.

As I am having username and password I want to use PostMapping only

My code as below:-

Angular

var formData: any = new FormData();
formData.append("userName", username);
formData.append("password", password);

let params = new HttpParams();
params = params.append('username', username);
params = params.append('password', password);
return this.http.post<any>('/api/v1/basicauth', { formData }).pipe(map((res) => {
    this.username = username;
    this.password = password;
}));

Spring boot:-

@PostMapping(path = "/basicauth")
public AuthenticationBean helloWorldBean(@RequestBody UserDetails user) {
log.info("Start helloWorldBean method");

UserDetails.java

    public class UserDetails {

        private int userId;
        private String userName;
        private String password;
   }

Body:
Client side

login(username: string, password: string) {
        return this.http.post<any>('/api/v1/basicauth', { username, password })
            .pipe(map(user => {
                // eg.
                // localStorage.setItem('currentUser', JSON.stringify(user));
                return user;
            }));

Example from: https://jasonwatmore.com/post/2019/06/22/angular-8-jwt-authentication-example-tutorial

Server side

You are retrieving paramaters with @RequestParam, which means you're expeting parametes as http://host:8080/api/auth?password=abc&....

Please check https://www.baeldung.com/spring-request-response-body


问:
Cross component communication with angular 2+ (any child to any parent)
I have been working on web application in Angular 2+. and i have following situation

```<code>component A
  |
  component B
    |
    component C
      |
      component D   //click on button -> call apis and return value to component A's variable
</code>```

In component D there is button if user click on that we need to call rest API and that API's result should be show in component A.

Business case : Consider that component A is your top header which contain point count and form component D user do some task and based on that task i need to increment that points.

I can achieve this functionality with broadcast service in angular Subject<BroadcastEvent> (after api return value create broadcast and in component A i am listing that event ) but i am not sure that if there is a better way to do this stuff.
Or i can't use same service in both component because I need to assign value in variable as well as in show in DOM. If i need only DOM element to be updated than service can resolve my problem but i also need in components variable.

答:
In my experience it makes sense to make a service keep the number of points. That service is then injected into component D to call service.addPoints().
That service is also injected into component A to call service.getPoints().

componentA.component.ts:

```<code>export class componentA  {

constructor(public myService: MyService){}

}
</code>```

componentA.component.html:

```<code>{{myService.getPoints()}}
</code>```

componentD.component.ts:

```<code>export class componentD  {

constructor(public myService: MyService){}

}
</code>```

componentD.component.html:

```<code><button (click)="{{myService.addPoints()"></button>
</code>```

myService.ts:

```<code>@Injectable()
export class MyService {
public points: number;

public getPoints(){
  return this.points;
}

public addPoints(){
  this.points = this.points +1;
}
}
</code>```

Body:
I have been working on web application in Angular 2+. and i have following situation

component A
  |
  component B
    |
    component C
      |
      component D   //click on button -> call apis and return value to component A's variable

In component D there is button if user click on that we need to call rest API and that API's result should be show in component A.

Business case : Consider that component A is your top header which contain point count and form component D user do some task and based on that task i need to increment that points.

I can achieve this functionality with broadcast service in angular Subject<BroadcastEvent> (after api return value create broadcast and in component A i am listing that event ) but i am not sure that if there is a better way to do this stuff.
Or i can't use same service in both component because I need to assign value in variable as well as in show in DOM. If i need only DOM element to be updated than service can resolve my problem but i also need in components variable.

Body:
In my experience it makes sense to make a service keep the number of points. That service is then injected into component D to call service.addPoints().
That service is also injected into component A to call service.getPoints().

componentA.component.ts:

export class componentA  {

constructor(public myService: MyService){}

}

componentA.component.html:

{{myService.getPoints()}}

componentD.component.ts:

export class componentD  {

constructor(public myService: MyService){}

}

componentD.component.html:

<button (click)="{{myService.addPoints()"></button>

myService.ts:

@Injectable()
export class MyService {
public points: number;

public getPoints(){
  return this.points;
}

public addPoints(){
  this.points = this.points +1;
}
}


问:
What does WorkManager do with jobs after hitting JobScheduler limit of 100?
I have scoured the internet for info on this subject but nobody seems to be experiencing this issue anymore.

Remember this fun error?

java.lang.IllegalStateException: JobScheduler 100 job limit exceeded.  We count 101 WorkManager jobs in JobScheduler; we have 50 tracked jobs in our DB; our Configuration limit is 50.

with

Caused by: java.lang.IllegalStateException: Apps may not schedule more than 100 distinct jobs

Well, despite switching a lot of jobs to do enqueueUniqueWork, it appears some of my users are still hitting that limit. My use case is for people with poor and no connectivity doing a lot of stuff offline and thereby creating lots of jobs to update resources on the remote server. I never had this problem with FirebaseJobDispatcher (at least I wasn't aware of it) and some people may be without signal for days, and what happens if somebody can't connect for weeks? It will easily build up hundreds of jobs. Hence, this error.

My question is what happens to these jobs when the limit is reached? Are they simply discarded by the scheduler? Am I losing people's data right now as I type this?

Update

Android Versions: Confirmed on 7.0, 8.0, 8.1, probably a lot more

WorkManager Version: 2.3.0

答:
We fixed a bug recently, where there is a mismatch between WorkManagers tracking of jobs in JobScheduler and the actual state of the jobs. This happens in very rare cases, and I think that's what is going on in your case.

https://issuetracker.google.com/issues/149092520 was a recently reported bug. I fixed it before the bug was reported on the public tracker, because one of Google's apps ran into the same edge case.

This change (https://android-review.googlesource.com/c/platform/frameworks/support/+/1226859) has the fix. We should release this as part of WorkManager 2.3.2 very soon.

If you cannot wait, you can use a snapshot build that should be identical to the eventual release.

Here is the gradle snippet you will need:

```<code>repositories {
    google()
    maven { url 'https://ci.android.com/builds/submitted/6195753/androidx_snapshot/latest/repository/' }
}

dependencies {
  implementation "androidx.work:work-runtime:2.4.0-SNAPSHOT"
}
</code>```

One other thing you might need to do is to get rid of stale jobs. It is as simple as calling JobScheduler.cancelAllJobs() before WorkManager is initialized. You can do it inside Application.onCreate() in your Application subclass.

If you need more help, please feel free to reach out on the bug tracker and I can help you out.

Body:
We fixed a bug recently, where there is a mismatch between WorkManagers tracking of jobs in JobScheduler and the actual state of the jobs. This happens in very rare cases, and I think that's what is going on in your case.

https://issuetracker.google.com/issues/149092520 was a recently reported bug. I fixed it before the bug was reported on the public tracker, because one of Google's apps ran into the same edge case.

This change (https://android-review.googlesource.com/c/platform/frameworks/support/+/1226859) has the fix. We should release this as part of WorkManager 2.3.2 very soon.

If you cannot wait, you can use a snapshot build that should be identical to the eventual release.

Here is the gradle snippet you will need:

repositories {
    google()
    maven { url 'https://ci.android.com/builds/submitted/6195753/androidx_snapshot/latest/repository/' }
}

dependencies {
  implementation "androidx.work:work-runtime:2.4.0-SNAPSHOT"
}

One other thing you might need to do is to get rid of stale jobs. It is as simple as calling JobScheduler.cancelAllJobs() before WorkManager is initialized. You can do it inside Application.onCreate() in your Application subclass.

If you need more help, please feel free to reach out on the bug tracker and I can help you out.


问:
How to mute and unmute sound in Angular2?
I have a sound in my Angular project, like this:

```<code>introInfo() {
   this.audio.src = '../assets/sound1.wav';
   this.audio.load();
   this.audio.play();
 }

 feedbackInfo() {
   this.audio.src = '../assets/sound1.wav';
   this.audio.load();
   // auto-start
   this.audio.play();
 }
</code>```

And I would like to be able to mute all sounds. If I click the button in my template:

```<code><img class="grow" id="mute" [src]='mute' (click)="muteF()"/>
</code>```

How could I write my function muteF? I would like to mute if I click the button. If I click a second time, it must perform unmute.

答:
You can use muted property such as

```<code>this.audio.muted = true;
</code>```

Works for video element as well.

Source: https://www.w3schools.com/tags/av_prop_muted.asp

Body:
I have a sound in my Angular project, like this:

introInfo() {
   this.audio.src = '../assets/sound1.wav';
   this.audio.load();
   this.audio.play();
 }

 feedbackInfo() {
   this.audio.src = '../assets/sound1.wav';
   this.audio.load();
   // auto-start
   this.audio.play();
 }

And I would like to be able to mute all sounds. If I click the button in my template:

How could I write my function muteF? I would like to mute if I click the button. If I click a second time, it must perform unmute.

Body:
You can use muted property such as

this.audio.muted = true;

Works for video element as well.

Source: https://www.w3schools.com/tags/av_prop_muted.asp


问:
how to set the path of local module in python to be recognized in CircleCI?
I am building a python module. In order to define its path, a .pth file has been defined as follows:

# creation of the virtual environment
python -v venv env

# activation of the newly creation virtual environment
source env/bin/activate
```

<p>To set the path of my module (<em>my module is located in</em> <code>packages/regression_model/regression_model</code>) I created this <code>.pth</code> file  <code>env/lib/python3.7/site-packages/regression_model.pth</code> which contains:</p>

```# env/lib/python3.7/site-packages/regression_model.pth
../../../../packages/regression_model
```

<p>Now, any where in my project, I can import my module <code>regression_model</code> through this command:</p>

<pre class="lang-py prettyprint-override"><code>import regression_model
</code>```

Actually my objective is to use CircleCI for the deployment of my project.

CircleCI is configured as follows:

```<code>version: 2
jobs:
  test_regression_model:
    working_directory: ~/project
    docker:
      - image: circleci/python:3.7.6
        environment: # environment variables for primary container
          PYTHONPATH: ~/project/packages/regression_model:~/project/packages/ml_api
    steps:
      - checkout
      - run:
          name: Runnning tests
          command: |
            virtualenv venv
            . venv/bin/activate
            pip install --upgrade pip
            pip install -r packages/regression_model/requirements.txt
            chmod +x ./scripts/fetch_kaggle_dataset.sh
            ./scripts/fetch_kaggle_dataset.sh
            python packages/regression_model/regression_model/train_pipeline.py
            py.test -vv packages/regression_model/tests

workflows:
  version: 2
  test-all:
    jobs:
      - test_regression_model
</code>```

The problem I am facing is that CircleCI is indicating that my module can not be imported

```<code>Traceback (most recent call last):
  File "packages/regression_model/regression_model/train_pipeline.py", line 4, in <module>
    from regression_model import pipeline
ModuleNotFoundError: No module named 'regression_model'
</code>```

To solve the problem, the path to that module regression_model has to be defined exactly as it was done locally. The question is then: how to define path in the CircleCI?

I tried to do it through the use of the environment variable PYTHONPATH but without success.

Any suggestions?

答:
I found out the solution. Similarly to what it has been done manually on my local machine, I just define 2 command lines to get it done in CircleCI:

echo "../../../../packages/regression_model" >> env/lib/python3.7/site-packages/extra.pth
echo "../../../../packages/ml_api" >> env/lib/python3.7/site-packages/extra.pth
```

<p>And below the full yml file just in case it could help others.</p>

```version: 2
jobs:
  test_regression_model:
    working_directory: ~/project
    docker:
      - image: circleci/python:3.7.6
    steps:
      - checkout
      - run:
          name: Runnning tests
          command: |
            virtualenv env
            . env/bin/activate
            pip install --upgrade pip
            pip install -r packages/regression_model/requirements.txt
            echo "../../../../packages/regression_model" >> env/lib/python3.7/site-packages/extra.pth
            echo "../../../../packages/ml_api" >> env/lib/python3.7/site-packages/extra.pth
            chmod +x ./scripts/fetch_kaggle_dataset.sh
            ./scripts/fetch_kaggle_dataset.sh
            sudo apt-get install unzip
            unzip  packages/regression_model/regression_model/datasets/house-prices-advanced-regression-techniques.zip -d packages/regression_model/regression_model/datasets/
            python packages/regression_model/regression_model/train_pipeline.py
            py.test -vv packages/regression_model/tests

workflows:
  version: 2
  test-all:
    jobs:
      - test_regression_model
```

Body:
I am building a python module. In order to define its path, a .pth file has been defined as follows:

# creation of the virtual environment
python -v venv env

# activation of the newly creation virtual environment
source env/bin/activate

To set the path of my module (my module is located in packages/regression_model/regression_model) I created this .pth file  env/lib/python3.7/site-packages/regression_model.pth which contains:

# env/lib/python3.7/site-packages/regression_model.pth
../../../../packages/regression_model

Now, any where in my project, I can import my module regression_model through this command:

import regression_model

Actually my objective is to use CircleCI for the deployment of my project.

CircleCI is configured as follows:

version: 2
jobs:
  test_regression_model:
    working_directory: ~/project
    docker:
      - image: circleci/python:3.7.6
        environment: # environment variables for primary container
          PYTHONPATH: ~/project/packages/regression_model:~/project/packages/ml_api
    steps:
      - checkout
      - run:
          name: Runnning tests
          command: |
            virtualenv venv
            . venv/bin/activate
            pip install --upgrade pip
            pip install -r packages/regression_model/requirements.txt
            chmod +x ./scripts/fetch_kaggle_dataset.sh
            ./scripts/fetch_kaggle_dataset.sh
            python packages/regression_model/regression_model/train_pipeline.py
            py.test -vv packages/regression_model/tests

workflows:
  version: 2
  test-all:
    jobs:
      - test_regression_model

The problem I am facing is that CircleCI is indicating that my module can not be imported

Traceback (most recent call last):
  File "packages/regression_model/regression_model/train_pipeline.py", line 4, in <module>
    from regression_model import pipeline
ModuleNotFoundError: No module named 'regression_model'

To solve the problem, the path to that module regression_model has to be defined exactly as it was done locally. The question is then: how to define path in the CircleCI?

I tried to do it through the use of the environment variable PYTHONPATH but without success.

Any suggestions?

Body:
I found out the solution. Similarly to what it has been done manually on my local machine, I just define 2 command lines to get it done in CircleCI:

echo "../../../../packages/regression_model" >> env/lib/python3.7/site-packages/extra.pth
echo "../../../../packages/ml_api" >> env/lib/python3.7/site-packages/extra.pth

And below the full yml file just in case it could help others.

version: 2
jobs:
  test_regression_model:
    working_directory: ~/project
    docker:
      - image: circleci/python:3.7.6
    steps:
      - checkout
      - run:
          name: Runnning tests
          command: |
            virtualenv env
            . env/bin/activate
            pip install --upgrade pip
            pip install -r packages/regression_model/requirements.txt
            echo "../../../../packages/regression_model" >> env/lib/python3.7/site-packages/extra.pth
            echo "../../../../packages/ml_api" >> env/lib/python3.7/site-packages/extra.pth
            chmod +x ./scripts/fetch_kaggle_dataset.sh
            ./scripts/fetch_kaggle_dataset.sh
            sudo apt-get install unzip
            unzip  packages/regression_model/regression_model/datasets/house-prices-advanced-regression-techniques.zip -d packages/regression_model/regression_model/datasets/
            python packages/regression_model/regression_model/train_pipeline.py
            py.test -vv packages/regression_model/tests

workflows:
  version: 2
  test-all:
    jobs:
      - test_regression_model


问:
how to add id and class to select box in Cakephp
i am new to cakephp so i dont know how to i do this ... i have a view page in which there is a select box in which time zone is displaying

```<code>  <?php

    echo $this->Timezone->select('timezone');

     ?>
</code>```

i want to add the 'id' , 'class' and label to it .. and if label isnt possible then its okk ..but the id and class is very important

what i want actually my select box is this

```<code><label for="validation-select" class="label">Select</label>
<select id="validation-select" name="validation-select" class="select validate[required]">
</code>```

or if i want to add the timezone in this i dont know how can i do this

helper class

http://bakery.cakephp.org/articles/MarkAlanEvans/2009/12/17/updated-timezone-helper

答:
```<code>$month = array('1' => 'January', '2' => 'February', '3' => 'March', '4' => 'April', '5' => 'May', '6' => 'June', '7' => 'July', '8' => 'August', '9' => 'September', '10' => 'October', '11' => 'November', '12' => 'December');

 echo $this->Form->select('month', $month, array('class' => 'form-control month', 'placeholder' => 'Month', 'id' => 'month', 'empty' => 'Select Month'));
</code>```

Body:
i am new to cakephp so i dont know how to i do this ... i have a view page in which there is a select box in which time zone is displaying

  <?php

    echo $this->Timezone->select('timezone');

     ?>

i want to add the 'id' , 'class' and label to it .. and if label isnt possible then its okk ..but the id and class is very important

what i want actually my select box is this

Select
<select id="validation-select" name="validation-select" class="select validate[required]">

or if i want to add the timezone in this i dont know how can i do this

helper class

http://bakery.cakephp.org/articles/MarkAlanEvans/2009/12/17/updated-timezone-helper


问:
Android automatically Capture selfie on face detection and display in image view
I am developing an android app I want to capture the user's face when activity open and then display that image in the image view. Thanks </p>

答: You can use Mobil Vision API to trigger activity for taking pictures when the face detected. And if you want to send it to another activity it would be a real problem because of intents don't send high memory data. You can check it from here</p>


问:
Is it possible to marshal/unmarshal Prometheus state in go-client?
I'd like to be able to save the save the state of various Prometheus metrics (CounterVec, HistogramVec, ...) to a file from my app, and resume it later when necessary. Would that be possible?

I see that there is the Write method in metric.go, but can't find the Read one.

答: No Prometheus client library supports this, nor should you need this. Client libraries are designed to work entirely in memory, and functions like rate() will gracefully handle the counter resets due to a process restarting.


问:
NGINX lua use secure_link_md5 from env var
I'm using NGINX with lua support to accesses hostnames and other App releated variables from my .env file.
Now i wanted to use the secure_link_md5 var. from a .env file but i dont understand how to put together the string so that nginx can understand it.

This is how my nginx config looks like:

```<code>env LINK_SECRET;

set_by_lua $curr_dl_link_secret 'return os.getenv("LINK_SECRET")'; # Needs to be set correctly
secure_link_md5 = "${curr_dl_link_secret}$uri$secure_link_expires";
</code>```

Normaly i would set the config line like that without the use of lua and env vars:

```<code>secure_link_md5 "XGc7YyXERjiSvs4PtzpnBMANuFd22VAmXDc66g6JU$uri$secure_link_expires";
</code>```

Currently NGINX always returns the following error:

invalid number of arguments in "secure_link_md5"

答:
NGINX counts "=" as an argument. I am not familiar with NGINX with lua, but I think "{}" are also unnecessary.

I guess you want something like this:

```<code>secure_link_md5 "$curr_dl_link_secret$uri$secure_link_expires";
</code>```

Body:
I'm using NGINX with lua support to accesses hostnames and other App releated variables from my .env file.
Now i wanted to use the secure_link_md5 var. from a .env file but i dont understand how to put together the string so that nginx can understand it.

This is how my nginx config looks like:

env LINK_SECRET;

set_by_lua $curr_dl_link_secret 'return os.getenv("LINK_SECRET")'; # Needs to be set correctly
secure_link_md5 = "${curr_dl_link_secret}$uri$secure_link_expires";

Normaly i would set the config line like that without the use of lua and env vars:

secure_link_md5 "XGc7YyXERjiSvs4PtzpnBMANuFd22VAmXDc66g6JU$uri$secure_link_expires";

Currently NGINX always returns the following error:

invalid number of arguments in "secure_link_md5"

Body:
NGINX counts "=" as an argument. I am not familiar with NGINX with lua, but I think "{}" are also unnecessary.

I guess you want something like this:

secure_link_md5 "$curr_dl_link_secret$uri$secure_link_expires";


问:
Passing an Array Parameter In FXML
I'm trying to create a custom control that stores a list of images. Ideally in the FXML file I could instantiate my control by passing an argument that is a list of file paths to said images.

I have gotten the control to load from FXML just fine here is the constructor

```<code>public Gallery(@NamedArg("images") List<String> images) {
    this.imageQueue = new PriorityQueue<>(images);
    this.load("gallery.fxml");
    this.scrollImage();
}
</code>```

Here is the FXML that loads it

```<code><Gallery fx:id="contentPane" prefHeight="250.0" prefWidth="600.0">
      <images>
          1.png,
          2.png,
          3.png
      </images>
  </Gallery>
</code>```

Loads without issue, but there are no images and doing some simple prints I see that instead of creating a list with three values of 1.png,2.png,3.png it creates a list with 1 value of "1.png, 2.png, 3.png"

So my question is how do I get this to instantiate as a list with 3 separate values in it?

答:
A similar approach would work with readonly list properties, but there are pieces of information that are not provided with this kind of fxml:

Which implementation of List should be used?

How many strings are there and where to seperate them; how to tell whether you want a list containing "1.png,\n          2.png,\n          3.png", "1.png,", "\n          2.png,\n          3.png" or something else?

It is possible to do something like this, but you need to modify the structure of your fxml:

<?import java.util.ArrayList?>
<?import java.lang.String?>

...

<Gallery fx:id="contentPane" prefHeight="250.0" prefWidth="600.0">
    <images>
        <ArrayList>
          <String fx:value="1.png" />
          <String fx:value="2.png" />
          <String fx:value="3.png" />
        </ArrayList>
    </images>
</Gallery>
```

Title: Passing an Array Parameter In FXML

Body:
I'm trying to create a custom control that stores a list of images. Ideally in the FXML file I could instantiate my control by passing an argument that is a list of file paths to said images.

I have gotten the control to load from FXML just fine here is the constructor

public Gallery(@NamedArg("images") List<String> images) {
    this.imageQueue = new PriorityQueue<>(images);
    this.load("gallery.fxml");
    this.scrollImage();
}

Here is the FXML that loads it

<Gallery fx:id="contentPane" prefHeight="250.0" prefWidth="600.0">
      <images>
          1.png,
          2.png,
          3.png
      </images>
  </Gallery>

Loads without issue, but there are no images and doing some simple prints I see that instead of creating a list with three values of 1.png,2.png,3.png it creates a list with 1 value of "1.png, 2.png, 3.png"

So my question is how do I get this to instantiate as a list with 3 separate values in it?


问:
I have used "cors" but I found "Access to XMLHttpRequest has been blocked". Why?
I have an express API running and when I make a request I get this message.

Error:
Access to XMLHttpRequest at 'http://localhost:9000/api/courses' from origin
'http://localhost:4222' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.
```

<p>I am using <code>cors</code> in my API here is my code: </p>

<pre class="lang-js prettyprint-override"><code>import * as express from 'express';
import {Application} from "express";
import {getAllCourses, getCourseById} from "./get-courses.route";
import {searchLessons} from "./search-lessons.route";
import {loginUser} from "./auth.route";
import {saveCourse} from "./save-course.route";

const bodyParser = require('body-parser');
const app: Application = express();

app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());

app.route('/api/login').post(loginUser);
app.route('/api/courses').get(getAllCourses);
app.route('/api/courses/:id').put(saveCourse);
app.route('/api/courses/:id').get(getCourseById);
app.route('/api/lessons').get(searchLessons);

const httpServer = app.listen(9000, () => {
    console.log("HTTP REST API Server running at http://localhost:" + httpServer.address().port);
});
</code>```

Kindly assist me. I appreciate all responses. Thanks Ahead.

答:
Give an origin to it</p>

```<code>app.use(cors({
  origin: 'http://yourapp.com'
}));
</code>```

Body:
I have an express API running and when I make a request I get this message.

Error:
Access to XMLHttpRequest at 'http://localhost:9000/api/courses' from origin
'http://localhost:4222' has been blocked by CORS policy:
No 'Access-Control-Allow-Origin' header is present on the requested resource.

I am using cors in my API here is my code:

import * as express from 'express';
import {Application} from "express";
import {getAllCourses, getCourseById} from "./get-courses.route";
import {searchLessons} from "./search-lessons.route";
import {loginUser} from "./auth.route";
import {saveCourse} from "./save-course.route";

const bodyParser = require('body-parser');
const app: Application = express();

app.use(bodyParser.json());
var cors = require('cors');
app.use(cors());

app.route('/api/login').post(loginUser);
app.route('/api/courses').get(getAllCourses);
app.route('/api/courses/:id').put(saveCourse);
app.route('/api/courses/:id').get(getCourseById);
app.route('/api/lessons').get(searchLessons);

const httpServer = app.listen(9000, () => {
    console.log("HTTP REST API Server running at http://localhost:" + httpServer.address().port);
});

Kindly assist me. I appreciate all responses. Thanks Ahead.

Body:
Give an origin to it

app.use(cors({
  origin: 'http://yourapp.com'
}));


问:
Append Values of Button on Click on Input Type
How can I append the value of the button on click to delete_id_receiver   text field. The output should be 1,2,3 if the 3 buttons are click.

And change the value of delete button to "UNDO" and remove the values on the text input.

```<code><table class="table">
<tr>
    <td><button onclick="deleteVal(1)" type="button"> Delete </button></td>
    <td> John </td>
</tr>
<tr>
    <td><button onclick="deleteVal(2)" type="button"> Delete </button></td>
    <td> May </td>
</tr>
<tr>
    <td><button onclick="deleteVal(3)" type="button"> Delete </button></td>
    <td> Andrew </td>
</tr>
</code>```

```<code><input type="text" id="delete_id_receiver">
</code>```

This is what i've tried but it does not stock the id's on click

```<code> function deleteVal(val){
      var delete_id = val;
     document.getElementById('delete_id_receiver').value = val;
 }
</code>```

答:
Below solution is able to append, UNDO with no duplicates and no unnecessary commas.

function deleteVal(val){
   var buttonText = document.getElementById(val).innerText.trim();

   if(buttonText == 'Delete')
   {
      var valueToAppend = val;
      var valueInsideTextbox = document.getElementById('delete_id_receiver').value;

      if(valueInsideTextbox.includes(valueToAppend))
     return;

      if(valueInsideTextbox.trim() != "")
     valueToAppend = "," + valueToAppend;

      document.getElementById('delete_id_receiver').value = valueInsideTextbox + valueToAppend;
      document.getElementById(val).innerText = 'UNDO';
   }
   else if(buttonText == 'UNDO')
   {
     var valueToRemove = val;
     var valueInsideTextbox = document.getElementById('delete_id_receiver').value;

     if(valueInsideTextbox.trim() != "" && valueInsideTextbox.includes(valueToRemove))
     {
     valueInsideTextbox = valueInsideTextbox.replace("," + val, "").replace(val + ",", "").replace(val, "");
     }
     document.getElementById('delete_id_receiver').value = valueInsideTextbox;
     document.getElementById(val).innerText = 'Delete';
   }
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table class="table">
<tr>
    <td><button id="1" onclick="deleteVal(1)" type="button"> Delete
</button></td>
    <td> John </td>
</tr>
<tr>
    <td><button id="2" onclick="deleteVal(2)" type="button"> Delete </button></td>
    <td> May </td>
</tr>
<tr>
    <td><button id="3" onclick="deleteVal(3)" type="button"> Delete
    </button></td>
    <td> Andrew </td>
</tr>
<input type="text" id="delete_id_receiver"></code>```

Body:
How can I append the value of the button on click to delete_id_receiver   text field. The output should be 1,2,3 if the 3 buttons are click.

And change the value of delete button to "UNDO" and remove the values on the text input.

    <button onclick="deleteVal(1)" type="button"> Delete </button>
     John

    <button onclick="deleteVal(2)" type="button"> Delete </button>
     May

    <button onclick="deleteVal(3)" type="button"> Delete </button>
     Andrew

<input type="text" id="delete_id_receiver">

This is what i've tried but it does not stock the id's on click

 function deleteVal(val){
      var delete_id = val;
     document.getElementById('delete_id_receiver').value = val;
 }

Body:
Below solution is able to append, UNDO with no duplicates and no unnecessary commas.

function deleteVal(val){
   var buttonText = document.getElementById(val).innerText.trim();

   if(buttonText == 'Delete')
   {
      var valueToAppend = val;
      var valueInsideTextbox = document.getElementById('delete_id_receiver').value;

      if(valueInsideTextbox.includes(valueToAppend))
     return;

      if(valueInsideTextbox.trim() != "")
     valueToAppend = "," + valueToAppend;

      document.getElementById('delete_id_receiver').value = valueInsideTextbox + valueToAppend;
      document.getElementById(val).innerText = 'UNDO';
   }
   else if(buttonText == 'UNDO')
   {
     var valueToRemove = val;
     var valueInsideTextbox = document.getElementById('delete_id_receiver').value;

     if(valueInsideTextbox.trim() != "" && valueInsideTextbox.includes(valueToRemove))
     {
     valueInsideTextbox = valueInsideTextbox.replace("," + val, "").replace(val + ",", "").replace(val, "");
     }
     document.getElementById('delete_id_receiver').value = valueInsideTextbox;
     document.getElementById(val).innerText = 'Delete';
   }
}

<table class="table">
<tr>
    <td><button id="1" onclick="deleteVal(1)" type="button"> Delete
</button></td>
    <td> John </td>
</tr>
<tr>
    <td><button id="2" onclick="deleteVal(2)" type="button"> Delete </button></td>
    <td> May </td>
</tr>
<tr>
    <td><button id="3" onclick="deleteVal(3)" type="button"> Delete
    </button></td>
    <td> Andrew </td>
</tr>
<input type="text" id="delete_id_receiver">


问:
How do you center an error message created with BootstrapValidate?
First time using bootstrap and first time asking a question on stackoverflow! I am creating this mockup with forms for email, subject and message. I am also using bootstrap validator to get error messages to pop-up (like ""). but they appear all the way to the left of the window. Anyone know of a way to get the below the input box? Or even above the input box? Like if where says "Email" I would like the error message that says "Please enter a valid email" to pop up right next to it. I've included the html and css. Hopefully I did it right. Thanks!</p>

```<code><!DOCTYPE html>
<html>

<head>
    <link rel="stylesheet" type="text/css" href="form-issue.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://cdn.rawgit.com/PascaleBeier/bootstrap-validate/v2.2.0/dist/bootstrap-validate.js"></script>
</head>

<body>
    <div class="contact">
        <h2>CONTACT</h2>
        <form action="" method="POST">
            <div class="form-group">
                <label class="label" for="email">Email</label>
                <input id="email" class="form-control" type="text" name="email">
            </div>
            <div class="form-group">
                <label class="label" for="subject"> Subject </label>
                <input id="subject" class="form-control" type="text" name="subject">
            </div>
            <div class="form-group">
                <label class="label" for="message">Message</label>
                <textarea id="message" class="form-control" name="message" rows="10"></textarea>
                <input class="button" type="submit" value="Submit">
            </div>
        </form>
    </div>

    <script>
        bootstrapValidate('#email', 'email:Please enter a valid email');
        bootstrapValidate('#subject', 'required:Subject is required');
        bootstrapValidate('#message', 'required:Message is required');
    </script>
</body>

</html>
</code>```

```<code>.contact {
    color: white;
    background-color: #c0c0c0;
    padding-top: 2%;
    padding-bottom: 4%;
    width: 100%;
}

.contact h2 {
    text-align: center;
}

.form-group {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 25px;
}

#email,
#subject,
#message {
    width: 30%;
}

.label {
    width: 30%;
    text-align: left;
}

.button {
    background-color: #000000;
    color: white;
    text-align: center;
    width: fit-content;
    min-height: inherit;
    border-color: #000000;
    border-width: 10px;
    margin-top: 20px;
    margin-bottom: 5px;
}
</code>```

答:
Please see below example for validation! And add one line style: .invalid-feedback{ width:30%; }

Please see below example for validation! And add one line style: .invalid-feedback{ width:30%; }

<!DOCTYPE html>

    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

CONTACT

        <form action="" method="POST" class="needs-validation" novalidate>

                Email
                <input id="email" class="form-control" type="text" name="email" required="">

 Please enter valid email.

                <input class="button" type="submit" value="Submit">

        </form>

```

Body:
First time using bootstrap and first time asking a question on stackoverflow! I am creating this mockup with forms for email, subject and message. I am also using bootstrap validator to get error messages to pop-up (like ""). but they appear all the way to the left of the window. Anyone know of a way to get the below the input box? Or even above the input box? Like if where says "Email" I would like the error message that says "Please enter a valid email" to pop up right next to it. I've included the html and css. Hopefully I did it right. Thanks!

<!DOCTYPE html>

    <link rel="stylesheet" type="text/css" href="form-issue.css">
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">

CONTACT

        <form action="" method="POST">

                Email
                <input id="email" class="form-control" type="text" name="email">

                 Subject
                <input id="subject" class="form-control" type="text" name="subject">

                Message
                <textarea id="message" class="form-control" name="message" rows="10"></textarea>
                <input class="button" type="submit" value="Submit">

        </form>

.contact {
    color: white;
    background-color: #c0c0c0;
    padding-top: 2%;
    padding-bottom: 4%;
    width: 100%;
}

.contact h2 {
    text-align: center;
}

.form-group {
    width: 100%;
    display: flex;
    flex-direction: column;
    align-items: center;
    margin: 25px;
}

#email,
#subject,
#message {
    width: 30%;
}

.label {
    width: 30%;
    text-align: left;
}

.button {
    background-color: #000000;
    color: white;
    text-align: center;
    width: fit-content;
    min-height: inherit;
    border-color: #000000;
    border-width: 10px;
    margin-top: 20px;
    margin-bottom: 5px;
}

Body:
Please see below example for validation! And add one line style: .invalid-feedback{ width:30%; }

Please see below example for validation! And add one line style: .invalid-feedback{ width:30%; }

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous">
    <script src="https://cdn.rawgit.com/PascaleBeier/bootstrap-validate/v2.2.0/dist/bootstrap-validate.js"></script>
    <script type="text/javascript">
        (function() {
            'use strict';
            window.addEventListener('load', function() {
            // Fetch all the forms we want to apply custom Bootstrap validation styles to
            var forms = document.getElementsByClassName('needs-validation');
            // Loop over them and prevent submission
            var validation = Array.prototype.filter.call(forms, function(form) {
            form.addEventListener('submit', function(event) {
            if (form.checkValidity() === false) {
            event.preventDefault();
            event.stopPropagation();
            }
            form.classList.add('was-validated');
            }, false);
            });
            }, false);
            })();
    </script>
</head>

<body>
    <div class="contact">
        <h2>CONTACT</h2>
        <form action="" method="POST" class="needs-validation" novalidate>
            <div class="form-group">
                <label class="label" for="email">Email</label>
                <input id="email" class="form-control" type="text" name="email" required="">
                <div class="invalid-feedback"> Please enter valid email.</div>
            </div>
            <div class="form-group">
                <input class="button" type="submit" value="Submit">
            </div>
        </form>
    </div>
</body>
</html>