问:
Is it possible to point DateTimeOffset custom format for object's property?
Is it possible to point DateTimeOffset custom format for object's property? This object will be serialized/deserialized (JSON) in ASP.NET controller's action.

I thought it can be done through attribute, like `[Required], but I didn't find it.

```<code>public abstract class EventDto
{
    public EventDto(EventTypes eventType)
    {
        EventType = eventType;
    }

    [Required]
    public EventTypes EventType { get; }

    [Required]
    public Guid SessionId { get; set; }

    [Required]
    // Something like this: [JsonFormat("YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz")]
    public DateTimeOffset Timestamp { get; set; }
}
</code>```

答:
Try something like this</p>
```<code>       public class Test
        {
            public DateTime date { get; set; }
            public string Timestamp
            {
                get { return date.ToString("YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz");}
                set { date = DateTime.ParseExact(value, "YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz", System.Globalization.CultureInfo.InvariantCulture)}
            }
        }
</code>```

Body:
Is it possible to point DateTimeOffset custom format for object's property? This object will be serialized/deserialized (JSON) in ASP.NET controller's action.

I thought it can be done through attribute, like `[Required], but I didn't find it.

public abstract class EventDto
{
    public EventDto(EventTypes eventType)
    {
        EventType = eventType;
    }

    [Required]
    public EventTypes EventType { get; }

    [Required]
    public Guid SessionId { get; set; }

    [Required]
    // Something like this: [JsonFormat("YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz")]
    public DateTimeOffset Timestamp { get; set; }
}

Body:
Try something like this

       public class Test
        {
            public DateTime date { get; set; }
            public string Timestamp
            {
                get { return date.ToString("YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz");}
                set { date = DateTime.ParseExact(value, "YYYY-mm-DD HH:MM:SS.FFFFFFFF zzz", System.Globalization.CultureInfo.InvariantCulture)}
            }
        }


来源: stackexchange

问:
Why do I get a segmentation fault when calling a virtual method in this code?
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

```<code>#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}
</code>```

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

答:
There are few problems here. The first thing is your base class destructor has to be virtual. Otherwise your base class destructor will always be called even if it points to derived object. Second is you should not assign derived class object to base class object.  This is called object slicing.
So, assignment should be done through pointer or reference.  </p>

<p>The segmentation problem is happening because it contains garbage value. You need to initialize it in the constructor. </p>

OwnerDisplayName: Srikanth

ContentLicense: CC BY-SA 2.5

Body:
I'm still learning C++; I was trying out how polymorphism works and I got a segmentation fault when calling a virtual method.

(Note: I didn't mark the destructor as virtual, I was just trying out to see what happens.) Here's the code:

#include <iostream>

using namespace std;

class Base
{
protected:
  char *name;

public:
  Base(char *name)
  {
    cout << name << ": Base class cons" << endl;
  }

  ~Base()
  {
    cout << name << ": Base class des" << endl;
  }

  virtual void disp();
};

void Base::disp()
{
  cout << name << ": Base disp()" << endl;
}

class Child : public Base
{
public:
  Child(char *name):
    Base(name)
  {
    cout << name << ": Child class cons" << endl;
  }

  ~Child()
  {
    cout << name << ": Child class des" << endl;
  }

  virtual void disp()
  {
    cout << name << ": Child disp()" << endl;
  }
};

int main()
{
  //Base b;
  //b.disp();
  Base c = Child("2");
  c.disp();
}

Also, if you've any other tips regarding the usage of inheritance and polymorphism in general for someone who knows these concepts in Java, please let me know. Thank you!

Body:
There are few problems here. The first thing is your base class destructor has to be virtual. Otherwise your base class destructor will always be called even if it points to derived object. Second is you should not assign derived class object to base class object.  This is called object slicing.
So, assignment should be done through pointer or reference.

The segmentation problem is happening because it contains garbage value. You need to initialize it in the constructor.

OwnerDisplayName: chappar


问:
What are the advantages of proc functions to methods
I was solving some problems on Project Euler and I mentioned that I always wrap short methods in proc functions. I asked myself "Why?". The answer was "I don't know. Maybe because it is short?".

So what are the advantages of proc functions to ordinary methods except that they are short :)

```<code># Proc
is_prime = proc{|number| !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})}

# Ordinary method
def is_prime(number)
  !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})
end
</code>```

答:
Being able to pass them around and to store them in data structures is something that immediately comes to mind. I used the latter case not too long in a small command line parser: parse user input with a regex and call commands[command] with the rest of the parsed string as arguments. Sure, you could do the same with methods and send, but IMHO the commands hash is nicer. Another thing I sometimes use — even though it's not really common in Ruby — is to curry procs, which you can't really do with a method:

```<code>>> multiplier = proc { |x, y| x * y }
=> #<Proc:0x00000100a158f0@(irb):1>
>> times_two = multiplier.curry[2]
=> #<Proc:0x00000100a089c0>
>> times_two[5]
=> 10
</code>```

EDIT: Here's another example (simplified, no error handling):

```<code> commands = { :double => proc { |x| x * 2 }, :half => proc { |x| x / 2 } }
 run_command = proc do
     command, arg = STDIN.gets.split
     commands[command.intern][arg.to_i]
 end
 run_command.call
 half 10
 # => 5
 run_command[]
 double 5
 # => 10
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I was solving some problems on Project Euler and I mentioned that I always wrap short methods in proc functions. I asked myself "Why?". The answer was "I don't know. Maybe because it is short?".

So what are the advantages of proc functions to ordinary methods except that they are short :)

# Proc
is_prime = proc{|number| !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})}

# Ordinary method
def is_prime(number)
  !((number%2 == 0) || (3..Math.sqrt(number).to_i).step(2).any?{|n| (number%n).zero?})
end

Body:
Being able to pass them around and to store them in data structures is something that immediately comes to mind. I used the latter case not too long in a small command line parser: parse user input with a regex and call commands[command] with the rest of the parsed string as arguments. Sure, you could do the same with methods and send, but IMHO the commands hash is nicer. Another thing I sometimes use — even though it's not really common in Ruby — is to curry procs, which you can't really do with a method:

>> multiplier = proc { |x, y| x * y }
=> #<Proc:0x00000100a158f0@(irb):1>
>> times_two = multiplier.curry[2]
=> #<Proc:0x00000100a089c0>
>> times_two[5]
=> 10

EDIT: Here's another example (simplified, no error handling):

 commands = { :double => proc { |x| x * 2 }, :half => proc { |x| x / 2 } }
 run_command = proc do
     command, arg = STDIN.gets.split
     commands[command.intern][arg.to_i]
 end
 run_command.call
 half 10
 # => 5
 run_command[]
 double 5
 # => 10


问:
HTTP status code for an expired confirmation code
I have an endpoint in my REST API that sends a code the user received per email to verify the email address.

What status code should I better use to return that this code has expired?

Is it 401, 410 or 498?

答:
I would recommend using status code 498 if you wanna show the user that their authorization code is invalid

or use 410 to show that the link is invalid

Edit: Note that 498 is an unofficial status code

ContentLicense: CC BY-SA 4.0


问:
filter object from array and select field
I've got a list of objects with name value pairs in them and I can't figure out how to retrieve a value from an array where name is a certain value.

For instance:

```<code>    {
            "ordernumber" : "192915",
            "orderparameters" : {
                    "list" : [
                            {
                                    "composite" : null,
                                    "name" : "CURRENCY_CODE",
                                    "value" : "NOK",
                                    "type" : "String"
                            },
                            {
                                    "composite" : null,
                                    "name" : "NEED_CUSTOMS_DOCUMENT",
                                    "value" : "True",
                                    "type" : "Boolean"
                            }
              ]}
    }
