问:
Amazon S3, streaming video while still uploading it
I wanted to know if it would be possible to stream video while you are uploading it.

For example I have a 100MB video uploading to s3, the first 50MB are uploaded, so can a client start reproducing the video through cloudfront even tho it's not yet fully uploaded?

Or does S3 first wait for the upload to completely finish, then assemble the video file, and then publish it?

Thanks!

答:
S3 provides read-after-write consistency for PUTS of new objects. The data will not be able to read until the write is complete.

Amazon S3 provides read-after-write consistency for PUTS of new
  objects in your S3 bucket in all regions with one caveat. The caveat
  is that if you make a HEAD or GET request to the key name (to find if
  the object exists) before creating the object, Amazon S3 provides
  eventual consistency for read-after-write.

S3 consistency model


来源: stackexchange

问:
php code, is it slow or wrong?
"multiple annotations found at this line"

i have been using aptana and other IDE before, but never gave me this error, but yesterday i installed zend studio and it was giving following error in all my code where i have assigned and also check if condition at same time.

```<code>code:
line 16: if ($message_array = @unserialize($e->getMessage()))
line 17:    $message = $message_array;
</code>```

on all if condition, where i assigned the value to a variable and also check if the variable is true/false, it gives me error "multiple annotations found at this line"

答:
That is not an actual error. Instead the IDE has found more than one error, warnings or hints at the same code line.

You can look at the Problems tab to see the actual errors and warnings.

ContentLicense: CC BY-SA 2.5

Title: php code, is it slow or wrong?

Body:
"multiple annotations found at this line"

i have been using aptana and other IDE before, but never gave me this error, but yesterday i installed zend studio and it was giving following error in all my code where i have assigned and also check if condition at same time.

code:
line 16: if ($message_array = @unserialize($e->getMessage()))
line 17:    $message = $message_array;

on all if condition, where i assigned the value to a variable and also check if the variable is true/false, it gives me error "multiple annotations found at this line"


问:
CSS for making an image responsive both to width and visible height of the containing element
I need the image to take the entire width of the container unless the resulting height is bigger then the available container's viewport height.

Basically I want the image to be responsive but also that it should still fit the screen. If it doesn't fit the screen it should be scaled down, horizontally centered, and preferably added with black tiles on its sides.

Currently, my CSS class looks like this:

```<code>.img-responsive{
  display: block;
  max-width: 100%;
  min-width: 100%;
  height: auto;
}
</code>```

I've tried to play around with max-height on the image, or on a dedicated container, nothing seemed to do the trick by pure CSS.

Clarifications:

I don't know the images dimensions in advance so can't just put them in a container with a preset size.

Basically, my goal is for the images to be always fully visible on the screen (if you scroll to the image) and take up the largest possible surface.

Here's a more detailed example:

