问:
Getting React error: "setState(...): Can only update a mounted or mounting component" ONLY with Child Component
I've been chasing this bug all day. I have a dead-simple React entry point, and a dead-simple component state change example component. If I put the component into the entry point, like this:

```<code>import React from 'react';
import { render } from 'react-dom';

export default class Template extends React.Component {
  constructor(props) {
    super(props);

    this.toggleNavbar = this.toggleNavbar.bind(this);
    this.state = {
      collapsed: true,
    };
  }

  toggleNavbar() {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }
  render() {
    return (
      <div>
        <p>Collapsed: { this.state.collapsed ? 'true' : 'false' }</p>
        <button onClick={this.toggleNavbar}>Toggle</button>
      </div>
    );
  }
}

render(
  <Template />,
  document.querySelector('#react-app'),
);
</code>```

It works as expected. You click the toggle button, and the text changes back and forth between 'true' and 'false'. However, the minute I break it out into two separate files, giving me this for the entry point:

```<code>import React from 'react';
import { render } from 'react-dom';

import Template from './components/Template';

render(
  <Template />,
  document.querySelector('#react-app'),
);
</code>```

and this for Template.jsx

```<code>import React from 'react';

export default class Template extends React.Component {
  constructor(props) {
    super(props);

    this.toggleNavbar = this.toggleNavbar.bind(this);
    this.state = {
      collapsed: true,
    };
  }

  toggleNavbar() {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }
  render() {
    return (
      <div>
        <p>Collapsed: { this.state.collapsed ? 'true' : 'false' }</p>
        <button onClick={this.toggleNavbar}>Toggle</button>
      </div>
    );
  }
}
</code>```

Any time I click on the button I get the following error in the console:

build.js:23484 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Template component.

... I've checked all of the other Stack Overflow answers for that error (and also searched around a ton), and none of them seem to be applicable here. Anyone have any idea what I'm doing wrong?

side note: I've tried adding:

```<code>componentWillUnmount() {
  this.isUnmounted = true;
}
</code>```

and a !this.isUnmounted check before setState() and I still get the error.

Thanks!

答:
I found the issue: my .babelrc contained this line:

```<code>  "plugins": ["react-hot-loader/babel"]
</code>```

And it was conflicting with the rest of my webpack hot-reloading setup. Removing that line did the trick. I think what was happening is that the component was getting rendered, but somehow react was getting confused about what was/wasn't mounted (maybe it was very quickly getting mounted, unmounted, and then re-mounted, and so the bound toggleClick function was trying to set state on an old version of the component? Unsure).

Anyway, the moral of the story is: the React code is fine. It was a problem with my config.

Body:
I've been chasing this bug all day. I have a dead-simple React entry point, and a dead-simple component state change example component. If I put the component into the entry point, like this:

import React from 'react';
import { render } from 'react-dom';

export default class Template extends React.Component {
  constructor(props) {
    super(props);

    this.toggleNavbar = this.toggleNavbar.bind(this);
    this.state = {
      collapsed: true,
    };
  }

  toggleNavbar() {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }
  render() {
    return (

Collapsed: { this.state.collapsed ? 'true' : 'false' }

        <button onClick={this.toggleNavbar}>Toggle</button>

    );
  }
}

render(
  <Template />,
  document.querySelector('#react-app'),
);

It works as expected. You click the toggle button, and the text changes back and forth between 'true' and 'false'. However, the minute I break it out into two separate files, giving me this for the entry point:

import React from 'react';
import { render } from 'react-dom';

import Template from './components/Template';

render(
  <Template />,
  document.querySelector('#react-app'),
);

and this for Template.jsx

import React from 'react';

export default class Template extends React.Component {
  constructor(props) {
    super(props);

    this.toggleNavbar = this.toggleNavbar.bind(this);
    this.state = {
      collapsed: true,
    };
  }

  toggleNavbar() {
    this.setState({
      collapsed: !this.state.collapsed,
    });
  }
  render() {
    return (

Collapsed: { this.state.collapsed ? 'true' : 'false' }

        <button onClick={this.toggleNavbar}>Toggle</button>

    );
  }
}

Any time I click on the button I get the following error in the console:

build.js:23484 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Template component.

... I've checked all of the other Stack Overflow answers for that error (and also searched around a ton), and none of them seem to be applicable here. Anyone have any idea what I'm doing wrong?

side note: I've tried adding:

componentWillUnmount() {
  this.isUnmounted = true;
}

and a !this.isUnmounted check before setState() and I still get the error.

Thanks!

Body:
I found the issue: my .babelrc contained this line:

  "plugins": ["react-hot-loader/babel"]

And it was conflicting with the rest of my webpack hot-reloading setup. Removing that line did the trick. I think what was happening is that the component was getting rendered, but somehow react was getting confused about what was/wasn't mounted (maybe it was very quickly getting mounted, unmounted, and then re-mounted, and so the bound toggleClick function was trying to set state on an old version of the component? Unsure).

Anyway, the moral of the story is: the React code is fine. It was a problem with my config.


来源: stackexchange

问:
How to make a serialized column empty?
I have a column in Company, that is serialized as Array:

```<code>class Company
  serialize :column_name, Array
end
</code>```

In rails console, when I try the following:

```<code>existing = Company.last.column_name
# it gives a array with single element, say [1]
existing.delete(1)
# now existing is []
Company.last.update_attributes!(column_name: existing)
# It empties the array, so:
Company.last.column_name #gives []
</code>```

But, when I try the same code in remove method of some controller, it never removes the last element. It always returns [1].

How can I empty the serialized column?

NOTE:- This logic works when I have multiple elements, but doesn't work for the last element alone.

CONTROLLER CODE

```<code>def remove_restricted_num
  company = Company.where(id: params[:id]).first
  restricted_numbers = company.restricted_numbers
  num = params[:num].to_i

  if restricted_numbers.include?(num)
    restricted_numbers.delete(num)
    company.update_attributes!(restricted_numbers: restricted_numbers)

    render js: "alert('#{num} was removed')"
  else
    render js: "alert('Number not found in the list')"
  end
end
</code>```

答:
I got the fix, we need to use dup to get a independent variable existing, which otherwise was referencing Company.last.column_name

```<code>existing = Company.last.column_name.dup # THIS WORKS!!!
existing.delete(1)
Company.last.update_attributes!(column_name: existing)
</code>```

This updates the column to [], as I need.

ContentLicense: CC BY-SA 3.0

Title: How to make a serialized column empty?

Body:
I have a column in Company, that is serialized as Array:

class Company
  serialize :column_name, Array
end

In rails console, when I try the following:

existing = Company.last.column_name
# it gives a array with single element, say [1]
existing.delete(1)
# now existing is []
Company.last.update_attributes!(column_name: existing)
# It empties the array, so:
Company.last.column_name #gives []

But, when I try the same code in remove method of some controller, it never removes the last element. It always returns [1].

How can I empty the serialized column?

NOTE:- This logic works when I have multiple elements, but doesn't work for the last element alone.

CONTROLLER CODE

def remove_restricted_num
  company = Company.where(id: params[:id]).first
  restricted_numbers = company.restricted_numbers
  num = params[:num].to_i

  if restricted_numbers.include?(num)
    restricted_numbers.delete(num)
    company.update_attributes!(restricted_numbers: restricted_numbers)

    render js: "alert('#{num} was removed')"
  else
    render js: "alert('Number not found in the list')"
  end
end

Body:
I got the fix, we need to use dup to get a independent variable existing, which otherwise was referencing Company.last.column_name

existing = Company.last.column_name.dup # THIS WORKS!!!
existing.delete(1)
Company.last.update_attributes!(column_name: existing)

This updates the column to [], as I need.


问:
Gmail isn't verifying my email address
When I send an email from my domain email to a Gmail account, a question mark appears as the logo and a message that says "Gmail couldn't verify that [domain name] actually sent this message (and not a spammer)"
How do I resolve it?

Thanks in Advance

答:
It's depends on your site DNS and servers. If you change server, the problem will be solved.

If you send an email from another domain but from same server (DNS) you will still see question mark!

Title: Gmail isn't verifying my email address


问:
GoldenGate version 12 installation/upgradation on zOS
I have GoldenGate version 11.1 on my z/OS and Linux servers. I need to upgrade the GoldenGate to version 12 on both the servers. The database that GG is interacting is DB2. I looked up on the internet for the instructions but to me they seem little complex.
My question is if it is possible for a standard GoldenGate developer to install/upgrade its version on both the servers or I will need a consultant from Oracle to do this activity for me? The good part of calling a Oracle consultant is I will get a lot of learning but the con is they charge a lot for this activity.

Please suggest.

答:
Upgrading a replication system is not a straightforward task. As you have mentioned, there are many thing you need to be aware of. You need first to plan the upgrade process, test it and as a final task, implement it on the production replication system.

For example, GoldenGate 12 has different default values for some parameters than GoldenGate 11. You might need to check the PRM files and adapt them to the never version.

Everything about the upgrade process is written in the documentation and in the Oracle MOS notes. It is possible that all the work that is done during the upgrade is made by a mortal person.

You have to choose by yourself what level of risk you are willing to accept. And make a plan what to do if something goes wrong.


问:
Repair normals on possibly bad .stl files
I am new to Three.js and have been assigned the task of trying to repair the normals on files that have been coming in occasionally that appear to be bad. We do not know if they are bad scans or possibly bad uploads. We are looking into the upload function, but also would like to try and repair them if possible. Can anyone provide any ideas or tips to repair the file or find the correct normals?

Below is the code where we grab the normals and how we grab them. NOTE: this code works fine generally, it is only a problem when the normals are bad. I am also attaching one of the files so you can see the types of normals and "bad file" I am dealing with. Get File here

We are also using VTK on the backend with C++, so a solution or idea using either of these is helpful.