</code>```

Now I need to find the value of the item with

"name": "NEED_CUSTOMS_DOCUMENT"

so in this case

"value": "True"

I can list all the values with

```<code> db.orders.aggregate({ $match: { ordernumber:'1234' } }, { $project: { 'orderparameters.list.name': 1 } }).pretty()
</code>```

But then how to retrieve the value field from the index with that name?

The index could be different on every document so I cant simply query "orderparameters.list.1.value"

答:
There is an operator especially made for this

$elemMatch

The $elemMatch operator matches documents that contain an array field
with at least one element that matches all the specified query
criteria.

```<code>db.orders.aggregate({ $match: { 'orderparameters.list': { $elemMatch: { name: "NEED_CUSTOMS_DOCUMENT", value: "True" } } } })

db.orders.find({ 'orderparameters.list': { $elemMatch: { name: "NEED_CUSTOMS_DOCUMENT", value: "True" } } })
</code>```

Body:
I've got a list of objects with name value pairs in them and I can't figure out how to retrieve a value from an array where name is a certain value.

For instance:

    {
            "ordernumber" : "192915",
            "orderparameters" : {
                    "list" : [
                            {
                                    "composite" : null,
                                    "name" : "CURRENCY_CODE",
                                    "value" : "NOK",
                                    "type" : "String"
                            },
                            {
                                    "composite" : null,
                                    "name" : "NEED_CUSTOMS_DOCUMENT",
                                    "value" : "True",
                                    "type" : "Boolean"
                            }
              ]}
    }

Now I need to find the value of the item with

"name": "NEED_CUSTOMS_DOCUMENT"

so in this case

"value": "True"

I can list all the values with

 db.orders.aggregate({ $match: { ordernumber:'1234' } }, { $project: { 'orderparameters.list.name': 1 } }).pretty()

But then how to retrieve the value field from the index with that name?

The index could be different on every document so I cant simply query "orderparameters.list.1.value"

Body:
There is an operator especially made for this

$elemMatch

The $elemMatch operator matches documents that contain an array field
with at least one element that matches all the specified query
criteria.

db.orders.aggregate({ $match: { 'orderparameters.list': { $elemMatch: { name: "NEED_CUSTOMS_DOCUMENT", value: "True" } } } })

db.orders.find({ 'orderparameters.list': { $elemMatch: { name: "NEED_CUSTOMS_DOCUMENT", value: "True" } } })


问:
Pandas dataframe groupby text value that occurs in two columns
My dataframe looks like this:

     v1           v2        distance
0   be          belong      0.666667
4   increase    decrease    0.666667
9   analyze     assay       0.666667
11  bespeak     circulate   0.769231
21  induce      generate    0.800000
24  decrease    delay       0.750000
26  cause       trip        0.666667
27  isolate     distinguish 0.750000
28  give        infect      0.666667
29  result      prove       0.800000
31  describe    explain     0.714286
33  report      circulate   0.666667
36  affect      expose      0.666667
40  explain     intercede   0.705882
41  suppress    restrict    0.833333
```

With v1 and v2 being verbs and distance is their similarity. I want to create clusters of similar words, based on their appearance in the dataframe.

For example, the word circulate appears be similar with both bespeak and report. So I would like to have a cluster of these 3 words. Groupby doesn't help since they are string values. Can someone help?

答:
The following line would select only the rows containing the string target_string:

```<code>rows = df[df.applymap(lambda element: element ==  target_string).any(axis = 1)]
</code>```

Concatenate them and find the unique elements:

```<code>cluster = pd.concat([rows[['v1', 'v2']]], axis = 1).unique()
</code>```

If you want to find clusters with all the words, repeat this for all the unique elements. An inefficient example:

```<code>clusters = pd.DataFrame()
for target_string in df.v1.unique():
    rows = df[df.applymap(lambda element: element ==  target_string).any(axis = 1)]
    clusters.append(pd.concat([rows[['v1', 'v2']]], axis = 1).unique())
</code>```

Body:
My dataframe looks like this:

     v1           v2        distance
0   be          belong      0.666667
4   increase    decrease    0.666667
9   analyze     assay       0.666667
11  bespeak     circulate   0.769231
21  induce      generate    0.800000
24  decrease    delay       0.750000
26  cause       trip        0.666667
27  isolate     distinguish 0.750000
28  give        infect      0.666667
29  result      prove       0.800000
31  describe    explain     0.714286
33  report      circulate   0.666667
36  affect      expose      0.666667
40  explain     intercede   0.705882
41  suppress    restrict    0.833333

With v1 and v2 being verbs and distance is their similarity. I want to create clusters of similar words, based on their appearance in the dataframe.

For example, the word circulate appears be similar with both bespeak and report. So I would like to have a cluster of these 3 words. Groupby doesn't help since they are string values. Can someone help?

Body:
The following line would select only the rows containing the string target_string:

rows = df[df.applymap(lambda element: element ==  target_string).any(axis = 1)]

Concatenate them and find the unique elements:

cluster = pd.concat([rows[['v1', 'v2']]], axis = 1).unique()

If you want to find clusters with all the words, repeat this for all the unique elements. An inefficient example:

clusters = pd.DataFrame()
for target_string in df.v1.unique():
    rows = df[df.applymap(lambda element: element ==  target_string).any(axis = 1)]
    clusters.append(pd.concat([rows[['v1', 'v2']]], axis = 1).unique())


问:
Why is Pandas insistent on storing times as Pandas Timestamps?
I have some code which is using datetime.datetime format throughout. I have data in X.csv:

```<code>EventDatetime  |  RunnerNumber
"20220203 1024"|  42
"20220203 1331"|  69
  ...          |  ...
</code>```

which I have read into a pd.dataframe, with EventDatetime as datetime.datetime format:

```<code>dfX = pd.read_csv("X.csv", header=0,
                  converters={"EventDatetime" : (lambda x: datetime.strptime(x, "%Y%m%d %H%M%S")}
                 )
</code>```

(For reference, datetime.strptime("20220203 1024", "%Y%m%d %H%M%S") returns a datetime.datetime object).

Unfortunately, Pandas seems to convert this format into its native Timestamp format, which makes indexing very annoying.

```<code>dfX.index = dfX["EventDatetime"]
type(dfX.index.iloc[1])  # returns:  pandas._libs.tslibs.timestamps.Timestamp
dfX.loc[[datetime.datetime(2022,02,03,10,24), datetime.datetime(2022,02,03,13,31)]]
</code>```

should return a dataframe with two lines, but rather throws an error because Pandas has converted the datetime.datetime object into timestamp.

Sadly it seems, Pandas has not kept to the Unix mantra of ``do one thing, and do it well''. I can find ways around this problem (various SO posts have been helpful). But what I want to know is, Why does Pandas coerce these datetimes into timestamps? Is it a bug, or a design feature which I have yet to appreciate?

答:
This is not really an answer to the title of your question. But I can index the dateframe with datetime.datetime object with the following code

```<code>import datetime
dfX = pd.DataFrame(
    {'EventDatetime': ['20220203 1024', '20220203 1331'],
     'RunnerNumber': ['42', '69']}
)
dfX['EventDatetime'] = pd.to_datetime(dfX['EventDatetime'], format='%Y%m%d %H%M')
dfX.index = dfX['EventDatetime']
dfX.loc[[datetime.datetime(2022,2,3,10,24), datetime.datetime(2022,2,3,13,31)]]
</code>```

