问:
Is returning a forward-declared structure undefined behavior?
I have the following code (include-guards omitted for simplicity's sake):

= foo.hpp =

```<code>struct FOO
{
  int not_used_in_this_sample;
  int not_used_in_this_sample2;
};
</code>```

= main.cpp =

```<code>#include "foo_generator.hpp"
#include "foo.hpp"

int main()
{
  FOO foo = FooGenerator::createFoo(0xDEADBEEF, 0x12345678);

  return 0;
}
</code>```

= foo_generator.hpp =

```<code>struct FOO; // FOO is only forward-declared

class FooGenerator
{
  public:

    // Note: we return a FOO, not a FOO&
    static FOO createFoo(size_t a, size_t b);
};
</code>```

= foo_generator.cpp =

```<code>#include "foo_generator.hpp"
#include "foo.hpp"

FOO FooGenerator::createFoo(size_t a, size_t b)
{
  std::cout << std::hex << a << ", " << b << std::endl;

  return FOO();
}
</code>```

This code, as it stands, compiles perfectly fine without any warning. If my understanding is correct, it should output:

```<code>deadbeef, 12345678
</code>```

But instead, it randomly displays:

```<code>12345678, 32fb23a1
</code>```

Or just crashes.

If I replace the forward-declaration of FOO in foo_generator.hpp with #include "foo.hpp", then it works.

So here is my question: Does returning a forward-declared structure lead to undefined behavior ? Or what can possibly go wrong ?

Compiler used: MSVC 9.0 and 10.0 (both show the issue)

答: It works fine for me under GCC.  I don't know why it wouldn't, since foo.hpp is included before foo_generator.hpp.

Body:
I have the following code (include-guards omitted for simplicity's sake):

= foo.hpp =

struct FOO
{
  int not_used_in_this_sample;
  int not_used_in_this_sample2;
};

= main.cpp =

#include "foo_generator.hpp"
#include "foo.hpp"

int main()
{
  FOO foo = FooGenerator::createFoo(0xDEADBEEF, 0x12345678);

  return 0;
}

= foo_generator.hpp =

struct FOO; // FOO is only forward-declared

class FooGenerator
{
  public:

    // Note: we return a FOO, not a FOO&
    static FOO createFoo(size_t a, size_t b);
};

= foo_generator.cpp =

#include "foo_generator.hpp"
#include "foo.hpp"

FOO FooGenerator::createFoo(size_t a, size_t b)
{
  std::cout << std::hex << a << ", " << b << std::endl;

  return FOO();
}

This code, as it stands, compiles perfectly fine without any warning. If my understanding is correct, it should output:

deadbeef, 12345678

But instead, it randomly displays:

12345678, 32fb23a1

Or just crashes.

If I replace the forward-declaration of FOO in foo_generator.hpp with #include "foo.hpp", then it works.

So here is my question: Does returning a forward-declared structure lead to undefined behavior ? Or what can possibly go wrong ?

Compiler used: MSVC 9.0 and 10.0 (both show the issue)


来源: stackexchange

问:
Amazon Redshift, getting slower in every update run
I am beginning with Amanzon Redshift.

I have just loaded a big table, millions of rows and 171 fields. The data quality is poor, there are a lot of characters that must be removed.

I have prepare updates for every column, since redshift stores in column mode, I suppose it is faster by column.

UPDATE MyTable SET Field1 = REPLACE(Field1, '~', '');

UPDATE MyTable SET Field2 = REPLACE(Field2, '~', '');

.
.
.

UPDATE MyTable set FieldN = Replace(FieldN, '~', '');

The first 'update' took 1 min. The second one took 1 min and 40 sec...

Every time a run one of the updates, it takes more time than the last one. I have run 19 and the last one took almost 25 min. The time consumed by every 'update' increases one after another.

Another thing is that with the first update, the cpu utilization was minimal, now with the last update it is taking 100%

I have a 3-nodes cluster of dc1.large instances.

I have rebooted the cluster but the problem continues.

Please, I need orientation to find the cause of this problem.

答:
A more optimal way might be

Create another identical table.

Read N ( say 10000) rows at a time from first table, process and load into the second table using s3
loading (instead of insert).

Delete first table and rename second table

If are running into space issues, delete the N migrated rows after every iteration from the first table and run vacuum delete only <name_of_first_table>

Refrences

s3 loading : http://docs.aws.amazon.com/redshift/latest/dg/tutorial-loading-run-copy.html

copy table from 's3://<your-bucket-name>/load/key_prefix' credentials 'aws_access_key_id=<Your-Access-Key-ID>;aws_secret_access_key=<Your-Secret-Access-Key>' options;

ContentLicense: CC BY-SA 3.0


问:
What is the 'apt-get update' equivalent command in Arch Linux?
What is the command for Arch Linux to update the packages before installing a new package?

For instance, I know that in Ubuntu, I do this in a terminal window:

```<code>sudo apt-get update
sudo apt-get <package name>
</code>```

What about in Arch Linux?

I came across a couple of versions, but they don't seem agree with each others. I can't see the consistency there.

Example 1. (it looks tedious to me):

```<code>sudo pacman -Syy
sudo pacman -Su
</code>```

Example 2:

```<code>sudo pacman -Sy
</code>```

Example 3:

always use "-Sy" with a "u". I.e., "pacman -Syu"
and then "pacman -S <package>", and never "pacman -Sy <package>".

答:
The equivalent of apt-get update in Arch Linux is pacman -Syy.

pacman -Syu is equivalent to apt-get update && apt-get upgrade.

Might as well make this complete if it stays...

pacman -S <package> is apt-get install <package>.

ContentLicense: CC BY-SA 4.0

Body:
What is the command for Arch Linux to update the packages before installing a new package?

For instance, I know that in Ubuntu, I do this in a terminal window:

sudo apt-get update
sudo apt-get <package name>

What about in Arch Linux?

I came across a couple of versions, but they don't seem agree with each others. I can't see the consistency there.

Example 1. (it looks tedious to me):

sudo pacman -Syy
sudo pacman -Su

Example 2:

sudo pacman -Sy

Example 3:

always use "-Sy" with a "u". I.e., "pacman -Syu"
and then "pacman -S <package>", and never "pacman -Sy <package>".


问:
How to convert ISO-8859-1 to UTF-8 in node.js from readfile buffer
as per title, I am trying to parse a txt encoded in ISO-8859-1 to put data into a DB. I do need that these data is converted into UTF-8 before. This is due to the fact that some special character, particularly uppercase accented characters, are shown as question mark in the DB and in front-end consequently.

The code I am using is:

```<code>this.fs.readFile(fileName, null, function(err, buff){
                    if (err) {
                        self.openFiles();
                    } else {

                        var data = buff.toString('UTF-8');
                        self.parseNews(data, fileName);
                    }
                });
</code>```

I know there are similar questions on SO, but none helped me...
Could you help me in some way or address to a solution?

Thanks!
Fabio

答:
You need to specify the input encoding. Assuming that this.fs.readFile is the same as fs.readFile:

```<code>this.fs.readFile(fileName, { encoding : 'latin1' }, function(err, buff) {
  ...
  var data = buff.toString(); // no need to specify encoding here
});
</code>```

Body:
as per title, I am trying to parse a txt encoded in ISO-8859-1 to put data into a DB. I do need that these data is converted into UTF-8 before. This is due to the fact that some special character, particularly uppercase accented characters, are shown as question mark in the DB and in front-end consequently.

The code I am using is:

this.fs.readFile(fileName, null, function(err, buff){
                    if (err) {
                        self.openFiles();
                    } else {

                        var data = buff.toString('UTF-8');
                        self.parseNews(data, fileName);
                    }
                });

I know there are similar questions on SO, but none helped me...
Could you help me in some way or address to a solution?

Thanks!
Fabio

Body:
You need to specify the input encoding. Assuming that this.fs.readFile is the same as fs.readFile:

this.fs.readFile(fileName, { encoding : 'latin1' }, function(err, buff) {
  ...
  var data = buff.toString(); // no need to specify encoding here
});


问:
Unexpected results when trying to match string pattern
Given a string, return true if the first instance of "x" in the string is immediately followed by another "x". It will not work for the case of doubleX("axxbb"). It should return true but gives false.</p>

```<code>boolean doubleX(String str) {
  for (int i = 0; i < str.length(); i++) {
    if (str.substring(i) == "x") {
      if ( str.substring(i) == str.substring(i + 1)){
      return true;
      }

    }

  }
  return false;
}
</code>```

答:
It will not work for the case of doubleX("axxbb"). It should return true but gives false.

You have couple problems with your code:

```<code>if (str.substring(i) == "x") {
</code>```

The String.substring(...) method returns the portion of the string that starts at position i.  To quote the javadocs:

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

So if you do str.substring(1) where str is "axxbb" then substring would return "xxbb".   I think you should instead use str.charAt(i) which returns the character at that position.  So your code should be:

```<code>if (str.charAt(i) == 'x') {
    ...
}
</code>```

The 2nd conceptual problem is that strings cannot be compared with ==.  String is an object and when objects are compared with == then you are comparing the reference of the object instead of its contents.  To compare strings you should use string.equals("x").  See this answer for more details.

But, again, you wanted to do str.charAt(i) here.

Lastly, your code is going to have problems on the last character because you are string to do a str.charAt(i + 1) which will throw a StringIndexOutOfBoundsException.  So the loop should be:

```<code>// subtract one from the length because we are looking for 2 x's in a row
for (int i = 0; i < str.length() - 1; i++) {
</code>```

We go to str.length() - 1 because we are looking for 2 characters in a row.

Body:
Given a string, return true if the first instance of "x" in the string is immediately followed by another "x". It will not work for the case of doubleX("axxbb"). It should return true but gives false.

boolean doubleX(String str) {
  for (int i = 0; i < str.length(); i++) {
    if (str.substring(i) == "x") {
      if ( str.substring(i) == str.substring(i + 1)){
      return true;
      }

    }

  }
  return false;
}

Body:
It will not work for the case of doubleX("axxbb"). It should return true but gives false.

You have couple problems with your code:

if (str.substring(i) == "x") {

The String.substring(...) method returns the portion of the string that starts at position i.  To quote the javadocs:

Returns a new string that is a substring of this string. The substring begins with the character at the specified index and extends to the end of this string.

So if you do str.substring(1) where str is "axxbb" then substring would return "xxbb".   I think you should instead use str.charAt(i) which returns the character at that position.  So your code should be:

if (str.charAt(i) == 'x') {
    ...
}

The 2nd conceptual problem is that strings cannot be compared with ==.  String is an object and when objects are compared with == then you are comparing the reference of the object instead of its contents.  To compare strings you should use string.equals("x").  See this answer for more details.

But, again, you wanted to do str.charAt(i) here.

Lastly, your code is going to have problems on the last character because you are string to do a str.charAt(i + 1) which will throw a StringIndexOutOfBoundsException.  So the loop should be:

// subtract one from the length because we are looking for 2 x's in a row
for (int i = 0; i < str.length() - 1; i++) {

We go to str.length() - 1 because we are looking for 2 characters in a row.


问:
Feeding Access Token into list_folder method, Dropbox API
I'm making a small python script to list all files recursively within a user's Dropbox account. The OAuth2.0 flow works, but I am frankensteining in another call to the list_folder method to list those files/folders.

I'm stuck at like 22 where I need to provide the access token returned by the OAuth flow. What can I call to return the token?

(Or, do you know of a quick python script that already does what I am asking)

```<code>from dropbox.client import DropboxOAuth2FlowNoRedirect, DropboxClient
from dropbox import rest as dbrest
import requests
import json

auth_flow = DropboxOAuth2FlowNoRedirect('<APP_KEY>', '<APP_SECRET>')
###These are filled out in my code, but I hid them here.

authorize_url = auth_flow.start()
print "1. Go to: " + authorize_url
print "2. Click \"Allow\" (you might have to log in first)."
print "3. Copy the authorization code."
auth_code = raw_input("Enter the authorization code here: ").strip()

try:
    oauth_result = auth_flow.finish(auth_code)
except dbrest.ErrorResponse, e:
    print('Error: %s' % (e,))

url = "https://api.dropboxapi.com/2/files/list_folder"

headers = {
    "Authorization": "Bearer <ACCESS_TOKEN>",
    "Content-Type": "application/json"
}

data = {
    "path": "",
    "recursive": True,
    "include_media_info": True,
    "include_deleted": True
}

r = requests.post(url, headers=headers, data=json.dumps(data))

print(r.text)
</code>```

答:
If you're using the Dropbox Python SDK, you don't need to make the HTTP POST request manually like you're attempting.

You can get the access token from the app authorization flow, and make a Dropbox client, as shown in the DropboxOAuth2FlowNoRedirect documentation.

Then, you can call files_list_folder as shown in this example, (and files_list_folder_continue if ListFolderResult.has_more was True).

Body:
I'm making a small python script to list all files recursively within a user's Dropbox account. The OAuth2.0 flow works, but I am frankensteining in another call to the list_folder method to list those files/folders.

I'm stuck at like 22 where I need to provide the access token returned by the OAuth flow. What can I call to return the token?

(Or, do you know of a quick python script that already does what I am asking)

from dropbox.client import DropboxOAuth2FlowNoRedirect, DropboxClient
from dropbox import rest as dbrest
import requests
import json

auth_flow = DropboxOAuth2FlowNoRedirect('<APP_KEY>', '<APP_SECRET>')
###These are filled out in my code, but I hid them here.

authorize_url = auth_flow.start()
print "1. Go to: " + authorize_url
print "2. Click \"Allow\" (you might have to log in first)."
print "3. Copy the authorization code."
auth_code = raw_input("Enter the authorization code here: ").strip()

try:
    oauth_result = auth_flow.finish(auth_code)
except dbrest.ErrorResponse, e:
    print('Error: %s' % (e,))

url = "https://api.dropboxapi.com/2/files/list_folder"

headers = {
    "Authorization": "Bearer <ACCESS_TOKEN>",
    "Content-Type": "application/json"
}

data = {
    "path": "",
    "recursive": True,
    "include_media_info": True,
    "include_deleted": True
}

r = requests.post(url, headers=headers, data=json.dumps(data))

print(r.text)


问:
Can't Move a dynamically created nested div from one div to another div
I have created some dynamic div based on an input inside a parent div.

Now what I want to do is that if I click one of those created divs, it should move to other parent div and vice versa.

My code:

```<code>/*Html code*/

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<div id="firstDiv">
<div id="1" class="a">Value</div>(Working over statically created div  )
</div>
<br>
--------------
--------------
-------------
<br>
<div id="SecondDiv">
<div id="4" class="b">
</div>
</div>
</code>```

And JavaScript code:

```<code>  $(document).ready(function() {
  $('#btnSave').click(function() {
  addDiv($('#txtName').val());
  $('#txtName').val('');
  });
  $("div.a").on("click", function() {
  var $this = $(this);
 if ($this.hasClass("a")) {
    $this.removeClass("a").addClass("b").prependTo("#firstDiv");
 } else {
    $this.removeClass("b").addClass("a").prependTo("#SecondDiv");
 }
 });

});

function addDiv(name) {
var container = $('#firstDiv ');
$('<div />', {class:'a',text:name }).appendTo(container).after("<br/>");
}
</code>```

But the code is only working over already created div. I tested this, but it is not working for dynamically created div.

All I want is that I can create child div dynamically and move it to another div when clicked.

A Sample Fiddle is also added

答:
use $(document).on("click", "div.a", function() {}); instead of $("div.a").on("click", function() {});

$(document).on("click","element", function() {}); sees everything added to the DOM

$("element") only sees what is already in the DOM when the jquery code is loaded.

updated jsfiddle: http://jsfiddle.net/2kgu38am/7/

Body:
I have created some dynamic div based on an input inside a parent div.

Now what I want to do is that if I click one of those created divs, it should move to other parent div and vice versa.

My code:

/*Html code*/

<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />

Value
(Working over statically created div  )

--------------
--------------
-------------

And JavaScript code:

  $(document).ready(function() {
  $('#btnSave').click(function() {
  addDiv($('#txtName').val());
  $('#txtName').val('');
  });
  $("div.a").on("click", function() {
  var $this = $(this);
 if ($this.hasClass("a")) {
    $this.removeClass("a").addClass("b").prependTo("#firstDiv");
 } else {
    $this.removeClass("b").addClass("a").prependTo("#SecondDiv");
 }
 });

});

function addDiv(name) {
var container = $('#firstDiv ');
$('
', {class:'a',text:name }).appendTo(container).after("
");
}

But the code is only working over already created div. I tested this, but it is not working for dynamically created div.

All I want is that I can create child div dynamically and move it to another div when clicked.

A Sample Fiddle is also added


问:
Div with nowrap still wraps
I want to make the div stay the same size while I resize the window.
My css for the div:

```<code>.header {
    white-space: nowrap;
    color: #fff;
    padding: 0.5em;
    background: linear-gradient(90deg, #B71C1C, #0D47A1, #0D47A1);
  }
</code>```

and here is the output before the wrap:

and after the wrap:

what I want is to header div always stay the same size no matter the browser's width.

答:
The "white-space:nowrap" property is meant for text wrapping, not for general responsiveness of your elements. https://www.w3schools.com/cssref/pr_text_white-space.asp

You either want to add a fixed "width" property (f.e. in pixels), or a "min-width" property to your element.

Title: Div with nowrap still wraps

Body:
I want to make the div stay the same size while I resize the window.
My css for the div:

.header {
    white-space: nowrap;
    color: #fff;
    padding: 0.5em;
    background: linear-gradient(90deg, #B71C1C, #0D47A1, #0D47A1);
  }

and here is the output before the wrap:

and after the wrap:

what I want is to header div always stay the same size no matter the browser's width.


问:
Android request ACCESS_NOTIFICATION_POLICY and mute phone
I am a beginner Android developer and I have an interesting question at hand. I am trying to mute the phone with

```<code>AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
</code>```

But I am getting the following error

```<code>java.lang.SecurityException: Not allowed to change Do Not Disturb state
</code>```

Now I do not understand this, as I am using EasyPermissions (https://github.com/googlesamples/easypermissions) and requesting the permission

```<code>Manifest.permission.ACCESS_NOTIFICATION_POLICY
</code>```

But it does not ask me to allow anything on app startup. I figured this is because ACCESS_NOTIFICATION_POLICY is a non dangerous permission and thus granted at installation time, for which I also added it to my manifest.xml as thus

```<code><uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />
</code>```

But it is still not working, my app is crashing because it throws the "Not allowed to change to Do Not Disturb state" error. Wierdly I found that I can request to go to the "Do Not Disturb access" screen with the following code

```<code>Intent intent = new Intent(
                    android.provider.Settings
                            .ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
 startActivity(intent);
</code>```

What am I doing wrong here? Why cannot I request this permissions as a normal permission? Do I really have to go through the intent to allow my app to mute the phone?

答:
From the AudioManager#setRingerMode() reference:

From N onward, ringer mode adjustments that would toggle Do Not Disturb are not allowed unless the app has been granted Do Not Disturb Access.

From API level 23 and onward, you have to declare ACCESS_NOTIFICATION_POLICY permission in the manifest AND then the user needs to grant your app access to toggle Do Not Disturb. You can check if the access is granted with NotificationManager#isNotificationPolicyAccessGranted(). If your package do not have access, start an ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS intent so the user can give your app access.

```<code>NotificationManager n = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if(n.isNotificationPolicyAccessGranted()) {
  AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
  audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}else{
  // Ask the user to grant access
  Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
  startActivityForResult(intent);
}
</code>```

Body:
I am a beginner Android developer and I have an interesting question at hand. I am trying to mute the phone with

AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);

But I am getting the following error

java.lang.SecurityException: Not allowed to change Do Not Disturb state

Now I do not understand this, as I am using EasyPermissions (https://github.com/googlesamples/easypermissions) and requesting the permission

Manifest.permission.ACCESS_NOTIFICATION_POLICY

But it does not ask me to allow anything on app startup. I figured this is because ACCESS_NOTIFICATION_POLICY is a non dangerous permission and thus granted at installation time, for which I also added it to my manifest.xml as thus

<uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />

But it is still not working, my app is crashing because it throws the "Not allowed to change to Do Not Disturb state" error. Wierdly I found that I can request to go to the "Do Not Disturb access" screen with the following code

Intent intent = new Intent(
                    android.provider.Settings
                            .ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
 startActivity(intent);

What am I doing wrong here? Why cannot I request this permissions as a normal permission? Do I really have to go through the intent to allow my app to mute the phone?

Body:
From the AudioManager#setRingerMode() reference:

From N onward, ringer mode adjustments that would toggle Do Not Disturb are not allowed unless the app has been granted Do Not Disturb Access.

From API level 23 and onward, you have to declare ACCESS_NOTIFICATION_POLICY permission in the manifest AND then the user needs to grant your app access to toggle Do Not Disturb. You can check if the access is granted with NotificationManager#isNotificationPolicyAccessGranted(). If your package do not have access, start an ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS intent so the user can give your app access.

NotificationManager n = (NotificationManager) getApplicationContext().getSystemService(Context.NOTIFICATION_SERVICE);
if(n.isNotificationPolicyAccessGranted()) {
  AudioManager audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
  audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}else{
  // Ask the user to grant access
  Intent intent = new Intent(android.provider.Settings.ACTION_NOTIFICATION_POLICY_ACCESS_SETTINGS);
  startActivityForResult(intent);
}


问:
Update Query problem in asp.net c# and Mysql using odbc
when i specify values in my update query the query works fine and the database gets updated, but when i use parameters in my query the database does not update

here is the code i have written

```<code>try
        {
            OdbcConnection MyConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);

MyConnection.Open();
            String MyString = "UPDATE orddetpabak SET jud1=@jud1,jud2=@jud2,jud3=@jud3,adv=@adv where fil_no=@fil_no AND orderdate=@orderdate";
            OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
            String j1=DropDownList4.SelectedValue;
            String j2=DropDownList5.SelectedValue;
            String j3=DropDownList6.SelectedValue;
            String j4=TextBox4.Text;
            String j5 = HiddenField1.Value;
            String j6 = TextBox3.Text;

            MyCmd.Parameters.AddWithValue("@jud1",j1);
            MyCmd.Parameters.AddWithValue("@jud2",j2);
            MyCmd.Parameters.AddWithValue("@jud3",j3);
            MyCmd.Parameters.AddWithValue("@adv",j4);
            MyCmd.Parameters.AddWithValue("@fil_no",j5);
            MyCmd.Parameters.AddWithValue("@orderdate",j6);

            Response.Write(DropDownList4.SelectedValue);
            Response.Write("    " + DropDownList5.SelectedValue);
            Response.Write("    " + DropDownList6.SelectedValue);
            Response.Write("    " + TextBox4.Text);
            Response.Write("    " + HiddenField1.Value);
            Response.Write("    " + TextBox3.Text);

            MyCmd.ExecuteNonQuery();
            //MyConnection.Close();
        }
        catch(Exception epp)
        {
            Response.Write(epp);
        }
</code>```

Please Help

答:
As far as I know you cannot use named parameters in MySQL. If you change your string to be

```<code>String MyString = "UPDATE orddetpabak SET jud1=?,jud2=?,jud3=?,adv=?
where fil_no=? AND orderdate=?";
</code>```

and your parameters as:

```<code>MyCmd.Parameters.AddWithValue("",j1);
MyCmd.Parameters.AddWithValue("",j2);
MyCmd.Parameters.AddWithValue("",j3);
MyCmd.Parameters.AddWithValue("",j4);
MyCmd.Parameters.AddWithValue("",j5);
MyCmd.Parameters.AddWithValue("",j6);
</code>```

Hope this helps.

ContentLicense: CC BY-SA 2.5

Body:
when i specify values in my update query the query works fine and the database gets updated, but when i use parameters in my query the database does not update

here is the code i have written

try
        {
            OdbcConnection MyConnection = new OdbcConnection(ConfigurationManager.ConnectionStrings["myconn"].ConnectionString);

MyConnection.Open();
            String MyString = "UPDATE orddetpabak SET jud1=@jud1,jud2=@jud2,jud3=@jud3,adv=@adv where fil_no=@fil_no AND orderdate=@orderdate";
            OdbcCommand MyCmd = new OdbcCommand(MyString, MyConnection);
            String j1=DropDownList4.SelectedValue;
            String j2=DropDownList5.SelectedValue;
            String j3=DropDownList6.SelectedValue;
            String j4=TextBox4.Text;
            String j5 = HiddenField1.Value;
            String j6 = TextBox3.Text;

            MyCmd.Parameters.AddWithValue("@jud1",j1);
            MyCmd.Parameters.AddWithValue("@jud2",j2);
            MyCmd.Parameters.AddWithValue("@jud3",j3);
            MyCmd.Parameters.AddWithValue("@adv",j4);
            MyCmd.Parameters.AddWithValue("@fil_no",j5);
            MyCmd.Parameters.AddWithValue("@orderdate",j6);

            Response.Write(DropDownList4.SelectedValue);
            Response.Write("    " + DropDownList5.SelectedValue);
            Response.Write("    " + DropDownList6.SelectedValue);
            Response.Write("    " + TextBox4.Text);
            Response.Write("    " + HiddenField1.Value);
            Response.Write("    " + TextBox3.Text);

            MyCmd.ExecuteNonQuery();
            //MyConnection.Close();
        }
        catch(Exception epp)
        {
            Response.Write(epp);
        }

Please Help

Body:
As far as I know you cannot use named parameters in MySQL. If you change your string to be

String MyString = "UPDATE orddetpabak SET jud1=?,jud2=?,jud3=?,adv=?
where fil_no=? AND orderdate=?";

and your parameters as:

MyCmd.Parameters.AddWithValue("",j1);
MyCmd.Parameters.AddWithValue("",j2);
MyCmd.Parameters.AddWithValue("",j3);
MyCmd.Parameters.AddWithValue("",j4);
MyCmd.Parameters.AddWithValue("",j5);
MyCmd.Parameters.AddWithValue("",j6);

Hope this helps.


问:
R.Studio: Lost my code changes while zooming out using "ctrl" + "-" in Rstudio source editor
I was using ctrl + - to make the code font smaller (or zooming out) in the R studio source editor and I got the pop up window (picture attached).

I think I pressed OK by mistake and I lost a huge chunk of code. How can I recover that?

Also. it makes me bit skeptical of using Rstudio. Pop out message

答:
ctrl + z is the undo command (Windows)

For other shortcuts:

https://support.rstudio.com/hc/en-us/articles/200711853-Keyboard-Shortcuts

From a beginner standpoint, I find rstudio to be one of the most user friendly dedicated IDE's available for any programming language.


答:
Try using

$(document).on('click', 'div.a', function(){ ... });

This will allow the event to be attached to any dynamically-created div.a elements.

Title: Can't Move a dynamically created nested div from one div to another div


问:
InvalidAuthenticityToken issue when calling ajax from assets/javascript/ function
I have a link like )">Delete this function del_file is defined in assets/javascript/file.js it calls an ajax and deletes file from server . this has been working for past 8 months. this week i have gone through some major changes in front end but the InvalidAuthenticityToken keeps showing in logs while i've not touched the backend code a bit. can anyone tell why it has changed its behavior. i'm using rails 4.2 and ruby 2.3.1

答:
You must include the CSRF token before sending the request, which is taken from the meta attribute. If you're using jQuery $.ajax, you'll have to add this in the options object:

```<code>      beforeSend: function(xhr) {
           xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},
</code>```

Alternatively, you could use the remote: true tag to create a rails ajax request, which will handle the CSRF token submission.

Body: I have a link like <a href="" onclick=" return del_file(<%= "#{file.id}" %>)">Delete this function del_file is defined in assets/javascript/file.js it calls an ajax and deletes file from server . this has been working for past 8 months. this week i have gone through some major changes in front end but the InvalidAuthenticityToken keeps showing in logs while i've not touched the backend code a bit. can anyone tell why it has changed its behavior. i'm using rails 4.2 and ruby 2.3.1

Body:
You must include the CSRF token before sending the request, which is taken from the meta attribute. If you're using jQuery $.ajax, you'll have to add this in the options object:

      beforeSend: function(xhr) {
           xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},

Alternatively, you could use the remote: true tag to create a rails ajax request, which will handle the CSRF token submission.


问:
Does Aurelia-Fetch have a dependency on whatwg-fetch?
I am trying to upgrade my Aurelia project from a beta version to the March version.

One of the errors I am getting is:

Cannot find name 'Request'.

Googling this brings up this issue on GitHub: https://github.com/aurelia/fetch-client/issues/65

This issue says that the "fix" is to install the typescript definitions for whatwg-fetch.  When I do install those typescript definitions, the error goes away.

But does that mean I need whatwg-fetch too?  (Looking in my node_modules folder, whatwg-fetch is not installed.)

答:
aurelia-fetch-client wraps the Fetch API. wahtwg-fetch is a Fetch polyfill, so it wouldn't make sense for the fetch client to depend on the polyfill. Furthermore, which polyfill you will use changed depending on which module loader you are using.

JSPM/SystemJS based apps use the fetch polyfill from GitHub, while most other module loaders use whatwg-fetch.

So yes, you will need to install whatwg-fetch, but there's a good reason for why the aurelia-fetch-client doesn't have a dependency on it.


问:
Java enhanced enhanced for loop
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

```<code>int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}
</code>```

答:
It's better to keep an outside counter to get the index,but you could do something like this ( it's bit of an overkill for a simple task):

```<code>class Enum<T> implements Iterable<Indexer<T>> {
    private int indx;
    private Iterator<T> itr;
    private Indexer<T> indxr = new Indexer<T>();

    private Enum(Iterable<T> iter) {
        this.itr = iter.iterator();
    }

    public static <T> Enum<T> iterate(Iterable<T> iter) {
        return new Enum<T>(iter);
    }

    @Override
    public Iterator<Indexer<T>> iterator() {
        return new AbstractIterator<Indexer<T>>() {
            @Override
            protected Indexer<T> computeNext() {
                if (itr.hasNext()) {
                    indxr.index = indx++;
                    indxr.val = itr.next();
                    return indxr;
                }
                return endOfData();
            }

        };
    }

}

class Indexer<T> {
    public int index;
    public T val;

    @Override
    public String toString() {
        return String.format("[ %d : %s ]", index, val);
    }
</code>```

For getting index while  while iterating:

```<code>    List<Integer> list = new ArrayList<Integer>() ;
    list.addAll(Arrays.asList(1, 2, 3, 4, 5,6,55,23,12,24,16));
    for (Indexer<Integer> en : Enum.iterate(list))
      System.out.println(en.index+" "+en.val);
</code>```

Note:The above code has dependency to Guava's AbstractIterator

Title: Java enhanced enhanced for loop

Body:
Currently (as of Java 6), using Java's enhanced for-loop I do not know of any way to directly access the iterator index short of reverting to the old indexed for-loop or using an outside counter.

Are there plans (or perhaps a current way) to implement this "enhanced enhanced" for-loop where one would be able to access the index of the loop (and even possibly manipulate it)?

As an example where this might be needed, consider(this is from actual production code):

int i = 1;
for (final String action : actions) {
  parameters.set(String.valueOf(i++), action);
}

Body:
It's better to keep an outside counter to get the index,but you could do something like this ( it's bit of an overkill for a simple task):

class Enum<T> implements Iterable<Indexer<T>> {
    private int indx;
    private Iterator<T> itr;
    private Indexer<T> indxr = new Indexer<T>();

    private Enum(Iterable<T> iter) {
        this.itr = iter.iterator();
    }

    public static <T> Enum<T> iterate(Iterable<T> iter) {
        return new Enum<T>(iter);
    }

    @Override
    public Iterator<Indexer<T>> iterator() {
        return new AbstractIterator<Indexer<T>>() {
            @Override
            protected Indexer<T> computeNext() {
                if (itr.hasNext()) {
                    indxr.index = indx++;
                    indxr.val = itr.next();
                    return indxr;
                }
                return endOfData();
            }

        };
    }

}

class Indexer<T> {
    public int index;
    public T val;

    @Override
    public String toString() {
        return String.format("[ %d : %s ]", index, val);
    }

For getting index while  while iterating:

    List<Integer> list = new ArrayList<Integer>() ;
    list.addAll(Arrays.asList(1, 2, 3, 4, 5,6,55,23,12,24,16));
    for (Indexer<Integer> en : Enum.iterate(list))
      System.out.println(en.index+" "+en.val);

Note:The above code has dependency to Guava's AbstractIterator


问:
Refined and existential types for runtime values
Suppose I want to map between some strings and integer identifiers, and I want my types to make it impossible to get a runtime failure because someone tried to look up an id that was out of range. Here's one straightforward API:

```<code>trait Vocab {
  def getId(value: String): Option[Int]
  def getValue(id: Int): Option[String]
}
</code>```

This is annoying, though, if users will typically be getting their ids from getId and therefore know they're valid. The following is an improvement in that sense:

```<code>trait Vocab[Id] {
  def getId(value: String): Option[Id]
  def getValue(id: Id): String
}
</code>```

Now we could have something like this:

```<code>class TagId private(val value: Int) extends AnyVal

object TagId {
  val tagCount: Int = 100

  def fromInt(id: Int): Option[TagId] =
    if (id >= 0 && id < tagCount) Some(new TagId(id)) else None
}
</code>```

And then our users can work with Vocab[TagId] and not have to worry about checking whether getValue lookups failed in the typical case, but they can still look up arbitrary integers if they need to. It's still pretty awkward, though, since we have to write a separate type for each kind of thing we want a vocabulary for.

We can also do something like this with refined:

```<code>import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval.ClosedOpen
import shapeless.Witness

class Vocab(values: Vector[String]) {
  type S <: Int
  type P = ClosedOpen[Witness.`0`.T, S]

  def size: S = values.size.asInstanceOf[S]

  def getId(value: String): Option[Refined[Int, P]] = values.indexOf(value) match {
    case -1 => None
    case i  => Some(Refined.unsafeApply[Int, P](i))
  }

  def getValue(id: Refined[Int, P]): String = values(id.value)
}
</code>```

Now even though S isn't known at compile time, the compiler is still able to keep track of the fact that the ids it gives us are between zero and S, so that we don't have to worry about the possibility of failure when we go back to values (if we're using the same vocab instance, of course).

What I want is to be able to write this:

```<code>val x = 2
val vocab = new Vocab(Vector("foo", "bar", "qux"))

eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
</code>```

So that users can easily look up arbitrary integers when they really need to. This doesn't compile, though:

```<code>scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
<console>:17: error: could not find implicit value for parameter v: eu.timepit.refined.api.Validate[Int,vocab.P]
       eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
                                          ^
</code>```

I can make it compile by providing a Witness instance for S:

```<code>scala> implicit val witVocabS: Witness.Aux[vocab.S] = Witness.mkWitness(vocab.size)
witVocabS: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@485aac3c

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
res1: scala.util.Either[String,String] = Right(qux)
</code>```

And of course it fails (at runtime but safely) when the value is out of range:

```<code>scala> val y = 3
y: Int = 3

scala> println(eu.timepit.refined.refineV[vocab.P](y).map(vocab.getValue))
Left(Right predicate of (!(3 < 0) && (3 < 3)) failed: Predicate failed: (3 < 3).)
</code>```

I could also put the witness definition inside my Vocab class and then import vocab._ to make it available when I need this, but what I really want is to be able to provide refineV support without extra imports or definitions.

I've tried various stuff like this:

```<code>object Vocab {
  implicit def witVocabS[V <: Vocab](implicit
    witV: Witness.Aux[V]
  ): Witness.Aux[V#S] = Witness.mkWitness(witV.value.size)
}
</code>```

But this still requires an explicit definition for each vocab instance:

```<code>scala> implicit val witVocabS: Witness.Aux[vocab.S] = Vocab.witVocabS
witVocabS: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@1bde5374

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
res4: scala.util.Either[String,String] = Right(qux)
</code>```

I know I could implement witVocabS with a macro, but I feel like there should be a nicer way to do this kind of thing, since it seems like a pretty reasonable use case (and I'm not very familiar with refined, so it's entirely possible that I'm missing something obvious).

答:
Turns out that this works as you would like if we make the type parameter S concrete by assigning it the singleton type of values.size using shapeless.Witness:

```<code>import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval.ClosedOpen
import shapeless.Witness

class Vocab(values: Vector[String]) {
  val sizeStable: Int = values.size
  val sizeWitness = Witness(sizeStable)

  type S = sizeWitness.T
  type P = ClosedOpen[Witness.`0`.T, S]

  def size: S = sizeWitness.value

  def getId(value: String): Option[Refined[Int, P]] = values.indexOf(value) match {
    case -1 => None
    case i => Some(Refined.unsafeApply[Int, P](i))
  }

  def getValue(id: Refined[Int, P]): String = values(id.value)
}
</code>```

If Scala would allow singleton types of AnyVals, we could remove sizeWitness and define type S = sizeStable.type. This limitation is lifted in the SIP-23 implementation.

Using refineV now just works even with the path dependant type vocab.P:

```<code>scala> val vocab = new Vocab(Vector("foo", "bar", "baz"))
vocab: Vocab = Vocab@5fae6bb9

scala> refineV[vocab.P](2)
res0: Either[String,eu.timepit.refined.api.Refined[Int,vocab.P]] = Right(2)

scala> refineV[vocab.P](4)
res1: Either[String,eu.timepit.refined.api.Refined[Int,vocab.P]] = Left(Right predicate of (!(4 < 0) && (4 < 3)) failed: Predicate failed: (4 < 3).)

scala> refineV[vocab.P](2).map(vocab.getValue)
res2: scala.util.Either[String,String] = Right(baz)
</code>```

This works since the compiler can now find an implicit Witness.Aux[vocab.S] outside the scope of Vocab instances:

```<code>scala> val s = implicitly[shapeless.Witness.Aux[vocab.S]]
s: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@16cd7aa2

scala> s.value
res2: s.T = 3
</code>```

refined now uses this implicit instance to construct a Validate[Int, vocab.P] instance which refineV uses to decide if an Int is valid index for vocab.

Body:
Suppose I want to map between some strings and integer identifiers, and I want my types to make it impossible to get a runtime failure because someone tried to look up an id that was out of range. Here's one straightforward API:

trait Vocab {
  def getId(value: String): Option[Int]
  def getValue(id: Int): Option[String]
}

This is annoying, though, if users will typically be getting their ids from getId and therefore know they're valid. The following is an improvement in that sense:

trait Vocab[Id] {
  def getId(value: String): Option[Id]
  def getValue(id: Id): String
}

Now we could have something like this:

class TagId private(val value: Int) extends AnyVal

object TagId {
  val tagCount: Int = 100

  def fromInt(id: Int): Option[TagId] =
    if (id >= 0 && id < tagCount) Some(new TagId(id)) else None
}

And then our users can work with Vocab[TagId] and not have to worry about checking whether getValue lookups failed in the typical case, but they can still look up arbitrary integers if they need to. It's still pretty awkward, though, since we have to write a separate type for each kind of thing we want a vocabulary for.

We can also do something like this with refined:

import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval.ClosedOpen
import shapeless.Witness

class Vocab(values: Vector[String]) {
  type S <: Int
  type P = ClosedOpen[Witness.`0`.T, S]

  def size: S = values.size.asInstanceOf[S]

  def getId(value: String): Option[Refined[Int, P]] = values.indexOf(value) match {
    case -1 => None
    case i  => Some(Refined.unsafeApply[Int, P](i))
  }

  def getValue(id: Refined[Int, P]): String = values(id.value)
}

Now even though S isn't known at compile time, the compiler is still able to keep track of the fact that the ids it gives us are between zero and S, so that we don't have to worry about the possibility of failure when we go back to values (if we're using the same vocab instance, of course).

What I want is to be able to write this:

val x = 2
val vocab = new Vocab(Vector("foo", "bar", "qux"))

eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)

So that users can easily look up arbitrary integers when they really need to. This doesn't compile, though:

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
<console>:17: error: could not find implicit value for parameter v: eu.timepit.refined.api.Validate[Int,vocab.P]
       eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
                                          ^

I can make it compile by providing a Witness instance for S:

scala> implicit val witVocabS: Witness.Aux[vocab.S] = Witness.mkWitness(vocab.size)
witVocabS: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@485aac3c

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
res1: scala.util.Either[String,String] = Right(qux)

And of course it fails (at runtime but safely) when the value is out of range:

scala> val y = 3
y: Int = 3

scala> println(eu.timepit.refined.refineV[vocab.P](y).map(vocab.getValue))
Left(Right predicate of (!(3 < 0) && (3 < 3)) failed: Predicate failed: (3 < 3).)

I could also put the witness definition inside my Vocab class and then import vocab._ to make it available when I need this, but what I really want is to be able to provide refineV support without extra imports or definitions.

I've tried various stuff like this:

object Vocab {
  implicit def witVocabS[V <: Vocab](implicit
    witV: Witness.Aux[V]
  ): Witness.Aux[V#S] = Witness.mkWitness(witV.value.size)
}

But this still requires an explicit definition for each vocab instance:

scala> implicit val witVocabS: Witness.Aux[vocab.S] = Vocab.witVocabS
witVocabS: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@1bde5374

scala> eu.timepit.refined.refineV[vocab.P](x).map(vocab.getValue)
res4: scala.util.Either[String,String] = Right(qux)

I know I could implement witVocabS with a macro, but I feel like there should be a nicer way to do this kind of thing, since it seems like a pretty reasonable use case (and I'm not very familiar with refined, so it's entirely possible that I'm missing something obvious).

Body:
Turns out that this works as you would like if we make the type parameter S concrete by assigning it the singleton type of values.size using shapeless.Witness:

import eu.timepit.refined.api.Refined
import eu.timepit.refined.numeric.Interval.ClosedOpen
import shapeless.Witness

class Vocab(values: Vector[String]) {
  val sizeStable: Int = values.size
  val sizeWitness = Witness(sizeStable)

  type S = sizeWitness.T
  type P = ClosedOpen[Witness.`0`.T, S]

  def size: S = sizeWitness.value

  def getId(value: String): Option[Refined[Int, P]] = values.indexOf(value) match {
    case -1 => None
    case i => Some(Refined.unsafeApply[Int, P](i))
  }

  def getValue(id: Refined[Int, P]): String = values(id.value)
}

If Scala would allow singleton types of AnyVals, we could remove sizeWitness and define type S = sizeStable.type. This limitation is lifted in the SIP-23 implementation.

Using refineV now just works even with the path dependant type vocab.P:

scala> val vocab = new Vocab(Vector("foo", "bar", "baz"))
vocab: Vocab = Vocab@5fae6bb9

scala> refineV[vocab.P](2)
res0: Either[String,eu.timepit.refined.api.Refined[Int,vocab.P]] = Right(2)

scala> refineV[vocab.P](4)
res1: Either[String,eu.timepit.refined.api.Refined[Int,vocab.P]] = Left(Right predicate of (!(4 < 0) && (4 < 3)) failed: Predicate failed: (4 < 3).)

scala> refineV[vocab.P](2).map(vocab.getValue)
res2: scala.util.Either[String,String] = Right(baz)

This works since the compiler can now find an implicit Witness.Aux[vocab.S] outside the scope of Vocab instances:

scala> val s = implicitly[shapeless.Witness.Aux[vocab.S]]
s: shapeless.Witness.Aux[vocab.S] = shapeless.Witness$$anon$1@16cd7aa2

scala> s.value
res2: s.T = 3

refined now uses this implicit instance to construct a Validate[Int, vocab.P] instance which refineV uses to decide if an Int is valid index for vocab.


问:
Dynamically create a tuple with all the same type and a known number of elements
I am looking to dynamically create tuples of a given size that have all the same type.

So if I wanted a tuple of strings of size three I would get Tuple<string, string, string>

I have tried both to pass strings into the angle brackets for Tuple like this:

```<code>string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);
</code>```

and to pass an array of types into the angle brackets like this:

```<code>List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);
</code>```

Neither one of these worked. Does anyone know how to make the described dynamic tuples?

(The reason I want to do this is to use tuples inside of a dictionary like

```<code>Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();
</code>```

Using tuples here is more useful than HashSets because the comparison in tuples is by components instead of by reference so that if I have

```<code>Tuple<string, string> testTuple1 = new Tuple<string, string>("yes", "no");
Tuple<string, string> testTuple2 = new Tuple<string, string>("yes", "no");
Dictionary<Tuple<string, string>, string> testDictionary = new Dictionary<Tuple<string, string>, string>() {
    {testTuple1, "maybe"}
};
Console.WriteLine(testDict[testTuple2]);
</code>```

it writes "maybe". If you run this same test with HashSets, it throws an error. If there is a better way to accomplish this same thing, that would also be useful.)

答:
You could do something like this using reflection:

```<code>    public static object GetTuple<T>(params T[] values)
    {
        Type genericType = Type.GetType("System.Tuple`" + values.Length);
        Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
        Type specificType = genericType.MakeGenericType(typeArgs);
        object[] constructorArguments = values.Cast<object>().ToArray();
        return Activator.CreateInstance(specificType, constructorArguments);
    }
</code>```

That will give you a tuple for a variable number of elements.

Body:
I am looking to dynamically create tuples of a given size that have all the same type.

So if I wanted a tuple of strings of size three I would get Tuple<string, string, string>

I have tried both to pass strings into the angle brackets for Tuple like this:

string foo = "string, string, string";
Tuple<foo> testTuple = Tuple<foo>(~parameters~);

and to pass an array of types into the angle brackets like this:

List<Type> types = new List<Type>() {"".GetType(), "".GetType(), "".GetType()};
Tuple<types> testTuple = Tuple<foo>(~parameters~);

Neither one of these worked. Does anyone know how to make the described dynamic tuples?

(The reason I want to do this is to use tuples inside of a dictionary like

Dictionary<Tuple<# strings>, int> testDictionary = new Dictionary<Tuple<x # strings>, int>();

Using tuples here is more useful than HashSets because the comparison in tuples is by components instead of by reference so that if I have

Tuple<string, string> testTuple1 = new Tuple<string, string>("yes", "no");
Tuple<string, string> testTuple2 = new Tuple<string, string>("yes", "no");
Dictionary<Tuple<string, string>, string> testDictionary = new Dictionary<Tuple<string, string>, string>() {
    {testTuple1, "maybe"}
};
Console.WriteLine(testDict[testTuple2]);

it writes "maybe". If you run this same test with HashSets, it throws an error. If there is a better way to accomplish this same thing, that would also be useful.)

Body:
You could do something like this using reflection:

    public static object GetTuple<T>(params T[] values)
    {
        Type genericType = Type.GetType("System.Tuple`" + values.Length);
        Type[] typeArgs = values.Select(_ => typeof(T)).ToArray();
        Type specificType = genericType.MakeGenericType(typeArgs);
        object[] constructorArguments = values.Cast<object>().ToArray();
        return Activator.CreateInstance(specificType, constructorArguments);
    }

That will give you a tuple for a variable number of elements.


问:
different behaviors between Eigen::Ref and Eigen::MatrixBase
I am wondering why the following code generates a compile-time error:

```<code>void f(const double e) {}

void f(const Eigen::Ref<const MatrixX<double>>& g) {}

int main {
  Eigen::Matrix<double, 2, 1> m1;
  Eigen::Matrix<double, 2, 1> m2;
  m1 << 1.0, 2.0;
  m2 << 1.0, 2.0;
  f(m1.transpose() * m2);  // error: call to 'f' is ambiguous
}
</code>```

while the following one doesn't.

```<code>void f(const double e) {}

template <typename Derived>
void f(const Eigen::MatrixBase<Derived>& m) {}

int main {
  Eigen::Matrix<double, 2, 1> m1;
  Eigen::Matrix<double, 2, 1> m2;
  m1 << 1.0, 2.0;
  m2 << 1.0, 2.0;
  f(m1.transpose() * m2);  // no error
}
</code>```

答:
This because in your case m1.transpose() * m2 is an inner product that is allowed to be assigned to a scalar:

```<code>double v = m1.transpose() * m2;
</code>```

This is the unique situation where a 1x1 matrix expression is allowed to be converted to a scalar. In the second version there is no ambiguity because the type of the expression m1.transpose() * m2 inherits MatrixBase.

Body:
I am wondering why the following code generates a compile-time error:

void f(const double e) {}

void f(const Eigen::Ref<const MatrixX<double>>& g) {}

int main {
  Eigen::Matrix<double, 2, 1> m1;
  Eigen::Matrix<double, 2, 1> m2;
  m1 << 1.0, 2.0;
  m2 << 1.0, 2.0;
  f(m1.transpose() * m2);  // error: call to 'f' is ambiguous
}

while the following one doesn't.

void f(const double e) {}

template <typename Derived>
void f(const Eigen::MatrixBase<Derived>& m) {}

int main {
  Eigen::Matrix<double, 2, 1> m1;
  Eigen::Matrix<double, 2, 1> m2;
  m1 << 1.0, 2.0;
  m2 << 1.0, 2.0;
  f(m1.transpose() * m2);  // no error
}

Body:
This because in your case m1.transpose() * m2 is an inner product that is allowed to be assigned to a scalar:

double v = m1.transpose() * m2;

This is the unique situation where a 1x1 matrix expression is allowed to be converted to a scalar. In the second version there is no ambiguity because the type of the expression m1.transpose() * m2 inherits MatrixBase.


问:
PictureBox not sizing properly
I created a PictureBox and load an image into it, and I wanted the pictures to have a maximum size (let's say 250px). Here is the code I'm using at that moment

```<code>PictureBox cellPictureBox = new PictureBox();
                            cellPictureBox.AutoSize = false;
                            cellPictureBox.Dock = DockStyle.Fill;
                            cellPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
                            cellPictureBox.Image = Base64ToImage(data.ToString().Trim());

                            cellPictureBox.Width = 250;
                            cellPictureBox.Height = 250;
</code>```

When I load the first image, it's quite large. When I load a second image, it's automatically scaled down to be very tiny, and the newly loaded image takesthe large size the first image had. This trend continues as I add more rows to my data.

What can I do to help manage the sizing of my images? Making a custom control I've been told is useful, but I don't see what is happening that I have wrong.

答:
To set maximum and minimum sizes, have a look at the following:

```<code>PictureBox cellPictureBox = new PictureBox();
cellPictureBox.AutoSize = false;
cellPictureBox.Dock = DockStyle.Fill;
cellPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
cellPictureBox.Image = Base64ToImage(data.ToString().Trim());

cellPictureBox.MinimumSize = new Size(100, 100); // or whatever size you want.
cellPictureBox.MaximumSize = new Size(250, 250);
</code>```

If you only want to set a limit on one dimension, for example, the width, but the height is allowed to be anything, then use int.MaxValue:

```<code>cellPictureBox.MaximumSize = new Size(250, int.MaxValue);
</code>```

Title: PictureBox not sizing properly

Body:
I created a PictureBox and load an image into it, and I wanted the pictures to have a maximum size (let's say 250px). Here is the code I'm using at that moment

PictureBox cellPictureBox = new PictureBox();
                            cellPictureBox.AutoSize = false;
                            cellPictureBox.Dock = DockStyle.Fill;
                            cellPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
                            cellPictureBox.Image = Base64ToImage(data.ToString().Trim());

                            cellPictureBox.Width = 250;
                            cellPictureBox.Height = 250;

When I load the first image, it's quite large. When I load a second image, it's automatically scaled down to be very tiny, and the newly loaded image takesthe large size the first image had. This trend continues as I add more rows to my data.

What can I do to help manage the sizing of my images? Making a custom control I've been told is useful, but I don't see what is happening that I have wrong.

Body:
To set maximum and minimum sizes, have a look at the following:

PictureBox cellPictureBox = new PictureBox();
cellPictureBox.AutoSize = false;
cellPictureBox.Dock = DockStyle.Fill;
cellPictureBox.SizeMode = PictureBoxSizeMode.Zoom;
cellPictureBox.Image = Base64ToImage(data.ToString().Trim());

cellPictureBox.MinimumSize = new Size(100, 100); // or whatever size you want.
cellPictureBox.MaximumSize = new Size(250, 250);

If you only want to set a limit on one dimension, for example, the width, but the height is allowed to be anything, then use int.MaxValue:

cellPictureBox.MaximumSize = new Size(250, int.MaxValue);


问:
How can I use Sails.js actionUtil.js in my controller?
I generated an api building using sails command line and now I would like to customize logic inside route /building. I checked sails source code to replicate the basic behaviour of find action with my customizations.

I saw that the very convenient library actionUtil is used to perform this action and I would like to reuse this file in my controller. How can I do that ?

My final goal is just to display buildings which user has access to, if you have a better idea than replicate sails source code, I'm in !

Thanks

答:
Santosh Gali's answer is right, but just wanted to suggest a way of achieving what you're after.

I don't know if this is the right way of doing this, but...

If you look at the parseCriteria method in actionUtil, you'll find this line: where = _.merge({}, req.options.where || {}, where) || undefined;, so you can actually modify the criteria by modifying req.options.where.

So if you create a policy like this one, you should be good to go

module.exports = function (req, res, next) {
  if (!req.options.where) req.options.where = {};
  req.options.where.owner = req.session.user;
  next();
};

Of course you'll have to be using sessions and save the user id in it for this to work.


问:
Websphere x JSR 286 best practices
I am now defining the architectural approach we'll use on a new project with Websphere 6 + JSR86 portlets under a very known portal tool.

What I am planning is to use one .ear file per portlet group (eg.: if two portlets are closely related they'll be on the same .ear) and using shared libraries to hold common code and libraries used by these portlets.

Did someone use this approach (or another one) before? Do you consider this a good approach?

I am looking for some opinions or talking about this architecture with someone (as I didn't find on IBM website a "best practices" article that adresses my scenario), as it looks very clear to me but it wouldn't be good to discover some problem ahead just because I've never asked someone.

答: Usually I deployed the portlet to WebSphere Portal in war files, this is the only option if I have access to administration page in Portal view. You have to distinguish admin page of WAS (here you can deploy J2EE apps,but they are not considered as portlet) and admin page of Portal. I put shared libraries in shared folder of portal, but maybe it's not a best practice. </p>

Title: Websphere x JSR 286 best practices


问:
JS keeps redirecting me to a null page
I have this js script that will make the page fade in when the user enters, and fades out when the user clicks a link to another page. It works, but somehow I have my anchor links within the page and whenever I click the links, it takes me to the anchor and within a few seconds it redirects me to a null page like localhost/website/null

here's the code:

```<code>jQuery('body').css('display', 'none');
jQuery(document).ready(function() {
   jQuery('body').fadeIn();
   jQuery('a').on('click', function(event) {
      var thetarget = this.getAttribute('target')
      if (thetarget !="_blank" ) {
         var thehref = this.getAttribute('href')
         event.preventDefault();
         jQuery('body').fadeOut(function(){
            window.location = thehref
         });
      }
    });
});
setTimeout(function() {
    jQuery('body').fadeIn();
}, 1000)
</code>```

答:
I'm not understanding the problem -- maybe there isn't an issue? Refer to the snippet below?

Meta/Sidenote: SO needs a better way of creating snippets for comments -- this shouldn't be an answer, but there's no better way to supply a SO-generated demo.

jQuery('.container').css('display', 'none');

jQuery(document).ready(function($) {
  var $container = $('container').fadeIn();

  $('a').on('click', function(e) {
    var _target = this.getAttribute('target');

    if (_target != "_blank") { // (e.g., null, '_self')
      var _href = this.getAttribute('href');
      e.preventDefault();

      $('.container').fadeOut(function() {
        window.location = _href;
      });
    }
  });
});

setTimeout(function() {
  jQuery('.container').fadeIn();
}, 1000)```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.container {
  background: #09c;
  padding: 1em;
  height: 100%;
  width: 100vw;
}

a:nth-child(2n)::after {
  content: "\A";
  white-space: pre;
}

body {
  margin: 0;
  padding: 0;
}</code>```

    _self (external link)
    _self (internal link)
    _blank (external link)
    _blank (internal link)
    No target (external link)
    No target (internal link)

Lorem ipsum dolor sit amet, consectetur adipisicing elit. Esse, reprehenderit, nostrum. Tempora totam, iusto, inventore cupiditate hic quam quas explicabo dolore mollitia eius ullam rerum minus placeat nobis in debitis magni non, dolor aut libero
      dignissimos fugiat. Sed laboriosam itaque necessitatibus hic excepturi, perferendis, exercitationem cumque incidunt asperiores labore dolor.

Minus velit rerum, reiciendis perspiciatis pariatur accusamus, magni voluptatibus, voluptatem fugit optio libero quidem! Nostrum pariatur eveniet ipsum obcaecati aperiam deleniti hic quam facilis reprehenderit dolor ipsam suscipit, quidem laboriosam
      impedit fugiat sit dignissimos delectus qui. Suscipit necessitatibus natus omnis eveniet molestiae nostrum aut culpa, tempora, voluptatibus modi eius nisi.

Illo quo, iure doloremque unde ullam iste. Fuga ullam dicta voluptate, odio sint molestiae expedita sequi, placeat omnis porro. Blanditiis ut, laboriosam nobis necessitatibus esse ipsam, magnam facilis in placeat delectus quidem eos laborum, illum
      similique fugiat nesciunt doloremque ratione unde vel fugit excepturi dolor minima, amet tenetur. Tempora, eveniet.

Aliquam ex assumenda eum perspiciatis odio suscipit nemo in delectus. Iste in, ipsam iure deserunt, explicabo ipsum maxime. Praesentium, vitae, quos quia sed doloribus laboriosam. Architecto sapiente totam quisquam esse saepe asperiores provident
      voluptatibus aperiam, similique sunt fugit cupiditate beatae aspernatur laborum, eius quas ab tempore consequatur officiis vero! Fugiat.

Explicabo minima necessitatibus soluta odio, sunt saepe aspernatur quasi molestiae cum? Nulla eveniet ad accusantium sed sapiente quod ea soluta repellendus culpa, ut deleniti dolore. Porro amet, quasi dignissimos provident modi nihil rerum quis explicabo,
      voluptatem illo assumenda itaque. Maxime sequi asperiores enim tempora maiores dolor. Nihil quidem repudiandae asperiores!

Dicta facere at dolorum ut veritatis recusandae praesentium nesciunt illo, omnis doloremque labore repellendus soluta officia distinctio aperiam pariatur minus quia placeat enim, amet, quae repellat reiciendis nihil magni. Ad expedita dolores cupiditate
      debitis dolore? Unde vitae inventore provident reiciendis adipisci dolorum ad ipsa possimus excepturi, mollitia nobis. Perspiciatis, voluptate.

Officia minima nulla delectus neque sapiente in voluptates iste facere dolorum sequi, animi fuga illo enim alias explicabo, culpa? Quaerat nesciunt animi, eius assumenda quidem sunt saepe nam suscipit voluptate eaque, laborum minus expedita nostrum
      praesentium iusto eveniet officia ab tempore eos at. Dolores minus qui fugit, temporibus sequi tempora!

    ID:foo

```

Title: JS keeps redirecting me to a null page

Body:
I have this js script that will make the page fade in when the user enters, and fades out when the user clicks a link to another page. It works, but somehow I have my anchor links within the page and whenever I click the links, it takes me to the anchor and within a few seconds it redirects me to a null page like localhost/website/null

here's the code:

jQuery('body').css('display', 'none');
jQuery(document).ready(function() {
   jQuery('body').fadeIn();
   jQuery('a').on('click', function(event) {
      var thetarget = this.getAttribute('target')
      if (thetarget !="_blank" ) {
         var thehref = this.getAttribute('href')
         event.preventDefault();
         jQuery('body').fadeOut(function(){
            window.location = thehref
         });
      }
    });
});
setTimeout(function() {
    jQuery('body').fadeIn();
}, 1000)

Body:
I'm not understanding the problem -- maybe there isn't an issue? Refer to the snippet below?

Meta/Sidenote: SO needs a better way of creating snippets for comments -- this shouldn't be an answer, but there's no better way to supply a SO-generated demo.

jQuery('.container').css('display', 'none');

jQuery(document).ready(function($) {
  var $container = $('container').fadeIn();

  $('a').on('click', function(e) {
    var _target = this.getAttribute('target');

    if (_target != "_blank") { // (e.g., null, '_self')
      var _href = this.getAttribute('href');
      e.preventDefault();

      $('.container').fadeOut(function() {
        window.location = _href;
      });
    }
  });
});

setTimeout(function() {
  jQuery('.container').fadeIn();
}, 1000)

.container {
  background: #09c;
  padding: 1em;
  height: 100%;
  width: 100vw;
}

a:nth-child(2n)::after {
  content: "\A";
  white-space: pre;
}

body {
  margin: 0;
  padding: 0;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<body>

  <div class="container">
    <a href="//www.google.com" target="_self">_self (external link)</a>
    <a href="#foo" target="_self">_self (internal link)</a>
    <a href="//www.google.com" target="_blank">_blank (external link)</a>
    <a href="#foo" target="_blank">_blank (internal link)</a>
    <a href="//www.google.com">No target (external link)</a>
    <a href="#foo">No target (internal link)</a>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Esse, reprehenderit, nostrum. Tempora totam, iusto, inventore cupiditate hic quam quas explicabo dolore mollitia eius ullam rerum minus placeat nobis in debitis magni non, dolor aut libero
      dignissimos fugiat. Sed laboriosam itaque necessitatibus hic excepturi, perferendis, exercitationem cumque incidunt asperiores labore dolor.</p>
    <p>Minus velit rerum, reiciendis perspiciatis pariatur accusamus, magni voluptatibus, voluptatem fugit optio libero quidem! Nostrum pariatur eveniet ipsum obcaecati aperiam deleniti hic quam facilis reprehenderit dolor ipsam suscipit, quidem laboriosam
      impedit fugiat sit dignissimos delectus qui. Suscipit necessitatibus natus omnis eveniet molestiae nostrum aut culpa, tempora, voluptatibus modi eius nisi.</p>
    <p>Illo quo, iure doloremque unde ullam iste. Fuga ullam dicta voluptate, odio sint molestiae expedita sequi, placeat omnis porro. Blanditiis ut, laboriosam nobis necessitatibus esse ipsam, magnam facilis in placeat delectus quidem eos laborum, illum
      similique fugiat nesciunt doloremque ratione unde vel fugit excepturi dolor minima, amet tenetur. Tempora, eveniet.</p>
    <p>Aliquam ex assumenda eum perspiciatis odio suscipit nemo in delectus. Iste in, ipsam iure deserunt, explicabo ipsum maxime. Praesentium, vitae, quos quia sed doloribus laboriosam. Architecto sapiente totam quisquam esse saepe asperiores provident
      voluptatibus aperiam, similique sunt fugit cupiditate beatae aspernatur laborum, eius quas ab tempore consequatur officiis vero! Fugiat.</p>
    <p>Explicabo minima necessitatibus soluta odio, sunt saepe aspernatur quasi molestiae cum? Nulla eveniet ad accusantium sed sapiente quod ea soluta repellendus culpa, ut deleniti dolore. Porro amet, quasi dignissimos provident modi nihil rerum quis explicabo,
      voluptatem illo assumenda itaque. Maxime sequi asperiores enim tempora maiores dolor. Nihil quidem repudiandae asperiores!</p>
    <p>Dicta facere at dolorum ut veritatis recusandae praesentium nesciunt illo, omnis doloremque labore repellendus soluta officia distinctio aperiam pariatur minus quia placeat enim, amet, quae repellat reiciendis nihil magni. Ad expedita dolores cupiditate
      debitis dolore? Unde vitae inventore provident reiciendis adipisci dolorum ad ipsa possimus excepturi, mollitia nobis. Perspiciatis, voluptate.</p>
    <p>Officia minima nulla delectus neque sapiente in voluptates iste facere dolorum sequi, animi fuga illo enim alias explicabo, culpa? Quaerat nesciunt animi, eius assumenda quidem sunt saepe nam suscipit voluptate eaque, laborum minus expedita nostrum
      praesentium iusto eveniet officia ab tempore eos at. Dolores minus qui fugit, temporibus sequi tempora!</p>
    <a id="foo" name="foo">ID:foo</a>
  </div>

</body>


问:
Stringify (convert to JSON) a JavaScript object with circular reference
I've got a JavaScript object definition which contains a circular reference: it has a property that references the parent object.

It also has functions that I don't want to be passed through to the server. How would I serialize and deserialize these objects?

I've read that the best method to do this is to use Douglas Crockford's stringify. However, I'm getting the following error in Chrome:

TypeError: Converting circular structure to JSON

The code:

```<code>function finger(xid, xparent){
    this.id = xid;
    this.xparent;
    //other attributes
}

function arm(xid, xparent){
    this.id = xid;
    this.parent = xparent;
    this.fingers = [];

    //other attributes

    this.moveArm = function() {
        //moveArm function details - not included in this testcase
        alert("moveArm Executed");
    }
}

 function person(xid, xparent, xname){
    this.id = xid;
    this.parent = xparent;
    this.name = xname
    this.arms = []

    this.createArms = function () {
        this.arms[this.arms.length] = new arm(this.id, this);
    }
}

function group(xid, xparent){
    this.id = xid;
    this.parent = xparent;
    this.people = [];
    that = this;

    this.createPerson = function () {
        this.people[this.people.length] = new person(this.people.length, this, "someName");
        //other commands
    }

    this.saveGroup = function () {
        alert(JSON.stringify(that.people));
    }
}
</code>```

This is a test case that I created for this question. There are errors within this code but essentially I have objects within objects, and a reference passed to each object to show what the parent object is when the object is created. Each object also contains functions, which I don't want stringified. I just want the properties such as the Person.Name.

How do I serialize before sending to the server and deserialize it assuming that the same JSON is passed back?

答:
Happened upon this thread because I needed to log complex objects to a page, since remote debugging wasn't possible in my particular situation. Found Douglas Crockford's (inceptor of JSON) own cycle.js, which annotates circular references as strings such that they can be reconnected after parsing. The de-cycled deep copy is safe to pass through JSON.stringify. Enjoy!

https://github.com/douglascrockford/JSON-js

cycle.js: This file contains two functions, JSON.decycle and
  JSON.retrocycle, which make it possible to encode cyclical structures
  and dags in JSON, and to then recover them. This is a capability that
  is not provided by ES5. JSONPath  is used to represent the links.

Body:
I've got a JavaScript object definition which contains a circular reference: it has a property that references the parent object.

It also has functions that I don't want to be passed through to the server. How would I serialize and deserialize these objects?

I've read that the best method to do this is to use Douglas Crockford's stringify. However, I'm getting the following error in Chrome:

TypeError: Converting circular structure to JSON

The code:

function finger(xid, xparent){
    this.id = xid;
    this.xparent;
    //other attributes
}

function arm(xid, xparent){
    this.id = xid;
    this.parent = xparent;
    this.fingers = [];

    //other attributes

    this.moveArm = function() {
        //moveArm function details - not included in this testcase
        alert("moveArm Executed");
    }
}

 function person(xid, xparent, xname){
    this.id = xid;
    this.parent = xparent;
    this.name = xname
    this.arms = []

    this.createArms = function () {
        this.arms[this.arms.length] = new arm(this.id, this);
    }
}

function group(xid, xparent){
    this.id = xid;
    this.parent = xparent;
    this.people = [];
    that = this;

    this.createPerson = function () {
        this.people[this.people.length] = new person(this.people.length, this, "someName");
        //other commands
    }

    this.saveGroup = function () {
        alert(JSON.stringify(that.people));
    }
}

This is a test case that I created for this question. There are errors within this code but essentially I have objects within objects, and a reference passed to each object to show what the parent object is when the object is created. Each object also contains functions, which I don't want stringified. I just want the properties such as the Person.Name.

How do I serialize before sending to the server and deserialize it assuming that the same JSON is passed back?


问:
APACHE-DJANGO-WSGI Deployment
I have a django app located at

/home/user/myapp

I'm trying to run the app with apache2 and WSGI. Currently, the apache2 configuration is at /etc/apache2/apache2.conf and has this directory relating to my webiste

```<code>    <VirtualHost website.com:80>
   ServerName website.com
   ServerAlias www.website.com
   ServerAdmin email@website.com

   DocumentRoot /home/user/myapp/static

   WSGIScriptAlias / /var/www/website-directory/django.wsgi
   <Directory /home/user/myapp/static>
  Order allow,deny
      Allow from all
   </Directory>

   Alias /robots.txt /var/www/webisite-directory/robots.txt
   Alias /favicon.ico /var/www/webisite-directory/favicon.ico
   Alias /images /home/user/myapp/images
   Alias /static /home/user/myapp/static

   ErrorLog /var/www/webisite-directory/error.log
   CustomLog /var/www/webisite-directory/access.log combined
</VirtualHost>
</code>```

My django.wsgi is

```<code>import os
import sys

sys.path.append('/home/user/myapp')

os.environ['DJANGO_SETTINGS_MODULE'] = '/myapp_directory/settings'
sys.executable = '/usr/lib/python2.7/dist-packages'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()
</code>```

Here is my error log

```<code>  user@ubuntu:/var/www/website-directory$ vim error.log
[Thu Mar 30 01:25:10.060478 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] self.load_middleware(), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060490 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 48, in load_middleware, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060509 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] if settings.MIDDLEWARE is None:, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060521 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060558 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] self._setup(name), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060570 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060585 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] self._wrapped = Settings(settings_module), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060597 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 97, in __init__, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060612 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] mod = importlib.import_module(self.SETTINGS_MODULE), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060624 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060642 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] __import__(name), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060705 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] ImportError: Import by filename is not supported., referer: http://www.mywebsite
</code>```

答:
DJANGO_SETTINGS_MODULE should be a module, as the name implies, not a path.</p>

```<code>os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp_directory.settings'
</code>```

Title: APACHE-DJANGO-WSGI Deployment

Body:
I have a django app located at

/home/user/myapp

I'm trying to run the app with apache2 and WSGI. Currently, the apache2 configuration is at /etc/apache2/apache2.conf and has this directory relating to my webiste

    <VirtualHost website.com:80>
   ServerName website.com
   ServerAlias www.website.com
   ServerAdmin email@website.com

   DocumentRoot /home/user/myapp/static

   WSGIScriptAlias / /var/www/website-directory/django.wsgi
   <Directory /home/user/myapp/static>
  Order allow,deny
      Allow from all
   </Directory>

   Alias /robots.txt /var/www/webisite-directory/robots.txt
   Alias /favicon.ico /var/www/webisite-directory/favicon.ico
   Alias /images /home/user/myapp/images
   Alias /static /home/user/myapp/static

   ErrorLog /var/www/webisite-directory/error.log
   CustomLog /var/www/webisite-directory/access.log combined
</VirtualHost>

My django.wsgi is

import os
import sys

sys.path.append('/home/user/myapp')

os.environ['DJANGO_SETTINGS_MODULE'] = '/myapp_directory/settings'
sys.executable = '/usr/lib/python2.7/dist-packages'
import django.core.handlers.wsgi
application = django.core.handlers.wsgi.WSGIHandler()

Here is my error log

  user@ubuntu:/var/www/website-directory$ vim error.log
[Thu Mar 30 01:25:10.060478 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] self.load_middleware(), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060490 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 48, in load_middleware, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060509 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] if settings.MIDDLEWARE is None:, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060521 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 53, in __getattr__, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060558 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] self._setup(name), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060570 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 41, in _setup, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060585 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] self._wrapped = Settings(settings_module), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060597 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 97, in __init__, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060612 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] mod = importlib.import_module(self.SETTINGS_MODULE), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060624 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module, referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060642 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] __import__(name), referer: http://www.mywebsite
[Thu Mar 30 01:25:10.060705 2017] [wsgi:error] [pid 7235:tid 139856399259392] [client 98.16.70.181:51796] ImportError: Import by filename is not supported., referer: http://www.mywebsite

Body:
DJANGO_SETTINGS_MODULE should be a module, as the name implies, not a path.

os.environ['DJANGO_SETTINGS_MODULE'] = 'myapp_directory.settings'


问:
Are 'raise a,b,c,' and 'raise (a,b,c)' same in Python 2.7
Can somebody please explain if why or why not 'raise a,b,c,' and 'raise (a,b,c)' are same in Python 2.7.

I tried to find information on how Tuples are treated from here and here but I couldn't establish if I could use the above expressions in place of one another.

Here is some background.
I have a Python 2 code which is having a lot of following statements

```<code>raise e,v,t
</code>```

Python 3 gives error on this syntax.
Converting it to following gets away the Python 3 compiler error but I wanted to verify if intent remains same in both Python 2 as well as Python 3.

```<code>raise (e,v,t)
</code>```

答:
raise has never taken a tuple as a parameter. In Python 2, the syntax was such that it looked like a tuple, which is where your confusion is coming from. There was a drastic syntax change for Python 3, where the redundant exception class type was removed and the keyword from is used in place of a comma.

In Python 2:

```<code>raise a, b, c
</code>```

Becomes in Python 3:

```<code>raise b.with_traceback(c)
</code>```

Body:
Can somebody please explain if why or why not 'raise a,b,c,' and 'raise (a,b,c)' are same in Python 2.7.

I tried to find information on how Tuples are treated from here and here but I couldn't establish if I could use the above expressions in place of one another.

Here is some background.
I have a Python 2 code which is having a lot of following statements

raise e,v,t

Python 3 gives error on this syntax.
Converting it to following gets away the Python 3 compiler error but I wanted to verify if intent remains same in both Python 2 as well as Python 3.

raise (e,v,t)

Body:
raise has never taken a tuple as a parameter. In Python 2, the syntax was such that it looked like a tuple, which is where your confusion is coming from. There was a drastic syntax change for Python 3, where the redundant exception class type was removed and the keyword from is used in place of a comma.

In Python 2:

raise a, b, c

Becomes in Python 3:

raise b.with_traceback(c)


问:
What a "Comparable interface" specifically
Is "Comparable" a Single Abstract Method interface or an Abstarct interface in java ?(I am using it in a TreeSet and my class contains "compareTo" method)</p>

答:
The term "abstract interface" in Java is not commonly used, @John Dafoe. All interfaces are abstract, regardless of whether they have zero, one, or more abstract methods.

If you look at the Javadocs for Comparable, https://docs.oracle.com/javase/8/docs/api/java/lang/Comparable.html, how many abstract methods do you see documented there? If there's only one, then it's a "Single-Abstract-Method" or "SAM" interface. If more than one, then it's a "more-than-one-abstract-method" interface.


问:
Android Studio project files not showing up
I have a library project in Android Studio that has been working fine, but today I went to work on it and all of the files are missing except for a few git files. The folders/files are there when I look in the project's folder on my hard drive, they just aren't displaying in Android Studio. Here is a screenshot:

I tried reinstalling and updating Android Studio, but it didn't work. Any ideas as to what is going on here? How can I fix it?

答:
In my case i have a slash in the subproject
settings.gradle

As an example, this did not work:

include ":somedir/library"
```

<p>But changing it to this fixed it:</p>

<pre class="lang-groovy prettyprint-override"><code>include ":somedir-library"
project(":somedir-library").projectDir = new File(settingsDir, "somedir/library")
</code>```

Body:
In my case i have a slash in the subproject
settings.gradle

As an example, this did not work:

include ":somedir/library"

But changing it to this fixed it:

include ":somedir-library"
project(":somedir-library").projectDir = new File(settingsDir, "somedir/library")


问:
Create square thumbnails with Python + MagickWand
How can I create square thumbnails with Python and Wand? I'm trying to make square thumbnails from source images of any size. It's important that the thumbnail have the same aspect ratio as the original, cropping is ok, and it should fill the sapce of the thumbnail.</p>

答:
No cropping.

Fill the blank space with color (in this case: white).

Maintain aspect ratio

from math import ceil
from wand.image import Color

def square_image(img):
    width = float(img.width)
    height = float(img.height)
    if width == height:
        return img
    border_height = 0
    border_width = 0
    if width > height:
        crop_size = int(width)
        border_height = int(ceil((width - height)/2))
    else:
        crop_size = int(height)
        border_width = int(ceil((height - width)/2))
    img.border(color=Color('white'), height=border_height, width=border_width)
    img.crop(top=0, left=0, width=crop_size, height=crop_size)
    return img
```


问:
zlib.Gzip doesn't work in node.js
I'm trying to compress a html string in node.js (v4/v5/v6). It works fine with deflate but gzip just hangs. Anybody any ideas? </p>

```<code>var data="<html><head.....        "; //HTML document
zlib.deflate(data, function(err, buffer) {
    //WORKS :)
});

zlib.Gzip(data, function(err, buffer) {
    //HANGS :(
});
</code>```

答: You want to use zlib.gzip() (lowercase g).

Title: zlib.Gzip doesn't work in node.js

Body:
I'm trying to compress a html string in node.js (v4/v5/v6). It works fine with deflate but gzip just hangs. Anybody any ideas?

var data="<head.....        "; //HTML document
zlib.deflate(data, function(err, buffer) {
    //WORKS :)
});

zlib.Gzip(data, function(err, buffer) {
    //HANGS :(
});


问:
Writing into a text file line by line
I am writing a text into a file. I am getting a column from database and stored it in a string and writing it in a text file. That column contains c# code and it is writing like a single line with small squares for next line(space). I need to write it line by line. Here is my code.

```<code>using (var dest = File.AppendText(Path.Combine(_logFolderPath, "a.txt")))
{
    dest.WriteLine(line.TrimStart());
}
</code>```

Any suggestion?

答:
Does Notepad show small squares for new lines, but when you look at the file in Visual Studio it's OK? If so, my guess is that this will fix it:</p>

```<code>dest.WriteLine(line.TrimStart().Replace("\n", Environment.NewLine));
</code>```

Title: Writing into a text file line by line

Body:
I am writing a text into a file. I am getting a column from database and stored it in a string and writing it in a text file. That column contains c# code and it is writing like a single line with small squares for next line(space). I need to write it line by line. Here is my code.

using (var dest = File.AppendText(Path.Combine(_logFolderPath, "a.txt")))
{
    dest.WriteLine(line.TrimStart());
}

Any suggestion?

Body:
Does Notepad show small squares for new lines, but when you look at the file in Visual Studio it's OK? If so, my guess is that this will fix it:

dest.WriteLine(line.TrimStart().Replace("\n", Environment.NewLine));


问:
Where can I find the Angular 2 CDN or source code?
I've been trying to download the source code from angular 2, but I was unable to find it. I looked in their github repository, but couldn't identify the correct one. Can someone point me the one or a working CDN so I can download it?

Edit: I need to get the source without using Node.Js and NPM.

答:
Normally you would use angular.io to download the quick-start or CLI using NPM etc. Here is a copy of the CDN:

https://gist.github.com/johnpapa/dd9b8a06bf93f4b38a3e


问:
Comparing Strings with compareTo requiring Object as parameter
I made a class extending ArrayList called sortedWordList that holds and sorts Strings. I would like to implement a binary search to override the indexOf method.

I cannot use compareTo to compare my Strings. I understand that I am passing the type Object to compareTo, but I believe that has to be my parameter type in order to override ArrayList's indexOf method.

My binary search algorithm may be incorrect as I have not had a chance to debug it yet so you may ignore that.

```<code>@Override
public int indexOf(Object o) {

    int min = 0;
    int max = len - 1;
    while (true){
        int mid = (int)((min + max)/ 2);
        if (this.get(mid).compareTo(o) == 0){
            return(mid);
        }
        if (this.get(mid).compareTo(o) < 0){
            min = mid;
        }
        else if (this.get(mid).compareTo(o) > 0){
            max = mid;
        }

        if (max == mid) break;

    }

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

答:
If your this.get(i) returns a String, you might want to make you method signature be

```<code>public int indexOf(String o)
</code>```

and, instead of extending ArrayList, you might want to encapsulate it.

EDIT:

If you're forced to stick with that method signature, covert the Object to String with String.valueOf(o).

Body:
I made a class extending ArrayList called sortedWordList that holds and sorts Strings. I would like to implement a binary search to override the indexOf method.

I cannot use compareTo to compare my Strings. I understand that I am passing the type Object to compareTo, but I believe that has to be my parameter type in order to override ArrayList's indexOf method.

My binary search algorithm may be incorrect as I have not had a chance to debug it yet so you may ignore that.

@Override
public int indexOf(Object o) {

    int min = 0;
    int max = len - 1;
    while (true){
        int mid = (int)((min + max)/ 2);
        if (this.get(mid).compareTo(o) == 0){
            return(mid);
        }
        if (this.get(mid).compareTo(o) < 0){
            min = mid;
        }
        else if (this.get(mid).compareTo(o) > 0){
            max = mid;
        }

        if (max == mid) break;

    }

    return -1;
}

Body:
If your this.get(i) returns a String, you might want to make you method signature be

public int indexOf(String o)

and, instead of extending ArrayList, you might want to encapsulate it.

EDIT:

If you're forced to stick with that method signature, covert the Object to String with String.valueOf(o).


问:
Complete checkout for Rs.0 product in shopify android
I want to complete checkout in Shopify android.
I have applied 100% discount coupon code, checkout object is created but getting this error-

{"errors":{"checkout":{"payment_gateway":[{"code":"invalid","message":"is invalid","options":{}}]}}}

I have passed Empty Payment token.
What should i pass in Payment token field  ??
I am using this method-
  CancellableTask completeCheckout(PaymentToken paymentToken, String               checkoutToken, Callback callback);

答: Do you have a direct credit card gateway enabled on your shop (i.e. not an offsite payment gateway)? The Mobile Buy SDK is only compatible with direct payment gateways.</p>


问:
Regular expression for accent mark and other characters
I need to validate if in a string exist any letter with accent mark or the Spanish letter Ñ. I tried using regular expression but, I can't find a solution.

this is my code:

```<code>var videoname = document.getElementById('url').value;
var BLIDRegExpression = /[Á\É\Í\Ó\Ú\-\Ñ\ñ]+$/(]+$/;
var matchesCount = videoname.split(BLIDRegExpression).length - 1;
alert(matchesCount);
</code>```

The alert shows 0 result.

答:
```<code>var hasAccentChars = /^[a-z \u00E0-\u00FC]+$/i;
var str = "el niño";
console.log(hasAccentChars.test(str));
</code>```

Body:
I need to validate if in a string exist any letter with accent mark or the Spanish letter Ñ. I tried using regular expression but, I can't find a solution.

this is my code:

var videoname = document.getElementById('url').value;
var BLIDRegExpression = /[Á\É\Í\Ó\Ú\-\Ñ\ñ]+$/(]+$/;
var matchesCount = videoname.split(BLIDRegExpression).length - 1;
alert(matchesCount);

The alert shows 0 result.


问:
PYTHON and OANDA API
I am using the Spyder IDE to run and test my code. I am pretty much finished with the coding. However, when I run it, the following comes up:

```<code>/anaconda/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:843: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
{
    "code" : 1,
    "message" : "Invalid or malformed argument: accountId",
    "moreInfo" : "http:\/\/developer.oanda.com\/docs\/v1\/troubleshooting\/#errors"
}
</code>```

How do I fix this problem?

答:
Did you read the information provided in the link?

Making unverified HTTPS requests is strongly discouraged, however, if you understand the risks and wish to disable these warnings, you can use disable_warnings():

```<code>>>> import urllib3
>>> urllib3.disable_warnings()
</code>```

Alternatively you can capture the warnings with the standard logging module:

```<code>>>> logging.captureWarnings(True)
</code>```

Finally, you can suppress the warnings at the interpreter level by setting the PYTHONWARNINGS environment variable or by using the -W flag.

Title: PYTHON and OANDA API

Body:
I am using the Spyder IDE to run and test my code. I am pretty much finished with the coding. However, when I run it, the following comes up:

/anaconda/lib/python2.7/site-packages/requests/packages/urllib3/connectionpool.py:843: InsecureRequestWarning: Unverified HTTPS request is being made. Adding certificate verification is strongly advised. See: https://urllib3.readthedocs.io/en/latest/advanced-usage.html#ssl-warnings
  InsecureRequestWarning)
{
    "code" : 1,
    "message" : "Invalid or malformed argument: accountId",
    "moreInfo" : "http:\/\/developer.oanda.com\/docs\/v1\/troubleshooting\/#errors"
}

How do I fix this problem?

Body:
Did you read the information provided in the link?

Making unverified HTTPS requests is strongly discouraged, however, if you understand the risks and wish to disable these warnings, you can use disable_warnings():

>>> import urllib3
>>> urllib3.disable_warnings()

Alternatively you can capture the warnings with the standard logging module:

>>> logging.captureWarnings(True)

Finally, you can suppress the warnings at the interpreter level by setting the PYTHONWARNINGS environment variable or by using the -W flag.