问:
Camel JMS Component with Spring on Weblogic Server
I could not found any decent, clear example to learn JMS component with Spring configuration. So I wrote something like this:

```<code><bean id="weblogic" class="org.apache.camel.component.jms.JmsComponent">
    <property name="connectionFactory" ref="jmsConnectionFactory"/>
</bean>

<bean id="jmsJndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
        <props>
            <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
            <prop key="java.naming.provider.url">t3://${ip}:${port}</prop>
        </props>
    </property>
</bean>
<bean id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate" ref="jmsJndiTemplate"/>
    <property name="jndiName" value="jms/cdrPreMO-connfact-jndi"/>
</bean>

<camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">

    <camel:endpoint id="jmsQueue" uri="weblogic:queue:jms/cdrPreMO-queue-jndi"/>

    <route>
        <from ref="jmsQueue"/>
        <bean ref="test" method="writeFile"/>
        <to uri="log:errors?level=ERROR"/>
    </route>
</camelContext>
</code>```

But it gives the exception :

```<code>Caused by: javax.naming.NameNotFoundException: Unable to resolve 'weblogic.jms.backend.jms'. Resolved 'weblogic.jms.backend'; remaining name 'jms'
    at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
    at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:252)
    at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
    at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
    at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
    at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
    at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
    at weblogic.jndi.internal.WLEventContextImpl.lookup(WLEventContextImpl.java:254)
    at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:393)
    at weblogic.jms.frontend.FEManager.destinationCreate(FEManager.java:287)
    ... 8 more
</code>```

JMS Conf is true(ip port and jndi names). It is getting the  connection, and the session but gives the exception
Could someone tell me what are my mistakes?

Thanx

EDIT: fix applied according to the comment of Claus.

答:
Although question is pretty old, posting this solution for other users if they get this error. I ran into the this issue on Camel 2.19 version while trying to look up weblogic queue in weblogic 12c version. The lookup that happens here is most likely not a typical JNDI lookup when resolving queue destination in Weblogic.
The end point uri should contain the queue details as follows :

```<code>jms_server_name/jms_module_name!queue_name
</code>```

For example if queue name is TestRequestQueue, created under a module named sample_jms_module and the JMS server is named sample_jms_server in Weblogic, then the uri would need to be as follows :

```<code><camel:endpoint id="jmsQueue" uri="weblogic:queue:sample_jms_server/sample_jms_module!TestRequestQueue"/>
</code>```

In the prefix portion of the uri weblogic:queue:, the component name can be anything as long as it refers to the created component. It needn't necessarily be weblogic. For example, if the JmsComponent is named as test-jms, the uri will need to be declared with prefix as test-jms:queue: .

Name of the JMS server in weblogic can be obtained from Weblogic console by navigating to the below path :
   Services -> Messaging -> JMS Servers

Name of the queue, not the JNDI name, can be obtained from Weblogic console by navigating to the queue and clicking on Monitoring tab. This tab shows the destination name of the queue in the name column.

Body:
I could not found any decent, clear example to learn JMS component with Spring configuration. So I wrote something like this:

<bean id="weblogic" class="org.apache.camel.component.jms.JmsComponent">
    <property name="connectionFactory" ref="jmsConnectionFactory"/>
</bean>

<bean id="jmsJndiTemplate" class="org.springframework.jndi.JndiTemplate">
    <property name="environment">
        <props>
            <prop key="java.naming.factory.initial">weblogic.jndi.WLInitialContextFactory</prop>
            <prop key="java.naming.provider.url">t3://${ip}:${port}</prop>
        </props>
    </property>
</bean>
<bean id="jmsConnectionFactory" class="org.springframework.jndi.JndiObjectFactoryBean">
    <property name="jndiTemplate" ref="jmsJndiTemplate"/>
    <property name="jndiName" value="jms/cdrPreMO-connfact-jndi"/>
</bean>

<camelContext id="camelContext" xmlns="http://camel.apache.org/schema/spring">

    <camel:endpoint id="jmsQueue" uri="weblogic:queue:jms/cdrPreMO-queue-jndi"/>

    <route>
        <from ref="jmsQueue"/>
        <bean ref="test" method="writeFile"/>
        <to uri="log:errors?level=ERROR"/>
    </route>
</camelContext>

But it gives the exception :

Caused by: javax.naming.NameNotFoundException: Unable to resolve 'weblogic.jms.backend.jms'. Resolved 'weblogic.jms.backend'; remaining name 'jms'
    at weblogic.jndi.internal.BasicNamingNode.newNameNotFoundException(BasicNamingNode.java:1139)
    at weblogic.jndi.internal.BasicNamingNode.lookupHere(BasicNamingNode.java:252)
    at weblogic.jndi.internal.ServerNamingNode.lookupHere(ServerNamingNode.java:182)
    at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:206)
    at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
    at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
    at weblogic.jndi.internal.BasicNamingNode.lookup(BasicNamingNode.java:214)
    at weblogic.jndi.internal.WLEventContextImpl.lookup(WLEventContextImpl.java:254)
    at weblogic.jndi.internal.WLContextImpl.lookup(WLContextImpl.java:393)
    at weblogic.jms.frontend.FEManager.destinationCreate(FEManager.java:287)
    ... 8 more

JMS Conf is true(ip port and jndi names). It is getting the  connection, and the session but gives the exception
Could someone tell me what are my mistakes?

Thanx

EDIT: fix applied according to the comment of Claus.

Body:
Although question is pretty old, posting this solution for other users if they get this error. I ran into the this issue on Camel 2.19 version while trying to look up weblogic queue in weblogic 12c version. The lookup that happens here is most likely not a typical JNDI lookup when resolving queue destination in Weblogic.
The end point uri should contain the queue details as follows :

jms_server_name/jms_module_name!queue_name

For example if queue name is TestRequestQueue, created under a module named sample_jms_module and the JMS server is named sample_jms_server in Weblogic, then the uri would need to be as follows :

<camel:endpoint id="jmsQueue" uri="weblogic:queue:sample_jms_server/sample_jms_module!TestRequestQueue"/>

In the prefix portion of the uri weblogic:queue:, the component name can be anything as long as it refers to the created component. It needn't necessarily be weblogic. For example, if the JmsComponent is named as test-jms, the uri will need to be declared with prefix as test-jms:queue: .

Name of the JMS server in weblogic can be obtained from Weblogic console by navigating to the below path :
   Services -> Messaging -> JMS Servers

Name of the queue, not the JNDI name, can be obtained from Weblogic console by navigating to the queue and clicking on Monitoring tab. This tab shows the destination name of the queue in the name column.


来源: stackexchange

问:
Redirect from an asp.net mvc application to a .aspx file?
I have a button in an asp.net MVC 5 web application and I'm trying to redirect the user to an .aspx file.
So that when the user clicks on a button from asp.net MVC (the code of that button is in HTML), he will be redirected to a web form (.apsx).
I tried this code but it doesn't work.

```<code><button id="Login" runat="server" OnClientClick="window.open('Login.aspx', 'Login');">Login </button>
</code>```

答:
You have to call .aspx page in your Action method.</p>

```<code>public ActionResult Login()
    {
        return Redirect("~/Login.aspx");
    }
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a button in an asp.net MVC 5 web application and I'm trying to redirect the user to an .aspx file.
So that when the user clicks on a button from asp.net MVC (the code of that button is in HTML), he will be redirected to a web form (.apsx).
I tried this code but it doesn't work.

<button id="Login" runat="server" OnClientClick="window.open('Login.aspx', 'Login');">Login </button>

Body:
You have to call .aspx page in your Action method.

public ActionResult Login()
    {
        return Redirect("~/Login.aspx");
    }


问:
Vue.js - Using Child Components in a Single File Component
I have a Vue.js app. In this app, I have a single file component. In this component, I want to have another component that's specific to the component. I'm trying to do something like this:

parent.vue

```<code><template>
  <div>
    <child-component></child-component><br />
    <child-component></child-component>
  </div>
</template>

<script>
  export default {
    data() {
      return {
        info: 'hello'
      }
    },

    components: {
      childComponent: {
        template: '<div>child</div>',
        data() { return {}; }
      }
    }
  }
</script>
</code>```

After building with webpack, I then run my app in the browser. That app then generates an error in the console window that says:

Unknown custom element:  - did you register the component correctly?

I believe I've set this up properly. However, clearly I haven't. What am I doing wrong? I can see where I may not have registered "child-component". However, I guess I'm not sure how to do that within a single file component. What am I missing?

Thank you,

答:
Some ideas that might be helpful:
- as thanksd pointed out, register "child-component" intead of childComponent:

```<code>components: {
      "child-component": {
        template: '<div>child</div>',
        data() { return {}; }
      }
    }
