问:
How to create a new dataframe using existing dataframe?
I have a dataframe df. Now, I took a backup of this df using:

```<code>df_backup = df
</code>```

Later on in my code, I deleted few records from the original df using:

```<code>df.drop(df.index[indexes], inplace = True)
</code>```

these rows gets deleted from the backup as well.
It looks like df_backup is just a copy of df. How do I decouple both?

If I change anything to df, it shouldn't affect df_backup.

答:
you can decouple them by making an actual copy (a copy is a separate object)

```<code>df_backup = df.copy()
</code>```

as Anthony Sottile pointed out, you were creating another reference to your original dataframe rather than creating a new object. Which means you could change either your df or df_backup and both would show that change. He also suggested a good link to help understand this

Body:
I have a dataframe df. Now, I took a backup of this df using:

df_backup = df

Later on in my code, I deleted few records from the original df using:

df.drop(df.index[indexes], inplace = True)

these rows gets deleted from the backup as well.
It looks like df_backup is just a copy of df. How do I decouple both?

If I change anything to df, it shouldn't affect df_backup.

Body:
you can decouple them by making an actual copy (a copy is a separate object)

df_backup = df.copy()

as Anthony Sottile pointed out, you were creating another reference to your original dataframe rather than creating a new object. Which means you could change either your df or df_backup and both would show that change. He also suggested a good link to help understand this


来源: stackexchange

问:
Why mysql query takes long before received results?
I have these 2 tables with thousands of data and i will look for matches 1:1 on both tables. I have the query below, but when the limit is already beyond 1000 the return starts to slow down, it took almost an hour before I receive a result, I am using my local xampp as database for this and have a 4G(3.4G usable) RAM PC.

Is there any other way to enhance and make the query faster?

Thank you in advance for those who will help.

```<code>SELECT a.rNum,
        a.cDate,
        a.cTime,
        a.aNumber,
        a.bNumber,
        a.duration,
        a.tag,
        a.aNumber2,
        a.bNumber2,
        'hasMatch',
        a.concatDate,
        a.timeMinutes
FROM tableOne a
INNER JOIN
tableTwo b ON a.aNumber2 = b.aNumber2
AND a.bNumber2 = b.bNumber2
WHERE a.hasMatch = 'valid'
AND (a.duration - b.duration) <= 3
AND (a.duration - b.duration) >= -3
AND TIMEDIFF(a.concatDate,b.concatDate) <= 3
AND TIMEDIFF(a.concatDate,b.concatDate) >= -3
LIMIT 0,100;
</code>```

答:
The obvious question is:  do you have indexes?

As written, the best indexes to try on on tableOne(aNumber1, aNumber2) and tableTwo(bNumber1, bNumber2).

If you provide sample data, desired results, and an explanation of what you are trying to do, there might be further suggestions.

ContentLicense: CC BY-SA 3.0

Body:
I have these 2 tables with thousands of data and i will look for matches 1:1 on both tables. I have the query below, but when the limit is already beyond 1000 the return starts to slow down, it took almost an hour before I receive a result, I am using my local xampp as database for this and have a 4G(3.4G usable) RAM PC.

Is there any other way to enhance and make the query faster?

Thank you in advance for those who will help.

SELECT a.rNum,
        a.cDate,
        a.cTime,
        a.aNumber,
        a.bNumber,
        a.duration,
        a.tag,
        a.aNumber2,
        a.bNumber2,
        'hasMatch',
        a.concatDate,
        a.timeMinutes
FROM tableOne a
INNER JOIN
tableTwo b ON a.aNumber2 = b.aNumber2
AND a.bNumber2 = b.bNumber2
WHERE a.hasMatch = 'valid'
AND (a.duration - b.duration) <= 3
AND (a.duration - b.duration) >= -3
AND TIMEDIFF(a.concatDate,b.concatDate) <= 3
AND TIMEDIFF(a.concatDate,b.concatDate) >= -3
LIMIT 0,100;


问:
Trick a second transaction to see same thing with first even if first has made changes
I have the following two transactions (it's an old exam question that i'm trying to solve). I need without using commit, rollback or insert into
to get the same output in transaction A and B.
I managed to do this with adding

```<code>REPLACE INTO T
SELECT 10,10 FROM dual;
</code>```

to the red colored text (marked "(1)")
and it worked but I wonder if there is any other way, like changing isolation level or do something more tricky?
Also, is there any command from transaction B that we can delete it and still get the same results?

https://i.imgur.com/Ba9jLOz.png

答:
As per your comment you can only issue the command at the red dotted line. Based on your comment I also assume that innodb table engine is used with the default repeatable read isolation mode.

The above means that changing the transaction isolation level cannot be used, since obviously you cannot change the isolation level of an ongoing transaction.

This also means that you need a statement that adds one more record to the table to compensate for the record with id=5 that was added by transaction A, while transaction B was running. insert is ruled out by the question, so that really leaves you with replace, since it is the only other statement that can create a new record in a table.

There is another sneaky solution. Issue an

```<code>update t set b=1 where id=5;
</code>```

and the counts will match. The reason is that the consistent snapshot applies to select only, but not to changes to data. The above statement will update the record with id=5 and thus brings it into the snapshot:

The snapshot of the database state applies to SELECT statements within a transaction, not necessarily to DML statements. If you insert or modify some rows and then commit that transaction, a DELETE or UPDATE statement issued from another concurrent REPEATABLE READ transaction could affect those just-committed rows, even though the session could not query them. If a transaction does update or delete rows committed by a different transaction, those changes do become visible to the current transaction.

Also, if you remove the select before the insert in transaction B, you should get the same result without adding anything on the red dotted line. The consistent snapshot is established by the first read. By removing the mentioned select, the snapshot would be established after transaction A commits, therefore its changes would be visible to transaction B.

Body:
I have the following two transactions (it's an old exam question that i'm trying to solve). I need without using commit, rollback or insert into
to get the same output in transaction A and B.
I managed to do this with adding

REPLACE INTO T
SELECT 10,10 FROM dual;

to the red colored text (marked "(1)")
and it worked but I wonder if there is any other way, like changing isolation level or do something more tricky?
Also, is there any command from transaction B that we can delete it and still get the same results?

https://i.imgur.com/Ba9jLOz.png

Body:
As per your comment you can only issue the command at the red dotted line. Based on your comment I also assume that innodb table engine is used with the default repeatable read isolation mode.

The above means that changing the transaction isolation level cannot be used, since obviously you cannot change the isolation level of an ongoing transaction.

This also means that you need a statement that adds one more record to the table to compensate for the record with id=5 that was added by transaction A, while transaction B was running. insert is ruled out by the question, so that really leaves you with replace, since it is the only other statement that can create a new record in a table.

There is another sneaky solution. Issue an

update t set b=1 where id=5;

and the counts will match. The reason is that the consistent snapshot applies to select only, but not to changes to data. The above statement will update the record with id=5 and thus brings it into the snapshot:

The snapshot of the database state applies to SELECT statements within a transaction, not necessarily to DML statements. If you insert or modify some rows and then commit that transaction, a DELETE or UPDATE statement issued from another concurrent REPEATABLE READ transaction could affect those just-committed rows, even though the session could not query them. If a transaction does update or delete rows committed by a different transaction, those changes do become visible to the current transaction.

Also, if you remove the select before the insert in transaction B, you should get the same result without adding anything on the red dotted line. The consistent snapshot is established by the first read. By removing the mentioned select, the snapshot would be established after transaction A commits, therefore its changes would be visible to transaction B.


问:
Tags are appearing in left of the document in embedded Signing using template

``code`       DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
        recipient.Email = signer_email; // This person will use embedded signing. If you have his
            // email, supply it. If you don't, use a fake email that includes your
            // ClientUserID. Eg embedded_signer_{ClientUserID}@your_company.com
        recipient.UserName = signer_name;
        recipient.ID = 1;
        recipient.Type_x = 'Signer';
        recipient.RoutingOrder = 1;
        recipient.RoleName = 'Signer1';
        // We want this signer to be "captive" so we can use embedded signing with him
        recipient.CaptiveInfo = new DocuSignTK.RecipientCaptiveInfo();
        recipient.CaptiveInfo.ClientUserID = signer_user_id; // Must uniquely identify the

        // Create the recipient information
        DocuSignTK.ArrayOfRecipient1 recipients = new DocuSignTK.ArrayOfRecipient1();
        recipients.Recipient = new DocuSignTK.Recipient[1];
        recipients.Recipient[0] = recipient;

        DocuSignTK.ArrayOfTemplateReferenceRoleAssignment Roles = new DocuSignTK.ArrayOfTemplateReferenceRoleAssignment();
        Roles.RoleAssignment = new DocuSignTK.TemplateReferenceRoleAssignment[1];
        DocuSignTK.TemplateReferenceRoleAssignment role = new DocuSignTK.TemplateReferenceRoleAssignment();
        role.RoleName = 'Signer1';
        role.RecipientID = 1;
        Roles.RoleAssignment[0] = role;

        // Create the template reference from a server-side template ID
        DocuSignTK.TemplateReference templateReference = new DocuSignTK.TemplateReference();
        templateReference.Template = 'd0d80082-612b-4a04-b2a1-0672eb720491';
        templateReference.TemplateLocation = 'Server';

        templateReference.RoleAssignments = Roles;

        // Construct the envelope information
        DocuSignTK.EnvelopeInformation envelopeInfo = new DocuSignTK.EnvelopeInformation();
        envelopeInfo.AccountId = account_Id;
        envelopeInfo.Subject = 'Subject';
        envelopeInfo.EmailBlurb = 'Email content';

        // Make the call
        try {
            //DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
            // Create draft with all the template information
            DocuSignTK.ArrayOfTemplateReference TemplateReferenceArray = new DocuSignTK.ArrayOfTemplateReference();
            TemplateReferenceArray.TemplateReference = new DocuSignTK.TemplateReference[1];
            TemplateReferenceArray.TemplateReference[0] = templateReference;
            DocuSignTK.EnvelopeStatus result = api_sender.CreateEnvelopeFromTemplates( TemplateReferenceArray, recipients, envelopeInfo, true);
            envelope_id = result.EnvelopeID;
            System.debug('Returned successfully, envelope_id = ' + envelope_id );
        } catch ( CalloutException e) {
            System.debug('Exception - ' + e );
            error_code = 'Problem: ' + e;
            error_message = error_code;
        }  `code`````

I am integrating Docusign for embedded signing. I am using SOAP API and used method CreateEnvelopeFromTemplates . Template I created is having some fields/Tabs. But once I open signing url these fields are located on side of the document instead of the location which I sent in template.

I have also assigned Role name for recipient but it is not working. Please help.

Click here to see screenshot

答:
Here is the C# code to create an envelope from template using the DocuSign SOAP Api. Documentation here</p>

```<code>       string apiUrl = "https://demo.docusign.net/api/3.0/api.asmx";
        string accountId = "Enter accountId"; //
        string email = "Enter email";
        string userName = "Enter intergrator key";

        userName += email;
        string _password = "Enter password";
        var apiClient = new DocuSignTK.APIServiceSoapClient("APIServiceSoap", apiUrl);
        apiClient.ClientCredentials.UserName.UserName = userName;
        apiClient.ClientCredentials.UserName.Password = _password;

        // Construct all the recipient information
        var recipients = new DocuSignTK.Recipient[1];

        recipients[0] = new DocuSignTK.Recipient();
        recipients[0].Email = "recipientone@acme.com";
        recipients[0].UserName = "recipient one";
        recipients[0].Type = DocuSignTK.RecipientTypeCode.Signer;
        recipients[0].ID = "1";
        recipients[0].RoutingOrder = 1;
        recipients[0].RoleName = "Signer1";

        var roles = new DocuSignTK.TemplateReferenceRoleAssignment[1];
        roles[0] = new DocuSignTK.TemplateReferenceRoleAssignment();
        roles[0].RoleName = recipients[0].RoleName;
        roles[0].RecipientID = recipients[0].ID;

        // Use a server-side template -- you could make more than one of these
        var templateReference = new DocuSignTK.TemplateReference();
        templateReference.TemplateLocation = DocuSignTK.TemplateLocationCode.Server;
        // TODO: replace with template ID from your account
        templateReference.Template = "d0d80082-612b-4a04-b2a1-0672eb720491";
        templateReference.RoleAssignments = roles;

        // Construct the envelope information
        DocuSignTK.EnvelopeInformation envelopeInfo = new DocuSignTK.EnvelopeInformation();
        envelopeInfo.AccountId = " ";
        envelopeInfo.Subject = "create envelope from templates test";
        envelopeInfo.EmailBlurb = "testing docusign creation services";

        // Create draft with all the template information
        DocuSignTK.EnvelopeStatus status = apiClient.CreateEnvelopeFromTemplates(new DocuSignTK.TemplateReference[] { templateReference },
            recipients, envelopeInfo, false);