```<code>my.geometry = geometry;

    var front = new THREE.MeshPhongMaterial(
    {color: 0xe2e4dc, shininess: 50, side: THREE.DoubleSide});

var mesh = [new THREE.Mesh(geometry, front)];

my.scene.add(mesh[0]);
my.objects.push(mesh[0]);

var rc = new THREE.Raycaster();

var modelData = {'objects': [mesh[0].id], 'id': mesh[0].id};

var normalFound = false;
for (var dy = 80; dy >= -80; dy = dy - 10) {
  console.log('finding a normal on', 0, dy, -200);
  rc.set(new THREE.Vector3(0, dy, -200), new THREE.Vector3(0, 0, 1));

  var hit = rc.intersectObjects([mesh[0]]);

  if (hit.length) {
    my.normal = hit[0].face.normal.normalize();
    console.log('normal', my.normal.z);

    modelData['normal'] = my.normal;

    if ((my.normal.z > 0.9 && my.normal.z < 1.1)) {
      my.requireOrienteering = true;
      modelData['arch'] = 'lower';
      normalFound = true;
      console.log('we have a lower arch');
    } else if ((my.normal.z < -0.9 && my.normal.z > -1.1)) {
      modelData['arch'] = 'upper';
      normalFound = true;
      console.log('we have an upper arch');
      }

    break;
  }
}
</code>```

答:
VTK has a filter named vtkPolyDataNormals that you can run on your file to compute normals. You probably want to call ConsistencyOn(), NonManifoldTraversalOn(), and AutoOrientNormalsOn() before running it.

If you want point-normals (instead of per-cell normals) and your shape has sharp corners, you probably want to provide a feature angle with SetFeatureAngle() and call SplittingOn().

Body:
I am new to Three.js and have been assigned the task of trying to repair the normals on files that have been coming in occasionally that appear to be bad. We do not know if they are bad scans or possibly bad uploads. We are looking into the upload function, but also would like to try and repair them if possible. Can anyone provide any ideas or tips to repair the file or find the correct normals?

Below is the code where we grab the normals and how we grab them. NOTE: this code works fine generally, it is only a problem when the normals are bad. I am also attaching one of the files so you can see the types of normals and "bad file" I am dealing with. Get File here

We are also using VTK on the backend with C++, so a solution or idea using either of these is helpful.

my.geometry = geometry;

    var front = new THREE.MeshPhongMaterial(
    {color: 0xe2e4dc, shininess: 50, side: THREE.DoubleSide});

var mesh = [new THREE.Mesh(geometry, front)];

my.scene.add(mesh[0]);
my.objects.push(mesh[0]);

var rc = new THREE.Raycaster();

var modelData = {'objects': [mesh[0].id], 'id': mesh[0].id};

var normalFound = false;
for (var dy = 80; dy >= -80; dy = dy - 10) {
  console.log('finding a normal on', 0, dy, -200);
  rc.set(new THREE.Vector3(0, dy, -200), new THREE.Vector3(0, 0, 1));

  var hit = rc.intersectObjects([mesh[0]]);

  if (hit.length) {
    my.normal = hit[0].face.normal.normalize();
    console.log('normal', my.normal.z);

    modelData['normal'] = my.normal;

    if ((my.normal.z > 0.9 && my.normal.z < 1.1)) {
      my.requireOrienteering = true;
      modelData['arch'] = 'lower';
      normalFound = true;
      console.log('we have a lower arch');
    } else if ((my.normal.z < -0.9 && my.normal.z > -1.1)) {
      modelData['arch'] = 'upper';
      normalFound = true;
      console.log('we have an upper arch');
      }

    break;
  }
}


问:
Getting exceptions when InstanceContextMode is set to per session or per call
I am trying to make an application(for learning purpose) that can log in and will create an instance of "user" then save their userid in it. Then they can invoke the getUserid method and get the userid they saved. But if I use single InstanceContextMode, the userid of the old user will be replaced by a new user. So I am trying per session mode, but I am receiving exception below when I am invoking getUserid method after login.

```<code>Server stack trace:
   At System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at IService.getUserid()
   at ServiceClient.getUserid()
</code>```

This is my codes for my service class.

```<code>[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IService
{
    SqlConnection con;
    SqlCommand command;
    SqlDataReader sdr;
    user loginUser;

    public Service()
    {
        dataBase();
    }

    public bool Login(string username, string password)
    {
            command.CommandText = "select userid, password from chatuser where username = '" + username + "'";
            sdr = command.ExecuteReader();
            while (sdr.Read())
            {
                if (password.Equals(sdr.GetString(1)))
                {
                    loginUser = new user(sdr.GetString(0));
                    return true;
                }
            }
            return false;
    }

    public string getUserid()
    {
        return loginUser.Userid;
    }
}
</code>```

This is my user class.

```<code>[DataContract]
public class user
{
    string userid;
    public user()
    {
    }

    public user(string userid)
    {
        this.userid = userid;
    }

    [DataMember]
    public string Userid
    {
        get { return userid; }
        set { userid = value; }
    }
}
</code>```

And this is my interface class.

```<code>[ServiceContract]
public interface IService
{
    [OperationContract]
     bool Login(string username, string password);

    [OperationContract]
    string getUserid();
 }
</code>```

Errors occur after InstanceContextMode is changed to per session, the app runs fine when it's single but the new one will replace the old. So should it still be set to per session? Or have I done something wrong?

I am self-learning C# and new to it, so I am sorry if I am asking silly questions.

答:
I am using basicHttpsBinding

Well that's the issue since basicHttpsBinding doesn't support Session (by default) and thus if you use PerSession InstanceContextMode it's bound to throw exception since there is no session.

You should rather be using netTcpBinding or wsHttpBinding in this case which has Session facility

Body:
I am trying to make an application(for learning purpose) that can log in and will create an instance of "user" then save their userid in it. Then they can invoke the getUserid method and get the userid they saved. But if I use single InstanceContextMode, the userid of the old user will be replaced by a new user. So I am trying per session mode, but I am receiving exception below when I am invoking getUserid method after login.

Server stack trace:
   At System.ServiceModel.Channels.ServiceChannel.ThrowIfFaultUnderstood(Message reply, MessageFault fault, String action, MessageVersion version, FaultConverter faultConverter)
   at System.ServiceModel.Channels.ServiceChannel.HandleReply(ProxyOperationRuntime operation, ProxyRpc& rpc)
   at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)
   at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage methodCall, ProxyOperationRuntime operation)
   at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

Exception rethrown at [0]:
   at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage reqMsg, IMessage retMsg)
   at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)
   at IService.getUserid()
   at ServiceClient.getUserid()

This is my codes for my service class.

[ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)]
public class Service : IService
{
    SqlConnection con;
    SqlCommand command;
    SqlDataReader sdr;
    user loginUser;

    public Service()
    {
        dataBase();
    }

    public bool Login(string username, string password)
    {
            command.CommandText = "select userid, password from chatuser where username = '" + username + "'";
            sdr = command.ExecuteReader();
            while (sdr.Read())
            {
                if (password.Equals(sdr.GetString(1)))
                {
                    loginUser = new user(sdr.GetString(0));
                    return true;
                }
            }
            return false;
    }

    public string getUserid()
    {
        return loginUser.Userid;
    }
}

This is my user class.

[DataContract]
public class user
{
    string userid;
    public user()
    {
    }

    public user(string userid)
    {
        this.userid = userid;
    }

    [DataMember]
    public string Userid
    {
        get { return userid; }
        set { userid = value; }
    }
}

And this is my interface class.

[ServiceContract]
public interface IService
{
    [OperationContract]
     bool Login(string username, string password);

    [OperationContract]
    string getUserid();
 }

Errors occur after InstanceContextMode is changed to per session, the app runs fine when it's single but the new one will replace the old. So should it still be set to per session? Or have I done something wrong?

I am self-learning C# and new to it, so I am sorry if I am asking silly questions.


问:
Facebook messenger checkbox plugin is hidden
I'm trying to implement the new Facebook Checkbox plugin in a form but in a weird way I can't get it showing on the screen. So I don't get errors clientside but Iframe is hidden.

Here's an simplified example of the code:

    <input type="button" onclick="confirmOptIn()" value="Confirm Opt-in"/>

```

There are no errors in the dev console. Only logs that the plugin is hidden:

答:
Facebook updated their docs:

The web plugin takes a user_ref parameter which is used as an identifier for the user. When the user finishes the flow, we will pass this identifier back to you to identify the user. This parameter should be unique not just for every user, but for every time the plugin is rendered. If the parameter is not unique, then the plugin may not render.

You have to generate a new user_ref for every single render of the checkbox plugin.

Checklist to display CheckBox Plugin

<s>use Production App Id (not the test one)</s>

always regenerated user_ref

whitelist the domain in origin

use correct protocol in origin - http / https

Body:
I'm trying to implement the new Facebook Checkbox plugin in a form but in a weird way I can't get it showing on the screen. So I don't get errors clientside but Iframe is hidden.

Here's an simplified example of the code:

    <input type="button" onclick="confirmOptIn()" value="Confirm Opt-in"/>

There are no errors in the dev console. Only logs that the plugin is hidden:

ContentLicense: CC BY-SA 4.0


问:
C# - boolean and if statement
I'm currently writing code analysing images with the Google API Vision on Visual Studios.
But I have a problem that occures during my loop.
The analysis returns a list of annotation ( car, vehicle, land vehicle, etc.. ) and I wanted to filter it, with an "if", so i wrote this :

```<code>var image = Google.Cloud.Vision.V1.Image.FromFile("C:\\temp\\sequence\\1.jpg");
var client = ImageAnnotatorClient.Create();
var response = client.DetectLabels(image);
CropHintsAnnotation confidence = client.DetectCropHints(image);
bool empty = false;