Output:

```<code>    RunnerNumber
EventDatetime
2022-02-03 10:24:00 42
2022-02-03 13:31:00 69
</code>```

I think the key difference is that I used pd.to_datetime for the conversion but I don't know the reason behind that difference.

Body:
I have some code which is using datetime.datetime format throughout. I have data in X.csv:

EventDatetime  |  RunnerNumber
"20220203 1024"|  42
"20220203 1331"|  69
  ...          |  ...

which I have read into a pd.dataframe, with EventDatetime as datetime.datetime format:

dfX = pd.read_csv("X.csv", header=0,
                  converters={"EventDatetime" : (lambda x: datetime.strptime(x, "%Y%m%d %H%M%S")}
                 )

(For reference, datetime.strptime("20220203 1024", "%Y%m%d %H%M%S") returns a datetime.datetime object).

Unfortunately, Pandas seems to convert this format into its native Timestamp format, which makes indexing very annoying.

dfX.index = dfX["EventDatetime"]
type(dfX.index.iloc[1])  # returns:  pandas._libs.tslibs.timestamps.Timestamp
dfX.loc[[datetime.datetime(2022,02,03,10,24), datetime.datetime(2022,02,03,13,31)]]

should return a dataframe with two lines, but rather throws an error because Pandas has converted the datetime.datetime object into timestamp.

Sadly it seems, Pandas has not kept to the Unix mantra of ``do one thing, and do it well''. I can find ways around this problem (various SO posts have been helpful). But what I want to know is, Why does Pandas coerce these datetimes into timestamps? Is it a bug, or a design feature which I have yet to appreciate?

Body:
This is not really an answer to the title of your question. But I can index the dateframe with datetime.datetime object with the following code

import datetime
dfX = pd.DataFrame(
    {'EventDatetime': ['20220203 1024', '20220203 1331'],
     'RunnerNumber': ['42', '69']}
)
dfX['EventDatetime'] = pd.to_datetime(dfX['EventDatetime'], format='%Y%m%d %H%M')
dfX.index = dfX['EventDatetime']
dfX.loc[[datetime.datetime(2022,2,3,10,24), datetime.datetime(2022,2,3,13,31)]]

Output:

    RunnerNumber
EventDatetime
2022-02-03 10:24:00 42
2022-02-03 13:31:00 69

I think the key difference is that I used pd.to_datetime for the conversion but I don't know the reason behind that difference.


问:
Updating a PriorityQueue when iterating it
I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):

```<code>for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        e.setData(newData);
    }
}
</code>```

I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:

```<code>for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        mEntries.remove(e);
        mEntries.add(newEntry);
     }
}
</code>```

The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.

(This post is similar, but there priorities can change, which is not my case)

Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?

Thanks,
Rippel

PS: Some implementation details...

```<code>PriorityQueue<Entry> mEntries = new PriorityQueue<Entry>(1, Entry.EntryComparator());
</code>```

with:

```<code>public static class EntryComparator implements Comparator<Entry> {
    public int compare(Entry my, Entry their) {
        if (my.mPriority < their.mPriority) {
            return 1;
        }
        else if (my.mPriority > their.mPriority) {
            return -1;
        }
        return 0;
    }
}
</code>```

答:
What's wrong in your code was already explained -- implementing iterator, which can consistently iterate through collection with intersected modification is rather hard task to do. You need to specify how to deal with removed items (will it be seen through iterator?), added items, modified items... Even if you can do it consistently it will be rather complex and unefficient implementation -- and, mostly, not very usefull, since use case "iterate without modifications" is much more common. So, java architects choose to deny modification while iterate, and most collections from Java collection API follow this, and throw ConcurrentModificationException if such modification detected.

As for your code -- for me, your just should not make items immutable. Immutability is great thing, but it should not be overused. If Entry object you use here is some kind of domain object, and you really want them to be immutable -- you can just create some kind of temporary data holder (MutableEntry) object, use it inside your algorithm, and copy data to Entry before return. From my point of view it will be best solution.

Body:
I need to update some fixed-priority elements in a PriorityQueue based on their ID. I think it's quite a common scenario, here's an example snippet (Android 2.2):

for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        e.setData(newData);
    }
}

I've then made Entry "immutable" (no setter methods) so that a new Entry instance is created and returned by setData(). I modified my method into this:

for (Entry e : mEntries) {
    if (e.getId().equals(someId)) {
        Entry newEntry = e.setData(newData);
        mEntries.remove(e);
        mEntries.add(newEntry);
     }
}

The code seems to work fine, but someone pointed out that modifying a queue while iterating over it is a bad idea: it may throw a ConcurrentModificationException and I'd need to add the elements I want to remove to an ArrayList and remove it later. He didn't explain why, and it looks quite an overhead to me, but I couldn't find any specific explanation on internet.

(This post is similar, but there priorities can change, which is not my case)

Can anyone clarify what's wrong with my code, how should I change it and - most of all - why?

Thanks,
Rippel

PS: Some implementation details...

PriorityQueue<Entry> mEntries = new PriorityQueue<Entry>(1, Entry.EntryComparator());

with:

public static class EntryComparator implements Comparator<Entry> {
    public int compare(Entry my, Entry their) {
        if (my.mPriority < their.mPriority) {
            return 1;
        }
        else if (my.mPriority > their.mPriority) {
            return -1;
        }
        return 0;
    }
}


问:
Tailscale - how to integrate with express.js app?
I want to create a middleware for my express.js app that will reject requests not coming from a machine that's not connected to my Tailscale network.

How can I do that? Do I need to grab the request ip and then verify it somehow against Tailscale?

答:
On Linux Tailscale installs an iptables rule that 100.64.0.0/10 can only ingress via tailscale0. You can make the app check the source IP against 100.64.0.0/10 as the simplest solution.

There is Go code in https://github.com/tailscale/tailscale/tree/main/tsnet which provides more extensive information, like the User who is connecting. Eventually we'd expect there to be supported APIs which would be easier to get to from JavaScript, but for right now if you're willing to write a bit of Go scaffolding you might be able to run a binary from thge JavaScript to get the information you're looking for.


问:
android firestore adds up date on top of duplicate data

As you can see in the image, whenever I try to update(not replace) a field with a new value, it duplicates the data, and adds up on top of the duplicate. What is causing this issue?

Whenever a user posts, I need to add the post id to an existing array of post ids.

hierarchy:

users - collection - document(emblem(String), photo(String), postIds(String[])...)

```<code>mDb = FirebaseFirestore.getInstance();

        // remove old ids
        Map<String, Object> oldIds = new HashMap<>();
        oldIds.put("posts", _oldPostList);

        // add new ids
        Map<String, Object> newIds = new HashMap<>();
        _oldPostList.add(_newValue);
        newIds.put("posts", _oldPostList);

        String docId = FirebaseAuth.getInstance().getCurrentUser().getEmail();

        DocumentReference docRef = mDb.collection("users").document(docId);

        docRef.update("posts", FieldValue.arrayRemove(oldIds)).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void unused) {
                docRef.update("posts", FieldValue.arrayUnion(newIds)).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        sendBroadcast(_context, _action, true, null);
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        sendBroadcast(_context, _action, false, null);
                    }
                });
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                sendBroadcast(_context, _action, false, null);
            }
        });
</code>```

答:
I assume the structure you want is a list of posts, not a list of maps of lists of posts. If that is the case, the problem is that you are supplying the "posts" key twice - once in the update call and again in the data (Map) you pass. Instead of putting the post list into a map and passing the map like this

