问:
A problem about IEEE 754 floating point operation
I want to ask an operation question about IEEE 754  floating-point:

(Take IEEE 754 single-precision floating-point number as an example : 1 sign bit, 8 exponent bits, 23 mantissa bit)

When calculating the addition and subtraction of two floating-point numbers, the mantissa with a small exponent should be aligned with the mantissa with a large exponent.

That is, it depends on the exponent difference between two floating-point numbers to see how much mantissa shifts

Here comes my problem : If the mantissa with the smaller exponent is beyond the range that mantissa can express after the shift.

Should we count the bits that exceed the range together, or do we have to discard them?

For example:
I want to calculate the subtraction of two floating point numbers

The first operand:
"0"(sign) 10010011(exponent) 0000 0000 0000 0000 1111 111(mantissa)

The second operand:
"1"(sign)   "10001110"(exponent) "0000 0000 0000 0111 1111 111"(mantissa)

The exponent of the first number is 147 in decimal, and the exponent of the second number is 142 in decimal, and 147-127 (bias) = 20,142-127 = 15

So in fact the above two numbers can become:

The first operand: 1.0000 0000 0000 0000 1111 111 * 2 ^ 20

The second operand: -1.0000 0000 0000 0111 1111 111 * 2 ^ 15

Because the second number is five less than the power of the first number, it needs to be shifted 5 bits to the right, Then my question is, it will become:

All bits are reserved, so a total of 28 bits are required to represent mantissa
-0.0000 1000 0000 0000 0011 111 "1 1111"(These five bits exceed 23bit) * (2 ^ 20)

Cut off directly after exceeding 23bit, so satisfying 23bit means mantissa
-0.0000 1000 0000 0000 0011 111 * (2 ^ 20)

Add three bits of round, guard, and sticky to consider, so use 25bit to represent mantissa.
-0.0000 1000 0000 0000 0011 111 11  =>the last two bits(bit 24 and bit 25) are guard bit and round bit,and set S = 1 (because the last three 1s are cut off)

Which one of the above options is right or none of them is right?

答:
Per IEEE 754, all bits are always considered. The result produced by the operation is the same as if you computed the full result with real-number arithmetic and then rounded that to fit into the floating-point format using whichever rounding rule is in effect. (Round to nearest, ties to even low bit/digit, is common, but there are other options for rounding, such as always upward, always downward, toward zero, and always round any non-zero amount toward an odd low bit.)

This does not mean the computer always has to compute the full real number result. For addition and subtraction, using round, guard, and sticky bits suffices to get the required answer. For other operations, more complicated algorithms may be needed. The requirement is merely that the computer has to figure out what you would get if you computed the full real-number result and rounded it—it does not actually have to figure out the full real-number result.

(“Significand” is the preferred term for the fraction portion of a floating-point representation. “Mantissa” is an old term for the fraction portion of a logarithm. Mantissas are logarithmic; adding to a mantissa multiplies the number represented. Significands are linear; adding to a significand adds to the number represented.)


来源: stackexchange

问:
Spring boot: enforce best practices
I am setting up a project and wondering if there any way to enforce repository instance access from service layer only? </p>

答:
Here is one interesting method IMO, although (disclaimer) I haven’t seen that someone really implements this:

Create the following maven modules:

Controllers

Services-api

Service-impl

Repos-api

Repos-impl

Spring-boot-application

All the modules but the last one will be “ordinary” jars, the last one will be JAR/WAR build with spring boot maven plugin.

Now, define the dependencies as follows:

Controller depends on services-api

Services-api includes only interfaces for services, it does not have dependencies

Services-impl depends on services-api and repos-api

Repos-Api are again only interfaces, no dependencies there

Repos-Impl depends on Repos-api and persistence drivers (like JDBC drivers or whatever you use)

Spring-boot-application contains dependencies on the Controllers module, Service-impl (that brings transitively Service-Api) and Repos-impl (that brings repo api transitively). This is a kind of wrapper that glues everything together in runtime.

So now, if you’re writing the controller (module Controllers), then you can inject only interfaces of the services, otherwise it won’t compile. You can’t inject the repositories (neither interface, nor implementations), again it won’t compile.

When you create the service (interface) - you don’t need any dependencies, dependencies between services will be supplied at the level of implementation that may depend on other services.

When you’re writing the implementation of the service - its ok to inject repository api, but not an implementation (again, it won’t compile).

If you’re using Java 9+, you might probably create the same level of separation by using their module system, with which I’m not familiar, however the core idea is simple:

Spring is a runtime framework, and my answer is an attempt to “catch” these “bad” usages at the level of compilation.

I understand that the presented separation is “too strict” and probably many teams won’t bother doing such a thing, I by myself rather “rely” on the programmers that work on the project that they “know what they do”, but I also understand that sometimes you can’t really rely on that and hence my answer :)

ContentLicense: CC BY-SA 4.0

Title: Spring boot: enforce best practices


问:
Insert Data from Excel into Access
I've made some code to insert data from an excel table in to an access database - my code is as follow:

```<code>    Sub AddData()

Dim Cn As ADODB.Connection

Set Cn = New ADODB.Connection

'lets connect to the workbook first, I tested this, it works for me
Cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sample.xls;Extended Properties=Excel 8.0;" _
& "Persist Security Info=False"

' Append data from Sheet1 of workbook to Table1 of mydb.mdb:
Cn.Execute "INSERT INTO tblSales IN 'C:\Users\User\Documents\access.mdb' SELECT * FROM [datasheet]"

Cn.Close
Set Cn = Nothing

End Sub
</code>```

My problem is when executing this I get the error "Microsoft Jet Engine could not find the path to object "datasheet" . Datasheet is just the name of the sheet where the data is located in my workbook. Any help is much appreciated.

答:
```<code>xlFilepath = Application.ThisWorkbook.FullName
Sql = "INSERT INTO tblSales " & _

"SELECT * FROM [Excel 12.0 Macro;HDR=YES;DATABASE=" & xlFilepath & "].[datasheet$A1:AK10011] "

cnn.Execute Sql
</code>```

Warning in your Datasheet Table The first 8 rows. Assuming theres a Heading (HDR=YES)
the next 6 rows should contain a dummy data to define your columns equivalent to your access table column definition.

Title: Insert Data from Excel into Access

Body:
I've made some code to insert data from an excel table in to an access database - my code is as follow:

    Sub AddData()

Dim Cn As ADODB.Connection

Set Cn = New ADODB.Connection

'lets connect to the workbook first, I tested this, it works for me
Cn.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=sample.xls;Extended Properties=Excel 8.0;" _
& "Persist Security Info=False"

' Append data from Sheet1 of workbook to Table1 of mydb.mdb:
Cn.Execute "INSERT INTO tblSales IN 'C:\Users\User\Documents\access.mdb' SELECT * FROM [datasheet]"

Cn.Close
Set Cn = Nothing

End Sub

My problem is when executing this I get the error "Microsoft Jet Engine could not find the path to object "datasheet" . Datasheet is just the name of the sheet where the data is located in my workbook. Any help is much appreciated.

Body:
xlFilepath = Application.ThisWorkbook.FullName
Sql = "INSERT INTO tblSales " & _

"SELECT * FROM [Excel 12.0 Macro;HDR=YES;DATABASE=" & xlFilepath & "].[datasheet$A1:AK10011] "

cnn.Execute Sql

Warning in your Datasheet Table The first 8 rows. Assuming theres a Heading (HDR=YES)
the next 6 rows should contain a dummy data to define your columns equivalent to your access table column definition.


问:
when this code executes, it shows no output. Why is that?
Following code has no output when it executes. Can anyone explain the following code?

int main() {
  int i, j;

  for (i = 0; i < 10; i++) {
    if (i % 2)
      printf("%d\t", i);
    else
      break;
  }
}
```

答: 0 % 2 gives false so the loop terminates at the first iteration without calling the printf.


问:
How Spark distributes data using Hash Partitioner?
To understand how Spark partitioning works, I have the following piece of code on spark 1.6

```<code>// Count size of partition for RDD[(String, Int)]
def countByPartition1(rdd: RDD[(String, Int)]) = {
    rdd.mapPartitions(iter => Iterator(iter.length))
}

// Count size of partition for RDD[String]
def countByPartition2(rdd: RDD[String]) = {
    rdd.mapPartitions(iter => Iterator(iter.length))
}

// Case 1
val rdd1 = sc.parallelize(Array(("aa", 1), ("aa", 1), ("aa", 1), ("aa", 1)), 8)
countByPartition1(rdd1).collect()
>> Array[Int] = Array(0, 1, 0, 1, 0, 1, 0, 1)