foreach (var annotation in response)
{
    textBox1.Text += annotation.Description + "\r\n";
    textBox1.Text += "Score : " + annotation.Score + "\r\n";
    if (annotation.Description.Equals("vehicle"))
    {
        empty = false;
    }
    else
    {
        empty = true;
    }

}
textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";
</code>```

So, if I wrote this well, it should say " Empty ? false ", because the analysis returns "vehicle" once.
I tried also to replace the :

```<code>annotation.Description.Equals("vehicle")
</code>```

by

```<code>annotation.Description.Contains("vehicle") == true
</code>```

but no way, it still says " Empty ? true ", as it should not.

Any ideas ?

Thanks in advance for reading this, and for the help !

答:
Not exactly sure what you are trying to do here but assuming the response has more than one item the empty variable will only represent the value for the last one.

Reason is that for each iteration of the loop when it gets to the if statement it will enter it or the else and for sure will enter one of the two, so for each iteration the value of empty will be assigned and override the previous value

As for the code itself, it is neater to write it this way:

```<code>empty = !annotation.Description.Equals("vehicle");
</code>```

What you should change is to move the line of the assigning into the loop:

```<code>foreach(/*...*/)
{
    /*...*/
    empty = !annotation.Description.Equals("vehicle");
    textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";
}
</code>```

Title: C# - boolean and if statement

Body:
I'm currently writing code analysing images with the Google API Vision on Visual Studios.
But I have a problem that occures during my loop.
The analysis returns a list of annotation ( car, vehicle, land vehicle, etc.. ) and I wanted to filter it, with an "if", so i wrote this :

var image = Google.Cloud.Vision.V1.Image.FromFile("C:\\temp\\sequence\\1.jpg");
var client = ImageAnnotatorClient.Create();
var response = client.DetectLabels(image);
CropHintsAnnotation confidence = client.DetectCropHints(image);
bool empty = false;

foreach (var annotation in response)
{
    textBox1.Text += annotation.Description + "\r\n";
    textBox1.Text += "Score : " + annotation.Score + "\r\n";
    if (annotation.Description.Equals("vehicle"))
    {
        empty = false;
    }
    else
    {
        empty = true;
    }

}
textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";

So, if I wrote this well, it should say " Empty ? false ", because the analysis returns "vehicle" once.
I tried also to replace the :

annotation.Description.Equals("vehicle")

by

annotation.Description.Contains("vehicle") == true

but no way, it still says " Empty ? true ", as it should not.

Any ideas ?

Thanks in advance for reading this, and for the help !

Body:
Not exactly sure what you are trying to do here but assuming the response has more than one item the empty variable will only represent the value for the last one.

Reason is that for each iteration of the loop when it gets to the if statement it will enter it or the else and for sure will enter one of the two, so for each iteration the value of empty will be assigned and override the previous value

As for the code itself, it is neater to write it this way:

empty = !annotation.Description.Equals("vehicle");

What you should change is to move the line of the assigning into the loop:

foreach(/*...*/)
{
    /*...*/
    empty = !annotation.Description.Equals("vehicle");
    textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";
}


问:
Recieve JSON Object with 2 Arrays
im literally new at working with JSON and I have a problem with my Web Service. With normal JSON Objects i no problems. I want to get two Arrays from the Web Service (String and Integer), so i tried to put them into two JSON Array´s and this two into a JSON Object. Now i want them to get into my Android application, but im just getting errors.

```<code>public static String constructJSON(Integer[] array, String[] array2) {
    JSONObject mainObj = new JSONObject();
    try {
    JSONObject firstArray = new JSONObject();
    firstArray.put("array0", array[0]);
    firstArray.put("array1", array[1]);
    firstArray.put("array2", array[2]);
    firstArray.put("array3", array[3]);
    firstArray.put("array4", array[4]);

    JSONObject secondArray = new JSONObject();
    secondArray.put("sArray0", array2[0]);
    secondArray.put("sArray1", array2[1]);
    secondArray.put("sArray2", array2[2]);
    secondArray.put("sArray3", array2[3]);
    secondArray.put("sArray4", array2[4]);

    JSONArray JArr = new JSONArray();
    JArr.put(firstArray);
    JArr.put(secondArray);

    mainObj.put("arrays", JArr);
    } catch (JSONException e) {
    }
    return mainObj.toString();
}
</code>```

And now the method in Android Studio:

```<code>private void getBW(String krankheit) {
        RequestParams params = new RequestParams();
        params.put("krankheit", krankheit);
        // Invoke RESTful Web Service with Http parameters
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String response) {
                try {
                    // JSON Object
                    JSONObject obj = new JSONObject(response);
                    JSONArray firstJsonArr= obj.getJSONArray("array1");
                    JSONArray secondJsonArr= obj.getJSONArray("array2");
                    for (int k = 0; k < 5; k++) {
                        Bewertung1[k] = (Integer) firstJsonArr.get(k);

                    }
                    for (int j = 0; j < 5; j++) {
                        medikament[j] = (String) secondJsonArr.get(j);

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                    e.printStackTrace();

                }

            }
        });

        }