</code>```

Body:
``code`       DocuSignTK.Recipient recipient = new DocuSignTK.Recipient();
        recipient.Email = signer_email; // This person will use embedded signing. If you have his
            // email, supply it. If you don't, use a fake email that includes your
            // ClientUserID. Eg embedded_signer_{ClientUserID}@your_company.com
        recipient.UserName = signer_name;
        recipient.ID = 1;
        recipient.Type_x = 'Signer';
        recipient.RoutingOrder = 1;
        recipient.RoleName = 'Signer1';
        // We want this signer to be "captive" so we can use embedded signing with him
        recipient.CaptiveInfo = new DocuSignTK.RecipientCaptiveInfo();
        recipient.CaptiveInfo.ClientUserID = signer_user_id; // Must uniquely identify the

        // Create the recipient information
        DocuSignTK.ArrayOfRecipient1 recipients = new DocuSignTK.ArrayOfRecipient1();
        recipients.Recipient = new DocuSignTK.Recipient[1];
        recipients.Recipient[0] = recipient;

        DocuSignTK.ArrayOfTemplateReferenceRoleAssignment Roles = new DocuSignTK.ArrayOfTemplateReferenceRoleAssignment();
        Roles.RoleAssignment = new DocuSignTK.TemplateReferenceRoleAssignment[1];
        DocuSignTK.TemplateReferenceRoleAssignment role = new DocuSignTK.TemplateReferenceRoleAssignment();
        role.RoleName = 'Signer1';
        role.RecipientID = 1;
        Roles.RoleAssignment[0] = role;

        // Create the template reference from a server-side template ID
        DocuSignTK.TemplateReference templateReference = new DocuSignTK.TemplateReference();
        templateReference.Template = 'd0d80082-612b-4a04-b2a1-0672eb720491';
        templateReference.TemplateLocation = 'Server';

        templateReference.RoleAssignments = Roles;

        // Construct the envelope information
        DocuSignTK.EnvelopeInformation envelopeInfo = new DocuSignTK.EnvelopeInformation();
        envelopeInfo.AccountId = account_Id;
        envelopeInfo.Subject = 'Subject';
        envelopeInfo.EmailBlurb = 'Email content';

        // Make the call
        try {
            //DocuSignTK.EnvelopeStatus result = api_sender.CreateAndSendEnvelope(envelope);
            // Create draft with all the template information
            DocuSignTK.ArrayOfTemplateReference TemplateReferenceArray = new DocuSignTK.ArrayOfTemplateReference();
            TemplateReferenceArray.TemplateReference = new DocuSignTK.TemplateReference[1];
            TemplateReferenceArray.TemplateReference[0] = templateReference;
            DocuSignTK.EnvelopeStatus result = api_sender.CreateEnvelopeFromTemplates( TemplateReferenceArray, recipients, envelopeInfo, true);
            envelope_id = result.EnvelopeID;
            System.debug('Returned successfully, envelope_id = ' + envelope_id );
        } catch ( CalloutException e) {
            System.debug('Exception - ' + e );
            error_code = 'Problem: ' + e;
            error_message = error_code;
        }  `code``

I am integrating Docusign for embedded signing. I am using SOAP API and used method CreateEnvelopeFromTemplates . Template I created is having some fields/Tabs. But once I open signing url these fields are located on side of the document instead of the location which I sent in template.

I have also assigned Role name for recipient but it is not working. Please help.

Click here to see screenshot

Body:
Here is the C# code to create an envelope from template using the DocuSign SOAP Api. Documentation here

       string apiUrl = "https://demo.docusign.net/api/3.0/api.asmx";
        string accountId = "Enter accountId"; //
        string email = "Enter email";
        string userName = "Enter intergrator key";

        userName += email;
        string _password = "Enter password";
        var apiClient = new DocuSignTK.APIServiceSoapClient("APIServiceSoap", apiUrl);
        apiClient.ClientCredentials.UserName.UserName = userName;
        apiClient.ClientCredentials.UserName.Password = _password;

        // Construct all the recipient information
        var recipients = new DocuSignTK.Recipient[1];

        recipients[0] = new DocuSignTK.Recipient();
        recipients[0].Email = "recipientone@acme.com";
        recipients[0].UserName = "recipient one";
        recipients[0].Type = DocuSignTK.RecipientTypeCode.Signer;
        recipients[0].ID = "1";
        recipients[0].RoutingOrder = 1;
        recipients[0].RoleName = "Signer1";

        var roles = new DocuSignTK.TemplateReferenceRoleAssignment[1];
        roles[0] = new DocuSignTK.TemplateReferenceRoleAssignment();
        roles[0].RoleName = recipients[0].RoleName;
        roles[0].RecipientID = recipients[0].ID;

        // Use a server-side template -- you could make more than one of these
        var templateReference = new DocuSignTK.TemplateReference();
        templateReference.TemplateLocation = DocuSignTK.TemplateLocationCode.Server;
        // TODO: replace with template ID from your account
        templateReference.Template = "d0d80082-612b-4a04-b2a1-0672eb720491";
        templateReference.RoleAssignments = roles;

        // Construct the envelope information
        DocuSignTK.EnvelopeInformation envelopeInfo = new DocuSignTK.EnvelopeInformation();
        envelopeInfo.AccountId = " ";
        envelopeInfo.Subject = "create envelope from templates test";
        envelopeInfo.EmailBlurb = "testing docusign creation services";

        // Create draft with all the template information
        DocuSignTK.EnvelopeStatus status = apiClient.CreateEnvelopeFromTemplates(new DocuSignTK.TemplateReference[] { templateReference },
            recipients, envelopeInfo, false);


问:
Working with TIFFs (import, export) in Python using numpy
I need a python method to open and import TIFF images into numpy arrays so I can analyze and modify the pixel data and then save them as TIFFs again. (They are basically light intensity maps in greyscale, representing the respective values per pixel)

I couldn't find any documentation on PIL methods concerning TIFF. I tried to figure it out, but only got "bad mode" or "file type not supported" errors.

What do I need to use here?

答:
PyLibTiff worked better for me than PIL, which as of April 2023 still doesn't support color images with more than 8 bits per color.

```<code>from libtiff import TIFF

tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the current TIFF directory as a numpy array
image = tif.read_image()

# read all images in a TIFF file:
for image in tif.iter_images():
    pass

tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)
</code>```

You can install PyLibTiff with

```<code>pip3 install numpy pylibtiff
</code>```

The readme of PyLibTiff also mentions the tifffile library but I haven't tried it.

ContentLicense: CC BY-SA 4.0

Body:
PyLibTiff worked better for me than PIL, which as of April 2023 still doesn't support color images with more than 8 bits per color.

from libtiff import TIFF

tif = TIFF.open('filename.tif') # open tiff file in read mode
# read an image in the current TIFF directory as a numpy array
image = tif.read_image()

# read all images in a TIFF file:
for image in tif.iter_images():
    pass

tif = TIFF.open('filename.tif', mode='w')
tif.write_image(image)

You can install PyLibTiff with

pip3 install numpy pylibtiff

The readme of PyLibTiff also mentions the tifffile library but I haven't tried it.


问:
Moving all nodes the same time including links?
in D3.js I use the force-layout to shift all nodes to the right with this code below. But when call the function, only the nodes shift, the text and links stay the same. What exactly is missing here? Is it the tick() function that has to be called inside the function?</p>

```<code>  function(){ d3.select(".nodes").attr("transform", "translate(200,0)");

                simulation.alpha(0.8).restart();

};

        simulation
                    .nodes(nodes)
                    .on("tick", function(d)
                    {

                      link
                        .attr("x1", function(d) { return d.source.x; })
                        .attr("y1", function(d) { return d.source.y; })
                        .attr("x2", function(d) { return d.target.x; })
                        .attr("y2", function(d) { return d.target.y; });

                      node
                        .attr("cx", function(d) { return d.x; })
                        .attr("cy", function(d) { return d.y; });

                     text
                        .attr("x", function(d) { return d.x; })
                        .attr("y", function(d) { return d.y; });

                    }

                    );

                simulation.force("link")
                    .links(links);

              });