Let's say I have scrollable container with a lot of content. The container takes up the entire viewport width (let's say its 500px) and the available visible height of the container is the entire viewport height minus a navbar height (let's say 1000px).

I can't know in advance what's the container's visible dimensions as it can always change.

Inside the container there's whatever, text, images, etc.

Now, for a given image, here are possible scenarios:

If the image is 500x800, it should be presented as is, as it takes up the entire available width, and height is no bigger then the container's visible height.

If the image is 500x2000, it should be scaled down to 250x1000
and horizontally centered. This will take up the entire visible container's height, and keep the image's aspect ratio

If the image is 250x300, it should be scaled up to 500x600, taking up the entire available width

If the image is 200x500, it should be scaled up to 400x1000, taking up the entire available height

If the image is 1000x1000, it should be scaled down to 500x500, taking up the entire available width

Here's a JSFiddle explaining the problem

答: The best and the easiest way is to use vh and vw properties. vh when set to 100 takes up the complete Viewport Height and same goes with vw for width. Further, max height property may be added to stop image from stretching beyond its original dimensions.  </p>

ContentLicense: CC BY-SA 3.0

Body:
I need the image to take the entire width of the container unless the resulting height is bigger then the available container's viewport height.

Basically I want the image to be responsive but also that it should still fit the screen. If it doesn't fit the screen it should be scaled down, horizontally centered, and preferably added with black tiles on its sides.

Currently, my CSS class looks like this:

.img-responsive{
  display: block;
  max-width: 100%;
  min-width: 100%;
  height: auto;
}

I've tried to play around with max-height on the image, or on a dedicated container, nothing seemed to do the trick by pure CSS.

Clarifications:

I don't know the images dimensions in advance so can't just put them in a container with a preset size.

Basically, my goal is for the images to be always fully visible on the screen (if you scroll to the image) and take up the largest possible surface.

Here's a more detailed example:

Let's say I have scrollable container with a lot of content. The container takes up the entire viewport width (let's say its 500px) and the available visible height of the container is the entire viewport height minus a navbar height (let's say 1000px).

I can't know in advance what's the container's visible dimensions as it can always change.

Inside the container there's whatever, text, images, etc.

Now, for a given image, here are possible scenarios:

If the image is 500x800, it should be presented as is, as it takes up the entire available width, and height is no bigger then the container's visible height.

If the image is 500x2000, it should be scaled down to 250x1000
and horizontally centered. This will take up the entire visible container's height, and keep the image's aspect ratio

If the image is 250x300, it should be scaled up to 500x600, taking up the entire available width

If the image is 200x500, it should be scaled up to 400x1000, taking up the entire available height

If the image is 1000x1000, it should be scaled down to 500x500, taking up the entire available width

Here's a JSFiddle explaining the problem


问:
Shortcut to Uppercase Selected Text in Oracle SQL Developer
I would like to highlight some text in a SQL Developer worksheet and convert it to uppercase with some keyboard shortcut.

Is there any such shortcut in Oracle SQL Developer?

I am using version 4.1.2.

答: in 4.2.0.17 highlight the word(s) then Alt + '


问:
Accessing data within a JSON object using javascript
I have the following JSON object returned and I want to access all the "title" values. I have been able to get a new object of all the "pages," but not the "titles." I have tried everything except the correct thing! The "similar" questions on here are straight forward array access questions. This seems to involve nested arrays. Please help! Thanks.

```<code>{
    "batchcomplete": "",
    "continue": {
        "gsroffset": 15,
        "continue": "gsroffset||"
    },
    "query": {
        "pages": {
            "22989": {
                "pageid": 22989,
                "ns": 0,
                "title": "Paris",
                "index": 1
            },
            "59134": {
                "pageid": 59134,
                "ns": 0,
                "title": "Paris Commune",
                "index": 13
            },
            "61371": {
                "pageid": 61371,
                "ns": 0,
                "title": "Paris (disambiguation)",
                "index": 2
            },
            "64129": {
                "pageid": 64129,
                "ns": 0,
                "title": "Catacombs of Paris",
                "index": 11
            },
            "76286": {
                "pageid": 76286,
                "ns": 0,
                "title": "Disneyland Paris",
                "index": 15
            },
            "89106": {
                "pageid": 89106,
                "ns": 0,
                "title": "Paris–Brest–Paris",
                "index": 8
            },
            "357488": {
                "pageid": 357488,
                "ns": 0,
                "title": "Paris Saint-Germain F.C.",
                "index": 10
            },
            "868936": {
                "pageid": 868936,
                "ns": 0,
                "title": "Paris Gun",
                "index": 14
            },
            "2397134": {
                "pageid": 2397134,
                "ns": 0,
                "title": "Paris (Paris Hilton album)",
                "index": 6
            },
            "7618874": {
                "pageid": 7618874,
                "ns": 0,
                "title": "Paris syndrome",
                "index": 9
            },
            "11217925": {
                "pageid": 11217925,
                "ns": 0,
                "title": "Paris Hilton",
                "index": 7
            },
            "23528038": {
                "pageid": 23528038,
                "ns": 0,
                "title": "Paris Jackson (actress)",
                "index": 5
            },
            "30242372": {
                "pageid": 30242372,
                "ns": 0,
                "title": "Paris Agreement",
                "index": 4
            },
            "45259235": {
                "pageid": 45259235,
                "ns": 0,
                "title": "Paris Laxmi",
                "index": 12
            },
            "55340805": {
                "pageid": 55340805,
                "ns": 0,
                "title": "Paris Paris",
                "index": 3
            }
        }
    }
}
</code>```

It wants me to add more details, but I don't know what else I can add.

答:
Try this:

```<code>const data = //your json
const pages = data.query.pages
const titles = Object.keys(pages).map( key => pages[key].title )
</code>```

Store the values from 'pages' in a variable, then use Object.keys to get as an array all keys within 'pages' and then using map operator you will iterate over those keys and for each one, return the attribute 'title' for this entry.

Body:
I have the following JSON object returned and I want to access all the "title" values. I have been able to get a new object of all the "pages," but not the "titles." I have tried everything except the correct thing! The "similar" questions on here are straight forward array access questions. This seems to involve nested arrays. Please help! Thanks.

{
    "batchcomplete": "",
    "continue": {
        "gsroffset": 15,
        "continue": "gsroffset||"
    },
    "query": {
        "pages": {
            "22989": {
                "pageid": 22989,
                "ns": 0,
                "title": "Paris",
                "index": 1
            },
            "59134": {
                "pageid": 59134,
                "ns": 0,
                "title": "Paris Commune",
                "index": 13
            },
            "61371": {
                "pageid": 61371,
                "ns": 0,
                "title": "Paris (disambiguation)",
                "index": 2
            },
            "64129": {
                "pageid": 64129,
                "ns": 0,
                "title": "Catacombs of Paris",
                "index": 11
            },
            "76286": {
                "pageid": 76286,
                "ns": 0,
                "title": "Disneyland Paris",
                "index": 15
            },
            "89106": {
                "pageid": 89106,
                "ns": 0,
                "title": "Paris–Brest–Paris",
                "index": 8
            },
            "357488": {
                "pageid": 357488,
                "ns": 0,
                "title": "Paris Saint-Germain F.C.",
                "index": 10
            },
            "868936": {
                "pageid": 868936,
                "ns": 0,
                "title": "Paris Gun",
                "index": 14
            },
            "2397134": {
                "pageid": 2397134,
                "ns": 0,
                "title": "Paris (Paris Hilton album)",
                "index": 6
            },
            "7618874": {
                "pageid": 7618874,
                "ns": 0,
                "title": "Paris syndrome",
                "index": 9
            },
            "11217925": {
                "pageid": 11217925,
                "ns": 0,
                "title": "Paris Hilton",
                "index": 7
            },
            "23528038": {
                "pageid": 23528038,
                "ns": 0,
                "title": "Paris Jackson (actress)",
                "index": 5
            },
            "30242372": {
                "pageid": 30242372,
                "ns": 0,
                "title": "Paris Agreement",
                "index": 4
            },
            "45259235": {
                "pageid": 45259235,
                "ns": 0,
                "title": "Paris Laxmi",
                "index": 12
            },
            "55340805": {
                "pageid": 55340805,
                "ns": 0,
                "title": "Paris Paris",
                "index": 3
            }
        }
    }
}

It wants me to add more details, but I don't know what else I can add.

Body:
Try this:

const data = //your json
const pages = data.query.pages
const titles = Object.keys(pages).map( key => pages[key].title )

Store the values from 'pages' in a variable, then use Object.keys to get as an array all keys within 'pages' and then using map operator you will iterate over those keys and for each one, return the attribute 'title' for this entry.


问:
how can I discover the network device type?
On any given computer (OSX, WIn, Lin, etc) there are any number of connected network adapters... whether it's Wi-Fi, BlueTooth, Ethernet or other... And depending on the routing there may be multiple active devices.

In my NARROW use case I want to know what the current CONNECTED default adapter type (Wi-Fi etc...) although once that's known there are easily some others as well as some details.

Here is an example shell script that mostly works and converting it to Go is easy enough... it just seems to me there must be a native GO way.

答:
You can use  Interfaces() from net package

Sample:

```<code>package main

import (
    "fmt"
    "net"
)

func main() {
    l, err := net.Interfaces()
    if err != nil {
        panic(err)

    }
    for _, f := range l {
        if f.Flags&net.FlagUp > 0 {
            fmt.Printf("%s is up\n", f.Name)
        }
    }
}
</code>```

Body:
You can use  Interfaces() from net package

Sample:

package main

import (
    "fmt"
    "net"
)

func main() {
    l, err := net.Interfaces()
    if err != nil {
        panic(err)

    }
    for _, f := range l {
        if f.Flags&net.FlagUp > 0 {
            fmt.Printf("%s is up\n", f.Name)
        }
    }
}


问:
Set the initial value of Android Spinner with some dynamic value
I want to set the dynamic value for the spinner as its initial value..

If i set that dynamic value then, it doesn't allow me to change to another value..

The dynamic Value of spinner is "AMEX" if i want to change my value as "Discover" that is in Array value i cant ,

so pls give me solution here is my code..

```<code>spin_type = (Spinner) findViewById(R.id.Spinner_type);
                   adapter_type = new ArrayAdapter(Credit_Card_Main.this,android.R.layout.simple_spinner_item, array_type);
                   adapter_type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                   spin_type.setAdapter(adapter_type);

spin_type.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3) {
                        spin_type.setSelection(adapter_type.getPosition(Signin.VALUE_type[selected_position]));

@Override
    public void onNothingSelected(AdapterView<?> arg0) {
        }
    });
</code>```

Thanks

Venkatesh

答: you can set initial value for spinner by spinner.setPrompt();method .so just set yor dynamic value by that</p>

Body:
I want to set the dynamic value for the spinner as its initial value..

If i set that dynamic value then, it doesn't allow me to change to another value..

The dynamic Value of spinner is "AMEX" if i want to change my value as "Discover" that is in Array value i cant ,

so pls give me solution here is my code..

spin_type = (Spinner) findViewById(R.id.Spinner_type);
                   adapter_type = new ArrayAdapter(Credit_Card_Main.this,android.R.layout.simple_spinner_item, array_type);
                   adapter_type.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                   spin_type.setAdapter(adapter_type);

spin_type.setOnItemSelectedListener(new OnItemSelectedListener(){
public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3) {
                        spin_type.setSelection(adapter_type.getPosition(Signin.VALUE_type[selected_position]));

@Override
    public void onNothingSelected(AdapterView<?> arg0) {
        }
    });

Thanks

Venkatesh


问:
Power BI Embedded - Access Token
So I have some graphs in Power BI which I want to share with my clients.

I'm making a custom page here on my server and trying to embed those graphs using Power BI Embedded setup.

I'm following this link https://learn.microsoft.com/en-us/power-bi/developer/get-azuread-access-token

However, how do I get an access token via javascript API?

答:
I don't think that's possible in Javascript at the moment. I tried to create access tokens in Javascript not a long time ago but failed to find a way to do that.

I ended up doing a bit of server side code (something like this https://learn.microsoft.com/en-us/power-bi/developer/walkthrough-push-data-get-token) and printed the access code to a hidden div. Then I grabbed the token with Javascript and continued with Javascript from there (created the embed token and embedded the report itself).

It might be possible to do a sort of Javascript solution with a proxy, but that's out of my expertise (the proxy has the server side code).

The only pure Javascript solution I'm aware of is the Publish to web -solution (https://learn.microsoft.com/en-us/power-bi/service-publish-to-web), but it's got some limitations and security issues.

Title: Power BI Embedded - Access Token


问:
How to install PyQt4 in anaconda?
From the PyQt4 website their instructions for installing the package are to download the tarball and use the config file. I have two versions of Python, one is my normal system and the other is within anaconda. I'm not sure how I get this to install within anaconda. Is there a conda command to install PyQt4?</p>

答:
How to install PyQt4 on anaconda python 2 on Windows:

At first I have tried to isntall pyqt4 via pip install:

C:\Users\myuser\Anaconda2\Scripts\pip.exe search pyqt4 > pyqt4.txt

It shows:

```<code>PyQt4 (4.11.4) - Python bindings for the Qt cross platform GUI toolkit
</code>```

But when I tried to install, it gives an error:

```<code>C:\Users\myuser\Anaconda2\Scripts\pip.exe install PyQt4
Collecting PyQt4
  Could not find a version that satisfies the requirement PyQt4 (from versions:
)
No matching distribution found for PyQt4
</code>```

Seems this answer is realated to this problem:
https://superuser.com/a/725869/213959

Then I have tried to install it via conda install ( How to install PyQt4 in anaconda? ) :

```<code>C:\Users\myuser\Anaconda2\Scripts\conda.exe search pyqt
</code>```

It shows:

```<code>pyqt                         4.10.4                   py26_0  defaults
                             4.10.4                   py27_0  defaults
                             4.10.4                   py33_0  defaults
                             4.10.4                   py34_0  defaults
                             4.10.4                   py26_1  defaults
                             4.10.4                   py27_1  defaults
                             4.10.4                   py33_1  defaults
                             4.10.4                   py34_1  defaults
                             4.11.4                   py27_0  defaults
                             4.11.4                   py35_0  defaults
                             4.11.4                   py27_2  defaults
                             4.11.4                   py34_2  defaults
                             4.11.4                   py35_2  defaults
                             4.11.4                   py27_3  defaults
                             4.11.4                   py34_3  defaults
                             4.11.4                   py35_3  defaults
                             4.11.4                   py27_4  defaults
                             4.11.4                   py34_4  defaults
                             4.11.4                   py35_4  defaults
                             4.11.4                   py27_5  defaults
                             4.11.4                   py34_5  defaults
                             4.11.4                   py35_5  defaults
                             4.11.4                   py27_6  defaults
                             4.11.4                   py34_6  defaults
                             4.11.4                   py35_6  defaults
                             4.11.4                   py27_7  defaults
                             4.11.4                   py34_7  defaults
                             4.11.4                   py35_7  defaults
                             5.6.0                    py27_0  defaults
                             5.6.0                    py34_0  defaults
                             5.6.0                    py35_0  defaults
                             5.6.0                    py27_1  defaults
                             5.6.0                    py34_1  defaults
                             5.6.0                    py35_1  defaults
                             5.6.0                    py27_2  defaults
                             5.6.0                    py34_2  defaults
                             5.6.0                    py35_2  defaults
                             5.6.0                    py36_2  defaults
                             5.6.0            py27h224ed30_5  defaults
                             5.6.0            py35hd46907b_5  defaults
                             5.6.0            py36hb5ed885_5  defaults
</code>```

But it gives error:

```<code>C:\Users\myuser\Anaconda2\Scripts\conda.exe install pyqt=4.11.4
Fetching package metadata .............
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - navigator-updater -> pyqt >=5.6 -> qt 5.6.*
  - pyqt 4.11.4* -> qt >=4.8.6,<5.0
  - pyqt 4.11.4* -> sip >=4.16.4,<4.18
Use "conda info <package>" to see the dependencies for each package.
</code>```

Same with -c parameter:

```<code>C:\Users\myuser\Anaconda2\Scripts\conda.exe install -c anaconda pyqt=4.11.4
Fetching package metadata ...............
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - navigator-updater -> pyqt >=5.6 -> qt 5.6.*
  - pyqt 4.11.4* -> qt >=4.8.6,<5.0
  - pyqt 4.11.4* -> sip >=4.16.4,<4.18
Use "conda info <package>" to see the dependencies for each package.
</code>```

Then I tried to uninstall pyqt:

```<code>C:\Users\myuser\Anaconda2\Scripts\conda.exe uninstall pyqt
</code>```

And installed it again:

```<code>C:\Users\myuser\Anaconda2\Scripts\conda.exe install -c anaconda pyqt=4.11.4
</code>```

And finnaly it works!

Title: How to install PyQt4 in anaconda?

Body:
How to install PyQt4 on anaconda python 2 on Windows:

At first I have tried to isntall pyqt4 via pip install:

C:\Users\myuser\Anaconda2\Scripts\pip.exe search pyqt4 > pyqt4.txt

It shows:

PyQt4 (4.11.4) - Python bindings for the Qt cross platform GUI toolkit

But when I tried to install, it gives an error:

C:\Users\myuser\Anaconda2\Scripts\pip.exe install PyQt4
Collecting PyQt4
  Could not find a version that satisfies the requirement PyQt4 (from versions:
)
No matching distribution found for PyQt4

Seems this answer is realated to this problem:
https://superuser.com/a/725869/213959

Then I have tried to install it via conda install ( How to install PyQt4 in anaconda? ) :

C:\Users\myuser\Anaconda2\Scripts\conda.exe search pyqt

It shows:

pyqt                         4.10.4                   py26_0  defaults
                             4.10.4                   py27_0  defaults
                             4.10.4                   py33_0  defaults
                             4.10.4                   py34_0  defaults
                             4.10.4                   py26_1  defaults
                             4.10.4                   py27_1  defaults
                             4.10.4                   py33_1  defaults
                             4.10.4                   py34_1  defaults
                             4.11.4                   py27_0  defaults
                             4.11.4                   py35_0  defaults
                             4.11.4                   py27_2  defaults
                             4.11.4                   py34_2  defaults
                             4.11.4                   py35_2  defaults
                             4.11.4                   py27_3  defaults
                             4.11.4                   py34_3  defaults
                             4.11.4                   py35_3  defaults
                             4.11.4                   py27_4  defaults
                             4.11.4                   py34_4  defaults
                             4.11.4                   py35_4  defaults
                             4.11.4                   py27_5  defaults
                             4.11.4                   py34_5  defaults
                             4.11.4                   py35_5  defaults
                             4.11.4                   py27_6  defaults
                             4.11.4                   py34_6  defaults
                             4.11.4                   py35_6  defaults
                             4.11.4                   py27_7  defaults
                             4.11.4                   py34_7  defaults
                             4.11.4                   py35_7  defaults
                             5.6.0                    py27_0  defaults
                             5.6.0                    py34_0  defaults
                             5.6.0                    py35_0  defaults
                             5.6.0                    py27_1  defaults
                             5.6.0                    py34_1  defaults
                             5.6.0                    py35_1  defaults
                             5.6.0                    py27_2  defaults
                             5.6.0                    py34_2  defaults
                             5.6.0                    py35_2  defaults
                             5.6.0                    py36_2  defaults
                             5.6.0            py27h224ed30_5  defaults
                             5.6.0            py35hd46907b_5  defaults
                             5.6.0            py36hb5ed885_5  defaults

But it gives error:

C:\Users\myuser\Anaconda2\Scripts\conda.exe install pyqt=4.11.4
Fetching package metadata .............
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - navigator-updater -> pyqt >=5.6 -> qt 5.6.*
  - pyqt 4.11.4* -> qt >=4.8.6,<5.0
  - pyqt 4.11.4* -> sip >=4.16.4,<4.18
Use "conda info <package>" to see the dependencies for each package.

Same with -c parameter:

C:\Users\myuser\Anaconda2\Scripts\conda.exe install -c anaconda pyqt=4.11.4
Fetching package metadata ...............
Solving package specifications: .

UnsatisfiableError: The following specifications were found to be in conflict:
  - navigator-updater -> pyqt >=5.6 -> qt 5.6.*
  - pyqt 4.11.4* -> qt >=4.8.6,<5.0
  - pyqt 4.11.4* -> sip >=4.16.4,<4.18
Use "conda info <package>" to see the dependencies for each package.

Then I tried to uninstall pyqt:

C:\Users\myuser\Anaconda2\Scripts\conda.exe uninstall pyqt

And installed it again:

C:\Users\myuser\Anaconda2\Scripts\conda.exe install -c anaconda pyqt=4.11.4

And finnaly it works!


问:
What's the best way to change a controller name in swagger?
I wanna change company to companies. Is there a way to change this? Without having to rename the controller.

The controller name (above in bold) should remain Company. But in every operation I wanna change it to companies.

The reason I'm not using [Route] is because I have a super class which defines:

```<code>[Route("admin/codes/[controller]")]
</code>```

And the company controller is inheriting from that class. And I want to keep the "admin/codes/" in the url.

What is the best solution here? Without having to rename the controller class.

答:
Setting the old philosophical singular-plural battle aside, Swagger is a viewport to your API; you shouldn't change a controller name just in Swagger, as the poor souls using your APIs will be rather baffled – they would call /admin/codes/companies and get a 404 in return, as the MVC framework was not informed of the controller's new name.

What I think you should be looking for is how to change the controller's routing within the MVC framework, and you can do that without changing the super class's routing - for example, using a [RoutePrefix("companies")] annotation.

Body:
I wanna change company to companies. Is there a way to change this? Without having to rename the controller.

The controller name (above in bold) should remain Company. But in every operation I wanna change it to companies.

The reason I'm not using [Route] is because I have a super class which defines:

[Route("admin/codes/[controller]")]

And the company controller is inheriting from that class. And I want to keep the "admin/codes/" in the url.

What is the best solution here? Without having to rename the controller class.


问:
Defining fields in Laravel 5.5 Migrations with Postgres
Working with Laravel 5.5 Migrations with Postgres :

1) Defining field as :

```<code>$table->enum('is_applied', ['Y', 'N']) ->comment('Y => is_applied, N=> Is not applied');
</code>```

I see in generated table next:

```<code>is_applied varchar(255) NOT NULL,
    CONSTRAINT cs_tmp_csvps_is_applied_check CHECK (((is_applied)::text = ANY ((ARRAY['Y'::character varying, 'N'::character varying])::text[]))),
</code>```

actually I would like to get sql I used in Postgres with type:

```<code>CREATE TYPE type_cms_item_content_type AS ENUM (
    'P',
    'M',
    'H'
);

    content_type type_cms_item_content_type NOT NULL DEFAULT 'P'::type_cms_item_content_type,
</code>```

Is it possible?

2) Defining field as :