</code>```

I tried different solution´s, but none of them worked for me. I hope you guys can help me.

答:
You switched your function istead of what you wanted it does [{}{}]

Try this:

```<code>public static String constructJSON(Integer[] array, String[] array2) {
    try {
    JSONArray firstArray = new JSONArray ();
    firstArray.put( array[0]);
    firstArray.put( array[1]);
    firstArray.put( array[2]);
    firstArray.put( array[3]);
    firstArray.put( array[4]);

    JSONArray secondArray = new JSONArray ();
    secondArray.put(array2[0]);
    secondArray.put( array2[1]);
    secondArray.put( array2[2]);
    secondArray.put( array2[3]);
    secondArray.put( array2[4]);

    JSONObject JArr = new JSONObject();
    JArr.put("firstArr",firstArray);
    JArr.put("secondArr", secondArray);
    return JArr.toString();

    } catch (JSONException e) {
    }
     return null;
}
</code>```

this will give you the JSon you wanted , and this is the main code to use it:

```<code>JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("firstArr");
JSONArray secondJsonArr= obj.getJSONArray("secondArr");
for (int k = 0; k < firstJsonArr.size(); k++) {
    Log.e("item "+k,"item data : "+firstJsonArr.get(k));
}
for (int j = 0; j < secondJsonArr.size(); j++) {
    Log.e("item "+j,"item data : "+secondJsonArr.get(j));
}
</code>```

this is good for practices but later you should use a library that does these type of things for you like Gson etc...

Title: Recieve JSON Object with 2 Arrays

Body:
im literally new at working with JSON and I have a problem with my Web Service. With normal JSON Objects i no problems. I want to get two Arrays from the Web Service (String and Integer), so i tried to put them into two JSON Array´s and this two into a JSON Object. Now i want them to get into my Android application, but im just getting errors.

public static String constructJSON(Integer[] array, String[] array2) {
    JSONObject mainObj = new JSONObject();
    try {
    JSONObject firstArray = new JSONObject();
    firstArray.put("array0", array[0]);
    firstArray.put("array1", array[1]);
    firstArray.put("array2", array[2]);
    firstArray.put("array3", array[3]);
    firstArray.put("array4", array[4]);

    JSONObject secondArray = new JSONObject();
    secondArray.put("sArray0", array2[0]);
    secondArray.put("sArray1", array2[1]);
    secondArray.put("sArray2", array2[2]);
    secondArray.put("sArray3", array2[3]);
    secondArray.put("sArray4", array2[4]);

    JSONArray JArr = new JSONArray();
    JArr.put(firstArray);
    JArr.put(secondArray);

    mainObj.put("arrays", JArr);
    } catch (JSONException e) {
    }
    return mainObj.toString();
}

And now the method in Android Studio:

private void getBW(String krankheit) {
        RequestParams params = new RequestParams();
        params.put("krankheit", krankheit);
        // Invoke RESTful Web Service with Http parameters
        AsyncHttpClient client = new AsyncHttpClient();
        client.get(url, params, new AsyncHttpResponseHandler() {

            @Override
            public void onSuccess(String response) {
                try {
                    // JSON Object
                    JSONObject obj = new JSONObject(response);
                    JSONArray firstJsonArr= obj.getJSONArray("array1");
                    JSONArray secondJsonArr= obj.getJSONArray("array2");
                    for (int k = 0; k < 5; k++) {
                        Bewertung1[k] = (Integer) firstJsonArr.get(k);

                    }
                    for (int j = 0; j < 5; j++) {
                        medikament[j] = (String) secondJsonArr.get(j);

                    }

                } catch (JSONException e) {
                    // TODO Auto-generated catch block
                    Toast.makeText(getApplicationContext(), "Error Occured [Server's JSON response might be invalid]!", Toast.LENGTH_LONG).show();
                    e.printStackTrace();

                }

            }
        });

        }

I tried different solution´s, but none of them worked for me. I hope you guys can help me.

Body:
You switched your function istead of what you wanted it does [{}{}]

Try this:

public static String constructJSON(Integer[] array, String[] array2) {
    try {
    JSONArray firstArray = new JSONArray ();
    firstArray.put( array[0]);
    firstArray.put( array[1]);
    firstArray.put( array[2]);
    firstArray.put( array[3]);
    firstArray.put( array[4]);

    JSONArray secondArray = new JSONArray ();
    secondArray.put(array2[0]);
    secondArray.put( array2[1]);
    secondArray.put( array2[2]);
    secondArray.put( array2[3]);
    secondArray.put( array2[4]);

    JSONObject JArr = new JSONObject();
    JArr.put("firstArr",firstArray);
    JArr.put("secondArr", secondArray);
    return JArr.toString();

    } catch (JSONException e) {
    }
     return null;
}

this will give you the JSon you wanted , and this is the main code to use it:

JSONObject obj = new JSONObject(response);
JSONArray firstJsonArr= obj.getJSONArray("firstArr");
JSONArray secondJsonArr= obj.getJSONArray("secondArr");
for (int k = 0; k < firstJsonArr.size(); k++) {
    Log.e("item "+k,"item data : "+firstJsonArr.get(k));
}
for (int j = 0; j < secondJsonArr.size(); j++) {
    Log.e("item "+j,"item data : "+secondJsonArr.get(j));
}

this is good for practices but later you should use a library that does these type of things for you like Gson etc...


答:
Few possibilities :

Can you check the order of vehicle.It might also be that it actually does find a description of vehicle on say index 0, but index 1 is not vehicle and hence it overwrites the previous value. If this is the case, you might wish to break out of loop when your required condition is met.

```<code>foreach (var annotation in response)
{
    // not sure if you want this to
    textBox1.Text += annotation.Description + "\r\n";
    textBox1.Text += "Score : " + annotation.Score + "\r\n";
    if (annotation.Description.Equals("vehicle",
    StringComparison.InvariantCultureIgnoreCase))
    {
        empty = false;
        textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";
        //possibly also break if you've achieved what you want.
        break;
    }
}
</code>```

Title: C# - boolean and if statement

Body:
Few possibilities :

Can you check the order of vehicle.It might also be that it actually does find a description of vehicle on say index 0, but index 1 is not vehicle and hence it overwrites the previous value. If this is the case, you might wish to break out of loop when your required condition is met.

foreach (var annotation in response)
{
    // not sure if you want this to
    textBox1.Text += annotation.Description + "\r\n";
    textBox1.Text += "Score : " + annotation.Score + "\r\n";
    if (annotation.Description.Equals("vehicle",
    StringComparison.InvariantCultureIgnoreCase))
    {
        empty = false;
        textBox1.Text += "\r\nEmpty ?       " + empty + "\r\n\r\n";
        //possibly also break if you've achieved what you want.
        break;
    }
}


问:
variable is NaN in method of mobx class(observable - mobx)
I am trying to update counter whoch observable variable, and watch the values in component, swhen I click the increment button, this.counter is NaN always and couldnt understand why.
component:

```<code>@observer
class App extends Component {
  constructor(props){
    super(props)
  }
  render() {
    const counter = this.props.appState;
    return (
        <div className={styles.description}>
          <button onClick={counter.increment.bind(this)}>+</button>
</code>```

Mobx class;

```<code>class AppState{
    @observable counter=0

   increment(){
       debugger //its null..
        this.counter++;
    }
}
export default AppState
</code>```

mainjs:

```<code>import AppState from './AppState'
...
var appState = new AppState

ReactDOM.render(
  <App appState={appState}/>,
  document.getElementById('root')
);
</code>```

how can I fix it ?

答:
I think your issue is that you need to keep a sharp tongue when it comes to what this refers to. There's no counter field in App, and that's what you end up trying refer to when you write bind(this).

Try <button onClick={() => counter.increment()}>+</button>.

Body:
I am trying to update counter whoch observable variable, and watch the values in component, swhen I click the increment button, this.counter is NaN always and couldnt understand why.
component:

@observer
class App extends Component {
  constructor(props){
    super(props)
  }
  render() {
    const counter = this.props.appState;
    return (

          <button onClick={counter.increment.bind(this)}>+</button>

Mobx class;

class AppState{
    @observable counter=0

   increment(){
       debugger //its null..
        this.counter++;
    }
}
export default AppState

mainjs:

import AppState from './AppState'
...
var appState = new AppState

ReactDOM.render(
  <App appState={appState}/>,
  document.getElementById('root')
);

how can I fix it ?


问:
Performance of Java enums
I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think).

Actually I'm trying something like:

```<code>public enum Text {
  STRING1,
  STRING2,
  STRING3;

  public String text() {
    return text;
  }

  public String setText() {
    this.text = text;
  }
}
</code>```

Then to load them I can just fill the fields:

```<code>static
{
  Text.STRING1.setText("My localized string1");
  Text.STRING2.setText("My localized string2");
  Text.STRING3.setText("My localized string3");
}
</code>```

Of course when I'll have to manage many languages I'll load them from a file.

What I'm asking is

is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects)

how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase..

in general, is it a good approach or should I look forward something else?

Thanks

答:
I agree that an enum is best for the keys of I18n rather than the strings they translate to.
However to your specific problem, you should a constructor rather than a setter.  IMHO, In fact you should use a constructor in 90%+ of cases where a value is set on construction and not changed rather than using a setter.

```<code>public enum Text {
  STRING1("String one"),
  STRING2("String two"),
  STRING3("String two");

  private final String text;
  private Text(String text) { this.text = text; }
}
</code>```

In terms of performance of creating enums, you shouldn't worry about it for a game, clarify and flexibility should be considered first.  A 1000 enums might add 1 ms to the startup time of your app. c.f. Loading the text from a file is likely to add 10 ms.

ContentLicense: CC BY-SA 2.5

Title: Performance of Java enums

Body:
I was thinking about using enum type to manage i18n in a Java game I'm developing but I was curious about performance issues that can occur when working with enums that have lots of elements (thousands I think).

Actually I'm trying something like:

public enum Text {
  STRING1,
  STRING2,
  STRING3;

  public String text() {
    return text;
  }

  public String setText() {
    this.text = text;
  }
}

Then to load them I can just fill the fields:

static
{
  Text.STRING1.setText("My localized string1");
  Text.STRING2.setText("My localized string2");
  Text.STRING3.setText("My localized string3");
}

Of course when I'll have to manage many languages I'll load them from a file.

What I'm asking is

is an obect allocated (in addition to the string) for every element? (I guess yes, since enums are implemented with objects)

how is the right element retrieved from the enum? is it static at compile time? (I mean when somewhere I use Text.STRING1.text()). So it should be constant complexity or maybe they are just replaced during the compiling phase..

in general, is it a good approach or should I look forward something else?

Thanks

Body:
I agree that an enum is best for the keys of I18n rather than the strings they translate to.
However to your specific problem, you should a constructor rather than a setter.  IMHO, In fact you should use a constructor in 90%+ of cases where a value is set on construction and not changed rather than using a setter.

public enum Text {
  STRING1("String one"),
  STRING2("String two"),
  STRING3("String two");

  private final String text;
  private Text(String text) { this.text = text; }
}

In terms of performance of creating enums, you shouldn't worry about it for a game, clarify and flexibility should be considered first.  A 1000 enums might add 1 ms to the startup time of your app. c.f. Loading the text from a file is likely to add 10 ms.


问:
Using LINQ Where result in foreach: hidden if statement, double foreach?
```<code>foreach (Person criminal in people.Where(person => person.isCriminal)
{
    // do something
}
</code>```

I have this piece of code and want to know how does it actually work. Is it equivalent to an if statement nested inside the foreach iteration or does it first loop through the list of people and repeats the loop with selected values? I care to know more about this from the perspective of efficiency.

```<code>foreach (Person criminal in people)
{
    if (criminal.isCriminal)
    {
        // do something
    }
}
</code>```

答:
To understand what happens, you must know how IEnumerables<T> work (because LINQ to Objects always work on IEnumerables<T>. IEnumerables<T> return an IEnumerator<T> which implements an iterator. This iterator is lazy, i.e. it always only yields one element of the sequence at once. There is no looping done in advance, unless you have an OrderBy or another command which requires it.

So if you have ...

```<code>foreach (string name in source.Where(x => x.IsChecked).Select(x => x.Name)) {
    Console.WriteLine(name);
}
</code>```

... this will happen: The foreach-statement requires the first item which is requested from the Select, which in turn requires one item from Where, which in turn retrieves one item from the source. The first name is printed to the console.

Then the foreach-statement requires the second item which is requested from the Select, which in turn requires one item from Where, which in turn retrieves one item from the source. The second name is printed to the console.

and so on.

This means that both of your code snipptes are logically equivalent.

Body:
foreach (Person criminal in people.Where(person => person.isCriminal)
{
    // do something
}

I have this piece of code and want to know how does it actually work. Is it equivalent to an if statement nested inside the foreach iteration or does it first loop through the list of people and repeats the loop with selected values? I care to know more about this from the perspective of efficiency.

foreach (Person criminal in people)
{
    if (criminal.isCriminal)
    {
        // do something
    }
}

Body:
To understand what happens, you must know how IEnumerables<T> work (because LINQ to Objects always work on IEnumerables<T>. IEnumerables<T> return an IEnumerator<T> which implements an iterator. This iterator is lazy, i.e. it always only yields one element of the sequence at once. There is no looping done in advance, unless you have an OrderBy or another command which requires it.

So if you have ...

foreach (string name in source.Where(x => x.IsChecked).Select(x => x.Name)) {
    Console.WriteLine(name);
}

... this will happen: The foreach-statement requires the first item which is requested from the Select, which in turn requires one item from Where, which in turn retrieves one item from the source. The first name is printed to the console.

Then the foreach-statement requires the second item which is requested from the Select, which in turn requires one item from Where, which in turn retrieves one item from the source. The second name is printed to the console.

and so on.

This means that both of your code snipptes are logically equivalent.


问:
Translate this Excel formula into VBA code (function)
This is the formula in Excel that I'm trying to convert to VBA code:

```<code>=IFERROR(IF(effDate>curDate,0,IF((curDate-effDate+1)>nDays,nDays*(nSpend/365),((nSpend/365)*(curDate-effDate+1))-IF((curDate-effDate+1)-nDays>0,nSpend/365,0))),0)
</code>```

For checking working purposes here are the values for each variable:

```<code>effDate: 1/1/17 (dimmed as value)
curDate: 3/31/17 (dimmed as value)
nDays: 60
nSpend: 1600
</code>```

Correct answer: 263

I tried to make it work for two days now and I retyped in about a hundred different way and none of them work. The code may work for one cell but it doesn't calculate correctly for the others. Or it doesn't work at all. Here is one of the examples of what I made earlier (name of the function is APFcst):

```<code>If effDate > curDate then
APFcst = 0
Exit Function
End if

If (curDate - effDate + 1) > nDays then
APFcst = nDays * (nSpend / 365)
Else
val1 = (nSpend / 365) * (curDate - effDatea + 1)
end if

if (curDate - effDate + 1) - nDays > 0 then
val2 = nSpend / 365
else
val2 = 0
end if

APFcst = val1 - val2
Exit Function
End if
</code>```

NOTE: everything is dimmed properly, the issue that I'm having is just translating the actual formula so it'll give me the correct answer.
Please help! I've been staring at this for so long that I might not see an obvious solution.

答:
Something like this, maybe possible to shorten it a touch using IIF's and perhaps, looking at using (nSpend / 365) a bit more effectively, i'll take a look again later.  I've not properly tested as yet.

```<code>Function formula_test(dtCurrentDate As Date, dtEffectiveDate As Date, nDays As Long, nSpend As Double) As Double

On Error GoTo eHandle

If dtEffectiveDate > dtCurrentDate Then
    formula_test = 0
Else
    If ((dtCurrentDate - dtEffectiveDate) + 1) > nDays Then
        formula_test = nDays * (nSpend / 365)
    Else
        formula_test = ((nSpend / 365) * (dtCurrentDate - dtEffectiveDate + 1))
        If (dtCurrentDate - dtCurrentDate + 1) - nDays > 0 Then
            formula_test = formula_test - nSpend / 365
        End If
    End If
End If

Exit Function

eHandle:
        formula_test = 0

End Function
</code>```

Body:
This is the formula in Excel that I'm trying to convert to VBA code:

=IFERROR(IF(effDate>curDate,0,IF((curDate-effDate+1)>nDays,nDays*(nSpend/365),((nSpend/365)*(curDate-effDate+1))-IF((curDate-effDate+1)-nDays>0,nSpend/365,0))),0)

For checking working purposes here are the values for each variable:

effDate: 1/1/17 (dimmed as value)
curDate: 3/31/17 (dimmed as value)
nDays: 60
nSpend: 1600

Correct answer: 263

I tried to make it work for two days now and I retyped in about a hundred different way and none of them work. The code may work for one cell but it doesn't calculate correctly for the others. Or it doesn't work at all. Here is one of the examples of what I made earlier (name of the function is APFcst):

If effDate > curDate then
APFcst = 0
Exit Function
End if

If (curDate - effDate + 1) > nDays then
APFcst = nDays * (nSpend / 365)
Else
val1 = (nSpend / 365) * (curDate - effDatea + 1)
end if

if (curDate - effDate + 1) - nDays > 0 then
val2 = nSpend / 365
else
val2 = 0
end if

APFcst = val1 - val2
Exit Function
End if

NOTE: everything is dimmed properly, the issue that I'm having is just translating the actual formula so it'll give me the correct answer.
Please help! I've been staring at this for so long that I might not see an obvious solution.

Body:
Something like this, maybe possible to shorten it a touch using IIF's and perhaps, looking at using (nSpend / 365) a bit more effectively, i'll take a look again later.  I've not properly tested as yet.

Function formula_test(dtCurrentDate As Date, dtEffectiveDate As Date, nDays As Long, nSpend As Double) As Double

On Error GoTo eHandle

If dtEffectiveDate > dtCurrentDate Then
    formula_test = 0
Else
    If ((dtCurrentDate - dtEffectiveDate) + 1) > nDays Then
        formula_test = nDays * (nSpend / 365)
    Else
        formula_test = ((nSpend / 365) * (dtCurrentDate - dtEffectiveDate + 1))
        If (dtCurrentDate - dtCurrentDate + 1) - nDays > 0 Then
            formula_test = formula_test - nSpend / 365
        End If
    End If
End If

Exit Function

eHandle:
        formula_test = 0

End Function


问:
C# Web browser invoke click
I have a web browser that navigates to this url: https://www.tinglysning.dk/m/#/soeg

I want to automate a search on that by automatically entering text into the textbox then hit the "Søg" button. I do that with this:

```<code>        webBrowser1.Document.GetElementById("adresse").InnerText = "hobrovej 35 9000";
        webBrowser1.Document.GetElementById("btn-soeg").InvokeMember("Click");
</code>```

All that is working fine, the problem is that when the button is clicked, it only shows a loading box and not the actual results

Thanks in advance

答:
The problem is, that the WebBrowser control has many security restrictions, which prevents the correct execution if single page applications (SPAs) (like the use of AJAX). https://www.tinglysning.dk/m/#/soeg seems to be an Angular application.

I assume you develop a WindowsFormsApplication (because the WPF WebBrowser does not have the GetElementById functions). I found a working solution, taken of the answer in this post: https://stackoverflow.com/a/18333982/1681616

The code snipped below disables those security restrictions and allows the Angular application to work properly. Just make sure to call  SetBrowserFeatureControl before initializing the WebBrowser control. E.g. call this method before the forms  InitializeComponent

```<code>private void SetBrowserFeatureControl()
{
    // http://msdn.microsoft.com/en-us/library/ee330720(v=vs.85).aspx

    // FeatureControl settings are per-process
    var fileName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);

    // make the control is not running inside Visual Studio Designer
    if (string.Compare(fileName, "devenv.exe", true) == 0
        || string.Compare(fileName, "XDesProc.exe", true) == 0)
        return;

    SetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION",
                                fileName,
                                GetBrowserEmulationMode()); // Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
    SetBrowserFeatureControlKey("FEATURE_AJAX_CONNECTIONEVENTS", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_MANAGE_SCRIPT_CIRCULAR_REFS", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_DOMSTORAGE ", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_GPU_RENDERING ", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_IVIEWOBJECTDRAW_DMLT9_WITH_GDI  ", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_DISABLE_LEGACY_COMPRESSION", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_LOCALMACHINE_LOCKDOWN", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_BLOCK_LMZ_OBJECT", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_BLOCK_LMZ_SCRIPT", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_DISABLE_NAVIGATION_SOUNDS", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_SCRIPTURL_MITIGATION", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_SPELLCHECKING", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_STATUS_BAR_THROTTLING", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_TABBED_BROWSING", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_VALIDATE_NAVIGATE_URL", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_WEBOC_DOCUMENT_ZOOM", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_WEBOC_POPUPMANAGEMENT", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_WEBOC_MOVESIZECHILD", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_ADDON_MANAGEMENT", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_WEBSOCKET", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_WINDOW_RESTRICTIONS ", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_XMLHTTP", fileName, 1);
}

private void SetBrowserFeatureControlKey(string feature,
                                            string appName,
                                            uint value)
{
    using (var key = Registry.CurrentUser.CreateSubKey(
                                                        string.Concat(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\", feature),
                                                        RegistryKeyPermissionCheck.ReadWriteSubTree))
    {
        key.SetValue(appName, (uint) value, RegistryValueKind.DWord);
    }
}

private uint GetBrowserEmulationMode()
{
    var browserVersion = 7;
    using (var ieKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer",
                                                        RegistryKeyPermissionCheck.ReadSubTree,
                                                        RegistryRights.QueryValues))
    {
        var version = ieKey.GetValue("svcVersion");
        if (null == version)
        {
            version = ieKey.GetValue("Version");
            if (null == version)
                throw new ApplicationException("Microsoft Internet Explorer is required!");
        }

        int.TryParse(version.ToString().Split('.')[0], out browserVersion);
    }

    uint
        mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 Standards mode. Default value for Internet Explorer 11.
    switch (browserVersion)
    {
        case 7:
            mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.
            break;
        case 8:
            mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8
            break;
        case 9:
            mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.
            break;
        case 10:
            mode = 10000; // Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 mode. Default value for Internet Explorer 10.
            break;
        default:
            // use IE11 mode by default
            break;
    }

    return mode;
}
</code>```

Title: C# Web browser invoke click

Body:
I have a web browser that navigates to this url: https://www.tinglysning.dk/m/#/soeg

I want to automate a search on that by automatically entering text into the textbox then hit the "Søg" button. I do that with this:

        webBrowser1.Document.GetElementById("adresse").InnerText = "hobrovej 35 9000";
        webBrowser1.Document.GetElementById("btn-soeg").InvokeMember("Click");

All that is working fine, the problem is that when the button is clicked, it only shows a loading box and not the actual results

Thanks in advance

Body:
The problem is, that the WebBrowser control has many security restrictions, which prevents the correct execution if single page applications (SPAs) (like the use of AJAX). https://www.tinglysning.dk/m/#/soeg seems to be an Angular application.

I assume you develop a WindowsFormsApplication (because the WPF WebBrowser does not have the GetElementById functions). I found a working solution, taken of the answer in this post: https://stackoverflow.com/a/18333982/1681616

The code snipped below disables those security restrictions and allows the Angular application to work properly. Just make sure to call  SetBrowserFeatureControl before initializing the WebBrowser control. E.g. call this method before the forms  InitializeComponent

private void SetBrowserFeatureControl()
{
    // http://msdn.microsoft.com/en-us/library/ee330720(v=vs.85).aspx

    // FeatureControl settings are per-process
    var fileName = Path.GetFileName(Process.GetCurrentProcess().MainModule.FileName);

    // make the control is not running inside Visual Studio Designer
    if (string.Compare(fileName, "devenv.exe", true) == 0
        || string.Compare(fileName, "XDesProc.exe", true) == 0)
        return;

    SetBrowserFeatureControlKey("FEATURE_BROWSER_EMULATION",
                                fileName,
                                GetBrowserEmulationMode()); // Webpages containing standards-based !DOCTYPE directives are displayed in IE10 Standards mode.
    SetBrowserFeatureControlKey("FEATURE_AJAX_CONNECTIONEVENTS", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_ENABLE_CLIPCHILDREN_OPTIMIZATION", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_MANAGE_SCRIPT_CIRCULAR_REFS", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_DOMSTORAGE ", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_GPU_RENDERING ", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_IVIEWOBJECTDRAW_DMLT9_WITH_GDI  ", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_DISABLE_LEGACY_COMPRESSION", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_LOCALMACHINE_LOCKDOWN", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_BLOCK_LMZ_OBJECT", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_BLOCK_LMZ_SCRIPT", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_DISABLE_NAVIGATION_SOUNDS", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_SCRIPTURL_MITIGATION", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_SPELLCHECKING", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_STATUS_BAR_THROTTLING", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_TABBED_BROWSING", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_VALIDATE_NAVIGATE_URL", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_WEBOC_DOCUMENT_ZOOM", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_WEBOC_POPUPMANAGEMENT", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_WEBOC_MOVESIZECHILD", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_ADDON_MANAGEMENT", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_WEBSOCKET", fileName, 1);
    SetBrowserFeatureControlKey("FEATURE_WINDOW_RESTRICTIONS ", fileName, 0);
    SetBrowserFeatureControlKey("FEATURE_XMLHTTP", fileName, 1);
}

private void SetBrowserFeatureControlKey(string feature,
                                            string appName,
                                            uint value)
{
    using (var key = Registry.CurrentUser.CreateSubKey(
                                                        string.Concat(@"Software\Microsoft\Internet Explorer\Main\FeatureControl\", feature),
                                                        RegistryKeyPermissionCheck.ReadWriteSubTree))
    {
        key.SetValue(appName, (uint) value, RegistryValueKind.DWord);
    }
}

private uint GetBrowserEmulationMode()
{
    var browserVersion = 7;
    using (var ieKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Internet Explorer",
                                                        RegistryKeyPermissionCheck.ReadSubTree,
                                                        RegistryRights.QueryValues))
    {
        var version = ieKey.GetValue("svcVersion");
        if (null == version)
        {
            version = ieKey.GetValue("Version");
            if (null == version)
                throw new ApplicationException("Microsoft Internet Explorer is required!");
        }

        int.TryParse(version.ToString().Split('.')[0], out browserVersion);
    }

    uint
        mode = 11000; // Internet Explorer 11. Webpages containing standards-based !DOCTYPE directives are displayed in IE11 Standards mode. Default value for Internet Explorer 11.
    switch (browserVersion)
    {
        case 7:
            mode = 7000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE7 Standards mode. Default value for applications hosting the WebBrowser Control.
            break;
        case 8:
            mode = 8000; // Webpages containing standards-based !DOCTYPE directives are displayed in IE8 mode. Default value for Internet Explorer 8
            break;
        case 9:
            mode = 9000; // Internet Explorer 9. Webpages containing standards-based !DOCTYPE directives are displayed in IE9 mode. Default value for Internet Explorer 9.
            break;
        case 10:
            mode = 10000; // Internet Explorer 10. Webpages containing standards-based !DOCTYPE directives are displayed in IE10 mode. Default value for Internet Explorer 10.
            break;
        default:
            // use IE11 mode by default
            break;
    }

    return mode;
}


问:
RhinoMocks VerifyAllExpectations fails for multiple Expects on stubbed method
Dear RhinoMocks users out there. I am a newbie to RhinoMocks and have a problem wrapping my head around something. I need to test two methods in a class, on of them calls the other multiple times. I already tested the one called multiple times separately, the setup is somewhat complex so the idea for testing the other method was to stub the method that has been tested already. Here is a minimal example:

```<code>     public class TestedClass
     {
         public virtual void DoSthOnce(List<int> listParam)
         {
             foreach (var param in listParam)
                DoSthMultipleTimes(param);
         }

         public virtual void DoSthMultipleTimes(int intParam)
         {
             Console.WriteLine("param: " + intParam);
         }
    }
</code>```

I.e. DoSthMultipleTimes() is already tested. The following test code works and verifies that the DoSthMultipletimes()-Method was called for each element of the list that was provided as parameter to DoSthOnce().

```<code>    var paramList = Enumerable.Range(1, 10).ToList();
    var mock = MockRepository.GeneratePartialMock<TestedClass>();
    mock.Stub(m => m.DoSthMultipleTimes(Arg<int>.Is.Anything))
        .WhenCalled(mi =>
        {
            // Only for debug; this method is empty in the actual test code.
            Console.WriteLine("Stub called with " + mi.Arguments[0]);
        });

     mock.DoSthOnce(paramList);

     // This will not throw an exception
     foreach (var param in paramList)
         mock.AssertWasCalled(m => m.DoSthMultipleTimes(param));
</code>```

The output is as expected:

```<code>    Stub called with 1
    Stub called with 2
    Stub called with 3
    Stub called with 4
    Stub called with 5
    Stub called with 6
    Stub called with 7
    Stub called with 8
    Stub called with 9
    Stub called with 10
</code>```

However, the following fails throwing an exception although it should be the same thing as above, at least from my understanding:

```<code>    var paramList = Enumerable.Range(1, 10).ToList();
    var mock = MockRepository.GeneratePartialMock<TestedClass>();
    mock.Stub(/*same as above*/).WhenCalled(/*same as above*/);
    foreach (var param in paramList)
        mock.Expect(m => m.DoSthMultipleTimes(param));

    mock.DoSthOnce(paramList);
    mock.VerifyAllExpectations();
</code>```

The console output is identical, but an ExpectationViolationException is thrown by VerifyAllExpectations(). Additional information is:

```<code>    TestedClass.DoSthMultipleTimes(1); Expected #1, Actual #0.
    TestedClass.DoSthMultipleTimes(2); Expected #1, Actual #0.
    ...
    TestedClass.DoSthMultipleTimes(10); Expected #1, Actual #0.
</code>```

The parameters are correct, but what exactly is the problem here?

答:
I'm guessing because of your stub itself.

This piece of code would register the various expectations that you want:

```<code>foreach (var param in paramList)
    mock.Expect(m => m.DoSthMultipleTimes(param));
</code>```

This would set the Expectation that DoSthMultipleTimes(1), DoSthMultipleTimes(2), etc are being called.

However your Mock.Stub code would override / stubbing the implementation itself. This resulted that Rhino would execute this override/method (and not calling the original DoSthMultipleTimes method of the original class). As such, when VerifyAllExpectation being called, none of the method in original class was called.

You could verify the above by removing the following:

```<code>mock.Stub(m => m.DoSthMultipleTimes(Arg<int>.Is.Anything))
    .WhenCalled(mi =>
    {
        // Only for debug; this method is empty in the actual test code.
        Console.WriteLine("Stub called with " + mi.Arguments[0]);
    });
</code>```

Since you are using PartialMock, if you are not implementing the stub, it would call the original method. And supposedly, it would now successfully pass all the expectation.

(NB: beware when using PartialMock as it would run the original method if not being stubbed (ie: database call, etc)).

Body:
Dear RhinoMocks users out there. I am a newbie to RhinoMocks and have a problem wrapping my head around something. I need to test two methods in a class, on of them calls the other multiple times. I already tested the one called multiple times separately, the setup is somewhat complex so the idea for testing the other method was to stub the method that has been tested already. Here is a minimal example:

     public class TestedClass
     {
         public virtual void DoSthOnce(List<int> listParam)
         {
             foreach (var param in listParam)
                DoSthMultipleTimes(param);
         }

         public virtual void DoSthMultipleTimes(int intParam)
         {
             Console.WriteLine("param: " + intParam);
         }
    }

I.e. DoSthMultipleTimes() is already tested. The following test code works and verifies that the DoSthMultipletimes()-Method was called for each element of the list that was provided as parameter to DoSthOnce().

    var paramList = Enumerable.Range(1, 10).ToList();
    var mock = MockRepository.GeneratePartialMock<TestedClass>();
    mock.Stub(m => m.DoSthMultipleTimes(Arg<int>.Is.Anything))
        .WhenCalled(mi =>
        {
            // Only for debug; this method is empty in the actual test code.
            Console.WriteLine("Stub called with " + mi.Arguments[0]);
        });

     mock.DoSthOnce(paramList);

     // This will not throw an exception
     foreach (var param in paramList)
         mock.AssertWasCalled(m => m.DoSthMultipleTimes(param));

The output is as expected:

    Stub called with 1
    Stub called with 2
    Stub called with 3
    Stub called with 4
    Stub called with 5
    Stub called with 6
    Stub called with 7
    Stub called with 8
    Stub called with 9
    Stub called with 10

However, the following fails throwing an exception although it should be the same thing as above, at least from my understanding:

    var paramList = Enumerable.Range(1, 10).ToList();
    var mock = MockRepository.GeneratePartialMock<TestedClass>();
    mock.Stub(/*same as above*/).WhenCalled(/*same as above*/);
    foreach (var param in paramList)
        mock.Expect(m => m.DoSthMultipleTimes(param));

    mock.DoSthOnce(paramList);
    mock.VerifyAllExpectations();

The console output is identical, but an ExpectationViolationException is thrown by VerifyAllExpectations(). Additional information is:

    TestedClass.DoSthMultipleTimes(1); Expected #1, Actual #0.
    TestedClass.DoSthMultipleTimes(2); Expected #1, Actual #0.
    ...
    TestedClass.DoSthMultipleTimes(10); Expected #1, Actual #0.

The parameters are correct, but what exactly is the problem here?

Body:
I'm guessing because of your stub itself.

This piece of code would register the various expectations that you want:

foreach (var param in paramList)
    mock.Expect(m => m.DoSthMultipleTimes(param));

This would set the Expectation that DoSthMultipleTimes(1), DoSthMultipleTimes(2), etc are being called.

However your Mock.Stub code would override / stubbing the implementation itself. This resulted that Rhino would execute this override/method (and not calling the original DoSthMultipleTimes method of the original class). As such, when VerifyAllExpectation being called, none of the method in original class was called.

You could verify the above by removing the following:

mock.Stub(m => m.DoSthMultipleTimes(Arg<int>.Is.Anything))
    .WhenCalled(mi =>
    {
        // Only for debug; this method is empty in the actual test code.
        Console.WriteLine("Stub called with " + mi.Arguments[0]);
    });

Since you are using PartialMock, if you are not implementing the stub, it would call the original method. And supposedly, it would now successfully pass all the expectation.

(NB: beware when using PartialMock as it would run the original method if not being stubbed (ie: database call, etc)).


问:
how to reset the column value
i have table with 9 records that 2 records with _id = 1 was deleted:

```<code>id   |   name    |    index    |    _id
 1        a            1             1
 8        b            3             1
 9        c            7             1
 10       d            4             1
 15       e            2             1
 16       d            1             2
 17       e            2             2
</code>```

and I want to reset the index of _id = 1 like this:

```<code>id   |   name    |    index    |    _id
 1        a            1             1
 8        b            2             1
 9        c            3             1
 10       d            4             1
 15       e            5             1
 16       d            1             2
 17       e            2             2
</code>```

i 'd use this query

```<code>declare @_idCount int = (select count(*) from tbl where _id = 1),
        @index int = 1

while(@_idCount > 0)
    begin
        update tbl
        set code = @index
        where _id = 1

        set @index = @index + 1
        set @picCount = @picCount - 1
    end
</code>```

but this code is set all of record with same code.
what can i do to solve it?

答:
You can simply use ROW_NUMBER:

```<code>WITH CTE AS
(
    SELECT id,
           name,
           [index],
           [_id],
           new_index = ROW_NUMBER() OVER(PARTITION BY [_id]
                                         ORDER BY [id])
    FROM dbo.tbl
)
UPDATE CTE
SET [index] = new_index;
</code>```

Title: how to reset the column value

Body:
i have table with 9 records that 2 records with _id = 1 was deleted:

id   |   name    |    index    |    _id
 1        a            1             1
 8        b            3             1
 9        c            7             1
 10       d            4             1
 15       e            2             1
 16       d            1             2
 17       e            2             2

and I want to reset the index of _id = 1 like this:

id   |   name    |    index    |    _id
 1        a            1             1
 8        b            2             1
 9        c            3             1
 10       d            4             1
 15       e            5             1
 16       d            1             2
 17       e            2             2

i 'd use this query

declare @_idCount int = (select count(*) from tbl where _id = 1),
        @index int = 1

while(@_idCount > 0)
    begin
        update tbl
        set code = @index
        where _id = 1

        set @index = @index + 1
        set @picCount = @picCount - 1
    end

but this code is set all of record with same code.
what can i do to solve it?

Body:
You can simply use ROW_NUMBER:

WITH CTE AS
(
    SELECT id,
           name,
           [index],
           [_id],
           new_index = ROW_NUMBER() OVER(PARTITION BY [_id]
                                         ORDER BY [id])
    FROM dbo.tbl
)
UPDATE CTE
SET [index] = new_index;


问:
getting an exception in jBoss server as java.lang.RuntimeException: Error unmarshalling file:/opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
I have 2 instance in one instance my application is running fine but in another instance its giving an exception .I am working on red-hat with jboss-5.1.0.GA version.

the Exception is as follow

```<code>19:59:05,178 INFO  [ServerImpl] Server Temp Deploy Dir: /opt/jboss-5.1.0.GA/server/port_1/tmp/deploy
19:59:05,771 INFO  [ServerImpl] Starting Microcontainer, bootstrapURL=file:/opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
Failed to boot JBoss:
java.lang.RuntimeException: Error unmarshalling file:/opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
        at org.jboss.bootstrap.xml.BootstrapParser.parse(BootstrapParser.java:60)
        at org.jboss.bootstrap.microcontainer.ServerImpl.doStart(ServerImpl.java:123)
        at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:450)
        at org.jboss.Main.boot(Main.java:221)
        at org.jboss.Main$1.run(Main.java:556)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.jboss.xb.binding.JBossXBException: Failed to parse source: file:/opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:177)
        at org.jboss.xb.binding.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:119)
        at org.jboss.bootstrap.xml.BootstrapParser.parse(BootstrapParser.java:53)
        ... 5 more