</code>```

答: Your function only moves the g that contains the nodes. It doesn't update the underlying data (d.x and d.y) that is attached to the nodes. So while they visually move, it isn't because the force (or your code) has updated the d.x or d.y values.</p>

Body:
in D3.js I use the force-layout to shift all nodes to the right with this code below. But when call the function, only the nodes shift, the text and links stay the same. What exactly is missing here? Is it the tick() function that has to be called inside the function?

  function(){ d3.select(".nodes").attr("transform", "translate(200,0)");

                simulation.alpha(0.8).restart();

};

        simulation
                    .nodes(nodes)
                    .on("tick", function(d)
                    {

                      link
                        .attr("x1", function(d) { return d.source.x; })
                        .attr("y1", function(d) { return d.source.y; })
                        .attr("x2", function(d) { return d.target.x; })
                        .attr("y2", function(d) { return d.target.y; });

                      node
                        .attr("cx", function(d) { return d.x; })
                        .attr("cy", function(d) { return d.y; });

                     text
                        .attr("x", function(d) { return d.x; })
                        .attr("y", function(d) { return d.y; });

                    }

                    );

                simulation.force("link")
                    .links(links);

              });


答:
You can try many steps in a nutshell

First perform an EXPLAIN statement and act accordingly

Make sure the compared attributes are of equal length

Make your keys as short as possible

Consider adding indexes where you need too, (in the WHERE clause if the values are suitable for indexing, and you perform this query very often)

Make an ANALYZE TABLE

Avoid any redundant data or with NULL values as much as possible

Title: Why mysql query takes long before received results?


问:
Convert OLECHAR* to CString in VC++?
How to convert OLECHAR* to CString in VC++ ?

答:
OLECHAR* is the same as BSTR.  You can convert to CString like this (sorry about formatting, I have lost the code icon for now).

OLECHAR* value;

BSTR (bstrValue(value));

_bstr_t tmp(bstr, FALSE);   //wrap the BSTR

CString cs(static_cast<const char*>(tmp));  //convert it

Title: Convert OLECHAR* to CString in VC++?

ContentLicense: CC BY-SA 2.5


问:
Replace occurrence of string in another string with Numbers in PHP
I have a html string code which contain some "img" tags. I want to search the string and change each "<img " occurrence with something like "<img onclick=lightbox(XXXX)", so the first one should become "<img onclick=lightbox(0)" then the second occurrence should become "<img onclick=lightbox(1)" and then third one should become "<img onclick=lightbox(2)" and etc,  How can I achieve this in PHP?

答:
A regex-based solution which is a little more elegant and should be a lot faster:</p>

```<code><?php
$string = "<img /><img />";
$i = 0;
$newString = preg_replace_callback( '/<img /', function() use (&$i){
    return '<img onclick="lightbox(' . ($i++) . ');" ';
},$string);
echo $newString;
</code>```

Body:
A regex-based solution which is a little more elegant and should be a lot faster:

<?php
$string = "<img /><img />";
$i = 0;
$newString = preg_replace_callback( '/<img /', function() use (&$i){
    return '<img onclick="lightbox(' . ($i++) . ');" ';
},$string);
echo $newString;


问:
Basic Configuration of Golang App in Nginx
I have a CentOS 7 server where I have running some Golang apps. As you know, every app is running on his own port, lets say: 9000,9100,9200 and so on.

Now, I have installed Nginx to serve all the websites, I have a domain for every site and I want to receive all the petitions in the port 80 and then just based on the domain i have to redirect to the application that corresponds.

By now,am trying to make it with one of the site that is running in the port 9094, I have no experience with Nginx so I was just reading to know what to do,but it seems like it's not working. in the file nginx.conf I added these lines:

```<code>server {
                listen          80;
                server_name     mydomain.com;
                access_log      logs/mydomain.log main;

                location / {
                        proxy_pass      http://127.0.0.1:9094;
                }
        }
</code>```

I have to mention that I didn't delete these lines that comes for default in the file:

```<code>  server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }
</code>```

Is the configuration ok? and will allow me to add more sites? Thank you
If I ping to the domain everything is ok, but if I open the domain in the browser then I get status code 502

EDIT:

```<code>http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

        server {
                listen          80;
                server_name     mydomain.com;
                access_log      logs/mydomain.log main;

                location / {
                        proxy_pass      http://127.0.0.1:9094;
                }
        }

}
</code>```

答: Your server configuration looks okay and the 502 Status Code means you didn't configure the Go servers correctly. Specifically, Nginx did exactly what you expected it to, proxied the request to and from your upstream, but received an invalid response from your Go server.</p>

Body:
I have a CentOS 7 server where I have running some Golang apps. As you know, every app is running on his own port, lets say: 9000,9100,9200 and so on.

Now, I have installed Nginx to serve all the websites, I have a domain for every site and I want to receive all the petitions in the port 80 and then just based on the domain i have to redirect to the application that corresponds.

By now,am trying to make it with one of the site that is running in the port 9094, I have no experience with Nginx so I was just reading to know what to do,but it seems like it's not working. in the file nginx.conf I added these lines:

server {
                listen          80;
                server_name     mydomain.com;
                access_log      logs/mydomain.log main;

                location / {
                        proxy_pass      http://127.0.0.1:9094;
                }
        }

I have to mention that I didn't delete these lines that comes for default in the file:

  server {
        listen       80 default_server;
        listen       [::]:80 default_server;
        server_name  _;
        root         /usr/share/nginx/html;

        # Load configuration files for the default server block.
        include /etc/nginx/default.d/*.conf;

        location / {
        }

        error_page 404 /404.html;
            location = /40x.html {
        }

        error_page 500 502 503 504 /50x.html;
            location = /50x.html {
        }
    }

Is the configuration ok? and will allow me to add more sites? Thank you
If I ping to the domain everything is ok, but if I open the domain in the browser then I get status code 502

EDIT:

http {
    log_format  main  '$remote_addr - $remote_user [$time_local] "$request" '
                      '$status $body_bytes_sent "$http_referer" '
                      '"$http_user_agent" "$http_x_forwarded_for"';

    access_log  /var/log/nginx/access.log  main;

    sendfile            on;
    tcp_nopush          on;
    tcp_nodelay         on;
    keepalive_timeout   65;
    types_hash_max_size 2048;

    include             /etc/nginx/mime.types;
    default_type        application/octet-stream;

    # Load modular configuration files from the /etc/nginx/conf.d directory.
    # See http://nginx.org/en/docs/ngx_core_module.html#include
    # for more information.
    include /etc/nginx/conf.d/*.conf;

        server {
                listen          80;
                server_name     mydomain.com;
                access_log      logs/mydomain.log main;

                location / {
                        proxy_pass      http://127.0.0.1:9094;
                }
        }

}


问:
Confused why Time.deltaTime causes uneven movement
I'm trying to move an object so that it moves visually at the same speed regardless of frame rate fluctuations.  From my understanding, I should be using Time.deltaTime to determine how far to move during each iteration of Update.  My Update code is like this:

```<code>void Update()
{
    this.rigidBody.MovePosition(this.transform.position + new Vector3(Time.deltaTime * 2f, 0, 0));
}
</code>```

However, the object moves in faster and slower spurts as it moves across the screen.  If I move it a constant amount during each Update (like below), it appears to move evenly.

```<code>void Update()
{
    this.rigidBody.MovePosition(this.transform.position + new Vector3(0.02f, 0, 0));
}
</code>```

I'm confused because I thought that moving an object a constant distance during each Update should be the thing that causes jitter since its speed would be affected by the frame rate.  And I thought that using Time.deltaTime should cause a constant rate of framerate-independent movement.

My Time.deltaTime values vary between 0.002 to 0.17, which I also don't understand because I have a very simple scene of only 2D sprites so I don't understand why the variance is so great.

答:
If you want to calculate the exact new position of your RigidBody, you should just set the position directly. E.g.:

```<code>this.rigidBody.position += new Vector3(Time.deltaTime * 2f, 0, 0);
</code>```

Alternatively, execute the code you already have, but in the FixedUpdate() method.

The MovePosition() is intended to be used in the context of the FixedUpdate() method. Unity3d will attempt to calculate a movement rate according to the frame rate that will interpolate positions between the current position and the new position. You're confusing it by also doing that interpolation and using the result when you call MovePosition().

Body:
I'm trying to move an object so that it moves visually at the same speed regardless of frame rate fluctuations.  From my understanding, I should be using Time.deltaTime to determine how far to move during each iteration of Update.  My Update code is like this:

void Update()
{
    this.rigidBody.MovePosition(this.transform.position + new Vector3(Time.deltaTime * 2f, 0, 0));
}

However, the object moves in faster and slower spurts as it moves across the screen.  If I move it a constant amount during each Update (like below), it appears to move evenly.

void Update()
{
    this.rigidBody.MovePosition(this.transform.position + new Vector3(0.02f, 0, 0));
}

I'm confused because I thought that moving an object a constant distance during each Update should be the thing that causes jitter since its speed would be affected by the frame rate.  And I thought that using Time.deltaTime should cause a constant rate of framerate-independent movement.

My Time.deltaTime values vary between 0.002 to 0.17, which I also don't understand because I have a very simple scene of only 2D sprites so I don't understand why the variance is so great.

Body:
If you want to calculate the exact new position of your RigidBody, you should just set the position directly. E.g.:

this.rigidBody.position += new Vector3(Time.deltaTime * 2f, 0, 0);

Alternatively, execute the code you already have, but in the FixedUpdate() method.

The MovePosition() is intended to be used in the context of the FixedUpdate() method. Unity3d will attempt to calculate a movement rate according to the frame rate that will interpolate positions between the current position and the new position. You're confusing it by also doing that interpolation and using the result when you call MovePosition().


问:
HTML/JS projects working independently, failing when combined
I would like to apologize for my ignorance on this subject in advance, I am very new to this! I have two projects that work independently, but when they are combined do not. The first project is a fullPage.js project, and the second a (cursor) parallax project. The working project files are as follows:

Cursor Parallax:

```<code><!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery Mouse Parallax Plugin Demo</title>

    <script src="https://code.jquery.com/jquery-1.11.3.min.js" type="text/javascript" charset="utf-8"></script>
    <script src="http://cdnjs.cloudflare.com/ajax/libs/gsap/1.17.0/TweenMax.min.js"></script>
    <script src="../jquery-parallax.js"></script>

    <script>
      $( document ).mousemove( function( e ) {
        $( '.background' ).parallax( -30, e );
        $( '.cloud1' )    .parallax( 10 , e );
        $( '.cloud2' )    .parallax( 20 , e );
        $( '.cloud3' )    .parallax( 30 , e );
      });
    </script>
    <script type="text/javascript">

      var _gaq = _gaq || [];
      _gaq.push(['_setAccount', 'UA-36251023-1']);
      _gaq.push(['_setDomainName', 'jqueryscript.net']);
      _gaq.push(['_trackPageview']);

      (function() {
        var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
        ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
      })();
    </script>

    <style>

      body {
        padding: 0; margin: 0;
        overflow: hidden;
      }

      .background {
        position: absolute; top: -10%; left: -10%;
        width: 120%; height: 120%;
        z-index: 1;
        font-family: Courier;
      }

      .cloud {
        position: absolute;
        margin-top: 100px;
        margin-left: 100px;
        width: auto; height: auto;
        z-index: 2;
        opacity: 0.8;
      }
    </style>
  </head>
  <body>
    <img src="imgs/background.jpg" alt="New York" class="background">

    <img src="imgs/BigCircles.png" alt="Clouds" class="cloud cloud1">
    <img src="imgs/mediumCircles.png" alt="Clouds" class="cloud cloud2">
    <img src="imgs/smallCircles.png" alt="Clouds" class="cloud cloud3">
  </body>
