问:
Pandas dataframe get index and header when in multiple columns
I have a dataframe which looks like this:

```<code>d = {'id': ['Mc','Web','G','M','F'], 'Person1':['x','x','x',None,None],'Person2':['x',None,'x','x',None], 'Person3':['x',None, None,None, None]}

df = pd.DataFrame(d)
df.set_index('id', inplace=True)

    Person1 Person2 Person3
id
Mc        x       x       x
Web       x    None    None
G         x       x    None
M      None       x    None
F      None    None    None
</code>```

How can I get the id-value and column header if an id appears with more than one person?. For example, the above data frame should give the following dictionary:

{'Mc':[Person1, Person2, Person3], 'G':[Person1, Person2]}

Any help would be very much appreciated.

答:
First filter and create dictionary and then get keys if values are not Nones:

```<code>d = df[df.count(1) > 1].to_dict(orient='index')
print (d)
{'G': {'Person1': 'x', 'Person3': None, 'Person2': 'x'},
'Mc': {'Person1': 'x', 'Person3': 'x', 'Person2': 'x'}}

d1 = {k:[k1 for k1, v1 in v.items() if pd.notnull(v1)] for k,v in d.items()}
print (d1)
{'G': ['Person1', 'Person2'], 'Mc': ['Person1', 'Person3', 'Person2']}
</code>```

Body:
I have a dataframe which looks like this:

d = {'id': ['Mc','Web','G','M','F'], 'Person1':['x','x','x',None,None],'Person2':['x',None,'x','x',None], 'Person3':['x',None, None,None, None]}

df = pd.DataFrame(d)
df.set_index('id', inplace=True)

    Person1 Person2 Person3
id
Mc        x       x       x
Web       x    None    None
G         x       x    None
M      None       x    None
F      None    None    None

How can I get the id-value and column header if an id appears with more than one person?. For example, the above data frame should give the following dictionary:

{'Mc':[Person1, Person2, Person3], 'G':[Person1, Person2]}

Any help would be very much appreciated.

Body:
First filter and create dictionary and then get keys if values are not Nones:

d = df[df.count(1) > 1].to_dict(orient='index')
print (d)
{'G': {'Person1': 'x', 'Person3': None, 'Person2': 'x'},
'Mc': {'Person1': 'x', 'Person3': 'x', 'Person2': 'x'}}

d1 = {k:[k1 for k1, v1 in v.items() if pd.notnull(v1)] for k,v in d.items()}
print (d1)
{'G': ['Person1', 'Person2'], 'Mc': ['Person1', 'Person3', 'Person2']}


来源: stackexchange

问:
Register values from 0x20000000 to 0x20000FFC
I want to read the values of the register starting from 0x20000000 to 0x20000FFC.

Architecture: ARM

Register width: 32 bit

I did following:

```<code>#define REG      0x20000000

unsigned int volatile * const port = (unsigned int *) REG;

for(int i=0; i<4093; i++)
{
    printf("%d", *(port+i));
}
</code>```

Is this the right way?

答:
```<code>#define REG      0x20000000

unsigned int volatile const* port = (unsigned int *) REG;

for(; port < (unsigned int *) REG+0x1000; port++)
    printf("%u", *port);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to read the values of the register starting from 0x20000000 to 0x20000FFC.

Architecture: ARM

Register width: 32 bit

I did following:

#define REG      0x20000000

unsigned int volatile * const port = (unsigned int *) REG;

for(int i=0; i<4093; i++)
{
    printf("%d", *(port+i));
}

Is this the right way?


问:
Multi-Line Dictionary to Single-Line Dictionary
How would you go about converting a multi-line dictionary into one dictionary?

For example, the current dictionary, if printed to the screen, is of the form:

```<code>{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
</code>```

...and so on for over 100 hundred lines. How do you convert this to the following form:

```<code>{'keyword':'value','keyword':'value','keyword':'value','keyword':'value'}
</code>```

答:
Assuming that your initial data is actually a list of dictionaries and your keys are unique accross all your dictionaries I would use something like -

```<code>example = [{'a':1}, {'b':2}, {'c':3}]

objOut = {}
for d in example:
    for k,v in d.iteritems():
        objOut[k] = v
</code>```

OR

```<code>objIn = [{'a':1}, {'b':2}, {'c':3}]

objOut = {}
for d in objIn:
    objOut.update(d)

print objOut
</code>```

Body:
How would you go about converting a multi-line dictionary into one dictionary?

For example, the current dictionary, if printed to the screen, is of the form:

{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}
{'keyword':'value'}

...and so on for over 100 hundred lines. How do you convert this to the following form:

{'keyword':'value','keyword':'value','keyword':'value','keyword':'value'}

Body:
Assuming that your initial data is actually a list of dictionaries and your keys are unique accross all your dictionaries I would use something like -

example = [{'a':1}, {'b':2}, {'c':3}]

objOut = {}
for d in example:
    for k,v in d.iteritems():
        objOut[k] = v

OR

objIn = [{'a':1}, {'b':2}, {'c':3}]

objOut = {}
for d in objIn:
    objOut.update(d)

print objOut


问:
Accessing command line arguments in runtime
I'm using the following Vue SPA boilerplate, which is based on webpack.

When the app is running in the dev server or as a deployed version, I'm able to make use of process.env.NODE_ENV to determine whether if it's a development or production build. So far so good.

What I'm after is a way to pass command line arguments that can be parsed in the same fashion, i.e. npm run dev --foo=1 and fetch it using something like process.argv.slice(2).foo.

I've tried accessing things like accessing the command line arguments using process.argv inside the config files and decorating the config files.

I have also tried passing arguments through "env" --env.foo and changing the node modules export to something like

```<code>module.exports = env => {
    // make use of env
}
</code>```

without success.

Am I missing something obvious?

答:
The usual pattern for this type of thing is to maintain multiple complete configuration files and choose between them when they are loaded, even though it is arguably more concise not to.

I'll also add that while you may want a command-line flags for ergonomic reasons,

```<code>env="foo" npm run dev
</code>```

and

```<code>npm run dev --env=foo
</code>```

are both equally workable in most situations.

Body:
I'm using the following Vue SPA boilerplate, which is based on webpack.

When the app is running in the dev server or as a deployed version, I'm able to make use of process.env.NODE_ENV to determine whether if it's a development or production build. So far so good.

What I'm after is a way to pass command line arguments that can be parsed in the same fashion, i.e. npm run dev --foo=1 and fetch it using something like process.argv.slice(2).foo.

I've tried accessing things like accessing the command line arguments using process.argv inside the config files and decorating the config files.

I have also tried passing arguments through "env" --env.foo and changing the node modules export to something like

module.exports = env => {
    // make use of env
}

without success.

Am I missing something obvious?

Body:
The usual pattern for this type of thing is to maintain multiple complete configuration files and choose between them when they are loaded, even though it is arguably more concise not to.

I'll also add that while you may want a command-line flags for ergonomic reasons,

env="foo" npm run dev

and

npm run dev --env=foo

are both equally workable in most situations.


问:
Casting of `arrayfire::Array`
I'm using the arrayfire crate to open an image with af::load_image. This gives me a f32 array that I can do some processing on. After I am done, I would like to save it as an u8 image using af::save_image:

```<code>extern crate arrayfire as af;

fn main() {
    let im = af::load_image("image".into(), false);
    //let im2: af::Array = im.cast(); // Error: cannot infer type for T
    //let im2: af::Array<DType::U8> = im.cast(); // Error: expected no type arguments
}
</code>```

I can't figure out how to convert the array into a u8 type. I looked into the from method but I have no idea how to use it.

答:
The signature for cast is cast<T: HasAfEnum>(&self) -> Array

Array type doesn't have type parameters. It is the cast method which has one. You need to provide type parameter to the cast method using turbofish syntax ::<_>

let im2 = im.cast::<u8>();

Title: Casting of `arrayfire::Array`

Body:
I'm using the arrayfire crate to open an image with af::load_image. This gives me a f32 array that I can do some processing on. After I am done, I would like to save it as an u8 image using af::save_image:

extern crate arrayfire as af;

fn main() {
    let im = af::load_image("image".into(), false);
    //let im2: af::Array = im.cast(); // Error: cannot infer type for T
    //let im2: af::Array<DType::U8> = im.cast(); // Error: expected no type arguments
}

I can't figure out how to convert the array into a u8 type. I looked into the from method but I have no idea how to use it.


问:
What is the most common or average aspect ratio for mobile devices?
I know aspect ratio's can be defined by the market in question eg. the average aspect ration in India may differ from that of America. But what would you think would be the most common and or average aspect ratio of mobile devices universally speaking?

Does anyone have any stats on mobile devices in different continents?

I'm currently attempting to create the most dynamic media that will present perfectly on the most devices as possible.

EDIT: Media format must be in .jpeg

Thanks in advance,

答: According to appbrain, the samsung galaxy s7 is the most popular device in the united states. Afterwards is the s5, then the s6.</p>


问:
p:fileUpload oncomplete being executed multiple times
I want to allow my users to be able to upload between one and four images.

These images will then be attached to a single email which will be constructed and sent when the files have finished uploading.

The email cannot be sent until all the files have been attached to it.

I am using the fileUpload component in multiple mode to get the files from the user and I had hoped that I could use the oncomplete attribute in the fileUpload component to do this but it seems that this is invoked for every file which has been chosen and not when the entire list had been uploaded.

Is there a way to do a callback just once when all the files have finished uploading instead please? I can't seem to find one.

Markup:

```<code>            <p:fileUpload id = "fileChooser"
                          label="Choose File"
                          uploadLabel="Upload File(s)"
                          cancelLabel="Start Again"
                          skinSimple="true"
                          fileUploadListener = "#{MyController.handleFileUpload}"
                          mode = "advanced"
                          dragDropSupport = "false"
                          multiple = "true"
                          update = "@this"
                          sizeLimit = "4000000"
                          fileLimit = "4"
                          allowTypes = "/(\.|\/)(gif|jpe?g|png)$/"
                          oncomplete="#{MyController.uploadCompleted()}" />
</code>```

Bean:

```<code>@Named
@SessionScoped
public class MyBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private List<UploadedFile> uploadedFiles;

    @PostConstruct
    public void init() {
        uploadedFiles = new ArrayList<UploadedFile>();
    }

    public void upload(FileUploadEvent event) {
        uploadedFiles.add(event.getFile());
    }

    public List<UploadedFile> getUploadedFiles() {
        return uploadedFiles;
    }
    public void setUploadedFiles(List<UploadedFile> uploadedFiles) {
        this.uploadedFiles = uploadedFiles;
    }

}
</code>```

Controller:

```<code>@Named
@SessionScoped
public class MyController implements Serializable {