Caused by: java.io.FileNotFoundException: /opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
        at org.jboss.net.protocol.file.FileURLConnection.connect(FileURLConnection.java:105)
        at org.jboss.net.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:112)
        at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
        at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
        at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:173)
        ... 7 more
19:59:05,870 INFO  [ServerImpl] Runtime shutdown hook called, forceHalt: true
19:59:05,896 INFO  [ServerImpl] Shutdown complete
Shutdown complete
Halting VM
bash-3.2#
</code>```

答:
Pay attention to this:

```<code>Caused by: java.io.FileNotFoundException: /opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
</code>```

Also, be aware that you are using a version which is really old.

Body:
I have 2 instance in one instance my application is running fine but in another instance its giving an exception .I am working on red-hat with jboss-5.1.0.GA version.

the Exception is as follow

19:59:05,178 INFO  [ServerImpl] Server Temp Deploy Dir: /opt/jboss-5.1.0.GA/server/port_1/tmp/deploy
19:59:05,771 INFO  [ServerImpl] Starting Microcontainer, bootstrapURL=file:/opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
Failed to boot JBoss:
java.lang.RuntimeException: Error unmarshalling file:/opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
        at org.jboss.bootstrap.xml.BootstrapParser.parse(BootstrapParser.java:60)
        at org.jboss.bootstrap.microcontainer.ServerImpl.doStart(ServerImpl.java:123)
        at org.jboss.bootstrap.AbstractServerImpl.start(AbstractServerImpl.java:450)
        at org.jboss.Main.boot(Main.java:221)
        at org.jboss.Main$1.run(Main.java:556)
        at java.lang.Thread.run(Thread.java:748)
Caused by: org.jboss.xb.binding.JBossXBException: Failed to parse source: file:/opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:177)
        at org.jboss.xb.binding.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:119)
        at org.jboss.bootstrap.xml.BootstrapParser.parse(BootstrapParser.java:53)
        ... 5 more
Caused by: java.io.FileNotFoundException: /opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml
        at org.jboss.net.protocol.file.FileURLConnection.connect(FileURLConnection.java:105)
        at org.jboss.net.protocol.file.FileURLConnection.getInputStream(FileURLConnection.java:112)
        at org.apache.xerces.impl.XMLEntityManager.setupCurrentEntity(Unknown Source)
        at org.apache.xerces.impl.XMLVersionDetector.determineDocVersion(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XML11Configuration.parse(Unknown Source)
        at org.apache.xerces.parsers.XMLParser.parse(Unknown Source)
        at org.apache.xerces.parsers.AbstractSAXParser.parse(Unknown Source)
        at org.apache.xerces.jaxp.SAXParserImpl$JAXPSAXParser.parse(Unknown Source)
        at org.jboss.xb.binding.parser.sax.SaxJBossXBParser.parse(SaxJBossXBParser.java:173)
        ... 7 more
19:59:05,870 INFO  [ServerImpl] Runtime shutdown hook called, forceHalt: true
19:59:05,896 INFO  [ServerImpl] Shutdown complete
Shutdown complete
Halting VM
bash-3.2#

Body:
Pay attention to this:

Caused by: java.io.FileNotFoundException: /opt/jboss-5.1.0.GA/server/port_1/conf/bootstrap.xml

Also, be aware that you are using a version which is really old.


问:
'Uncaught ReferenceError: jQuery is not defined' with create-react-app
Am building a React App using create-react-app so the app is server ready.

When importing a bootstrap javascript plugin such as 'affix.js', I get the error 'Uncaught ReferenceError: jQuery is not defined', and the page no longer loads.

Am importing all the modules through the index.js file since with the create-react-app it dosent seem to load the 'src' and 'link' imports from the index.html file.

Am importing the bootstrap plugin like so:
import 'bootstrap/js/affix.js'

Have tried importing jquery in the following ways, at the top of the index.js file but none is working:

import jquery from 'jquery'

import jquery from 'jquery', window.$ = window.jQuery = jquery;

import jQuery from 'jquery'

import $ from 'jquery'

import 'jquery/dist/jquery.js';

require('./node_modules/jquery/dist/jquery.js')

Any ideas?

答:
In case someone land here. I had resolved similar issue for 'create-react-app' by using this:

```<code>import jQuery from 'jquery';
window.jQuery = jQuery;
</code>```

and for importing other packages that needs jQuery you should import those packages after this, in affix.js case,

```<code>require 'bootstrap/js/affix.js';
</code>```

Body:
In case someone land here. I had resolved similar issue for 'create-react-app' by using this:

import jQuery from 'jquery';
window.jQuery = jQuery;

and for importing other packages that needs jQuery you should import those packages after this, in affix.js case,

require 'bootstrap/js/affix.js';


问:
How to solve 'Error in plot.new() : figure margins too large' in rstudio?
I've read all posts relevant to this problem.But the truth is: if you have lots of variables to plot,this problem still occur.

My laptop resolution is 1080p, I open rstudio and run below script:

```<code>a<-iris[,1:4]
> a<-t(a)
> a<-as.data.frame(a)
> pairs(a)
Error in plot.new() : figure margins too large
</code>```

I  have tried all the solution in this site from similar questions, none is workable.

I really need this plot but cannot get it.How to solve this problem?

答:
I'll answer in two ways. Firstly, as you're using the iris dataset, are you sure you want a pairs plot of the transpose of a? That would mean comparing the individual flowers, rather than the features (like sepal length etc). Is this what you want instead?

```<code>> a <- iris[,1:4]
> pairs(a)
</code>```

This will give you a 4x4 pairs plot (comparing the flower features). If however, you really do want a pairs plot between observations instead of features, then you're asking for a 150x150 pairs plot! It seems to me that the only way to do that is to generate multiple pairs plots, each one for a subset of those 150 items.

Body:
I've read all posts relevant to this problem.But the truth is: if you have lots of variables to plot,this problem still occur.

My laptop resolution is 1080p, I open rstudio and run below script:

a<-iris[,1:4]
> a<-t(a)
> a<-as.data.frame(a)
> pairs(a)
Error in plot.new() : figure margins too large

I  have tried all the solution in this site from similar questions, none is workable.

I really need this plot but cannot get it.How to solve this problem?

Body:
I'll answer in two ways. Firstly, as you're using the iris dataset, are you sure you want a pairs plot of the transpose of a? That would mean comparing the individual flowers, rather than the features (like sepal length etc). Is this what you want instead?

> a <- iris[,1:4]
> pairs(a)

This will give you a 4x4 pairs plot (comparing the flower features). If however, you really do want a pairs plot between observations instead of features, then you're asking for a 150x150 pairs plot! It seems to me that the only way to do that is to generate multiple pairs plots, each one for a subset of those 150 items.


问:
Twig not working in Yii2
I want to use Twig in Yii2 framework but it isn't working.

I am using yii2-app-advanced as the base project but I am new in the Yii world so I think I am not configuring Twig in the right way.

First I downloaded it using:

```<code>composer require yiisoft/yii2-twig
</code>```

Then I follow this instructions but it's not easy to understand:
https://github.com/yiisoft/yii2-twig/blob/HEAD/docs/guide/installation.md#configuring-application

It says:
In order to start using Twig you need to configure view component like the following:

```<code>[
    'components' => [
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
                    'globals' => [
                        'html' => ['class' => '\yii\helpers\Html'],
                    ],
                    'uses' => ['yii\bootstrap'],
                ],
                // ...
            ],
        ],
    ],
]
</code>```

In which file I have to paste this code?

In my index.php file I added the following code but it is not working:

```<code>{% if true %}
    <p>It is true.</p>
{% else %}
    <p>It is false.</p>
{% endif %}
</code>```

答:
I solved it doing this:

I modified the file backend/config/main-local-php:

```<code><?php

