问:
CMake does not find Visual C++ compiler
After installing Visual Studio 2015 and running CMake on a previous project, CMake errors stating that it could not find the C compiler.

```<code>The C compiler identification is unknown
The CXX compiler identification is unknown
CMake Error at CMakeLists.txt:4 (PROJECT):
  No CMAKE_C_COMPILER could be found.

CMake Error at CMakeLists.txt:4 (PROJECT):
  No CMAKE_CXX_COMPILER could be found.
</code>```

I went searching for cl.exe in the Visual Studio folder,C:\Program Files\Microsoft Visual Studio 14.0, and could not find it.

How do I set up CMake to work on Windows with Visual Studio 2015?

答:
In my case there was an environment variable set which was the reason for this error.
The problem was solved after deleting cxx_flags from the environment variables.</p>

Title: CMake does not find Visual C++ compiler

Body:
After installing Visual Studio 2015 and running CMake on a previous project, CMake errors stating that it could not find the C compiler.

The C compiler identification is unknown
The CXX compiler identification is unknown
CMake Error at CMakeLists.txt:4 (PROJECT):
  No CMAKE_C_COMPILER could be found.

CMake Error at CMakeLists.txt:4 (PROJECT):
  No CMAKE_CXX_COMPILER could be found.

I went searching for cl.exe in the Visual Studio folder,C:\Program Files\Microsoft Visual Studio 14.0, and could not find it.

How do I set up CMake to work on Windows with Visual Studio 2015?


来源: stackexchange

问:
Don't know how to add string to arraylist and make it stick
I'm new to java and I was trying to test what I've learned by creating a TestAddRemove program. Essentially it's supposed to make you choose one of two arrays and allows you to add a company name, remove a company name and read whether a company you're looking for is in one of the arrays.

My main problem is with the adding to the arrays part. Each time I add a company using the Add class it works, but then when I check the arrays again the arrays are empty.

Main Question: How do I add a companyName to an array in the main program and have it stick?

Here's my code:

```<code>public class TestAddRemove
{
    static Scanner sc = new Scanner(System.in);
    static ArrayList<String> fileOne = new ArrayList<String>();
    static ArrayList<String> fileTwo = new ArrayList<String>();
    :
    :  //Some other stuff
    :
    String tryAgain = "Y";
    String answer;
    String fileAnswer;

    System.out.println("Welcome to the company tester; this program tests whether the company"
            + "you input is a company we already received donations from or a company we have"
            + "spoken to already, but declined to donate.");

    while (tryAgain.equalsIgnoreCase("Y"))
    {
        System.out.println("Do you want to test, add or remove a company name? ");
        answer = sc.next();
        String companyName;

        if (answer.equalsIgnoreCase("add"))
        {
            System.out.println("Which file do you want to add to?");
            fileAnswer = sc.next();

            if (fileAnswer.equalsIgnoreCase("fileOne"))
            {
                Add file = new Add(fileOne);
                System.out.println("Enter the company name you want to add. ");
                companyName = sc.next();

                file.addCompany(companyName);
            }
            else
            {
                Add file = new Add(fileTwo);
                System.out.println("Enter the company name you want to add. ");
                companyName = sc.next();

                file.addCompany(companyName);
            }
</code>```

The rest of the code is for the remove and test methods which I think I could understand once I understand how to add the companyName.

Here's the Add Class:

```<code>public class Add
{
    Scanner sc = new Scanner(System.in);
    ArrayList<String> file;

    public Add(ArrayList<String> fileOne)
    {
        this.file = fileOne;
    }

    public void addCompany (String companyName)
    {

        file.add(companyName);
    }

    public ArrayList<String> getFile()
    {
        return file;
    }

}
</code>```

Any help on this would be awesome, thanks and cheers!

答:
Running a Java application spawns a new JVM container. Such a container has its own memory in which it stores state for your program. When an application terminates, the JVM shuts down and discards all existing state. When you run the program a second time it runs in a different JVM totally unaware of any previous runs.

Regarding your problem, to access the list of companies created in a previous run, you need to add some sort of a persistence layer to your application like a database or a file in which you're able to store the companies.

The simplest solution would be to store the list in a text file, where each line represents one company, before the application shuts down and then load the file again when the application starts.

ContentLicense: CC BY-SA 3.0

Body:
I'm new to java and I was trying to test what I've learned by creating a TestAddRemove program. Essentially it's supposed to make you choose one of two arrays and allows you to add a company name, remove a company name and read whether a company you're looking for is in one of the arrays.

My main problem is with the adding to the arrays part. Each time I add a company using the Add class it works, but then when I check the arrays again the arrays are empty.

Main Question: How do I add a companyName to an array in the main program and have it stick?

Here's my code:

public class TestAddRemove
{
    static Scanner sc = new Scanner(System.in);
    static ArrayList<String> fileOne = new ArrayList<String>();
    static ArrayList<String> fileTwo = new ArrayList<String>();
    :
    :  //Some other stuff
    :
    String tryAgain = "Y";
    String answer;
    String fileAnswer;

    System.out.println("Welcome to the company tester; this program tests whether the company"
            + "you input is a company we already received donations from or a company we have"
            + "spoken to already, but declined to donate.");

    while (tryAgain.equalsIgnoreCase("Y"))
    {
        System.out.println("Do you want to test, add or remove a company name? ");
        answer = sc.next();
        String companyName;

        if (answer.equalsIgnoreCase("add"))
        {
            System.out.println("Which file do you want to add to?");
            fileAnswer = sc.next();

            if (fileAnswer.equalsIgnoreCase("fileOne"))
            {
                Add file = new Add(fileOne);
                System.out.println("Enter the company name you want to add. ");
                companyName = sc.next();

                file.addCompany(companyName);
            }
            else
            {
                Add file = new Add(fileTwo);
                System.out.println("Enter the company name you want to add. ");
                companyName = sc.next();

                file.addCompany(companyName);
            }

The rest of the code is for the remove and test methods which I think I could understand once I understand how to add the companyName.

Here's the Add Class:

public class Add
{
    Scanner sc = new Scanner(System.in);
    ArrayList<String> file;

    public Add(ArrayList<String> fileOne)
    {
        this.file = fileOne;
    }

    public void addCompany (String companyName)
    {

        file.add(companyName);
    }

    public ArrayList<String> getFile()
    {
        return file;
    }

}

Any help on this would be awesome, thanks and cheers!


问:
Multiple rows with same foreign key causing foreign key constraint error
I have 2 tables, an Owners table with MemberID as the primary key, and a Tigers table with TigerID as primary key and MemberID as a foreign key to indicate who owns the tiger. Naturally, an owner can own multiple tigers.

I'm displaying the tigers in a DataGridView using a DataAdapter in a Windows Form (Visual Studio let's you drag and drop a table onto a windows form and auto generates the code for you).

When I run the form, I get an error:

System.Data.ConstraintException: 'Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.'

EDIT 2:

I tried removing data again to see if having unique foreign keys erases the issue. It doesn't. I apologise for earlier wrong information. I also checked and there is no foreign key MemberID in Tigers which is not a primary key in Owners

EDIT:

```<code>CREATE TABLE [dbo].[Members] (
[MemberID] INT           IDENTITY (1, 1) NOT NULL,
[FName]    VARCHAR (50)  NOT NULL,
[LName]    VARCHAR (50)  NOT NULL,
[Street]   VARCHAR (MAX) NOT NULL,
[HouseNbr] INT           NOT NULL,
[PostNbr]  INT           NOT NULL,
[City]     NCHAR (10)    NOT NULL,
PRIMARY KEY CLUSTERED ([MemberID] ASC)
);

CREATE TABLE [dbo].[Tigers] (
[TigerID]  INT          IDENTITY (1, 1) NOT NULL,
[Name]     VARCHAR (50) NOT NULL,
[Type]     VARCHAR (50) NOT NULL,
[Weight]   INT          NOT NULL,
[MemberID] INT          NOT NULL,
PRIMARY KEY CLUSTERED ([TigerID] ASC)
);
</code>```

EDIT 3
Code in the Tigers Form

```<code>        private void tigersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        this.Validate();
        this.tigersBindingSource.EndEdit();
        this.tableAdapterManager.UpdateAll(this.tRFDDataSet);

    }

    private void frmTigerList_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'tRFDDataSet.Tigers' table. You can move, or remove it, as needed.
        this.tigersTableAdapter.Fill(this.tRFDDataSet.Tigers);

    }
</code>```

EDIT 4:

I went to the definition of the Tiger DataGrid Fill and Found this code:

```<code> private TRFDDataSet tRFDDataSet;
    private System.Windows.Forms.BindingSource tigersBindingSource;
    private TRFDDataSetTableAdapters.TigersTableAdapter tigersTableAdapter;
    private TRFDDataSetTableAdapters.TableAdapterManager tableAdapterManager;
    private System.Windows.Forms.DataGridView tigersDataGridView;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;
</code>```

So I added before the tigersBindingSource

```<code>        private System.Windows.Forms.BindingSource membersBindingSource;
    private TRFDDataSetTableAdapters.MembersTableAdapter membersTableAdapter;
</code>```

But it still didn't work. The error persisted

EDIT FINAL:

Dragging and dropping the Owners table worked and setting the generated code in the Form Designer code BEFORE the Tiger table code is the solution. This is due to the correct reply's insight about the parent table needing to load first in the same instance. I only need to find a way to edit that such I can hide the Owners table from displaying in this form.

答:
Make sure you are filling the Owners table before the Tigers table. In the same DataSet

For this line to execute with the constraint enabled

```<code>this.tigersTableAdapter.Fill(this.tRFDDataSet.Tigers);
</code>```

You the this.tRFDDataSet.Owners table needs to have a row for every Owner with a MemberId in this.tRFDDataSet.Tigers.
Meaning that you will have to create/drop in an OwnersTableAdapter and call its Fill Method before filling Tigers

Body:
I have 2 tables, an Owners table with MemberID as the primary key, and a Tigers table with TigerID as primary key and MemberID as a foreign key to indicate who owns the tiger. Naturally, an owner can own multiple tigers.

I'm displaying the tigers in a DataGridView using a DataAdapter in a Windows Form (Visual Studio let's you drag and drop a table onto a windows form and auto generates the code for you).

When I run the form, I get an error:

System.Data.ConstraintException: 'Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints.'

EDIT 2:

I tried removing data again to see if having unique foreign keys erases the issue. It doesn't. I apologise for earlier wrong information. I also checked and there is no foreign key MemberID in Tigers which is not a primary key in Owners

EDIT:

CREATE TABLE [dbo].[Members] (
[MemberID] INT           IDENTITY (1, 1) NOT NULL,
[FName]    VARCHAR (50)  NOT NULL,
[LName]    VARCHAR (50)  NOT NULL,
[Street]   VARCHAR (MAX) NOT NULL,
[HouseNbr] INT           NOT NULL,
[PostNbr]  INT           NOT NULL,
[City]     NCHAR (10)    NOT NULL,
PRIMARY KEY CLUSTERED ([MemberID] ASC)
);

CREATE TABLE [dbo].[Tigers] (
[TigerID]  INT          IDENTITY (1, 1) NOT NULL,
[Name]     VARCHAR (50) NOT NULL,
[Type]     VARCHAR (50) NOT NULL,
[Weight]   INT          NOT NULL,
[MemberID] INT          NOT NULL,
PRIMARY KEY CLUSTERED ([TigerID] ASC)
);

EDIT 3
Code in the Tigers Form