```<code>$table->timestamps();
</code>```

I have 2 fields created created_at and  updated_at .
As I need to create only created_at I could write :

```<code>$table->dateTime('created_at');
</code>```

But is there is a way to set default time on server, like :

```<code>created_at timestamp NOT NULL DEFAULT now(),
</code>```

?

Thanks!

答:
1) Defining field as:

```<code>$table->enum('is_applied', ['Y', 'N']) ->comment('Y => is_applied, N=> Is not applied');
</code>```

The method comment() it's only for MySQL, in the Migrations on Laravel.

See for more details: https://laravel.com/docs/5.5/migrations#creating-columns

2) Defining field as:

The Answer of @alex-harris is a gob option

```<code>$table->timestamp('created_at')->useCurrent();
</code>```

See: https://laravel.com/docs/5.5/migrations#column-modifiers  for more details

Body:
Working with Laravel 5.5 Migrations with Postgres :

1) Defining field as :

$table->enum('is_applied', ['Y', 'N']) ->comment('Y => is_applied, N=> Is not applied');

I see in generated table next:

is_applied varchar(255) NOT NULL,
    CONSTRAINT cs_tmp_csvps_is_applied_check CHECK (((is_applied)::text = ANY ((ARRAY['Y'::character varying, 'N'::character varying])::text[]))),

actually I would like to get sql I used in Postgres with type:

CREATE TYPE type_cms_item_content_type AS ENUM (
    'P',
    'M',
    'H'
);

    content_type type_cms_item_content_type NOT NULL DEFAULT 'P'::type_cms_item_content_type,

Is it possible?

2) Defining field as :

$table->timestamps();

I have 2 fields created created_at and  updated_at .
As I need to create only created_at I could write :

$table->dateTime('created_at');

But is there is a way to set default time on server, like :

created_at timestamp NOT NULL DEFAULT now(),

?

Thanks!

Body:
1) Defining field as:

$table->enum('is_applied', ['Y', 'N']) ->comment('Y => is_applied, N=> Is not applied');

The method comment() it's only for MySQL, in the Migrations on Laravel.

See for more details: https://laravel.com/docs/5.5/migrations#creating-columns

2) Defining field as:

The Answer of @alex-harris is a gob option

$table->timestamp('created_at')->useCurrent();

See: https://laravel.com/docs/5.5/migrations#column-modifiers  for more details


问:
JavaScript: Why does closure only happen if I assign the return function to a variable?
Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.

Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?

```<code>function counter() {

    var _counter = 0;

    function increase() { return _counter++ }

    return increase;
}

// Double ()() to call the returned function always return 0, so no closure.
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0

var createClosure = counter();

createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3
</code>```

答:
To put in another way, the return value of the counter() function, which is the closure, isn't persisted or rather it is discarded when you simply call the function as is.

However after assigning that return value to
var createClosure. You are able to call the closure as many times as needed

Body:
Even after reading You don't know JS and JavaScript: The Core I still couldn't understand the behavior of the following code.

Why, when I call counter()(), do I get no closure, but if I assign a variable to the result of counter(), like var getClosure = counter(), I then get a closure when calling getClosure()?

function counter() {

    var _counter = 0;

    function increase() { return _counter++ }

    return increase;
}

// Double ()() to call the returned function always return 0, so no closure.
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0
counter()() // returns 0

var createClosure = counter();

createClosure() // returns 0
createClosure() // returns 1
createClosure() // returns 2
createClosure() // returns 3


问:
How can I change this date and time format to yyyy-mm-dd hh:mm:ss using bash, this is from an apache log file
```<code>49,10.96.25.156,1274x40x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"
50,10.96.25.156,1274x41x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-25,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""9myyx9"
</code>```

This is how the log file looks, any help would be appreciated. Thanks!

Body:
49,10.96.25.156,1274x40x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-20,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""-"
50,10.96.25.156,1274x41x1,-,02/Nov/2017:21:14:31,http-nio-443-exec-25,"POST/rest/webResources/1.0/resourcesHTTP/1.1",503,40,0,"-","SilkPerformer17.0""9myyx9"