// Case 2
val rdd2 = sc.parallelize(Array("aa", "aa", "aa", "aa"), 8)
countByPartition2(rdd2).collect()
>> Array[Int] = Array(0, 1, 0, 1, 0, 1, 0, 1)
</code>```

In both, the cases data is distributed uniformly.
I do have the following questions on the basis of the above observation:

In the case of rdd1, hash partitioning should calculate hash code of the key (i.e. "aa" in this case), so all records should go to a single partition instead of uniform distribution?

In the case of rdd2, there is no key-value pair so how is hash partitioning going to work i.e. what is the key to calculating hash code?

I have followed @zero323's answer too but couldn't find answers for the above questions.

答:
On such initial assignment from reading a file or generating yourself from the driver there is no actual partitioner like hash applied.

If you run val p = rdd1.partitioner,  you will see the value None.

Given N values for an RDD of V or (K,V) format - then the V or (K,V) format is not actually relevant:

then for M partitions, Spark must have an algorithm for calculating where to place what data, else it could never proceed past this step and we could not get on with things!

then Spark will place an equal amount of data initially at equal intervals based on next integer (M/N).

So if I have 4 values with 10 partitions, every next higher integer of (10 / 2.5) steps Spark will place data. That is what you are seeing. Same applies to 4 values with 8 partitions - as you saw.

There is no hashing applied yet. Edge case is initial allocation. For driver created RDDs this is how it works, for file based sources a little different.

Body:
To understand how Spark partitioning works, I have the following piece of code on spark 1.6

// Count size of partition for RDD[(String, Int)]
def countByPartition1(rdd: RDD[(String, Int)]) = {
    rdd.mapPartitions(iter => Iterator(iter.length))
}

// Count size of partition for RDD[String]
def countByPartition2(rdd: RDD[String]) = {
    rdd.mapPartitions(iter => Iterator(iter.length))
}

// Case 1
val rdd1 = sc.parallelize(Array(("aa", 1), ("aa", 1), ("aa", 1), ("aa", 1)), 8)
countByPartition1(rdd1).collect()
>> Array[Int] = Array(0, 1, 0, 1, 0, 1, 0, 1)

// Case 2
val rdd2 = sc.parallelize(Array("aa", "aa", "aa", "aa"), 8)
countByPartition2(rdd2).collect()
>> Array[Int] = Array(0, 1, 0, 1, 0, 1, 0, 1)

In both, the cases data is distributed uniformly.
I do have the following questions on the basis of the above observation:

In the case of rdd1, hash partitioning should calculate hash code of the key (i.e. "aa" in this case), so all records should go to a single partition instead of uniform distribution?

In the case of rdd2, there is no key-value pair so how is hash partitioning going to work i.e. what is the key to calculating hash code?

I have followed @zero323's answer too but couldn't find answers for the above questions.


问:
How can i get value from URL in java script
http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz

How do i get value "XYZ" from the url using javascript

答:
The window.location object gives you everything you need to accomplish this. Check the API docs for Location to see all the available values you have regarding the current URL.

For this specific example you have given. window.location.pathname will be /admin/parking/airportParkingPriorityUpdate/xyz.

You can split this easily with window.location.pathname.split('/'). It's then a case of taking the last array value from the result.

```<code>const path = window.location.pathname;
const parts = path.split('/');
const result = parts[parts.length - 1];
</code>```

<= IE 10

Just to note that IE <=10 never includes the leading / in window.location.pathname.

Body:
The window.location object gives you everything you need to accomplish this. Check the API docs for Location to see all the available values you have regarding the current URL.

For this specific example you have given. window.location.pathname will be /admin/parking/airportParkingPriorityUpdate/xyz.

You can split this easily with window.location.pathname.split('/'). It's then a case of taking the last array value from the result.

const path = window.location.pathname;
const parts = path.split('/');
const result = parts[parts.length - 1];

<= IE 10

Just to note that IE <=10 never includes the leading / in window.location.pathname.


答:
i % 2 gives the remainder of the Euclidian division of i by 2. It does NOT mean "i is divisible by 2". If the latter is true, then i % 2 gives 0 which implicitely converts to false. If it is false, then i % 2 gives 1 which implicitely converts to true. Therefore, in the first iteration, the conditional ex^pression evaluates to false so you break out of the loop immediately.

If you want to check the divisibility of i by 2, you must use i % 2 == 0.

Title: when this code executes, it shows no output. Why is that?

Body:
Following code has no output when it executes. Can anyone explain the following code?

int main() {
  int i, j;

  for (i = 0; i < 10; i++) {
    if (i % 2)
      printf("%d\t", i);
    else
      break;
  }
}


问:
Why is my Trigger not triggering (Unity, C#)
I work at the moment on my enemies but in the script they don't want to activate the trigger in the script :/

I'm using the same script and trigger for every enemy (they only have different weapons)

The transition doesn't have exit time

Normally it should after Facetargetting me, starting to play animation because of trigger

This is the script:

```<code>public class Gegnerscript : MonoBehaviour
{
    public float lookRadius = 10f;

    Transform target;
    NavMeshAgent agent;

    Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        target = GegnerManager.instance.Player.transform;
        agent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        float distance = Vector3.Distance(target.position, transform.position);

        if (distance <= lookRadius)
        {
            agent.SetDestination(target.position);

            if (distance <= agent.stoppingDistance)
            {
                FaceTarget(); //is working
                // animator.SetTrigger("AngriffGegner");  // is not working/doesn't trigger
            }
        }
    }

    void FaceTarget ()
    {
        Vector3 direction = (target.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.black;
        Gizmos.DrawWireSphere(transform.position, lookRadius);
    }
}
</code>```

答: if agent.stoppingDistance > lookRadius, your trigger will not work.</p>

Body:
I work at the moment on my enemies but in the script they don't want to activate the trigger in the script :/

I'm using the same script and trigger for every enemy (they only have different weapons)

The transition doesn't have exit time

Normally it should after Facetargetting me, starting to play animation because of trigger

This is the script:

public class Gegnerscript : MonoBehaviour
{
    public float lookRadius = 10f;

    Transform target;
    NavMeshAgent agent;

    Animator animator;

    // Start is called before the first frame update
    void Start()
    {
        target = GegnerManager.instance.Player.transform;
        agent = GetComponent<NavMeshAgent>();
        animator = GetComponent<Animator>();
    }

    // Update is called once per frame
    void Update()
    {
        float distance = Vector3.Distance(target.position, transform.position);

        if (distance <= lookRadius)
        {
            agent.SetDestination(target.position);

            if (distance <= agent.stoppingDistance)
            {
                FaceTarget(); //is working
                // animator.SetTrigger("AngriffGegner");  // is not working/doesn't trigger
            }
        }
    }

    void FaceTarget ()
    {
        Vector3 direction = (target.position - transform.position).normalized;
        Quaternion lookRotation = Quaternion.LookRotation(new Vector3(direction.x, 0, direction.z));
        transform.rotation = Quaternion.Slerp(transform.rotation, lookRotation, Time.deltaTime * 5f);
    }

    private void OnDrawGizmosSelected()
    {
        Gizmos.color = Color.black;
        Gizmos.DrawWireSphere(transform.position, lookRadius);
    }
}


问:
Extracting data from dictionary returned by json.loads
Here is what I am trying to do:  Prompt for an URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data and compute their sum.

Here is what I have so far in Python:

```<code>import json
import urllib

serviceurl = 'http://python-data.dr-chuck.net/comments_42.json'

while True:
    url = serviceurl + urllib.urlencode(('sensor':'false', 'address' : address))
    print "Retrieving", url
    uh = urllib.urlopen(url)
    data = uh.read()
    print "Retrieved", len(data), "characters"

    try:    js = json.loads(str(data))
    except:     js = None

    print js.dumps(js, indent = 4)

    js = ["comment"][0]["count"]
    lst = list()
    lst.append(js)
    print sum(lst)
</code>```

Here is what the JSON data looks like:

```<code>{
  comments: [
    {
      name: "Matthias"
      count: 97
    },
    {
      name: "Geomer"
      count: 97
    }
    ...
  ]
}
</code>```

I am using Python 2. This is my first time doing this, so any feedback you can give me about this would be helpful, especially after the try/except statements. Thanks in advance.

答:
```<code>import urllib.request, urllib.parse, urllib.error
import json
import ssl

# Ignore SSL certificate errors
ctx = ssl.create_default_context()
ctx.check_hostname = False
ctx.verify_mode = ssl.CERT_NONE

url = input('Enter - ')
print('Retrieving', url)
uh = urllib.request.urlopen(url, context=ctx)
data = uh.read()

info = json.loads(data)
#print(info) #to see the info dictionary/object
#print(json.dumps(info, indent=2))

count = 0
sum = 0

for item in info['comments']:
    num = item['count']
    sum = sum + int(num)
    count = count + 1

print('Count: ', count)
print('Sum: ', sum)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Here is what I am trying to do:  Prompt for an URL, read the JSON data from that URL using urllib and then parse and extract the comment counts from the JSON data and compute their sum.

Here is what I have so far in Python:

import json
import urllib

serviceurl = 'http://python-data.dr-chuck.net/comments_42.json'

while True:
    url = serviceurl + urllib.urlencode(('sensor':'false', 'address' : address))
    print "Retrieving", url
    uh = urllib.urlopen(url)
    data = uh.read()
    print "Retrieved", len(data), "characters"

    try:    js = json.loads(str(data))
    except:     js = None

    print js.dumps(js, indent = 4)

    js = ["comment"][0]["count"]
    lst = list()
    lst.append(js)
    print sum(lst)

Here is what the JSON data looks like:

{
  comments: [
    {
      name: "Matthias"
      count: 97
    },
    {
      name: "Geomer"
      count: 97
    }
    ...
  ]
}

I am using Python 2. This is my first time doing this, so any feedback you can give me about this would be helpful, especially after the try/except statements. Thanks in advance.


问:
How to add numbers for a string sentence in Java?
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

```<code>public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}
</code>```

}
enter code here

答:
Store age1 and age2 as variables and use a separate int for increment string to output the result.
For example:

```<code>public int addToString(int increment, int age1, int age2){

String s = "My age is " +(age1 + inc)+ " , and your age is under " +(age2 + inc);

return s; //addToString(5, 50,30) returns: "My age is 55, and your age is under 35"
}
</code>```

Body:
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}

}
enter code here

Body:
Store age1 and age2 as variables and use a separate int for increment string to output the result.
For example:

public int addToString(int increment, int age1, int age2){

String s = "My age is " +(age1 + inc)+ " , and your age is under " +(age2 + inc);

return s; //addToString(5, 50,30) returns: "My age is 55, and your age is under 35"
}


问:
PHP code has replaced with '0000 0000 0000 0000....'
I am building a PHP project using MVC structure and I use SublimeText.

The project worked fine till yesterday but when I open the project folder today, all the codes of php files which are in the

```<code>controllers
</code>```

folder and

```<code>libs
</code>```

folder, has replaced with zeros with the pattern

```<code>**0000 0000 0000 0000 0000 0000 0000 0000**
</code>```

This pattern continues in to number of lines.

Please, can anyone tell me why this happens? and How can I recover my code back?

答:
The easiest way to delete zero width spaces in Sublime Text is using the search and replace functionality:

Press Ctrl + h ( Alt + Cmd + f for Mac )

Enable the Regular expression flag by clicking the leftmost button on the search panel or pressing Alt + r ( Alt + Cmd + r for Mac )

Enter \x{200b} as the search term

Make sure the "Replace with" field is empty and hit "Replace All"

Plugins for solving this problem for good!

I searched for a plugin that would highlight all the possibly code breaking characters but couldn't find one for Sublime Text so I wrote one: https://github.com/TuureKaunisto/highlight-dodgy-chars

The plugin works on a whitelist principle: all non-ascii characters that are not whitelisted in the settings get highlighted.

If you want to highlight things based on your own regular expression, this plugin will do the trick: https://github.com/bluegray/Highlighter and is also easily installable via Package Manager.

Body:
I am building a PHP project using MVC structure and I use SublimeText.

The project worked fine till yesterday but when I open the project folder today, all the codes of php files which are in the

controllers

folder and

libs

folder, has replaced with zeros with the pattern

**0000 0000 0000 0000 0000 0000 0000 0000**