    private static final long serialVersionUID = -261758226698276865L;

    private static final Logger LOG = Logger.getLogger(MyController.class);

    @Inject
    private MyBean myBean;

    // This is hit every single time a file finishes uploading which is unwanted behaviour.
    public void uploadCompleted() {
        LOG.info("Uploading finished, Number of files:" + myBean.getUploadedFiles().size());
    }

    public void handleFileUpload(FileUploadEvent event) {
        LOG.info("New file upload event passed to event handler");
        LOG.info("File Name :" + event.getFile().getFileName() + " File Size:" + event.getFile().getSize());
        myBean.upload(event);
    }

    public MyBean getMyBean() {
        return uploadNonUKLicenceBean;
    }
    public void setMyBean(MyBean myBean) {
        this.myBean = myBean;
    }

}
</code>```

答:
In case anyone else runs into this, as files are chosen they are added into a list contained in the fileUpload files property, as the files are uploaded then they are removed from this so using p:remoteCommand I've just checked the length of this so that I can call the method I want in my controller when it's empty.

(There was a bug in my original question with the oncomplete attribute which crept in there when I was sanitising the code to post here, I've corrected it in the answer as per the comments).

If there's a better way of doing it I'd love to know.

```<code><p:fileUpload id = "fileChooser"
              label="Choose File"
              uploadLabel="Upload File(s)"
              cancelLabel="Start Again"
              fileUploadListener = "#{nonUKLicenceCheckController.handleFileUpload}"
              mode = "advanced"
              dragDropSupport = "false"
              multiple = "true"
              update = "@this"
              sizeLimit = "4000000"
              fileLimit = "4"
              allowTypes = "/(\.|\/)(gif|jpe?g|png)$/"
              widgetVar="uploadWidget"
              oncomplete="isFileListEmpty(PF('uploadWidget'), uploadsFinished);"
              />
<p:remoteCommand name="uploadsFinished" actionListener="#{nonUKLicenceCheckController.uploadCompleted()}" />
<script type="text/javascript">
    function isFileListEmpty(fileupload, finished) {
    if (fileupload.files.length === 0) {
            if (finished) {
                finished();
            }
        }
    }
</script>
</code>```

Body:
I want to allow my users to be able to upload between one and four images.

These images will then be attached to a single email which will be constructed and sent when the files have finished uploading.

The email cannot be sent until all the files have been attached to it.

I am using the fileUpload component in multiple mode to get the files from the user and I had hoped that I could use the oncomplete attribute in the fileUpload component to do this but it seems that this is invoked for every file which has been chosen and not when the entire list had been uploaded.

Is there a way to do a callback just once when all the files have finished uploading instead please? I can't seem to find one.

Markup:

            <p:fileUpload id = "fileChooser"
                          label="Choose File"
                          uploadLabel="Upload File(s)"
                          cancelLabel="Start Again"
                          skinSimple="true"
                          fileUploadListener = "#{MyController.handleFileUpload}"
                          mode = "advanced"
                          dragDropSupport = "false"
                          multiple = "true"
                          update = "@this"
                          sizeLimit = "4000000"
                          fileLimit = "4"
                          allowTypes = "/(\.|\/)(gif|jpe?g|png)$/"
                          oncomplete="#{MyController.uploadCompleted()}" />

Bean:

@Named
@SessionScoped
public class MyBean implements Serializable {

    private static final long serialVersionUID = 1L;

    private List<UploadedFile> uploadedFiles;

    @PostConstruct
    public void init() {
        uploadedFiles = new ArrayList<UploadedFile>();
    }

    public void upload(FileUploadEvent event) {
        uploadedFiles.add(event.getFile());
    }

    public List<UploadedFile> getUploadedFiles() {
        return uploadedFiles;
    }
    public void setUploadedFiles(List<UploadedFile> uploadedFiles) {
        this.uploadedFiles = uploadedFiles;
    }

}

Controller:

@Named
@SessionScoped
public class MyController implements Serializable {

    private static final long serialVersionUID = -261758226698276865L;

    private static final Logger LOG = Logger.getLogger(MyController.class);

    @Inject
    private MyBean myBean;

    // This is hit every single time a file finishes uploading which is unwanted behaviour.
    public void uploadCompleted() {
        LOG.info("Uploading finished, Number of files:" + myBean.getUploadedFiles().size());
    }

    public void handleFileUpload(FileUploadEvent event) {
        LOG.info("New file upload event passed to event handler");
        LOG.info("File Name :" + event.getFile().getFileName() + " File Size:" + event.getFile().getSize());
        myBean.upload(event);
    }

    public MyBean getMyBean() {
        return uploadNonUKLicenceBean;
    }
    public void setMyBean(MyBean myBean) {
        this.myBean = myBean;
    }

}

Body:
In case anyone else runs into this, as files are chosen they are added into a list contained in the fileUpload files property, as the files are uploaded then they are removed from this so using p:remoteCommand I've just checked the length of this so that I can call the method I want in my controller when it's empty.

(There was a bug in my original question with the oncomplete attribute which crept in there when I was sanitising the code to post here, I've corrected it in the answer as per the comments).

If there's a better way of doing it I'd love to know.

<p:fileUpload id = "fileChooser"
              label="Choose File"
              uploadLabel="Upload File(s)"
              cancelLabel="Start Again"
              fileUploadListener = "#{nonUKLicenceCheckController.handleFileUpload}"
              mode = "advanced"
              dragDropSupport = "false"
              multiple = "true"
              update = "@this"
              sizeLimit = "4000000"
              fileLimit = "4"
              allowTypes = "/(\.|\/)(gif|jpe?g|png)$/"
              widgetVar="uploadWidget"
              oncomplete="isFileListEmpty(PF('uploadWidget'), uploadsFinished);"
              />
<p:remoteCommand name="uploadsFinished" actionListener="#{nonUKLicenceCheckController.uploadCompleted()}" />
<script type="text/javascript">
    function isFileListEmpty(fileupload, finished) {
    if (fileupload.files.length === 0) {
            if (finished) {
                finished();
            }
        }
    }
</script>


问:
Sending a file over TCP sockets in Python
I've successfully been able to copy the file contents (image) to a new file. However when I try the same thing over TCP sockets I'm facing issues. The server loop is not exiting. The client loop exits when it reaches the EOF, however the server is unable to recognize EOF.

Here's the code:

Server

```<code>import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.
s.bind((host, port))        # Bind to the port
f = open('torecv.png','wb')
s.listen(5)                 # Now wait for client connection.
while True:
    c, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    print "Receiving..."
    l = c.recv(1024)
    while (l):
        print "Receiving..."
        f.write(l)
        l = c.recv(1024)
    f.close()
    print "Done Receiving"
    c.send('Thank you for connecting')
    c.close()                # Close the connection
</code>```

Client

```<code>import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.

s.connect((host, port))
s.send("Hello server!")
f = open('tosend.png','rb')
print 'Sending...'
l = f.read(1024)
while (l):
    print 'Sending...'
    s.send(l)
    l = f.read(1024)
f.close()
print "Done Sending"
print s.recv(1024)
s.close                     # Close the socket when done
</code>```

Here's the screenshot:

Server

Client

Edit 1: Extra data copied over. Making the file "not complete."
The first column shows the image that has been received. It seems to be larger than the one sent. Because of this, I'm not able to open the image. It seems like a corrupted file.

Edit 2: This is how I do it in the console. The file sizes are the same here.

答:
Put file inside while True like so

```<code>while True:
     f = open('torecv.png','wb')
     c, addr = s.accept()     # Establish connection with client.
     print 'Got connection from', addr
     print "Receiving..."
     l = c.recv(1024)
     while (l):
         print "Receiving..."
         f.write(l)
         l = c.recv(1024)
     f.close()
     print "Done Receiving"
     c.send('Thank you for connecting')
     c.close()