This is how the log file looks, any help would be appreciated. Thanks!

Body:
bash only conversion:

declare -A m
m=([Jan]=01 [Feb]=02 [Mar]=03 [Apr]=04 [May]=05 [Jun]=06 [Jul]=07 [Aug]=08 [Set]=09 [Oct]=10 [Nov]=11 [Dec]=12)
IFS='/:' read -r -a a <<< '02/Nov/2017:21:14:31'
echo "${a[2]}-${m[${a[1]}]}-${a[0]} ${a[3]}:${a[4]}:${a[5]}"

EDIT

I mean something like this to read the file and split the lines

printline() {
    local l=("$@")
    echo -n "${l[0]}"
    for f in "${l[@]:1}"
    do
        echo -n ",$f"
    done
    echo
}

declare -A m
m=([Jan]=01 [Feb]=02 [Mar]=03 [Apr]=04 [May]=05 [Jun]=06 [Jul]=07 [Aug]=08 [Set]=09 [Oct]=10 [Nov]=11 [Dec]=12)
while read line
do
    IFS=',' read -r -a l <<< "$line"
    IFS='/:' read -r -a a <<< ${l[4]}
    l[4]="${a[2]}-${m[${a[1]}]}-${a[0]} ${a[3]}:${a[4]}:${a[5]}"
    printline "${l[@]}"
done


问:
Primitive types pass template parameter between c++ and CLI
I have a c++ templated class:

```<code>template<class T>
class A {
    void test (T temp) { }
};
</code>```

But i need to wrap it in CLI so it can be used in c#.

Example:

CLI:

```<code>template<class T>
ref class AWrap {
     private:
        A* a;
     public:
        void test (T temp) {
           a->test<T>(temp);
        }
};
</code>```

C#:

```<code>Awrap blah = new AWrap();
blah<int>(3);
</code>```

If I make a CLI templated ref class , which call the templated c++ method, will the primitive types generate the right c++ templated code on compilation ?->

答: What you are using in C# are generics, not templates. There is no way of specializing a C++/CLI template from C#. </p>

Body:
I have a c++ templated class:

template<class T>
class A {
    void test (T temp) { }
};

But i need to wrap it in CLI so it can be used in c#.

Example:

CLI:

template<class T>
ref class AWrap {
     private:
        A* a;
     public:
        void test (T temp) {
           a->test<T>(temp);
        }
};

C#:

Awrap blah = new AWrap();
blah<int>(3);

If I make a CLI templated ref class , which call the templated c++ method, will the primitive types generate the right c++ templated code on compilation ?->


问:
Spring JPARepository querying many to many intersection table
I have 3 entity classes as follows (Example taken from https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/)

Book class

```<code>@Entity
public class Book{
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Book() {
    }

    public Book(String name) {
        this.name = name;
        bookPublishers = new HashSet<>();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<BookPublisher>   getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}
</code>```

Publisher class

```<code>@Entity
public class Publisher {
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Publisher(){

    }

    public Publisher(String name){
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "publisher")
    public Set<BookPublisher> getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}
</code>```

Intersection Table

```<code>@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable{
    private Book book;
    private Publisher publisher;
    private Date publishedDate;

    @Id
    @ManyToOne
    @JoinColumn(name = "book_id")
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Id
    @ManyToOne
    @JoinColumn(name = "publisher_id")
    public Publisher getPublisher() {
        return publisher;
    }

    public void setPublisher(Publisher publisher) {
        this.publisher = publisher;
    }

    @Column(name = "published_date")
    public Date getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(Date publishedDate) {
        this.publishedDate = publishedDate;
    }
}
</code>```

I want to query 2 things,

Get list of books belonging to a particular publisher e.g. get all books associated with publisher 100

Get list of books not associated with a particular publisher e.g. get all books not associated with publisher 100

I want to achieve this using a simple JPARepository query if possible like findByXYZIn(...) etc.

Please let me know if querying a many to many relation is possible using JPA repository queries and if yes, whether I can do it directly or would it require any changes in the entity classes

答: I'm not sure if you can make it just by method name. But you definitely can use JPA query. Something like this: "SELECT b FROM Book b JOIN b.bookPublishers bp JOIN bp.publisher p WHERE p.id = ?1". and with not equal for the second case