</html>
</code>```

https://pastebin.com/bDSnQ2Nz

(for easier viewing ^)

fullPage.js

```<code><!DOCTYPE html>

<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello There.</title>

<link rel="stylesheet" type="text/css" href="../jquery.fullPage.css" />
<link rel="stylesheet" type="text/css" href="examples.css" />
<link href='https://fonts.googleapis.com/css?family=Six Caps' rel='stylesheet'>
<link href="//fonts.googleapis.com/css?family=Playfair+Display" rel='stylesheet' type="text/css" />
<style>
body{
  padding: 0; margin: 0;
  overflow: hidden;

}

.background {
  position: absolute;
  z-index: 1;
}

.cloud {
  position: absolute;
  margin-top: 100px;
  margin-left: 100px;
  width: auto; height: auto;
  z-index: 2;
  opacity: 0.8;
}
/* Style for our header texts
* --------------------------------------- */
h1{
  font-size: 50px;
  font-family: "Six Caps";
  margin:0;
  padding:0;

}
h2{
  font-size: 65px;
  color: #5b5a57;
  line-height: 100%;
  letter-spacing: 5px;
  margin: 0 0 18px 0;
  font-family: "Six Caps";
}
h3 {
  font-family: "Playfair Display";
  font-weight: 100;
  font-size: 1px;
  letter-spacing: 1px;

}
table {
  font-family: "Six Caps";
  font-size: 20px;
  letter-spacing: 2px;
  border-collapse: collapse;
  width: 80%;

}
td, th {
  text-align: left;
  padding: 0px;
  padding-top: 10px;
}

/* Common styles
* --------------------------------------- */
img{
  -webkit-transition: all 0.7s ease-out;
  -moz-transition: all 0.7s ease-out;
  -o-transition: all 0.7s ease-out;
  transition: all 0.7s ease-out;
}
.section{
  text-align:center;
  overflow:hidden;
}
.wrap{
  width: 1180px;
  height: 100%;
  margin-left: auto;
  margin-right: auto;
  position: relative;

}
.box{
  text-align: left;
  color: #5b5a57;
  font-size: 14px;
  line-height: 25px;
  font-family: "Playfair Display";

}

span {
  opacity: 0.5;
}

/* Section 0
* --------------------------------------- */
#section0{
  padding: 60px 0;
}
#section0 img{
  height: 100%;
  margin: 40px 0 0 0;
}

#container {
  width: 100%;
  height: 400px;
  background: url("imgs/backgroundImage.png");
}

/* Section 1
* --------------------------------------- */
#section1 img{
  position:absolute;
}
#section1 {
  background-image: url("imgs/backgroundImage.png");
  background-size: 100%;
}
#section1 .imgsContainer,
#staticImg .imgsContainer,
#section3 .imgsContainer{
  position: absolute;
  z-index: 1;
  left: 50%;
  display: block;
  margin-top: -288px;
  margin-left: -636px;
  width: 0;
  height: 0;

  -webkit-transition: all 1.2s ease-in-out;
  -moz-transition: all 1.2s ease-in-out;
  -o-transition: all 1.2s ease-in-out;
  transition: all 1.2s ease-in-out;
}

#section1.moveUp .imgsContainer{
  top: 50%;
}

#section1.moveDown .imgsContainer,
#staticImg .imgsContainer{
  top: 90%;
}

#section1.active .imgsContainer{
  top: 50%;
}

#iphone2{
  z-index: 100;
}
#iphone2.active{
  -webkit-transform: translate3d(+300px, 0px, 0px);
  -moz-transform: translate3d(+300px, 0px, 0px);
  -ms-transform:translate3d(+300px, 0px, 0px);
  transform: translate3d(+300px, 0px, 0px);
}

#section1 .box{
  top: 22%;
  left: 42%;
  position: absolute;
  width: 582px;

}

#iphone2 {
  top: -50px;
  left: -425px;
}

#iphone3 {
  top: -50px;
  left: 106px;
}

#staticImg{
  display: block;
  position: absolute;
  z-index: 1;
  top: 200%;
  left: 0;
  width: 100%;
  min-width: 980px;
  height: 100%;

  -webkit-transition: all 0.7s ease-out;
  -moz-transition: all 0.7s ease-out;
  -o-transition: all 0.7s ease-out;
  transition: all 0.7s ease-out;

  -webkit-backface-visibility: hidden;
  -webkit-perspective: 1000;
}
#staticImg.moveDown{
  -webkit-transform: translate3d(0, 100%, 0);
  -ms-transform: translate3d(0, 100%, 0);
  transform: translate3d(0, 100%, 0);
}
#staticImg.moveUp{

  -webkit-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
}
#staticImg.moveDown .imgsContainer{
  top: 50%;
}
#staticImg.moveDown img{
  top: 155px;
}

#staticImg.active .imgsContainer{
  top: 50%;
}

#staticImg.active img{
  top: 487px;
}

.cloud {
  position: absolute;
  margin-top: 100px;
  margin-left: 100px;
  width: auto; height: auto;
  z-index: 150;
}

/* Section 2
* --------------------------------------- */
#section2 img{
  position:absolute;
}
#section2 .imgsContainer,
#staticImg .imgsContainer,
#section3 .imgsContainer{
  position: absolute;
  z-index: 1;
  left: 50%;
  display: block;
  margin-top: -288px;
  margin-left: -636px;
  width: 0;
  height: 0;

  -webkit-transition: all 1.2s ease-in-out;
  -moz-transition: all 1.2s ease-in-out;
  -o-transition: all 1.2s ease-in-out;
  transition: all 1.2s ease-in-out;
}

#section2.moveUp .imgsContainer{
  top: 50%;
}

#section2.moveDown .imgsContainer,
#staticImg .imgsContainer{
  top: 90%;
}

#section2.active .imgsContainer{
  top: 50%;
}

#section2 .box{
  top: 22%;
  left: 42%;
  position: absolute;
  width: 582px;
}

#iphone-yellow{
  top: -35px;
  left: -222px;
}

#iphone-red{
  top: -194px;
  left: 106px;
}

#iphone-blue{
  top: 320px;
  left: 448px;
}

#iphone-green{
  left: 106px;
  position:absolute;
}

#staticImg{
  display: block;
  position: absolute;
  z-index: 1;
  top: 200%;
  left: 0;
  width: 100%;
  min-width: 980px;
  height: 100%;

  -webkit-transition: all 0.7s ease-out;
  -moz-transition: all 0.7s ease-out;
  -o-transition: all 0.7s ease-out;
  transition: all 0.7s ease-out;

  -webkit-backface-visibility: hidden;
  -webkit-perspective: 1000;
}
#staticImg.moveDown{
  -webkit-transform: translate3d(0, 100%, 0);
  -ms-transform: translate3d(0, 100%, 0);
  transform: translate3d(0, 100%, 0);
}
#staticImg.moveUp{

  -webkit-transform: translate3d(0, 0, 0);
  -ms-transform: translate3d(0, 0, 0);
  transform: translate3d(0, 0, 0);
}
#staticImg.moveDown .imgsContainer{
  top: 50%;
}
#staticImg.moveDown img{
  top: 155px;
}

#staticImg.active .imgsContainer{
  top: 50%;
}

#staticImg.active img{
  top: 487px;
}

/* Overwriting fullPage.js tooltip color
* --------------------------------------- */
.fp-tooltip{
  color: #AAA;
}
#fp-nav span, .fp-slidesNav span{
  border-color: #AAA;
}
#fp-nav li .active span, .fp-slidesNav .active span{
  background: #AAA;
}

</style>

<!--[if IE]>
<script type="text/javascript">
var console = { log: function() {} };
</script>
<![endif]-->

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>

<script type="text/javascript" src="../jquery.fullPage.js"></script>
<script type="text/javascript" src="examples.js"></script>

<script type="text/javascript">
  $(document).ready(function() {
    $('#fullpage').fullpage({
      'verticalCentered': false,
      'css3': true,
      'sectionsColor': ['#F0F2F4', '#f7f3eb', '#fff', '#fff'],
      'navigation': true,
      'navigationPosition': 'right',
      'navigationTooltips': ['fullPage.js', 'Powerful', 'Amazing', 'Simple'],

      'afterLoad': function(anchorLink, index){
        if(index == 2){
          $('#iphone3, #iphone2, #iphone4').addClass('active');
        }
      },

      'onLeave': function(index, nextIndex, direction){
        if (index == 3 && direction == 'down'){
          $('.section').eq(index -1).removeClass('moveDown').addClass('moveUp');
        }
        else if(index == 3 && direction == 'up'){
          $('.section').eq(index -1).removeClass('moveUp').addClass('moveDown');
        }

        $('#staticImg').toggleClass('active', (index == 2 && direction == 'down' ) || (index == 4 && direction == 'up'));
        $('#staticImg').toggleClass('moveDown', nextIndex == 4);
        $('#staticImg').toggleClass('moveUp', index == 4 && direction == 'up');
      }
    });
  });
</script>

</head>