</code>```

Body:
I've successfully been able to copy the file contents (image) to a new file. However when I try the same thing over TCP sockets I'm facing issues. The server loop is not exiting. The client loop exits when it reaches the EOF, however the server is unable to recognize EOF.

Here's the code:

Server

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.
s.bind((host, port))        # Bind to the port
f = open('torecv.png','wb')
s.listen(5)                 # Now wait for client connection.
while True:
    c, addr = s.accept()     # Establish connection with client.
    print 'Got connection from', addr
    print "Receiving..."
    l = c.recv(1024)
    while (l):
        print "Receiving..."
        f.write(l)
        l = c.recv(1024)
    f.close()
    print "Done Receiving"
    c.send('Thank you for connecting')
    c.close()                # Close the connection

Client

import socket               # Import socket module

s = socket.socket()         # Create a socket object
host = socket.gethostname() # Get local machine name
port = 12345                 # Reserve a port for your service.

s.connect((host, port))
s.send("Hello server!")
f = open('tosend.png','rb')
print 'Sending...'
l = f.read(1024)
while (l):
    print 'Sending...'
    s.send(l)
    l = f.read(1024)
f.close()
print "Done Sending"
print s.recv(1024)
s.close                     # Close the socket when done

Here's the screenshot:

Server

Client

Edit 1: Extra data copied over. Making the file "not complete."
The first column shows the image that has been received. It seems to be larger than the one sent. Because of this, I'm not able to open the image. It seems like a corrupted file.

Edit 2: This is how I do it in the console. The file sizes are the same here.

Body:
Put file inside while True like so

while True:
     f = open('torecv.png','wb')
     c, addr = s.accept()     # Establish connection with client.
     print 'Got connection from', addr
     print "Receiving..."
     l = c.recv(1024)
     while (l):
         print "Receiving..."
         f.write(l)
         l = c.recv(1024)
     f.close()
     print "Done Receiving"
     c.send('Thank you for connecting')
     c.close()


问:
Make an algorithm start again?
So I'm pretty new to coding with Java (started yesterday). What I am trying to do is to make an Input of an Integer, if the int c it is higher than 1 or lower than 0 (if it is not 1 or 0), I want it to start again. If int c equals either 1 or 0, I want the alogrithm to continue. I tried to insert some kind of loops after if(c > 1 || c < 0) but it does not seem to work and only spams my console with the result. Is there any easy way to make the algorithm start over again? I'm already trying to fix this for more than 2 hours, but I'm just confusing me over and over again.

```<code>// more code up here but it is unimportant
int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant
</code>```

答:
You can put your code in a function (which I hope is already the case) and then when you don't have the expected result and want to call it again, just do so by calling your function inside itself.

It's called recursion.
You can learn more here .
For example :

```<code>// more code up here but it is unimportant
public void myFunction(){
    int c = sc.nextInt();
    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant
    }
    //You want to call your function again
    myFunction();
}
</code>```

Title: Make an algorithm start again?

Body:
So I'm pretty new to coding with Java (started yesterday). What I am trying to do is to make an Input of an Integer, if the int c it is higher than 1 or lower than 0 (if it is not 1 or 0), I want it to start again. If int c equals either 1 or 0, I want the alogrithm to continue. I tried to insert some kind of loops after if(c > 1 || c < 0) but it does not seem to work and only spams my console with the result. Is there any easy way to make the algorithm start over again? I'm already trying to fix this for more than 2 hours, but I'm just confusing me over and over again.

// more code up here but it is unimportant
int c = sc.nextInt();

    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant

Body:
You can put your code in a function (which I hope is already the case) and then when you don't have the expected result and want to call it again, just do so by calling your function inside itself.

It's called recursion.
You can learn more here .
For example :

// more code up here but it is unimportant
public void myFunction(){
    int c = sc.nextInt();
    if(c > 1 || c < 0) {
        result = result + wrong;
        System.out.println(result);
    } else if (c == 1) {
        result = result + notImplemented;
        System.out.println(result);
    } else if (c == 0) { //more code follows here but is unimportant
    }
    //You want to call your function again
    myFunction();
}


答:
I found that every Android device had one of the following aspect ratios (from most square to most rectangular):

4:3

3:2

8:5

5:3

16:9

And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)

Title: What is the most common or average aspect ratio for mobile devices?

Body:
I know aspect ratio's can be defined by the market in question eg. the average aspect ration in India may differ from that of America. But what would you think would be the most common and or average aspect ratio of mobile devices universally speaking?

Does anyone have any stats on mobile devices in different continents?

I'm currently attempting to create the most dynamic media that will present perfectly on the most devices as possible.

EDIT: Media format must be in .jpeg

Thanks in advance,


问:
Socket.io with AWS elastic load balancer
I haven't really found a good solution to Websocket, socket.io connection with Elastic Load Balancer using Elastic Beanstalk running on node.js. Anyone has a good set up on how to scale node.js with socket.io implementation

Here are some question:
if we use a load balancer with tcp listener, how can the socket.io establish the connection with https?

Really appreciate anyone who has tried this implementation setup to give some insights :)
Cheers

答:
Now-a-days there's socket.io-redis

https://github.com/socketio/socket.io-redis


问:
Send both POST and GET in a form
I need to make a form send both POST and GET requests (due to some bugs in IE and iframes), how can you do so?

The data being sent is nothing mega secure so it doesn't matter if it can be set via GET, just need to make sure it is set both ways.

Thanks for the help!

答:
Easy: Just specify the GET data in the form URL.

```<code><form method="POST" action="form.php?a=1&b=2&c=3">
</code>```

however, very carefully check how the data is used in the receiving script. Don't use $_REQUEST- rather parse $_GET and $_POST according to your exact needs and in the priority order you need them.

ContentLicense: CC BY-SA 2.5

Title: Send both POST and GET in a form

Body:
Easy: Just specify the GET data in the form URL.

<form method="POST" action="form.php?a=1&b=2&c=3">

however, very carefully check how the data is used in the receiving script. Don't use $_REQUEST- rather parse $_GET and $_POST according to your exact needs and in the priority order you need them.


问:
Cannot assign foreign key with item ID
I am trying to auto assign a value to a foreign key, so that the model is automatically associated with another model. This is done when an entry is made by a form. I get the following error

```<code>ValueError at /nodiso/createaction/23/
Cannot assign "'23'": "LeadActions.lead" must be a "Leads" instance.
</code>```

This is the two models:

```<code>class Leads(models.Model):
    company = models.ManyToManyField(Company)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=265)
    email = models.EmailField(max_length=265)
    tel = models.IntegerField()
    dateenq = models.DateField(auto_now_add=True,null=True)

    def get_absolute_url(self):
      return reverse('nodisoapp:leadlist')

    def __str__(self):
       return self.name

class LeadActions(models.Model):
    lead = models.ForeignKey(Leads)
    name = models.CharField(max_length=265)
    crdate = models.DateField(auto_now_add=True)
    Duedate = models.DateField()
    creator = models.CharField(max_length=265)
    overdue = models.IntegerField(null=True,blank=True)

    def get_absolute_url(self):
      return reverse('nodisoapp:leadlist')

    def __str__(self):
      return self.name
</code>```

This is the View

```<code>class ActionCreateView(LoginRequiredMixin, generic.CreateView):
    login_url = '/scrty/login/'
    template_name = "nodiso/actioncreate.html"
    form_class = forms.LeadActionCreateForm
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.lead = self.kwargs['pk']
        self.object.creator = self.request.user
        self.object.save()
        return super(LeadCreateView, self).form_valid(form)
</code>```

This is the model form

```<code>class LeadActionCreateForm(forms.ModelForm):
    class Meta:
        model = models.LeadActions
        fields = ['name','Duedate']
</code>```

I would appreciate the help.

答:
Instead of

```<code>self.object.lead = self.kwargs['pk']
</code>```

try doing

```<code>lead_id = int(self.kwargs['pk'])
self.object.lead = Lead.objects.get(pk=lead_id)
</code>```

When using the field name to assign relationship fields in Django, you must pass a model instance not a primary key. You could also use the primary key by doing:

```<code>lead_id = int(self.kwargs['pk'])
self.object.lead_id = lead_id
</code>```

Title: Cannot assign foreign key with item ID

Body:
I am trying to auto assign a value to a foreign key, so that the model is automatically associated with another model. This is done when an entry is made by a form. I get the following error

ValueError at /nodiso/createaction/23/
Cannot assign "'23'": "LeadActions.lead" must be a "Leads" instance.

This is the two models:

class Leads(models.Model):
    company = models.ManyToManyField(Company)
    user = models.ManyToManyField(settings.AUTH_USER_MODEL)
    name = models.CharField(max_length=265)
    email = models.EmailField(max_length=265)
    tel = models.IntegerField()
    dateenq = models.DateField(auto_now_add=True,null=True)

    def get_absolute_url(self):
      return reverse('nodisoapp:leadlist')

    def __str__(self):
       return self.name

class LeadActions(models.Model):
    lead = models.ForeignKey(Leads)
    name = models.CharField(max_length=265)
    crdate = models.DateField(auto_now_add=True)
    Duedate = models.DateField()
    creator = models.CharField(max_length=265)
    overdue = models.IntegerField(null=True,blank=True)

    def get_absolute_url(self):
      return reverse('nodisoapp:leadlist')

    def __str__(self):
      return self.name

This is the View

class ActionCreateView(LoginRequiredMixin, generic.CreateView):
    login_url = '/scrty/login/'
    template_name = "nodiso/actioncreate.html"
    form_class = forms.LeadActionCreateForm
    def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.lead = self.kwargs['pk']
        self.object.creator = self.request.user
        self.object.save()
        return super(LeadCreateView, self).form_valid(form)

This is the model form

class LeadActionCreateForm(forms.ModelForm):
    class Meta:
        model = models.LeadActions
        fields = ['name','Duedate']

I would appreciate the help.

Body:
Instead of

self.object.lead = self.kwargs['pk']

try doing

lead_id = int(self.kwargs['pk'])
self.object.lead = Lead.objects.get(pk=lead_id)

When using the field name to assign relationship fields in Django, you must pass a model instance not a primary key. You could also use the primary key by doing:

lead_id = int(self.kwargs['pk'])
self.object.lead_id = lead_id


问:
The best way to implement showing "No Connection" message throughout the app
I'm developing the application-messenger and need to  show dynamically "No Connection" message in case of lack of Internet, like in popular messengers (Viber, etc).

It should look like the narrow strip below the Action Bar or below the tabs.
What is the best way to add such view dynamically? Is it custom SnackBar or PopupWindow?

答:
You can use this:

```<code>compile 'com.androidadvance:topsnackbar:1.1.1'
</code>```

then in the code add this example:

```<code>TSnackbar.make(findViewById(android.R.id.content),"no internet connection",TSnackbar.LENGTH_LONG).show();
</code>```

This is the library for the above, it adds snackbars under toolbars:

https://github.com/AndreiD/TSnackBar

Body:
You can use this:

compile 'com.androidadvance:topsnackbar:1.1.1'

then in the code add this example:

TSnackbar.make(findViewById(android.R.id.content),"no internet connection",TSnackbar.LENGTH_LONG).show();

This is the library for the above, it adds snackbars under toolbars:

https://github.com/AndreiD/TSnackBar


问:
Does TestCafe fit into BDD and cucumber?
I understand TestCafe attempts to replace Webdriver based test frameworks like Selenium. I couldn't find examples of integration with BDD (cucumber) yet.</p>

答: You can find a demonstration of integration TestCafe into CucumberJS tests in the testcafe-cucumber-demo GitHub repository.</p>


问:
How can I use ng-bind-html inside my directive?
I'm using templates based on my JSON. So, I can't really use my ng-bind-html like I would normally do.

Seems like the only option I have is to use my sanitized html inside an directive.
Looking for similar questions, I couldn't figure it out how to apply in my case.
Yes, I am pretty newbie into angular.

I'm currently receiving this data from my controller:

```<code>$scope.safecontainers = $sanitize($scope.containersmsg);
</code>```

In my html would normally be like this:

```<code><p ng-bind-html="containersmsg"></p>
</code>```

But I don't want this, I need to use this ng-bind-html inside a directive!

Some people have talked about $compile, but I couldn't really figure it out how to apply in my case.

EDIT:

Based on comments, i'll add more code to help you guys further understand my goal.

Inside my index.html I'm declaring the controllers needed and calling my

```<code><ng-view></ng-view>
</code>```

Then, based on what I receive, i'll load one view or another:

```<code>      <div ng-if='setores[0].SetorTema == "1"'>
        <theme-one titulo="{{setores[0].SetorNome}}" logo="
            {{setores[0].SetorLogo}}" evento="{{evento[0].EventoNome}}">
        </theme-one>
 // I omitted some of the parameters because they ain't relevant
      </div>