Body:
I have 3 entity classes as follows (Example taken from https://hellokoding.com/jpa-many-to-many-extra-columns-relationship-mapping-example-with-spring-boot-maven-and-mysql/)

Book class

@Entity
public class Book{
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Book() {
    }

    public Book(String name) {
        this.name = name;
        bookPublishers = new HashSet<>();
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "book", cascade = CascadeType.ALL, orphanRemoval = true)
    public Set<BookPublisher>   getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}

Publisher class

@Entity
public class Publisher {
    private int id;
    private String name;
    private Set<BookPublisher> bookPublishers;

    public Publisher(){

    }

    public Publisher(String name){
        this.name = name;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.AUTO)
    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @OneToMany(mappedBy = "publisher")
    public Set<BookPublisher> getBookPublishers() {
        return bookPublishers;
    }

    public void setBookPublishers(Set<BookPublisher> bookPublishers) {
        this.bookPublishers = bookPublishers;
    }
}

Intersection Table

@Entity
@Table(name = "book_publisher")
public class BookPublisher implements Serializable{
    private Book book;
    private Publisher publisher;
    private Date publishedDate;

    @Id
    @ManyToOne
    @JoinColumn(name = "book_id")
    public Book getBook() {
        return book;
    }

    public void setBook(Book book) {
        this.book = book;
    }

    @Id
    @ManyToOne
    @JoinColumn(name = "publisher_id")
    public Publisher getPublisher() {
        return publisher;
    }

    public void setPublisher(Publisher publisher) {
        this.publisher = publisher;
    }

    @Column(name = "published_date")
    public Date getPublishedDate() {
        return publishedDate;
    }

    public void setPublishedDate(Date publishedDate) {
        this.publishedDate = publishedDate;
    }
}

I want to query 2 things,

Get list of books belonging to a particular publisher e.g. get all books associated with publisher 100

Get list of books not associated with a particular publisher e.g. get all books not associated with publisher 100

I want to achieve this using a simple JPARepository query if possible like findByXYZIn(...) etc.

Please let me know if querying a many to many relation is possible using JPA repository queries and if yes, whether I can do it directly or would it require any changes in the entity classes


问:
git push Out of memory, malloc failed
I am trying to push my changes remotely to GitHub, every so often git fails due to

```<code>C:\dev\projects>git push -v
Pushing to https://user@github.com/mycompany/My-Project.git
Password for 'github.com':
fatal: Out of memory, malloc failed (tried to allocate 524288000 bytes)
fatal: write error: Invalid argument
</code>```

This is very, very aggravating.  I have run the following commands, upgraded git (which wiped out my settings and caused lots of pain, but I digress)

```<code>git gc --auto --prune=today --aggressive
git repack
</code>```

I have even bumped the value of

```<code>http.postbuffer
</code>```

but eventually it will fail again.

This is a typical Rails 3.1 application, total project size on disk is 9.69 MB.

答: I had the same problem on an AWS t2.small. Also running sonar. I shutdown Sonar to free memory, checked out and restarted Sonar. I will increase the instance size. </p>

Title: git push Out of memory, malloc failed

Body:
I am trying to push my changes remotely to GitHub, every so often git fails due to

C:\dev\projects>git push -v
Pushing to https://user@github.com/mycompany/My-Project.git
Password for 'github.com':
fatal: Out of memory, malloc failed (tried to allocate 524288000 bytes)
fatal: write error: Invalid argument

This is very, very aggravating.  I have run the following commands, upgraded git (which wiped out my settings and caused lots of pain, but I digress)

git gc --auto --prune=today --aggressive
git repack

I have even bumped the value of

http.postbuffer

but eventually it will fail again.

This is a typical Rails 3.1 application, total project size on disk is 9.69 MB.


问:
datepicker jQuery UI doesn´t show properly
I do have a contact form (MVC View)with a jQuery UI datepicker, in the form the datepicker is above a textbox control as shows in the image below

my problem is that when the user displays the datepicker to select a date, it shows the textbox in the calendar so the month cannot be displayed correctly as shows in the image below

this is the script code of my datepicker

```<code> $("#datepicker").datepicker({
            dayNamesMin: ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"],
            monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
            dateFormat: 'dd/mm/yy',
            showAnim: "fold"
        });

        $("#datepicker").datepicker();
</code>```

and the code of my form

```<code> <div class="col-xs-10">
                    my datepicker
                    <div class="input-group">
                        <span class="input-group-addon">
                            <input type="checkbox" aria-label="Radio button for following text input" id="chk3">
                        </span>
                        <input type="text" id="datepicker">
                    </div>
                </div>
                <br />
                <br />
                <div class="col-xs-10">
                    The textbox
                    <div class="input-group">
                        <span class="input-group-addon">
                            <input type="checkbox" aria-label="Radio button for following text input" id="chk1">
                        </span>
                        <input type="text" class="form-control" aria-label="Text input with radio button" id="txt1">
                    </div>
                </div>
</code>```

and the libraries imported as cdn

```<code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-datetimepicker/2.5.4/build/jquery.datetimepicker.full.js">
</script>

    <!-- CSS -->
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
    <link rel=" stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">
</code>```

could you please help me and tell me how to show the datepicker properly?

答:
Use this css and fix it!</p>

```<code>.ui-datepicker {
    z-index: 1336 !important;
}
</code>```

Body:
I do have a contact form (MVC View)with a jQuery UI datepicker, in the form the datepicker is above a textbox control as shows in the image below

my problem is that when the user displays the datepicker to select a date, it shows the textbox in the calendar so the month cannot be displayed correctly as shows in the image below

this is the script code of my datepicker

 $("#datepicker").datepicker({
            dayNamesMin: ["Dom", "Lun", "Mar", "Mie", "Jue", "Vie", "Sab"],
            monthNames: ['Enero', 'Febrero', 'Marzo', 'Abril', 'Mayo', 'Junio', 'Julio', 'Agosto', 'Septiembre', 'Octubre', 'Noviembre', 'Diciembre'],
            dateFormat: 'dd/mm/yy',
            showAnim: "fold"
        });

        $("#datepicker").datepicker();

and the code of my form

                    my datepicker

                            <input type="checkbox" aria-label="Radio button for following text input" id="chk3">

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

                    The textbox

                            <input type="checkbox" aria-label="Radio button for following text input" id="chk1">

                        <input type="text" class="form-control" aria-label="Text input with radio button" id="txt1">

and the libraries imported as cdn

    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.css">
    <link rel=" stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css">

could you please help me and tell me how to show the datepicker properly?

Body:
Use this css and fix it!

.ui-datepicker {
    z-index: 1336 !important;
}


问:
How do I save values submitted from form in activejdbc?
```<code>@Override
public Long createPost(Request request) {

    Base.open();

    ObjectMapper mapper = new ObjectMapper();

    try {
        Post newPost  = mapper.readValue(request.body(), Post.class);
//        Map values = ... initialize map
//        newPost.saveIt();

    } catch (IOException ex) {
        Logger.getLogger(PostServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    Base.close();

    return 1L;
}
</code>```

From the official docs, this Map values = ... initialize map is not clear. I can do newPost.set("first_name", "Sam") but is there a better way instead of setting values likes this?

答:
If I'm understanding correctly, you are looking at how to take values from a POST request and then use ActiveJDBC to save those values.   I'm quite new as well and we are in the beginning stages of our app, but we are using SparkJava with ActiveJDBC.

The example is actual code, I didn't have time to simplify it.  But basically we created a POJO for the model class.   We originally extended the org.javalite.activejdbc.Model but we needed to handle audit fields (create, update user/time) and help translate from JSON, so we extended this with a custom class called CecilModel.  But CecilModel extends the Model class.

We have a controller that receives the request.  The request comes in as JSON that matches the field names of our model class.  In our custom CecilModel class we map the JSON to a Map which then we use Model.fromMap method to hyrdrate the fields and puts it into our custom model POJO.   We don't need the getters or setters, it's more for convenience.   We just need our JSON request to have the same names as in our model.

Below is our code but maybe you can peek through it to see how we are doing it.

Our table model pojo.

```<code>package com.brookdale.model;

import java.sql.Timestamp;

import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.BelongsTo;
import org.javalite.activejdbc.annotations.BelongsToParents;
import org.javalite.activejdbc.annotations.IdGenerator;
import org.javalite.activejdbc.annotations.IdName;
import org.javalite.activejdbc.annotations.Table;

import com.brookdale.model.activejdbc.CecilModel;

// This class handles mapping of data from the database to objects
// and back, including custom selection queries.

@Table("RECURRINGITEMSCHEDULE")
@BelongsToParents({
    @BelongsTo(foreignKeyName="itemID",parent=Item.class),
    @BelongsTo(foreignKeyName="contactAgreementID",parent=ContactAgreement.class),
    @BelongsTo(foreignKeyName="unitOfMeasureCode",parent=UnitOfMeasure.class)
})
@IdGenerator("SQ_RECURRINGITEMSCHEDULE.nextVal")
@IdName("recurringItemScheduleID")
public class RecurringItem extends CecilModel {

    public Long getRecurringItemScheduleID() {
        return getLong("recurringItemScheduleID");
    }
    public void setRecurringItemScheduleID(Long recurringItemScheduleID) {
        set("recurringItemScheduleID",recurringItemScheduleID);
    }
    public Long getContactAgreementID() {
        return getLong("contactAgreementID");
    }
    public void setContactAgreementID(Long contactAgreementID) {
        set("contactAgreementID",contactAgreementID);
    }
    public Long getItemID() {
        return getLong("itemID");
    }
    public void setItemID(Long itemID) {
        set("itemID",itemID);
    }
    public Double getUnitChargeAmt() {
        return getDouble("unitChargeAmt");
    }
    public void setUnitChargeAmt(Double unitChargeAmt) {
        set("unitChargeAmt",unitChargeAmt);
    }
    public Integer getUnitQty() {
        return getInteger("unitQty");
    }
    public void setUnitQty(Integer unitQty) {
        set("unitQty",unitQty);
    }
    public String getUnitOfMeasureCode() {
        return getString("unitOfMeasureCode");
    }
    public void setUnitOfMeasureCode(String unitOfMeasureCode) {
        set("unitOfMeasureCode",unitOfMeasureCode);
    }
    public Timestamp getLastGeneratedPeriodEndDate() {
        return getTimestamp("lastGeneratedPeriodEndDate");
    }
    public void setLastGeneratedPeriodEndDate(Timestamp lastGeneratedPeriodEndDate) {
        set("lastGeneratedPeriodEndDate",lastGeneratedPeriodEndDate);
    }
    public Timestamp getEffEndDate() {
        return getTimestamp("effEndDate");
    }
    public void setEffEndDate(Timestamp effEndDate) {
        set("effEndDate",effEndDate);
    }
    public Timestamp getEffStartDate() {
        return getTimestamp("effStartDate");
    }
    public void setEffStartDate(Timestamp effStartDate) {
        set("effStartDate",effStartDate);
    }

    @Override
    public void validate() {
        validatePresenceOf("unitofmeasurecode","itemid","unitqty","effstartdate","unitChargeAmt","contactAgreementID");
        validateNumericalityOf("itemid","unitQty","contactAgreementID");
        // check to make sure this is an update operation
        if (!this.isNew()) {
            RecurringItem ridb = RecurringItem.findById(this.getId());
            if (ridb.getLastGeneratedPeriodEndDate() != null) {
                if (this.getItemID() != ridb.getItemID())
                    this.addError("itemid", "Item can not be updated once a charge has been created.");
                if (!this.getEffStartDate().equals(ridb.getEffStartDate()))
                    this.addError("effstartdate", "Effective start date can not be updated once a charge has been created.");
                if (this.getUnitChargeAmt() != ridb.getUnitChargeAmt())
                    this.addError("unitchargeamt", "Unit charge amount can not be updated after last generated period end date has been set.");
                if (this.getUnitQty() != ridb.getUnitQty())
                    this.addError("unitqty", "Unit quantity can not be updated after last generated period end date has been set.");
                if (!this.getUnitOfMeasureCode().equals(ridb.getUnitOfMeasureCode()))
                    this.addError("", "Unit of measure can not be updated after last generated period end date has been set.");
            }
        }

        if (this.getEffEndDate() != null && this.getEffStartDate().compareTo(this.getEffEndDate()) >= 0) {
            this.addError("effenddate", "Effective end date can not come before the start date.");
        }

    }

}
</code>```

Extends our custom Model class.  This will extend the actual ActiveJDBC Model class.

```<code>package com.brookdale.model.activejdbc;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.validation.ValidationBuilder;
import org.javalite.activejdbc.validation.ValidatorAdapter;

import com.brookdale.core.CLArgs;
import com.brookdale.security.bo.User;

public abstract class CecilModel extends Model {

    private static final transient TypeReference<HashMap<String, Object>> mapType = new TypeReference<HashMap<String, Object>>() {};
    private static final transient TypeReference<LinkedList<HashMap<String, Object>>> listMapType = new TypeReference<LinkedList<HashMap<String, Object>>>() {};
    private static final transient SimpleDateFormat jsonDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    public Timestamp getUpdateDateTime() {
        return getTimestamp("updateDateTime");
    }
    public void setUpdateDateTime(LocalDateTime updateDateTime) {
        set("updateDateTime",updateDateTime == null ? null : Timestamp.valueOf(updateDateTime));
    }
    public Timestamp getCreateDateTime() {
        return getTimestamp("createDateTime");
    }
    public void setCreateDateTime(LocalDateTime createDateTime) {
        set("createDateTime",createDateTime == null ? null : Timestamp.valueOf(createDateTime));
    }
    public String getUpdateUsername() {
        return getString("updateUsername");
    }
    public void setUpdateUsername(String updateUsername) {
        set("updateUsername",updateUsername);
    }
    public String getCreateUsername() {
        return getString("createUsername");
    }
    public void setCreateUsername(String createUsername) {
        set("createUsername",createUsername);
    }
    public Long getUpdateTimeId() {
        return getLong("updateTimeId");
    }
    public void setUpdateTimeId(Long updateTimeId) {
        set("updateTimeId",updateTimeId);
    }

    public boolean save(User user) {
        String userId = (CLArgs.args.isAuthenabled()) ? user.getUserid() : "TEST_MODE";
        // insert
        java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
        if (this.getId() == null || this.getId().toString().equals("0")) {
            this.setId(null);
            this.set("createDateTime", now);
            this.set("createUsername", userId);
            this.set("updateDateTime", now);
            this.set("updateUsername", userId);
            this.set("updateTimeId", 1);
        }
        // update
        else {
            Long updatetimeid = this.getLong("updateTimeid");
            this.set("updateDateTime", now);
            this.set("updateUsername", userId);
            this.set("updateTimeId",  updatetimeid == null ? 1 : updatetimeid + 1);
        }
        return super.save();
    }

    public boolean saveIt(User user) {
        String userId = (CLArgs.args.isAuthenabled()) ? user.getUserid() : "TEST_MODE";
        // insert
        java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
        if (this.isNew()) {
            this.setId(null);
            this.set("createDateTime", now);
            this.set("createUsername", userId);
            this.set("updateDateTime", now);
            this.set("updateUsername", userId);
            this.set("updateTimeId", 1);
        }
        // update
        else {
            Long updatetimeid = this.getLong("updateTimeid");
            this.set("updateDateTime", now);
            this.set("updateUsername", userId);
            this.set("updateTimeId",  updatetimeid == null ? 1 : updatetimeid + 1);
        }
        return super.saveIt();
    }

    public boolean saveModel(User user, boolean insert) {
        if(insert){
            this.insertIt(user);
        }else{
            this.updateIt(user);
        }
        return super.saveIt();
    }

    public boolean insertIt(User user) {
        // insert
        java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
        this.setId(null);
        this.set("createDateTime", now);
        this.set("createUsername", user.getUserid());
        this.set("updateDateTime", now);
        this.set("updateUsername", user.getUserid());
        this.set("updateTimeId", 1);
        return super.saveIt();
    }

    public boolean updateIt(User user) {
        // insert
        java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
        Long updatetimeid = this.getLong("updateTimeid");
        this.set("updateDateTime", now);
        this.set("updateUsername", user.getUserid());
        this.set("updateTimeId",  updatetimeid == null ? 1 : updatetimeid + 1);
        return super.saveIt();
    }

    // Convert a single ActiveJdbc Object to a json string
    @SuppressWarnings("unchecked")
    public String toJson() {
        Map<String, Object> objMap = this.toMap();
        try {
            if (objMap.containsKey("parents")) {
                Map<String, ?> parentsMap = (Map<String, ?>) objMap.get("parents");
                for (String key: parentsMap.keySet()) {
                    objMap.put(key, parentsMap.get(key));
                }
                objMap.remove("parents");
            }
            if (objMap.containsKey("children")) {
                Map<String, ?> childrenMap = (Map<String, ?>) objMap.get("children");
                for (String key: childrenMap.keySet()) {
                    objMap.put(key, childrenMap.get(key));
                }
                objMap.remove("children");
            }
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(jsonDateFormat);
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objMap);
        } catch (Exception e) { throw new RuntimeException(e); }
    }
    // Converts a single json object into an ActiveJdbc Model
    public <T extends CecilModel> T toObj(String json) {
        try {
            Map<String, Object> objMap = toMap(json);
            convertDatesToTimestamp(objMap);
            return this.fromMap(objMap);
        } catch (Exception e) { throw new RuntimeException(e); }
    }

    // STATIC CONVERTERS FOR COLLECTIONS OF OBJECTS
    // Convert an ActiveJdbc LazyList Collection to a JSON string
    public static <T extends Model> String toJson(Collection<T> objCollection) {
        //objCollection.load();
        StringBuffer json = new StringBuffer("[ ");
        for (T obj: objCollection) {
            if (CecilModel.class.isInstance(obj)) {
                json.append(((CecilModel)obj).toJson() + ",");
            } else {
                try {
                    json.append(new ObjectMapper().writeValueAsString(obj));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return json.substring(0, json.length()-1) + "]";
    }
    // Converts an array of json objects into a list of ActiveJdbc Models
    public static <T extends Model> List<T> toObjList(String json, Class<T> cls) {
        List<T> results = new LinkedList<T>();
        try {
            List<Map<String, Object>> objMapList = toMaps(json);
            for (Map<String, Object> objMap: objMapList) {
                convertDatesToTimestamp(objMap);
                T obj = cls.newInstance().fromMap(objMap);
                results.add(obj);
            }
        } catch (Exception e) { throw new RuntimeException(e); }
        return results;
    }

    // Converts a single json object into a map of key:value pairs
    private static Map<String, Object> toMap(String json) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json, mapType);
        } catch (IOException e) { throw new RuntimeException(e); }
    }
    // Converts an array of json objects into a list of maps
    private static List<Map<String, Object>> toMaps(String json) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json, listMapType);
        } catch (IOException e) { throw new RuntimeException(e); }
    }
    // checks for Strings that are formatted in 'yyyy-MM-ddTHH:mm:ss.SSSZ' format
    // if found it will replace the String value with a java.sql.Timestamp value in the objMap
    private static final Map<String,Object> convertDatesToTimestamp(Map<String, Object> objMap) {
        // attempt to convert all dates to java.sql.Timestamp
        for (String key: objMap.keySet()) {
            Object value = objMap.get(key);
            System.out.println("Checking if '" + key + "=" + (value == null ? "null" : value.toString()) +"' is a date...");
            if (value instanceof String && ((String) value).matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$")) {
                String valuestr = (String) value;
                System.out.println("DATE FOUND FOR '" + key + "' " + value);
                objMap.put(key, Timestamp.valueOf(ZonedDateTime.parse(valuestr).toLocalDateTime()));
            }
        }
        return objMap;
    }

    public static ValidationBuilder<?> validateAbsenceOf(String ... attributes) {
        return validateWith(new ValidatorAdapter() {

            @Override
            public void validate(Model m) {
                boolean containsAttribute = false;

                for(String attribute:attributes) {

                    if(m.attributeNames().contains(attribute)) {
                        //model contains attribute, invalidate now !
                        m.addValidator(this, attribute);
                        break;
                    }
                }
            }
        });
    }
}
</code>```

Our Controller

```<code>package com.brookdale.controller;

import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.put;

import org.codehaus.jackson.map.ObjectMapper;

import com.brookdale.model.RecurringItem;
import com.brookdale.model.activejdbc.CecilModel;
import com.brookdale.security.bo.User;
import com.brookdale.service.RecurringItemService;

public class RecurringItemController {

    public RecurringItemController(final RecurringItemService service) {
        // get list of recurring items based on the agreementid
        get("/api/recurring/list/:agreementid", (req,res)-> {
            String all = req.queryParams("all");
            Long agreementid = Long.parseLong(req.params(":agreementid"));
            //return RecurringItemAPI.searchByAgreement(Long.parseLong(req.params(":agreementid"))).toJson(true);
            return CecilModel.toJson(service.findByAgreementId(agreementid, all != null));

        });
        // insert
        post("/api/recurring/save", (req,res)-> {
            //RecurringItem ri = ActiveJdbcJson.toObj(req.body(), RecurringItem.class);
            RecurringItem ri = new RecurringItem().toObj(req.body());
            // set unitqty to '1' since the field is not nullable, but not used
            if (ri.getUnitQty() == null)
                ri.setUnitQty(1);
            System.out.println("ri to insert: " + new ObjectMapper().writeValueAsString(ri));
            return service.saveRecurringItem(ri, (User) req.attribute("user")).toJson();
        });
        // update
        put("/api/recurring/save", (req,res)-> {
            //RecurringItem ri = ActiveJdbcJson.toObj(req.body(), RecurringItem.class);
            RecurringItem ri = new RecurringItem().toObj(req.body());
            System.out.println("ri to update: " + new ObjectMapper().writeValueAsString(ri));
            return service.saveRecurringItem(ri, (User) req.attribute("user")).toJson();
        });

    }

}
</code>```

Which calls our service layer to do the save.

```<code>package com.brookdale.service;

import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;

import com.brookdale.model.RecurringItem;
import com.brookdale.security.bo.User;

public class RecurringItemService {

    public RecurringItemService() { }

    public LazyList<Model> findByAgreementId(Long agreementId, boolean includeAll) {
        if (includeAll)
            return RecurringItem.find("contactAgreementID = ?", agreementId).orderBy("effstartdate desc");
        else
            return RecurringItem.find("contactAgreementID = ? and effenddate is null", agreementId).orderBy("effstartdate desc");
    }
    public RecurringItem saveRecurringItem(RecurringItem ri, User user) {
        ri.saveIt(user);
        return ri;
    }

}
</code>```

Body:
@Override
public Long createPost(Request request) {

    Base.open();

    ObjectMapper mapper = new ObjectMapper();

    try {
        Post newPost  = mapper.readValue(request.body(), Post.class);
//        Map values = ... initialize map
//        newPost.saveIt();

    } catch (IOException ex) {
        Logger.getLogger(PostServiceImpl.class.getName()).log(Level.SEVERE, null, ex);
    }

    Base.close();

    return 1L;
}

From the official docs, this Map values = ... initialize map is not clear. I can do newPost.set("first_name", "Sam") but is there a better way instead of setting values likes this?

Body:
If I'm understanding correctly, you are looking at how to take values from a POST request and then use ActiveJDBC to save those values.   I'm quite new as well and we are in the beginning stages of our app, but we are using SparkJava with ActiveJDBC.

The example is actual code, I didn't have time to simplify it.  But basically we created a POJO for the model class.   We originally extended the org.javalite.activejdbc.Model but we needed to handle audit fields (create, update user/time) and help translate from JSON, so we extended this with a custom class called CecilModel.  But CecilModel extends the Model class.

We have a controller that receives the request.  The request comes in as JSON that matches the field names of our model class.  In our custom CecilModel class we map the JSON to a Map which then we use Model.fromMap method to hyrdrate the fields and puts it into our custom model POJO.   We don't need the getters or setters, it's more for convenience.   We just need our JSON request to have the same names as in our model.

Below is our code but maybe you can peek through it to see how we are doing it.

Our table model pojo.

package com.brookdale.model;

import java.sql.Timestamp;

import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.annotations.BelongsTo;
import org.javalite.activejdbc.annotations.BelongsToParents;
import org.javalite.activejdbc.annotations.IdGenerator;
import org.javalite.activejdbc.annotations.IdName;
import org.javalite.activejdbc.annotations.Table;

import com.brookdale.model.activejdbc.CecilModel;

// This class handles mapping of data from the database to objects
// and back, including custom selection queries.

@Table("RECURRINGITEMSCHEDULE")
@BelongsToParents({
    @BelongsTo(foreignKeyName="itemID",parent=Item.class),
    @BelongsTo(foreignKeyName="contactAgreementID",parent=ContactAgreement.class),
    @BelongsTo(foreignKeyName="unitOfMeasureCode",parent=UnitOfMeasure.class)
})
@IdGenerator("SQ_RECURRINGITEMSCHEDULE.nextVal")
@IdName("recurringItemScheduleID")
public class RecurringItem extends CecilModel {

    public Long getRecurringItemScheduleID() {
        return getLong("recurringItemScheduleID");
    }
    public void setRecurringItemScheduleID(Long recurringItemScheduleID) {
        set("recurringItemScheduleID",recurringItemScheduleID);
    }
    public Long getContactAgreementID() {
        return getLong("contactAgreementID");
    }
    public void setContactAgreementID(Long contactAgreementID) {
        set("contactAgreementID",contactAgreementID);
    }
    public Long getItemID() {
        return getLong("itemID");
    }
    public void setItemID(Long itemID) {
        set("itemID",itemID);
    }
    public Double getUnitChargeAmt() {
        return getDouble("unitChargeAmt");
    }
    public void setUnitChargeAmt(Double unitChargeAmt) {
        set("unitChargeAmt",unitChargeAmt);
    }
    public Integer getUnitQty() {
        return getInteger("unitQty");
    }
    public void setUnitQty(Integer unitQty) {
        set("unitQty",unitQty);
    }
    public String getUnitOfMeasureCode() {
        return getString("unitOfMeasureCode");
    }
    public void setUnitOfMeasureCode(String unitOfMeasureCode) {
        set("unitOfMeasureCode",unitOfMeasureCode);
    }
    public Timestamp getLastGeneratedPeriodEndDate() {
        return getTimestamp("lastGeneratedPeriodEndDate");
    }
    public void setLastGeneratedPeriodEndDate(Timestamp lastGeneratedPeriodEndDate) {
        set("lastGeneratedPeriodEndDate",lastGeneratedPeriodEndDate);
    }
    public Timestamp getEffEndDate() {
        return getTimestamp("effEndDate");
    }
    public void setEffEndDate(Timestamp effEndDate) {
        set("effEndDate",effEndDate);
    }
    public Timestamp getEffStartDate() {
        return getTimestamp("effStartDate");
    }
    public void setEffStartDate(Timestamp effStartDate) {
        set("effStartDate",effStartDate);
    }

    @Override
    public void validate() {
        validatePresenceOf("unitofmeasurecode","itemid","unitqty","effstartdate","unitChargeAmt","contactAgreementID");
        validateNumericalityOf("itemid","unitQty","contactAgreementID");
        // check to make sure this is an update operation
        if (!this.isNew()) {
            RecurringItem ridb = RecurringItem.findById(this.getId());
            if (ridb.getLastGeneratedPeriodEndDate() != null) {
                if (this.getItemID() != ridb.getItemID())
                    this.addError("itemid", "Item can not be updated once a charge has been created.");
                if (!this.getEffStartDate().equals(ridb.getEffStartDate()))
                    this.addError("effstartdate", "Effective start date can not be updated once a charge has been created.");
                if (this.getUnitChargeAmt() != ridb.getUnitChargeAmt())
                    this.addError("unitchargeamt", "Unit charge amount can not be updated after last generated period end date has been set.");
                if (this.getUnitQty() != ridb.getUnitQty())
                    this.addError("unitqty", "Unit quantity can not be updated after last generated period end date has been set.");
                if (!this.getUnitOfMeasureCode().equals(ridb.getUnitOfMeasureCode()))
                    this.addError("", "Unit of measure can not be updated after last generated period end date has been set.");
            }
        }

        if (this.getEffEndDate() != null && this.getEffStartDate().compareTo(this.getEffEndDate()) >= 0) {
            this.addError("effenddate", "Effective end date can not come before the start date.");
        }

    }

}

Extends our custom Model class.  This will extend the actual ActiveJDBC Model class.

package com.brookdale.model.activejdbc;

import java.io.IOException;
import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.ZonedDateTime;
import java.util.Collection;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.type.TypeReference;
import org.javalite.activejdbc.Model;
import org.javalite.activejdbc.validation.ValidationBuilder;
import org.javalite.activejdbc.validation.ValidatorAdapter;

import com.brookdale.core.CLArgs;
import com.brookdale.security.bo.User;

public abstract class CecilModel extends Model {

    private static final transient TypeReference<HashMap<String, Object>> mapType = new TypeReference<HashMap<String, Object>>() {};
    private static final transient TypeReference<LinkedList<HashMap<String, Object>>> listMapType = new TypeReference<LinkedList<HashMap<String, Object>>>() {};
    private static final transient SimpleDateFormat jsonDateFormat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");

    public Timestamp getUpdateDateTime() {
        return getTimestamp("updateDateTime");
    }
    public void setUpdateDateTime(LocalDateTime updateDateTime) {
        set("updateDateTime",updateDateTime == null ? null : Timestamp.valueOf(updateDateTime));
    }
    public Timestamp getCreateDateTime() {
        return getTimestamp("createDateTime");
    }
    public void setCreateDateTime(LocalDateTime createDateTime) {
        set("createDateTime",createDateTime == null ? null : Timestamp.valueOf(createDateTime));
    }
    public String getUpdateUsername() {
        return getString("updateUsername");
    }
    public void setUpdateUsername(String updateUsername) {
        set("updateUsername",updateUsername);
    }
    public String getCreateUsername() {
        return getString("createUsername");
    }
    public void setCreateUsername(String createUsername) {
        set("createUsername",createUsername);
    }
    public Long getUpdateTimeId() {
        return getLong("updateTimeId");
    }
    public void setUpdateTimeId(Long updateTimeId) {
        set("updateTimeId",updateTimeId);
    }

    public boolean save(User user) {
        String userId = (CLArgs.args.isAuthenabled()) ? user.getUserid() : "TEST_MODE";
        // insert
        java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
        if (this.getId() == null || this.getId().toString().equals("0")) {
            this.setId(null);
            this.set("createDateTime", now);
            this.set("createUsername", userId);
            this.set("updateDateTime", now);
            this.set("updateUsername", userId);
            this.set("updateTimeId", 1);
        }
        // update
        else {
            Long updatetimeid = this.getLong("updateTimeid");
            this.set("updateDateTime", now);
            this.set("updateUsername", userId);
            this.set("updateTimeId",  updatetimeid == null ? 1 : updatetimeid + 1);
        }
        return super.save();
    }

    public boolean saveIt(User user) {
        String userId = (CLArgs.args.isAuthenabled()) ? user.getUserid() : "TEST_MODE";
        // insert
        java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
        if (this.isNew()) {
            this.setId(null);
            this.set("createDateTime", now);
            this.set("createUsername", userId);
            this.set("updateDateTime", now);
            this.set("updateUsername", userId);
            this.set("updateTimeId", 1);
        }
        // update
        else {
            Long updatetimeid = this.getLong("updateTimeid");
            this.set("updateDateTime", now);
            this.set("updateUsername", userId);
            this.set("updateTimeId",  updatetimeid == null ? 1 : updatetimeid + 1);
        }
        return super.saveIt();
    }

    public boolean saveModel(User user, boolean insert) {
        if(insert){
            this.insertIt(user);
        }else{
            this.updateIt(user);
        }
        return super.saveIt();
    }

    public boolean insertIt(User user) {
        // insert
        java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
        this.setId(null);
        this.set("createDateTime", now);
        this.set("createUsername", user.getUserid());
        this.set("updateDateTime", now);
        this.set("updateUsername", user.getUserid());
        this.set("updateTimeId", 1);
        return super.saveIt();
    }

    public boolean updateIt(User user) {
        // insert
        java.sql.Timestamp now = java.sql.Timestamp.valueOf(java.time.LocalDateTime.now());
        Long updatetimeid = this.getLong("updateTimeid");
        this.set("updateDateTime", now);
        this.set("updateUsername", user.getUserid());
        this.set("updateTimeId",  updatetimeid == null ? 1 : updatetimeid + 1);
        return super.saveIt();
    }

    // Convert a single ActiveJdbc Object to a json string
    @SuppressWarnings("unchecked")
    public String toJson() {
        Map<String, Object> objMap = this.toMap();
        try {
            if (objMap.containsKey("parents")) {
                Map<String, ?> parentsMap = (Map<String, ?>) objMap.get("parents");
                for (String key: parentsMap.keySet()) {
                    objMap.put(key, parentsMap.get(key));
                }
                objMap.remove("parents");
            }
            if (objMap.containsKey("children")) {
                Map<String, ?> childrenMap = (Map<String, ?>) objMap.get("children");
                for (String key: childrenMap.keySet()) {
                    objMap.put(key, childrenMap.get(key));
                }
                objMap.remove("children");
            }
            ObjectMapper mapper = new ObjectMapper();
            mapper.setDateFormat(jsonDateFormat);
            return mapper.writerWithDefaultPrettyPrinter().writeValueAsString(objMap);
        } catch (Exception e) { throw new RuntimeException(e); }
    }
    // Converts a single json object into an ActiveJdbc Model
    public <T extends CecilModel> T toObj(String json) {
        try {
            Map<String, Object> objMap = toMap(json);
            convertDatesToTimestamp(objMap);
            return this.fromMap(objMap);
        } catch (Exception e) { throw new RuntimeException(e); }
    }

    // STATIC CONVERTERS FOR COLLECTIONS OF OBJECTS
    // Convert an ActiveJdbc LazyList Collection to a JSON string
    public static <T extends Model> String toJson(Collection<T> objCollection) {
        //objCollection.load();
        StringBuffer json = new StringBuffer("[ ");
        for (T obj: objCollection) {
            if (CecilModel.class.isInstance(obj)) {
                json.append(((CecilModel)obj).toJson() + ",");
            } else {
                try {
                    json.append(new ObjectMapper().writeValueAsString(obj));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

        }
        return json.substring(0, json.length()-1) + "]";
    }
    // Converts an array of json objects into a list of ActiveJdbc Models
    public static <T extends Model> List<T> toObjList(String json, Class<T> cls) {
        List<T> results = new LinkedList<T>();
        try {
            List<Map<String, Object>> objMapList = toMaps(json);
            for (Map<String, Object> objMap: objMapList) {
                convertDatesToTimestamp(objMap);
                T obj = cls.newInstance().fromMap(objMap);
                results.add(obj);
            }
        } catch (Exception e) { throw new RuntimeException(e); }
        return results;
    }

    // Converts a single json object into a map of key:value pairs
    private static Map<String, Object> toMap(String json) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json, mapType);
        } catch (IOException e) { throw new RuntimeException(e); }
    }
    // Converts an array of json objects into a list of maps
    private static List<Map<String, Object>> toMaps(String json) {
        ObjectMapper mapper = new ObjectMapper();
        try {
            return mapper.readValue(json, listMapType);
        } catch (IOException e) { throw new RuntimeException(e); }
    }
    // checks for Strings that are formatted in 'yyyy-MM-ddTHH:mm:ss.SSSZ' format
    // if found it will replace the String value with a java.sql.Timestamp value in the objMap
    private static final Map<String,Object> convertDatesToTimestamp(Map<String, Object> objMap) {
        // attempt to convert all dates to java.sql.Timestamp
        for (String key: objMap.keySet()) {
            Object value = objMap.get(key);
            System.out.println("Checking if '" + key + "=" + (value == null ? "null" : value.toString()) +"' is a date...");
            if (value instanceof String && ((String) value).matches("^\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}\\.\\d{3}Z$")) {
                String valuestr = (String) value;
                System.out.println("DATE FOUND FOR '" + key + "' " + value);
                objMap.put(key, Timestamp.valueOf(ZonedDateTime.parse(valuestr).toLocalDateTime()));
            }
        }
        return objMap;
    }

    public static ValidationBuilder<?> validateAbsenceOf(String ... attributes) {
        return validateWith(new ValidatorAdapter() {

            @Override
            public void validate(Model m) {
                boolean containsAttribute = false;

                for(String attribute:attributes) {

                    if(m.attributeNames().contains(attribute)) {
                        //model contains attribute, invalidate now !
                        m.addValidator(this, attribute);
                        break;
                    }
                }
            }
        });
    }
}