$config = [
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'CPeTotdTU98geIyM7q0PljmCpJbupPN4',
        ],
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
                    'globals' => [
                        'html' => ['class' => '\yii\helpers\Html'],
                    ],
                    'uses' => ['yii\bootstrap'],
                ],
                // ...
            ],
        ],
    ],
];

if (!YII_ENV_TEST) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
    ];
}

return $config;
</code>```

The SiteController.php file has the actionIndex() function. I added the extension .twig:

```<code>public function actionIndex()
{
    return $this->render('index.twig');
}
</code>```

And then I modified the name of the file backend/views/sire/index.php to index.twig.

Title: Twig not working in Yii2

Body:
I want to use Twig in Yii2 framework but it isn't working.

I am using yii2-app-advanced as the base project but I am new in the Yii world so I think I am not configuring Twig in the right way.

First I downloaded it using:

composer require yiisoft/yii2-twig

Then I follow this instructions but it's not easy to understand:
https://github.com/yiisoft/yii2-twig/blob/HEAD/docs/guide/installation.md#configuring-application

It says:
In order to start using Twig you need to configure view component like the following:

[
    'components' => [
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
                    'globals' => [
                        'html' => ['class' => '\yii\helpers\Html'],
                    ],
                    'uses' => ['yii\bootstrap'],
                ],
                // ...
            ],
        ],
    ],
]

In which file I have to paste this code?

In my index.php file I added the following code but it is not working:

{% if true %}

It is true.

{% else %}

It is false.

{% endif %}

Body:
I solved it doing this:

I modified the file backend/config/main-local-php:

<?php

$config = [
    'components' => [
        'request' => [
            // !!! insert a secret key in the following (if it is empty) - this is required by cookie validation
            'cookieValidationKey' => 'CPeTotdTU98geIyM7q0PljmCpJbupPN4',
        ],
        'view' => [
            'class' => 'yii\web\View',
            'renderers' => [
                'twig' => [
                    'class' => 'yii\twig\ViewRenderer',
                    'cachePath' => '@runtime/Twig/cache',
                    // Array of twig options:
                    'options' => [
                        'auto_reload' => true,
                    ],
                    'globals' => [
                        'html' => ['class' => '\yii\helpers\Html'],
                    ],
                    'uses' => ['yii\bootstrap'],
                ],
                // ...
            ],
        ],
    ],
];

if (!YII_ENV_TEST) {
    // configuration adjustments for 'dev' environment
    $config['bootstrap'][] = 'debug';
    $config['modules']['debug'] = [
        'class' => 'yii\debug\Module',
    ];

    $config['bootstrap'][] = 'gii';
    $config['modules']['gii'] = [
        'class' => 'yii\gii\Module',
    ];
}

return $config;

The SiteController.php file has the actionIndex() function. I added the extension .twig:

public function actionIndex()
{
    return $this->render('index.twig');
}

And then I modified the name of the file backend/views/sire/index.php to index.twig.


问:
Wpf- Unable to cast MenuItem to Listbox?
I am getting a very strange exception.
I get the exception:

"'Set connectionId threw an exception.' Line number '26' and line position '34'."

When I look at the Inner Exception I get:

"Unable to cast object of type 'System.Windows.Controls.MenuItem' to type 'System.Windows.Controls.ListBox'."

I have narrowed the cause of the exception to the MenuItem in the TreeViewItem style contained in this TreeView:

```<code><TreeView x:Name="ProjectElementTreeView" ItemsSource="{Binding ProjectElementCollection}"  DisplayMemberPath="Name" Padding="0" SelectedItemChanged="ProjectElementTreeView_SelectedItemChanged" GotKeyboardFocus="ProjectElementTreeView_GotKeyboardFocus">
        <TreeView.Resources>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="HorizontalAlignment" Value="Left" />
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Name="AddProjectElementMenuItem" Header="Add" Click="AddProjectElementMenuItem_Click"/>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.Resources>
    </TreeView>