This pattern continues in to number of lines.

Please, can anyone tell me why this happens? and How can I recover my code back?


问:
Build native image for micronaut application
As the title indicates I'm trying to build a native image for a Kotlin based Micronaut application using Docker.

I've added the following dependencies to my build.gradle file.

```<code>compileOnly 'org.graalvm.nativeimage:svm'
annotationProcessor 'io.micronaut:micronaut-graal'
</code>```

My Dockerfile looks as the following.

```<code>FROM oracle/graalvm-ce:20.1.0-java11 as graalvm
RUN gu install native-image

WORKDIR /src
COPY . /src

RUN ./gradlew assemble
RUN native-image --no-server -cp build/libs/*-all.jar dk.fitfit.injurylog.Application

FROM frolvlad/alpine-glibc
RUN apk update && apk add libstdc++
COPY --from=graalvm /src/dk.fitfit.injurylog.application /app/app
ENTRYPOINT ["/app/app"]
</code>```

Everything things seems to be in order. The image boots and seems to accept connections but when I initiates a http request the following error occurs.

```<code>11:38:52.033 [nioEventLoopGroup-1-2] ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: Failed to inject value for field [jacksonModules] of class: dk.fitfit.injurylog.util.CustomObjectMapperFactory

Message: Error setting field value: No field 'jacksonModules' found for type: io.micronaut.jackson.ObjectMapperFactory

io.micronaut.context.exceptions.DependencyInjectionException: Failed to inject value for field [jacksonModules] of class: dk.fitfit.injurylog.util.CustomObjectMapperFactory

Message: Error setting field value: No field 'jacksonModules' found for type: io.micronaut.jackson.ObjectMapperFactory

    at io.micronaut.context.AbstractBeanDefinition.injectBeanField(AbstractBeanDefinition.java:748)
    at dk.fitfit.injurylog.util.$CustomObjectMapperFactoryDefinition.injectBean(Unknown Source)
    at dk.fitfit.injurylog.util.$CustomObjectMapperFactoryDefinition.build(Unknown Source)
    at io.micronaut.context.DefaultBeanContext.doCreateBean(DefaultBeanContext.java:1714)
    at io.micronaut.context.DefaultBeanContext.createAndRegisterSingletonInternal(DefaultBeanContext.java:2428)
    at io.micronaut.context.DefaultBeanContext.createAndRegisterSingleton(DefaultBeanContext.java:2414)
    at io.micronaut.context.DefaultBeanContext.getBeanForDefinition(DefaultBeanContext.java:2105)
    at io.micronaut.context.DefaultBeanContext.getBeanInternal(DefaultBeanContext.java:2079)
    at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:1078)
    at dk.fitfit.injurylog.util.$CustomObjectMapperFactory$ObjectMapper1Definition.build(Unknown Source)
    at io.micronaut.context.DefaultBeanContext.doCreateBean(DefaultBeanContext.java:1714)
    at io.micronaut.context.DefaultBeanContext.createAndRegisterSingletonInternal(DefaultBeanContext.java:2428)
    at io.micronaut.context.DefaultBeanContext.createAndRegisterSingleton(DefaultBeanContext.java:2414)
    at io.micronaut.context.DefaultBeanContext.getBeanForDefinition(DefaultBeanContext.java:2105)
    at io.micronaut.context.DefaultBeanContext.getBeanInternal(DefaultBeanContext.java:2079)
    at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:616)
    at io.micronaut.context.UnresolvedProvider.get(UnresolvedProvider.java:58)
    at io.micronaut.jackson.codec.JacksonMediaTypeCodec.getObjectMapper(JacksonMediaTypeCodec.java:105)
    at io.micronaut.jackson.codec.JacksonMediaTypeCodec.encode(JacksonMediaTypeCodec.java:212)
    at io.micronaut.jackson.codec.JacksonMediaTypeCodec.encode(JacksonMediaTypeCodec.java:221)
    at io.micronaut.http.server.netty.RoutingInBoundHandler.encodeBodyAsByteBuf(RoutingInBoundHandler.java:1405)
    at io.micronaut.http.server.netty.RoutingInBoundHandler.encodeBodyWithCodec(RoutingInBoundHandler.java:1351)
    at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$subscribeToResponsePublisher$12(RoutingInBoundHandler.java:1272)
    at io.reactivex.internal.operators.flowable.FlowableMap$MapSubscriber.onNext(FlowableMap.java:63)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onNext(RxInstrumentedSubscriber.java:72)
    at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.onNext(FlowableSubscribeOn.java:97)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onNext(RxInstrumentedSubscriber.java:72)
    at io.micronaut.http.context.ServerRequestTracingPublisher$1.lambda$onNext$1(ServerRequestTracingPublisher.java:60)
    at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:68)
    at io.micronaut.http.context.ServerRequestTracingPublisher$1.onNext(ServerRequestTracingPublisher.java:60)
    at io.micronaut.http.context.ServerRequestTracingPublisher$1.onNext(ServerRequestTracingPublisher.java:52)
    at io.reactivex.internal.util.HalfSerializer.onNext(HalfSerializer.java:45)
    at io.reactivex.internal.subscribers.StrictSubscriber.onNext(StrictSubscriber.java:97)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onNext(RxInstrumentedSubscriber.java:72)
    at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FlowableSwitchIfEmpty.java:59)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onNext(RxInstrumentedSubscriber.java:67)
    at io.reactivex.internal.subscriptions.ScalarSubscription.request(ScalarSubscription.java:55)
    at io.reactivex.internal.subscriptions.SubscriptionArbiter.setSubscription(SubscriptionArbiter.java:99)
    at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty$SwitchIfEmptySubscriber.onSubscribe(FlowableSwitchIfEmpty.java:51)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onSubscribe(RxInstrumentedSubscriber.java:56)
    at io.reactivex.internal.operators.flowable.FlowableJust.subscribeActual(FlowableJust.java:34)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:58)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.reactivex.internal.operators.flowable.FlowableDefer.subscribeActual(FlowableDefer.java:42)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:58)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty.subscribeActual(FlowableSwitchIfEmpty.java:32)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:58)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14885)
    at io.micronaut.http.context.ServerRequestTracingPublisher.lambda$subscribe$0(ServerRequestTracingPublisher.java:52)
    at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:68)
    at io.micronaut.http.context.ServerRequestTracingPublisher.subscribe(ServerRequestTracingPublisher.java:52)
    at io.reactivex.internal.operators.flowable.FlowableFromPublisher.subscribeActual(FlowableFromPublisher.java:29)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:58)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
    at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker$BooleanRunnable.run(ExecutorScheduler.java:288)
    at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker.run(ExecutorScheduler.java:253)
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:834)
    at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:517)
    at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:193)
Caused by: java.lang.NoSuchFieldError: No field 'jacksonModules' found for type: io.micronaut.jackson.ObjectMapperFactory
    at io.micronaut.core.reflect.ReflectionUtils.lambda$getRequiredField$2(ReflectionUtils.java:301)
    at java.util.Optional.orElseThrow(Optional.java:408)
    at io.micronaut.core.reflect.ReflectionUtils.getRequiredField(ReflectionUtils.java:301)
    at io.micronaut.context.DefaultFieldInjectionPoint.getField(DefaultFieldInjectionPoint.java:117)
    at io.micronaut.context.DefaultFieldInjectionPoint.set(DefaultFieldInjectionPoint.java:127)
    at io.micronaut.context.AbstractBeanDefinition.injectBeanField(AbstractBeanDefinition.java:742)
    ... 77 common frames omitted
</code>```

Any clue about how to avoid the above error?

答: I had failed to annotate one of my entities with @Introspected.

Body:
As the title indicates I'm trying to build a native image for a Kotlin based Micronaut application using Docker.

I've added the following dependencies to my build.gradle file.

compileOnly 'org.graalvm.nativeimage:svm'
annotationProcessor 'io.micronaut:micronaut-graal'

My Dockerfile looks as the following.

FROM oracle/graalvm-ce:20.1.0-java11 as graalvm
RUN gu install native-image

WORKDIR /src
COPY . /src