Our Controller

package com.brookdale.controller;

import static spark.Spark.get;
import static spark.Spark.post;
import static spark.Spark.put;

import org.codehaus.jackson.map.ObjectMapper;

import com.brookdale.model.RecurringItem;
import com.brookdale.model.activejdbc.CecilModel;
import com.brookdale.security.bo.User;
import com.brookdale.service.RecurringItemService;

public class RecurringItemController {

    public RecurringItemController(final RecurringItemService service) {
        // get list of recurring items based on the agreementid
        get("/api/recurring/list/:agreementid", (req,res)-> {
            String all = req.queryParams("all");
            Long agreementid = Long.parseLong(req.params(":agreementid"));
            //return RecurringItemAPI.searchByAgreement(Long.parseLong(req.params(":agreementid"))).toJson(true);
            return CecilModel.toJson(service.findByAgreementId(agreementid, all != null));

        });
        // insert
        post("/api/recurring/save", (req,res)-> {
            //RecurringItem ri = ActiveJdbcJson.toObj(req.body(), RecurringItem.class);
            RecurringItem ri = new RecurringItem().toObj(req.body());
            // set unitqty to '1' since the field is not nullable, but not used
            if (ri.getUnitQty() == null)
                ri.setUnitQty(1);
            System.out.println("ri to insert: " + new ObjectMapper().writeValueAsString(ri));
            return service.saveRecurringItem(ri, (User) req.attribute("user")).toJson();
        });
        // update
        put("/api/recurring/save", (req,res)-> {
            //RecurringItem ri = ActiveJdbcJson.toObj(req.body(), RecurringItem.class);
            RecurringItem ri = new RecurringItem().toObj(req.body());
            System.out.println("ri to update: " + new ObjectMapper().writeValueAsString(ri));
            return service.saveRecurringItem(ri, (User) req.attribute("user")).toJson();
        });

    }

}