</code>```

make sure you register the component before create the vue instance (this may or may not apply to your case, I cannot tell from the source code you posted:

Vue.component(child-component', {
    template: 'child',
    data() { return {}; }
})

new Vue({ el: '#app' })

ContentLicense: CC BY-SA 4.0

Body:
I have a Vue.js app. In this app, I have a single file component. In this component, I want to have another component that's specific to the component. I'm trying to do something like this:

parent.vue

<template>

    <child-component></child-component>

    <child-component></child-component>

</template>

After building with webpack, I then run my app in the browser. That app then generates an error in the console window that says:

Unknown custom element:  - did you register the component correctly?

I believe I've set this up properly. However, clearly I haven't. What am I doing wrong? I can see where I may not have registered "child-component". However, I guess I'm not sure how to do that within a single file component. What am I missing?

Thank you,

Body:
Some ideas that might be helpful:
- as thanksd pointed out, register "child-component" intead of childComponent:

components: {
      "child-component": {
        template: '<div>child</div>',
        data() { return {}; }
      }
    }

make sure you register the component before create the vue instance (this may or may not apply to your case, I cannot tell from the source code you posted:

Vue.component(child-component', {
    template: 'child',
    data() { return {}; }
})

new Vue({ el: '#app' })


问:
AsyncTask and SOAP webservices
I'm new to SOAP webservices and AsyncTask, I'm developing an app which is using SOAP webservices for login.
I tried to do all work in onCreate method but I got android.os.NetworkOnMainThreadException.

So i tried to use AsyncTask,
but I'm not able to get reference to emailText and passwordText in RetrieveFeedTask class.

Here is my code:

```<code>public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static String SOAP_ACTION = "intentionally hided";
    private static String NAMESPACE = "intentionally hided";
    private static String METHOD_NAME = "intentionally hided";
    private static String URL = "intentionally hided";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final EditText emailText = (EditText) findViewById(R.id.emailText);
        final EditText passwordText = (EditText) findViewById(R.id.passwordText);
        Button loginButton = (Button) findViewById(R.id.button_login);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new RetrieveFeedTask().execute();

            }
        });
    }

    class RetrieveFeedTask extends AsyncTask<String, String, String> {

        protected String doInBackground(String... urls) {

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("userName", emailText.getText().toString());
            request.addProperty("userPassword", passwordText.getText().toString());

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapObject result = (SoapObject) envelope.bodyIn;
                if (result != null) {
                    Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }
</code>```

答:
You pass emailText and passwordText directly into the AsyncTask, you just need to make a few minor changes:

First in your onClick Listener:

String email = emailText.getText().toString();

String password = passwordText.getText().toString();

new RetrieveFeedTask().execute(email, password);

Second in your AsyncTask doInBackground Method:

String email = urls[0];

String password = urls[1];

Pretty much you can pass arbitrary values into the execute method of AsyncTask which are received as parameters in it's doInBackground method.

Title: AsyncTask and SOAP webservices

Body:
I'm new to SOAP webservices and AsyncTask, I'm developing an app which is using SOAP webservices for login.
I tried to do all work in onCreate method but I got android.os.NetworkOnMainThreadException.

So i tried to use AsyncTask,
but I'm not able to get reference to emailText and passwordText in RetrieveFeedTask class.

Here is my code:

public class MainActivity extends AppCompatActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private static String SOAP_ACTION = "intentionally hided";
    private static String NAMESPACE = "intentionally hided";
    private static String METHOD_NAME = "intentionally hided";
    private static String URL = "intentionally hided";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(toolbar);

        final EditText emailText = (EditText) findViewById(R.id.emailText);
        final EditText passwordText = (EditText) findViewById(R.id.passwordText);
        Button loginButton = (Button) findViewById(R.id.button_login);

        loginButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                new RetrieveFeedTask().execute();

            }
        });
    }

    class RetrieveFeedTask extends AsyncTask<String, String, String> {

        protected String doInBackground(String... urls) {

            SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

            request.addProperty("userName", emailText.getText().toString());
            request.addProperty("userPassword", passwordText.getText().toString());

            SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);

            envelope.setOutputSoapObject(request);
            envelope.dotNet = true;

            try {
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);

                androidHttpTransport.call(SOAP_ACTION, envelope);

                SoapObject result = (SoapObject) envelope.bodyIn;
                if (result != null) {
                    Toast.makeText(getApplicationContext(), "Login Successful!", Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(), "Login Failed!", Toast.LENGTH_LONG).show();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }


问:
Get the Special Character from URL
Url is like That:

```<code>http://localhost:620251/Default.aspx/?group=Bkgbdsconsumer & Retailmailinglist
</code>```

Want the group value on cs page:

```<code>Bkgbdsconsumer & Retailmailinglist
</code>```

I ma doing this:

```<code>string group= HttpUtility.UrlEncode(Request.QueryString["group"]);
</code>```

答:
EDIT:

Ok, as I thought, there is no space before and after & in your URL.

Also port number is too big 620251 (max is 65535 as I think).

```<code>// 'fixed' port number
string url = @"http://localhost:12345/Default.aspx/?group=Bkgbdsconsumer&Retailmailinglist";

Uri myUri = new Uri (url);

var groupValue = HttpUtility.ParseQueryString (myUri.Query)["group"];

string[] allKeysWithoutValue = HttpUtility.ParseQueryString (myUri.Query).GetValues (null);
</code>```

Now allKeysWithoutValue is an array with one element Retailmailinglist.

Title: Get the Special Character from URL

Body:
Url is like That:

http://localhost:620251/Default.aspx/?group=Bkgbdsconsumer & Retailmailinglist

Want the group value on cs page:

Bkgbdsconsumer & Retailmailinglist

I ma doing this:

string group= HttpUtility.UrlEncode(Request.QueryString["group"]);

Body:
EDIT:

Ok, as I thought, there is no space before and after & in your URL.

Also port number is too big 620251 (max is 65535 as I think).

// 'fixed' port number
string url = @"http://localhost:12345/Default.aspx/?group=Bkgbdsconsumer&Retailmailinglist";

Uri myUri = new Uri (url);

var groupValue = HttpUtility.ParseQueryString (myUri.Query)["group"];

string[] allKeysWithoutValue = HttpUtility.ParseQueryString (myUri.Query).GetValues (null);

Now allKeysWithoutValue is an array with one element Retailmailinglist.


问:
AWS Lambda package-deployed functions require() of a relative path, not found
I have a zip file containing the following structure (this is the root of the archive, not nested in a top-level folder, which I understand is a common cause of errors for aws-s3-lambda deployments):

```<code>- support/
    - shared.js
- one.js
- two.js
</code>```

and then in one.js and two.js:

```<code>var shared = require("./support/shared");

// ...
</code>```

When I run this code locally, it works.  I use the aws-sdk to upload the zip file to AWS-S3 and then use aws.lambda.createFunction() to create a function with that name and handler and everything.  The created function DOES show up in my Lambda dashboard, but when I test it, I get "Cannot find module './support/shared'".  I have also tried var shared = require("./support/shared.js"); and that gives "Cannot find module './support/shared.js'".

This is for runtime node6.10.  The filename cases are correct for case-sensitive lambda.

Shouldn't this work??  What's the gotcha?

Is there a way to verify the file structure that Lambda is working in to show that the additional ./support/shared.js file actually made it to the working directory or whatever it uses?

答: The gotcha is that the zip file created on a windows machine has the wrong chmod permissions set in it for when AWS unpacks it.  The files are there, but inaccessible but node just gives a generic warning about not found instead of that the folder access is denied.</p>

Body:
I have a zip file containing the following structure (this is the root of the archive, not nested in a top-level folder, which I understand is a common cause of errors for aws-s3-lambda deployments):

- support/
    - shared.js
- one.js
- two.js

and then in one.js and two.js:

var shared = require("./support/shared");

// ...

When I run this code locally, it works.  I use the aws-sdk to upload the zip file to AWS-S3 and then use aws.lambda.createFunction() to create a function with that name and handler and everything.  The created function DOES show up in my Lambda dashboard, but when I test it, I get "Cannot find module './support/shared'".  I have also tried var shared = require("./support/shared.js"); and that gives "Cannot find module './support/shared.js'".

This is for runtime node6.10.  The filename cases are correct for case-sensitive lambda.

Shouldn't this work??  What's the gotcha?

Is there a way to verify the file structure that Lambda is working in to show that the additional ./support/shared.js file actually made it to the working directory or whatever it uses?


问:
JS forEach method is breaking halfway through, how to troubleshoot?
This is my code. When I comment out getContentKWs it goes to 27, when I don't, it stops at 11. posts.length also says 27. I have no idea how to troubleshoot this. I put console logs everywhere and I don't see anything useful. I thought breaking a forEach method was not possible.

```<code>getAllPosts().then((posts) => {
    console.log("LENGTH", posts.length)
    posts
        .forEach( (post, i) => {
            console.log(i, post.title)
            getContentKWs(getTitleKWs(post.title), post.content)
        })

})
</code>```

This is the function:

```<code>function getContentKWs(titleKeywords, postContent) {
    titleKeywords
        .some((keyword) => { //loop through keywords to find a good anchor text
            var keywordRegex = new RegExp("(" + keyword + ".+? ......+?) ", "i"); //make regex
            var match = keywordRegex.exec(postContent)
            if (match) {console.log("FOUND MATCH", match[0]); return match[0]} // found match
            else {console.log("NO MATCH",keyword); return false} // not found
        })
}
</code>```

答:
You are probably throwing an exception somewhere that is then caught by the .then() handler.  You can probably see what is happening by adding a try/catch inside your .forEach().

But, you should also always have a .catch() after your .then() and the exception will show there too.

```<code>getAllPosts().then((posts) => {
    console.log("LENGTH", posts.length)
    posts.forEach( (post, i) => {
        console.log(i, post.title)
        getContentKWs(getTitleKWs(post.title), post.content)
    })

}).catch(function(err) {
    console.log(err);
});
</code>```

All standards-based .then() implementations automatically catch thrown exceptions and turn them into a rejected promise so if you don't want to accidentally eat/miss an exception, you should always have a .catch() handler somewhere in every promise chain.

One possibility for error in your getContentKWs() function is if keyword contains some characters that make your regex invalid when those characters aren't escaped.  The RegExp constructor will throw an exception if it is given an invalid regular expression.

Body:
This is my code. When I comment out getContentKWs it goes to 27, when I don't, it stops at 11. posts.length also says 27. I have no idea how to troubleshoot this. I put console logs everywhere and I don't see anything useful. I thought breaking a forEach method was not possible.

getAllPosts().then((posts) => {
    console.log("LENGTH", posts.length)
    posts
        .forEach( (post, i) => {
            console.log(i, post.title)
            getContentKWs(getTitleKWs(post.title), post.content)
        })

})

This is the function:

function getContentKWs(titleKeywords, postContent) {
    titleKeywords
        .some((keyword) => { //loop through keywords to find a good anchor text
            var keywordRegex = new RegExp("(" + keyword + ".+? ......+?) ", "i"); //make regex
            var match = keywordRegex.exec(postContent)
            if (match) {console.log("FOUND MATCH", match[0]); return match[0]} // found match
            else {console.log("NO MATCH",keyword); return false} // not found
        })
}

Body:
You are probably throwing an exception somewhere that is then caught by the .then() handler.  You can probably see what is happening by adding a try/catch inside your .forEach().

But, you should also always have a .catch() after your .then() and the exception will show there too.

getAllPosts().then((posts) => {
    console.log("LENGTH", posts.length)
    posts.forEach( (post, i) => {
        console.log(i, post.title)
        getContentKWs(getTitleKWs(post.title), post.content)
    })

}).catch(function(err) {
    console.log(err);
});

All standards-based .then() implementations automatically catch thrown exceptions and turn them into a rejected promise so if you don't want to accidentally eat/miss an exception, you should always have a .catch() handler somewhere in every promise chain.

One possibility for error in your getContentKWs() function is if keyword contains some characters that make your regex invalid when those characters aren't escaped.  The RegExp constructor will throw an exception if it is given an invalid regular expression.


问:
Tinymce as email editor - image preview with CID
I am using Tinymce as an email editor. When inserting an embedded image as attachment, the images are inserted as:

This works for the email sending part - but of course not for the editor. The image is not displayed...

Question: Is there a "content" and "display" layer in Tinymce where I can hook into?

My goal is to save the content as

and transform it in the editor window as

I am using Tinymce 4.

答:
The editor relies on the browser for the rendering of HTML so anything like your  won't render in the editor - its simply not valid HTML.

What you can do is rely on data-xxx attributes in HTML to store the data you really want and transform the HTML when you go to load it into TinyMCE.

For example...

When someone inserts the image you could create the following HTML

```<code><img data-src="cid:mycid@sth" src="/mypreview/image/2000" />
</code>```

...this would allow the editor to actually render an image while you still keep the data you need.  When you save the content you can strip out the existing src data and copy the data-src content back into the src if that is what your app needs for its server side processing.

If someone edits the content you can just reverse the process and change the src back to HTML that TinyMCE can render.

Body:
The editor relies on the browser for the rendering of HTML so anything like your <img src="cid:mycid@sth" /> won't render in the editor - its simply not valid HTML.

What you can do is rely on data-xxx attributes in HTML to store the data you really want and transform the HTML when you go to load it into TinyMCE.

For example...

When someone inserts the image you could create the following HTML

<img data-src="cid:mycid@sth" src="/mypreview/image/2000" />

...this would allow the editor to actually render an image while you still keep the data you need.  When you save the content you can strip out the existing src data and copy the data-src content back into the src if that is what your app needs for its server side processing.

If someone edits the content you can just reverse the process and change the src back to HTML that TinyMCE can render.


问:
Post angular 2 form data to symfony api
I have angular 2 form and I want to save it in the data base using symfony API web service, I'm trying to fetch data from angular form and sent it as json object to the url endpoint via post http request.

this is the component.html

```<code><div class="ui raised segment">
  <h2 class="ui header">Demo Form: Sku</h2>
  <form #f="ngForm"
        (ngSubmit)="onSubmit(f.value)"
        class="ui form">

    <div class="field">
      <label for="skuInput">SKU</label>
      <input type="text"
             id="skuInput"
             placeholder="SKU"
             name="sku" ngModel>
    </div>
    <div class="field">
      <label for="select1" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:français/anglais: </label>
      <select class="form-control" name="note1" id="select1" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      <label for="select2" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:français/anglais: </label>
      <select class="form-control" name="note2" id="select2" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      <label for="select3" class="col-md-4 col-lg-4 col-sm-2 align form-control-label">Langues:français/anglais: </label>
      <select class="form-control" name="note3" id="select3" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

    </div>

    <button type="submit" class="ui button">Submit</button>
  </form>
</div>
</code>```

the service :

```<code>import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import { savePostEvaluationapi} from '../../constants/api.endpoints';

@Injectable()
export class EvaluationService {
  http: Http;

  constructor(protected _http: Http) {
    this.http = _http;
  }

  savePostEvaluationService(postEvalform) {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const data = JSON.stringify(postEvalform);

    return this.http.post("http://evaluation.dev/app_dev.php/api/savePostEvaluation", data, options).map((res: Response) => res.json());
  }

}
</code>```

and the component.ts

```<code>import {Component, OnInit} from '@angular/core';
import {EvaluationService} from '../../services/evaluation/evaluation.service';

@Component({
  selector: 'app-eval-en-cours',
  templateUrl: './eval-en-cours.component.html',
  styleUrls: ['./eval-en-cours.component.css']
})
export class EvalEnCoursComponent implements OnInit {

  constructor(private evaluationService: EvaluationService) {
  }

  ngOnInit() {
  }

  // savePostEvaluation(data: Object) {
  //   this.evaluationService.savePostEvaluation(data).subscribe((dataResponse) => {
  //     console.log('execute' + dataResponse);
  //   });
  // }
    savePostEvaluation(form: any): void {

      this.evaluationService.savePostEvaluationService(form)
        .subscribe(
          data => data.json(),
          () => console.log('done send form to api')
        );
  }
</code>```

here is the symfony web service :

```<code>/**
     * @Rest\View()
     * @Rest\Post("/savePostEvaluation")
     * @return Response
     * @internal param Request $request
     */

    public function savePostEvaluation(Request $request){
        header("Access-Control-Allow-Origin: *");
        $data = json_decode($request->getContent(), true);
        dump($data);die;
    }
</code>```

when I try to dump the data value it return null object ! any help please !

答:
There are a couple of issues with the code your provided that may be causing the issue:

HTML <option> elements do not seem to have value attributes. Without a value there wouldn't be anything that can be passed to the API in terms of selected value.

ngModel is not currently doing anything as it does not have either the one-way [] or two-binding [()] syntax tying to some component class property.

Try creating a model to representing the form data:

```<code>export class Foo {
  constructor(
    public sku: string,
    public note1: string,
    public note2: string,
    public note3: string
  ) {  }
}
</code>```

Then create an instance of the model in EvalEnCoursComponent with some default/empty values:

```<code>import { Foo } from './Foo';

export class EvalEnCoursComponent implements OnInit {
   model = new Foo('', '', '', '');
   // rest of code
}
</code>```

In your form, update the ngModel to utilize two-way binding to ensure model properties are updating on change/select/etc events for each input/select. Otherwise you'd need extract the form values using something like FormData from the #f form object:

```<code><div class="field">
  <label for="skuInput">SKU</label>
  <input type="text"
         id="skuInput"
         placeholder="SKU"
         name="sku" [(ngModel)]="model.sku">
</div>
</code>```

Also be sure that your <select> elements' <options> actually have value properties:

```<code>  <select class="form-control" name="note2" id="select2" ngModel>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
  </select>
</code>```

Finally on submit, pass this.model to the service instead of the form instance itself:

```<code>savePostEvaluation(): void {
    this.evaluationService.savePostEvaluationService(this.model)
        .subscribe(data => console.log(data));
}
</code>```

Utilizing a class or interface to represent your form data model will provide you more control over your structure and using two-way data binding will automatically update the values of the model.

Hopefully this helps!

Title: Post angular 2 form data to symfony api

Body:
I have angular 2 form and I want to save it in the data base using symfony API web service, I'm trying to fetch data from angular form and sent it as json object to the url endpoint via post http request.

this is the component.html

Demo Form: Sku

  <form #f="ngForm"
        (ngSubmit)="onSubmit(f.value)"
        class="ui form">

      SKU
      <input type="text"
             id="skuInput"
             placeholder="SKU"
             name="sku" ngModel>

      Langues:français/anglais:
      <select class="form-control" name="note1" id="select1" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      Langues:français/anglais:
      <select class="form-control" name="note2" id="select2" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

      Langues:français/anglais:
      <select class="form-control" name="note3" id="select3" ngModel>
        <option>1</option>
        <option>2</option>
        <option>3</option>
        <option>4</option>
        <option>5</option>
      </select>

    <button type="submit" class="ui button">Submit</button>
  </form>

the service :

import { Injectable } from '@angular/core';
import {Http, Response, Headers, RequestOptions} from '@angular/http';
import { savePostEvaluationapi} from '../../constants/api.endpoints';

@Injectable()
export class EvaluationService {
  http: Http;

  constructor(protected _http: Http) {
    this.http = _http;
  }

  savePostEvaluationService(postEvalform) {
    const headers = new Headers({'Content-Type': 'application/json'});
    const options = new RequestOptions({headers: headers});
    const data = JSON.stringify(postEvalform);

    return this.http.post("http://evaluation.dev/app_dev.php/api/savePostEvaluation", data, options).map((res: Response) => res.json());
  }

}

and the component.ts

import {Component, OnInit} from '@angular/core';
import {EvaluationService} from '../../services/evaluation/evaluation.service';

@Component({
  selector: 'app-eval-en-cours',
  templateUrl: './eval-en-cours.component.html',
  styleUrls: ['./eval-en-cours.component.css']
})
export class EvalEnCoursComponent implements OnInit {

  constructor(private evaluationService: EvaluationService) {
  }

  ngOnInit() {
  }

  // savePostEvaluation(data: Object) {
  //   this.evaluationService.savePostEvaluation(data).subscribe((dataResponse) => {
  //     console.log('execute' + dataResponse);
  //   });
  // }
    savePostEvaluation(form: any): void {

      this.evaluationService.savePostEvaluationService(form)
        .subscribe(
          data => data.json(),
          () => console.log('done send form to api')
        );
  }

here is the symfony web service :

/**
     * @Rest\View()
     * @Rest\Post("/savePostEvaluation")
     * @return Response
     * @internal param Request $request
     */

    public function savePostEvaluation(Request $request){
        header("Access-Control-Allow-Origin: *");
        $data = json_decode($request->getContent(), true);
        dump($data);die;
    }

when I try to dump the data value it return null object ! any help please !

Body:
There are a couple of issues with the code your provided that may be causing the issue:

HTML <option> elements do not seem to have value attributes. Without a value there wouldn't be anything that can be passed to the API in terms of selected value.

ngModel is not currently doing anything as it does not have either the one-way [] or two-binding [()] syntax tying to some component class property.

Try creating a model to representing the form data:

export class Foo {
  constructor(
    public sku: string,
    public note1: string,
    public note2: string,
    public note3: string
  ) {  }
}

Then create an instance of the model in EvalEnCoursComponent with some default/empty values:

import { Foo } from './Foo';

export class EvalEnCoursComponent implements OnInit {
   model = new Foo('', '', '', '');
   // rest of code
}

In your form, update the ngModel to utilize two-way binding to ensure model properties are updating on change/select/etc events for each input/select. Otherwise you'd need extract the form values using something like FormData from the #f form object:

<div class="field">
  <label for="skuInput">SKU</label>
  <input type="text"
         id="skuInput"
         placeholder="SKU"
         name="sku" [(ngModel)]="model.sku">
</div>

Also be sure that your <select> elements' <options> actually have value properties:

  <select class="form-control" name="note2" id="select2" ngModel>
    <option value="1">1</option>
    <option value="2">2</option>
    <option value="3">3</option>
    <option value="4">4</option>
    <option value="5">5</option>
  </select>

Finally on submit, pass this.model to the service instead of the form instance itself:

savePostEvaluation(): void {
    this.evaluationService.savePostEvaluationService(this.model)
        .subscribe(data => console.log(data));
}

Utilizing a class or interface to represent your form data model will provide you more control over your structure and using two-way data binding will automatically update the values of the model.

Hopefully this helps!


问:
How to set up kitchen printer in Odoo?
I just installed Odoo version 9 locally. I haven't found the way to configure an order printer to be used with the Point of Sale module. Any help would be appreciated, thanks</p>

答: You can set up kitchen printer using pos_restaurant module. After installing this from app list you can see one menu in POS >> Configuration >> Order Printes in this menu you can setup printer

Title: How to set up kitchen printer in Odoo?


问:
While loop acting weird in regards to input
Been working on a simple school project but I've run into a small problem in regards to validation of user input via the use of a while loop. The following code is used to do so:

```<code>cout << "How much woud you like to bet?[100, 300, 500]" << endl;
    cin >> int_input;
    if (cin.fail()){
        int_input = 0;
    }

     //Validate check
     while(int_input!=100 && int_input!=300 && int_input!=500){
        cout << "Please enter a valid bet [100, 300, 500]" << endl;
        cin >> int_input;
        if (cin.fail()){
            int_input = 0;
        }
     }
</code>```

The issue arises when a non-integer is entered and the loop ends up spitting out the cout msg over and over again, skipping the request for new input. I assume that a non-integer always returns true for the while loop, but the program should still ask for user input, right?

The cin.fail is a recent addition and might not be necessary as it doesn't solve the problem, although I leave the code as it as it is.

答:
If you have an error on the stream, you set your value to 0. So the loop is run again... and the error's still on the stream. Repeat.

You need to clear the error flag.

```<code>cin.clear();
</code>```

Then extract enough "bad" data to get to the good part, or you'll just be right back where you started.

Body:
Been working on a simple school project but I've run into a small problem in regards to validation of user input via the use of a while loop. The following code is used to do so:

cout << "How much woud you like to bet?[100, 300, 500]" << endl;
    cin >> int_input;
    if (cin.fail()){
        int_input = 0;
    }

     //Validate check
     while(int_input!=100 && int_input!=300 && int_input!=500){
        cout << "Please enter a valid bet [100, 300, 500]" << endl;
        cin >> int_input;
        if (cin.fail()){
            int_input = 0;
        }
     }

The issue arises when a non-integer is entered and the loop ends up spitting out the cout msg over and over again, skipping the request for new input. I assume that a non-integer always returns true for the while loop, but the program should still ask for user input, right?

The cin.fail is a recent addition and might not be necessary as it doesn't solve the problem, although I leave the code as it as it is.

Body:
If you have an error on the stream, you set your value to 0. So the loop is run again... and the error's still on the stream. Repeat.

You need to clear the error flag.

cin.clear();

Then extract enough "bad" data to get to the good part, or you'll just be right back where you started.


问:
What, exactly, is memcmp supposed to return?
I would like to know what the function memcmp must return.

I've been searching on the Internet, and usually, memcmp definitions state something like the following:

The memcmp() function returns an integer greater than, equal to, or less than zero, accordingly as the object pointed to by s1 is greater than, equal to, or less than the object pointed to by s2.

It is never explicitly said what, exactly, is returned: is it the difference between two byte values, or is it -1, 0 or 1? I am confused:

When testing the function memcmp in a little program, it returns -1, 0 or 1, even when the difference between the two bytes evaluated is higher than 1 or lower than -1.

When looking at functions named memcmp on the Internet, they almost all return the difference between 2 bytes, as an int, instead of returning either -1, 0 or 1.

Since I can't get a precise enough definition of the function memcmp, I ask this question here: what, exactly, is the function memcmp supposed to return? Is there an "official" source code somewhere? (I have seen a lot of source codes for memcmp but none gave me an answer: I then suppose that they are not the function that is written in the library string.h, at least not on my computer...)

答:
The particular values returned by memcmp() are not specified by the Standard. The C11 Draft Standard does say, in §7.24.4 1:

The sign of a nonzero value returned by the comparison functions
  memcmp, strcmp, and strncmp is determined by the sign of the
  difference between the values of the first pair of characters (both
  interpreted as unsigned char) that differ in the objects being
  compared.

So only the sign of nonzero return values from the comparison functions should be taken as meaningful. The latitude given here allows each implementation to interpret these requirements as it sees fit.

Also, note that there is no "official source code"; the Standard is the document that C implementations must adhere to. Even reading the source code for the implementation that you are using to find the underlying method used to generate the memcmp() return values, use of these values in code is at best not portable, and is vulnerable to future changes in that implementation.


问:
Unknown prop- react
Currently learning react, when i try and run the following code:

var userData = {
 name: 'Evans D',
 occupation: ' Logistics Planner',
 location: 'Birmingham, UK',
 img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTAlfOT5088Z6Bj8_qSsvp3UTlU3ub9H5wG1k6qJareFXS7uqDvsQ'
};

class userInfo extends React.Component {
  render() {
    return (

Name: {this.props.user.name}

Occupation: {this.props.user.occupation}

Location: {this.props.user.location}

       //

    )
  }
}

ReactDOM.render(
  <userInfo user={userData}/>,
  document.getElementById('userInfo')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Github Battle</title>
</head>
<body>
<div id='userInfo'></div>
</body>
</html></code>```

Console throws the following error :

'Unknown prop user on  tag. Remove this prop from the element.'

Any ideas on what I'm doing wrong?

答:
The user props seems fine to me. However, I notice 3 Things that are out of place in your snippet.

You have to use babeljs / es2015 option in code snippet to write JSX.

You need to include react library to use it.

Make sure that your component name is capitalised.

See working code below

var userData = {
 name: 'Evans D',
 occupation: ' Logistics Planner',
 location: 'Birmingham, UK',
 img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTAlfOT5088Z6Bj8_qSsvp3UTlU3ub9H5wG1k6qJareFXS7uqDvsQ'
};

class UserInfo extends React.Component {
  render() {
    return (

Name: {this.props.user.name}

Occupation: {this.props.user.occupation}

Location: {this.props.user.location}

       //

    )
  }
}

ReactDOM.render(
  <UserInfo user={userData}/>,
  document.getElementById('userInfo')
);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><!DOCTYPE html>
<html>
<head>
 <title>Github Battle</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</head>
<body>
<div id='userInfo'></div>
</body>
</html></code>```

Title: Unknown prop- react

Body:
Currently learning react, when i try and run the following code:

var userData = {
 name: 'Evans D',
 occupation: ' Logistics Planner',
 location: 'Birmingham, UK',
 img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTAlfOT5088Z6Bj8_qSsvp3UTlU3ub9H5wG1k6qJareFXS7uqDvsQ'
};

class userInfo extends React.Component {
  render() {
    return (

Name: {this.props.user.name}

Occupation: {this.props.user.occupation}

Location: {this.props.user.location}

       //

    )
  }
}

ReactDOM.render(
  <userInfo user={userData}/>,
  document.getElementById('userInfo')
);

<!DOCTYPE html>

 <title>Github Battle</title>

Console throws the following error :

'Unknown prop user on  tag. Remove this prop from the element.'

Any ideas on what I'm doing wrong?

Body:
The user props seems fine to me. However, I notice 3 Things that are out of place in your snippet.

You have to use babeljs / es2015 option in code snippet to write JSX.

You need to include react library to use it.

Make sure that your component name is capitalised.

See working code below

var userData = {
 name: 'Evans D',
 occupation: ' Logistics Planner',
 location: 'Birmingham, UK',
 img: 'https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTAlfOT5088Z6Bj8_qSsvp3UTlU3ub9H5wG1k6qJareFXS7uqDvsQ'
};

class UserInfo extends React.Component {
  render() {
    return (
      <div>
       <h1>Name: {this.props.user.name} </h1>
       <h2>Occupation: {this.props.user.occupation} </h2>
       <h3>Location: {this.props.user.location} </h3>
       // <img src={this.props.user.img} />
      </div>
    )
  }
}

ReactDOM.render(
  <UserInfo user={userData}/>,
  document.getElementById('userInfo')
);

<!DOCTYPE html>
<html>
<head>
 <title>Github Battle</title>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
</head>
<body>
<div id='userInfo'></div>
</body>
</html>


问:
jQuery/Javascript add/remove this.class on click
```<code><script>
$(".image-popup").on('click', function() {
       $(this).find(".myModal").addClass("modal-active");
       $(".modal-active").css("display", "block");
   });
$(".close").on('click', function() {
       $(".modal-active").css("display", "none");
       var myVar = $(this).closest(".image-popup");
       myVar.find(".myModal").removeClass("modal-active");
       $(".modal-active").css("display","none");
   });
</script>
</code>```

I am attempting to have a modal appear and then disappear when I click the close button. The problem is that the removeClass() will not work and the "display", "none" will not override the first click function. Any Help?

答:
My guess from your question and your comment above is that the event from your second handler is bubbling up to your first handler:

```<code>$(".image-popup").on('click', function() {
    $(this).find(".myModal")
        .addClass("modal-active")
        .show();
});

$(".close").on('click', function(evt) {
    evt.preventDefault();

    $(this).closest(".image-popup")
        .find(".myModal")
        .removeClass("modal-active");
        .hide();
});
</code>```

Try to prevent the event from bubbling out of the .close handler by using evt.preventDefault();

Body:
My guess from your question and your comment above is that the event from your second handler is bubbling up to your first handler:

$(".image-popup").on('click', function() {
    $(this).find(".myModal")
        .addClass("modal-active")
        .show();
});

$(".close").on('click', function(evt) {
    evt.preventDefault();

    $(this).closest(".image-popup")
        .find(".myModal")
        .removeClass("modal-active");
        .hide();
});

Try to prevent the event from bubbling out of the .close handler by using evt.preventDefault();


问:
Circle line-segment collision detection algorithm?
I have a line from A to B and a circle positioned at C with the radius R.

What is a good algorithm to use to check whether the line intersects the circle? And at what coordinate along the circles edge it occurred?

答:
Here's an implementation in Javascript. My approach is to first convert the line segment into an infinite line then find the intersection point(s). From there I check if the point(s) found are on the line segment. The code is well documented, you should be able to follow along.

You can try out the code here on this live demo.
The code was taken from my algorithms repo.

// Small epsilon value
var EPS = 0.0000001;

// point (x, y)
function Point(x, y) {
  this.x = x;
  this.y = y;
}

// Circle with center at (x,y) and radius r
function Circle(x, y, r) {
  this.x = x;
  this.y = y;
  this.r = r;
}

// A line segment (x1, y1), (x2, y2)
function LineSegment(x1, y1, x2, y2) {
  var d = Math.sqrt( (x1-x2)*(x1-x2) + (y1-y2)*(y1-y2) );
  if (d < EPS) throw 'A point is not a line segment';
  this.x1 = x1; this.y1 = y1;
  this.x2 = x2; this.y2 = y2;
}

// An infinite line defined as: ax + by = c
function Line(a, b, c) {
  this.a = a; this.b = b; this.c = c;
  // Normalize line for good measure
  if (Math.abs(b) < EPS) {
    c /= a; a = 1; b = 0;
  } else {
    a = (Math.abs(a) < EPS) ? 0 : a / b;
    c /= b; b = 1;
  }
}

// Given a line in standard form: ax + by = c and a circle with
// a center at (x,y) with radius r this method finds the intersection
// of the line and the circle (if any).
function circleLineIntersection(circle, line) {

  var a = line.a, b = line.b, c = line.c;
  var x = circle.x, y = circle.y, r = circle.r;

  // Solve for the variable x with the formulas: ax + by = c (equation of line)
  // and (x-X)^2 + (y-Y)^2 = r^2 (equation of circle where X,Y are known) and expand to obtain quadratic:
  // (a^2 + b^2)x^2 + (2abY - 2ac + - 2b^2X)x + (b^2X^2 + b^2Y^2 - 2bcY + c^2 - b^2r^2) = 0
  // Then use quadratic formula X = (-b +- sqrt(a^2 - 4ac))/2a to find the
  // roots of the equation (if they exist) and this will tell us the intersection points

  // In general a quadratic is written as: Ax^2 + Bx + C = 0
  // (a^2 + b^2)x^2 + (2abY - 2ac + - 2b^2X)x + (b^2X^2 + b^2Y^2 - 2bcY + c^2 - b^2r^2) = 0
  var A = a*a + b*b;
  var B = 2*a*b*y - 2*a*c - 2*b*b*x;
  var C = b*b*x*x + b*b*y*y - 2*b*c*y + c*c - b*b*r*r;

  // Use quadratic formula x = (-b +- sqrt(a^2 - 4ac))/2a to find the
  // roots of the equation (if they exist).

  var D = B*B - 4*A*C;
  var x1,y1,x2,y2;

  // Handle vertical line case with b = 0
  if (Math.abs(b) < EPS) {

    // Line equation is ax + by = c, but b = 0, so x = c/a
    x1 = c/a;

    // No intersection
    if (Math.abs(x-x1) > r) return [];

    // Vertical line is tangent to circle
    if (Math.abs((x1-r)-x) < EPS || Math.abs((x1+r)-x) < EPS)
      return [new Point(x1, y)];

    var dx = Math.abs(x1 - x);
    var dy = Math.sqrt(r*r-dx*dx);

    // Vertical line cuts through circle
    return [
      new Point(x1,y+dy),
      new Point(x1,y-dy)
    ];

  // Line is tangent to circle
  } else if (Math.abs(D) < EPS) {

    x1 = -B/(2*A);
    y1 = (c - a*x1)/b;

    return [new Point(x1,y1)];

  // No intersection
  } else if (D < 0) {

    return [];

  } else {

    D = Math.sqrt(D);

    x1 = (-B+D)/(2*A);
    y1 = (c - a*x1)/b;

    x2 = (-B-D)/(2*A);
    y2 = (c - a*x2)/b;

    return [
      new Point(x1, y1),
      new Point(x2, y2)
    ];

  }

}

// Converts a line segment to a line in general form
function segmentToGeneralForm(x1,y1,x2,y2) {
  var a = y1 - y2;
  var b = x2 - x1;
  var c = x2*y1 - x1*y2;
  return new Line(a,b,c);
}

// Checks if a point 'pt' is inside the rect defined by (x1,y1), (x2,y2)
function pointInRectangle(pt,x1,y1,x2,y2) {
  var x = Math.min(x1,x2), X = Math.max(x1,x2);
  var y = Math.min(y1,y2), Y = Math.max(y1,y2);
  return x - EPS <= pt.x && pt.x <= X + EPS &&
         y - EPS <= pt.y && pt.y <= Y + EPS;
}

// Finds the intersection(s) of a line segment and a circle
function lineSegmentCircleIntersection(segment, circle) {

  var x1 = segment.x1, y1 = segment.y1, x2 = segment.x2, y2 = segment.y2;
  var line = segmentToGeneralForm(x1,y1,x2,y2);
  var pts = circleLineIntersection(circle, line);

  // No intersection
  if (pts.length === 0) return [];

  var pt1 = pts[0];
  var includePt1 = pointInRectangle(pt1,x1,y1,x2,y2);

  // Check for unique intersection
  if (pts.length === 1) {
    if (includePt1) return [pt1];
    return [];
  }

  var pt2 = pts[1];
  var includePt2 = pointInRectangle(pt2,x1,y1,x2,y2);

  // Check for remaining intersections
  if (includePt1 && includePt2) return [pt1, pt2];
  if (includePt1) return [pt1];
  if (includePt2) return [pt2];
  return [];

}
```


问:
Print Button In Excel 2016 Using Macros?
I'm currently trying to create a Print Button on one of my worksheets.  I need it to print that worksheet as well as another one.  Both of the names are "Budget Sheet" and "Listed Commitments Sheet" without the quotation marks.

I created the button without hassle, but I know very little about Macros so I still need the code.  I've tried multiple solutions, but nothing seems to work.  I've recently tried to use this Code, but it hasn't worked.  What am I doing wrong?  What code could I possibly use instead?

```<code>Private Sub CommandButton1_Click()

Function PrintMultipleSheets()
    Sheets(Array("Budget Sheet", "Listed Commitments Sheet")).PrintOut
End Function

End Sub
</code>```

答:
Just a simple loop with a print call:</p>

```<code>Sub forEachWs()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call printSheet(ws)
    Next
End Sub

Function pasteContents(ws as Worksheet)
     ActiveSheet.PrintOut
End Function
</code>```

Body:
I'm currently trying to create a Print Button on one of my worksheets.  I need it to print that worksheet as well as another one.  Both of the names are "Budget Sheet" and "Listed Commitments Sheet" without the quotation marks.

I created the button without hassle, but I know very little about Macros so I still need the code.  I've tried multiple solutions, but nothing seems to work.  I've recently tried to use this Code, but it hasn't worked.  What am I doing wrong?  What code could I possibly use instead?

Private Sub CommandButton1_Click()

Function PrintMultipleSheets()
    Sheets(Array("Budget Sheet", "Listed Commitments Sheet")).PrintOut
End Function

End Sub

Body:
Just a simple loop with a print call:

Sub forEachWs()
    Dim ws As Worksheet
    For Each ws In ActiveWorkbook.Worksheets
        Call printSheet(ws)
    Next
End Sub

Function pasteContents(ws as Worksheet)
     ActiveSheet.PrintOut
End Function


问:
Deserialize json into C# object for class which has default private constructor
I need to deserialize json for following class.

```<code>public class Test
{
    public string Property { get; set; }

    private Test()
    {
        //NOTHING TO INITIALIZE
    }

    public Test(string prop)
    {
        Property = prop;
    }
}
</code>```

I can create an instance of Test like

```<code>var instance = new Test("Instance");
</code>```

considering my json something like

```<code>"{  "Property":"Instance" }"
</code>```

How shall I create an object of Test class as my default constructor is private and I am getting object where Property is NULL

I am using Newtonsoft Json parser.

答:
No need to create a Serializer setting and give assign ConstructorHandling here. Please remember to define the [JsonConstructor] attribute to the private constructor.
I have similar case with abstract BaseNode.cs and its concrete ComputerNode.cs implementation. You can create the classes, copy/paste the code below and do some experiment.

```<code>    public abstract class BaseNode
{
    [JsonConstructor] // ctor used when Json Deserializing
    protected BaseNode(string Owner, string Name, string Identifier)
    {
        this.Name = Name;
        this.Identifier = Identifier;
    }

    // ctor called by concrete class.
    protected BaseNode(string [] specifications)
    {
        if (specifications == null)
        {
            throw new ArgumentNullException();
        }
        if (specifications.Length == 0)
        {
            throw new ArgumentException();
        }

        Name = specifications[0];
        Identifier = specifications[1];

    }

    public string Name{ get; protected set; }
    public string Identifier { get; protected set; }

}

public class ComputerNode: BaseNode
{
    public string Owner { get; private set; }

    [JsonConstructor] // not visible while creating object from outside and only used during Json Deserialization.
    private ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
    {
        this.Owner = Owner;
    }

    public ComputerNode(string[] specifications):base(specifications)
    {
        Owner = specifications[2];
    }
}
</code>```

For JSon Read and Write  following code helps -

```<code>    public class Operation<T>
{
    public string path;

    public Operation()
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");

        if (File.Exists(path) == false)
        {
            using (File.Create(path))
            {
            }
        }
        this.path = path;
    }

    public void Write(string path, List<T> nodes)
    {
        var ser = JsonConvert.SerializeObject(nodes, Formatting.Indented);

        File.WriteAllText(path, ser);
    }

    public List<T> Read(string path)
    {
        var text = File.ReadAllText(path);

        var res =  JsonConvert.DeserializeObject<List<T>>(text);
        return res;
    }

}
</code>```

All the best!

Body:
I need to deserialize json for following class.

public class Test
{
    public string Property { get; set; }

    private Test()
    {
        //NOTHING TO INITIALIZE
    }

    public Test(string prop)
    {
        Property = prop;
    }
}

I can create an instance of Test like

var instance = new Test("Instance");

considering my json something like

"{  "Property":"Instance" }"

How shall I create an object of Test class as my default constructor is private and I am getting object where Property is NULL

I am using Newtonsoft Json parser.

Body:
No need to create a Serializer setting and give assign ConstructorHandling here. Please remember to define the [JsonConstructor] attribute to the private constructor.
I have similar case with abstract BaseNode.cs and its concrete ComputerNode.cs implementation. You can create the classes, copy/paste the code below and do some experiment.

    public abstract class BaseNode
{
    [JsonConstructor] // ctor used when Json Deserializing
    protected BaseNode(string Owner, string Name, string Identifier)
    {
        this.Name = Name;
        this.Identifier = Identifier;
    }

    // ctor called by concrete class.
    protected BaseNode(string [] specifications)
    {
        if (specifications == null)
        {
            throw new ArgumentNullException();
        }
        if (specifications.Length == 0)
        {
            throw new ArgumentException();
        }

        Name = specifications[0];
        Identifier = specifications[1];

    }

    public string Name{ get; protected set; }
    public string Identifier { get; protected set; }

}

public class ComputerNode: BaseNode
{
    public string Owner { get; private set; }

    [JsonConstructor] // not visible while creating object from outside and only used during Json Deserialization.
    private ComputerNode(string Owner, string Name, string Identifier):base(Owner, Name, Identifier)
    {
        this.Owner = Owner;
    }

    public ComputerNode(string[] specifications):base(specifications)
    {
        Owner = specifications[2];
    }
}

For JSon Read and Write  following code helps -

    public class Operation<T>
{
    public string path;

    public Operation()
    {
        var path = Path.Combine(Directory.GetCurrentDirectory(), "nodes.txt");

        if (File.Exists(path) == false)
        {
            using (File.Create(path))
            {
            }
        }
        this.path = path;
    }

    public void Write(string path, List<T> nodes)
    {
        var ser = JsonConvert.SerializeObject(nodes, Formatting.Indented);

        File.WriteAllText(path, ser);
    }

    public List<T> Read(string path)
    {
        var text = File.ReadAllText(path);

        var res =  JsonConvert.DeserializeObject<List<T>>(text);
        return res;
    }

}

All the best!


问:
Toggle between hiding and showing RowDetails when DataGridRow is clicked
I have a DataGrid that has RowDetailsVisibilityMode set to "VisibleWhenSelected" so that the RowDetailsTemplate displays when I select a particular row. What I want is to be able to toggle the RowDetails visibility when I click the row again. By default, the RowDetails will be visible so long as its selected, but I want to essentially "unselect" the selected row if I click it again.

After trying a lot of things, I've found a sort of wacky solution that at least makes it so that I can toggle the visibility when I click the row:

```<code>private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
    if (DataGrid.SelectedIndex == prevSelectedIndex) { //check if I'm clicking on what's already selected
          DataGrid.SelectedIndex = -1; //collapses everything
    }
    prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
}
</code>```

The delay makes sure that the SelectedIndex property is already updated when I check for the selected index. I wish I didn't have to use it - I would be happy to find a better solution.

The problem now, however, is that whenever I click anything in the RowDetails of the selected row, this event fires and the row details disappear again. I want to be able to somehow check that I only expand/collapse the row when I click the row itself, not when I click whatever's in the RowDetailsTemplate. Is that possible? I don't want to use an extra Expander button for each row.

答:
I found a solution to my problem:

In my RowDetailsTemplate under the ContentControl, I added an EventSetter that captured the PreviewMouseDown event:

```<code><EventSetter Event="PreviewMouseDown" Handler="ContentControl_PreviewMouseDown" />
</code>```

The Handler for the event set a global variable that indicated whether I had clicked on what's in the ContentControl:

```<code>private void ContentControl_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    ClickedRowDetails = true;
}
</code>```

Finally, in my original code, I simply checked whether I had clicked on the ContentControl, or whether it was something else, which in this case, meant it was the row itself:

```<code>private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    ClickedRowDetails = false; //default assume that we haven't clicked row details

    await Task.Delay(1); //wait for other events to fire

    if (!ClickedRowDetails) {
        if (DataGrid.SelectedIndex == prevSelectedIndex )
        {
            DataGrid.SelectedIndex = -1;
        }
        prevSelectedIndex = DataGrid.SelectedIndex;
    }
}
</code>```

So now, I can successfully expand/collapse rows by simply clicking on them, and then I can manipulate whatever's in the RowDetailsTemplate without accidently collapsing the row. This was done without an Expander button.

Body:
I have a DataGrid that has RowDetailsVisibilityMode set to "VisibleWhenSelected" so that the RowDetailsTemplate displays when I select a particular row. What I want is to be able to toggle the RowDetails visibility when I click the row again. By default, the RowDetails will be visible so long as its selected, but I want to essentially "unselect" the selected row if I click it again.

After trying a lot of things, I've found a sort of wacky solution that at least makes it so that I can toggle the visibility when I click the row:

private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    await Task.Delay(1); //ensures DataGrid.SelectedIndex is what I just clicked, not the previous value
    if (DataGrid.SelectedIndex == prevSelectedIndex) { //check if I'm clicking on what's already selected
          DataGrid.SelectedIndex = -1; //collapses everything
    }
    prevSelectedIndex = DataGrid.SelectedIndex; //save current selected index
}

The delay makes sure that the SelectedIndex property is already updated when I check for the selected index. I wish I didn't have to use it - I would be happy to find a better solution.

The problem now, however, is that whenever I click anything in the RowDetails of the selected row, this event fires and the row details disappear again. I want to be able to somehow check that I only expand/collapse the row when I click the row itself, not when I click whatever's in the RowDetailsTemplate. Is that possible? I don't want to use an extra Expander button for each row.

Body:
I found a solution to my problem:

In my RowDetailsTemplate under the ContentControl, I added an EventSetter that captured the PreviewMouseDown event:

<EventSetter Event="PreviewMouseDown" Handler="ContentControl_PreviewMouseDown" />

The Handler for the event set a global variable that indicated whether I had clicked on what's in the ContentControl:

private void ContentControl_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    ClickedRowDetails = true;
}

Finally, in my original code, I simply checked whether I had clicked on the ContentControl, or whether it was something else, which in this case, meant it was the row itself:

private async void DataGrid_PreviewMouseDown(object sender, MouseButtonEventArgs e)
{
    ClickedRowDetails = false; //default assume that we haven't clicked row details

    await Task.Delay(1); //wait for other events to fire

    if (!ClickedRowDetails) {
        if (DataGrid.SelectedIndex == prevSelectedIndex )
        {
            DataGrid.SelectedIndex = -1;
        }
        prevSelectedIndex = DataGrid.SelectedIndex;
    }
}

So now, I can successfully expand/collapse rows by simply clicking on them, and then I can manipulate whatever's in the RowDetailsTemplate without accidently collapsing the row. This was done without an Expander button.


问:
Error to check my Noip uploaded in a host (as txt file content)
I have a txt uploaded in my site where the content of this txt file is my Noip address that must be consulted by a http request.

The trouble in my code below is that if this file was removed of site, is generated a exception and not is possible execute the folowing lines for function returns a right result.

How solve it?

```<code>program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  idhttp,
  SysUtils;

function GetURLAsString(const aURL, bURL: string): string;
var
  lHTTP: TIdHTTP;
  a, b: string;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    a := lHTTP.Get(aURL);
     if lhttp.responsecode = 200 then
      begin
        Result := a
      end
      else
      begin
       b := lHTTP.Get(bURL);
       if lHTTP.ResponseCode = 200 then
        Result := b
        else
         Result := 'mydnsname.ddns.net';
      end;
  finally
    lHTTP.Free;
  end;
end;

begin
  try
    GetURLAsString('http://www.mysite01.com/conn.txt','http://www.mysite02.com/conn.txt');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.
</code>```

thanks in advance.

EDIT

the result of GetURLAsString must be 'mydnsname.ddns.net' if some of two request fail. Else, the result must be content of txt file uploaded in my site ( that is the same mydnsname.ddns.net ).

答:
By design, TIdHTTP raises an EIdHTTPProtocolException exception by default if the HTTP server returns a failure response code, like 404 NOT FOUND.

There are several different ways you can handle this:

Catch the exception:

```<code>function GetURLAsString(const aURL, bURL: string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    try
      Result := lHTTP.Get(aURL);
    except
      try
        Result := lHTTP.Get(bURL);
      except
        Result := 'mydnsname.ddns.net';
      end;
    end;
  finally
    lHTTP.Free;
  end;
end;
</code>```

Pass 404 in the AIgnoreReplies parameter of Get() so the exception is not raised on 404 errors, but still raised on other errors:

```<code>function GetURLAsString(const aURL, bURL: string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    Result := lHTTP.Get(aURL, [404]);
    if lHTTP.ResponseCode = 200 then Exit;
    Result := lHTTP.Get(bURL, [404]);
    if lHTTP.ResponseCode = 200 then Exit;
    Result := 'mydnsname.ddns.net';
  finally
    lHTTP.Free;
  end;
end;
</code>```

Enable the hoNoProtocolErrorException flag in the HTTPOptions property so the exception is not raised at all:

```<code>function GetURLAsString(const aURL, bURL: string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    lHTTP.HTTPOptions := lHTTP.HTTPOptions + [HoNoProtocolErrorException];
    Result := lHTTP.Get(aURL);
    if lHTTP.ResponseCode = 200 then Exit;
    Result := lHTTP.Get(bURL);
    if lHTTP.ResponseCode = 200 then Exit;
    Result := 'mydnsname.ddns.net';
  finally
    lHTTP.Free;
  end;
end;
</code>```

Body:
I have a txt uploaded in my site where the content of this txt file is my Noip address that must be consulted by a http request.

The trouble in my code below is that if this file was removed of site, is generated a exception and not is possible execute the folowing lines for function returns a right result.

How solve it?

program Project1;

{$APPTYPE CONSOLE}

{$R *.res}

uses
  idhttp,
  SysUtils;

function GetURLAsString(const aURL, bURL: string): string;
var
  lHTTP: TIdHTTP;
  a, b: string;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    a := lHTTP.Get(aURL);
     if lhttp.responsecode = 200 then
      begin
        Result := a
      end
      else
      begin
       b := lHTTP.Get(bURL);
       if lHTTP.ResponseCode = 200 then
        Result := b
        else
         Result := 'mydnsname.ddns.net';
      end;
  finally
    lHTTP.Free;
  end;
end;

begin
  try
    GetURLAsString('http://www.mysite01.com/conn.txt','http://www.mysite02.com/conn.txt');
  except
    on E: Exception do
      Writeln(E.ClassName, ': ', E.Message);
  end;
  Readln;
end.

thanks in advance.

EDIT

the result of GetURLAsString must be 'mydnsname.ddns.net' if some of two request fail. Else, the result must be content of txt file uploaded in my site ( that is the same mydnsname.ddns.net ).

Body:
By design, TIdHTTP raises an EIdHTTPProtocolException exception by default if the HTTP server returns a failure response code, like 404 NOT FOUND.

There are several different ways you can handle this:

Catch the exception:

function GetURLAsString(const aURL, bURL: string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    try
      Result := lHTTP.Get(aURL);
    except
      try
        Result := lHTTP.Get(bURL);
      except
        Result := 'mydnsname.ddns.net';
      end;
    end;
  finally
    lHTTP.Free;
  end;
end;

Pass 404 in the AIgnoreReplies parameter of Get() so the exception is not raised on 404 errors, but still raised on other errors:

function GetURLAsString(const aURL, bURL: string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    Result := lHTTP.Get(aURL, [404]);
    if lHTTP.ResponseCode = 200 then Exit;
    Result := lHTTP.Get(bURL, [404]);
    if lHTTP.ResponseCode = 200 then Exit;
    Result := 'mydnsname.ddns.net';
  finally
    lHTTP.Free;
  end;
end;

Enable the hoNoProtocolErrorException flag in the HTTPOptions property so the exception is not raised at all:

function GetURLAsString(const aURL, bURL: string): string;
var
  lHTTP: TIdHTTP;
begin
  lHTTP := TIdHTTP.Create(nil);
  try
    lHTTP.HTTPOptions := lHTTP.HTTPOptions + [HoNoProtocolErrorException];
    Result := lHTTP.Get(aURL);
    if lHTTP.ResponseCode = 200 then Exit;
    Result := lHTTP.Get(bURL);
    if lHTTP.ResponseCode = 200 then Exit;
    Result := 'mydnsname.ddns.net';
  finally
    lHTTP.Free;
  end;
end;


问:
All intents disappeared in API.ai agent
I have a few agents in my account and all the intents for 3 just disappeared!!! I also see a popup on the bottom right saying "You do not have rights for this operation"

Please help - how do I get my intents back AND ensure this never happens again!

答:
Seems like it's an authentication problem related to https://discuss.api.ai/t/keep-getting-logged-out-and-have-to-re-authenticate-my-google-account/8890

Logout and re-authenticate. They will come back.

Title: All intents disappeared in API.ai agent


问:
Unable to delete a row completely from GridBagSizer in wxpython
I'm trying to dynamically delete a set of buttons in a row in a GridBagSizer then reuse the cell space to generate a new set of buttons but when I try to Add the new buttons to the newly deleted row it says that I am unable to as there is an item already in that position.</p>

```<code>    def delete_tool(self, event, specific_option=None):

        for i in range(0 , 7):
            item = self.activetoolsizer.FindItemAtPosition((specific_option, i))
            item.Show(False)
            self.activetoolsizer.Layout()
        self.activetoolcount -= 1
</code>```

答:
Instead of item.Show(False) which merely hides the item, you need to use item.Destroy() which removes it.

Later you can self.activetoolsizer.Add(......) at that position and remember to use self.activetoolsizer.Layout()

Silly example (keep clicking button 1 and button 2 will be removed and then replaced):

```<code>import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)
        self.button1 = wx.Button(self,-1, "Button 1")
        self.button2 = wx.Button(self,-1, "Button 2")
        self.sizer = wx.GridBagSizer(2, 2)
        self.sizer.Add(wx.StaticText(self,-1, "Label 1"), (0, 0), flag=wx.ALIGN_CENTER)
        self.sizer.Add(self.button1, (0, 1), flag=wx.EXPAND)
        self.sizer.Add(self.button2, (1, 0), flag=wx.EXPAND)
        self.sizer.Add (wx.StaticText(self,-1, "Label 2"), (1, 1), flag=wx.ALIGN_CENTER)
        self.Bind(wx.EVT_BUTTON, self.button_click, self.button1)
        self.SetSizerAndFit(self.sizer)
        self.button_index = 3

    def button_click(self, event):
        item = self.sizer.FindItemAtPosition((1, 0))
        if (item != None):
            self.button2.Destroy()
        else:
            self.button2 = wx.Button(self,-1, "Button "+str(self.button_index))
            self.sizer.Add(self.button2, (1, 0), flag=wx.EXPAND)
            self.sizer.Layout()
            self.button_index +=1

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, "Replace item in Gridbagsizer")
        frame.Show(True)
        return True

app = MyApp()
app.MainLoop()
</code>```

Body:
I'm trying to dynamically delete a set of buttons in a row in a GridBagSizer then reuse the cell space to generate a new set of buttons but when I try to Add the new buttons to the newly deleted row it says that I am unable to as there is an item already in that position.

    def delete_tool(self, event, specific_option=None):

        for i in range(0 , 7):
            item = self.activetoolsizer.FindItemAtPosition((specific_option, i))
            item.Show(False)
            self.activetoolsizer.Layout()
        self.activetoolcount -= 1

Body:
Instead of item.Show(False) which merely hides the item, you need to use item.Destroy() which removes it.

Later you can self.activetoolsizer.Add(......) at that position and remember to use self.activetoolsizer.Layout()

Silly example (keep clicking button 1 and button 2 will be removed and then replaced):

import wx

class MyFrame(wx.Frame):
    def __init__(self, parent, id, title):
        wx.Frame.__init__(self, parent, id, title)
        self.button1 = wx.Button(self,-1, "Button 1")
        self.button2 = wx.Button(self,-1, "Button 2")
        self.sizer = wx.GridBagSizer(2, 2)
        self.sizer.Add(wx.StaticText(self,-1, "Label 1"), (0, 0), flag=wx.ALIGN_CENTER)
        self.sizer.Add(self.button1, (0, 1), flag=wx.EXPAND)
        self.sizer.Add(self.button2, (1, 0), flag=wx.EXPAND)
        self.sizer.Add (wx.StaticText(self,-1, "Label 2"), (1, 1), flag=wx.ALIGN_CENTER)
        self.Bind(wx.EVT_BUTTON, self.button_click, self.button1)
        self.SetSizerAndFit(self.sizer)
        self.button_index = 3

    def button_click(self, event):
        item = self.sizer.FindItemAtPosition((1, 0))
        if (item != None):
            self.button2.Destroy()
        else:
            self.button2 = wx.Button(self,-1, "Button "+str(self.button_index))
            self.sizer.Add(self.button2, (1, 0), flag=wx.EXPAND)
            self.sizer.Layout()
            self.button_index +=1

class MyApp(wx.App):
    def OnInit(self):
        frame = MyFrame(None, -1, "Replace item in Gridbagsizer")
        frame.Show(True)
        return True

app = MyApp()
app.MainLoop()


问:
Conditional formatting derived from formula
In cell D11, I have a date derived from a formula. (IF&Vlookup)

I have tried to insert a basic conditional formatting to highlight D11 if the date is before today's date. The format of cell D11 is date.
The conditional formatting works if I type in the date but won't if it is derived from a formula.

```<code>=IFERROR(TEXT(VLOOKUP($D$10,'Lookup data'!G6:I52,3,FALSE),"dd/mm/yyyy"),"  " )
</code>```

The conditonal formatting formula is:

```<code>=D11>TODAY()
</code>```

答:
The CF formula =D11>TODAY() is supposed to compare a date with another date.

The D11 should be a date, (not formatted as a date with TEXT function). The TEXT function represents the date in that format dd/mm/yyyy, but it is still a text and cannot be compared with a date

You may have to use the DATE function in your VLOOKUP instead. Of format the lookup table with date format. Try it out and let us know if you are stuck somewhere

Body:
In cell D11, I have a date derived from a formula. (IF&Vlookup)

I have tried to insert a basic conditional formatting to highlight D11 if the date is before today's date. The format of cell D11 is date.
The conditional formatting works if I type in the date but won't if it is derived from a formula.

=IFERROR(TEXT(VLOOKUP($D$10,'Lookup data'!G6:I52,3,FALSE),"dd/mm/yyyy"),"  " )

The conditonal formatting formula is:

=D11>TODAY()


问:
Typing a comment block and 5o *[ESC] creates extra spaces
I am learning vim and in the process learned that you can tell a command to automatically repeat itself. So this has some application in adding lines to a comment block in C code quickly.
So I would type

```<code>    \
    60a*[ESC]
    5o *[ESC]
</code>```

etc to complete the block, but the command

```<code>    5o *[ESC]
</code>```

produces

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

which doesn't seem like it is following what the command is supposed to do? Any insight as to why this would happen?

Note: If I do it without the space the behavior is as expected (a vertical line of *'s), but that space is pretty necessary to not waste some time.

SOLVED: o puts a new line directly under your cursor.

答:
I solved the problem, and am marking it solved

'o' creates a new line UNDER your cursor

Body:
I am learning vim and in the process learned that you can tell a command to automatically repeat itself. So this has some application in adding lines to a comment block in C code quickly.
So I would type

    \
    60a*[ESC]
    5o *[ESC]

etc to complete the block, but the command

    5o *[ESC]

produces

    *
     *
      *
       *
        *

which doesn't seem like it is following what the command is supposed to do? Any insight as to why this would happen?

Note: If I do it without the space the behavior is as expected (a vertical line of *'s), but that space is pretty necessary to not waste some time.

SOLVED: o puts a new line directly under your cursor.


问:
Why is my site load time so slow?
For the site contractorsequipmentdirectory.com I have a full load time of over 22 seconds according to gtmetrix. According to my waterfall chart it is the very first get that is the problem.

I was on another host and migrated to Hostgator, since the migration the site load time has tripled. Hostgator absolutely refuses to help me at all with this issue.

I have another wordpress site with the exact same plugins and themes with a 4 second load time.

答:
Try to optimise your website using result and recommendations from Google Page speed insights

https://developers.google.com/speed/pagespeed/insights/?url=contractorsequipmentdirectory.com&tab=desktop

Download optimised images, minify css and js file from bottom of page as shown in screenshot. Replace original resource with optimised downloaded resource.

Try to check combine css and js files if possible which will decrease number of requests. Decreasing number of requests will help in improving page speed.

Also try to validate HTML of your website using below url:
https://validator.w3.org

Title: Why is my site load time so slow?


问:
Angular 2 : Can't access files in assets folder
I am having an error 404, when I tried to access local file within my app.
I can't access and display a pdf that I put in a sub-folder (pdf) within assets folder.I am using cli

```<code><embed width="100%" height="100%" src="./assets/pdf/fef.pdf"/>
</code>```

the error it display "GET http://localhost:4200/app/assets/pdf/fef.pdf 404 (Not Found)"

Thanks for your help in advance

答:
You need to template bind the src change it to:

<embed width="100%" height="100%" [src]="'assets/pdf/fef.pdf'"/>```

Body:
I am having an error 404, when I tried to access local file within my app.
I can't access and display a pdf that I put in a sub-folder (pdf) within assets folder.I am using cli

<embed width="100%" height="100%" src="./assets/pdf/fef.pdf"/>

the error it display "GET http://localhost:4200/app/assets/pdf/fef.pdf 404 (Not Found)"

Thanks for your help in advance