<body>
  <div id="fullpage">
    <div id="staticImg">
      <div class="imgsContainer">
        <img src="imgs/Mockup.png" alt="iphone" id="iphone-green" />
      </div>
    </div>

    <div class="section " id="section0">
      <h1>Hello There.</h1>
      <img src="imgs/iphone1.jpg" alt="iphone" />
    </div>
    <div class="section moveDown" id="section1">
      <div class="wrap">
        <div class="imgsContainer">
          <img src="imgs/iphone3.png" alt="iphone" id="iphone3" />
          <img src="imgs/iphone2.png" alt="iphone" id="iphone2" />
        </div>
        <div class="box">
          <h1>01.</h1>
          <h2>Some Text</h2>
          <span>Even more text</span>
          <table>
            <tr>
              <th>Role</th>
              <th>Year</th>
              <th>Compensation</th>
            </tr>
            <tr>
              <td>Sole</td>
              <td>2016-2017</td>
              <td>Volunteer</td>
            </tr>
          </table>

        </div>
      </div>
    </div>
    <div class="section moveDown" id="section2">
      <div class="wrap">
        <div class="imgsContainer">
          <img src="imgs/iphone-yellow.png" alt="iphone" id="iphone-yellow" />
          <img src="imgs/iphone-red.png" alt="iphone" id="iphone-red" />
          <img src="imgs/iphone-blue.png" alt="iphone" id="iphone-blue" />
        </div>

        <div class="box">
          <h2>Amazing stuff</h2>
          Combining <strong>fullPage.js</strong> with your own CSS styles and animations, you will be able to create something remarkable.

        </div>
      </div>
    </div>
  </div>
</body>

</html>
</code>```

(For easier viewing ^)

When I try to combine them, for some reason, they do not work. In particular when it seems to fail is when I add the:

```<code><script src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.1/jquery-ui.min.js"></script>

<script type="text/javascript" src="../jquery.fullPage.js"></script>
<script type="text/javascript" src="examples.js"></script>

<script type="text/javascript">
  $(document).ready(function() {
    $('#fullpage').fullpage({
      'verticalCentered': false,
      'css3': true,
      'sectionsColor': ['#F0F2F4', '#f7f3eb', '#fff', '#fff'],
      'navigation': true,
      'navigationPosition': 'right',
      'navigationTooltips': ['fullPage.js', 'Powerful', 'Amazing', 'Simple'],

      'afterLoad': function(anchorLink, index){
        if(index == 2){
          $('#iphone3, #iphone2, #iphone4').addClass('active');
        }
      },

      'onLeave': function(index, nextIndex, direction){
        if (index == 3 && direction == 'down'){
          $('.section').eq(index -1).removeClass('moveDown').addClass('moveUp');
        }
        else if(index == 3 && direction == 'up'){
          $('.section').eq(index -1).removeClass('moveUp').addClass('moveDown');
        }

        $('#staticImg').toggleClass('active', (index == 2 && direction == 'down' ) || (index == 4 && direction == 'up'));
        $('#staticImg').toggleClass('moveDown', nextIndex == 4);
        $('#staticImg').toggleClass('moveUp', index == 4 && direction == 'up');
      }
    });
  });
</script>
</code>```

To the parallax folder, it "breaks" the parallax movement. Any help you could provide would be very much appreciated!! Thank you all!

答:
The Console clearly tells the problem: Uncaught TypeError: $(...).parallax is not a function, maybe I'm missing something, but I'm sure you haven't called:

```<code><script src="jquery-parallax.js"></script>
</code>```

Body:
I would like to apologize for my ignorance on this subject in advance, I am very new to this! I have two projects that work independently, but when they are combined do not. The first project is a fullPage.js project, and the second a (cursor) parallax project. The working project files are as follows:

Cursor Parallax:

<!doctype html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>jQuery Mouse Parallax Plugin Demo</title>

https://pastebin.com/bDSnQ2Nz

(for easier viewing ^)

fullPage.js

<!DOCTYPE html>

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Hello There.</title>

<link rel="stylesheet" type="text/css" href="../jquery.fullPage.css" />
<link rel="stylesheet" type="text/css" href="examples.css" />
<link href='https://fonts.googleapis.com/css?family=Six Caps' rel='stylesheet'>
<link href="//fonts.googleapis.com/css?family=Playfair+Display" rel='stylesheet' type="text/css" />

Hello There.

01.

Some Text

          Even more text

              Role
              Year
              Compensation

              Sole
              2016-2017
              Volunteer

Amazing stuff

          Combining fullPage.js with your own CSS styles and animations, you will be able to create something remarkable.

(For easier viewing ^)

When I try to combine them, for some reason, they do not work. In particular when it seems to fail is when I add the:

To the parallax folder, it "breaks" the parallax movement. Any help you could provide would be very much appreciated!! Thank you all!

Body:
The Console clearly tells the problem: Uncaught TypeError: $(...).parallax is not a function, maybe I'm missing something, but I'm sure you haven't called:

<script src="jquery-parallax.js"></script>


问:
How to do pinch-and-zoom with a touchpad on ChromeOS/Android?
I have an Android app which I'm running on a Chromebook.  I have views which scale with pinch-and-zoom gestures when the user touches the device's screen, and these work fine on the Chromebook.  I'm trying to get pinch-and-zoom working with the touchpad as well.

I can three-finger drag scrollable elements.  I can two-finger drag and it drags around screen elements where dragging makes sense.  I still get hover events and the events claim there are two pointers, so that's all good.  However, as soon as the fingers start moving in opposing directions, the event stream stops.

Is there any way I can get the unfiltered everything input event stream so I can see what's going on?  I feel like the emulation layer's best-effort attempt to make everything "just work" (and it's a really good effort!) is biting me here.  I also notice that some events are coming in as generic motion events, and some are coming in as touch events.  And some, like tap-to-click do some of each.  If it matters, the input device data for ChromeOS Mouse claims it has the ( touchscreen mouse ) sources, which mostly makes sense.  Except shouldn't it be touchpad instead since it's not directly attached to a display?

On this page, list item #5 implies that some kind of synthetic event might be created and used somehow.  Is there any way to see if those are being generated?  And if yes, how would I take advantage?

Help!

A little more detail:  Single finger operation of the touchpad gives me ACTION_HOVER_MOVE generic events.  Two-finger drag gives me ACTION_MOVE touch events so long as both fingers are moving together.  As soon as they start heading in different directions, the event stream stops.

答:
Pinch-to-zoom support for Touchpad is still work in progress. Once it is there, it will work seamlessly with the standard gesture recognizer used for touchscreen zoom as well, you should not have to do anything.

I can highly recommend upgrading to API level 24 if you want to target Chromebooks, there are also more details on input devices on Chromebooks to be found here: https://developer.android.com/topic/arc/input-compatibility.html

edit: The "touchpad" device type is very confusingly named. It is reserved for off-screen devices. The touchpad is treated as a mouse since it moves the mouse cursor on screen.


问:
Predicting on new data using locally weighted regression (LOESS/LOWESS)
How to fit a locally weighted regression in python so that it can be used to predict on new data?

There is statsmodels.nonparametric.smoothers_lowess.lowess, but it returns the estimates only for the original data set; so it seems to only do fit and predict together, rather than separately as I expected.

scikit-learn always has a fit method that allows the object to be used later on new data with predict; but it doesn't implement lowess.

答:
Consider using Kernel Regression instead.

statmodels has an implementation.

If you have too many data points, why not use sk.learn's radiusNeighborRegression and specify a tricube weighting function?


问:
How to prevent jumping in bootstrap affix when window is narrow height?
When search results is few than page height is narrow and affix sidebar is jumping when scrolling. I tryed to make min-height of main container  greater then sidebar but it does not look nice. How to disable affix-bottom or work around to prevent jumping when window height is narrow?

Template presents my current application: jsfiddle

JS:

```<code>$('#sidebar').affix({});
</code>```

HTML:

```<code><div id="nav" class="navbar"></div>
<div id="content" class="container">
    <div class="row">
        <div class="col-sm-7 col-md-7 main"></div>
        <div class="col-sm-5 col-md-5">
            <div class="sidebar-fixed" data-spy="affix" data-offset-top="60" data-offset-bottom="50" id="sidebar"></div>
        </div>
    </div>
</div>
<footer class="container"></footer>
</code>```

CSS:

```<code>body {
    position: relative;
}
.navbar {
    height: 60px;
    background-color: #dce7ed;
}
.main {
    background-color: #9fc8e3;
    height: 390px;
    margin-top: 60px;
}
#sidebar {
    background-color: #d5cbc6;
    height: 400px;
    margin-top: 60px;
}
#sidebar.affix-top {
    position: static;
}
#sidebar.affix {
    position: fixed;
    top: 20px;
    width: 283px;
}
#sidebar.affix-bottom {
    position: absolute;
    /* bottom: 50px; */
    top: auto;
    bottom: 50px;
}
footer {
    height: 50px;
    background-color: #dce7ed;
}
</code>```

答:
Try implementing this in your internal or external CSS file.

```<code>.affix + .container-fluid {
         padding-top: 0px;
         margin-top: 50px;
     }
</code>```

Replace the margin-top with the height of your navbar.
Hope this helps.
Also, bear in mind that this is for container-fluid. If you would like this CSS to work on container classed div elements replace container-fluid with container.

Body:
When search results is few than page height is narrow and affix sidebar is jumping when scrolling. I tryed to make min-height of main container  greater then sidebar but it does not look nice. How to disable affix-bottom or work around to prevent jumping when window height is narrow?

Template presents my current application: jsfiddle

JS:

$('#sidebar').affix({});

HTML:

CSS:

body {
    position: relative;
}
.navbar {
    height: 60px;
    background-color: #dce7ed;
}
.main {
    background-color: #9fc8e3;
    height: 390px;
    margin-top: 60px;
}
#sidebar {
    background-color: #d5cbc6;
    height: 400px;
    margin-top: 60px;
}
#sidebar.affix-top {
    position: static;
}
#sidebar.affix {
    position: fixed;
    top: 20px;
    width: 283px;
}
#sidebar.affix-bottom {
    position: absolute;
    /* bottom: 50px; */
    top: auto;
    bottom: 50px;
}
footer {
    height: 50px;
    background-color: #dce7ed;
}

Body:
Try implementing this in your internal or external CSS file.

.affix + .container-fluid {
         padding-top: 0px;
         margin-top: 50px;
     }

Replace the margin-top with the height of your navbar.
Hope this helps.
Also, bear in mind that this is for container-fluid. If you would like this CSS to work on container classed div elements replace container-fluid with container.


问:
Attachment_fu or Paperclip for Rails3
I have just upgraded to rails3 and when I installed my usual attachment_fu plugin failed.  So I started googling it and although I did manage to find a rails3 version there seemed to be a lot more people talking about paperclip with rails3.

So firstly what are the advantages of paperclip?

Is there better support for rails3 with it?

答:
I made attachment_fu rails3 compatible.

See https://github.com/mihael/attachment_fu

EDIT: but it is broken for some users, and i am not maintaining it further, so please look into other solutions, if you do not want to hack it yourself ;)

I tested paperclip vs carrierwave vs attachment_fu with rails3.0.3 for a project I am working on.

So far attachment_fu works very well as always, but the code still needs some refactoring with the callback system. It has backends for cloudfiles, s3.

Paperclip is also very good and is very easy to use. The basic setup did not let me upload movies (had to add option :whiny=>false), and it did not sanitize filenames the way I expected. This is how I did it:

```<code>class Asset < ActiveRecord::Base
  has_attached_file :file, :styles => { :small => "300x300>", :thumb => "50x50>" }, :whiny => false
  before_create :sanitize_file_name
  private
  def sanitize_file_name
    self.file.instance_write( :file_name,  file_file_name.gsub(/[^A-Za-z0-9\.\-]/, '_'))
  end