Which calls our service layer to do the save.

package com.brookdale.service;

import org.javalite.activejdbc.LazyList;
import org.javalite.activejdbc.Model;

import com.brookdale.model.RecurringItem;
import com.brookdale.security.bo.User;

public class RecurringItemService {

    public RecurringItemService() { }

    public LazyList<Model> findByAgreementId(Long agreementId, boolean includeAll) {
        if (includeAll)
            return RecurringItem.find("contactAgreementID = ?", agreementId).orderBy("effstartdate desc");
        else
            return RecurringItem.find("contactAgreementID = ? and effenddate is null", agreementId).orderBy("effstartdate desc");
    }
    public RecurringItem saveRecurringItem(RecurringItem ri, User user) {
        ri.saveIt(user);
        return ri;
    }

}


问:
WebBrowser Control Retrieving jQuery Text
I am trying to retrieve whenever the website displays the following message from a jQuery event. Initially this HTML inst displayed in the HTML.

```<code> <div id="toast-container" class="toast-top-right"><div class="toast toast-error" aria-live="assertive" style="display: block;"><div class="toast-message">Check email & password.</div></div></div>
</code>```

My assumption is, that the webBrowser1.DocumentText.Contains is only looking from the initial load of the content.

So I thought maybe some sort of timer would work every 5 seconds, looking to see if the code has changed - but I don't even think this is right as it's checking the code that's already loaded repeatedly?