</code>```

My template is like this: (Just a little part of it to avoid much useless code)

```<code>  <section class="target">
    <div class="col-md-6 col-xs-12">
        <div class="" ng-repeat="banner in title">
            <div class="target-title">{{ banner.BannerLevelTitulo }}
            </div>
            <div class="target-desc">{{banner.BannerLevelDescricao}}</div>
        </div>
    </div>
    <div class="col-md-6 col-xs-hidden">
        <div class="target-image"><img ng-src="{{targetimage}}" alt="">
        </div>
    </div>
</section>
</code>```

This is the controller I want my sanitized code.

```<code>hotsite.controller('containerController', function($scope, $http, $sanitize)
{

$scope.containers = [];
$scope.containersmsg = '';
$scope.safecontainers = $sanitize($scope.containersmsg);

$http.get('/Admin/rest/getContainer')
.then(function onSuccess(response) {
    var data = response.data;
    $scope.containers = data;

      $scope.containers = response.data.filter(containers =>
containers.ContainerAtivo);
      $scope.containersmsg = $scope.containers[0].ContainerDesc;
  })
 .catch(function onError(response) {
    var data = response.data;
    console.log(data);
  });
});
</code>```

This is a piece of my directive:

```<code>    angular.module('hotsiteDirectives', [])
.directive('themeOne', function($compile) {
  var ddo = {};

     ddo.restrict = "AE";
     ddo.transclude = true;

     ddo.scope = {
         titulo: '@',
         ...
         (a lot of other scope's)
         contimg: '@'
     };

     ddo.templateUrl = 'app/directives/theme-one.html';

     return ddo;
 })
</code>```

And yes, I am calling the ngSanitize

```<code>var hotsite = angular.module('hotsite',['ngRoute', 'hotsiteDirectives',
'ngSanitize']);
</code>```

TL;DR

This is how my code looks like inside a directive, with raw html and not rendered:

This is how it works with ng-bind-html, formatted html

If I do put this inside my view

```<code>    <p ng-bind-html="containersmsg"></p>
</code>```

It will be alright, all of it working like it should.

BUT, I need to call this only inside my directive, and I don't know how to do it.
So, with this context:

How can I put my sanitized html inside my directive and template?

答:
You don't even have to trust the html to render it using ngBindHtml because the directive already does it for you. You basically need to create a parameter attribute for your directive to hold the html string, so, inside the directive's template, you use ng-bind-html="myParam".

The following snippet implements a simple demonstration of creating a directive that receives and renders an html input parameter that comes from a controller.

angular.module('app', ['ngSanitize'])
  .controller('AppCtrl', function($scope) {
    $scope.myHtml = '
Hello! I\'m an html string being rendered dynamicalli by ngBindHtml
';
  })
  .directive('myDirective', function() {
    return {
      template: '

',
      scope: {
        html: '='
      }
    };
  });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div ng-app="app" ng-controller="AppCtrl">
  <my-directive html="myHtml"></my-directive>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-sanitize.js"></script></code>```

Body:
I'm using templates based on my JSON. So, I can't really use my ng-bind-html like I would normally do.

Seems like the only option I have is to use my sanitized html inside an directive.
Looking for similar questions, I couldn't figure it out how to apply in my case.
Yes, I am pretty newbie into angular.

I'm currently receiving this data from my controller:

$scope.safecontainers = $sanitize($scope.containersmsg);

In my html would normally be like this:

But I don't want this, I need to use this ng-bind-html inside a directive!

Some people have talked about $compile, but I couldn't really figure it out how to apply in my case.

EDIT:

Based on comments, i'll add more code to help you guys further understand my goal.

Inside my index.html I'm declaring the controllers needed and calling my

<ng-view></ng-view>

Then, based on what I receive, i'll load one view or another:

        <theme-one titulo="{{setores[0].SetorNome}}" logo="
            {{setores[0].SetorLogo}}" evento="{{evento[0].EventoNome}}">
        </theme-one>
 // I omitted some of the parameters because they ain't relevant

My template is like this: (Just a little part of it to avoid much useless code)

{{ banner.BannerLevelTitulo }}

{{banner.BannerLevelDescricao}}

This is the controller I want my sanitized code.

hotsite.controller('containerController', function($scope, $http, $sanitize)
{

$scope.containers = [];
$scope.containersmsg = '';
$scope.safecontainers = $sanitize($scope.containersmsg);

$http.get('/Admin/rest/getContainer')
.then(function onSuccess(response) {
    var data = response.data;
    $scope.containers = data;

      $scope.containers = response.data.filter(containers =>
containers.ContainerAtivo);
      $scope.containersmsg = $scope.containers[0].ContainerDesc;
  })
 .catch(function onError(response) {
    var data = response.data;
    console.log(data);
  });
});

This is a piece of my directive:

    angular.module('hotsiteDirectives', [])
.directive('themeOne', function($compile) {
  var ddo = {};

     ddo.restrict = "AE";
     ddo.transclude = true;

     ddo.scope = {
         titulo: '@',
         ...
         (a lot of other scope's)
         contimg: '@'
     };

     ddo.templateUrl = 'app/directives/theme-one.html';

     return ddo;
 })

And yes, I am calling the ngSanitize

var hotsite = angular.module('hotsite',['ngRoute', 'hotsiteDirectives',
'ngSanitize']);

TL;DR

This is how my code looks like inside a directive, with raw html and not rendered:

This is how it works with ng-bind-html, formatted html

If I do put this inside my view

It will be alright, all of it working like it should.

BUT, I need to call this only inside my directive, and I don't know how to do it.
So, with this context:

How can I put my sanitized html inside my directive and template?

Body:
You don't even have to trust the html to render it using ngBindHtml because the directive already does it for you. You basically need to create a parameter attribute for your directive to hold the html string, so, inside the directive's template, you use ng-bind-html="myParam".

The following snippet implements a simple demonstration of creating a directive that receives and renders an html input parameter that comes from a controller.

angular.module('app', ['ngSanitize'])
  .controller('AppCtrl', function($scope) {
    $scope.myHtml = '<div><b>Hello!</b> I\'m an <i>html string</i> being rendered dynamicalli by <code>ngBindHtml</code></div>';
  })
  .directive('myDirective', function() {
    return {
      template: '<hr><div ng-bind-html="html"></div><hr>',
      scope: {
        html: '='
      }
    };
  });

<div ng-app="app" ng-controller="AppCtrl">
  <my-directive html="myHtml"></my-directive>
</div>

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.0/angular-sanitize.js"></script>


问:
flex 3 getting webserice call to wait for result
i have a function which retrieves values from a webservice , then loops through the returned values and for each returned value does another webservice lookup.

Im having a problem however that when i make the second webservice call within the for loop that the function does not wait for the reuslt and just keeps processing and in turn giving me no value

the code looks like this;

```<code>    private function getResult(e:ResultEvent):void{

   var lengthOfResult:int = e.result.length;
   var arrayCollResults:ArrayCollection = new ArrayCollection();
   var resultArray:Array = new Array(e.result);

       for(var i:int = 0 ; i < lengthOfResult; i++){
      var currentName:String = e.result[i].toString();
      arrayCollResults.addItem(e.result[i] + ws.getMatches(currentName));
   }

   acu.dataProvider = arrayCollResults;
   }
</code>```

what can i do to insure that the value of ws.getMatches(currentName) actually returns a value before moving to next line?

答:
The documentation here indicates that you do not call the Web service directly, you need to set up an event listener and handle the response on completed delivery.

From the section "Calling web services in ActionScript":

```<code><?xml version="1.0"?>
<!-- fds\rpc\WebServiceInAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script>
        <![CDATA[
        import mx.rpc.soap.WebService;
        import mx.rpc.events.ResultEvent;
        import mx.rpc.events.FaultEvent;
        private var ws:WebService;
        public function useWebService(intArg:int, strArg:String):void {
            ws = new WebService();
            ws.destination = "echoArgService";
            ws.echoArgs.addEventListener("result", echoResultHandler);
            ws.addEventListener("fault", faultHandler);
            ws.loadWSDL();
            ws.echoArgs(intArg, strArg);
        }

        public function echoResultHandler(event:ResultEvent):void {
            var retStr:String = event.result.echoStr;
            var retInt:int = event.result.echoInt;
         //Do something.
        }

        public function faultHandler(event:FaultEvent):void {
      //deal with event.fault.faultString, etc
        }
        ]]>
    </mx:Script>
</mx:Application>
</code>```

Put the "arrayCollResults.addItem(...)" segment in the result handler for your ws.getMatches() event.

OwnerDisplayName: luckoftheirish

Body:
i have a function which retrieves values from a webservice , then loops through the returned values and for each returned value does another webservice lookup.

Im having a problem however that when i make the second webservice call within the for loop that the function does not wait for the reuslt and just keeps processing and in turn giving me no value

the code looks like this;

    private function getResult(e:ResultEvent):void{

   var lengthOfResult:int = e.result.length;
   var arrayCollResults:ArrayCollection = new ArrayCollection();
   var resultArray:Array = new Array(e.result);

       for(var i:int = 0 ; i < lengthOfResult; i++){
      var currentName:String = e.result[i].toString();
      arrayCollResults.addItem(e.result[i] + ws.getMatches(currentName));
   }

   acu.dataProvider = arrayCollResults;
   }

what can i do to insure that the value of ws.getMatches(currentName) actually returns a value before moving to next line?

Body:
The documentation here indicates that you do not call the Web service directly, you need to set up an event listener and handle the response on completed delivery.

From the section "Calling web services in ActionScript":

<?xml version="1.0"?>
<!-- fds\rpc\WebServiceInAS.mxml -->
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml">
    <mx:Script>
        <![CDATA[
        import mx.rpc.soap.WebService;
        import mx.rpc.events.ResultEvent;
        import mx.rpc.events.FaultEvent;
        private var ws:WebService;
        public function useWebService(intArg:int, strArg:String):void {
            ws = new WebService();
            ws.destination = "echoArgService";
            ws.echoArgs.addEventListener("result", echoResultHandler);
            ws.addEventListener("fault", faultHandler);
            ws.loadWSDL();
            ws.echoArgs(intArg, strArg);
        }

        public function echoResultHandler(event:ResultEvent):void {
            var retStr:String = event.result.echoStr;
            var retInt:int = event.result.echoInt;
         //Do something.
        }

        public function faultHandler(event:FaultEvent):void {
      //deal with event.fault.faultString, etc
        }
        ]]>
    </mx:Script>
</mx:Application>

Put the "arrayCollResults.addItem(...)" segment in the result handler for your ws.getMatches() event.

OwnerDisplayName: seanhodges


问:
How does Firebase app start time profiling work on Android?
I noticed that Firebase Performance Monitoring does provide some automatic traces out of the box.
In particular I was looking at the cold app start time trace which is exactly what I need to do right now.
Unfortunately I need to do have more granular data, so I was thinking I could do it on my own, but so far I failed to come up with a reasonable how to measure a true cold start time of an Android app (think time between tapping an icon in launcher and seeing the UI of given Activity).

The docs says, that Firebase starts the trace when FirebasePerfProvider.onCreate callback gets called. As far as I know this should happen very soon after the application process starts, so that's good, but it also means that it gets called even when the app just receives a notification (or some broadcast in general) and at that point the process might not be terminated by the time the user actually opens the app. That means it'd measure the duration wrong.

Given the SDK is not (yet?) open sourced, I could not find a better description of how this works.

Does anybody know more?

答:
If the Android process is launched via a Service or BroadcastReceiver, no trace is started.  So, if and when an Activity is actually started in that process, there will be no problems with an app start trace that could appear to be very long.  The app start trace only happens if the process is invoked by an Activity.

I've updated the documentation to include this fact, and that change should be published soon.


问:
mysql running total, order by date
I have been trying to do a running total "order by date". The problem is that if you have two entries with the same date, then it shows the same total on both rows.

Table structure is something like this

```<code>sipID|Date|Amount
1|2017-11-07|2
2|2017-11-09|27
3|2017-11-07|24
</code>```

So I know how to do a running total by id like this.

```<code>SELECT `sipID`,DATE_FORMAT(`Date`,'%d %M %Y') as `DateFormat`,`Amount`,
(SELECT SUM(`Amount`) FROM `salesinvoice_payments` as `Lin` WHERE `Lin`.`sipID`<=`Lout`.`sipID` && `salesinvoice_id`=115) as `Balance`
FROM `salesinvoice_payments` as `Lout`
WHERE `salesinvoice_id`=115
ORDER BY `sipID`
</code>```

But I wanted it to be ordered by date ascending so I did this

```<code>SELECT `sipID`,DATE_FORMAT(`Date`,'%d %M %Y') as `DateFormat`,`Amount`,
(SELECT SUM(`Amount`) FROM `salesinvoice_payments` as `Lin` WHERE `Lin`.`Date`<=`Lout`.`Date` && `salesinvoice_id`=115) as `Balance`
FROM `salesinvoice_payments` as `Lout`
WHERE `salesinvoice_id`=115
ORDER BY `Date` ASC
</code>```

Now this does work. The problem happens when you have 2 rows with the same date. What happens then is that both rows have the same running total.
eg

```<code>07 November 2017    2.00    24.00
07 November 2017    22.00   24.00
09 November 2017    3.00    27.00
</code>```

What I want is this

```<code>07 November 2017    2.00    2.00
07 November 2017    22.00   24.00
09 November 2017    3.00    27.00
</code>```

Is there a workaround so that I can have a proper running total, and have it ordered by date without it getting the same total on the same date?

EDIT:
@Strawberry:
I have finally worked out how sqlfiddle works, and put this for my original question.
http://www.sqlfiddle.com/#!9/c6dc75/1

答:
You need something to separate Ammount from same day.

SQL DEMO

```<code>SELECT `sipID`,
        DATE_FORMAT(`Date`,'%d %M %Y') as `DateFormat`,
        `Amount`,
         (SELECT SUM(`Amount`)
          FROM `salesinvoice_payments` as `Lin`
          WHERE `Lin`.`Date` < `Lout`.`Date`
            OR  (`Lin`.`Date` = `Lout`.`Date`
                 AND `Lin`.`sipID` <= `Lout`.`sipID`)
          ) as `Balance`
FROM `salesinvoice_payments` as `Lout`
ORDER BY `Date` ASC
</code>```

OUTPUT

Title: mysql running total, order by date

Body:
I have been trying to do a running total "order by date". The problem is that if you have two entries with the same date, then it shows the same total on both rows.

Table structure is something like this

sipID|Date|Amount
1|2017-11-07|2
2|2017-11-09|27
3|2017-11-07|24

So I know how to do a running total by id like this.

SELECT `sipID`,DATE_FORMAT(`Date`,'%d %M %Y') as `DateFormat`,`Amount`,
(SELECT SUM(`Amount`) FROM `salesinvoice_payments` as `Lin` WHERE `Lin`.`sipID`<=`Lout`.`sipID` && `salesinvoice_id`=115) as `Balance`
FROM `salesinvoice_payments` as `Lout`
WHERE `salesinvoice_id`=115
ORDER BY `sipID`

But I wanted it to be ordered by date ascending so I did this

SELECT `sipID`,DATE_FORMAT(`Date`,'%d %M %Y') as `DateFormat`,`Amount`,
(SELECT SUM(`Amount`) FROM `salesinvoice_payments` as `Lin` WHERE `Lin`.`Date`<=`Lout`.`Date` && `salesinvoice_id`=115) as `Balance`
FROM `salesinvoice_payments` as `Lout`
WHERE `salesinvoice_id`=115
ORDER BY `Date` ASC

Now this does work. The problem happens when you have 2 rows with the same date. What happens then is that both rows have the same running total.
eg

07 November 2017    2.00    24.00
07 November 2017    22.00   24.00
09 November 2017    3.00    27.00

What I want is this

07 November 2017    2.00    2.00
07 November 2017    22.00   24.00
09 November 2017    3.00    27.00

Is there a workaround so that I can have a proper running total, and have it ordered by date without it getting the same total on the same date?

EDIT:
@Strawberry:
I have finally worked out how sqlfiddle works, and put this for my original question.
http://www.sqlfiddle.com/#!9/c6dc75/1

Body:
You need something to separate Ammount from same day.

SQL DEMO

SELECT `sipID`,
        DATE_FORMAT(`Date`,'%d %M %Y') as `DateFormat`,
        `Amount`,
         (SELECT SUM(`Amount`)
          FROM `salesinvoice_payments` as `Lin`
          WHERE `Lin`.`Date` < `Lout`.`Date`
            OR  (`Lin`.`Date` = `Lout`.`Date`
                 AND `Lin`.`sipID` <= `Lout`.`sipID`)
          ) as `Balance`
FROM `salesinvoice_payments` as `Lout`
ORDER BY `Date` ASC

OUTPUT


问:
java.lang.SecurityException: Failed to find provider questions for user 0; expected to find a valid ContentProvider
I am using se.emilsjolander:sprinkles:1.3.1 library for saving data to my database. When I upgraded to oreo sdk 26, getting an error saying that there should be a valid content provider. I didn't get how to implement it with my library. Can anybody make this clear for me? I am adding the stack here.</p>

```<code> java.lang.SecurityException: Failed to find provider questions f user 0; expected to find a valid ContentProvider for this authority 10-31
</code>```

答:
Before API level 26, you could provide a stub ContentProvider with no functionality, now some minimal functionality is mandatory.
See https://developer.android.com/about/versions/oreo/android-8.0-changes.html#ccn

Android 8.0 (API level 26) changes how ContentResolver.notifyChange() and registerContentObserver(Uri, boolean, ContentObserver) behave for apps targeting Android 8.0.

These APIs now require that a valid ContentProvider is defined for the authority in all Uris. Defining a valid ContentProvider with relevant permissions will help defend your app against content changes from malicious apps, and prevent you from leaking potentially private data to malicious apps.

Body:
I am using se.emilsjolander:sprinkles:1.3.1 library for saving data to my database. When I upgraded to oreo sdk 26, getting an error saying that there should be a valid content provider. I didn't get how to implement it with my library. Can anybody make this clear for me? I am adding the stack here.

 java.lang.SecurityException: Failed to find provider questions f user 0; expected to find a valid ContentProvider for this authority 10-31

ContentLicense: CC BY-SA 4.0


问:
testing my REPOSITORY layer with DBUnit/Junit, should I manually build scheme or automate it? what's the advantages?
I am thinking on how to design my unit-tests for my java based-repositories and encountering design problems:
Lets assume I have a Consumer table with data related to my consumer:
{ ID, Name, Phone }
And my ConsumerRepository extends BaseRepository which extends JPA repo and supports findByPhone, findByName, findAll queries and save option.

I'm using H2 in-memo DB and DBUnit for those tests, all configured and running and was thinking about this:

When launching data to my in-memory DB, should I be configuring the data with the ConsumerTestData.xml (DBUnit) and manually adding the Consumer data for each test for e.g:

```<code><dataset>
<CONSUMER CONSUMER_ID="1" FIRST_NAME="Elvis" LAST_NAME="Presley" PHONE="+972123456789" EMAIL="elvis@isep.com" CREATION_DATE="2017-08-29"/>
<CONSUMER CONSUMER_ID="2" FIRST_NAME="Bob" LAST_NAME="Dylan" PHONE="+972123456780" EMAIL="bob@isep.com" CREATION_DATE="2017-08-29"/>
<CONSUMER CONSUMER_ID="3" FIRST_NAME="Lady" LAST_NAME="Gaga" PHONE="+972123456781" EMAIL="gaga@isep.com" CREATION_DATE="2017-08-29"/>
</dataset>
</code>```

or should I automate it? for e.g:

```<code>@Test
public void findByPhone(){
    ConsumerEntity consumerEntity = ConsumerUtil.createRandomConsumer();
    ConsumerEntity savedConsumerEntity = consumerRepository.save(consumerEntity);
    assertThat(consumerRepository.findByPhone(savedConsumerEntity.getPhone()).isEqualTo(savedConsumerEntity.getPhone());
}
</code>```

While my createRandomConsumer generates random data.

Pros:
I think automating would be much more generic and handy as if ConsumerEntity might change or any code changes next - i will not have to change my .xml file and just be able to add things to the TestEntity function.
Cons:
Creating new objects and saving to in-memo DB might be more difficult if contains any constraints in the DB scheme.

Should I use DBUnit at all? if automating it - why should I use DBUnit? is it better just to use JUnit (Rolling back the data after each test and just adding the data I need for the test automatically as in the example above?)

If chose to use DBUnit for this - and manually added - what are the advantages of such thing? why is it better than using simple JUnit with Spring?

Thanks!

答:
1) Testing with only random or runtime generated fixture is not fine.

It doesn't make tests reproducible, so make them harder to debug if fails and it doesn't make tests document the code either.

Besides, fixtures with explicit data reduces side effects as the data generation may introduce.

Are you sure that the generated data respect the requirements ?

Are you sure that your generate tool works as expected ?

Have you tested it ?

And so for...
Finding required edge cases is fine but inventing not required edge cases means your tests will change your requirements.

And you don't want that.

If you identified all specific cases and you want to generate some data because you deem that you have too many combinations (dozen of input cases for example), of course generating fixture by relying on the requirements is nice.

Otherwise, don't make it as it seems an overhead.

2) DBUnit, it is a choice.