end
</code>```

Paperclip has s3 backend, but does not have a backend for cloudfiles built-in. There is a paperclip fork for that (google for paperclip-cloudfiles) which is built for rails2.3.5 (search github for paperclip_demo).

Carrierwave looks very nice, with the decoupled architecture, but I do not like the fact that it does not delete stuff on updates and destroys of objects, leaving a bunch of files and directories on disk. The basic carrierwave setup also did not let me upload movies, although it sanitizes filenames nicely. I did not found a quick fix for this, yet. If You are using Mongoid and GridFS, carrierwave has built in support.

Finally, I took Paperclip for my project.

Title: Attachment_fu or Paperclip for Rails3

Body:
I made attachment_fu rails3 compatible.

See https://github.com/mihael/attachment_fu

EDIT: but it is broken for some users, and i am not maintaining it further, so please look into other solutions, if you do not want to hack it yourself ;)

I tested paperclip vs carrierwave vs attachment_fu with rails3.0.3 for a project I am working on.

So far attachment_fu works very well as always, but the code still needs some refactoring with the callback system. It has backends for cloudfiles, s3.

Paperclip is also very good and is very easy to use. The basic setup did not let me upload movies (had to add option :whiny=>false), and it did not sanitize filenames the way I expected. This is how I did it:

class Asset < ActiveRecord::Base
  has_attached_file :file, :styles => { :small => "300x300>", :thumb => "50x50>" }, :whiny => false
  before_create :sanitize_file_name
  private
  def sanitize_file_name
    self.file.instance_write( :file_name,  file_file_name.gsub(/[^A-Za-z0-9\.\-]/, '_'))
  end
end

Paperclip has s3 backend, but does not have a backend for cloudfiles built-in. There is a paperclip fork for that (google for paperclip-cloudfiles) which is built for rails2.3.5 (search github for paperclip_demo).

Carrierwave looks very nice, with the decoupled architecture, but I do not like the fact that it does not delete stuff on updates and destroys of objects, leaving a bunch of files and directories on disk. The basic carrierwave setup also did not let me upload movies, although it sanitizes filenames nicely. I did not found a quick fix for this, yet. If You are using Mongoid and GridFS, carrierwave has built in support.

Finally, I took Paperclip for my project.


问:
How to calculate age in query?Age search
Hello I have a table divided by year months and day

How do I calculate age to use it in an input?
The code that invokes the input is..

```<code>if(isset($keyage)){

$keyag = "AND bday_month LIKE '".$keyage."'";

}
</code>```

But the research is based only on the month, how can I look through age-
Thank you

答:
Try this to compute your age according to your sample data:</p>

```<code>select case when m_now>m_table then age
            when m_now=m_table THEN
                 case when d_now=d_table then age ELSE
                       case when d_now<=d_table then age-1 else age end

       end
ELSE age -1 END as age from

(select day(date(now()))d_now,day(date(CONCAT_WS('-',bday_year,bday_month,bday_day))) d_table,
month(date(now()))m_now, month(date(CONCAT_WS('-',bday_year,bday_month,bday_day)))m_table,
year(date(now()))-year(date(CONCAT_WS('-',bday_year,bday_month,bday_day))) age from
(Select 4 bday_month, 1 as bday_day , 1981 bday_year) as a) as a
</code>```

Body:
Hello I have a table divided by year months and day

How do I calculate age to use it in an input?
The code that invokes the input is..

if(isset($keyage)){

$keyag = "AND bday_month LIKE '".$keyage."'";

}

But the research is based only on the month, how can I look through age-
Thank you

Body:
Try this to compute your age according to your sample data:

select case when m_now>m_table then age
            when m_now=m_table THEN
                 case when d_now=d_table then age ELSE
                       case when d_now<=d_table then age-1 else age end

       end
ELSE age -1 END as age from

(select day(date(now()))d_now,day(date(CONCAT_WS('-',bday_year,bday_month,bday_day))) d_table,
month(date(now()))m_now, month(date(CONCAT_WS('-',bday_year,bday_month,bday_day)))m_table,
year(date(now()))-year(date(CONCAT_WS('-',bday_year,bday_month,bday_day))) age from
(Select 4 bday_month, 1 as bday_day , 1981 bday_year) as a) as a


问:
AWS Elastic Load Balancer not Forwarding HTTP Headers to EC2 Instance
I'm currently running a Python Flask Application on Amazon Elastic Beanstalk. When I test the application, it all works fine locally (I used Postman to send the GET & POST requests). However, on AWS, it doesn't work because the request that gets to my EC2 instances (behind the load balancer) does not include the Authorization header. It seems like the load balancer strips off the header. Is there something I'm doing wrong here?

Here's a comparison of what I get when I print out the header locally and on Elastic Beanstalk.

Locally

[2017-07-04 13:18:14,650] [INFO] [common.decorators] Headers = Host: localhost:5000
Connection: keep-alive
Content-Length: 151
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36
Cache-Control: no-cache
Origin: chrome-extension://fhbjgbiflinjbdggehcddcbncdddomop
Content-Type: application/json
Authorization: Bearer ad9fd4d9-6ce6-497b-855a-dcebebdad65b
Postman-Token: xxxxx
Accept: */*
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8

Elastic Beanstalk:

[2017-07-04 17:27:03,813] [DEBUG] [common.decorators] Headers = Accept-Language: en-US,en;q=0.8
Accept: */*
Host: dev.onetext.com
X-Forwarded-For: 66.30.13.108
Content-Type: application/json
Postman-Token: xxxxx
Connection: keep-alive
Accept-Encoding: gzip, deflate, sdch, br
X-Forwarded-Proto: https
Cache-Control: no-cache
X-Forwarded-Port: 443
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.110 Safari/537.36

答:
Thanks to the comment added by @notionquest, I found the solution at https://forums.aws.amazon.com/thread.jspa?messageID=729128

I solved this by adding a new file under the .ebextensions folder with the following content:

files:
  "/etc/httpd/conf.d/wsgihacks.conf":
    mode: "000644"
    owner: root
    group: root
    content: |
      WSGIPassAuthorization On


问:
Azure ad b2c authentication challenge loses session object
I am using the github example active-directory-b2c-dotnet-webapp-and-webapi.

I configured my own b2c tenant and got the MVC sample to work successfully.

However, I need this to work with a WebForms app. I created a new Webforms app, checked that the references were pointing to the same versions of the dlls as the working sample and adjusted the code to work in WebForms.

Everything works up until the time that I issue the Authentication.Challenge and process the AuthorizationCodeReceivedNotification in the OnAuthorizationCodeReceived function.

The Session object in notification.OwinContext.Environment["System.Web.HttpContextBase"] is null whereas at this point in the MVC sample the session object in notification.OwinContext.Environment["System.Web.HttpContextBase"].Session is a System.Web.HttpSessionStateWrapper with a valid SessionId.

In WebForms, HttpContext.GetOwinContext throws an error as not being available, so I then tried HttpContext.Current.GetOwinContext which returned an HttpContext object instead of a HttpContextBase object. So I finally used

```<code>if (!Request.IsAuthenticated)
{
   HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
   context.GetOwinContext().Authentication.Challenge();
   return;
}
</code>```

instead of the following which is used in the MVC sample

```<code>if (!Request.IsAuthenticated)
{
   HttpContext.GetOwinContext().Authentication.Challenge();
   return;
}
</code>```

At this point in the code, in both MVC and WebForms the Authentication object has a valid Session object in its OwinContext.Environment prior to the Challenge being issued. The problem is that whilst in the MVC version the resulting notification includes the session object, the WebForms version of the notification has a null object.

The problem finally surfaces when getting the TokenCache by calling the MSALSessionCache which uses the httpContext.Session object (MVC works; Webforms throws Null reference exception)

I am aware that MVC and Webforms treat the session differently but cannot work out how to solve this problem.

EDIT

Whilst this worked it did not address the problem regarding the session id. I added

```<code>Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = AuthenticationFailed,
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    MessageReceived = OnMessageReceived,
                    SecurityTokenReceived=OnSecurityTokenReceived,
                    SecurityTokenValidated= OnSecurityTokenValidated
                },
</code>```

to your code with the appropriate stubs for these functions. MessageReceived was invoked as was SecurityTokenReceived and Validated. However, AuthorizationCodeReceived was never invoked. When the first three were invoked, I examined the notification.OwinContext.Environment["System.Web.HttpContextBase"] and in all cases the Session object is null - which is what my problem was to start with.

EDIT (includes answer)

Thanks to @Ramakrishna the solution is to add A RequireAspNetSession helper function at the beginning of ConfigureAuth. The revised code snippet for his sample is as follows:

```<code>public void ConfigureAuth(IAppBuilder app)
    {
        RequireAspNetSession(app);

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        // Configure OpenID Connect middleware for each policy
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
    }

    public static void RequireAspNetSession(IAppBuilder app)
    {
        app.Use((context, next) =>
        {
            var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
            httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
            return next();
        });

        // To make sure the above `Use` is in the correct position:
        app.UseStageMarker(PipelineStage.MapHandler);
    }