</code>```

The exception only occurs when the MenuItem has a click event handler and is thrown even when the click event handler does not contain any code.

答:
I got the same exception as you did. After looking closer at the code, this feels like a situation where you would get

"The event 'Click' cannot be specified
  on a Target tag in a Style. Use an
  EventSetter instead."

I'm not sure why that doesn't apply here.

Anyway, using an EventSetter works

```<code><Setter Property="ContextMenu">
    <Setter.Value>
        <ContextMenu>
            <MenuItem Name="AddProjectElementMenuItem" Header="Add">
                <MenuItem.Style>
                    <Style TargetType="MenuItem">
                        <EventSetter Event="Click" Handler="AddProjectElementMenuItem_Click"/>
                    </Style>
                </MenuItem.Style>
            </MenuItem>
        </ContextMenu>
    </Setter.Value>
</Setter>
</code>```

Body:
I am getting a very strange exception.
I get the exception:

"'Set connectionId threw an exception.' Line number '26' and line position '34'."

When I look at the Inner Exception I get:

"Unable to cast object of type 'System.Windows.Controls.MenuItem' to type 'System.Windows.Controls.ListBox'."

I have narrowed the cause of the exception to the MenuItem in the TreeViewItem style contained in this TreeView:

<TreeView x:Name="ProjectElementTreeView" ItemsSource="{Binding ProjectElementCollection}"  DisplayMemberPath="Name" Padding="0" SelectedItemChanged="ProjectElementTreeView_SelectedItemChanged" GotKeyboardFocus="ProjectElementTreeView_GotKeyboardFocus">
        <TreeView.Resources>

        </TreeView.Resources>
    </TreeView>

The exception only occurs when the MenuItem has a click event handler and is thrown even when the click event handler does not contain any code.

Body:
I got the same exception as you did. After looking closer at the code, this feels like a situation where you would get

"The event 'Click' cannot be specified
  on a Target tag in a Style. Use an
  EventSetter instead."

I'm not sure why that doesn't apply here.

Anyway, using an EventSetter works

<Setter Property="ContextMenu">
    <Setter.Value>
        <ContextMenu>
            <MenuItem Name="AddProjectElementMenuItem" Header="Add">
                <MenuItem.Style>
                    <Style TargetType="MenuItem">
                        <EventSetter Event="Click" Handler="AddProjectElementMenuItem_Click"/>
                    </Style>
                </MenuItem.Style>
            </MenuItem>
        </ContextMenu>
    </Setter.Value>
</Setter>


问:
htaccess redirect to parent folder index.php if does not exist
I'm building a web api via php.  One of the things I'm struggling with is setting up the htaccess file to redirect to index.php of the parent folder when something does not exist.  My folder structure looks like this:

```<code>/SkedApi/
    index.php
    /Users/
        index.php