RUN ./gradlew assemble
RUN native-image --no-server -cp build/libs/*-all.jar dk.fitfit.injurylog.Application

FROM frolvlad/alpine-glibc
RUN apk update && apk add libstdc++
COPY --from=graalvm /src/dk.fitfit.injurylog.application /app/app
ENTRYPOINT ["/app/app"]

Everything things seems to be in order. The image boots and seems to accept connections but when I initiates a http request the following error occurs.

11:38:52.033 [nioEventLoopGroup-1-2] ERROR i.m.h.s.netty.RoutingInBoundHandler - Unexpected error occurred: Failed to inject value for field [jacksonModules] of class: dk.fitfit.injurylog.util.CustomObjectMapperFactory

Message: Error setting field value: No field 'jacksonModules' found for type: io.micronaut.jackson.ObjectMapperFactory

io.micronaut.context.exceptions.DependencyInjectionException: Failed to inject value for field [jacksonModules] of class: dk.fitfit.injurylog.util.CustomObjectMapperFactory

Message: Error setting field value: No field 'jacksonModules' found for type: io.micronaut.jackson.ObjectMapperFactory

    at io.micronaut.context.AbstractBeanDefinition.injectBeanField(AbstractBeanDefinition.java:748)
    at dk.fitfit.injurylog.util.$CustomObjectMapperFactoryDefinition.injectBean(Unknown Source)
    at dk.fitfit.injurylog.util.$CustomObjectMapperFactoryDefinition.build(Unknown Source)
    at io.micronaut.context.DefaultBeanContext.doCreateBean(DefaultBeanContext.java:1714)
    at io.micronaut.context.DefaultBeanContext.createAndRegisterSingletonInternal(DefaultBeanContext.java:2428)
    at io.micronaut.context.DefaultBeanContext.createAndRegisterSingleton(DefaultBeanContext.java:2414)
    at io.micronaut.context.DefaultBeanContext.getBeanForDefinition(DefaultBeanContext.java:2105)
    at io.micronaut.context.DefaultBeanContext.getBeanInternal(DefaultBeanContext.java:2079)
    at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:1078)
    at dk.fitfit.injurylog.util.$CustomObjectMapperFactory$ObjectMapper1Definition.build(Unknown Source)
    at io.micronaut.context.DefaultBeanContext.doCreateBean(DefaultBeanContext.java:1714)
    at io.micronaut.context.DefaultBeanContext.createAndRegisterSingletonInternal(DefaultBeanContext.java:2428)
    at io.micronaut.context.DefaultBeanContext.createAndRegisterSingleton(DefaultBeanContext.java:2414)
    at io.micronaut.context.DefaultBeanContext.getBeanForDefinition(DefaultBeanContext.java:2105)
    at io.micronaut.context.DefaultBeanContext.getBeanInternal(DefaultBeanContext.java:2079)
    at io.micronaut.context.DefaultBeanContext.getBean(DefaultBeanContext.java:616)
    at io.micronaut.context.UnresolvedProvider.get(UnresolvedProvider.java:58)
    at io.micronaut.jackson.codec.JacksonMediaTypeCodec.getObjectMapper(JacksonMediaTypeCodec.java:105)
    at io.micronaut.jackson.codec.JacksonMediaTypeCodec.encode(JacksonMediaTypeCodec.java:212)
    at io.micronaut.jackson.codec.JacksonMediaTypeCodec.encode(JacksonMediaTypeCodec.java:221)
    at io.micronaut.http.server.netty.RoutingInBoundHandler.encodeBodyAsByteBuf(RoutingInBoundHandler.java:1405)
    at io.micronaut.http.server.netty.RoutingInBoundHandler.encodeBodyWithCodec(RoutingInBoundHandler.java:1351)
    at io.micronaut.http.server.netty.RoutingInBoundHandler.lambda$subscribeToResponsePublisher$12(RoutingInBoundHandler.java:1272)
    at io.reactivex.internal.operators.flowable.FlowableMap$MapSubscriber.onNext(FlowableMap.java:63)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onNext(RxInstrumentedSubscriber.java:72)
    at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.onNext(FlowableSubscribeOn.java:97)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onNext(RxInstrumentedSubscriber.java:72)
    at io.micronaut.http.context.ServerRequestTracingPublisher$1.lambda$onNext$1(ServerRequestTracingPublisher.java:60)
    at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:68)
    at io.micronaut.http.context.ServerRequestTracingPublisher$1.onNext(ServerRequestTracingPublisher.java:60)
    at io.micronaut.http.context.ServerRequestTracingPublisher$1.onNext(ServerRequestTracingPublisher.java:52)
    at io.reactivex.internal.util.HalfSerializer.onNext(HalfSerializer.java:45)
    at io.reactivex.internal.subscribers.StrictSubscriber.onNext(StrictSubscriber.java:97)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onNext(RxInstrumentedSubscriber.java:72)
    at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty$SwitchIfEmptySubscriber.onNext(FlowableSwitchIfEmpty.java:59)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onNext(RxInstrumentedSubscriber.java:67)
    at io.reactivex.internal.subscriptions.ScalarSubscription.request(ScalarSubscription.java:55)
    at io.reactivex.internal.subscriptions.SubscriptionArbiter.setSubscription(SubscriptionArbiter.java:99)
    at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty$SwitchIfEmptySubscriber.onSubscribe(FlowableSwitchIfEmpty.java:51)
    at io.micronaut.reactive.rxjava2.RxInstrumentedSubscriber.onSubscribe(RxInstrumentedSubscriber.java:56)
    at io.reactivex.internal.operators.flowable.FlowableJust.subscribeActual(FlowableJust.java:34)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:58)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.reactivex.internal.operators.flowable.FlowableDefer.subscribeActual(FlowableDefer.java:42)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:58)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.internal.operators.flowable.FlowableSwitchIfEmpty.subscribeActual(FlowableSwitchIfEmpty.java:32)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:58)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14885)
    at io.micronaut.http.context.ServerRequestTracingPublisher.lambda$subscribe$0(ServerRequestTracingPublisher.java:52)
    at io.micronaut.http.context.ServerRequestContext.with(ServerRequestContext.java:68)
    at io.micronaut.http.context.ServerRequestTracingPublisher.subscribe(ServerRequestTracingPublisher.java:52)
    at io.reactivex.internal.operators.flowable.FlowableFromPublisher.subscribeActual(FlowableFromPublisher.java:29)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.micronaut.reactive.rxjava2.RxInstrumentedFlowable.subscribeActual(RxInstrumentedFlowable.java:58)
    at io.reactivex.Flowable.subscribe(Flowable.java:14935)
    at io.reactivex.Flowable.subscribe(Flowable.java:14882)
    at io.reactivex.internal.operators.flowable.FlowableSubscribeOn$SubscribeOnSubscriber.run(FlowableSubscribeOn.java:82)
    at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker$BooleanRunnable.run(ExecutorScheduler.java:288)
    at io.reactivex.internal.schedulers.ExecutorScheduler$ExecutorWorker.run(ExecutorScheduler.java:253)
    at io.netty.util.concurrent.AbstractEventExecutor.safeExecute(AbstractEventExecutor.java:164)
    at io.netty.util.concurrent.SingleThreadEventExecutor.runAllTasks(SingleThreadEventExecutor.java:472)
    at io.netty.channel.nio.NioEventLoop.run(NioEventLoop.java:500)
    at io.netty.util.concurrent.SingleThreadEventExecutor$4.run(SingleThreadEventExecutor.java:989)
    at io.netty.util.internal.ThreadExecutorMap$2.run(ThreadExecutorMap.java:74)
    at io.netty.util.concurrent.FastThreadLocalRunnable.run(FastThreadLocalRunnable.java:30)
    at java.lang.Thread.run(Thread.java:834)
    at com.oracle.svm.core.thread.JavaThreads.threadStartRoutine(JavaThreads.java:517)
    at com.oracle.svm.core.posix.thread.PosixJavaThreads.pthreadStartRoutine(PosixJavaThreads.java:193)
Caused by: java.lang.NoSuchFieldError: No field 'jacksonModules' found for type: io.micronaut.jackson.ObjectMapperFactory
    at io.micronaut.core.reflect.ReflectionUtils.lambda$getRequiredField$2(ReflectionUtils.java:301)
    at java.util.Optional.orElseThrow(Optional.java:408)
    at io.micronaut.core.reflect.ReflectionUtils.getRequiredField(ReflectionUtils.java:301)
    at io.micronaut.context.DefaultFieldInjectionPoint.getField(DefaultFieldInjectionPoint.java:117)
    at io.micronaut.context.DefaultFieldInjectionPoint.set(DefaultFieldInjectionPoint.java:127)
    at io.micronaut.context.AbstractBeanDefinition.injectBeanField(AbstractBeanDefinition.java:742)
    ... 77 common frames omitted

Any clue about how to avoid the above error?


问:
How to send a POST request with Advanced Custom Fields data
I'm trying to send a post request to the rest api with some custom fields. THis is my code

```<code>                let newCharacter = {
                    'title': $('.create-char-name').val(),
                    'acf': {
                        'char_class': $('#char-class').val(),
                        'char_subclass': $('#char-subclass').val(),
                        'char_level': $('#char-level').val()
                    },
                    'status': 'publish'
                }

                $.ajax({
                    beforeSend: (xhr) => {
                        xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
                    },
                    url: spbk_data.root_url + '/wp-json/wp/v2/character/',
                    method: 'POST',
                    data: newCharacter,
                    success: (response) => {
                        console.log("congrats");
                        console.log(response);
                    },
                    error: (response) => {
                        console.log("Sorry");
                        console.log(response);
                    }
                });
</code>```

The request goes through without any problems, but when I check the json, the "acf" field returns false.
I'm using the acf to wp api plugin, if that information is useful.

The only info I found about this issue was this post, but I don't really understand what the answer meant. I tried adding xhr.setRequestHeader('Content-Type', application/json); (I also tried with lower case initials), below the nonce, like the post seems to suggest, but that returns this error:

"{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}"

答:
Try something like below:</p>

```<code>function NewCharacter(){

    this.title;
    this.acf;
    this.status;
}

function CharInfo(){

    this.char_class;
    this.char_subclass;
    this.char_level;

}

var charInfo = new CharInfo();
charInfo.char_class=$('#char-class').val();
charInfo.char_subclass=$('#char-subclass').val();
charInfo.char_level=$('#char-level').val();

var newCharacter = new NewCharacter();
newCharacter.title=$('.create-char-name').val();
newCharacter.acf=charInfo
newCharacter.status="publish";

$.ajax({
     beforeSend: (xhr) => {
         xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
     },
     url: spbk_data.root_url + '/wp-json/wp/v2/character/',
     method: 'POST',
     data: JSON.stringify(newCharacter),
     success: (response) => {
         console.log("congrats");
         console.log(response);
     },
     error: (response) => {
         console.log("Sorry");
         console.log(response);
     }
});

</code>```

Body:
I'm trying to send a post request to the rest api with some custom fields. THis is my code

                let newCharacter = {
                    'title': $('.create-char-name').val(),
                    'acf': {
                        'char_class': $('#char-class').val(),
                        'char_subclass': $('#char-subclass').val(),
                        'char_level': $('#char-level').val()
                    },
                    'status': 'publish'
                }

                $.ajax({
                    beforeSend: (xhr) => {
                        xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
                    },
                    url: spbk_data.root_url + '/wp-json/wp/v2/character/',
                    method: 'POST',
                    data: newCharacter,
                    success: (response) => {
                        console.log("congrats");
                        console.log(response);
                    },
                    error: (response) => {
                        console.log("Sorry");
                        console.log(response);
                    }
                });

The request goes through without any problems, but when I check the json, the "acf" field returns false.
I'm using the acf to wp api plugin, if that information is useful.

The only info I found about this issue was this post, but I don't really understand what the answer meant. I tried adding xhr.setRequestHeader('Content-Type', application/json); (I also tried with lower case initials), below the nonce, like the post seems to suggest, but that returns this error:

"{"code":"rest_invalid_json","message":"Invalid JSON body passed.","data":{"status":400,"json_error_code":4,"json_error_message":"Syntax error"}}"

Body:
Try something like below:

function NewCharacter(){

    this.title;
    this.acf;
    this.status;
}

function CharInfo(){

    this.char_class;
    this.char_subclass;
    this.char_level;

}

var charInfo = new CharInfo();
charInfo.char_class=$('#char-class').val();
charInfo.char_subclass=$('#char-subclass').val();
charInfo.char_level=$('#char-level').val();

var newCharacter = new NewCharacter();
newCharacter.title=$('.create-char-name').val();
newCharacter.acf=charInfo
newCharacter.status="publish";

$.ajax({
     beforeSend: (xhr) => {
         xhr.setRequestHeader('X-WP-Nonce', spbk_data.nonce);
     },
     url: spbk_data.root_url + '/wp-json/wp/v2/character/',
     method: 'POST',
     data: JSON.stringify(newCharacter),
     success: (response) => {
         console.log("congrats");
         console.log(response);
     },
     error: (response) => {
         console.log("Sorry");
         console.log(response);
     }
});


问:
Filter out a circle boundary in matplotlib python
I am trying to plot the electric field generated when an spheric conductor is placed in an homogeneous electric field. I based my code on this question to use np.where function to filter out the unitary circle. But instead of that, all of the field at -1< x<1 is filtered out.

My code is shown below, how can I fix this?

```<code>import sys
import numpy as np
import matplotlib.pyplot as plt
import scipy.constants as spc

def E(x, y):
    """due to an spheric conductor set on a homogeneous electric field"""
    E_x = 3*x*y/((y**2+x**2)**2.5)
    E_y = 3*y*y/((y**2+x**2)**2.5)-1/((y**2+x**2)**1.5)+1
    return E_x, E_y

# Grid of x, y points
n= 100
a=2
y = np.linspace(-a, a, n)
x = np.linspace(-a, a, n)
X, Y = np.meshgrid(x, y)
r=(x**2+y**2)**0.5
circle = r>=1
Ex, Ey = E(X,Y)
Ex, Ey = np.where(circle,Ex,0), np.where(circle,Ey,0)

#plot
fig = plt.figure()
ax = fig.add_subplot(111)

color = 2 * np.log(np.hypot(Ex, Ey))
ax.streamplot(x, y, Ex, Ey, color=color, linewidth=1, cmap=plt.cm.inferno,
              density=1, arrowstyle='->', arrowsize=1.5)

ax.set_ylabel('$y$')
ax.set_xlabel('$x$')
ax.set_ylim(-a,a)
ax.set_xlim(-a,a)
ax.set_aspect('equal')
plt.show()
</code>```

答:
When you create your r array to use in the circle filter, you are using the 1D x and y arrays, when you should be using the 2D X and Y arrays.

Change that line from

```<code>r = (x**2 + y**2)**0.5
</code>```

to

```<code>r = (X**2 + Y**2)**0.5
</code>```

and it works as expected

Body:
I am trying to plot the electric field generated when an spheric conductor is placed in an homogeneous electric field. I based my code on this question to use np.where function to filter out the unitary circle. But instead of that, all of the field at -1< x<1 is filtered out.

My code is shown below, how can I fix this?

import sys
import numpy as np
import matplotlib.pyplot as plt
import scipy.constants as spc

def E(x, y):
    """due to an spheric conductor set on a homogeneous electric field"""
    E_x = 3*x*y/((y**2+x**2)**2.5)
    E_y = 3*y*y/((y**2+x**2)**2.5)-1/((y**2+x**2)**1.5)+1
    return E_x, E_y

# Grid of x, y points
n= 100
a=2
y = np.linspace(-a, a, n)
x = np.linspace(-a, a, n)
X, Y = np.meshgrid(x, y)
r=(x**2+y**2)**0.5
circle = r>=1
Ex, Ey = E(X,Y)
Ex, Ey = np.where(circle,Ex,0), np.where(circle,Ey,0)

#plot
fig = plt.figure()
ax = fig.add_subplot(111)

color = 2 * np.log(np.hypot(Ex, Ey))
ax.streamplot(x, y, Ex, Ey, color=color, linewidth=1, cmap=plt.cm.inferno,
              density=1, arrowstyle='->', arrowsize=1.5)

ax.set_ylabel('$y$')
ax.set_xlabel('$x$')
ax.set_ylim(-a,a)
ax.set_xlim(-a,a)
ax.set_aspect('equal')
plt.show()

Body:
When you create your r array to use in the circle filter, you are using the 1D x and y arrays, when you should be using the 2D X and Y arrays.

Change that line from

r = (x**2 + y**2)**0.5

to

r = (X**2 + Y**2)**0.5

and it works as expected


答:
You could use a regular expression:

// create a url - object
let url = new URL('http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz');

// use just the pathname of the url (if there would exist url - params in the url they would be filtered out)
let result = url.pathname.match(/((?!\/).)+$/)[0];

// use the result however you want
console.log(result)```

Title: How can i get value from URL in java script

Body:
http://localhost:3000/admin/parking/airportParkingPriorityUpdate/xyz

How do i get value "XYZ" from the url using javascript


问:
Why occur KotlinNullPointerException in this code?
I'm making a chat app.
When I send the message, it is storaged in firebase real-time database and will be display users with whom i have messages.

but, in this process, occur the KotlinNullPointerExcpetion.

You can read below codes.

First, codes when I send the message. (MessageActivity.kt)

```<code>sendBtn.setOnClickListener(object : View.OnClickListener{
        override fun onClick(v: View?) {
            var msg = msgSendBox.text.toString()
            if(!msg.equals("")) {
                sendMessage(firebaseUser.uid, receiverId, msgSendBox.text.toString())
                msgSendBox.setText("")
            }
        }
    })
</code>```

.
.

```<code>private fun sendMessage(sender : String, receiver : String, message : String){
    var reference = FirebaseDatabase.getInstance().getReference()

    var hashMap : HashMap<String, Object> = HashMap();
    hashMap.put("sender", sender as Object)
    hashMap.put("receiver", receiver as Object)
    hashMap.put("message", message as Object)

    reference.child("Chats").push().setValue(hashMap)
}
</code>```

and codes that display all users.(UserListFragment.kt)

```<code>private fun readUsers(){
    var firebaseUser = FirebaseAuth.getInstance().currentUser
    var reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.addValueEventListener(object : ValueEventListener{
        override fun onDataChange(dataSnapShot: DataSnapshot) {

            for(snapShot in dataSnapShot.children){
                var user = snapShot.getValue(User::class.java)

                assert(user != null)
                assert(firebaseUser != null)
                if(!(user?.id.equals(firebaseUser?.uid))){
                    mUsers.add(user!!)
                }
            }

            userAdapter = UserAdapter(context!!, mUsers)

            recyclerView.adapter = userAdapter
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}
</code>```

and codes that display users whom i have messages(ChatListFragment.kt)

```<code>private fun readChat(){
    mUsers = ArrayList()

    reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.addValueEventListener(object : ValueEventListener{
        override fun onDataChange(dataSnapShot: DataSnapshot) {
            mUsers.clear()

            for(snapShot in dataSnapShot.children){
                var user = snapShot.getValue(User::class.java) as User

                for(mId in usersList) {
                    assert(user != null)
                    if (user.id.equals(mId)) {
                        mUsers.add(user)
                    }
                }

            }
            userAdapter = UserAdapter(context!!, mUsers)
            recyclerView.adapter = userAdapter
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}
</code>```

in this codes, it occurs the errors like below.

```<code>    Process: com.techtown.breadchatapp, PID: 7773
kotlin.KotlinNullPointerException
    at com.techtown.breadchatapp.fragment.UserListFragment$readUsers$1.onDataChange(UserListFragment.kt:65)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
    at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
    at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7506)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:956)
</code>```

答:
Look at the code mentioned in the error:

```<code>    at com.techtown.breadchatapp.fragment.UserListFragment$readUsers$1.onDataChange(UserListFragment.kt:65)
</code>```

65th line...

Body:
I'm making a chat app.
When I send the message, it is storaged in firebase real-time database and will be display users with whom i have messages.

but, in this process, occur the KotlinNullPointerExcpetion.

You can read below codes.

First, codes when I send the message. (MessageActivity.kt)

sendBtn.setOnClickListener(object : View.OnClickListener{
        override fun onClick(v: View?) {
            var msg = msgSendBox.text.toString()
            if(!msg.equals("")) {
                sendMessage(firebaseUser.uid, receiverId, msgSendBox.text.toString())
                msgSendBox.setText("")
            }
        }
    })

.
.

private fun sendMessage(sender : String, receiver : String, message : String){
    var reference = FirebaseDatabase.getInstance().getReference()

    var hashMap : HashMap<String, Object> = HashMap();
    hashMap.put("sender", sender as Object)
    hashMap.put("receiver", receiver as Object)
    hashMap.put("message", message as Object)

    reference.child("Chats").push().setValue(hashMap)
}

and codes that display all users.(UserListFragment.kt)

private fun readUsers(){
    var firebaseUser = FirebaseAuth.getInstance().currentUser
    var reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.addValueEventListener(object : ValueEventListener{
        override fun onDataChange(dataSnapShot: DataSnapshot) {

            for(snapShot in dataSnapShot.children){
                var user = snapShot.getValue(User::class.java)

                assert(user != null)
                assert(firebaseUser != null)
                if(!(user?.id.equals(firebaseUser?.uid))){
                    mUsers.add(user!!)
                }
            }

            userAdapter = UserAdapter(context!!, mUsers)

            recyclerView.adapter = userAdapter
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}

and codes that display users whom i have messages(ChatListFragment.kt)

private fun readChat(){
    mUsers = ArrayList()

    reference = FirebaseDatabase.getInstance().getReference("Users")

    reference.addValueEventListener(object : ValueEventListener{
        override fun onDataChange(dataSnapShot: DataSnapshot) {
            mUsers.clear()

            for(snapShot in dataSnapShot.children){
                var user = snapShot.getValue(User::class.java) as User

                for(mId in usersList) {
                    assert(user != null)
                    if (user.id.equals(mId)) {
                        mUsers.add(user)
                    }
                }

            }
            userAdapter = UserAdapter(context!!, mUsers)
            recyclerView.adapter = userAdapter
        }

        override fun onCancelled(p0: DatabaseError) {

        }
    })
}

in this codes, it occurs the errors like below.

    Process: com.techtown.breadchatapp, PID: 7773
kotlin.KotlinNullPointerException
    at com.techtown.breadchatapp.fragment.UserListFragment$readUsers$1.onDataChange(UserListFragment.kt:65)
    at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.2.1:75)
    at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.2.1:63)
    at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.2.1:55)
    at android.os.Handler.handleCallback(Handler.java:907)
    at android.os.Handler.dispatchMessage(Handler.java:99)
    at android.os.Looper.loop(Looper.java:216)
    at android.app.ActivityThread.main(ActivityThread.java:7506)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:548)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:956)

Body:
Look at the code mentioned in the error:

    at com.techtown.breadchatapp.fragment.UserListFragment$readUsers$1.onDataChange(UserListFragment.kt:65)

65th line...


问:
Why I am able to pass a bigger array into a smaller array in Java?
This might be a silly question but does a Java array accept more than its size? If yes then why do we need ArrayList? I thought that arrays had a fixed size that can't be increased at runtime. Here is my test code:</p>

```<code>public class ArraySizeDemo {
    int[] anArray = new int[5];

    public int[] getAnArray() {
        return anArray;
    }

    public void setAnArray(int[] anArray) {
        this.anArray = anArray;
    }
}

public class ArrayDemo {
    public static void main(String[] args) {
        ArraySizeDemo ar = new ArraySizeDemo();

        int arr[] = {0,1,2,3,4,5,6,7,8,9};
        int testarray[] = new int[10];
        ar.setAnArray(arr); // it should give an error here since I am trying to
        // assign an array of 10 to an array of 5
        testarray = ar.getAnArray();
        for (int i = 0; i < arr.length; i++)
            System.out.println(testarray[i]);
    }
}
</code>```

答:
As others have said, the statement: this.anArray = anArray

or, in general any statement of type: array[x] = array[y]

does not copy element's of one array to another. The assignment operator, here, simply references(provides location/address of) one array to other.

A clear in-depth explanation about this is provided here (archived)

Body:
This might be a silly question but does a Java array accept more than its size? If yes then why do we need ArrayList? I thought that arrays had a fixed size that can't be increased at runtime. Here is my test code:

public class ArraySizeDemo {
    int[] anArray = new int[5];

    public int[] getAnArray() {
        return anArray;
    }

    public void setAnArray(int[] anArray) {
        this.anArray = anArray;
    }
}

public class ArrayDemo {
    public static void main(String[] args) {
        ArraySizeDemo ar = new ArraySizeDemo();

        int arr[] = {0,1,2,3,4,5,6,7,8,9};
        int testarray[] = new int[10];
        ar.setAnArray(arr); // it should give an error here since I am trying to
        // assign an array of 10 to an array of 5
        testarray = ar.getAnArray();
        for (int i = 0; i < arr.length; i++)
            System.out.println(testarray[i]);
    }
}


问:
How to configure a conditional type based on value of a property?
I have a number of Item objects and a method that processes them. The issue is that some Items could potentially have certain properties that others don't.

type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint' | 'ApiGatewayMethod';

export default interface Item {
    ref?: string;
    position: Position;
    type: ItemType;
    children?: Item[];
}

function process(item: Item) {...}
```

<p>Now, let's say I want to create a separate interface <code>ApiGatewayMethodItem</code> (that extends <code>Item</code>) that has an additional string property called 'method' representing whether it's a GET or POST or something else. Is there a way I can type it in such a way that as soon as I type <code>process({type: 'ApiGatewayMethod'})</code> tsc will start complaining about the missing property <code>method</code> ? I understand that TS has a pretty good support for the "conditional types", but I haven't used them before and I'm having a hard time wrapping my head around them...</p>

<p>So let's say I have the interface </p>

```interface ApiGatewayMethodItem extends Omit<Item, 'type'> {
    type: 'ApiGatewayMethod';
    method: string;
}
```

now when I call the process function, I need the compiler to complain that the method property is missing when I don't specify it, but specify the type ApiGatewayMethod

答:
You can make Item a union type, and define an interface which holds the properties which are common to all items:

export default interface CommonItemProperties {
    ref?: string;
    position: Position;
    children?: Item[];
}

interface ApiGatewayMethodItem extends CommonItemProperties {
    type: 'ApiGatewayMethod';
    method: 'GET' | 'POST';
}

interface ApiGatewayEndpointItem extends CommonItemProperties {
  type: 'ApiGatewayEndpoint';
  path: string;
}

type Item = ApiGatewayEndpointItem | ApiGatewayMethodItem;

function process(item: Item) {
  switch (item.type) {
    case ('ApiGatewayMethod'):
      return item.method; // this is not a type error - typescript 'knows' the item is a ApiGatewayMethodItem
    case ('ApiGatewayEndpoint'):
      return item.path;   // this is not a type error - typescript 'knows' the item is a ApiGatewayEndpointItem
  }
}
```

The switch statement is just an example of how typescript can determine the type of item you've passed in based on a check against type.

Body:
I have a number of Item objects and a method that processes them. The issue is that some Items could potentially have certain properties that others don't.

type ItemType = 'ApiGateway' | 'ApiGatewayEndpoint' | 'ApiGatewayMethod';

export default interface Item {
    ref?: string;
    position: Position;
    type: ItemType;
    children?: Item[];
}

function process(item: Item) {...}

Now, let's say I want to create a separate interface ApiGatewayMethodItem (that extends Item) that has an additional string property called 'method' representing whether it's a GET or POST or something else. Is there a way I can type it in such a way that as soon as I type process({type: 'ApiGatewayMethod'}) tsc will start complaining about the missing property method ? I understand that TS has a pretty good support for the "conditional types", but I haven't used them before and I'm having a hard time wrapping my head around them...

So let's say I have the interface

interface ApiGatewayMethodItem extends Omit<Item, 'type'> {
    type: 'ApiGatewayMethod';
    method: string;
}

now when I call the process function, I need the compiler to complain that the method property is missing when I don't specify it, but specify the type ApiGatewayMethod

Body:
You can make Item a union type, and define an interface which holds the properties which are common to all items:

export default interface CommonItemProperties {
    ref?: string;
    position: Position;
    children?: Item[];
}

interface ApiGatewayMethodItem extends CommonItemProperties {
    type: 'ApiGatewayMethod';
    method: 'GET' | 'POST';
}

interface ApiGatewayEndpointItem extends CommonItemProperties {
  type: 'ApiGatewayEndpoint';
  path: string;
}

type Item = ApiGatewayEndpointItem | ApiGatewayMethodItem;

function process(item: Item) {
  switch (item.type) {
    case ('ApiGatewayMethod'):
      return item.method; // this is not a type error - typescript 'knows' the item is a ApiGatewayMethodItem
    case ('ApiGatewayEndpoint'):
      return item.path;   // this is not a type error - typescript 'knows' the item is a ApiGatewayEndpointItem
  }
}

The switch statement is just an example of how typescript can determine the type of item you've passed in based on a check against type.


问:
infinite loop with array.push() in Angular
I have a small problem and I don't understand why...

The situation : I have a array of all the reservation for the day. I would like, if I click on a button "evening", have only the reservation for the evening.

The getEvening() function is called in parent component when I click on a button.

In my child component.html, I have :

```<code><tbody *ngFor="let resa of resas">
        <tr class="addred" (click)='setResa(resa)'>
            <td *ngIf="!size">{{ resa.confirmResa }}</td>
            <td>{{ resa.arrivee.split(' ')[1] }}</td>
            <td>{{ resa.nom_client }}</td>
            <td *ngIf="!size">{{ resa.nbre_client }}</td>
            <td *ngIf="!size">{{ resa.num_phone_client }}</td>
            <td *ngIf="!size">{{ resa.num_table }}</td>
            <td *ngIf="!size">{{ resa.formule }}</td>
            <td *ngIf="!size" (click)="stopEvent($event)" (mouseover)=setResaId(resa)>

                <input class="venu" type="checkbox" clrToggle (change)="came($event)" [checked]="resa.venu === 1" />
            </td>
        </tr>
    </tbody>
</code>```

In my child component.ts, I have :

```<code>export class ReservationTabComponent implements OnInit {

  @Input() date: Subject<string>;

  @Output() resa = new EventEmitter<any>();

  addred: boolean;
  resas: any[] = [];
  resaId: string;

  dateDay: string;
  hour: number;

  scrHeight: number;
  scrWidth: number;

  size: boolean;
  bool: boolean;

  venu: number;

  constructor(
    private datastore: DatastoreService,
    private resaService: ReservationService
  ) { }

  ngOnInit(): void {
    this.getScreenSize();
    this.date.subscribe((date) => {
      this.dateDay = date;
      this.setDate(this.dateDay);
    });
    this.addred = false;
  }

  setDate(date: string) {
    this.datastore.findResaOfTheDay(date)
      .subscribe(
        (resas) => {
          this.resas = resas.data.original;
          console.log(this.resas);
        });
  }

  getAll() {

    this.setDate(this.dateDay);
  }

  getMidi() {
    this.resas = [];
  }

  getEvening() {
    for (let resa of this.resas) {

      this.hour = parseInt(moment().format(resa.arrivee.split(' ')[1]), 10);
      if (this.hour > 13) {
        this.resas.push(resa);  <-- this causing infinite loop...
        console.log(resa);  <-- this works correctly
      }
    }
  }
}
</code>```

Actually, when I click on the button, I have a infinte loop with push() method but not with console.log() method...

I don't understand why...

答:
You're pushing more elements to the very same list you're iterating, hence every time you push an element, you'll iterate over it, and push it again and repeat forever.

Let's say you match for B:

```<code> v
[A,B,C]

   v
[A,B,C] push B

     v
[A,B,C,B]

       v
[A,B,C,B] push B

         v
[A,B,C,B,B] push B

           v
[A,B,C,B,B,B] push B
</code>```

You may want to use two different arrays :)

Body:
I have a small problem and I don't understand why...

The situation : I have a array of all the reservation for the day. I would like, if I click on a button "evening", have only the reservation for the evening.

The getEvening() function is called in parent component when I click on a button.

In my child component.html, I have :

            {{ resa.confirmResa }}
            {{ resa.arrivee.split(' ')[1] }}
            {{ resa.nom_client }}
            {{ resa.nbre_client }}
            {{ resa.num_phone_client }}
            {{ resa.num_table }}
            {{ resa.formule }}

                <input class="venu" type="checkbox" clrToggle (change)="came($event)" [checked]="resa.venu === 1" />

In my child component.ts, I have :

export class ReservationTabComponent implements OnInit {

  @Input() date: Subject<string>;

  @Output() resa = new EventEmitter<any>();

  addred: boolean;
  resas: any[] = [];
  resaId: string;

  dateDay: string;
  hour: number;

  scrHeight: number;
  scrWidth: number;

  size: boolean;
  bool: boolean;

  venu: number;

  constructor(
    private datastore: DatastoreService,
    private resaService: ReservationService
  ) { }

  ngOnInit(): void {
    this.getScreenSize();
    this.date.subscribe((date) => {
      this.dateDay = date;
      this.setDate(this.dateDay);
    });
    this.addred = false;
  }

  setDate(date: string) {
    this.datastore.findResaOfTheDay(date)
      .subscribe(
        (resas) => {
          this.resas = resas.data.original;
          console.log(this.resas);
        });
  }

  getAll() {

    this.setDate(this.dateDay);
  }

  getMidi() {
    this.resas = [];
  }

  getEvening() {
    for (let resa of this.resas) {

      this.hour = parseInt(moment().format(resa.arrivee.split(' ')[1]), 10);
      if (this.hour > 13) {
        this.resas.push(resa);  <-- this causing infinite loop...
        console.log(resa);  <-- this works correctly
      }
    }
  }
}

Actually, when I click on the button, I have a infinte loop with push() method but not with console.log() method...

I don't understand why...

Body:
You're pushing more elements to the very same list you're iterating, hence every time you push an element, you'll iterate over it, and push it again and repeat forever.

Let's say you match for B:

 v
[A,B,C]

   v
[A,B,C] push B

     v
[A,B,C,B]

       v
[A,B,C,B] push B

         v
[A,B,C,B,B] push B

           v
[A,B,C,B,B,B] push B

You may want to use two different arrays :)


问:
How to convert "#00E4FF" to Brush in code?
I need to convert some color ( in Hex ) to Brush.
I need to do it in the code. </p>

<p>How can i do it ? </p>

答:
```<code>public static SolidColorBrush GetColorFromHexa(string hexaColor)
{
    return new SolidColorBrush(Color.FromArgb(
            Convert.ToByte(hexaColor.Substring(1, 2), 16),
            Convert.ToByte(hexaColor.Substring(3, 2), 16),
            Convert.ToByte(hexaColor.Substring(5, 2), 16),
            Convert.ToByte(hexaColor.Substring(7, 2), 16)
        )
    );
}
</code>```

Hope this helps

Body:
I need to convert some color ( in Hex ) to Brush.
I need to do it in the code.

How can i do it ?

Body:
public static SolidColorBrush GetColorFromHexa(string hexaColor)
{
    return new SolidColorBrush(Color.FromArgb(
            Convert.ToByte(hexaColor.Substring(1, 2), 16),
            Convert.ToByte(hexaColor.Substring(3, 2), 16),
            Convert.ToByte(hexaColor.Substring(5, 2), 16),
            Convert.ToByte(hexaColor.Substring(7, 2), 16)
        )
    );
}

Hope this helps


答:
You have 2 ways. If the string is created by you you can use:

```<code>    int age = 50;
    String s = String.format("My age is %d, and your age is under 30.", age);
</code>```

Otherwise I suggest something like a regex to pick the numbers and rewrite the string. For instance:

```<code>class Scratch {
static Pattern pattern = Pattern.compile("\\d+");

public static void main(String[] args) {
    String string = "My age is 50, and your age is under 30.";
    Matcher matcher = pattern.matcher(string);

    if (matcher.find()) {
        String theAge = matcher.group(0);
    }
  }
}
</code>```

Title: How to add numbers for a string sentence in Java?

Body:
I want to add numbers using Java.

For example, the sentence is given String: "My age is 50, and your age is under 30." If I want to add 5 to the sentence, it should be like
"My age is 55, and your age is under 35."

The restriction is the sentence is given, so you need to extract numbers from the sentence and add the numbers to the original sentence.

I was trying to split by space (" ") and try to add numbers after that.
But I don't know how to substitute numbers with the original sentence.

I am confused since it has comma when I am trying to split by " " and even if you can extract all the numbers from the sentence, I am not sure how can I get back to numbers to string.

public class Main {

public static Pattern pattern = Pattern.compile("\\d+");

public static String addNumber(String str, int n) {

    Matcher matcher = pattern.matcher(str);
    if (matcher.find()) {
        String theAge = matcher.group(0);
        int newAge = Integer.parseInt(theAge) + n;
    }

    String addSentence = str;

    return addSentence;
}

public static void main(String[] args) {
    String testString = "My age is 50, and your age is under 30.";
    String testString2 = "My age is 50, and your age is under 30 and my friend age is 44.";

    String newSent = addNumber(testString, 5);
    // -> should be "My age is 55, and your age is under 35.
    String newSent2 = addNumber(testString2, 10);
    // -> should be "My age is 60, and your age is under 40 and my friend age is 54.";

}

}
enter code here

Body:
You have 2 ways. If the string is created by you you can use:

    int age = 50;
    String s = String.format("My age is %d, and your age is under 30.", age);

Otherwise I suggest something like a regex to pick the numbers and rewrite the string. For instance:

class Scratch {
static Pattern pattern = Pattern.compile("\\d+");

public static void main(String[] args) {
    String string = "My age is 50, and your age is under 30.";
    Matcher matcher = pattern.matcher(string);

    if (matcher.find()) {
        String theAge = matcher.group(0);
    }
  }
}


问:
How do I make an object change color when it hits another object?
I'm making a screen saver in swift, and the screen saver has a paddle, and a ball, like pong. I am trying to make it so that when the ball hits the paddle, both the paddle and the ball change to a random color. How would I accomplish this?

It is curently set to fill in white.

```<code> private func drawBall() {
    let ballRect = NSRect(x: ballPosition.x - ballRadius,
                          y: ballPosition.y - ballRadius,
                          width: ballRadius * 2,
                          height: ballRadius * 2)
    let ball = NSBezierPath(roundedRect: ballRect,
                            xRadius: ballRadius,
                            yRadius: ballRadius)
    NSColor.white.setFill()
    ball.fill()
}

private func drawPaddle() {
    let paddleRect = NSRect(x: paddlePosition - paddleSize.width / 2,
                            y: paddleBottomOffset - paddleSize.height / 2,
                            width: paddleSize.width,
                            height: paddleSize.height)
    let paddle = NSBezierPath(rect: paddleRect)
    NSColor.white.setFill()
    paddle.fill()
}
</code>```

答:
it seems to me that you want a Collision detector.
I suggest use iOS UIDynamic instead of implementing your own physics engine.

specifically this class UICollisionBehavior.

Body:
I'm making a screen saver in swift, and the screen saver has a paddle, and a ball, like pong. I am trying to make it so that when the ball hits the paddle, both the paddle and the ball change to a random color. How would I accomplish this?

It is curently set to fill in white.

 private func drawBall() {
    let ballRect = NSRect(x: ballPosition.x - ballRadius,
                          y: ballPosition.y - ballRadius,
                          width: ballRadius * 2,
                          height: ballRadius * 2)
    let ball = NSBezierPath(roundedRect: ballRect,
                            xRadius: ballRadius,
                            yRadius: ballRadius)
    NSColor.white.setFill()
    ball.fill()
}

private func drawPaddle() {
    let paddleRect = NSRect(x: paddlePosition - paddleSize.width / 2,
                            y: paddleBottomOffset - paddleSize.height / 2,
                            width: paddleSize.width,
                            height: paddleSize.height)
    let paddle = NSBezierPath(rect: paddleRect)
    NSColor.white.setFill()
    paddle.fill()
}


问:
R problem, JSON objects in csv file, one per cell:
```<code>{"received":1588687345,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687345,"sensor":[{"type":"temp","unit":"degc","value":20}]}}
{"received":1588687346,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687344,"sensor":[{"type":"temp","unit":"degc","value":22}]}}
{"received":1588687346,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687346,"sensor":[{"type":"temp","unit":"degc","value":22}]}}
{"received":1588687348,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687347,"sensor":[{"type":"temp","unit":"degc","value":28}]}}
{"received":1588687349,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687347,"sensor":[{"type":"temp","unit":"degc","value":-667}]}}
</code>```

all the data are in the first column of the csv file. I would like to convert to readable format such as dataframe, and save with write.csv()? Thanks for your help

答:
library(jsonlite)

df <- read.csv("example.csv", header = FALSE)

jsonlite::stream_in(textConnection(gsub("\\n", "", df)))
```

Body:
{"received":1588687345,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687345,"sensor":[{"type":"temp","unit":"degc","value":20}]}}
{"received":1588687346,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687344,"sensor":[{"type":"temp","unit":"degc","value":22}]}}
{"received":1588687346,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687346,"sensor":[{"type":"temp","unit":"degc","value":22}]}}
{"received":1588687348,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687347,"sensor":[{"type":"temp","unit":"degc","value":28}]}}
{"received":1588687349,"guid":"0CA2F400004","eventtype":"sensor","payload":{"time":1588687347,"sensor":[{"type":"temp","unit":"degc","value":-667}]}}

all the data are in the first column of the csv file. I would like to convert to readable format such as dataframe, and save with write.csv()? Thanks for your help


问:
Getting script error in YouTube Python download script
When I try to download the playlist with the youtube-dl Python script I get this error.

no fmt_url_map or conn information found in video info

Error no fmt_url_map or conn information found in video info with specific video explains the problem and solution, but I don't know how can I apply the solution.

What do I need to do?

答:
It works perfectly fine with videos:

```<code>$ git clone https://github.com/rg3/youtube-dl.git
$ ./youtube-dl  http://www.youtube.com/watch?v=VHkPiU9YAQk
</code>```

Then you can play the video "VHkPiU9YAQk.mp4"

Also with playlists:

```<code>$ ./youtube-dl --playlist-start=1 --playlist-end=1 http://www.youtube.com/my_playlists?p=AA0F3A8E116E1219
</code>```

Check the parameters you are using.

Body:
It works perfectly fine with videos:

$ git clone https://github.com/rg3/youtube-dl.git
$ ./youtube-dl  http://www.youtube.com/watch?v=VHkPiU9YAQk

Then you can play the video "VHkPiU9YAQk.mp4"

Also with playlists:

$ ./youtube-dl --playlist-start=1 --playlist-end=1 http://www.youtube.com/my_playlists?p=AA0F3A8E116E1219

Check the parameters you are using.


问:
Ansible apt module to execute with sudo
I'm trying to get ansible to execute sudo apt-get update. I already have the sudoers setup to run without a password and it works if I login as the user ansible is using and execute sudo apt-get update. If I use the following ansible playbook

```<code>---
  - name: updates
    hosts: pis
    tasks:
      - name: Update APT
        become: true
        apt:
          update_cache: yes
</code>```

It will give me the following error

```<code>fatal: [127.0.0.1]: FAILED! => {"changed": false, "module_stderr": "Shared connection to 127.0.0.1 closed.\r\n", "module_stdout": "sudo: a password is required\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}
</code>```

but the following playbook works fine

```<code>---
  - name: updates
    hosts: pis
    tasks:
      - name: Update APT
        command: sudo apt-get update
</code>```

答:
When using become: yes the connection will try to spawn shell as root (as you haven't specified become_user).

It seems you have access to run sudo apt-get update without password, i.e:

/etc/sudodoers may contain something similar to this:

ansible ALL=(ALL) NOPASSWD: /bin/apt-get update

To replicate the issue, login as user ansible and issue a command sudo -i

If you're using a dedicated user (ansible ?) for all ansible connectivity, you might want to give that user access to all commands via sudo without password. Read Here this is however not the best practice, you are always better off giving access to specific commands for security reasons

Add the following line to /etc/sudoers file using visudo /etc/sudoers

ansible ALL=(ALL) NOPASSWD:ALL

If you opt for this, I would also advise to use a key-pair authentication for this privileged account rather than password authentication. More info

Title: Ansible apt module to execute with sudo

Body:
I'm trying to get ansible to execute sudo apt-get update. I already have the sudoers setup to run without a password and it works if I login as the user ansible is using and execute sudo apt-get update. If I use the following ansible playbook

---
  - name: updates
    hosts: pis
    tasks:
      - name: Update APT
        become: true
        apt:
          update_cache: yes

It will give me the following error

fatal: [127.0.0.1]: FAILED! => {"changed": false, "module_stderr": "Shared connection to 127.0.0.1 closed.\r\n", "module_stdout": "sudo: a password is required\r\n", "msg": "MODULE FAILURE\nSee stdout/stderr for the exact error", "rc": 1}

but the following playbook works fine

---
  - name: updates
    hosts: pis
    tasks:
      - name: Update APT
        command: sudo apt-get update


问:
I got an error when I run my codes in R Studio
Here are the codes that I use

```<code>library(quantmod)
library(timetk)
library(dplyr)
library(tibble)
library(tidyr)

mdate <- "2015-10-30"
edate <- "2016-01-05"

tickers <- c("ABG","ACH","ADM","AEG","AEM","AGQ","AGRO","AKOb","APO")

data <- do.call(cbind.data.frame, lapply(tickers, function(x)
  getSymbols(x, from = mdate, to = edate, auto.assign = F)))

# Transpose data.frame:
td_data <- within(data.frame(price_var = row.names(t(data)), t(data), row.names = NULL),
                  {
                    ticker_cd <- as.factor(gsub("[.].*", "", price_var))
                    price_var <- as.factor(gsub(".*[.]", "", price_var))
                  }
)
# Reshape:
abc <- do.call("cbind", split(td_data, td_data$price_var))
</code>```

When I run these I got:

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 44, 38
In addition: Warning message:
AKOb contains missing values. Some functions will not work if objects contain missing values in the middle of the series. Consider using na.omit(), na.approx(), na.fill(), etc to remove or replace them.

I found that this error was caused by "AKOB". The data from first and sixth days are blank, so the first day of "AKOB" stars on Nov 9th 2015 which is different than other stock data. The way I found was to run one by one and compared their differences. It is very inefficient way whenever it happens.

I want to skip if a stock has no data in my setting (from start date to end date)
How can I do to do this?

答:
```<code>library(quantmod)

mdate <- "2015-10-30"
edate <- "2016-01-05"

tickers <- c("ABG","ACH","ADM","AEG","AEM","AGQ","AGRO","AKOb","APO", "JJE")

# Iterate through the tickers and retrieve data from Yahoo Finance defensively: data => xts
data <- do.call("cbind", lapply(seq_along(tickers), function(i){
        try_var <- try(getSymbols(tickers[i], from = mdate, to = edate, auto.assign = FALSE))
        if(inherits(try_var, "try-error")) {
          i <- i + 1
        } else{
          getSymbols(tickers[i], from = mdate, to = edate, auto.assign = FALSE)
        }
      }
    )
  )

# Transpose data.frame: td_data => data.frame
td_data <- within(data.frame(price_var = row.names(t(data)), t(data), row.names = NULL),
                  {
                    ticker_cd <- as.factor(gsub("[.].*", "", price_var))
                    price_var <- as.factor(gsub(".*[.]", "", price_var))
                  }
                )

# Re-order vectors; keep complete cases: td_data_o => data.frame
td_data_o <- td_data[complete.cases(td_data),
                     c(names(td_data)[sapply(td_data, is.factor)],
                       names(td_data)[sapply(td_data, function(x){!is.factor(x)})])]

# Reshape: abc => data.frame
abc <- do.call("cbind", split(td_data_o, td_data_o$price_var))
</code>```

Body:
Here are the codes that I use

library(quantmod)
library(timetk)
library(dplyr)
library(tibble)
library(tidyr)

mdate <- "2015-10-30"
edate <- "2016-01-05"

tickers <- c("ABG","ACH","ADM","AEG","AEM","AGQ","AGRO","AKOb","APO")

data <- do.call(cbind.data.frame, lapply(tickers, function(x)
  getSymbols(x, from = mdate, to = edate, auto.assign = F)))

# Transpose data.frame:
td_data <- within(data.frame(price_var = row.names(t(data)), t(data), row.names = NULL),
                  {
                    ticker_cd <- as.factor(gsub("[.].*", "", price_var))
                    price_var <- as.factor(gsub(".*[.]", "", price_var))
                  }
)
# Reshape:
abc <- do.call("cbind", split(td_data, td_data$price_var))

When I run these I got:

Error in data.frame(..., check.names = FALSE) :
  arguments imply differing number of rows: 44, 38
In addition: Warning message:
AKOb contains missing values. Some functions will not work if objects contain missing values in the middle of the series. Consider using na.omit(), na.approx(), na.fill(), etc to remove or replace them.

I found that this error was caused by "AKOB". The data from first and sixth days are blank, so the first day of "AKOB" stars on Nov 9th 2015 which is different than other stock data. The way I found was to run one by one and compared their differences. It is very inefficient way whenever it happens.

I want to skip if a stock has no data in my setting (from start date to end date)
How can I do to do this?


问:
iOS 13 safaridriver can not create safari session
tl;dr: safaridriver very often not able to connect to mobileSafari on real iOS 13 device. mobileSafari seems to be in kind of suspended mode after webdriver connection has been closed. Only solution, to make further connects, is manually killing mobileSafari via iOS app switcher.

edit: The issue can be reproduced only on iPads. The problem does not seem to exist on iPhones.

I am trying to run selenium tests, directly on an iOS device, using the the new iOS 13 webdriver possibilities.
It seems to work as described in https://webkit.org/blog/9395/webdriver-is-coming-to-safari-in-ios-13/ but when trying to run a 2nd test session, safaridriver doesnt seem to be able to connect do mobileSafari on the device.
This seems to happen, if the 2nd session is not immediately started after the 1st one - mobileSafari seems to be suspended and safaridriver can not handle this situation.

Use Postman, connecting to a running safaridriver -p 5500 server.
Make a localhost:5500/session request with raw body:

```<code>{
    "capabilities": {
        "alwaysMatch": {
            "browserName": "Safari",
            "platformName": "iOS"
        }
    }
}
</code>```

After several retries this will result in:

```<code>{
    "value": {
        "error": "session not created",
        "message": "Could not create a session: The session timed out while connecting to a Safari instance.",
        "stacktrace": ""
    }
}
</code>```

It is not possible to get around this issue. Only solution is to manually kill mobileSafari via App Switcher.

Perhaps anyone has an idea, how this could be fixed. Would be thankful, since this is a real showstopper for running continuous automatic running tests.

答:
I had the exact same problem when trying to start a session on a real iPad device.

After digging into the safaridriver manual with man safaridriver, I found out that setting safari:deviceType in the capabilities exists, so I tried it and it works:

```<code>POST /session

{
    "capabilities": {
        "firstMatch": [
            {
                "safari:deviceType": "iPad", // <- add this
                "platformName": "ios",
                "browserName": "Safari"
            }
        ]
    }
}
</code>```

Additional footnotes:

I used firstMatch, but alwaysMatch is expected to work too.

safaridriver will evaluate the values without case sensitivity

Tested with Safari 13.1's safaridriver and Safari Technology Preview 107's safaridriver. Works on both, though STP's error messages are more helpful.

Also, you will need to switch on "Safari > Advanced > Web Inspector" on the iPad (this only appears after the iPad is connected to a MacOs machine) to start the session.

Body:
tl;dr: safaridriver very often not able to connect to mobileSafari on real iOS 13 device. mobileSafari seems to be in kind of suspended mode after webdriver connection has been closed. Only solution, to make further connects, is manually killing mobileSafari via iOS app switcher.

edit: The issue can be reproduced only on iPads. The problem does not seem to exist on iPhones.

I am trying to run selenium tests, directly on an iOS device, using the the new iOS 13 webdriver possibilities.
It seems to work as described in https://webkit.org/blog/9395/webdriver-is-coming-to-safari-in-ios-13/ but when trying to run a 2nd test session, safaridriver doesnt seem to be able to connect do mobileSafari on the device.
This seems to happen, if the 2nd session is not immediately started after the 1st one - mobileSafari seems to be suspended and safaridriver can not handle this situation.

Use Postman, connecting to a running safaridriver -p 5500 server.
Make a localhost:5500/session request with raw body:

{
    "capabilities": {
        "alwaysMatch": {
            "browserName": "Safari",
            "platformName": "iOS"
        }
    }
}

After several retries this will result in:

{
    "value": {
        "error": "session not created",
        "message": "Could not create a session: The session timed out while connecting to a Safari instance.",
        "stacktrace": ""
    }
}

It is not possible to get around this issue. Only solution is to manually kill mobileSafari via App Switcher.

Perhaps anyone has an idea, how this could be fixed. Would be thankful, since this is a real showstopper for running continuous automatic running tests.

Body:
I had the exact same problem when trying to start a session on a real iPad device.

After digging into the safaridriver manual with man safaridriver, I found out that setting safari:deviceType in the capabilities exists, so I tried it and it works:

POST /session

{
    "capabilities": {
        "firstMatch": [
            {
                "safari:deviceType": "iPad", // <- add this
                "platformName": "ios",
                "browserName": "Safari"
            }
        ]
    }
}

Additional footnotes:

I used firstMatch, but alwaysMatch is expected to work too.

safaridriver will evaluate the values without case sensitivity

Tested with Safari 13.1's safaridriver and Safari Technology Preview 107's safaridriver. Works on both, though STP's error messages are more helpful.

Also, you will need to switch on "Safari > Advanced > Web Inspector" on the iPad (this only appears after the iPad is connected to a MacOs machine) to start the session.