// Don't do this - creates a list of maps, not a list of posts
Map<String, Object> oldIds = new HashMap<>();
oldIds.put("posts", _oldPostList);
docRef.update("posts", FieldValue.arrayRemove(oldIds));
```
<p>you should just pass the list directly, since the update call already defines the "posts" key.</p>
<p>If you just want to add a new post to the list, you don't need to remove the old list first either. You can just use <code>arrayUnion</code> to add the new post to the existing list like this:</p>
<pre class="lang-java prettyprint-override"><code>docRef.update("posts", FieldValue.arrayUnion(_newValue));
</code>```

Take a look at the Firestore docs for some more examples too.

Body:
As you can see in the image, whenever I try to update(not replace) a field with a new value, it duplicates the data, and adds up on top of the duplicate. What is causing this issue?

Whenever a user posts, I need to add the post id to an existing array of post ids.

hierarchy:

users - collection - document(emblem(String), photo(String), postIds(String[])...)

mDb = FirebaseFirestore.getInstance();

        // remove old ids
        Map<String, Object> oldIds = new HashMap<>();
        oldIds.put("posts", _oldPostList);

        // add new ids
        Map<String, Object> newIds = new HashMap<>();
        _oldPostList.add(_newValue);
        newIds.put("posts", _oldPostList);

        String docId = FirebaseAuth.getInstance().getCurrentUser().getEmail();

        DocumentReference docRef = mDb.collection("users").document(docId);

        docRef.update("posts", FieldValue.arrayRemove(oldIds)).addOnSuccessListener(new OnSuccessListener<Void>() {
            @Override
            public void onSuccess(Void unused) {
                docRef.update("posts", FieldValue.arrayUnion(newIds)).addOnSuccessListener(new OnSuccessListener<Void>() {
                    @Override
                    public void onSuccess(Void unused) {
                        sendBroadcast(_context, _action, true, null);
                    }
                }).addOnFailureListener(new OnFailureListener() {
                    @Override
                    public void onFailure(@NonNull Exception e) {
                        sendBroadcast(_context, _action, false, null);
                    }
                });
            }
        }).addOnFailureListener(new OnFailureListener() {
            @Override
            public void onFailure(@NonNull Exception e) {
                sendBroadcast(_context, _action, false, null);
            }
        });

Body:
I assume the structure you want is a list of posts, not a list of maps of lists of posts. If that is the case, the problem is that you are supplying the "posts" key twice - once in the update call and again in the data (Map) you pass. Instead of putting the post list into a map and passing the map like this

// Don't do this - creates a list of maps, not a list of posts
Map<String, Object> oldIds = new HashMap<>();
oldIds.put("posts", _oldPostList);
docRef.update("posts", FieldValue.arrayRemove(oldIds));

you should just pass the list directly, since the update call already defines the "posts" key.

If you just want to add a new post to the list, you don't need to remove the old list first either. You can just use arrayUnion to add the new post to the existing list like this:

docRef.update("posts", FieldValue.arrayUnion(_newValue));

Take a look at the Firestore docs for some more examples too.


问:
Unity3D get an Object in start Method
Hey im trying to get an object which is referenced in another script (dictionary).
But when i try to get the object in the start method it seems like the dictionary isnt populated jet.
Error: NullReferenceException: Object reference not set to an instance of an object

If I run this line of code in the update method it works completely fine.

Is there an easy way to let this line run after the dictionary is populated?

Grid Manager Script

Camera Movement Script

答: Populate the dictionary in Awake() method instead of Start(), then it would be ready by the time you need it in Start() of another script.</p>

Title: Unity3D get an Object in start Method


问:
Android SQLite query to prevent returning duplicate.
I have a database as follows:

_ID  : SUBJECT : Topic :  LectureNumber

```<code>1 : WMCC   : RF       :     1
2 : WMCC   : Fading   :     2
3 : CCN    : IP       :     1
4 : CCN    : MAC      :     2
5 : WMCC   : Planning :     3
</code>```

I have to place the queries in a List using SimpleCursorAdaptor such that

1)at first all subjects are placed in the List only once(No duplicates), i.e. the List displays only WMCC and CCN

2)when I click on a Subject Name, a new list is displayed containing all Lectures on that subject. e.g. If I click WMCC a new list is displayed containing all lectures on WMCC.

I am actually facing the problem in achieving the first task i.e PLACING SUBJECT NAMES IN A LIST USING SimpleCursorAdaptor only once.

Thanks.

答:
Typically, in a "normalized" relational database, you would have a separate SUBJECTS table.  What you have shown above is not a "database" but a "denormalized table".

You could get the unique set of subjects from your denormalized table (let's call it LECTURES) so:

```<code>       select DISTINCT subject from LECTURES
</code>```

The query to get the set of lectures for a given subject:

```<code>      select * from LECTURES where subject =  'the-subject-chosen-from-your-GUI-list'
</code>```

Body:
I have a database as follows:

_ID  : SUBJECT : Topic :  LectureNumber

1 : WMCC   : RF       :     1
2 : WMCC   : Fading   :     2
3 : CCN    : IP       :     1
4 : CCN    : MAC      :     2
5 : WMCC   : Planning :     3

I have to place the queries in a List using SimpleCursorAdaptor such that

1)at first all subjects are placed in the List only once(No duplicates), i.e. the List displays only WMCC and CCN

2)when I click on a Subject Name, a new list is displayed containing all Lectures on that subject. e.g. If I click WMCC a new list is displayed containing all lectures on WMCC.

I am actually facing the problem in achieving the first task i.e PLACING SUBJECT NAMES IN A LIST USING SimpleCursorAdaptor only once.

Thanks.

Body:
Typically, in a "normalized" relational database, you would have a separate SUBJECTS table.  What you have shown above is not a "database" but a "denormalized table".