Before I used it. Now, I stopped. It has some strengths but it is cumbersome and its maintenance/improvements are very light.

Recently, I tried DbSetup from JBNizet (a SO member).

It is rather a fine API to insert Data in a database from Java code : simple and straight usable.

For example to insert data in DB, An Operation can be defined as :

```<code>Operation consumerInserts = sequenceOf(
    insertInto("CONSUMER")
        .columns("ID", "FIRST_NAME", "LAST_NAME")
        .values(1, "Elvis", "Presley")
        .values(2, "Lady", "Gaga")
        .values(3, "Bob", "Dylan")
        .build();
)
</code>```

3) So, nothing to add.

Body:
I am thinking on how to design my unit-tests for my java based-repositories and encountering design problems:
Lets assume I have a Consumer table with data related to my consumer:
{ ID, Name, Phone }
And my ConsumerRepository extends BaseRepository which extends JPA repo and supports findByPhone, findByName, findAll queries and save option.

I'm using H2 in-memo DB and DBUnit for those tests, all configured and running and was thinking about this:

When launching data to my in-memory DB, should I be configuring the data with the ConsumerTestData.xml (DBUnit) and manually adding the Consumer data for each test for e.g:

<dataset>
<CONSUMER CONSUMER_ID="1" FIRST_NAME="Elvis" LAST_NAME="Presley" PHONE="+972123456789" EMAIL="elvis@isep.com" CREATION_DATE="2017-08-29"/>
<CONSUMER CONSUMER_ID="2" FIRST_NAME="Bob" LAST_NAME="Dylan" PHONE="+972123456780" EMAIL="bob@isep.com" CREATION_DATE="2017-08-29"/>
<CONSUMER CONSUMER_ID="3" FIRST_NAME="Lady" LAST_NAME="Gaga" PHONE="+972123456781" EMAIL="gaga@isep.com" CREATION_DATE="2017-08-29"/>
</dataset>