</code>```

This is what I have so far, but it isn't working:

```<code>RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [NC,L]
</code>```

Currently if it doesn't exist it redirects it all the way back to /SkedApi/index.php.  But in the case of /Users/3 I need it to redirect to /Users/index.php.  /Users/ works correctly and directs it to /Users/index.php.

答:
you can use absolute paths:

```<code>RewriteRule ^Users/(.*)$ /Users/index.php [NC,L]
</code>```

for users and

```<code>RewriteRule ^(.*)$ /index.php [NC,L]
</code>```

for the rest.

Comment: You need the parenthesis in the regexp if you want to reuse that. Like this: RewriteRule ^User/(.*)$ /User/index.php?uid=$1 [NC,L] Unless yo can go for the simple ^User/

Edit: if you want to implement some kind of controller logic, you can catch them with regexps.

Considering your controller is a single word:

```<code>RewriteRule ^([^/]*)/(.*)$ /Users/index.php?mycontroler=$1&mydata=$2 [NC,L]
</code>```

of course you can omit $1 $2 if your framework gets this info from the query string directly.

```<code>RewriteRule ^([^/]*) /Users/index.php [NC,L]
</code>```

Body:
I'm building a web api via php.  One of the things I'm struggling with is setting up the htaccess file to redirect to index.php of the parent folder when something does not exist.  My folder structure looks like this:

/SkedApi/
    index.php
    /Users/
        index.php

This is what I have so far, but it isn't working:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [NC,L]

Currently if it doesn't exist it redirects it all the way back to /SkedApi/index.php.  But in the case of /Users/3 I need it to redirect to /Users/index.php.  /Users/ works correctly and directs it to /Users/index.php.

Body:
you can use absolute paths:

RewriteRule ^Users/(.*)$ /Users/index.php [NC,L]

for users and

RewriteRule ^(.*)$ /index.php [NC,L]

for the rest.

Comment: You need the parenthesis in the regexp if you want to reuse that. Like this: RewriteRule ^User/(.*)$ /User/index.php?uid=$1 [NC,L] Unless yo can go for the simple ^User/

Edit: if you want to implement some kind of controller logic, you can catch them with regexps.

Considering your controller is a single word:

RewriteRule ^([^/]*)/(.*)$ /Users/index.php?mycontroler=$1&mydata=$2 [NC,L]

of course you can omit $1 $2 if your framework gets this info from the query string directly.

RewriteRule ^([^/]*) /Users/index.php [NC,L]


问:
PHP + MySQL - What column type should be used to store serialized objects?
With PHP, I am storing serialized objects in a MySQL database.

What column type should I use? I am currently using "LONGTEXT" since basically it's a string.

It's working but I worry that bigger objects might not save correctly.

What column type should I use?

答:
BLOB, can hold various types of data.

https://dev.mysql.com/doc/refman/5.7/en/blob.html

This was the column type i used for storing objects in a database recently.

Hope this helps


问:
System.Data.SqlClient.SqlException: Incorrect syntax near '*'
I'm trying to create session, using the following code:</p>

```<code>SqlConnection conn = new SqlConnection("Data Source=THIRD-I;Initial Catalog=sessionlogin;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("Select (*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString()== "1")
{
    Session["user"] = UserName.Text;
    Response.Redirect("welcome.aspx");
}
</code>```

答: You need count of records from the data adapter. So the SQL query should be new SqlDataAdapter("Select count(*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);

Body:
I'm trying to create session, using the following code:

SqlConnection conn = new SqlConnection("Data Source=THIRD-I;Initial Catalog=sessionlogin;Integrated Security=True;");
SqlDataAdapter sda = new SqlDataAdapter("Select (*) From logintable Where username='" + UserName.Text + "' and password='" + Password.Text + "'",conn);
DataTable dt = new DataTable();
sda.Fill(dt);
if (dt.Rows[0][0].ToString()== "1")
{
    Session["user"] = UserName.Text;
    Response.Redirect("welcome.aspx");
}