</code>```

you will need to add the following references:

```<code>using System.Web.SessionState;
using Microsoft.Owin.Extensions;
</code>```

答:
```<code>if (!Request.IsAuthenticated)
{
   HttpContext.Current.GetOwinContext().Authentication.Challenge(
   new AuthenticationProperties() { RedirectUri = "/" }, Startup.SignUpPolicyId);
}
</code>```

Try this in webforms.

EDIT

Sample Application hosted at https://github.com/Zen3InfoSolutions/B2CSamples/tree/master/B2C-WebForms

Zero configuration required to run and verify the policies.

Body:
I am using the github example active-directory-b2c-dotnet-webapp-and-webapi.

I configured my own b2c tenant and got the MVC sample to work successfully.

However, I need this to work with a WebForms app. I created a new Webforms app, checked that the references were pointing to the same versions of the dlls as the working sample and adjusted the code to work in WebForms.

Everything works up until the time that I issue the Authentication.Challenge and process the AuthorizationCodeReceivedNotification in the OnAuthorizationCodeReceived function.

The Session object in notification.OwinContext.Environment["System.Web.HttpContextBase"] is null whereas at this point in the MVC sample the session object in notification.OwinContext.Environment["System.Web.HttpContextBase"].Session is a System.Web.HttpSessionStateWrapper with a valid SessionId.

In WebForms, HttpContext.GetOwinContext throws an error as not being available, so I then tried HttpContext.Current.GetOwinContext which returned an HttpContext object instead of a HttpContextBase object. So I finally used

if (!Request.IsAuthenticated)
{
   HttpContextBase context = new HttpContextWrapper(HttpContext.Current);
   context.GetOwinContext().Authentication.Challenge();
   return;
}

instead of the following which is used in the MVC sample

if (!Request.IsAuthenticated)
{
   HttpContext.GetOwinContext().Authentication.Challenge();
   return;
}

At this point in the code, in both MVC and WebForms the Authentication object has a valid Session object in its OwinContext.Environment prior to the Challenge being issued. The problem is that whilst in the MVC version the resulting notification includes the session object, the WebForms version of the notification has a null object.

The problem finally surfaces when getting the TokenCache by calling the MSALSessionCache which uses the httpContext.Session object (MVC works; Webforms throws Null reference exception)

I am aware that MVC and Webforms treat the session differently but cannot work out how to solve this problem.

EDIT

Whilst this worked it did not address the problem regarding the session id. I added

Notifications = new OpenIdConnectAuthenticationNotifications
                {
                    AuthenticationFailed = AuthenticationFailed,
                    AuthorizationCodeReceived = OnAuthorizationCodeReceived,
                    MessageReceived = OnMessageReceived,
                    SecurityTokenReceived=OnSecurityTokenReceived,
                    SecurityTokenValidated= OnSecurityTokenValidated
                },

to your code with the appropriate stubs for these functions. MessageReceived was invoked as was SecurityTokenReceived and Validated. However, AuthorizationCodeReceived was never invoked. When the first three were invoked, I examined the notification.OwinContext.Environment["System.Web.HttpContextBase"] and in all cases the Session object is null - which is what my problem was to start with.

EDIT (includes answer)

Thanks to @Ramakrishna the solution is to add A RequireAspNetSession helper function at the beginning of ConfigureAuth. The revised code snippet for his sample is as follows:

public void ConfigureAuth(IAppBuilder app)
    {
        RequireAspNetSession(app);

        app.SetDefaultSignInAsAuthenticationType(CookieAuthenticationDefaults.AuthenticationType);

        app.UseCookieAuthentication(new CookieAuthenticationOptions());

        // Configure OpenID Connect middleware for each policy
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignUpPolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(ProfilePolicyId));
        app.UseOpenIdConnectAuthentication(CreateOptionsFromPolicy(SignInPolicyId));
    }

    public static void RequireAspNetSession(IAppBuilder app)
    {
        app.Use((context, next) =>
        {
            var httpContext = context.Get<HttpContextBase>(typeof(HttpContextBase).FullName);
            httpContext.SetSessionStateBehavior(SessionStateBehavior.Required);
            return next();
        });

        // To make sure the above `Use` is in the correct position:
        app.UseStageMarker(PipelineStage.MapHandler);
    }

you will need to add the following references:

using System.Web.SessionState;
using Microsoft.Owin.Extensions;

Body:
if (!Request.IsAuthenticated)
{
   HttpContext.Current.GetOwinContext().Authentication.Challenge(
   new AuthenticationProperties() { RedirectUri = "/" }, Startup.SignUpPolicyId);
}

Try this in webforms.

EDIT

Sample Application hosted at https://github.com/Zen3InfoSolutions/B2CSamples/tree/master/B2C-WebForms

Zero configuration required to run and verify the policies.


问:
If statements executed even with false condition
I am having this annoying problem with if/elif statements. I'm a newbie, sorry for dumb question. I tried finding a fix but no one had it for Python.
So, I want the program to execute the code in the if clause if both conditions are True. As far as I know the code in the clause will only execute if both the conditions are True, am I right? That doesn't seem to happen in my code, though.

```<code>result = userNumber + randomNumber
if not result % 2 == 0 and userChoice == 'e' or 'even':
    print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
    print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
    print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
    print ('That number is even, so you lost :(')
</code>```

So, the userNumber and the randomNumber variables were set before. In this game, what happens is: the user chooses even or odd, and inputs a number from 0 to 5. Then, the computer randomly chooses a number from 0 to 5, using random.randint().
After that, the variable result is set to the sum of userNumber + randomNumber. If the result of that sum is odd and the user chose odd, the user wins, and if the user chose even, the user loses. If the sum is even it's exactly the opposite: if the result of the previous sum result is even and the user chose even, the user wins, and if the user chose odd, the user loses.
I hope you understand!

So, the problem with my code right now is that it executes all four IF statements for some reason, so the final output looks like this:

Welcome to the Even or Odd game!

Type letter 'o' if you want odd and the letter 'e' if you want even.

Your choice: o

Now, type in a number from 0 to 5: 2

Your number: 2

Computer's number: 5

Adding these two numbers together, we get 7

That number is odd, so you lost :(

That number is even, so you won :)

That number is odd, so you won :)

That number is even, so you lost :(

The code for that is:

```<code>import random
import time

print ('Welcome to the Even or Odd game!')
print ('Type letter \'o\' if you want odd and the letter \'e\' if you want even.')

userChoice = input('Your choice: ').lower()
time.sleep(1)
userNumber = int(input('Now, type in a number from 0 to 5: '))

randomNumber = random.randint(0,5)
time.sleep(2)

print ('Your number: ' + str(int(userNumber)))
time.sleep(2)
print ('Computer\'s number: ' + str(int(randomNumber)))
time.sleep(2)

result = userNumber + randomNumber
print (str(result))
print ('Adding these two numbers together, we get ' + str(result))
if not result % 2 == 0 and userChoice == 'e' or 'even':
    print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
    print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
    print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
    print ('That number is even, so you lost :(')
</code>```

Any ideas? Sorry for long post, and sorry if duplicate! I just didn't find any answers around the internet :/ Thank you so much!

EDIT: I also tried using elif statements instead of all if, didn't work either.

答:
```<code>>>> if False or 'even':
...     print('This shouldn\'t work')
...
This shouldn't work
</code>```

The truth value of a non-empty string is True. Although your other conditions are False, you're still executing those statements because of the way you've written your condition.

As it stands, this is how your condition is evaluated:

```<code>if (not result % 2 == 0) and ((userChoice == 'e') or ('even')):
# __________1________________________2_________________3_____
</code>```

(1) is True. (2) is False. But (3) is True (because of the truthiness of strings). So you execute the first if.

What's more, you only want one of these conditions to execute. Not all of them. You'll need to replace your second if and onwards with elif. So, if one condition is True, all the other conditions are skipped.

You'll need to make a small change:

```<code>if not result % 2 == 0 and userChoice in ['e', 'even']:
    ...
elif result % 2 == 0 and userChoice in ['e', 'even']:
    ...
elif not result % 2 == 0 and userChoice in ['o', 'odd']:
    ...
elif result % 2 == 0 and userChoice ['o', 'odd']:
    ...
</code>```

Body:
I am having this annoying problem with if/elif statements. I'm a newbie, sorry for dumb question. I tried finding a fix but no one had it for Python.
So, I want the program to execute the code in the if clause if both conditions are True. As far as I know the code in the clause will only execute if both the conditions are True, am I right? That doesn't seem to happen in my code, though.

result = userNumber + randomNumber
if not result % 2 == 0 and userChoice == 'e' or 'even':
    print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
    print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
    print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
    print ('That number is even, so you lost :(')

So, the userNumber and the randomNumber variables were set before. In this game, what happens is: the user chooses even or odd, and inputs a number from 0 to 5. Then, the computer randomly chooses a number from 0 to 5, using random.randint().
After that, the variable result is set to the sum of userNumber + randomNumber. If the result of that sum is odd and the user chose odd, the user wins, and if the user chose even, the user loses. If the sum is even it's exactly the opposite: if the result of the previous sum result is even and the user chose even, the user wins, and if the user chose odd, the user loses.
I hope you understand!

So, the problem with my code right now is that it executes all four IF statements for some reason, so the final output looks like this:

Welcome to the Even or Odd game!

Type letter 'o' if you want odd and the letter 'e' if you want even.

Your choice: o

Now, type in a number from 0 to 5: 2

Your number: 2

Computer's number: 5

Adding these two numbers together, we get 7

That number is odd, so you lost :(

That number is even, so you won :)

That number is odd, so you won :)

That number is even, so you lost :(

The code for that is:

import random
import time

print ('Welcome to the Even or Odd game!')
print ('Type letter \'o\' if you want odd and the letter \'e\' if you want even.')

userChoice = input('Your choice: ').lower()
time.sleep(1)
userNumber = int(input('Now, type in a number from 0 to 5: '))

randomNumber = random.randint(0,5)
time.sleep(2)

print ('Your number: ' + str(int(userNumber)))
time.sleep(2)
print ('Computer\'s number: ' + str(int(randomNumber)))
time.sleep(2)

result = userNumber + randomNumber
print (str(result))
print ('Adding these two numbers together, we get ' + str(result))
if not result % 2 == 0 and userChoice == 'e' or 'even':
    print ('That number is odd, so you lost :(')
if result % 2 == 0 and userChoice == 'e' or 'even':
    print ('That number is even, so you won :)')
if not result % 2 == 0 and userChoice == 'o' or 'odd':
    print ('That number is odd, so you won :)')
if result % 2 == 0 and userChoice == 'o' or 'odd':
    print ('That number is even, so you lost :(')

Any ideas? Sorry for long post, and sorry if duplicate! I just didn't find any answers around the internet :/ Thank you so much!

EDIT: I also tried using elif statements instead of all if, didn't work either.

Body:
>>> if False or 'even':
...     print('This shouldn\'t work')
...
This shouldn't work

The truth value of a non-empty string is True. Although your other conditions are False, you're still executing those statements because of the way you've written your condition.

As it stands, this is how your condition is evaluated:

if (not result % 2 == 0) and ((userChoice == 'e') or ('even')):
# __________1________________________2_________________3_____

(1) is True. (2) is False. But (3) is True (because of the truthiness of strings). So you execute the first if.

What's more, you only want one of these conditions to execute. Not all of them. You'll need to replace your second if and onwards with elif. So, if one condition is True, all the other conditions are skipped.

You'll need to make a small change:

if not result % 2 == 0 and userChoice in ['e', 'even']:
    ...
elif result % 2 == 0 and userChoice in ['e', 'even']:
    ...
elif not result % 2 == 0 and userChoice in ['o', 'odd']:
    ...
elif result % 2 == 0 and userChoice ['o', 'odd']:
    ...


问:
Error: Uncaught SyntaxError: Unexpected token <
For some reason, I'm getting this error message:

```<code>Uncaught SyntaxError: Unexpected token <
</code>```

For this line of code:

```<code>title: '<img src="/images/text/text_mario_planet_jukebox.png" id="text_mario_planet_jukebox"/>',
</code>```

In this context:

```<code>$(document).ready(function() {
    $('#infobutton').click(function() {
        $('#music_descrip').dialog('open');
    });
        $('#music_descrip').dialog({
            title: '<img src="/images/text/text_mario_planet_jukebox.png" id="text_mario_planet_jukebox"/>',
            autoOpen: false,
            height: 375,
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                'Without Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'no', { expires: 365 * 10 });
                },
                'With Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'yes', { expires: 365 * 10 });
                }
            }
        });
    });