or should I automate it? for e.g:

@Test
public void findByPhone(){
    ConsumerEntity consumerEntity = ConsumerUtil.createRandomConsumer();
    ConsumerEntity savedConsumerEntity = consumerRepository.save(consumerEntity);
    assertThat(consumerRepository.findByPhone(savedConsumerEntity.getPhone()).isEqualTo(savedConsumerEntity.getPhone());
}

While my createRandomConsumer generates random data.

Pros:
I think automating would be much more generic and handy as if ConsumerEntity might change or any code changes next - i will not have to change my .xml file and just be able to add things to the TestEntity function.
Cons:
Creating new objects and saving to in-memo DB might be more difficult if contains any constraints in the DB scheme.

Should I use DBUnit at all? if automating it - why should I use DBUnit? is it better just to use JUnit (Rolling back the data after each test and just adding the data I need for the test automatically as in the example above?)

If chose to use DBUnit for this - and manually added - what are the advantages of such thing? why is it better than using simple JUnit with Spring?

Thanks!

Body:
1) Testing with only random or runtime generated fixture is not fine.

It doesn't make tests reproducible, so make them harder to debug if fails and it doesn't make tests document the code either.

Besides, fixtures with explicit data reduces side effects as the data generation may introduce.

Are you sure that the generated data respect the requirements ?

Are you sure that your generate tool works as expected ?

Have you tested it ?

And so for...
Finding required edge cases is fine but inventing not required edge cases means your tests will change your requirements.

And you don't want that.

If you identified all specific cases and you want to generate some data because you deem that you have too many combinations (dozen of input cases for example), of course generating fixture by relying on the requirements is nice.

Otherwise, don't make it as it seems an overhead.

2) DBUnit, it is a choice.

Before I used it. Now, I stopped. It has some strengths but it is cumbersome and its maintenance/improvements are very light.

Recently, I tried DbSetup from JBNizet (a SO member).

It is rather a fine API to insert Data in a database from Java code : simple and straight usable.

For example to insert data in DB, An Operation can be defined as :

Operation consumerInserts = sequenceOf(
    insertInto("CONSUMER")
        .columns("ID", "FIRST_NAME", "LAST_NAME")
        .values(1, "Elvis", "Presley")
        .values(2, "Lady", "Gaga")
        .values(3, "Bob", "Dylan")
        .build();
)

3) So, nothing to add.


问:
Entity Framework DbUpdateConcurrencyException
on unitOfWork.Complete(); I get this error

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException:
  'Store update, insert, or delete statement affected an unexpected
  number of rows (0). Entities may have been modified or deleted since
  entities were loaded

I gave a look at this but with no results. Also this question does not help me a lot.
What's the point? Where is the error?

Program

```<code>using (var unitOfWork = new UnitOfWork(new
    var ultimaDateTimeElaborata =
            unitOfWork.LogRegistrazioneLavorazioneMacchinaRepository.
            GetUltimaRegistrazioneLineaRilevata(l.IdLinea);
    [...]

            unitOfWork.LogRegistrazioneLavorazioneMacchinaRepository.Add(
            new LogRegistrazioneLavorazioneMacchina()
            {
                IdMacchina = "MB1_1",
                DataRegistrazione = DateTime.Now,
                IdLinea = 1,
                MetriLinLato= 1,
                TempoLavorazioneSecondi= 1,
                IdLavorazioneLinea ="LavorazioneProva",
                IdLavorazioneMacchina = "LMB_1_PP",
                StepLavorazioneLinea = 3,
            });
            unitOfWork.Complete();

    //  HERE I GET THE ERROR!!!
    // LogRegistrazioneLavorazioneMacchinaRepository.unitOfWork
    //contains the right data I want to save
    unitOfWork.Complete();
    [...]
}
</code>```

UnitOfWork

```<code>public class UnitOfWork : IUnitOfWork
    {
        private readonly J2MSEntities _context;
        public ILogRegistrazioneLavorazioneMacchinaRepository
        LogRegistrazioneLavorazioneMacchinaRepository { get; private set; }

        public UnitOfWork(J2MSEntities context)
        {
            _context = context;
            LogRegistrazioneLavorazioneMacchinaRepository(_context);
        }

        public int Complete()
        {
           return _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }
    }
</code>```

答:
Right now I've found a "solution": the table where I would like to write had one primary key with two attributes; now with only one primary key with one attribute I have no errors.

Why?

Body:
on unitOfWork.Complete(); I get this error

System.Data.Entity.Infrastructure.DbUpdateConcurrencyException:
  'Store update, insert, or delete statement affected an unexpected
  number of rows (0). Entities may have been modified or deleted since
  entities were loaded

I gave a look at this but with no results. Also this question does not help me a lot.
What's the point? Where is the error?

Program