You could get the unique set of subjects from your denormalized table (let's call it LECTURES) so:

       select DISTINCT subject from LECTURES

The query to get the set of lectures for a given subject:

      select * from LECTURES where subject =  'the-subject-chosen-from-your-GUI-list'


问:
best way to replace an eval( "new object()" )
I m looking for the best way to replace eval( "new object();" )

The ugly source :

```<code>    //var type = window.$(droppedDomNode).data("shape");
    var type = "sankey.shape.Start";

    var figure = eval("new "+type+"();");

    // create a command for the undo/redo support
    var command = new draw2d.command.CommandAdd(this, figure, x, y);
</code>```

The eval create a new sankey.shape.Start object.

I'm looking for best solution to replace this kind of code.

Thanks

答:
You can split it and walk up the path from window if it is global

var foo = {
  bar: {
    world: 'baz',
  }
}

const getIt = (str, start = window) => {
  return str.split(/\./).reduce((o, k) => o[k], start);
}

const x = "foo.bar.world";
console.log(getIt(x))```

Body:
I m looking for the best way to replace eval( "new object();" )

The ugly source :

    //var type = window.$(droppedDomNode).data("shape");
    var type = "sankey.shape.Start";

    var figure = eval("new "+type+"();");

    // create a command for the undo/redo support
    var command = new draw2d.command.CommandAdd(this, figure, x, y);

The eval create a new sankey.shape.Start object.

I'm looking for best solution to replace this kind of code.

Thanks


问:
Anyone can tale me why my Original list updating when I Update in copied list?
This code give me --> [[0, 0, 0, 0], [0, 0, 0, 0], [0, 0, 0, 0]]♂ that means the code still updating the original list e.i: matrix2

matrix2 = [[0, 1, 2, 0], [3, 4, 5, 2], [1, 3, 1, 5]]

def changedItto_zero(col, row, column, arr):
    matrix_copy = arr[:] # --> copy list using slice , but it still updating ♂ the original list
    matrixLen_row = len(arr)
    matrixLen_col = len(arr[0])
    for row_index in range(0, matrixLen_row):
        for column_index in range(0, matrixLen_col):
            matrix_copy[row][column_index] = 0
            matrix_copy[row_index][column] = 0
    return matrix_copy

def change(arr):
    global col
    matrixLen_row = len(arr)
    matrixLen_col = len(arr[0])
    for row_index in range(0, matrixLen_row):
        for column_index in range(0, matrixLen_col):
            if(arr[row_index][column_index] == 0):
                find_row, find_column = row_index, column_index
                print('row ', find_row, ' col ', find_column)
               #  print('matx ', arr)
                col += 1
                finded = changedItto_zero(col, find_row, find_column, arr)
    return finded

print(change(matrix2))

# Right Output:[[0,0,0,0],[0,4,5,0],[0,3,1,0]]

```

答:
Just like someone commented, the problem is that arr[:] creates a copy of the arr list but not a copy of its contents. You can confirm this by printing id(matrix_copy) and id(arr) right after creating the copy, which should display different values, meaning different lists. But if you do the same with the first element of each list (id(matrix_copy[0]) and id(arr[0])) you'll see that they are the same list. A simple solution to this problem is creating a deep copy explicitly:

```<code>matrix_copy = copy.deepcopy(arr)  # You should import copy to use this function
</code>```

Body:
Just like someone commented, the problem is that arr[:] creates a copy of the arr list but not a copy of its contents. You can confirm this by printing id(matrix_copy) and id(arr) right after creating the copy, which should display different values, meaning different lists. But if you do the same with the first element of each list (id(matrix_copy[0]) and id(arr[0])) you'll see that they are the same list. A simple solution to this problem is creating a deep copy explicitly:

matrix_copy = copy.deepcopy(arr)  # You should import copy to use this function


问:
Unable to get OpenSearch dashboard by running OpenSearch docker compose
I am a windows user. I installed Windows Subsystem for Linux [wsl2] and then installed docker using it. Then I tried to get started with OpenSearch so I followed the documentation in the given link
https://opensearch.org/downloads.html and run docker-compose up, In the shell, I am getting an error message like

opensearch-dashboards  | {"type":"log","@timestamp":"2022-01-18T16:31:18Z","tags":["error","opensearch","data"],"pid":1,"message":"[ConnectionError]: getaddrinfo EAI_AGAIN opensearch-node1 opensearch-node1:9200"}

In the port http://localhost:5601/ I am getting messages like

OpenSearch Dashboards server is not ready yet

I also changed resources preference for memory to 5GB in docker-desktop but it still doesn't work. Can somebody help me with this?

答:
I had the same error message when opening "http://localhost:5601/" while testing opensearch and opensearch dasboard locally using Docker in Windows 10:

OpenSearch Dashboards server is not ready yet

opensearch-dashboards |
{"type":"log","@timestamp":"2022-02-10T12:29:35Z","tags":["error","opensearch","data"],"pid":1,"message":"[ConnectionError]:
getaddrinfo EAI_AGAIN opensearch-node1 opensearch-node1:9200"}

But when looking into the log I also found this other error:

opensearch-node1 | [1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

The 3 part solution working for me was:

Part 1

On each opensearch nodes update the file:

```<code>/usr/share/opensearch/config/opensearch.yml
</code>```

And add line:

```<code>plugins.security.disabled: true
</code>```

Before the security plugins:

```<code>cks. "Single-node" mode disables them again.
#discovery.type: single-node

plugins.security.disabled: true

######## Start OpenSearch Security Demo Configuration ########
# WARNING: revise all the lines below before you go into production
plugins.security.ssl.transport.pemcert_filepath: esnode.pem
</code>```

I found the information on opensearch official documentation

Part 2

Setting allocated memory for docker desktop to 4GB into .wslconfig more information here:
opendistrocommunity discussion
stackoverflow aloocate memory

Make sure your allocated memory is well set up (you have to restart docker desktop) with this command: docker info and check the line "Total Memory" it should be set to 4GB (approximately, in my case it has be set to 3.84GiB)

Part 3

And also increase vm.max_map_count:

open powershell

wsl -d docker-desktop

echo "vm.max_map_count = 262144" > /etc/sysctl.d/99-docker-desktop.conf

The info was founded here on github discussion

Body:
I had the same error message when opening "http://localhost:5601/" while testing opensearch and opensearch dasboard locally using Docker in Windows 10:

OpenSearch Dashboards server is not ready yet

opensearch-dashboards |
{"type":"log","@timestamp":"2022-02-10T12:29:35Z","tags":["error","opensearch","data"],"pid":1,"message":"[ConnectionError]:
getaddrinfo EAI_AGAIN opensearch-node1 opensearch-node1:9200"}

But when looking into the log I also found this other error:

opensearch-node1 | [1]: max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144]

The 3 part solution working for me was:

Part 1

On each opensearch nodes update the file:

/usr/share/opensearch/config/opensearch.yml

And add line:

plugins.security.disabled: true

Before the security plugins:

cks. "Single-node" mode disables them again.
#discovery.type: single-node

plugins.security.disabled: true

######## Start OpenSearch Security Demo Configuration ########
# WARNING: revise all the lines below before you go into production
plugins.security.ssl.transport.pemcert_filepath: esnode.pem

I found the information on opensearch official documentation

Part 2

Setting allocated memory for docker desktop to 4GB into .wslconfig more information here:
opendistrocommunity discussion
stackoverflow aloocate memory

Make sure your allocated memory is well set up (you have to restart docker desktop) with this command: docker info and check the line "Total Memory" it should be set to 4GB (approximately, in my case it has be set to 3.84GiB)

Part 3

And also increase vm.max_map_count:

open powershell

wsl -d docker-desktop

echo "vm.max_map_count = 262144" > /etc/sysctl.d/99-docker-desktop.conf

The info was founded here on github discussion


问:
Log4j Vulnerability in 3rd party applications like apache zookeeper
Apache log4j zookeeper uses log4j 1.2 which is vulnerable to RCE.
To rectify this issue we planned to exclude log4j 1.2 and include log4j 2.17.1 core and log4j 2.17.1 api  in the dependency

It doesnt help. Can somebody please suggest how to exclude jars from third party libraries

Error:
Getting this errror :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/jmx/HierarchyDynamicMBean
at org.apache.zookeeper.jmx.ManagedUtil.registerLog4jMBeans(ManagedUtil.java:50)
at org.apache.zookeeper.server.ZooKeeperServerMain.initializeAndRun(ZooKeeperServerMain.java:91)
at org.apache.zookeeper.server.ZooKeeperServerMain.main(ZooKeeperServerMain.java:61)
at org.apache.zookeeper.server.quorum.QuorumPeerMain.initializeAndRun(QuorumPeerMain.java:125)
at org.apache.zookeeper.server.quorum.QuorumPeerMain.main(QuorumPeerMain.java:79)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.jmx.HierarchyDynamicMBean
at java.net.URLClassLoader.findClass(URLClassLoader.

We tried this ..

```<code><dependencies>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.5.1-alpha</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-1.2-api</artifactId>
            <version>2.17.1</version>
        </dependency>
    </dependencies>
</code>```

答:
I believe I figured it out but I haven't tested this for long enough.

Considering this was applied to a v3.6.1 Zookeeper server, a summary of what needs to be done is:

Delete old log4j libraries from Zookeeper

log4j-1.2.17.jar

log4j-1.2.17.LICENSE.txt (That's obviously not necessary)

Add recent log4j libraries that has the fix for the log4shell vulerability.

A log4j2 bridge that is backward compatible with log4j1.x: log4j-1.2-api-2.17.1.jar

Necessary log4j libraries: log4j-api-2.17.1.jar & log4j-core-2.17.1.jar

Modify Zookeeper's server environment options file (i.e. /zookeeper/conf/server_jvm.properties) by adding the following lines

-Dlog4j.configuration=/incorta/IncortaAnalytics/IncortaNode/zookeeper/conf/log4j.properties (A pointer for log4j2 to the existing log4j1.x configuration file, see the reference below for more details)

-Dzookeeper.jmx.log4j.disable=true (Disable Zookeeper's JMX dependency on log4j1.x. Thanks to Piotr for that tip he mentioned for this question)

What this does is that it keeps the sl4j libraries shipped with Zookeeper because changing those to a version that is log4j2 compatible wasn't a pleasant experience for me.

And instead, I upgraded log4j1.x libraries to log4j2 while having the log4j bridge library too to enable Zookeeper's outdated slf4j libraries to use the recent log4j2 ones.

Reference

Update: Using JDK 11, we faced a weird error where our Zookeeper client couldn't connect to Zookeeper, and the solution was to remove the slf4j-log4j12 binder from our classpath.

Body:
Apache log4j zookeeper uses log4j 1.2 which is vulnerable to RCE.
To rectify this issue we planned to exclude log4j 1.2 and include log4j 2.17.1 core and log4j 2.17.1 api  in the dependency

It doesnt help. Can somebody please suggest how to exclude jars from third party libraries

Error:
Getting this errror :
Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/log4j/jmx/HierarchyDynamicMBean
at org.apache.zookeeper.jmx.ManagedUtil.registerLog4jMBeans(ManagedUtil.java:50)
at org.apache.zookeeper.server.ZooKeeperServerMain.initializeAndRun(ZooKeeperServerMain.java:91)
at org.apache.zookeeper.server.ZooKeeperServerMain.main(ZooKeeperServerMain.java:61)
at org.apache.zookeeper.server.quorum.QuorumPeerMain.initializeAndRun(QuorumPeerMain.java:125)
at org.apache.zookeeper.server.quorum.QuorumPeerMain.main(QuorumPeerMain.java:79)
Caused by: java.lang.ClassNotFoundException: org.apache.log4j.jmx.HierarchyDynamicMBean
at java.net.URLClassLoader.findClass(URLClassLoader.

We tried this ..

<dependencies>
        <dependency>
            <groupId>org.apache.zookeeper</groupId>
            <artifactId>zookeeper</artifactId>
            <version>3.5.1-alpha</version>
            <exclusions>
                <exclusion>
                    <groupId>log4j</groupId>
                    <artifactId>log4j</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-core</artifactId>
            <version>2.17.1</version>
        </dependency>
        <dependency>
            <groupId>org.apache.logging.log4j</groupId>
            <artifactId>log4j-1.2-api</artifactId>
            <version>2.17.1</version>
        </dependency>
    </dependencies>


问:
How to load CF7 CSS & JS only when form is on the page
I want to speed up my site. I want to load Contact form 7 css & js only when form is one the page. I found solutions for this but they are not 100% for me. Why? Because they are based on which page I am. I want to make it another way. I'm using gutenberg to create my site and I don't know where the form will be. I could be on Contact page, on main page or on subpage in future. So my idea is load css & js only when the form is in page. Any page. So is it any way to do it? I was thinking about simple ACF Checkbox to do it. When user want to put CF7 shortcode/form he need to click checkbox for example Website have form. Maybe there's more elegant way?

答:
I cannot get the script in the previous answer to work.

However the following works:

```<code>function contactform7_dequeue_scripts() {
    $check_cf7 = false;

    if( is_page('contact') ) {
        $check_cf7 = true;
    }

    if( !$check_cf7 ) {
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
        wp_dequeue_script( 'cf7-conditional-fields' );
        wp_dequeue_style( 'cf7-conditional-fields' );
    }
}
add_action( 'wp_enqueue_scripts', 'contactform7_dequeue_scripts', 77 );
</code>```

Body:
I cannot get the script in the previous answer to work.

However the following works:

function contactform7_dequeue_scripts() {
    $check_cf7 = false;

    if( is_page('contact') ) {
        $check_cf7 = true;
    }

    if( !$check_cf7 ) {
        wp_dequeue_script( 'contact-form-7' );
        wp_dequeue_style( 'contact-form-7' );
        wp_dequeue_script( 'cf7-conditional-fields' );
        wp_dequeue_style( 'cf7-conditional-fields' );
    }
}
add_action( 'wp_enqueue_scripts', 'contactform7_dequeue_scripts', 77 );


问:
Update Text() based on user input in a TextFormField() within a form, perform a calculation and display results in another TextFormField()
I'm still new in Flutter, I'm trying to Update Text() based on user input in a TextFormField() within a form, perform two calculations and display results in other TextFormField() then POST the data to an API on pressing the Upload Button. I have tried using setState(){} as below but it's not working out.
'serviceFee' is supposed to be 2% of the 'amount' entered by the user then 'takeHome' is supposed to be 'amount' minus 'serviceFee'. Below is my code...

```<code>import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:keilvog/Screens/6kg_cylinder_screen.dart';
import 'package:keilvog/Widget/edit_image.dart';
import 'package:keilvog/Widget/header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:http/http.dart' as http;
import 'package:keilvog/Widget/validators.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SellDetails extends StatefulWidget {
  const SellDetails({Key? key}) : super(key: key);

  @override
  State<SellDetails> createState() => _SellDetailsState();
}

class _SellDetailsState extends State<SellDetails> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final brandController = TextEditingController();
  final capacityController = TextEditingController();
  final amountController = TextEditingController();
  final serviceFeeController = TextEditingController();
  final takeHomeController = TextEditingController();
  File? image;

  bool isLoading = false;
  double _serviceFee = 0;
  // ignore: unused_field
  double _takeHome = 0;
  double amount = 0;

  Future UploadData({
    String? brand,
    String? capacity,
    double? amount,
    double? serviceFee,
    double? takeHome,
    File? image
  }) async
  {
    final SharedPreferences preferences = await SharedPreferences.getInstance();
    final String? myJWT = preferences.getString('jwt');
    Map<String, dynamic> token = jsonDecode(myJWT!);
    final myResponse = await http.post(
    Uri.parse('https://kelivog.com/sell/cylinder'),
    headers: <String, String>{
                'Content-Type': 'application/json; charset=UTF-8',
                'X-Requested-With': 'XMLHttpRequest',
                'Authorization': '$token',
                },

    body: jsonEncode(
      {
        'brand': brand,
        'capacity': capacity,
        'amount': amount,
        'serviceFee': serviceFee,
        'takeHome': takeHome,
        'image':'data:image/png;base64,' + base64Encode(image!.readAsBytesSync()),
      }),

    );
    return myResponse.statusCode;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage("images/background.jpg"), fit: BoxFit.cover)),
      child: Scaffold(
        // body: SingleChildScrollView(
        body: SingleChildScrollView(
          child: Column(
            children: [
              header(),
              SizedBox(height: 20.h),
              const EditImage(),
              SizedBox(height: 30.h),
              Container(
                width: 350.w,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(15.r)),
                  image: const DecorationImage(
                    image: AssetImage("images/background.jpg"),
                    fit: BoxFit.fitWidth,
                    alignment: Alignment.topCenter,
                  ),
                  boxShadow: const [
                    BoxShadow(color: Colors.grey, spreadRadius: 2),
                  ],
                ),
                child: Column(
                  children: [
                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("BRAND",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                child: TextFormField(
                                  //textAlignVertical: TextAlignVertical.center,
                                  validator: brandValidator,
                                  controller: brandController,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    //const Divider(indent: 15, endIndent: 15, thickness: 2),

                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("CAPACITY",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                child: TextFormField(
                                  validator: capacityValidator,
                                  controller: capacityController,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("AMOUNT",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                child: TextFormField(
                                  validator: amountValidator,
                                  controller: amountController,
                                  keyboardType: TextInputType.number,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                  onChanged: (value) {
                                    setState(() {
                                      amount = value as double;
                                    });
                                  },
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("SERVICE FEE",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                //child: Text(serviceFeeController.text),
                                child: TextFormField(
                                  onChanged: (value) => setState(() {
                                    _serviceFee = value as double;
                                  }),
                                  // validator: ,
                                  // controller: ,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("TAKE HOME",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                //child: Text(serviceFeeController.text),
                                child: TextFormField(
                                  onChanged: (value) => setState(() {
                                    _takeHome = value as double;
                                  }),
                                  // validator: ,
                                  // controller: ,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    // rowItem('BRAND'),
                    // rowItem('CAPACITY'),
                    // rowItem('AMOUNT'),
                    // rowItem('SERVICE FEE'),
                    // rowItem('TAKE HOME'),
                  ],
                ),
              ),
              SizedBox(height: 40.h),
              ElevatedButton(
                onPressed: () async {
                  setState(() {
                    _serviceFee = (amount * 0.02);
                  });

                  setState(() {
                    _takeHome = amount - _serviceFee;
                  });
                  //final FormState? form = _formKey.currentState;
                  if (_formKey.currentState!.validate()){
                    if (image != null) {
                      await UploadData(
                        image: image,
                        brand: brandController.text,
                        capacity: capacityController.text,
                        amount: amountController.text as double,
                        serviceFee: serviceFeeController.text as double,
                        takeHome: takeHomeController.text as double
                      );
                    }
                    else
                    {
                      // ignore: avoid_print
                      print('You have not added an image');
                    }
                    if (isLoading) {
                      Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  const SixCylindersListsScreen(
                                    item: '', id: '', title: '',
                                  )));
                    } else {
                      throw Exception('Failed to upload details.');
                    }
                  }
                },
                child: Text(
                  'UPLOAD',
                  style: TextStyle(
                    color: Colors.yellow[600],
                    fontSize: 22.sp,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  elevation: 5,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15.r),
                  ),
                  fixedSize: Size(150.w, 50.h),
                  primary: const Color(0xff261005),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

}

</code>```

答:
Here a quick example</p>
```<code> void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {

  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp>{

  final TextEditingController _controller = TextEditingController();
  double? fees;
  double? takeHome;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Column(
            children: [
          TextFormField(
            decoration: const InputDecoration(
                labelText: 'Type the amount',
              ),
            controller: _controller,
          ),
          const SizedBox(height: 20),
          OutlinedButton(
            child:const Text('OK'),
            onPressed: () => _doTheMath(),
          ),
          const SizedBox(height: 20),
              if(fees != null)
               Text('fee: $fees'),
          const SizedBox(height: 20),
              if(takeHome != null)
               Text('takeHome: $takeHome'),
        ]),
      ),
    );
  }

   _doTheMath(){
     //perform validation then do the math
     double? amount = double.tryParse(_controller.text);
     if(amount != null) {
       setState((){
         final serviceFee = amount * 0.02;
         fees = serviceFee;
         takeHome = amount - serviceFee;
       });
     } else {
       print('Invalid input');
       setState((){
         fees = null;
         takeHome = null;
       });
     }
  }
}
</code>```

Body:
I'm still new in Flutter, I'm trying to Update Text() based on user input in a TextFormField() within a form, perform two calculations and display results in other TextFormField() then POST the data to an API on pressing the Upload Button. I have tried using setState(){} as below but it's not working out.
'serviceFee' is supposed to be 2% of the 'amount' entered by the user then 'takeHome' is supposed to be 'amount' minus 'serviceFee'. Below is my code...

import 'dart:async';
import 'dart:convert';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:keilvog/Screens/6kg_cylinder_screen.dart';
import 'package:keilvog/Widget/edit_image.dart';
import 'package:keilvog/Widget/header.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:http/http.dart' as http;
import 'package:keilvog/Widget/validators.dart';
import 'package:shared_preferences/shared_preferences.dart';

class SellDetails extends StatefulWidget {
  const SellDetails({Key? key}) : super(key: key);

  @override
  State<SellDetails> createState() => _SellDetailsState();
}

class _SellDetailsState extends State<SellDetails> {
  final GlobalKey<FormState> _formKey = GlobalKey<FormState>();

  final brandController = TextEditingController();
  final capacityController = TextEditingController();
  final amountController = TextEditingController();
  final serviceFeeController = TextEditingController();
  final takeHomeController = TextEditingController();
  File? image;

  bool isLoading = false;
  double _serviceFee = 0;
  // ignore: unused_field
  double _takeHome = 0;
  double amount = 0;

  Future UploadData({
    String? brand,
    String? capacity,
    double? amount,
    double? serviceFee,
    double? takeHome,
    File? image
  }) async
  {
    final SharedPreferences preferences = await SharedPreferences.getInstance();
    final String? myJWT = preferences.getString('jwt');
    Map<String, dynamic> token = jsonDecode(myJWT!);
    final myResponse = await http.post(
    Uri.parse('https://kelivog.com/sell/cylinder'),
    headers: <String, String>{
                'Content-Type': 'application/json; charset=UTF-8',
                'X-Requested-With': 'XMLHttpRequest',
                'Authorization': '$token',
                },

    body: jsonEncode(
      {
        'brand': brand,
        'capacity': capacity,
        'amount': amount,
        'serviceFee': serviceFee,
        'takeHome': takeHome,
        'image':'data:image/png;base64,' + base64Encode(image!.readAsBytesSync()),
      }),

    );
    return myResponse.statusCode;
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          image: DecorationImage(
              image: AssetImage("images/background.jpg"), fit: BoxFit.cover)),
      child: Scaffold(
        // body: SingleChildScrollView(
        body: SingleChildScrollView(
          child: Column(
            children: [
              header(),
              SizedBox(height: 20.h),
              const EditImage(),
              SizedBox(height: 30.h),
              Container(
                width: 350.w,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.all(Radius.circular(15.r)),
                  image: const DecorationImage(
                    image: AssetImage("images/background.jpg"),
                    fit: BoxFit.fitWidth,
                    alignment: Alignment.topCenter,
                  ),
                  boxShadow: const [
                    BoxShadow(color: Colors.grey, spreadRadius: 2),
                  ],
                ),
                child: Column(
                  children: [
                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("BRAND",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                child: TextFormField(
                                  //textAlignVertical: TextAlignVertical.center,
                                  validator: brandValidator,
                                  controller: brandController,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    //const Divider(indent: 15, endIndent: 15, thickness: 2),

                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("CAPACITY",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                child: TextFormField(
                                  validator: capacityValidator,
                                  controller: capacityController,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("AMOUNT",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                child: TextFormField(
                                  validator: amountValidator,
                                  controller: amountController,
                                  keyboardType: TextInputType.number,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                  onChanged: (value) {
                                    setState(() {
                                      amount = value as double;
                                    });
                                  },
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("SERVICE FEE",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                //child: Text(serviceFeeController.text),
                                child: TextFormField(
                                  onChanged: (value) => setState(() {
                                    _serviceFee = value as double;
                                  }),
                                  // validator: ,
                                  // controller: ,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),

                    Padding(
                      padding: EdgeInsets.symmetric(
                          vertical: 12.h, horizontal: 16.w),
                      child: Row(
                        children: [
                          Expanded(
                            child: Text("TAKE HOME",
                                style: TextStyle(
                                  fontSize: 18.sp,
                                  fontWeight: FontWeight.bold,
                                )),
                          ),
                          SizedBox(width: 1.w),
                          Expanded(
                            child: Container(
                              width: 90.w,
                              height: 40.h,
                              decoration: BoxDecoration(
                                  color: Colors.yellow[600],
                                  borderRadius: BorderRadius.circular(15)),
                              child: Center(
                                //child: Text(serviceFeeController.text),
                                child: TextFormField(
                                  onChanged: (value) => setState(() {
                                    _takeHome = value as double;
                                  }),
                                  // validator: ,
                                  // controller: ,
                                  showCursor: false,
                                  style: const TextStyle(
                                    fontSize: 20.0,
                                    height: 2.0,
                                    color: Colors.black,
                                  ),
                                  decoration: const InputDecoration(
                                    contentPadding: EdgeInsets.only(
                                        top: 1.0, bottom: 100.0, left: 8.0),
                                    border: OutlineInputBorder(
                                      borderRadius: BorderRadius.all(
                                          Radius.circular(15.0)),
                                    ),
                                  ),
                                ),
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    // rowItem('BRAND'),
                    // rowItem('CAPACITY'),
                    // rowItem('AMOUNT'),
                    // rowItem('SERVICE FEE'),
                    // rowItem('TAKE HOME'),
                  ],
                ),
              ),
              SizedBox(height: 40.h),
              ElevatedButton(
                onPressed: () async {
                  setState(() {
                    _serviceFee = (amount * 0.02);
                  });

                  setState(() {
                    _takeHome = amount - _serviceFee;
                  });
                  //final FormState? form = _formKey.currentState;
                  if (_formKey.currentState!.validate()){
                    if (image != null) {
                      await UploadData(
                        image: image,
                        brand: brandController.text,
                        capacity: capacityController.text,
                        amount: amountController.text as double,
                        serviceFee: serviceFeeController.text as double,
                        takeHome: takeHomeController.text as double
                      );
                    }
                    else
                    {
                      // ignore: avoid_print
                      print('You have not added an image');
                    }
                    if (isLoading) {
                      Navigator.pushReplacement(
                          context,
                          MaterialPageRoute(
                              builder: (context) =>
                                  const SixCylindersListsScreen(
                                    item: '', id: '', title: '',
                                  )));
                    } else {
                      throw Exception('Failed to upload details.');
                    }
                  }
                },
                child: Text(
                  'UPLOAD',
                  style: TextStyle(
                    color: Colors.yellow[600],
                    fontSize: 22.sp,
                    fontWeight: FontWeight.w700,
                  ),
                ),
                style: ElevatedButton.styleFrom(
                  elevation: 5,
                  shape: RoundedRectangleBorder(
                    borderRadius: BorderRadius.circular(15.r),
                  ),
                  fixedSize: Size(150.w, 50.h),
                  primary: const Color(0xff261005),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

}

Body:
Here a quick example

 void main() {
  runApp(const MyApp());
}

class MyApp extends StatefulWidget {

  const MyApp({Key? key}) : super(key: key);

  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp>{

  final TextEditingController _controller = TextEditingController();
  double? fees;
  double? takeHome;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        body: Column(
            children: [
          TextFormField(
            decoration: const InputDecoration(
                labelText: 'Type the amount',
              ),
            controller: _controller,
          ),
          const SizedBox(height: 20),
          OutlinedButton(
            child:const Text('OK'),
            onPressed: () => _doTheMath(),
          ),
          const SizedBox(height: 20),
              if(fees != null)
               Text('fee: $fees'),
          const SizedBox(height: 20),
              if(takeHome != null)
               Text('takeHome: $takeHome'),
        ]),
      ),
    );
  }

   _doTheMath(){
     //perform validation then do the math
     double? amount = double.tryParse(_controller.text);
     if(amount != null) {
       setState((){
         final serviceFee = amount * 0.02;
         fees = serviceFee;
         takeHome = amount - serviceFee;
       });
     } else {
       print('Invalid input');
       setState((){
         fees = null;
         takeHome = null;
       });
     }
  }
}


问:
Jooq enum converter uses the ordinal number. How can I switch to use the enum value number instead?
We have an Enum class with customized values. The values are different from their ordinals intentionally for business purpose which I cannot change.

```<code>enum class Role(val value: Int) {
  EXECUTOR(1),
  MONITOR(3),
  ADMIN(5),

  companion object {
    private val map = Role.values().associateBy(Role::value)
    fun fromInt(role: Int) = map[role]
  }
}
</code>```

We are using JOOQ and postgres. We use the JOOQ default EnumConverter to convert db role integer values to objects.

```<code>ForcedType()
    .withUserType("com.company.enums.Role")
    .withEnumConverter(true)
    .withIncludeExpression("role"),
</code>```

However we noticed a problem -- the database stored the ordinals of the enum, instead of the values. For example we see in the db in roles column, the db value is 1, and the translated Enum is MONITOR, coz MONITOR has an ordinal of 1.

How can we store the values of Enum into db using JOOQ?

Thank you!

答: Ohhh I figured it out! There's Custom Converter https://www.jooq.org/doc/latest/manual/code-generation/custom-data-types/ which is exactly what I need.</p>

Body:
We have an Enum class with customized values. The values are different from their ordinals intentionally for business purpose which I cannot change.

enum class Role(val value: Int) {
  EXECUTOR(1),
  MONITOR(3),
  ADMIN(5),

  companion object {
    private val map = Role.values().associateBy(Role::value)
    fun fromInt(role: Int) = map[role]
  }
}

We are using JOOQ and postgres. We use the JOOQ default EnumConverter to convert db role integer values to objects.

ForcedType()
    .withUserType("com.company.enums.Role")
    .withEnumConverter(true)
    .withIncludeExpression("role"),

However we noticed a problem -- the database stored the ordinals of the enum, instead of the values. For example we see in the db in roles column, the db value is 1, and the translated Enum is MONITOR, coz MONITOR has an ordinal of 1.

How can we store the values of Enum into db using JOOQ?

Thank you!


问:
absolute movement using css3 transitions and translates
I know that when you set a new css translate you need to the pixels you want to move, ex: 50px,60px.
So that is a relative movement to those pixels: http://jsfiddle.net/8CECx/
The div's remain next to each-other

Is there a way to move absolutly? For example you can say "move to 30px 50px" and have 2 elements overlap?

Thanks for the info :)

答:
Ok, I’m adding another answer, since the question changed.

I’m still not sure what you’re trying to achieve. If you just want the 1st div to move and overlap the 2nd, why animate the 2nd as well? Or if you want both to move, just the 1st one more, why give it the same translateX value?

Also, I don’t see why you need transforms at all for this. If you just need translate() and no other transform, chances are absolute or relative positioning probably works for you just as well (and has much better browser support)