</code>```

I think everything should be good to go, but I don't understand why the < is somehow throwing this off..

whoops, forgot to show where this is happening! My bad,

http://www.marioplanet.com/index.asp

Any ideas?

答: try to replace the text/javascript to text/html then save the note and reload browser then bring it back to text/javascript.. I don't know but for unknown reason this one works with me.. I am searching and copy-pasting and I just accidentally undo what I am typing then boom kablooey it worked 0.O  by the way I am just noob.. sorry I just thought it could help though..

Body:
For some reason, I'm getting this error message:

Uncaught SyntaxError: Unexpected token <

For this line of code:

title: '',

In this context:

$(document).ready(function() {
    $('#infobutton').click(function() {
        $('#music_descrip').dialog('open');
    });
        $('#music_descrip').dialog({
            title: '',
            autoOpen: false,
            height: 375,
            width: 500,
            modal: true,
            resizable: false,
            buttons: {
                'Without Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'no', { expires: 365 * 10 });
                },
                'With Music': function() {
                    $(this).dialog('close');
                    $.cookie('autoPlay', 'yes', { expires: 365 * 10 });
                }
            }
        });
    });

I think everything should be good to go, but I don't understand why the < is somehow throwing this off..

whoops, forgot to show where this is happening! My bad,

http://www.marioplanet.com/index.asp

Any ideas?


问:
parent.window.location redirection from spring mvc modelandview
My application consists of few iframes. In Spring MVC is there a way to redirect to the parent page instead of the current iframe? For example in javascript we can do parent.window.location to load the page in parent instead of using window.location which would load only in the iframe.

The following view loads login.go in current iframe, but i want the login.go to be displayed in whole page (parent)

```<code>return new ModelAndView(new RedirectView("/login.go", false, true, true));
</code>```

Any ideas please..

答:
This is certainly another reason why frames are evil.

It's not possible to break out of a frame without using javascript.

Body:
My application consists of few iframes. In Spring MVC is there a way to redirect to the parent page instead of the current iframe? For example in javascript we can do parent.window.location to load the page in parent instead of using window.location which would load only in the iframe.

The following view loads login.go in current iframe, but i want the login.go to be displayed in whole page (parent)

return new ModelAndView(new RedirectView("/login.go", false, true, true));

Any ideas please..


问:
SQL - Split table based upon a column's content
I have a large database (~50,000 rows) with 20 columns, and I want to "split" the data based upon the values in the third column (called FEATURE_CLASS). The values of FEATURE_CLASS are all of type VARCHAR(), and I want to create however many tables I'd need to replace the single, large table with many smaller tables each entitled with whatever the original table's FEATURE_CLASS value was.

Not sure of the best way to go about this, I was thinking something along the lines of creating a temporary table which would serve as an index, each row carrying a unique value of FEATURE_CLASS, then to iterate over the temp table and perform copying operations for each row of the temp table. I'm not sure really where to go from here, any help/ideas would be appreciated. Thanks!

答:
The basic idea is to create a result set of statements that will create the tables for you and populate with the correct data.  Run the below to generate the statements.  You can then execute these statements manually (copy/paste) or from within a script.

SQL Server Example

```<code>SELECT DISTINCT
    'SELECT * INTO [' + TableName.FEATURE_CLASS + '] FROM TableName WHERE FEATURE_CLASS = ''' + TableName.FEATURE_CLASS + ''';'
FROM
    TableName
</code>```

If you have any special characters in the FEATURE_CLASS column, you might want to consider removing them in the script above to prevent table names that are either invalid or tough to work with.

For example:

```<code>...
    'SELECT * INTO [' + REPLACE(TableName.FEATURE_CLASS, '.', '') + '] FROM TableName WHERE FEATURE_CLASS = ''' + TableName.FEATURE_CLASS + ''';'
...
</code>```

MySQL Example

```<code>SELECT DISTINCT
    CONCAT('CREATE TABLE `', DB1.FEATURE_CLASS,
        '` AS SELECT * FROM DB1 WHERE FEATURE_CLASS = ''',
        DB1.FEATURE_CLASS, ''';') AS statements
FROM DB1;
</code>```

This will give you a MySQL command something like this:

```<code>CREATE TABLE `feature_class_value` AS
    SELECT * FROM DB1
        WHERE FEATURE_CLASS = 'feature_class_value';
</code>```

Check out the MySQL docs for more info on CREATE TABLE SELECT options https://dev.mysql.com/doc/refman/5.7/en/create-table-select.html.

Body:
The basic idea is to create a result set of statements that will create the tables for you and populate with the correct data.  Run the below to generate the statements.  You can then execute these statements manually (copy/paste) or from within a script.

SQL Server Example

SELECT DISTINCT
    'SELECT * INTO [' + TableName.FEATURE_CLASS + '] FROM TableName WHERE FEATURE_CLASS = ''' + TableName.FEATURE_CLASS + ''';'
FROM
    TableName

If you have any special characters in the FEATURE_CLASS column, you might want to consider removing them in the script above to prevent table names that are either invalid or tough to work with.

For example:

...
    'SELECT * INTO [' + REPLACE(TableName.FEATURE_CLASS, '.', '') + '] FROM TableName WHERE FEATURE_CLASS = ''' + TableName.FEATURE_CLASS + ''';'
...

MySQL Example

SELECT DISTINCT
    CONCAT('CREATE TABLE `', DB1.FEATURE_CLASS,
        '` AS SELECT * FROM DB1 WHERE FEATURE_CLASS = ''',
        DB1.FEATURE_CLASS, ''';') AS statements
FROM DB1;

This will give you a MySQL command something like this:

CREATE TABLE `feature_class_value` AS
    SELECT * FROM DB1
        WHERE FEATURE_CLASS = 'feature_class_value';

Check out the MySQL docs for more info on CREATE TABLE SELECT options https://dev.mysql.com/doc/refman/5.7/en/create-table-select.html.


问:
Migrating from one DBMS to another
Does anyone have any experience migrating from one DBMS to another?  If you have done this, why did you do it? Features? Cost? Corporate Directive?

At times, I've worked with DBAs who insisted that we not use features specific to a DBMS (for example, CLR Stored Procedures in SQL Server.)  The DBAs point is, if we use these features, it will make it more difficult to switch to another DBMS if we have to.  But so far, I've never been asked to switch.

答: We did it a HP3000 to Oracle migration. It cost us 25 million dollars and also added cost of losing 200 million dollars in data because of just such a damn hurry they didn't think about what they were doing. Also I have found a lot of places that just see it as just a move. They'll figure out the rest later.......much later.</p>

Title: Migrating from one DBMS to another


问:
Wagtail: set default page privacy
I would like to modify the default 'privacy level' of for a page class in Wagtail. In other words, when an admin panel user goes to create a new instance of MyPage, the default privacy would be accessible to logged-in users only, rather than completely public.

This seems like something that should have an obvious answer, but after quite a lot of googling, I can't seem to find any description of how this might be done.

Thanks!

答:
AFAIK, there is not currently an option in Wagtail to set a default privacy level on pages. There doesn't seem to be an issue on GitHub for this either; perhaps add one?

https://github.com/wagtail/wagtail/issues?utf8=%E2%9C%93&q=is%3Aissue%20is%3Aopen%20privacy

Good luck!

Title: Wagtail: set default page privacy


问:
Deploying multi-docker local setup to AWS using Elastic Beanstalk
I'm having e multi-docker setup running locally. Now, I would like to deploy that to AWS using Elastic Beanstalk.

My folder config is like this

```<code>app
    /.ebextensions
        composer.config
    /.elasticbeanstalk
        config.yml
    /docker (docker-compose and additional Docker files)
        docker-compose.yml
    /www (root folder of application)
</code>```

I already ran eb init, but I don't know how to actually deploy my local docker-compose configuration to AWS.

I read about the Dockerrun.aws.json file, should I just copy paste my docker-compose to that file? Or how does it work?

I already tried to:

zip my folder and upload it to AWS

eb create / eb deploy but then I get the following error message:

Platform Multi-container Docker 17.03.1-ce (Generic) does not appear to be valid

Thank you

答:
I'm having a very similar issue (not using multi-container) and it appears Amazon has a bug. By selecting Docker 1.12.6 I am able to execute eb create which fails for me otherwise.

EDIT: This appears to have been a bug in the EB CLI. I upgraded and it works fine now.

Body:
I'm having e multi-docker setup running locally. Now, I would like to deploy that to AWS using Elastic Beanstalk.

My folder config is like this

app
    /.ebextensions
        composer.config
    /.elasticbeanstalk
        config.yml
    /docker (docker-compose and additional Docker files)
        docker-compose.yml
    /www (root folder of application)

I already ran eb init, but I don't know how to actually deploy my local docker-compose configuration to AWS.

I read about the Dockerrun.aws.json file, should I just copy paste my docker-compose to that file? Or how does it work?

I already tried to:

zip my folder and upload it to AWS

eb create / eb deploy but then I get the following error message:

Platform Multi-container Docker 17.03.1-ce (Generic) does not appear to be valid

Thank you