using (var unitOfWork = new UnitOfWork(new
    var ultimaDateTimeElaborata =
            unitOfWork.LogRegistrazioneLavorazioneMacchinaRepository.
            GetUltimaRegistrazioneLineaRilevata(l.IdLinea);
    [...]

            unitOfWork.LogRegistrazioneLavorazioneMacchinaRepository.Add(
            new LogRegistrazioneLavorazioneMacchina()
            {
                IdMacchina = "MB1_1",
                DataRegistrazione = DateTime.Now,
                IdLinea = 1,
                MetriLinLato= 1,
                TempoLavorazioneSecondi= 1,
                IdLavorazioneLinea ="LavorazioneProva",
                IdLavorazioneMacchina = "LMB_1_PP",
                StepLavorazioneLinea = 3,
            });
            unitOfWork.Complete();

    //  HERE I GET THE ERROR!!!
    // LogRegistrazioneLavorazioneMacchinaRepository.unitOfWork
    //contains the right data I want to save
    unitOfWork.Complete();
    [...]
}

UnitOfWork

public class UnitOfWork : IUnitOfWork
    {
        private readonly J2MSEntities _context;
        public ILogRegistrazioneLavorazioneMacchinaRepository
        LogRegistrazioneLavorazioneMacchinaRepository { get; private set; }

        public UnitOfWork(J2MSEntities context)
        {
            _context = context;
            LogRegistrazioneLavorazioneMacchinaRepository(_context);
        }

        public int Complete()
        {
           return _context.SaveChanges();
        }

        public void Dispose()
        {
            _context.Dispose();
        }
    }


问:
AnyLogic agent-based modelling: ClassCastException
I am working with an agent-based simulation of an infectious disease epidemic in AnyLogic. I have two agents types in my model- Person and Building. I'm trying to write a function that counts the number of infectious contacts that the agent type 'Person' has at any given point in time. Below is my code for the function:

```<code>int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;
</code>```

The code compiles without any errors but during runtime, it throws up a java.lang.ClassCastException with the message: model.Building cannot be cast to model.Person.

When I try the same code with just one agent type (i.e. 'Person'), the model runs fine and the function returns the correct value. Could someone tell me how I could rectify my code so that I am able to run the function for 'Person' please?

答:
If you just want to ignore agents of type Building, then you can do the following:

```<code>int infectedConnections = 0;

if (getConnections() != null) {
    for (Agent a : this.getConnections())
    {
        if(a instanceof Person) {
            Person p = (Person) a;

            if (p.IsCurrentlyInfected()) {
               infectedConnections++;
            }
        }
    }
}
return infectedConnections;
</code>```

The problem is that (Person) a; will fail if a is a Building instead of a Person.

Body:
I am working with an agent-based simulation of an infectious disease epidemic in AnyLogic. I have two agents types in my model- Person and Building. I'm trying to write a function that counts the number of infectious contacts that the agent type 'Person' has at any given point in time. Below is my code for the function:

int infectedConnections = 0;

if (getConnections() != null)
    for (Agent a : this.getConnections())
        {
        Person p = (Person) a;

        if (p.IsCurrentlyInfected())
            infectedConnections++;
            }

return infectedConnections ;

The code compiles without any errors but during runtime, it throws up a java.lang.ClassCastException with the message: model.Building cannot be cast to model.Person.

When I try the same code with just one agent type (i.e. 'Person'), the model runs fine and the function returns the correct value. Could someone tell me how I could rectify my code so that I am able to run the function for 'Person' please?

Body:
If you just want to ignore agents of type Building, then you can do the following:

int infectedConnections = 0;

if (getConnections() != null) {
    for (Agent a : this.getConnections())
    {
        if(a instanceof Person) {
            Person p = (Person) a;

            if (p.IsCurrentlyInfected()) {
               infectedConnections++;
            }
        }
    }
}
return infectedConnections;

The problem is that (Person) a; will fail if a is a Building instead of a Person.


答:
the form should set post do the get in the url</p>

```<code><form method="post" action="http://www.yourpage.php?firstparam=1&sec=2">
.
.
</form>
</code>```

Title: Send both POST and GET in a form

Body:
I need to make a form send both POST and GET requests (due to some bugs in IE and iframes), how can you do so?

The data being sent is nothing mega secure so it doesn't matter if it can be set via GET, just need to make sure it is set both ways.

Thanks for the help!

Body:
the form should set post do the get in the url

<form method="post" action="http://www.yourpage.php?firstparam=1&sec=2">
.
.
</form>


问:
How to allow only certain words consecutively with Regex in javascript
I'm trying to write a regex that will return true if it matches the format below, otherwise, it should return false. It should only allow words as below:

Positive match (return true)

```<code>UA-1234-1,UA-12345-2,UA-34578-2
</code>```

Negative match (return false or null)

Note: A is missing after U

```<code>UA-1234-1,U-12345-2
</code>```

It should always give me true when the string passed to regex is
UA-1234-1,UA-12345-2,UA-34578-2,...........

Below is what I am trying to do but it is matching only the first element and not returning null.

```<code>var pattern=/^UA-[0-9]+(-[0-9]+)?/g;

pattern.match("UA-1234-1,UA-12345-2,UA-34578-2");

pattern.exec("UA-1234-1,UA-12345-2,UA-34578-2)
</code>```

Thanks in advance. Help is greatly appreciated.

答: split the string by commas, and test each element instead.</p>

Body:
I'm trying to write a regex that will return true if it matches the format below, otherwise, it should return false. It should only allow words as below:

Positive match (return true)

UA-1234-1,UA-12345-2,UA-34578-2

Negative match (return false or null)

Note: A is missing after U

UA-1234-1,U-12345-2

It should always give me true when the string passed to regex is
UA-1234-1,UA-12345-2,UA-34578-2,...........

Below is what I am trying to do but it is matching only the first element and not returning null.

var pattern=/^UA-[0-9]+(-[0-9]+)?/g;

pattern.match("UA-1234-1,UA-12345-2,UA-34578-2");

pattern.exec("UA-1234-1,UA-12345-2,UA-34578-2)

Thanks in advance. Help is greatly appreciated.


问:
ScrapySharp causes Windows Form to freeze without exception
When included in my code

```<code>ScrapingBrowser browser = new ScrapingBrowser();

WebPage testPage = browser.NavigateToPage(new Uri("https://www.google.co.uk/"));
</code>```

causes the Windows Form to stop working (once this line is reached in execution, the form freezes and I have to halt execution). However, there are no errors or anything else to indicate something is wrong.

答:
You should not use this method from your UI thread. Use your favorite technology (BackgroundWorker, Task, Thread) to run this on another thread that does not block the UI thread.

You could also use ScrapySharp's own async method:  NavigateToPageAsync

Body:
When included in my code

ScrapingBrowser browser = new ScrapingBrowser();

WebPage testPage = browser.NavigateToPage(new Uri("https://www.google.co.uk/"));

causes the Windows Form to stop working (once this line is reached in execution, the form freezes and I have to halt execution). However, there are no errors or anything else to indicate something is wrong.


问:
offline data sync with local storage firestore web application
I've already created a simple web page which saves and displays data in firebase database. I tried different times to make the offline cache data to be synced with the fire base data. But it doesn't work. I've attached .html and .js files. Could anybody help me, how the local storage cache be synced with fire base data once the connection established after the disconnect of the app?</p>

```<code>var output = document.getElementById("data");
var dataText = document.getElementById("data-text");

var firebaseReference = firebase.database().ref('users/');

(function() {

    firebaseReference.on("value", function(snapshot) {
        output.innerHTML = JSON.stringify(snapshot.val(), null, 2);
    });
})();

$(document).ready(function(){
    $("form").submit(function(){
        firebaseReference.push().set({Name: dataText.value});
    });
});

var connectedRef = firebase.database().ref(".info/connected");

connectedRef.on("value", function(snap) {
    if (snap.val() === true) {
        alert("connected");
    } else {
        alert("not connected");
    }
});

<html>
  <head>
    <meta charset="utf-8"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
    <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase.js"></script>
    <script src="https://www.gstatic.com/firebasejs/4.6.0/firebase-firestore.js"></script>
    <script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>
    <title>Firebase</title>
  </head>
  <body>
    <h1>Firebase  Example</h1>
    <h2>Add New</h2>
    <form action="" class="form-group">
      <input type="text" required id="data-text">
      <input type="submit" id="data-submit" class="btn btn-primary">
    </form>
    <h2>Existing Data</h2>
    <pre id='data'>```
    <script>
        var config = {
            apiKey: "AIzaSyBGKWHQlLok3q70Y6Q5CAzWyLbN4GyKnAQ",
            authDomain: "my-firebase-project-536a4.firebaseapp.com",
            databaseURL: "https://my-firebase-project-536a4.firebaseio.com",
            projectId: "my-firebase-project-536a4",
            storageBucket: "my-firebase-project-536a4.appspot.com",
            messagingSenderId: "711083146609"
        };

        firebase.initializeApp(config);

    </script>
    <script src="script.js"></script>
  </body>
</html>
</code>```

答:
Your code is using the Firebase Realtime Database, which doesn't support disk persistence in its web client at the moment. While the feature has been worked on in the open-source repo, it hasn't been released yet.

If you want offline caching support for a web application, I recommend using Cloud Firestore for Firebase where such support is built in.

Body:
I've already created a simple web page which saves and displays data in firebase database. I tried different times to make the offline cache data to be synced with the fire base data. But it doesn't work. I've attached .html and .js files. Could anybody help me, how the local storage cache be synced with fire base data once the connection established after the disconnect of the app?

var output = document.getElementById("data");
var dataText = document.getElementById("data-text");

var firebaseReference = firebase.database().ref('users/');

(function() {

    firebaseReference.on("value", function(snapshot) {
        output.innerHTML = JSON.stringify(snapshot.val(), null, 2);
    });
})();

$(document).ready(function(){
    $("form").submit(function(){
        firebaseReference.push().set({Name: dataText.value});
    });
});

var connectedRef = firebase.database().ref(".info/connected");

connectedRef.on("value", function(snap) {
    if (snap.val() === true) {
        alert("connected");
    } else {
        alert("not connected");
    }
});

    <meta charset="utf-8"/>
    <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">

    <title>Firebase</title>

Firebase  Example

Add New

    <form action="" class="form-group">
      <input type="text" required id="data-text">
      <input type="submit" id="data-submit" class="btn btn-primary">
    </form>

Existing Data


问:
One class property (of many) is lost after object passed back to caller/creator?
I have a class that includes two constructors.

One constructor File_Attachment(int Attachment_ID) creates an instance of the class, populated with data from a single database row.

The second constructor File_Attachment(string type, int mid) creates numerous instances of the class with the first constructor, and collects them in a List<>.

Here is the full class code:

```<code>using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System.Data.SqlClient;

public class File_Attachment {

    private string cs = ApplicationData.dbConnectionString;
    private string where = "";

    public List<File_Attachment> File_Attachments = new List<File_Attachment>();

    public int Attachment_ID { get; set; }
    public string Attachment_Type { get; set; }
    public int Attachment_Type_ID { get; set; }
    public int Old_ID { get; set; }
    public string File_Name { get; set; }
    public string Content_Type { get; set; }
    public byte[] Data { get; set; }

    // ****************************************************************************************************************************

    public File_Attachment() {
    }

    // ****************************************************************************************************************************

    public File_Attachment(int Attachment_ID) {

        using (SqlConnection cn = new SqlConnection(cs)) {

            cn.Open();

            using (SqlCommand cmd = new SqlCommand("SELECT * FROM File_Attachments WHERE Attachment_ID = " + Attachment_ID, cn))
            using (SqlDataReader rs = cmd.ExecuteReader()) {

                if (rs.HasRows) {

                    rs.Read();

                    Attachment_ID = (int) rs["Attachment_ID"];
                    Attachment_Type = (string) rs["Attachment_Type"];
                    Attachment_Type_ID = (int) rs["Attachment_Type_ID"];
                    Old_ID = (int) rs["Old_ID"];
                    File_Name = (string) rs["File_Name"];
                    Content_Type = (string) rs["Content_Type"];
                    Data = (byte[]) rs["Data"];

                }
            }
        }

    }

    // ****************************************************************************************************************************

    public File_Attachment(string type, int mid) {

        if (type.ToLower() == "meeting") {
            where = " Attachment_Type = 'Meeting' ";
        }
        if (type.ToLower() == "discussion") {
            where = " Attachment_Type = 'Discussion' ";
        }
        if (type.ToLower() == "action") {
            where = " Attachment_Type = 'Action' ";
        }

        where += " AND Attachment_Type_ID = " + mid.ToString() + " ";

        using (SqlConnection cn = new SqlConnection(cs)) {

            cn.Open();

            using (SqlCommand cmd = new SqlCommand("SELECT * FROM File_Attachments WHERE " + where, cn))
            using (SqlDataReader rs = cmd.ExecuteReader()) {

                if (rs.HasRows) {

                    while (rs.Read()) {

                        File_Attachment fa = new File_Attachment((int)rs["Attachment_ID"]);
                        File_Attachments.Add(fa);

                    }

                }

            }
        }

    }

}
</code>```

The problem is, the second class constructor creates numerous instances of itself (same class) using the first constructor.

During debugging, at the conclusion of the first contructor's code:

```<code>if (rs.HasRows) {

                    rs.Read();

                    Attachment_ID = (int) rs["Attachment_ID"];
                    Attachment_Type = (string) rs["Attachment_Type"];
                    Attachment_Type_ID = (int) rs["Attachment_Type_ID"];
                    Old_ID = (int) rs["Old_ID"];
                    File_Name = (string) rs["File_Name"];
                    Content_Type = (string) rs["Content_Type"];
                    Data = (byte[]) rs["Data"];  //<--------- BREAK POINT!!!!

                }
</code>```

... All the fields, including Attachment_ID are populated with correct data.

However, when the List<> object is received back, each instance in the list has all the fields STILL properly populated with data EXCEPT Attachment_ID, which are ALL zero.

See debugger screen caps: https://imgur.com/a/Vxftf

It is perplexing, because each object in the List<> has Attachment_Type_ID with proper data, even though it is an (int) field just like Attachment_ID is.  See pics, again.

Things I have considered:

Originally, in my visual studio project, Attachment_ID was declared:

```<code>public int Attachment_ID { get; private set; }
</code>```

This was later changed to:

```<code>public int Attachment_ID { get; set; }
</code>```

Is this a caching issue?  I've rebuilt the solution several times.  No change.

Also, In the database, Attachment_ID is the Primary Key, if that helps.

What is happening to my Attachment_ID in between the time that it is added to the list, and the time the list is received back by the caller/initiator code?

答:
One problem you have is that you declared a global variable with the exact name as a local variable. That's problematic, because it leads to weird issues.

Try replacing:

```<code>public File_Attachment(int Attachment_ID)
</code>```

with:

```<code>public File_Attachment(int attachmentID)
</code>```

Then in your first constructor, change:

```<code>using (SqlCommand cmd = new SqlCommand("SELECT * FROM File_Attachments WHERE Attachment_ID = " + Attachment_ID, cn))
</code>```

to:

```<code>using (SqlCommand cmd = new SqlCommand("SELECT * FROM File_Attachments WHERE Attachment_ID = " + attachmentID, cn))
</code>```

It's likely that when you do:

```<code>Attachment_ID = (int) rs["Attachment_ID"];
</code>```

You're changing the Local Variable to that value, which gets thrown away when the constructor is done.

As a bonus, your first constructor should simply set the "Attachment_ID" to the parameter it takes. You don't need to set the ID to the one you find in the database, because your constructor gets the ID as a parameter.

So something like:

```<code>public File_Attachment(int attachmentID){
    Attachment_ID = attachmentID;
    ...
</code>```

Body:
I have a class that includes two constructors.

One constructor File_Attachment(int Attachment_ID) creates an instance of the class, populated with data from a single database row.

The second constructor File_Attachment(string type, int mid) creates numerous instances of the class with the first constructor, and collects them in a List<>.

Here is the full class code:

using System;
using System.IO;
using System.Web;
using System.Collections.Generic;
using System.Data.SqlClient;

public class File_Attachment {

    private string cs = ApplicationData.dbConnectionString;
    private string where = "";

    public List<File_Attachment> File_Attachments = new List<File_Attachment>();

    public int Attachment_ID { get; set; }
    public string Attachment_Type { get; set; }
    public int Attachment_Type_ID { get; set; }
    public int Old_ID { get; set; }
    public string File_Name { get; set; }
    public string Content_Type { get; set; }
    public byte[] Data { get; set; }

    // ****************************************************************************************************************************

    public File_Attachment() {
    }

    // ****************************************************************************************************************************

    public File_Attachment(int Attachment_ID) {

        using (SqlConnection cn = new SqlConnection(cs)) {

            cn.Open();

            using (SqlCommand cmd = new SqlCommand("SELECT * FROM File_Attachments WHERE Attachment_ID = " + Attachment_ID, cn))
            using (SqlDataReader rs = cmd.ExecuteReader()) {

                if (rs.HasRows) {

                    rs.Read();

                    Attachment_ID = (int) rs["Attachment_ID"];
                    Attachment_Type = (string) rs["Attachment_Type"];
                    Attachment_Type_ID = (int) rs["Attachment_Type_ID"];
                    Old_ID = (int) rs["Old_ID"];
                    File_Name = (string) rs["File_Name"];
                    Content_Type = (string) rs["Content_Type"];
                    Data = (byte[]) rs["Data"];

                }
            }
        }

    }

    // ****************************************************************************************************************************

    public File_Attachment(string type, int mid) {

        if (type.ToLower() == "meeting") {
            where = " Attachment_Type = 'Meeting' ";
        }
        if (type.ToLower() == "discussion") {
            where = " Attachment_Type = 'Discussion' ";
        }
        if (type.ToLower() == "action") {
            where = " Attachment_Type = 'Action' ";
        }

        where += " AND Attachment_Type_ID = " + mid.ToString() + " ";

        using (SqlConnection cn = new SqlConnection(cs)) {

            cn.Open();

            using (SqlCommand cmd = new SqlCommand("SELECT * FROM File_Attachments WHERE " + where, cn))
            using (SqlDataReader rs = cmd.ExecuteReader()) {

                if (rs.HasRows) {

                    while (rs.Read()) {

                        File_Attachment fa = new File_Attachment((int)rs["Attachment_ID"]);
                        File_Attachments.Add(fa);

                    }

                }

            }
        }

    }

}

The problem is, the second class constructor creates numerous instances of itself (same class) using the first constructor.

During debugging, at the conclusion of the first contructor's code:

if (rs.HasRows) {

                    rs.Read();

                    Attachment_ID = (int) rs["Attachment_ID"];
                    Attachment_Type = (string) rs["Attachment_Type"];
                    Attachment_Type_ID = (int) rs["Attachment_Type_ID"];
                    Old_ID = (int) rs["Old_ID"];
                    File_Name = (string) rs["File_Name"];
                    Content_Type = (string) rs["Content_Type"];
                    Data = (byte[]) rs["Data"];  //<--------- BREAK POINT!!!!

                }

... All the fields, including Attachment_ID are populated with correct data.

However, when the List<> object is received back, each instance in the list has all the fields STILL properly populated with data EXCEPT Attachment_ID, which are ALL zero.

See debugger screen caps: https://imgur.com/a/Vxftf

It is perplexing, because each object in the List<> has Attachment_Type_ID with proper data, even though it is an (int) field just like Attachment_ID is.  See pics, again.

Things I have considered:

Originally, in my visual studio project, Attachment_ID was declared:

public int Attachment_ID { get; private set; }

This was later changed to:

public int Attachment_ID { get; set; }

Is this a caching issue?  I've rebuilt the solution several times.  No change.

Also, In the database, Attachment_ID is the Primary Key, if that helps.

What is happening to my Attachment_ID in between the time that it is added to the list, and the time the list is received back by the caller/initiator code?

Body:
One problem you have is that you declared a global variable with the exact name as a local variable. That's problematic, because it leads to weird issues.

Try replacing:

public File_Attachment(int Attachment_ID)

with:

public File_Attachment(int attachmentID)

Then in your first constructor, change:

using (SqlCommand cmd = new SqlCommand("SELECT * FROM File_Attachments WHERE Attachment_ID = " + Attachment_ID, cn))

to:

using (SqlCommand cmd = new SqlCommand("SELECT * FROM File_Attachments WHERE Attachment_ID = " + attachmentID, cn))

It's likely that when you do:

Attachment_ID = (int) rs["Attachment_ID"];

You're changing the Local Variable to that value, which gets thrown away when the constructor is done.

As a bonus, your first constructor should simply set the "Attachment_ID" to the parameter it takes. You don't need to set the ID to the one you find in the database, because your constructor gets the ID as a parameter.

So something like:

public File_Attachment(int attachmentID){
    Attachment_ID = attachmentID;
    ...


问:
How does NSTextView's automaticLinkDetectionEnabled method work?
I'm setting up an NSTextView programmatically:

```<code>    NSTextView *infoTextView = [[NSTextView alloc] initWithFrame:insetRect];
[infoTextView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
    [infoTextView setBackgroundColor:[NSColor clearColor]];
    [infoTextView setTextContainerInset:NSZeroSize];
    [infoTextView setEditable:YES];
    [infoTextView setSelectable:YES];
    [infoTextView setAutomaticLinkDetectionEnabled:YES];
</code>```

I'm targeting 10.6, and thought that automaticLinkDetectionEnabled meant that when the user typed a string that was a website address, NSTextView would format it blue color, underlined, and make it a clickable link. that doesn't happen. its just read as plain text. i have no formatting on the textView's textStorage.

the doc reads:

'Automatic link detection causes
  strings representing URLs typed in the
  view to be automatically made into
  links to those URLs.'

what else do i need to do?

答:
answering my own question in case there is someone else on the planet who made the same mistake i did:

in a core data app, with a property 'notes', as in Entity.notes, if you set notes as binary type, and then use IB binding on an NSTextView for AttributedString binding, (do not use the Values binding), and use the built-in NSTransformer: NSKeyedUnarchiveFromData, the check boxes on the Inspector for Smart Links et al, work to setup the automatic link detection.
you may do that programmatically as well.

i had my notes property as 'string', and also was binding to 'value'.

double d'oh.....

Body:
I'm setting up an NSTextView programmatically:

    NSTextView *infoTextView = [[NSTextView alloc] initWithFrame:insetRect];
[infoTextView setAutoresizingMask:NSViewWidthSizable|NSViewHeightSizable];
    [infoTextView setBackgroundColor:[NSColor clearColor]];
    [infoTextView setTextContainerInset:NSZeroSize];
    [infoTextView setEditable:YES];
    [infoTextView setSelectable:YES];
    [infoTextView setAutomaticLinkDetectionEnabled:YES];

I'm targeting 10.6, and thought that automaticLinkDetectionEnabled meant that when the user typed a string that was a website address, NSTextView would format it blue color, underlined, and make it a clickable link. that doesn't happen. its just read as plain text. i have no formatting on the textView's textStorage.

the doc reads:

'Automatic link detection causes
  strings representing URLs typed in the
  view to be automatically made into
  links to those URLs.'

what else do i need to do?


问:
Can NumPy take care that an array is (nonstrictly) increasing along one axis?
Is there a function in numpy to guarantee or rather fix an array such that it is (nonstrictly) increasing along one particular axis?
For example, I have the following 2D array:

```<code>X = array([[1, 2, 1, 4, 5],
           [0, 3, 1, 5, 4]])
</code>```

the output of np.foobar(X) should return

```<code>array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])
</code>```

Does foobar exist or do I need to do that manually by using something like np.diff and some smart indexing?

答:
pandas offers you the df.cummax function:

```<code>import pandas as pd
pd.DataFrame(X).cummax(axis=1).values

array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])
</code>```

It's useful to know that there's a first class function on hand in case your data is already loaded into a dataframe.

Body:
Is there a function in numpy to guarantee or rather fix an array such that it is (nonstrictly) increasing along one particular axis?
For example, I have the following 2D array:

X = array([[1, 2, 1, 4, 5],
           [0, 3, 1, 5, 4]])

the output of np.foobar(X) should return

array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])

Does foobar exist or do I need to do that manually by using something like np.diff and some smart indexing?

Body:
pandas offers you the df.cummax function:

import pandas as pd
pd.DataFrame(X).cummax(axis=1).values

array([[1, 2, 2, 4, 5],
       [0, 3, 3, 5, 5]])

It's useful to know that there's a first class function on hand in case your data is already loaded into a dataframe.