```<code>    private void timer2_Tick(object sender, EventArgs e)
    {

        // Checks for any errors on sign in page

            if (webBrowser1.DocumentText.Contains("toast toast-error"))
            {
                // Toast Notifications
                var signinErrorNotification = new Notification("Error", "Please check your email and password are correct.", 50, FormAnimator.AnimationMethod.Fade, FormAnimator.AnimationDirection.Left);
                signinErrorNotification.Show();
            }

    }
</code>```

How do I go about getting the latest code that's been affected by any jQuery.

P.S. My c# level is beginner.

答:
The Document property should give you what you need.

Notice that the docs for DocumentText say

Gets or sets the HTML contents of the page displayed in the WebBrowser
  control.

For Document they say

Gets an HtmlDocument representing the Web page currently displayed in the WebBrowser control.

To me that's saying that DocumentText is like the starting document and Document is the current DOM.  Also see https://learn.microsoft.com/en-us/dotnet/framework/winforms/controls/how-to-access-the-managed-html-document-object-model

Body:
I am trying to retrieve whenever the website displays the following message from a jQuery event. Initially this HTML inst displayed in the HTML.

Check email & password.

My assumption is, that the webBrowser1.DocumentText.Contains is only looking from the initial load of the content.

So I thought maybe some sort of timer would work every 5 seconds, looking to see if the code has changed - but I don't even think this is right as it's checking the code that's already loaded repeatedly?

    private void timer2_Tick(object sender, EventArgs e)
    {

        // Checks for any errors on sign in page

            if (webBrowser1.DocumentText.Contains("toast toast-error"))
            {
                // Toast Notifications
                var signinErrorNotification = new Notification("Error", "Please check your email and password are correct.", 50, FormAnimator.AnimationMethod.Fade, FormAnimator.AnimationDirection.Left);
                signinErrorNotification.Show();
            }

    }

How do I go about getting the latest code that's been affected by any jQuery.

P.S. My c# level is beginner.


问:
Python Variables across Class functions - how to call them?
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class?  I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!

```<code>class Test:
    def __init__(self):
        self.root = None
        running_sum = 0

    def test_function(self):
        print(Test.running_sum)
        return

    x = Test()
    x.test_function()
</code>```

Error:

```<code>Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Test:
  File "so.py", line 10, in Test
    x = Test()
NameError: name 'Test' is not defined
</code>```

答:
Use self parameter provided in the method signature.

Note that what you wrote is not a method, but an external function using class Test. To write a method of Test, the def should be at one level of indentation inside class Test as following:

```<code>class Test:
    def __init__(self):
        self.running_sum = 0
    def test_function(self):
        print(self.running_sum)
</code>```

There are several things to add if you want an explanation behind this "best practice".

Assuming you write the following code:

```<code>class Test:
    numbers = []
    def add(self, value):
        self.numbers.append(value)
</code>```

The Test.numbers list is instantiated once and shared accross all instances of Test. Therefore, if 2 different instances add to the list, both act on the same list:

```<code>a = Test()
b = Test()
a.add(5)
b.add(10)
assert a.numbers == b.numbers == Test.numbers
</code>```

When creating instance variables in the __init__ function, __init__ will be run at each instantiation, and therefore, the list will no longer be shared because they will be created for each individual instances.

```<code>class Test:
    def __init__(self):
        self.numbers = []
    def add(self, number):
        self.numbers.append(number)

a = Test()
b = Test()
a.add(5)
b.add(10)
assert a != b
</code>```

Body:
Instead of using a global variable, I'm trying to make an instance of a variable in a class, as it seems to be best practice. How do I reference this variable across other functions in the class?  I would have thought that Test.running_sum would work or at least running_sum in test_function, but I'm not having any luck with either. Thanks very much!

class Test:
    def __init__(self):
        self.root = None
        running_sum = 0

    def test_function(self):
        print(Test.running_sum)
        return

    x = Test()
    x.test_function()

Error:

Traceback (most recent call last):
  File "so.py", line 1, in <module>
    class Test:
  File "so.py", line 10, in Test
    x = Test()
NameError: name 'Test' is not defined

Body:
Use self parameter provided in the method signature.

Note that what you wrote is not a method, but an external function using class Test. To write a method of Test, the def should be at one level of indentation inside class Test as following:

class Test:
    def __init__(self):
        self.running_sum = 0
    def test_function(self):
        print(self.running_sum)

There are several things to add if you want an explanation behind this "best practice".

Assuming you write the following code:

class Test:
    numbers = []
    def add(self, value):
        self.numbers.append(value)

The Test.numbers list is instantiated once and shared accross all instances of Test. Therefore, if 2 different instances add to the list, both act on the same list:

a = Test()
b = Test()
a.add(5)
b.add(10)
assert a.numbers == b.numbers == Test.numbers

When creating instance variables in the __init__ function, __init__ will be run at each instantiation, and therefore, the list will no longer be shared because they will be created for each individual instances.

class Test:
    def __init__(self):
        self.numbers = []
    def add(self, number):
        self.numbers.append(number)

a = Test()
b = Test()
a.add(5)
b.add(10)
assert a != b