        private void tigersBindingNavigatorSaveItem_Click(object sender, EventArgs e)
    {
        this.Validate();
        this.tigersBindingSource.EndEdit();
        this.tableAdapterManager.UpdateAll(this.tRFDDataSet);

    }

    private void frmTigerList_Load(object sender, EventArgs e)
    {
        // TODO: This line of code loads data into the 'tRFDDataSet.Tigers' table. You can move, or remove it, as needed.
        this.tigersTableAdapter.Fill(this.tRFDDataSet.Tigers);

    }

EDIT 4:

I went to the definition of the Tiger DataGrid Fill and Found this code:

 private TRFDDataSet tRFDDataSet;
    private System.Windows.Forms.BindingSource tigersBindingSource;
    private TRFDDataSetTableAdapters.TigersTableAdapter tigersTableAdapter;
    private TRFDDataSetTableAdapters.TableAdapterManager tableAdapterManager;
    private System.Windows.Forms.DataGridView tigersDataGridView;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn1;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn2;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn3;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn4;
    private System.Windows.Forms.DataGridViewTextBoxColumn dataGridViewTextBoxColumn5;

So I added before the tigersBindingSource

        private System.Windows.Forms.BindingSource membersBindingSource;
    private TRFDDataSetTableAdapters.MembersTableAdapter membersTableAdapter;

But it still didn't work. The error persisted

EDIT FINAL:

Dragging and dropping the Owners table worked and setting the generated code in the Form Designer code BEFORE the Tiger table code is the solution. This is due to the correct reply's insight about the parent table needing to load first in the same instance. I only need to find a way to edit that such I can hide the Owners table from displaying in this form.

Body:
Make sure you are filling the Owners table before the Tigers table. In the same DataSet

For this line to execute with the constraint enabled

this.tigersTableAdapter.Fill(this.tRFDDataSet.Tigers);

You the this.tRFDDataSet.Owners table needs to have a row for every Owner with a MemberId in this.tRFDDataSet.Tigers.
Meaning that you will have to create/drop in an OwnersTableAdapter and call its Fill Method before filling Tigers


问:
Speeding up the scala.js/sbt Edit-Compile-Run/Debug cycle
The Edit-Compile-Run cycle for my Play+Scala.JS application is painfully slow.  I'm wondering if you have tips for speeding it up.

For example, is there a way to avoid restarting the server every time the client (scala.js) code changes?  We don't need to close and re-open database connections and all just to serve a new javascript file!  @aholland makes partial progress on this at https://github.com/aholland/play-scalajs-workbench-example but his technique involves manually splitting the project into the server part and the client part and then (manually) merging them again.  Ugh!

@OlivierBanvillain's sample project at https://github.com/OlivierBlanvillain/full-stack-scala says it has "proper sbt configuration for development/deployment".  The build.sbt file does some interesting things with which files are watched for changes, etc.  But I don't see a difference in actual use:  the play server still restarts every time scala.js source is changed.  Perhaps I misunderstand his intent (the explanation is pretty sparse!).

I've also seen the sbt-revolver plugin (https://github.com/spray/sbt-revolver) -- in fact the above project uses it.  It advertises "dangerously fast development turnaround in Scala" but again, I don't understand what its advantage is.  It talks about starting/stopping the application in the background, but how is that different than normal sbt?

答: I rewrote my build.sbt file using the example from https://github.com/vmunier/play-with-scalajs-example, including the plugins.  That's helped a lot.</p>


问:
Encapsulating controller logic in rails
I have 2 controllers in rails with different authentications schemes,
but they do almost the same.

What is the best way in rails to encapsulate
the logic of a controller in another class or helper?

Sample:

```<code>def ControllerA < BasicAuthController
  def create
    blablacode
  end
end

def ControllerB < TokenAuthController
  def create
    blablacode
  end
end
</code>```

Whats the proper way to do this? create a model with the code?
Create a helper? other?

答:
The simplest thing is to make a module and then include it into the other controllers:

```<code>module ControllerMixin
  def create
    blablacode
  end
end
</code>```

The remaining question, though, is where to put this code such that it is works with Rails autoloader, since it needs to be loaded before the controllers. One way to do it would be to write the module to a file in the lib/ directory, then add that to the autoload paths (see auto-loading-lib-files-in-rails-4

Title: Encapsulating controller logic in rails

Body:
I have 2 controllers in rails with different authentications schemes,
but they do almost the same.

What is the best way in rails to encapsulate
the logic of a controller in another class or helper?

Sample:

def ControllerA < BasicAuthController
  def create
    blablacode
  end
end

def ControllerB < TokenAuthController
  def create
    blablacode
  end
end

Whats the proper way to do this? create a model with the code?
Create a helper? other?

Body:
The simplest thing is to make a module and then include it into the other controllers:

module ControllerMixin
  def create
    blablacode
  end
end

The remaining question, though, is where to put this code such that it is works with Rails autoloader, since it needs to be loaded before the controllers. One way to do it would be to write the module to a file in the lib/ directory, then add that to the autoload paths (see auto-loading-lib-files-in-rails-4


问:
IQKeyboardManager with CustomTextField (SkyFloatingLabelTextField) using Swift 3
I am using the SkyFloatingLabelTextField which is a custom UITextField. After Adding the IQKeyboardManager into my Podfile (pod install), it was expected that it will automatically handle the keyboard issue.

Any clue to integrate IQKeyboardManager with customTextfield?

答:
Solution For SWIFT 3.0+

In AppDelegate :

```<code> // Enable IQKeyboardManager for customization
        IQKeyboardManager.sharedManager().enable = true
</code>```

In UIViewController

```<code>class A : UIViewController

viewDidLoad() {
        customizeKeyboard()
    }

func customizeKeyboard(){

    IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
    IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder = false
    IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = ""
    IQKeyboardManager.sharedManager().shouldHidePreviousNext = true
    IQKeyboardManager.sharedManager().keyboardDistanceFromTextField = 150

    emailTextField.delegate = self
    passwordTextField.delegate = self

    // to remove the autocorrect on top of keyboard
    emailTextField.autocorrectionType = .no
    emailTextField.keyboardType = .emailAddress

    // to remove the IQManager view on top of Keyboard
    let emptyUIView = UIView()
    emailTextField.inputAccessoryView = emptyUIView
    passwordTextField.inputAccessoryView = emptyUIView
    forgotEmailTextField.inputAccessoryView = emptyUIView
    }
}
</code>```

Body:
Solution For SWIFT 3.0+

In AppDelegate :

 // Enable IQKeyboardManager for customization
        IQKeyboardManager.sharedManager().enable = true

In UIViewController

class A : UIViewController

viewDidLoad() {
        customizeKeyboard()
    }

func customizeKeyboard(){

    IQKeyboardManager.sharedManager().shouldResignOnTouchOutside = true
    IQKeyboardManager.sharedManager().shouldShowTextFieldPlaceholder = false
    IQKeyboardManager.sharedManager().toolbarDoneBarButtonItemText = ""
    IQKeyboardManager.sharedManager().shouldHidePreviousNext = true
    IQKeyboardManager.sharedManager().keyboardDistanceFromTextField = 150

    emailTextField.delegate = self
    passwordTextField.delegate = self

    // to remove the autocorrect on top of keyboard
    emailTextField.autocorrectionType = .no
    emailTextField.keyboardType = .emailAddress

    // to remove the IQManager view on top of Keyboard
    let emptyUIView = UIView()
    emailTextField.inputAccessoryView = emptyUIView
    passwordTextField.inputAccessoryView = emptyUIView
    forgotEmailTextField.inputAccessoryView = emptyUIView
    }
}


问:
Error thrown while using Gmail API
I have a python script which sends an email via the Gmail api.  When running the script manually, all works fine.  However, when the script is run via a cronjob, the script fails with the following error:

/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access /root/.credentials/sendEmail.json: No such file or directory
        warnings.warn(_MISSING_FILE_MESSAGE.format(filename))

I've the client_secret.json file in the same folder as the python script.  Any suggestions would be much appreciated.

UPDATE

Update on this.  I add the call to the python file in root's crontab.  This has generated 2 new errors:

```<code>Failed to start a local webserver listening on either port 8080
or port 8090. Please check your firewall settings and locally
running programs that may be blocking or using those ports.

Falling back to --noauth_local_webserver and continuing with
authorization.

Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.compose&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&client_id=611764062141-gccaftd5eh9ekk11nv4007uh7t2qlr09.apps.googleusercontent.com&access_type=offline

Enter verification code: Traceback (most recent call last):
  File "/home/pi/python_scripts/glasses_scrape/glasses.py", line 174, in <module>
    credentials = get_credentials()
  File "/home/pi/python_scripts/glasses_scrape/glasses.py", line 165, in get_credentials
    credentials = tools.run_flow(flow, store, flags)
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/tools.py", line 240, in run_flow
    code = input('Enter verification code: ').strip()
EOFError: EOF when reading a line
</code>```

What's interesting here is the URL to click through to authorise my application to use gmail, now displays a code and I'm asked to switch to my application and enter it in there.

答: I resolved the issue by adding the call to the python file in root's crontab.  Gmail prompts me to approve my applications use of gmail and then the script works as expected.</p>

Title: Error thrown while using Gmail API

Body:
I have a python script which sends an email via the Gmail api.  When running the script manually, all works fine.  However, when the script is run via a cronjob, the script fails with the following error:

/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py:255: UserWarning: Cannot access /root/.credentials/sendEmail.json: No such file or directory
        warnings.warn(_MISSING_FILE_MESSAGE.format(filename))

I've the client_secret.json file in the same folder as the python script.  Any suggestions would be much appreciated.

UPDATE

Update on this.  I add the call to the python file in root's crontab.  This has generated 2 new errors:

Failed to start a local webserver listening on either port 8080
or port 8090. Please check your firewall settings and locally
running programs that may be blocking or using those ports.

Falling back to --noauth_local_webserver and continuing with
authorization.

Go to the following link in your browser:

    https://accounts.google.com/o/oauth2/auth?scope=https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fgmail.compose&redirect_uri=urn%3Aietf%3Awg%3Aoauth%3A2.0%3Aoob&response_type=code&client_id=611764062141-gccaftd5eh9ekk11nv4007uh7t2qlr09.apps.googleusercontent.com&access_type=offline

Enter verification code: Traceback (most recent call last):
  File "/home/pi/python_scripts/glasses_scrape/glasses.py", line 174, in <module>
    credentials = get_credentials()
  File "/home/pi/python_scripts/glasses_scrape/glasses.py", line 165, in get_credentials
    credentials = tools.run_flow(flow, store, flags)
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/_helpers.py", line 133, in positional_wrapper
    return wrapped(*args, **kwargs)
  File "/usr/local/lib/python2.7/dist-packages/oauth2client/tools.py", line 240, in run_flow
    code = input('Enter verification code: ').strip()
EOFError: EOF when reading a line

What's interesting here is the URL to click through to authorise my application to use gmail, now displays a code and I'm asked to switch to my application and enter it in there.


问:
Hibernate disconnect proxy when fetch=FetchType.LAZY
```<code>@Entity
public class Master implements Serializable{
private List slaves;
@OneToMany(mappedBy = "Master",fetch=FetchType.LAZY)
public List getSlaves() {
   return slaves;
}
}

I want this code to pass.

List m = createQuery("from Master where id=1").getResultList();
for (Master master : m) {
    assertNull(master.getSlaves());
}
</code>```

I want getSlaves() to return null and not to initialize a proxy to connect to the database(this master has slaves and I dont want to delete them from database).

Is there any way to do that in Hibernate or JPA?

Is there also way of doing that when fetch is EAGER?

答:
If I understand you correctly, you want a master that actually HAS slaves to return a null value for the list of slaves anyhow? Is this in a test context? Are you sure that this is what you want, and that you are on the right track?

Another ugly approach is to just set the list of slaves to null explicitly. This will ensure that getSlaves() returns null as long as you are in the same session, but nothing will actually be changed in the database (at least for hibernate). This approach works also for an eager collection.

ContentLicense: CC BY-SA 2.5

Body:
@Entity
public class Master implements Serializable{
private List slaves;
@OneToMany(mappedBy = "Master",fetch=FetchType.LAZY)
public List getSlaves() {
   return slaves;
}
}

I want this code to pass.

List m = createQuery("from Master where id=1").getResultList();
for (Master master : m) {
    assertNull(master.getSlaves());
}

I want getSlaves() to return null and not to initialize a proxy to connect to the database(this master has slaves and I dont want to delete them from database).

Is there any way to do that in Hibernate or JPA?

Is there also way of doing that when fetch is EAGER?


问:
Intercept sending request to change a header with request library
I am using the infamous request library to send requests.
One of those requests requires me to send the header multipart/mixed; boundary={myboundary}.

Request is using the form-data library for such requests but it does not set the Content-Type header properly. Therefore I would need to set it like this:

```<code>let req = request.post({url: "https://..."}, formData: formData)
req.setHeader('Content-Type', `multipart/mixed; boundary=${req.form().getBoundary()}`)
</code>```

Sadly I can't add/alter any headers after firing the request. Therefore I want to know whether there is a way to intercept the sending so I can change the header?

答:
You will need to use the multipart option instead of formData to use other, arbitrary multipart/* content types. Each object in the multipart array contains the headers to send in that part. The one exception is the body property which is used as the actual body of that part.

```<code>request.post({
  url: 'https://...',
  multipart: [
    { 'X-Foo-Header': 'bar', body: 'baz' },
    // ...
  ],
  headers: { 'Content-Type': 'multipart/mixed' }
});
</code>```

The boundary should be automatically appended for an existing, explicit Content-Type header. This request test explicitly tests for this behavior.

Body:
I am using the infamous request library to send requests.
One of those requests requires me to send the header multipart/mixed; boundary={myboundary}.

Request is using the form-data library for such requests but it does not set the Content-Type header properly. Therefore I would need to set it like this:

let req = request.post({url: "https://..."}, formData: formData)
req.setHeader('Content-Type', `multipart/mixed; boundary=${req.form().getBoundary()}`)

Sadly I can't add/alter any headers after firing the request. Therefore I want to know whether there is a way to intercept the sending so I can change the header?

Body:
You will need to use the multipart option instead of formData to use other, arbitrary multipart/* content types. Each object in the multipart array contains the headers to send in that part. The one exception is the body property which is used as the actual body of that part.

request.post({
  url: 'https://...',
  multipart: [
    { 'X-Foo-Header': 'bar', body: 'baz' },
    // ...
  ],
  headers: { 'Content-Type': 'multipart/mixed' }
});

The boundary should be automatically appended for an existing, explicit Content-Type header. This request test explicitly tests for this behavior.


问:
Stackoverflow due to large return type of a function
this my code:

```<code>#include <iostream>
#include <array>

using namespace std;

array< array<int, 1000>, 1000 > largeThing;

array< array<int, 1000>, 1000 > functionFoo() {
    return largeThing;
}

void main(){
    functionFoo();
    return;
}
</code>```

If i run this i get a Stackoverflow error. I've got so far that the reason for this is the large return type of functionFoo(), because the return value is actually on the Heap.

Question:

How to use a function with a large return type so that all the memory that the function will put on the stack will be put on the heap instead?

Edit:

I just increased the stacksize, it worked fine.

答:
std::array is allocated on the stack, which depending on your build settings can be relatively small (a typical size is 1 MiB).

If you need something bigger you may explicitly allocate that array on the heap and return a pointer. The std::unique_ptr in this example is a smart pointer that takes care of deallocation when the pointer goes out of scope, so we don't have to remember calling delete.

```<code>using bigarray = std::array< std::array<int, 1000>, 1000 >;

std::unique_ptr< bigarray > functionFoo() {
   return std::make_unique< bigarray >();
}
</code>```

Another way would be to use a different class that already manages memory on the heap, for instance std::vector:

```<code>std::vector< std::vector<int> > functionFoo() {
    std::vector< std::vector<int> > largeThing( 1000, std::vector<int>( 1000 ) );
    return largeThing;
}
</code>```

Body:
this my code:

#include <iostream>
#include <array>

using namespace std;

array< array<int, 1000>, 1000 > largeThing;

array< array<int, 1000>, 1000 > functionFoo() {
    return largeThing;
}

void main(){
    functionFoo();
    return;
}

If i run this i get a Stackoverflow error. I've got so far that the reason for this is the large return type of functionFoo(), because the return value is actually on the Heap.

Question:

How to use a function with a large return type so that all the memory that the function will put on the stack will be put on the heap instead?

Edit:

I just increased the stacksize, it worked fine.

Body:
std::array is allocated on the stack, which depending on your build settings can be relatively small (a typical size is 1 MiB).

If you need something bigger you may explicitly allocate that array on the heap and return a pointer. The std::unique_ptr in this example is a smart pointer that takes care of deallocation when the pointer goes out of scope, so we don't have to remember calling delete.

using bigarray = std::array< std::array<int, 1000>, 1000 >;

std::unique_ptr< bigarray > functionFoo() {
   return std::make_unique< bigarray >();
}

Another way would be to use a different class that already manages memory on the heap, for instance std::vector:

std::vector< std::vector<int> > functionFoo() {
    std::vector< std::vector<int> > largeThing( 1000, std::vector<int>( 1000 ) );
    return largeThing;
}


问:
Accessing host different ports in production
I'm making an app with Vue.js as frontend and Rails as backend, everything running with docker on development and production.

in development, I can access the services with localhost:8080 (front end) and make request to the backend URL with localhost:5678 (rails port).

but when I deploy this to production, which has a domain name(www.websiteurl.com), I can view the front end but can't access the backend, I am unable to make any request.

I try to make requests to www.websiteurl.com:5678 and nothing happens, how can I access the backend port with a domain name?

ps1: I'm sorry if the question is not clear enough, feel free to ask anything
ps2: I have correctly set up CORS access on the backend
ps3: if I access the production server via IP, it works correctly, the problem is when I access via the domain name

Update:
Command used to run front-end:

```<code>docker build -t runaterra:ekko .
docker run -d \
    -w /runaterra-ekko/ \
    -p 80:8080 \
    --name ekko \
    --restart unless-stopped \
    runaterra:ekko npm run dev
</code>```

Command used to run backend:

```<code>docker-compose up -d --restart unless-stopped db
docker-compose build app
docker-compose run --rm app rake db:migrate
docker-compose up -d --restart unless-stopped app
</code>```

答: You didn't expose port 5678 of your app to the internet. </p>

ContentLicense: CC BY-SA 4.0

Body:
I'm making an app with Vue.js as frontend and Rails as backend, everything running with docker on development and production.

in development, I can access the services with localhost:8080 (front end) and make request to the backend URL with localhost:5678 (rails port).

but when I deploy this to production, which has a domain name(www.websiteurl.com), I can view the front end but can't access the backend, I am unable to make any request.

I try to make requests to www.websiteurl.com:5678 and nothing happens, how can I access the backend port with a domain name?

ps1: I'm sorry if the question is not clear enough, feel free to ask anything
ps2: I have correctly set up CORS access on the backend
ps3: if I access the production server via IP, it works correctly, the problem is when I access via the domain name

Update:
Command used to run front-end:

docker build -t runaterra:ekko .
docker run -d \
    -w /runaterra-ekko/ \
    -p 80:8080 \
    --name ekko \
    --restart unless-stopped \
    runaterra:ekko npm run dev

Command used to run backend:

docker-compose up -d --restart unless-stopped db
docker-compose build app
docker-compose run --rm app rake db:migrate
docker-compose up -d --restart unless-stopped app


问:
Bypassing SSL Certificate Validation on DotNet Core Service Stack
I know that ServicePointManager.ServerCertificateValidationCallback no longer exists in .Net Core and is instead replaced with:

```<code>using(var handler = new System.Net.Http.HttpClientHandler())
{
    using (var httpClient = new System.Net.Http.HttpClient(handler))
    {
        handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
        {
            return true;
        };

    }
}
</code>```

However we are currently using the ServiceStack.Core library which, as far as I can see, does not expose either a property like this or the handler itself.

How would I tell a ServiceStack client to bypass ssl validation in this code?

```<code>using(var client = new JsonServiceClient("https://www.google.com"))
{
    var response = client.Get("/results");
}
</code>```

If there is a way, would this work the same on both Windows and Linux?

答:
JsonServiceClient is built on .NET HttpWebRequest which has been rewritten in .NET Core as a wrapper over HttpClient so we'd generally recommend for .NET Core to avoid this overhead (which is much slower than .NET 4.5) and switch to using JsonHttpClient in ServiceStack.HttpClient instead as it uses HttpClient directly and where you can inject your own HttpClientHandler with:

```<code>var client = new JsonHttpClient(baseUrl)
{
    HttpMessageHandler = new HttpClientHandler
    {
        UseCookies = true,
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
        ServerCertificateCustomValidationCallback = (req,cert,chain,errors) => true
    }
};
</code>```

Note it's recommended to reuse HttpClient instances so you should try to reuse HttpClient instances when possible and avoid disposing them.

Body:
I know that ServicePointManager.ServerCertificateValidationCallback no longer exists in .Net Core and is instead replaced with:

using(var handler = new System.Net.Http.HttpClientHandler())
{
    using (var httpClient = new System.Net.Http.HttpClient(handler))
    {
        handler.ServerCertificateCustomValidationCallback = (request, cert, chain, errors) =>
        {
            return true;
        };

    }
}

However we are currently using the ServiceStack.Core library which, as far as I can see, does not expose either a property like this or the handler itself.

How would I tell a ServiceStack client to bypass ssl validation in this code?

using(var client = new JsonServiceClient("https://www.google.com"))
{
    var response = client.Get("/results");
}

If there is a way, would this work the same on both Windows and Linux?

Body:
JsonServiceClient is built on .NET HttpWebRequest which has been rewritten in .NET Core as a wrapper over HttpClient so we'd generally recommend for .NET Core to avoid this overhead (which is much slower than .NET 4.5) and switch to using JsonHttpClient in ServiceStack.HttpClient instead as it uses HttpClient directly and where you can inject your own HttpClientHandler with:

var client = new JsonHttpClient(baseUrl)
{
    HttpMessageHandler = new HttpClientHandler
    {
        UseCookies = true,
        AutomaticDecompression = DecompressionMethods.GZip | DecompressionMethods.Deflate,
        ServerCertificateCustomValidationCallback = (req,cert,chain,errors) => true
    }
};

Note it's recommended to reuse HttpClient instances so you should try to reuse HttpClient instances when possible and avoid disposing them.


问:
Using PHP variable in SQL query
I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)

```<code><?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";

$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
   echo $row['value'];
}
?>
</code>```

I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.

Thank you in advance.

Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:

```<code><?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";

$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
   echo $row['value'];
}
?>
</code>```

I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.

Thanks again.

答:
Yes mysql_real_escape_string() is deprecated.

One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.

To continue using the mysqli_* functions, use:

mysqli_prepare() to get a prepared statement

mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')

mysqli_stmt_execute() to execute the statement

mysqli_stmt_bind_result() to send the output to a variable.

```<code><?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";

$statement = mysqli_prepare($conn, $query);

//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);

//execute the statement
mysqli_stmt_execute($statement);

//bind an output variable
mysqli_stmt_bind_result($stmt, $value);

while ( mysqli_stmt_fetch($stmt)) {
    echo $value; //print the value from each returned row
}
</code>```

If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.

Title: Using PHP variable in SQL query

Body:
I'm having some trouble using a variable declared in PHP with an SQL query. I have used the resources at How to include a PHP variable inside a MySQL insert statement but have had no luck with them. I realize this is prone to SQL injection and if someone wants to show me how to protect against that, I will gladly implement that. (I think by using mysql_real_escape_string but that may be deprecated?)

<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'hospital_name' AND value = '$q'";

$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
   echo $row['value'];
}
?>

I have tried switching '$q' with $q and that doesn't work. If I substitute the hospital name directly into the query, the SQL query and PHP output code works so I know that's not the problem unless for some reason it uses different logic with a variable when connecting to the database and executing the query.

Thank you in advance.

Edit: I'll go ahead and post more of my actual code instead of just the problem areas since unfortunately none of the answers provided have worked. I am trying to print out a "Case ID" that is the primary key tied to a patient. I am using a REDCap clinical database and their table structure is a little different than normal relational databases. My code is as follows:

<?php
$q = 'Hospital_Name';
$query = "SELECT * FROM database.table WHERE field_name = 'case_id' AND record in (SELECT distinct record FROM database.table WHERE field_name = 'hospital_name' AND value = '$q')";

$query_result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_assoc($query_result)) {
   echo $row['value'];
}
?>

I have tried substituting $q with '$q' and '".$q."' and none of those print out the case_id that I need. I also tried using the mysqli_stmt_* functions but they printed nothing but blank as well. Our server uses PHP version 5.3.3 if that is helpful.

Thanks again.

Body:
Yes mysql_real_escape_string() is deprecated.

One solution, as hinted by answers like this one in that post you included a link to, is to use prepared statements. MySQLi and PDO both support binding parameters with prepared statements.

To continue using the mysqli_* functions, use:

mysqli_prepare() to get a prepared statement

mysqli_stmt_bind_param() to bind the parameter (e.g. for the WHERE condition value='$q')

mysqli_stmt_execute() to execute the statement

mysqli_stmt_bind_result() to send the output to a variable.

<?php
$q = 'Hospital_Name';
$query = "SELECT value FROM database.table WHERE field_name = 'hospital_name' AND value = ?";

$statement = mysqli_prepare($conn, $query);

//Bind parameter for $q; substituted for first ? in $query
//first parameter: 's' -> string
mysqli_stmt_bind_param($statement, 's', $q);

//execute the statement
mysqli_stmt_execute($statement);

//bind an output variable
mysqli_stmt_bind_result($stmt, $value);

while ( mysqli_stmt_fetch($stmt)) {
    echo $value; //print the value from each returned row
}

If you consider using PDO, look at bindparam(). You will need to determine the parameters for the PDO constructor but then can use it to get prepared statements with the prepare() method.


问:
Is this program for binary to decimal is correct?
```<code>#include <stdio.h>
#include <math.h>

int main() {
    long long int bin;
    int dec=0,i;

    scanf("%lld", &bin);
    for(i=0; bin!=0; i++){
        if(bin%10==0 || bin%10==1){
            dec+=(bin%10)*pow(2,i);
            bin/=10;
        }
        else {
            printf("Invalid Binary number!!\n");
            return 0;
        }

    }
    printf("%d\n", dec);

    return 0;
}
</code>```

I make this program to convert binary to decimal.
There are many code in online but I want to know
Is everything ok with this code?

答:
It would be better to read character by character and convert directly to a machine number. That more clearly expresses your intent.

```<code>#include <stdio.h>
#include <limits.h>

int main(void)
{
    unsigned long long n = 0;
    int c;
    fputs("enter a number in base 2: ", stdout);
    while ((c = getchar()) != EOF && c != '\n') {
        if (n >= (ULLONG_MAX >> 1) + 1) {
            fprintf(stderr, "binary number is too large\n");
            return 1;
        }
        n <<= 1;
        if (c == '0')
            n += 0;
        else if (c == '1')
            n += 1;
        else {
            fprintf(stderr, "bad binary digit '%c'\n", c);
            return 1;
        }
    }
    printf("that number in base 10 is %llu\n", n);
    return 0;
}
</code>```

Completely untested.  Negative numbers left as an exercise (caution: shifting into the sign bit of a signed integer provokes undefined behavior).

Body:
#include <stdio.h>
#include <math.h>

int main() {
    long long int bin;
    int dec=0,i;

    scanf("%lld", &bin);
    for(i=0; bin!=0; i++){
        if(bin%10==0 || bin%10==1){
            dec+=(bin%10)*pow(2,i);
            bin/=10;
        }
        else {
            printf("Invalid Binary number!!\n");
            return 0;
        }

    }
    printf("%d\n", dec);

    return 0;
}

I make this program to convert binary to decimal.
There are many code in online but I want to know
Is everything ok with this code?

Body:
It would be better to read character by character and convert directly to a machine number. That more clearly expresses your intent.

#include <stdio.h>
#include <limits.h>

int main(void)
{
    unsigned long long n = 0;
    int c;
    fputs("enter a number in base 2: ", stdout);
    while ((c = getchar()) != EOF && c != '\n') {
        if (n >= (ULLONG_MAX >> 1) + 1) {
            fprintf(stderr, "binary number is too large\n");
            return 1;
        }
        n <<= 1;
        if (c == '0')
            n += 0;
        else if (c == '1')
            n += 1;
        else {
            fprintf(stderr, "bad binary digit '%c'\n", c);
            return 1;
        }
    }
    printf("that number in base 10 is %llu\n", n);
    return 0;
}

Completely untested.  Negative numbers left as an exercise (caution: shifting into the sign bit of a signed integer provokes undefined behavior).


问:
Varargs not working in 64bit with managed objects?
I'm trying to migrate some managed c++ code to 64bits.
I have a function that gets varargs, and when I pass a System::String variable to it, it appears not to pass correctly.
Here is a simplification of the code that shows the problem:

```<code>    #include <stdio.h>
    #include <stdarg.h>
    void test(char* formatPtr, ...)
    {
        va_list args;
        int bufSize;
        char buffer[2600];

        /////////////////////////////////////
        //parse arguments from function stack
        /////////////////////////////////////
        va_start(args, formatPtr);

        bufSize = vsprintf(buffer, (const char*) formatPtr, args);
        printf(buffer);

        va_end(args);
    }

    void main() {
        System::String^ s;
        s = "Shahar";
        test("Hello %s", s);
        getchar();
    }
</code>```

When this code runs in 32 bits, it displays Hello Shahar.

When it runs in 64 bits, it displays Hello Çz∟⌠■.

Assuming I want to make the least amount of changes to the code, how should I fix this?

答:
The %s specifier expects a C-style null-terminated string, not a System::String^. C++/CLI headers provide some methods that can convert System::String^ to std::string, which can be converted to a C-string, and can probably just convert straight to a C-string.

You have other problems too. void main()? Assigning a literal to a char*? Fixed-size buffer?

Body:
I'm trying to migrate some managed c++ code to 64bits.
I have a function that gets varargs, and when I pass a System::String variable to it, it appears not to pass correctly.
Here is a simplification of the code that shows the problem:

    #include <stdio.h>
    #include <stdarg.h>
    void test(char* formatPtr, ...)
    {
        va_list args;
        int bufSize;
        char buffer[2600];

        /////////////////////////////////////
        //parse arguments from function stack
        /////////////////////////////////////
        va_start(args, formatPtr);

        bufSize = vsprintf(buffer, (const char*) formatPtr, args);
        printf(buffer);

        va_end(args);
    }

    void main() {
        System::String^ s;
        s = "Shahar";
        test("Hello %s", s);
        getchar();
    }

When this code runs in 32 bits, it displays Hello Shahar.

When it runs in 64 bits, it displays Hello Çz∟⌠■.

Assuming I want to make the least amount of changes to the code, how should I fix this?


问:
Bad Data exception during RSA decryption
I was working on a project. Encryption is working fine but when it comes to decryption my program is throwing "Bad data Exception". How do I remedy this problem?</p>

```<code>using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace WindowsFormsApplication2
{

    public partial class Form1 : Form
    {
        byte[] cipher;
        byte[] plain;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private static string Encrypt(byte[] plain)
        {
            byte[] encrypted;
          RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new StreamReader("D:\\PjesaVetemPublike.xml");
                string VetemPublikeXML = StRe.ReadToEnd();
                rsa.FromXmlString(VetemPublikeXML);
                StRe.Close();
                encrypted = rsa.Encrypt(plain, true);

            return Encoding.UTF8.GetString(encrypted);
        }

        private static string Decrypt(byte[] encrypted)
        {
            byte[] decrypted;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new
         StreamReader("D:\\PjesaPublikeDhePrivate.xml");
                string PublikeDhePrivate = StRe.ReadToEnd();
                rsa.FromXmlString(PublikeDhePrivate);
                StRe.Close();

                decrypted = rsa.Decrypt(encrypted, false);   //THE ERROR APPEARS RIGHT HERE

            return Encoding.UTF8.GetString(decrypted);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            plain = Encoding.UTF8.GetBytes(txtPlain.Text);
            txtCipher.Text = Encrypt(plain);

        }

        private void button2_Click(object sender, EventArgs e)
        {

            txtDekriptuar.Text = Decrypt(cipher);
        }
    }
}
</code>```

答:
Assuming your key pair is correct, the issue is that you're using different padding schemes for encryption and decryption.

The second argument that is passed to RSACryptoServiceProvider#Encrypt and RSACryptoServiceProvider#Decrypt denotes whether OAEP is used. During encryption you're requesting OAEP, but during decryption you're requesting PKCS#1 v1.5 padding. Those are not compatible. Just use OAEP which is more secure.

You should use

```<code>decrypted = rsa.Decrypt(encrypted, true);
</code>```

Body:
I was working on a project. Encryption is working fine but when it comes to decryption my program is throwing "Bad data Exception". How do I remedy this problem?

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Text;
using System.IO;
using System.Security.Cryptography;

namespace WindowsFormsApplication2
{

    public partial class Form1 : Form
    {
        byte[] cipher;
        byte[] plain;

        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {

        }

        private static string Encrypt(byte[] plain)
        {
            byte[] encrypted;
          RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new StreamReader("D:\\PjesaVetemPublike.xml");
                string VetemPublikeXML = StRe.ReadToEnd();
                rsa.FromXmlString(VetemPublikeXML);
                StRe.Close();
                encrypted = rsa.Encrypt(plain, true);

            return Encoding.UTF8.GetString(encrypted);
        }

        private static string Decrypt(byte[] encrypted)
        {
            byte[] decrypted;
            RSACryptoServiceProvider rsa = new RSACryptoServiceProvider();

                StreamReader StRe = new
         StreamReader("D:\\PjesaPublikeDhePrivate.xml");
                string PublikeDhePrivate = StRe.ReadToEnd();
                rsa.FromXmlString(PublikeDhePrivate);
                StRe.Close();

                decrypted = rsa.Decrypt(encrypted, false);   //THE ERROR APPEARS RIGHT HERE

            return Encoding.UTF8.GetString(decrypted);
        }

        private void button1_Click(object sender, EventArgs e)
        {
            plain = Encoding.UTF8.GetBytes(txtPlain.Text);
            txtCipher.Text = Encrypt(plain);

        }

        private void button2_Click(object sender, EventArgs e)
        {

            txtDekriptuar.Text = Decrypt(cipher);
        }
    }
}

Body:
Assuming your key pair is correct, the issue is that you're using different padding schemes for encryption and decryption.

The second argument that is passed to RSACryptoServiceProvider#Encrypt and RSACryptoServiceProvider#Decrypt denotes whether OAEP is used. During encryption you're requesting OAEP, but during decryption you're requesting PKCS#1 v1.5 padding. Those are not compatible. Just use OAEP which is more secure.

You should use

decrypted = rsa.Decrypt(encrypted, true);


问:
Caffe: what will happen if two layers backprop gradients to the same bottom blob?
I'm wondering what if I have a layer generating a bottom blob that is further consumed by two subsequent layers, both of which will generate some gradients to fill bottom.diff in the back propagation stage. Will both two gradients be added up to form the final gradient? Or, only one of them can live? In my understanding, Caffe layers need to memset the bottom.diff to all zeros before filling it with some computed gradients, right? Will the memset flush out the already computed gradients by the other layer? Thank you!</p>

答:
Using more than a single loss layer is not out-of-the-ordinary, see GoogLeNet for example: It has three loss layers "pushing" gradients at different depths of the net.

In caffe, each loss layer has a associated loss_weight: how this particular component contribute to the loss function of the net. Thus, if your net has two loss layers, Loss1 and Loss1 the overall loss of your net is

```<code>Loss = loss_weight1*Loss1 + loss_weight2*Loss2
</code>```

The backpropagation uses the chain rule to propagate the gradient of Loss (the overall loss) through all the layers in the net. The chain rule breaks down the derivation of Loss into partial derivatives, i.e., the derivatives of each layer, the overall effect is obtained by propagating the gradients through the partial derivatives. That is, by using top.diff and the layer's backward() function to compute bottom.diff one takes into account not only the layer's derivative, but also the effect of ALL higher layers expressed in top.diff.

TL;DR

You can have multiple loss layers. Caffe (as well as any other decent deep learning framework) handles it seamlessly for you.

Body:
Using more than a single loss layer is not out-of-the-ordinary, see GoogLeNet for example: It has three loss layers "pushing" gradients at different depths of the net.

In caffe, each loss layer has a associated loss_weight: how this particular component contribute to the loss function of the net. Thus, if your net has two loss layers, Loss1 and Loss1 the overall loss of your net is

Loss = loss_weight1*Loss1 + loss_weight2*Loss2

The backpropagation uses the chain rule to propagate the gradient of Loss (the overall loss) through all the layers in the net. The chain rule breaks down the derivation of Loss into partial derivatives, i.e., the derivatives of each layer, the overall effect is obtained by propagating the gradients through the partial derivatives. That is, by using top.diff and the layer's backward() function to compute bottom.diff one takes into account not only the layer's derivative, but also the effect of ALL higher layers expressed in top.diff.

TL;DR

You can have multiple loss layers. Caffe (as well as any other decent deep learning framework) handles it seamlessly for you.


问:
Get size of request
I have an API written using the express framework. As part of the logging/scaling-tests process, I'd like to know how large a received request is in bytes (so we can determine the effect it's going to have on the network).

Is there a way of doing this? I've read through the Express Documentation and couldn't find anything. Will reading off the content-length header work? Or could that value be sent incorrectly?

答: I have most commonly seen code using the content-length header, for example with req.get("content-length"). However I recently ran into a situation where that header wasn't provided, so I switched to using req.socket.bytesRead.

Title: Get size of request


问:
Not able to get contents of JSON / Array in PHP
new to php.... can't seem to get the contents of this array... ie. trying to do: $key = var0  and  $value = string0

This is what I am trying the following, with no success:

```<code>$getJSON = [
    {
        "item0": [
            {"var0":"string0"},
            {"var1":"string1"},
            {"var2":"string2"},
            {"var3":"string3"}
        ]
    }
]

$arr = json_decode( $getJSON, true );

$test1 = $arr[0]['item0']['var0'];
$test2 = $arr['item0']['var0'];
</code>```

答:
The argument to json_decode() has to be a string, not an array. So put it in quotes.

```<code>$getJSON = '[
    {
        "item0": [
            {"var0":"string0"},
            {"var1":"string1"},
            {"var2":"string2"},
            {"var3":"string3"}
        ]
    }
]';
</code>```

After you decode, $arr[0]['item0'] contains an array, so to get the var0 element it would be $arr[0]['item0'][0]['var0'].

Having an array of separate objects, each with different keys, is probably not a great design. It would be better if the you did it like this:

```<code>$getJSON = '{
    "item0": {
        "var0":"string0",
        "var1":"string1",
        "var2":"string2",
        "var3":"string3"
    }
}'
</code>```

Then the value you want would be:

```<code>$arr['item0']['var0']
</code>```

Body:
new to php.... can't seem to get the contents of this array... ie. trying to do: $key = var0  and  $value = string0

This is what I am trying the following, with no success:

$getJSON = [
    {
        "item0": [
            {"var0":"string0"},
            {"var1":"string1"},
            {"var2":"string2"},
            {"var3":"string3"}
        ]
    }
]

$arr = json_decode( $getJSON, true );

$test1 = $arr[0]['item0']['var0'];
$test2 = $arr['item0']['var0'];

Body:
The argument to json_decode() has to be a string, not an array. So put it in quotes.

$getJSON = '[
    {
        "item0": [
            {"var0":"string0"},
            {"var1":"string1"},
            {"var2":"string2"},
            {"var3":"string3"}
        ]
    }
]';

After you decode, $arr[0]['item0'] contains an array, so to get the var0 element it would be $arr[0]['item0'][0]['var0'].

Having an array of separate objects, each with different keys, is probably not a great design. It would be better if the you did it like this:

$getJSON = '{
    "item0": {
        "var0":"string0",
        "var1":"string1",
        "var2":"string2",
        "var3":"string3"
    }
}'

Then the value you want would be:

$arr['item0']['var0']


问:
How do I insert a space between an alpha character and a numeric character?
This is a continuation of my original question:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?

I was able to achieve a desired result of inserting spaces between caps with only letters in the string:

```<code>my $camel ="SomeCamel IsEnteringText";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Prints:

Some Camel Is Entering Text

But, when numbers are present, I ran into issues:

```<code>my $camel ="Some 440Camel220 IsEntering100Text Nogo";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;
</code>```

Prints:

Some 440Camel220 Is Entering100Text Nogo

Desired:

Some 440 Camel 220 Is Entering 100 Text Nogo

So, how do I now insert a space between the letters and the numbers?.

答:
Add the following two substitutions:

```<code>$camel =~ s/(?<=[0-9])(?=[a-z])/ /ig;
$camel =~ s/(?<=[a-z])(?=[0-9])/ /ig;
</code>```

The first inserts a space at any transition between a digit and a letter. The i modifier at the end makes the expression case-insensitive. The second does the opposite.

Body:
This is a continuation of my original question:
Perl- How do I insert a space before each capital letter except for the first occurrence or existing?

I was able to achieve a desired result of inserting spaces between caps with only letters in the string:

my $camel ="SomeCamel IsEnteringText";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;

Prints:

Some Camel Is Entering Text

But, when numbers are present, I ran into issues:

my $camel ="Some 440Camel220 IsEntering100Text Nogo";
$camel =~ s/(?<=[a-z])(?=[A-Z])/ /g;
$camel =~ s/([^[:space:]]+)/\u$1/g;

Prints:

Some 440Camel220 Is Entering100Text Nogo

Desired:

Some 440 Camel 220 Is Entering 100 Text Nogo

So, how do I now insert a space between the letters and the numbers?.

Body:
Add the following two substitutions:

$camel =~ s/(?<=[0-9])(?=[a-z])/ /ig;
$camel =~ s/(?<=[a-z])(?=[0-9])/ /ig;

The first inserts a space at any transition between a digit and a letter. The i modifier at the end makes the expression case-insensitive. The second does the opposite.


问:
Classic ASP: log database errors
I implemented a simple function to create a log of my Classic ASP web application.
I can see all messages I set in the code (with a string like WriteLog("my message"), but I need to write in log errors coming from database (I'm using ADODB.Connection to connect to several databases, fro example Oracle, AS400, SQL Srv, etc...).

How can I catch a db error and write it on log file?

答:
you would call your function any time you do anything with the database, whether it's simply connecting to it, running a query against it, or whatever:

```<code>conn.open connString
if Err.Number <> 0 then WriteLog("error connection")

set rs = conn.Execute("<sql query>")
if Err.Number <> 0 then WriteLog("error running query")
</code>```

if this doesnt answer your question, please be more specific on what you want to accomplish

Title: Classic ASP: log database errors

Body:
you would call your function any time you do anything with the database, whether it's simply connecting to it, running a query against it, or whatever:

conn.open connString
if Err.Number <> 0 then WriteLog("error connection")

set rs = conn.Execute("<sql query>")
if Err.Number <> 0 then WriteLog("error running query")

if this doesnt answer your question, please be more specific on what you want to accomplish


问:
What is the meaning of the implementation of the KL divergence in Keras?
I'm a little confused about how the KL divergence is applied, specifically in Keras, but I think the question is general to deep learning applications. In keras, the KL loss function is defined like this:

```<code>def kullback_leibler_divergence(y_true, y_pred):
    y_true = K.clip(y_true, K.epsilon(), 1)
    y_pred = K.clip(y_pred, K.epsilon(), 1)
    return K.sum(y_true * K.log(y_true / y_pred), axis=-1)
</code>```

In my model, y_true and y_pred are matrices; each row of y_true a one-hot encoding for one training example, and each row of y_pred the output of the model (a probability distribution) for that example.

I can run this KL divergence calculation on any given pair of rows from y_true and y_pred and get the expected result. The mean of these KL divergence results over the rows matches the loss reported by Keras in the training history. But that aggregation - running KL divergence on each row and taking the mean - doesn't happen within loss function. In contrast, I understand MAE or MSE to aggregate across the examples:

```<code>def mean_squared_error(y_true, y_pred):
    return K.mean(K.square(y_pred - y_true), axis=-1)
</code>```

For the KL divergence, it's not totally obvious to me that taking the mean across the examples is the right thing to do. I guess the idea is that the examples are random samples from the true distribution, so they should appear in proportion to their probability. But that seems to make a pretty strong assumption about how the training data was collected. I haven't really seen this aspect (aggregating across samples from a dataset) addressed in the online treatments of the KL divergence; I just see a lot of redefinition of the basic formula.

So my questions are:

Is this interpretation of what Keras is doing to come up with the KL divergence loss (i.e. averaging over the KL divergence of the rows) correct?

Why is this the right thing to do?

From an implementation perspective, why doesn't the definition of the loss function in Keras do the aggregation over the rows the way MAE or MSE does?

答:
Kullback-Leibler divergence is a measure of similarity between two probability distributions. The KL divergence implemented in Keras assumes two discrete probability distributions (hence the sum).

The exact format of your KL loss function depends on the underlying probability distributions. A common usecase is that the neural network models the parameters of a probability distribution P (eg a Gaussian), and the KL divergence is then used in the loss function to determine the similarity between the modelled distribution and some other, known distribution (potentially Gaussian as well). E.g. a network outputs two vectors mu and sigma^2. Mu forms the mean of a Gaussian distribution P while sigma^2 is the diagonal of the covariance matrix Sigma. A possible loss function is then the KL divergence between the Gaussian P described by mu and Sigma, and a unit Gaussian N(0, I). The exact format of the KL divergence in that case can be derived analytically, yielding a custom keras loss function that is not at all equal to the KL divergence implemented in Keras.

In the original paper that introduces Variational Auto-Encoders, the loss function is summed over the samples in the minibatch and then multiplied by a factor (N/M), where N is the size of the entire dataset, and M is the size of the minibatch. See equations 8 and 10 in https://arxiv.org/abs/1312.6114.

Body:
I'm a little confused about how the KL divergence is applied, specifically in Keras, but I think the question is general to deep learning applications. In keras, the KL loss function is defined like this:

def kullback_leibler_divergence(y_true, y_pred):
    y_true = K.clip(y_true, K.epsilon(), 1)
    y_pred = K.clip(y_pred, K.epsilon(), 1)
    return K.sum(y_true * K.log(y_true / y_pred), axis=-1)

In my model, y_true and y_pred are matrices; each row of y_true a one-hot encoding for one training example, and each row of y_pred the output of the model (a probability distribution) for that example.

I can run this KL divergence calculation on any given pair of rows from y_true and y_pred and get the expected result. The mean of these KL divergence results over the rows matches the loss reported by Keras in the training history. But that aggregation - running KL divergence on each row and taking the mean - doesn't happen within loss function. In contrast, I understand MAE or MSE to aggregate across the examples:

def mean_squared_error(y_true, y_pred):
    return K.mean(K.square(y_pred - y_true), axis=-1)

For the KL divergence, it's not totally obvious to me that taking the mean across the examples is the right thing to do. I guess the idea is that the examples are random samples from the true distribution, so they should appear in proportion to their probability. But that seems to make a pretty strong assumption about how the training data was collected. I haven't really seen this aspect (aggregating across samples from a dataset) addressed in the online treatments of the KL divergence; I just see a lot of redefinition of the basic formula.

So my questions are:

Is this interpretation of what Keras is doing to come up with the KL divergence loss (i.e. averaging over the KL divergence of the rows) correct?

Why is this the right thing to do?

From an implementation perspective, why doesn't the definition of the loss function in Keras do the aggregation over the rows the way MAE or MSE does?


问:
PowerShell - Copy specific lines from multiple specific nested files
So, the folder structure looks like this:

RootFolder

RootFolder

SubFolder1

SubSubFolder1

totals.txt

SubSubFolder2

totals.txt

SubFolder2

SubSubFolder1

totals.txt

SubSubFolder2

totals.txt

What I want to do is recursively walk through these Subfolders for the totals.txt file. Read content, and copy lines 22,26,30,34,38,and 42 (with first line being 0 not 1)into a single combined file.

I started with this code:

```<code>Get-ChildItem -Recurse | Where-Object {$_ -like "totals.txt" } | Get-Content | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"
</code>```

However this only finds RootFolder\SubFolder\SubSubFolder\totals.txt and then exits script. Not what I'm looking for...

What I need is the above script to continue searching recursively for the next file and next until all directories have been searched in structure. So I used this:

```<code>Get-ChildItem -Recurse | ForEach-Object {$_ -like "totals.txt" } | Get-Content | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"
</code>```

However, this script errors

```<code>C:\Users\user1\scripts\Untitled1.ps1:1 char:69
+ ... urse | ForEach-Object {$_ -like "totals.txt" } | $_.filename #| Get- ...
+                                                       ~~~~~~~~~~~
Expressions are only allowed as the first element of a pipeline.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline
</code>```

I could use some help figuring out the rest of this powershell script. So close but no joy. Thanks for the help.

答:
Realized I needed to walk through the array

For other's reference, this code works as required:

```<code>Get-ChildItem -Recurse | Where-Object {$_ -like "totals.txt" } |
    %{
        (Get-Content $_.FullName) | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"
        }
</code>```

Body:
So, the folder structure looks like this:

RootFolder

RootFolder

SubFolder1

SubSubFolder1

totals.txt

SubSubFolder2

totals.txt

SubFolder2

SubSubFolder1

totals.txt

SubSubFolder2

totals.txt

What I want to do is recursively walk through these Subfolders for the totals.txt file. Read content, and copy lines 22,26,30,34,38,and 42 (with first line being 0 not 1)into a single combined file.

I started with this code:

Get-ChildItem -Recurse | Where-Object {$_ -like "totals.txt" } | Get-Content | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"

However this only finds RootFolder\SubFolder\SubSubFolder\totals.txt and then exits script. Not what I'm looking for...

What I need is the above script to continue searching recursively for the next file and next until all directories have been searched in structure. So I used this:

Get-ChildItem -Recurse | ForEach-Object {$_ -like "totals.txt" } | Get-Content | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"

However, this script errors

C:\Users\user1\scripts\Untitled1.ps1:1 char:69
+ ... urse | ForEach-Object {$_ -like "totals.txt" } | $_.filename #| Get- ...
+                                                       ~~~~~~~~~~~
Expressions are only allowed as the first element of a pipeline.
    + CategoryInfo          : ParserError: (:) [], ParentContainsErrorRecordException
    + FullyQualifiedErrorId : ExpressionsMustBeFirstInPipeline

I could use some help figuring out the rest of this powershell script. So close but no joy. Thanks for the help.

Body:
Realized I needed to walk through the array

For other's reference, this code works as required:

Get-ChildItem -Recurse | Where-Object {$_ -like "totals.txt" } |
    %{
        (Get-Content $_.FullName) | Select-Object -Index 22,26,30,34,38,42  | Add-Content "DataInportFile.txt"
        }


问:
Error related to data shape when running MXNetR
I am trying to build a Feed Forward neural network with MXNetR. My input is a data frame with 6380 rows and 180 columns. My training and testing outputs are one-dimensional vectors with 319 elements each.

I run the model with the batch size set to 1 and the number of neurons at the output layer set to 319. So for each batch, I expected to get a vector with 319 elements. I aim to minimize my loss function, which is the correlation between my predicted output vector and actual output vector.

Below is my code:

```<code>    # Define the input data
    data <- mx.symbol.Variable("data")

    # Define the first fully connected layer
    fc1 <- mx.symbol.FullyConnected(data, num_hidden = 100)
    act.fun <- mx.symbol.Activation(fc1, act_type = "relu") # create a hidden layer with Rectified Linear Unit as its activation function.
    output <<- mx.symbol.FullyConnected(act.fun, num_hidden = 319)

    # Customize loss function
    label <- mx.symbol.Variable("label")
    lro <-
        mx.symbol.MakeLoss(mx.symbol.Correlation(mx.symbol.reshape(output
    ,shape = (1,319)),label))

    model <- mx.model.FeedForward.create(symbol=lro, X=train.x,
                                         y=train.y,
                                         eval.data = list( data = test.x,
                                                       label = test.y),
                                         num.round=5000,
                                         array.batch.size=1,
                                         optimizer = "adam",
                                         learning.rate = 0.0003,
                                         eval.metric = mx.metric.rmse,
                                         epoch.end.callback =
                                         mx.callback.log.train.metric(20, logger))
</code>```

And here is the error when I run the code above:

```<code>[15:49:28] /home/cgagnon/src/q5/mxnet/dmlc-core/include/dmlc/./logging.h:304: [15:49:28] src/operator/./correlation-inl.h:176: Check failed: dshape1.ndim() == 4U (2 vs. 4) data should be a 4D tensor

Stack trace returned 10 entries:
[bt] (0) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZN4dmlc15LogMessageFatalD1Ev+0x29) [0x7f725a8528b9]
[bt] (1) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZNK5mxnet2op15CorrelationProp10InferShapeEPSt6vectorIN4nnvm6TShapeESaIS4_EES7_S7_+0x2a2) [0x7f725b4a8222]
[bt] (2) /usr/lib64/R/library/mxnet/libs/libmxnet.so(+0xd461f9) [0x7f725b3241f9]
[bt] (3) /usr/lib64/R/library/mxnet/libs/libmxnet.so(+0x116630f) [0x7f725b74430f]
[bt] (4) /usr/lib64/R/library/mxnet/libs/libmxnet.so(+0x1167bb2) [0x7f725b745bb2]
[bt] (5) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZN4nnvm11ApplyPassesENS_5GraphERKSt6vectorISsSaISsEE+0x501) [0x7f725b761481]
[bt] (6) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZN4nnvm9ApplyPassENS_5GraphERKSs+0x8e) [0x7f725b699f2e]
[bt] (7) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZN4nnvm4pass10InferShapeENS_5GraphESt6vectorINS_6TShapeESaIS3_EESs+0x240) [0x7f725b69c520]
[bt] (8) /usr/lib64/R/library/mxnet/libs/libmxnet.so(MXSymbolInferShape+0x281) [0x7f725b6959a1]
[bt] (9) /usr/lib64/R/library/mxnet/libs/mxnet.so(_ZNK5mxnet1R6Symbol10InferShapeERKN4Rcpp6VectorILi19ENS2_15PreserveStorageEEE+0x6b9) [0x7f724cef6739]
</code>```

At the moment, I am clueless about how I should fix this error. I have been searching for a way to reshape my data sets so that they are 4D tensors but could not find any. I do not look for an explicit solution for my problem, but any suggestions on how I should tackle this error would be greatly appreciated.

答:
I couldn't reproduce the problem without the data but I think if you are looking to just reshape your dataset into 4D tensors, you should be able to do it by
"symbol.reshape(output,shape = c(1,1,1,319))".
Not sure if it helps you though.</p>

Body:
I am trying to build a Feed Forward neural network with MXNetR. My input is a data frame with 6380 rows and 180 columns. My training and testing outputs are one-dimensional vectors with 319 elements each.

I run the model with the batch size set to 1 and the number of neurons at the output layer set to 319. So for each batch, I expected to get a vector with 319 elements. I aim to minimize my loss function, which is the correlation between my predicted output vector and actual output vector.

Below is my code:

    # Define the input data
    data <- mx.symbol.Variable("data")

    # Define the first fully connected layer
    fc1 <- mx.symbol.FullyConnected(data, num_hidden = 100)
    act.fun <- mx.symbol.Activation(fc1, act_type = "relu") # create a hidden layer with Rectified Linear Unit as its activation function.
    output <<- mx.symbol.FullyConnected(act.fun, num_hidden = 319)

    # Customize loss function
    label <- mx.symbol.Variable("label")
    lro <-
        mx.symbol.MakeLoss(mx.symbol.Correlation(mx.symbol.reshape(output
    ,shape = (1,319)),label))

    model <- mx.model.FeedForward.create(symbol=lro, X=train.x,
                                         y=train.y,
                                         eval.data = list( data = test.x,
                                                       label = test.y),
                                         num.round=5000,
                                         array.batch.size=1,
                                         optimizer = "adam",
                                         learning.rate = 0.0003,
                                         eval.metric = mx.metric.rmse,
                                         epoch.end.callback =
                                         mx.callback.log.train.metric(20, logger))

And here is the error when I run the code above:

[15:49:28] /home/cgagnon/src/q5/mxnet/dmlc-core/include/dmlc/./logging.h:304: [15:49:28] src/operator/./correlation-inl.h:176: Check failed: dshape1.ndim() == 4U (2 vs. 4) data should be a 4D tensor

Stack trace returned 10 entries:
[bt] (0) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZN4dmlc15LogMessageFatalD1Ev+0x29) [0x7f725a8528b9]
[bt] (1) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZNK5mxnet2op15CorrelationProp10InferShapeEPSt6vectorIN4nnvm6TShapeESaIS4_EES7_S7_+0x2a2) [0x7f725b4a8222]
[bt] (2) /usr/lib64/R/library/mxnet/libs/libmxnet.so(+0xd461f9) [0x7f725b3241f9]
[bt] (3) /usr/lib64/R/library/mxnet/libs/libmxnet.so(+0x116630f) [0x7f725b74430f]
[bt] (4) /usr/lib64/R/library/mxnet/libs/libmxnet.so(+0x1167bb2) [0x7f725b745bb2]
[bt] (5) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZN4nnvm11ApplyPassesENS_5GraphERKSt6vectorISsSaISsEE+0x501) [0x7f725b761481]
[bt] (6) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZN4nnvm9ApplyPassENS_5GraphERKSs+0x8e) [0x7f725b699f2e]
[bt] (7) /usr/lib64/R/library/mxnet/libs/libmxnet.so(_ZN4nnvm4pass10InferShapeENS_5GraphESt6vectorINS_6TShapeESaIS3_EESs+0x240) [0x7f725b69c520]
[bt] (8) /usr/lib64/R/library/mxnet/libs/libmxnet.so(MXSymbolInferShape+0x281) [0x7f725b6959a1]
[bt] (9) /usr/lib64/R/library/mxnet/libs/mxnet.so(_ZNK5mxnet1R6Symbol10InferShapeERKN4Rcpp6VectorILi19ENS2_15PreserveStorageEEE+0x6b9) [0x7f724cef6739]

At the moment, I am clueless about how I should fix this error. I have been searching for a way to reshape my data sets so that they are 4D tensors but could not find any. I do not look for an explicit solution for my problem, but any suggestions on how I should tackle this error would be greatly appreciated.


问:
ACORD AL3 - What's the deal with "?"s
We're writing a parser for ACORD AL3. Read AL3 coming in, write AL3 going out. Nice and simple.

As of right now, it is 99% solid. The only thing that's driving me nuts is the use of "?"s in the ACORD AL3 standard. It appears that they are used as placeholders for fields that do not have values in the message. HOWEVER, that's not the only rule for it, because if it was, the AL3 I'm currently generating would look that the sample files I'm trying to have it match.

So if anyone here knows anything about the rules around AL3 "?"s, that would be great. I've been pouring over the Data Dictionary and the other documentation from ACORD, and I'm seeing nothing to indicate which fields get it, and which ones don't.

Also, if the "?"s are not required for AL3 processing to begin with, that would also be great to know, because then I could just stop worrying about the whole thing.

答:
There may be individual elements in a group that are valid, but the sender
cannot send them for some reason.  The solution is to fill that data element with questions marks (?????)  The receiving system will recognize this and not update that field on their system. </p>

Title: ACORD AL3 - What's the deal with "?"s


问:
using jQuery to load a php file and the php file includes
This may be a "stupid" question but ...

If I use JQuery .load(); etc to load a page into a  is there a way that I can pass a php config file data to it without having to redeclare it?  At the moment I am having to load the config files etc into the loaded page as well as on the page it loads into.

e.g.

In the head of page1.php - require('config.php');
then if I load page2.php into a  on page1 I have to call config.php on page2.php aswell but is there a way that I don't have to?

答: Nope, you're talking about a client request to get part of a page, loading part of the initial page that may have server-side variable really isn't what .load() is designed for.


问:
replace commas to decimal points in DataFrame columns to make them numeric
```<code>import pandas as pd
df = pd.DataFrame([["one", 1.2, "", "4,3"],
   ["two","1,7", "2,4", 0.55],
   ["three","", 5.4, "3,9"]],
   columns=['a','b','c','d'])
</code>```

How can I replace the commas in the columns b to d to points and make these columns numeric?
Column a (or any number of leading columns) should be retained untouched (can contain commas as well)

答:
```<code>import re

for col in ['b', 'c', 'd']:
    df[col] = pd.to_numeric(df[col].apply(lambda x: re.sub(',', '.', str(x))))
</code>```

Body:
import pandas as pd
df = pd.DataFrame([["one", 1.2, "", "4,3"],
   ["two","1,7", "2,4", 0.55],
   ["three","", 5.4, "3,9"]],
   columns=['a','b','c','d'])

How can I replace the commas in the columns b to d to points and make these columns numeric?
Column a (or any number of leading columns) should be retained untouched (can contain commas as well)


问:
What is the difference between these two similar SQL ARRAY_TO_STRING statements?
I am sniffing out an error in my SQL query that revolves around the ARRAY_AGG function. Below are the following two lines of SQL.

The below line is the correct and complete SQL version that I ultimately want to have. This behavior is the behavior that results in a correct query.

```<code>ARRAY_TO_STRING((ARRAY_AGG(R.version ORDER BY R.released_on DESC))[1:10], ', ')
</code>```

and this line here I thought would be equivalent but when I execute this line of SQL I receive ERROR:  more than one row returned by a subquery used as an expression

```<code>ARRAY_TO_STRING(ARRAY_AGG((SELECT  "releases"."version" FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10)), ',')
</code>```

I am arriving at this line of SQL through arel and is proving to be a little challenging but is it possible that the two lines could be equivalent? The first line is slicing an array to retrieve 10 items while the second is essentially doing the same thing albeit in rows. Could this be tweaked or will this need to be rewritten?

答:
I haven't used ruby but it looks like the nesting in different between the two lines. Your ARRAY_AGG is getting two different sets of data.

First:

```<code>ARRAY_AGG(R.version ORDER BY R.released_on DESC)
</code>```

Second:

```<code>ARRAY_AGG((SELECT  "releases"."version" FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10))
</code>```

Looking there I think on your second statement is wrong, from what I see online it looks like ARRAY_AGG should be use as a column function not on a table set. Below are some links that I was looking at but I wan't sure which is correct as ARRAY_AGG looks to be a sql function and i'm not sure what flavor you are using...

https://msdn.microsoft.com/en-us/library/azure/mt763803.aspx

https://www.postgresql.org/docs/8.4/static/functions-aggregate.html

 With that I think it should look like:

```<code>(SELECT  ARRAY_AGG("releases"."version") FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10)
</code>```

Just a guess..

Body:
I am sniffing out an error in my SQL query that revolves around the ARRAY_AGG function. Below are the following two lines of SQL.

The below line is the correct and complete SQL version that I ultimately want to have. This behavior is the behavior that results in a correct query.

ARRAY_TO_STRING((ARRAY_AGG(R.version ORDER BY R.released_on DESC))[1:10], ', ')

and this line here I thought would be equivalent but when I execute this line of SQL I receive ERROR:  more than one row returned by a subquery used as an expression

ARRAY_TO_STRING(ARRAY_AGG((SELECT  "releases"."version" FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10)), ',')

I am arriving at this line of SQL through arel and is proving to be a little challenging but is it possible that the two lines could be equivalent? The first line is slicing an array to retrieve 10 items while the second is essentially doing the same thing albeit in rows. Could this be tweaked or will this need to be rewritten?

Body:
I haven't used ruby but it looks like the nesting in different between the two lines. Your ARRAY_AGG is getting two different sets of data.

First:

ARRAY_AGG(R.version ORDER BY R.released_on DESC)

Second:

ARRAY_AGG((SELECT  "releases"."version" FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10))

Looking there I think on your second statement is wrong, from what I see online it looks like ARRAY_AGG should be use as a column function not on a table set. Below are some links that I was looking at but I wan't sure which is correct as ARRAY_AGG looks to be a sql function and i'm not sure what flavor you are using...

https://msdn.microsoft.com/en-us/library/azure/mt763803.aspx

https://www.postgresql.org/docs/8.4/static/functions-aggregate.html

 With that I think it should look like:

(SELECT  ARRAY_AGG("releases"."version") FROM "releases"  ORDER BY "releases"."released_on" DESC LIMIT 10)

Just a guess..


问:
Get diagonal elements from tf.matmul(tf.transpose(A), A) in Tensorflow
I have a matrix A with several columns, and I need to compute the self dot products, i.e. tf.matmul(A[:,i]), A[:,i], transpose_a=True) where i indexes columns of A. One way is to just compute tf.matmul(A,A, transpose_a=True) and extract the diagonal, but this involves a lot of superfluous multiplication (all non-diagonal results are discarded, and the non-diagonal results are most of the results for any matrix larger than 2 x 2). Another way is to do something like

```<code>out = []
for i in range(tf.shape(A)[1]):
    out.append(tf.matmul((A[:,i],A[:,i],transpose_a=True))
</code>```

and then collect out into a tf.Tensor. But it seems like this is a fairly common computation, so I would expect a function to exist for it (i.e. computing squared norms of weight vectors).

答:
You can multiply the matrix by itself elementwise and then sum along axis 0.

```<code>import tensorflow as tf
tf.InteractiveSession()

A = tf.reshape(tf.range(12), (3, 4))
tf.reduce_sum(tf.pow(A, 2), axis=0).eval()
</code>```

returns

```<code>array([ 80, 107, 140, 179], dtype=int32)
</code>```

Body:
I have a matrix A with several columns, and I need to compute the self dot products, i.e. tf.matmul(A[:,i]), A[:,i], transpose_a=True) where i indexes columns of A. One way is to just compute tf.matmul(A,A, transpose_a=True) and extract the diagonal, but this involves a lot of superfluous multiplication (all non-diagonal results are discarded, and the non-diagonal results are most of the results for any matrix larger than 2 x 2). Another way is to do something like

out = []
for i in range(tf.shape(A)[1]):
    out.append(tf.matmul((A[:,i],A[:,i],transpose_a=True))

and then collect out into a tf.Tensor. But it seems like this is a fairly common computation, so I would expect a function to exist for it (i.e. computing squared norms of weight vectors).

Body:
You can multiply the matrix by itself elementwise and then sum along axis 0.

import tensorflow as tf
tf.InteractiveSession()

A = tf.reshape(tf.range(12), (3, 4))
tf.reduce_sum(tf.pow(A, 2), axis=0).eval()

returns

array([ 80, 107, 140, 179], dtype=int32)


问:
Find number of vowels in a word
How can a find all the vowels for a word in bash?

```<code>grep -o "a"  <<<$1 | wc l
</code>```

This command finds only a, and I want to find aeiou.

For example:

for car I want the output to be 1

for computer I want the output to be 3

答:
bash approach with GNU expr command:

Input variables:

```<code>v1="computer"
v2="car"
</code>```

```<code>expr length "${v1//[^aeuoi]}"
3
</code>```

```<code>expr length "${v2//[^aeuoi]}"
1
</code>```

${v2//[^aeuoi]} - replacing/removing all non-vowel characters

expr length STRING - evaluates length of STRING

A more compatible variation would look like:

```<code>vowels="${v1//[^aeuoi]}"
echo "${#vowels}"
3
</code>```

Title: Find number of vowels in a word

Body:
How can a find all the vowels for a word in bash?

grep -o "a"  <<<$1 | wc l

This command finds only a, and I want to find aeiou.

For example:

for car I want the output to be 1

for computer I want the output to be 3

Body:
bash approach with GNU expr command:

Input variables:

v1="computer"
v2="car"

expr length "${v1//[^aeuoi]}"
3

expr length "${v2//[^aeuoi]}"
1

${v2//[^aeuoi]} - replacing/removing all non-vowel characters

expr length STRING - evaluates length of STRING

A more compatible variation would look like:

vowels="${v1//[^aeuoi]}"
echo "${#vowels}"
3


问:
Parameter Validation on Reports
I'm new to SSRS, so I apologize if this question is too simple:

I have a report which accepts a parameter called "Amount". I want to constrain valid inputs to currency values >= 0, and pop open an error message if the user enters improper values.

I don't want to validate inputs in my stored procedure and throw exceptions, because SSRS displays a very generic "Query execution failed for 'someTable'" message to users who access the report from another machine, and my business does not want to turn on the "Enable Remote Errors" flag.

How do I add input validation to report parameters and notify users of bad input?

Yes, I've googled around, but haven't had much luck. Thanks in advance :)

答:
It's possible to make report parameters in SSRS that are based on a particular list or a lookup query but I don't think you can apply a regex or something like that.

Instead you might consider separating your report into two panels, one which displays your report and one which displays an error and then you create an assembly with a function in it that validates the parameters for the report before it is run. If the validate parameters function is successful you hide the error panel and show the report panel, if not you do the opposite.

OwnerDisplayName: Princess

Title: Parameter Validation on Reports

OwnerDisplayName: Chris Simpson


问:
How can I get Symfony request context to use the REQUEST_URI from a IIS rewrite rule?
I setup a Reverse Proxy Rewrite Rule in IIS7 for requests to Symfony.
It matches the pattern and passes the correct request details so from a technical perspective it is working, but Symfony doesn't seem to use the correct info or rather the info I want it to use.

Breakpointing in app.php to see what symfony receives from the other server in the $_SERVER details the relevant parameters for this are:

HTTP_X_ORIGINAL_URL="/foo/bar/foo/someCall/123456789"

REQUEST_URI="/bar/foo/someCall/123456789" (what was matched by the
pattern in the rewrite rule)

A route has been setup for /bar/foo/someCall/{id}, but the request context only sets the pathInfo as /foo/bar/foo/someCall/{id}, which results in a "No route exists ..." error.

I need the request context (possibly route listener etc) to use what is in REQUEST_URI. How would one be able to do so, if at all possible?

答:
When using a reverse proxy, you shouldn't change your application to match your proxy url (or even be aware that is is running behind a proxy). Instead the proxy needs to ensure it send the correct information to your application. In order to do that, you need to understand how Syfony decides if a route matches or not.

Symfony by default uses the REQUEST_URI to determine a route. But it also supports IIS rewrite rules, which then overwrite the REQUEST_URI value, which can be seen here: https://github.com/symfony/symfony/blob/2.8/src/Symfony/Component/HttpFoundation/Request.php#L1684-L1717. So just working with the REQUEST_URI won't work here.

In this case, the interesting part is the way Symfony determines the base URL (https://github.com/symfony/symfony/blob/2.8/src/Symfony/Component/HttpFoundation/Request.php#L1729-L1752). Since you are trying to rewrite the base of the URL, your best bet would be to manipulate the script path that is passed as part of the proxy. I'm not an expert in IIS or how it's rewrite rules work, but when using Nginx as a reverse proxy, you normally would set the X-SCRIPT-NAME header to your base path, so you can try something similar in IIS.