问:
Redux-form FieldArray, handleSubmit' is not defined
I'm working to use a redux-form FieldArray. I'm having challenges connecting the form w the actual react component. When I try to submit the form, I get the following error: error    'handleSubmit' is not defined

The file is below. Am I building this form correctly in my React component? Any idea why handleSubmit is erroring?

```<code>import React from 'react';
import {Field, FieldArray, reduxForm} from 'redux-form'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as inviteActions from '../../actions/inviteActions';

let renderEmailField = ({input, label, type, meta: {touched, error}}) =>
  <div>
    <label>{label}</label>
    <div>
      <input {...input} name="email" type="email"/>
      {touched && error && <span>{error}</span>}
    </div>
  </div>

let renderEmails = ({fields, meta: {submitFailed, error}}) =>
  <ul>
    <li>
      <button type="button" onClick={() => fields.push()}>Add Email</button>
    </li>
    {fields.map((email, index) =>
      <li key={index}>
        {index > 2 && <button
          type="button"
          title="Remove Email"
          onClick={() => fields.remove(index)}
        />}
        <Field
          name={email}
          component={renderEmailField}
          label={`Email #${index + 1}`}
        />
      </li>
    )}
    {submitFailed && error && <li className="error">{error}</li>}
  </ul>

let EmailsForm = ({handleSubmit, pristine, reset, submitting}) =>
  <form onSubmit={handleSubmit}>
    <FieldArray name="emails" component={renderEmails} />
    <div>
      <button type="submit" disabled={submitting}>Submit</button>
      <button type="button" disabled={pristine || submitting} onClick={reset}>
        Clear Values
      </button>
    </div>
  </form>

class InvitePage extends React.Component {

  handleSubmit(data) {
    console.log(data)
    this.props.actions.createInvites(data);
  }

  render() {

    return (
      <div>
        <h1>Invites</h1>
        <EmailsForm onSubmit={handleSubmit}/>
      </div>
    );
  }

}

EmailsForm = reduxForm({
  form: 'emailsForm',
  initialValues: {
    emails: ['', '', '']
  },
  validate(values) {
    const errors = {}
    if (!values.emails || !values.emails.length) {
      errors.emails = {_error: 'At least one email must be entered'}
    }
    else {
      let emailsArrayErrors = []
      values.emails.forEach((email, emailIndex) => {
        const emailErrors = {}
        if (email == null || !email.trim()) {
          emailsArrayErrors[emailIndex] = 'Required'
        }
      })
      if (emailsArrayErrors.length) {
        errors.emails = emailsArrayErrors
      }
    }
    return errors
  }
})(EmailsForm)

const mapStateToProps = state => {
  return {
    currentUser: state.currentUser
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(inviteActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(InvitePage);
</code>```

答:
You have not provided onSubmit function as a prop to EmailsForm. You can pass it in two ways:

```<code>EmailsForm = reduxForm({
  form: 'emailsForm',
  ...
  onSubmit: () => {}
  ...
})(EmailsForm)
</code>```

or you can pass onSubmit as a prop while calling EmailsForm

```<code><EmailsForm onSubmit={() => {}} />
</code>```

In your case, you have to write like this:

```<code><EmailsForm onSubmit={this.handleSubmit.bind(this)}/>
</code>```

According to me, if you can re-use these small components renderEmailField, renderEmails, EmailsForm, then you can create them as a separate component as you have done now.

I would recommend, you should not separate EmailsForm from InvitePage class as you will have to pass all props from InvitePage to EmailsForm as your requirement grows. InvitePage is not serving any other purpose as of now other than passing onSubmit function.

```<code>class InvitePage extends React.Component {

  handleSubmit = data => {
    console.log(data)
    this.props.actions.createInvites(data);
  }

  render() {
    const { pristine, reset, submitting } = this.props
    return (
      <div>
        <h1>Invites</h1>
        <form onSubmit={this.handleSubmit}> // react recommends we should not bind function here. Either bind that in constructor or write handleSubmit like I have written.
          <FieldArray name="emails" component={renderEmails} />

          <div>
            <button type="submit" disabled={submitting}>Submit</button>
            <button type="button" disabled={pristine || submitting} onClick={reset}>
              Clear Values
            </button>
          </div>
        </form>
      </div>
    )
  }

}

InvitePage = reduxForm({
  form: 'emailsForm',
  initialValues: {
    emails: ['', '', ''],
  },
  validate(values) {
    ...
  }
})(InvitePage)
</code>```

Hope it works.

Try to use const rather than let if you are not changing the value of any variable.

Body:
I'm working to use a redux-form FieldArray. I'm having challenges connecting the form w the actual react component. When I try to submit the form, I get the following error: error    'handleSubmit' is not defined

The file is below. Am I building this form correctly in my React component? Any idea why handleSubmit is erroring?

import React from 'react';
import {Field, FieldArray, reduxForm} from 'redux-form'
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as inviteActions from '../../actions/inviteActions';

let renderEmailField = ({input, label, type, meta: {touched, error}}) =>

    {label}

      <input {...input} name="email" type="email"/>
      {touched && error && {error}}

let renderEmails = ({fields, meta: {submitFailed, error}}) =>

      <button type="button" onClick={() => fields.push()}>Add Email</button>

    {fields.map((email, index) =>

        {index > 2 && <button
          type="button"
          title="Remove Email"
          onClick={() => fields.remove(index)}
        />}
        <Field
          name={email}
          component={renderEmailField}
          label={`Email #${index + 1}`}
        />

    )}
    {submitFailed && error &&
{error}
}

let EmailsForm = ({handleSubmit, pristine, reset, submitting}) =>
  <form onSubmit={handleSubmit}>
    <FieldArray name="emails" component={renderEmails} />

      <button type="submit" disabled={submitting}>Submit</button>
      <button type="button" disabled={pristine || submitting} onClick={reset}>
        Clear Values
      </button>

  </form>

class InvitePage extends React.Component {

  handleSubmit(data) {
    console.log(data)
    this.props.actions.createInvites(data);
  }

  render() {

    return (

Invites

        <EmailsForm onSubmit={handleSubmit}/>

    );
  }

}

EmailsForm = reduxForm({
  form: 'emailsForm',
  initialValues: {
    emails: ['', '', '']
  },
  validate(values) {
    const errors = {}
    if (!values.emails || !values.emails.length) {
      errors.emails = {_error: 'At least one email must be entered'}
    }
    else {
      let emailsArrayErrors = []
      values.emails.forEach((email, emailIndex) => {
        const emailErrors = {}
        if (email == null || !email.trim()) {
          emailsArrayErrors[emailIndex] = 'Required'
        }
      })
      if (emailsArrayErrors.length) {
        errors.emails = emailsArrayErrors
      }
    }
    return errors
  }
})(EmailsForm)

const mapStateToProps = state => {
  return {
    currentUser: state.currentUser
  };
};

function mapDispatchToProps(dispatch) {
  return {
    actions: bindActionCreators(inviteActions, dispatch)
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(InvitePage);

Body:
You have not provided onSubmit function as a prop to EmailsForm. You can pass it in two ways:

EmailsForm = reduxForm({
  form: 'emailsForm',
  ...
  onSubmit: () => {}
  ...
})(EmailsForm)

or you can pass onSubmit as a prop while calling EmailsForm

<EmailsForm onSubmit={() => {}} />

In your case, you have to write like this:

<EmailsForm onSubmit={this.handleSubmit.bind(this)}/>

According to me, if you can re-use these small components renderEmailField, renderEmails, EmailsForm, then you can create them as a separate component as you have done now.

I would recommend, you should not separate EmailsForm from InvitePage class as you will have to pass all props from InvitePage to EmailsForm as your requirement grows. InvitePage is not serving any other purpose as of now other than passing onSubmit function.

class InvitePage extends React.Component {

  handleSubmit = data => {
    console.log(data)
    this.props.actions.createInvites(data);
  }

  render() {
    const { pristine, reset, submitting } = this.props
    return (
      <div>
        <h1>Invites</h1>
        <form onSubmit={this.handleSubmit}> // react recommends we should not bind function here. Either bind that in constructor or write handleSubmit like I have written.
          <FieldArray name="emails" component={renderEmails} />

          <div>
            <button type="submit" disabled={submitting}>Submit</button>
            <button type="button" disabled={pristine || submitting} onClick={reset}>
              Clear Values
            </button>
          </div>
        </form>
      </div>
    )
  }

}

InvitePage = reduxForm({
  form: 'emailsForm',
  initialValues: {
    emails: ['', '', ''],
  },
  validate(values) {
    ...
  }
})(InvitePage)

Hope it works.

Try to use const rather than let if you are not changing the value of any variable.


来源: stackexchange

问:
Get Filename Without Extension in Python
If I have a filename like one of these:

```<code>1.1.1.1.1.jpg

1.1.jpg

1.jpg
</code>```

How could I get only the filename, without the extension? Would a regex be appropriate?

ContentLicense: CC BY-SA 3.0

Body:
If I have a filename like one of these:

1.1.1.1.1.jpg

1.1.jpg

1.jpg

How could I get only the filename, without the extension? Would a regex be appropriate?

Body:
>>> import os
>>> os.path.splitext("1.1.1.1.1.jpg")
('1.1.1.1.1', '.jpg')

ContentLicense: CC BY-SA 2.5


问:
How to use Hibernate 5.2.10 MySQL JSON support without AttributeConverter or customUserType to map to Java Entity Class?
I am trying to map the MySQL JSON column to Java Entity class. Looking for the cleanest way of doing this.

Upon doing some research found 3 possible ways:

Extending AbstractSingleColumnStandardBasicType

Create a custom UserType

Use an attribute Converter

I used an attribute converter to convert the JSON column from String (as MySQL driver makes it to a String) to my required type -  this works with both the Hibernate V4.3.10 and V5.2.10

I tried to find if JSON is natively supported in Hibernate and found the PR https://github.com/hibernate/hibernate-orm/pull/1395, based on the PR looks like it does add JSON mapping to the MySQL Dialect hence letting Hibernate know about the JSON Column.

Does this mean I can use something like this to map to JSON Column in DB ?@Column(name="json_type_column")
 Private Object correspondingJsonAttribute;

If I cannot use it like this and need to use one of the above 3 methods, is there a reason I would need to upgrade to get the registerColumnType( Types.JAVA_OBJECT, "json" ); which is part of the PR and is present in Hibernate V5.2.10, Do I get any more features from V5.2.10 that support JSON columns?

I also looked into the corresponding test case to understand how the JSON column mapping is being done https://github.com/hibernate/hibernate-orm/blob/master/hibernate-core/src/test/java/org/hibernate/test/bytecode/enhancement/access/MixedAccessTestTask.java, this uses @Access annotation via property, looks like it sets the corresponding JSON column variable in Entity to Map after converting it from String.

Any help is much appreciated.

Thanks!

答:
Upon doing some research found 3 possible ways:

Extending AbstractSingleColumnStandardBasicType

Create a custom UserType

Use an attribute Converter

AttributeConvertor won't help you for this, but you can still use a custom UserType, or Hibernate Type Descriptors.

Does this mean I can use something like this to map to JSON Column in
DB?

```<code>@Column(name="json_type_column")  Private Object
correspondingJsonAttribute;
</code>```

No. The json type is just for JDBC so that Hibernate knows how to handle that JDBC object when setting a parameter on a PreparedStatement or when fetching a ResultSet.

Do I get any more features from V5.2.10 that support JSON columns?

No, but you just need to supply your own JSON type.

You can just use the hibernate-types which is available on Maven Central.

```<code><dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>${hibernate-types.version}</version>
</dependency>
</code>```

And use the provided JdonType from Hibernate Types as it works on MySQL, PostgreSQL, Oracle, SQL Server or H2 without doing any modifications.

Body:
Upon doing some research found 3 possible ways:

Extending AbstractSingleColumnStandardBasicType

Create a custom UserType

Use an attribute Converter

AttributeConvertor won't help you for this, but you can still use a custom UserType, or Hibernate Type Descriptors.

Does this mean I can use something like this to map to JSON Column in
DB?

@Column(name="json_type_column")  Private Object
correspondingJsonAttribute;

No. The json type is just for JDBC so that Hibernate knows how to handle that JDBC object when setting a parameter on a PreparedStatement or when fetching a ResultSet.

Do I get any more features from V5.2.10 that support JSON columns?

No, but you just need to supply your own JSON type.

You can just use the hibernate-types which is available on Maven Central.

<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-52</artifactId>
    <version>${hibernate-types.version}</version>
</dependency>

And use the provided JdonType from Hibernate Types as it works on MySQL, PostgreSQL, Oracle, SQL Server or H2 without doing any modifications.

ContentLicense: CC BY-SA 4.0


问:
HtmlHelp MS API search string
Does any one in 2017 knows how to implement calling HtmlHelp function that will open .chm file with "Search" pane and query string in it's listbox and will be able to execute this query?

I try following:

```<code>HH_FTS_QUERY query;

query.cbStruct         = sizeof(HH_FTS_QUERY);
query.fUniCodeStrings  = TRUE;
query.pszSearchQuery   = szSearchStr;
query.iProximity       = HH_FTS_DEFAULT_PROXIMITY;
query.fStemmedSearch   = TRUE;
query.fTitleOnly       = TRUE;
query.fExecute         = TRUE;
query.pszWindow        = NULL;

HWND hHelpWnd = ::HtmlHelp(m_hWnd, szFile, HH_DISPLAY_SEARCH, (DWORD_PTR)&query);
</code>```

but the query in query.pszSearchQuery won't be executed. I have opened .chm file with query.pszSearchQuery in "Search" pane's listbox on my screen, but I have to click "List Topics" myself to show results of search.

答:
With the help of HTMLHelp API - VBA, VB6 and VB2003, i will try to reply.
I believe there no API function to list topics in vc++. You have send button click event to launched help window.

```<code>LRESULT OnSearch(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
        TCHAR szBuf[128];
        GetDlgItem(IDC_EDIT1).GetWindowText(szBuf, sizeof(szBuf));

        if (!_tcslen(szBuf))
            return 0;

        //
        // First, invoke HtmlHelp with HH_DISPLAY_SEARCH.
        // It doesn't execute search, but it's need for showing 'search' tab.
        //
        HH_FTS_QUERY fq;
        ZeroMemory(&fq, sizeof(fq));
        fq.cbStruct = sizeof(fq);
        fq.fUniCodeStrings = FALSE;
        fq.pszSearchQuery = (LPCTSTR)szBuf;
        fq.iProximity       = HH_FTS_DEFAULT_PROXIMITY;
        fq.fStemmedSearch   = FALSE;
        fq.fTitleOnly       = FALSE;
        fq.fExecute         = FALSE;
        fq.pszWindow        = NULL;
        HWND hwndHelp = ::HtmlHelp(NULL, _T("realplay.chm"), HH_DISPLAY_SEARCH, (DWORD)&fq);

        //
        // Find query combobox and set query text.
        //
        HWND hPaneWnd, hPaneLast, hTabWnd, hDlgWnd, hCtlWnd;

        hPaneWnd = FindWindowEx(hwndHelp, NULL, _T("HH Child"), NULL);
        for (;;) // last HH Child
        {
            hPaneLast = FindWindowEx(hwndHelp, hPaneWnd, _T("HH Child"), NULL); // last HH Child
            if (!hPaneLast)
                break;
            hPaneWnd = hPaneLast;
        }
        ATLTRACE("hPaneWnd == %x", hPaneWnd);

        hCtlWnd = FindWindowEx(hPaneWnd, NULL, _T("Button"), NULL); // skip Tab Control
        //
        // There are two types of interfaces:
        //
        // 1.
        // Window hierarchy:
        // + Main window
        //   + HH Child
        //     + Browser ...
        //   + HH Child       <- second "HH Child" window
        //         - Edit     <- we have to fill this edit
        //         - Buttons  <- and press this buttons
        //         ...
        if (hCtlWnd)
        {
            hCtlWnd = FindWindowEx(hPaneWnd, NULL, _T("Edit"), NULL); // skip Tab Control
            // Set window text
            ATLASSERT(hCtlWnd != NULL);
            ::SendMessage(hCtlWnd, WM_SETTEXT, 0, (LPARAM)szBuf);   // fill it by our query

            ::SendMessage(hwndHelp, WM_COMMAND, 0xbc7, 0); // 0x3ee -- 'List Topics' button, it runs search
            if (::SendMessage(GetDlgItem(IDC_CHECK1), BM_GETCHECK, 0, 0) == BST_CHECKED)
                ::SendMessage(hwndHelp, WM_COMMAND, 0xbbe, 0); // 0x3f1 -- 'Display' button, it shows first item
        }
        //2.
        // Window hierarchy:
        // + Main window
        //   + HH Child
        //     + Browser ...
        //   + HH Child       <- second "HH Child" window
        //     + Tab Control
        //       + Dialog
        //         - Combobox <- we have to fill this combo
        //         - Buttons  <- and press this buttons
        //         ...
        else
        {

            hTabWnd = FindWindowEx(hPaneWnd, NULL, _T("SysTabControl32"), NULL); // skip Tab Control
            hDlgWnd = FindWindowEx(hTabWnd, NULL, NULL, NULL); // skip dialog

            TCHAR szClass[64];
            GetClassName(hDlgWnd, szClass, sizeof(szClass));
            ATLTRACE("hDlgWnd(1) == %x", hDlgWnd);
            if (!_tcsstr(szClass, "#")) // Is it dialog?
                hDlgWnd = FindWindowEx(hTabWnd, hDlgWnd, NULL, NULL); // skip dialog
            hCtlWnd = FindWindowEx(hDlgWnd, NULL, _T("ComboBox"), NULL); // well, it's combobox

            // Set window text
            ATLASSERT(hCtlWnd != NULL);
            ::SendMessage(hCtlWnd, WM_SETTEXT, 0, (LPARAM)szBuf);   // fill it by our query

            //
            // Run search and show first finded page
            //
            ::SendMessage(hwndHelp, WM_COMMAND, 0x3ee, 0); // 0x3ee -- 'List Topics' button, it runs search
            if (::SendMessage(GetDlgItem(IDC_CHECK1), BM_GETCHECK, 0, 0) == BST_CHECKED)
                ::SendMessage(hwndHelp, WM_COMMAND, 0x3f1, 0); // 0x3f1 -- 'Display' button, it shows first item
        }
        return 0;
}
</code>```

EDIT:

You can get control ID of List Topic by spy++

Title: HtmlHelp MS API search string

Body:
Does any one in 2017 knows how to implement calling HtmlHelp function that will open .chm file with "Search" pane and query string in it's listbox and will be able to execute this query?

I try following:

HH_FTS_QUERY query;

query.cbStruct         = sizeof(HH_FTS_QUERY);
query.fUniCodeStrings  = TRUE;
query.pszSearchQuery   = szSearchStr;
query.iProximity       = HH_FTS_DEFAULT_PROXIMITY;
query.fStemmedSearch   = TRUE;
query.fTitleOnly       = TRUE;
query.fExecute         = TRUE;
query.pszWindow        = NULL;

HWND hHelpWnd = ::HtmlHelp(m_hWnd, szFile, HH_DISPLAY_SEARCH, (DWORD_PTR)&query);

but the query in query.pszSearchQuery won't be executed. I have opened .chm file with query.pszSearchQuery in "Search" pane's listbox on my screen, but I have to click "List Topics" myself to show results of search.

Body:
With the help of HTMLHelp API - VBA, VB6 and VB2003, i will try to reply.
I believe there no API function to list topics in vc++. You have send button click event to launched help window.

LRESULT OnSearch(WORD /*wNotifyCode*/, WORD wID, HWND /*hWndCtl*/, BOOL& /*bHandled*/)
{
        TCHAR szBuf[128];
        GetDlgItem(IDC_EDIT1).GetWindowText(szBuf, sizeof(szBuf));

        if (!_tcslen(szBuf))
            return 0;

        //
        // First, invoke HtmlHelp with HH_DISPLAY_SEARCH.
        // It doesn't execute search, but it's need for showing 'search' tab.
        //
        HH_FTS_QUERY fq;
        ZeroMemory(&fq, sizeof(fq));
        fq.cbStruct = sizeof(fq);
        fq.fUniCodeStrings = FALSE;
        fq.pszSearchQuery = (LPCTSTR)szBuf;
        fq.iProximity       = HH_FTS_DEFAULT_PROXIMITY;
        fq.fStemmedSearch   = FALSE;
        fq.fTitleOnly       = FALSE;
        fq.fExecute         = FALSE;
        fq.pszWindow        = NULL;
        HWND hwndHelp = ::HtmlHelp(NULL, _T("realplay.chm"), HH_DISPLAY_SEARCH, (DWORD)&fq);

        //
        // Find query combobox and set query text.
        //
        HWND hPaneWnd, hPaneLast, hTabWnd, hDlgWnd, hCtlWnd;

        hPaneWnd = FindWindowEx(hwndHelp, NULL, _T("HH Child"), NULL);
        for (;;) // last HH Child
        {
            hPaneLast = FindWindowEx(hwndHelp, hPaneWnd, _T("HH Child"), NULL); // last HH Child
            if (!hPaneLast)
                break;
            hPaneWnd = hPaneLast;
        }
        ATLTRACE("hPaneWnd == %x", hPaneWnd);

        hCtlWnd = FindWindowEx(hPaneWnd, NULL, _T("Button"), NULL); // skip Tab Control
        //
        // There are two types of interfaces:
        //
        // 1.
        // Window hierarchy:
        // + Main window
        //   + HH Child
        //     + Browser ...
        //   + HH Child       <- second "HH Child" window
        //         - Edit     <- we have to fill this edit
        //         - Buttons  <- and press this buttons
        //         ...
        if (hCtlWnd)
        {
            hCtlWnd = FindWindowEx(hPaneWnd, NULL, _T("Edit"), NULL); // skip Tab Control
            // Set window text
            ATLASSERT(hCtlWnd != NULL);
            ::SendMessage(hCtlWnd, WM_SETTEXT, 0, (LPARAM)szBuf);   // fill it by our query

            ::SendMessage(hwndHelp, WM_COMMAND, 0xbc7, 0); // 0x3ee -- 'List Topics' button, it runs search
            if (::SendMessage(GetDlgItem(IDC_CHECK1), BM_GETCHECK, 0, 0) == BST_CHECKED)
                ::SendMessage(hwndHelp, WM_COMMAND, 0xbbe, 0); // 0x3f1 -- 'Display' button, it shows first item
        }
        //2.
        // Window hierarchy:
        // + Main window
        //   + HH Child
        //     + Browser ...
        //   + HH Child       <- second "HH Child" window
        //     + Tab Control
        //       + Dialog
        //         - Combobox <- we have to fill this combo
        //         - Buttons  <- and press this buttons
        //         ...
        else
        {

            hTabWnd = FindWindowEx(hPaneWnd, NULL, _T("SysTabControl32"), NULL); // skip Tab Control
            hDlgWnd = FindWindowEx(hTabWnd, NULL, NULL, NULL); // skip dialog

            TCHAR szClass[64];
            GetClassName(hDlgWnd, szClass, sizeof(szClass));
            ATLTRACE("hDlgWnd(1) == %x", hDlgWnd);
            if (!_tcsstr(szClass, "#")) // Is it dialog?
                hDlgWnd = FindWindowEx(hTabWnd, hDlgWnd, NULL, NULL); // skip dialog
            hCtlWnd = FindWindowEx(hDlgWnd, NULL, _T("ComboBox"), NULL); // well, it's combobox

            // Set window text
            ATLASSERT(hCtlWnd != NULL);
            ::SendMessage(hCtlWnd, WM_SETTEXT, 0, (LPARAM)szBuf);   // fill it by our query

            //
            // Run search and show first finded page
            //
            ::SendMessage(hwndHelp, WM_COMMAND, 0x3ee, 0); // 0x3ee -- 'List Topics' button, it runs search
            if (::SendMessage(GetDlgItem(IDC_CHECK1), BM_GETCHECK, 0, 0) == BST_CHECKED)
                ::SendMessage(hwndHelp, WM_COMMAND, 0x3f1, 0); // 0x3f1 -- 'Display' button, it shows first item
        }
        return 0;
}

EDIT:

You can get control ID of List Topic by spy++


问:
Display particular category image in stencil bigcommerce
I am working in Mega menu and i have add some new functionality i have display less than two category image in my mega menu how can i display? I am use stancil framwork.

i have use this code:

```<code><ul class="col-2">
    <li class="menuFeat">
        <a href="#">Image:
        {{category.subcategories.image}}
        </a>
    </li>

</ul>
</code>```

project link:
http://ptg6.mybigcommerce.com

答:
As I understood you want to show each category image into your mega menu so let's go if I am right.

Step 1: Open your admin end and then open your themes file editor I hope you know well how to open it.

Step 2  Go to components-> common -> navigation-list.html

Step 3  replace{{name}}   with this one {{name}}

check screenshot http://prntscr.com/fhocrk

and it will look like this one  http://deepak-diwan-s-store.mybigcommerce.com/

check all menus in my store, one more thing category should have images assigned from the back end.

Body:
I am working in Mega menu and i have add some new functionality i have display less than two category image in my mega menu how can i display? I am use stancil framwork.

i have use this code:

        Image:
        {{category.subcategories.image}}

project link:
http://ptg6.mybigcommerce.com

Body:
As I understood you want to show each category image into your mega menu so let's go if I am right.

Step 1: Open your admin end and then open your themes file editor I hope you know well how to open it.

Step 2  Go to components-> common -> navigation-list.html

Step 3  replace<a class="navPage-subMenu-action navPages-action" href="{{url}}">{{name}}</a>   with this one <a class="navPage-subMenu-action navPages-action" href="{{url}}">{{name}}<img src="{{getImage image "thumbnail"}}"></a>

check screenshot http://prntscr.com/fhocrk

and it will look like this one  http://deepak-diwan-s-store.mybigcommerce.com/

check all menus in my store, one more thing category should have images assigned from the back end.


问:
Is there any risk upgrading to Xcode 9 while working on projects to be released soon?
I'm currently working on an app that is soon to be released. This would tend to push me to wait before upgrading to Xcode 9 beta just to make sure my environment is stable but ARKit is making me really curious and I'm thinking about updating asap :).

For those of you who are already the Xcode 9 Beta, are you experiencing any difficulties working on your previous projects?

That might be a trivial questions but I had issues in the past when updating Xcode, hence why I ask this time.

答:
[edit]: it is now safe to upgrade to Xcode 9 (and Swift 3.2 or Swift 4) for releasing on iTunesConnect.

[original message follows (when Xcode 9 was only a beta)]

iTunes Connect requires AppStore submissions to be done with a stable release of Xcode, so no, you can't upgrade safely yet for a release.

Currently, for the period June, July, August, early September 2017, you can use most (but not all) versions of Xcode between 6.0.1 and 8.3.3 for a submission to AppStore.

Likely, early-September 2017 will be opened to submissions from Xcode 9. And I bet that around January 2018 support for Xcode 6 will be dropped, keeping only the range Xcode7-Xcode9.

This does not impact TestFlight: you can already submit test builds from Xcode 9 beta to TestFlight.

So just keep multiple installations of Xcode by renaming the app eventually, so that you always keep a stable version available.

And don't upgrade your code to Swift 4 using a custom toolchain for submission with Xcode 8: iTunes Connect only accepts for submission Swift toolchains natively bundled with the Xcode you're using. Yet, you can eventually write code like:

```<code>#if swift(>=3.2)
    // for Xcode 9 beta
#else
    // for Xcode 8 and release on AppStore
#endif
</code>```

Body:
[edit]: it is now safe to upgrade to Xcode 9 (and Swift 3.2 or Swift 4) for releasing on iTunesConnect.

[original message follows (when Xcode 9 was only a beta)]

iTunes Connect requires AppStore submissions to be done with a stable release of Xcode, so no, you can't upgrade safely yet for a release.

Currently, for the period June, July, August, early September 2017, you can use most (but not all) versions of Xcode between 6.0.1 and 8.3.3 for a submission to AppStore.

Likely, early-September 2017 will be opened to submissions from Xcode 9. And I bet that around January 2018 support for Xcode 6 will be dropped, keeping only the range Xcode7-Xcode9.

This does not impact TestFlight: you can already submit test builds from Xcode 9 beta to TestFlight.

So just keep multiple installations of Xcode by renaming the app eventually, so that you always keep a stable version available.

And don't upgrade your code to Swift 4 using a custom toolchain for submission with Xcode 8: iTunes Connect only accepts for submission Swift toolchains natively bundled with the Xcode you're using. Yet, you can eventually write code like:

#if swift(>=3.2)
    // for Xcode 9 beta
#else
    // for Xcode 8 and release on AppStore
#endif


问:
What's the difference between using a stateless functional component versus calling a method?
I'm trying to understand stateless components and what the difference is between these examples:

```<code>class App {
  render() {
    return (
      <div>
        {this.renderAFunction('hello')}
      </div>
    );
  }
  renderAFunction(text) {
    return (
      <p>{text}</p>
    );
  }
}
</code>```

and this:

```<code>class App {
  render() {
    return(
      <div>
        <RenderAFunction text='hello'/>
      </div>
    );
  }
}

const RenderAFunction = ({text}) => (
    <p>{text}</p>
);
</code>```

Or if there is any difference at all?

答:
Your App's render function  will be translated into following JS code for your first example:

```<code>render() {
   return React.createElement(
     'div',
     null,
     this.renderAFunction('hello')
   );
 }
</code>```

And the following one for the second one:

```<code>render() {
  return React.createElement(
    'div',
    null,
    React.createElement(RenderAFunction, { text: 'hello' })
  );
}
</code>```

While they both looks almost the same, there is one significant difference: laziness. React will execute RenderAFunction body only in case it gonna be mounted to the DOM hierarchy.

It is insignificant is your case, but imaging following example:

```<code>const LazyApp = () => {
  const heavy = <div><HeavyStuff /></div>
  // ...
  return <div>done it</div>
}

const HardWorkingApp = () => {
  const heavy = <div>{HeavyStuff()}</div>
  // ...
  return <div>done it</div>
}

const HeavyStuff = () => {
  // ... do heavy rendering here
}
</code>```

Lazy app will not perform any heavy stuff at all. Maybe it is not very clear from that synthetic example why one would do anything like that at all. But there are real-world examples out there, when something conceptually similar (creating Components without rendering them) is happening.

Body:
I'm trying to understand stateless components and what the difference is between these examples:

class App {
  render() {
    return (

        {this.renderAFunction('hello')}

    );
  }
  renderAFunction(text) {
    return (

{text}

    );
  }
}

and this:

class App {
  render() {
    return(

        <RenderAFunction text='hello'/>

    );
  }
}

const RenderAFunction = ({text}) => (

{text}

);

Or if there is any difference at all?

Body:
Your App's render function  will be translated into following JS code for your first example:

render() {
   return React.createElement(
     'div',
     null,
     this.renderAFunction('hello')
   );
 }

And the following one for the second one:

render() {
  return React.createElement(
    'div',
    null,
    React.createElement(RenderAFunction, { text: 'hello' })
  );
}

While they both looks almost the same, there is one significant difference: laziness. React will execute RenderAFunction body only in case it gonna be mounted to the DOM hierarchy.

It is insignificant is your case, but imaging following example:

const LazyApp = () => {
  const heavy = <div><HeavyStuff /></div>
  // ...
  return <div>done it</div>
}

const HardWorkingApp = () => {
  const heavy = <div>{HeavyStuff()}</div>
  // ...
  return <div>done it</div>
}

const HeavyStuff = () => {
  // ... do heavy rendering here
}

Lazy app will not perform any heavy stuff at all. Maybe it is not very clear from that synthetic example why one would do anything like that at all. But there are real-world examples out there, when something conceptually similar (creating Components without rendering them) is happening.


问:
Android Facebook Share Button asking for password again
I'm logged in in my app with a parse session linked with facebook. When I try to share a post to facebook it shows me the facebook window to login again. Why does it do that if I'm already logged in? I checked and the AccessToken.getCurrentAccessToken() is not null when I call the ShareDialog, so there is the session. What's wrong?

WelcomeActivity

```<code>public void initializeFacebookButton() {

    if (AccessToken.getCurrentAccessToken() == null)
        ParseFacebookUtils.initialize(this);

    mLoginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressBar.setVisibility(View.VISIBLE);
            ParseFacebookUtils.logInWithReadPermissionsInBackground(WelcomeActivity.this,
                    read_permissions, new LogInCallback() {
                        @Override
                        public void done(ParseUser user, ParseException e) {
                            progressBar.setVisibility(View.GONE);
                            if (e == null && user !=  null){
                                ParseFacebookUtils.linkWithPublishPermissionsInBackground(user,
                                        WelcomeActivity.this, publish_permission);
                                Log.d(TAG, "logged in");
                                   presenter.getUserFacebook(AccessToken.getCurrentAccessToken(),
                                        user);
                            } else {
                                Log.e(TAG, "Error logging in ");
                            }
                        }
                    });
        }
    });
}
</code>```

ShareActivity

```<code>Button shareButton;

shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
                .putString("og:type", "fitness.course")
                .putString("og:title", title)
                .putString("og:description", description)
                .putInt("fitness:duration:value", time_in_seconds)
                .putString("fitness:duration:units", "s")
                .putDouble("fitness:metrics:location:latitude", latitude)
                .putDouble("fitness:metrics:location:longitude", longitude)
                .build();
        ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
                .setActionType("fitness.runs")
                .putObject("fitness:course", object)
                .build();
        ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
                .setPreviewPropertyName("fitness:course")
                .setAction(action)
                .build();

                ShareDialog.show(ShareActivity.this, content);
            }
        });
</code>```

答:
I think your problem is this -

```<code>ParseFacebookUtils.logInWithReadPermissionsInBackground(WelcomeActivity.this,
                    read_permissions,
</code>```

You need to get publish permissions - refer here

Check - logInWithReadPermissionsInBackground

Body:
I'm logged in in my app with a parse session linked with facebook. When I try to share a post to facebook it shows me the facebook window to login again. Why does it do that if I'm already logged in? I checked and the AccessToken.getCurrentAccessToken() is not null when I call the ShareDialog, so there is the session. What's wrong?

WelcomeActivity

public void initializeFacebookButton() {

    if (AccessToken.getCurrentAccessToken() == null)
        ParseFacebookUtils.initialize(this);

    mLoginButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            progressBar.setVisibility(View.VISIBLE);
            ParseFacebookUtils.logInWithReadPermissionsInBackground(WelcomeActivity.this,
                    read_permissions, new LogInCallback() {
                        @Override
                        public void done(ParseUser user, ParseException e) {
                            progressBar.setVisibility(View.GONE);
                            if (e == null && user !=  null){
                                ParseFacebookUtils.linkWithPublishPermissionsInBackground(user,
                                        WelcomeActivity.this, publish_permission);
                                Log.d(TAG, "logged in");
                                   presenter.getUserFacebook(AccessToken.getCurrentAccessToken(),
                                        user);
                            } else {
                                Log.e(TAG, "Error logging in ");
                            }
                        }
                    });
        }
    });
}

ShareActivity

Button shareButton;

shareButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                ShareOpenGraphObject object = new ShareOpenGraphObject.Builder()
                .putString("og:type", "fitness.course")
                .putString("og:title", title)
                .putString("og:description", description)
                .putInt("fitness:duration:value", time_in_seconds)
                .putString("fitness:duration:units", "s")
                .putDouble("fitness:metrics:location:latitude", latitude)
                .putDouble("fitness:metrics:location:longitude", longitude)
                .build();
        ShareOpenGraphAction action = new ShareOpenGraphAction.Builder()
                .setActionType("fitness.runs")
                .putObject("fitness:course", object)
                .build();
        ShareOpenGraphContent content = new ShareOpenGraphContent.Builder()
                .setPreviewPropertyName("fitness:course")
                .setAction(action)
                .build();

                ShareDialog.show(ShareActivity.this, content);
            }
        });

Body:
I think your problem is this -

ParseFacebookUtils.logInWithReadPermissionsInBackground(WelcomeActivity.this,
                    read_permissions,

You need to get publish permissions - refer here

Check - logInWithReadPermissionsInBackground


问:
How can I display image behind div with bootstrap?
I have 2 rows in my container. In the second row I have 2 elements one and two. Now I am trying to display the image behind those too almost like a background. This is the html:

```<code><div class="container">
  <div class="row">
    <img src="someimageurl" alt="" />
  </div>
  <div class="row">
    <div class="col-md-6">one</div>
    <div class="col-md-6">two</div>
  </div>
</div>
</code>```

codepen

答:
use css to do that

```<code>#{your div ID}{
background-image: url("backgroundImage.png");
}
</code>```

i think this may be help you

Body:
I have 2 rows in my container. In the second row I have 2 elements one and two. Now I am trying to display the image behind those too almost like a background. This is the html:

one

two

codepen

Body:
use css to do that

#{your div ID}{
background-image: url("backgroundImage.png");
}

i think this may be help you


问:
RN Listview taking each character as a row of given json string
I have used Listview in other projects and just copied the code from there but now having an issue which I am not getting how to tackle.

I am having the following json got from my server and stored in my session class which I am using as a data source, But the render row does not take objects as a row item instead taking each character as a new row item , whic i have checked during debugging. using the following  code,any help is appreciated

JSON

```<code>[{"id":1,"name":null,"fullName":"Behraj Khan "},{"id":2,"name":null,"fullName":"Fareeha "},{"id":3,"name":null,"fullName":"Kashif "}]
</code>```

Code

```<code> constructor(props) {
          super(props);

            const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
            var facultyMembers;
            if(SessionManager.getSessionValue(Constants.FACULTY_MEMBERS) !== null){
                facultyMembers = SessionManager.getSessionValue(Constants.FACULTY_MEMBERS);
            }
            this.state = {
                 dataSource: ds.cloneWithRows(facultyMembers)
              };
          }

 render() {
        return (
            <View style={styles.container}>
                <ListView
                    style={styles.listviewcontainer}
                    dataSource={this.state.dataSource}
                    renderRow={(row) => this.renderRow(row)}
                    renderHeader={this.state.showHeader ? () => this.renderHeader(this.state.headerText) : () => {
                    }}
                    renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator}/>}
                />
            </View>
        );
    }

renderRow = (rowData) => (
        <TouchableHighlight underlayColor='gainsboro' onPress={() => {
            this.state.onPress(rowData)
        }}>
            <View style={styles.row}>
                <Text style={styles.header}>
                    {rowData.fullName}
                </Text>
            </View>
        </TouchableHighlight>
    );
</code>```

In first iteration of renderRow i got [
in second i got {
in third i got " and so on

答:
As per @MattAft and @Garrett McCullough, I was not parsing the string back to JSON as I was expecting I already getting the JSON

hence this simple solution works

```<code>ds.cloneWithRows(JSON.parse(facultyMembers))
</code>```

Body:
I have used Listview in other projects and just copied the code from there but now having an issue which I am not getting how to tackle.

I am having the following json got from my server and stored in my session class which I am using as a data source, But the render row does not take objects as a row item instead taking each character as a new row item , whic i have checked during debugging. using the following  code,any help is appreciated

JSON

[{"id":1,"name":null,"fullName":"Behraj Khan "},{"id":2,"name":null,"fullName":"Fareeha "},{"id":3,"name":null,"fullName":"Kashif "}]

Code

 constructor(props) {
          super(props);

            const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
            var facultyMembers;
            if(SessionManager.getSessionValue(Constants.FACULTY_MEMBERS) !== null){
                facultyMembers = SessionManager.getSessionValue(Constants.FACULTY_MEMBERS);
            }
            this.state = {
                 dataSource: ds.cloneWithRows(facultyMembers)
              };
          }

 render() {
        return (
            <View style={styles.container}>
                <ListView
                    style={styles.listviewcontainer}
                    dataSource={this.state.dataSource}
                    renderRow={(row) => this.renderRow(row)}
                    renderHeader={this.state.showHeader ? () => this.renderHeader(this.state.headerText) : () => {
                    }}
                    renderSeparator={(sectionId, rowId) => <View key={rowId} style={styles.separator}/>}
                />
            </View>
        );
    }

renderRow = (rowData) => (
        <TouchableHighlight underlayColor='gainsboro' onPress={() => {
            this.state.onPress(rowData)
        }}>
            <View style={styles.row}>
                <Text style={styles.header}>
                    {rowData.fullName}
                </Text>
            </View>
        </TouchableHighlight>
    );

In first iteration of renderRow i got [
in second i got {
in third i got " and so on

Body:
As per @MattAft and @Garrett McCullough, I was not parsing the string back to JSON as I was expecting I already getting the JSON

hence this simple solution works

ds.cloneWithRows(JSON.parse(facultyMembers))


问:
Problems trying to animate my objects in jquery
I am trying to make my character move diagonally. My aim is to make him move towards the door depending on which door I click. There are two doors on the screen; top-left door and top-right door. Right now when I click on the top-left door he moves towards that door, but when I click on the top-right door he moves straight. I don't know where I'm going wrong with this and I could really use some help.

Here is the code that I have so far:

$(document).ready(function() {

  //center the character
  function centreThing(obj) {
    //this is the height and width of heartless
    h = $(obj).height();
    w = $(obj).width();
    $(obj).css({
      //this is the height and width of the stage
      //height and width of stage by 2 - height and width of heartless by 2
      top: $('#stage').height() / 2 - h / 2,
      left: $('#stage').width() / 2 - w / 2,
      right: $('#stage').width() / 2 - w / 2
    })
  }
  centreThing('#character');

  //speech
  var progress = 0;
  var txt;

  //click the door to go to next page
  //animate character to the left door
  $('#door1').click(function() {
    $('#character').animate({
      top: 0,
      left: 150
    }, {
      duration: 1000,
      complete: function() {
        alert("entered");
      }
    });
  });

  //click the door to go to next page
  //animate character to the right door
  $('#door2').click(function() {
    $('#character').animate({
      top: 0,
      right: 150
    }, {
      duration: 1000,
      complete: function() {
        alert("entered");
      }
    });
  });

}); // do not delete this line```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#character {
  position: absolute;
  bottom: 0px;
  left: 0px;
  right: 0px;
  z-index: 99;
}

#door1 {
  background-image: url("https://placehold.it/50x50?text=closeddoor");
  position: absolute;
  width: 80px;
  height: 60px;
  top: -3px;
  left: 130px;
  z-index: 5;
}

#door1:hover {
  background-image: url("https://placehold.it/50x50?text=opendoor");
  position: absolute;
  width: 80px;
  height: 60px;
  top: -3px;
  left: 130px;
}

#door2 {
  background-image: url("https://placehold.it/50x50?text=closeddoor");
  position: absolute;
  width: 80px;
  height: 60px;
  top: -3px;
  left: 510px;
}

#door2:hover {
  background-image: url("https://placehold.it/50x50?text=opendoor");
  position: absolute;
  width: 80px;
  height: 60px;
  top: -3px;
  left: 510px;
  z-index: 5;
}

#stage {
  position: relative;
  width: 720px;
  height: 480px;
  margin: auto;
  margin-top: 100px;
  background-color: black;
  border-style: solid;
  border-width: 5px;
  border-color: white;
}</code>```

<!doctype html>

  <meta charset="utf-8">
  <title>MAS340</title>

```

答:
Try it like this.Reset the left position on clicking the #door2.It happens baecause you have set the left position of the character in centreThing().So on clicking the #door2 the character has left,right and top value.So it is starting at the left value.I have removed the  left value on clicking on  #door2 and it worked

$(document).ready(function() {

 //center the character
 function centreThing(obj) {
 //this is the height and width of heartless
  h = $(obj).height();
  w = $(obj).width();
  $(obj).css({
   //this is the height and width of the stage
   //height and width of stage by 2 - height and width of heartless by 2
   top: $('#stage').height()/2-h/2,
   left: $('#stage').width()/2-w/2,
   right: $('#stage').width()/2-w/2
  })
 }
 centreThing('#character');

 //speech
 var progress = 0;
 var txt;

 //click the door to go to next page
 //animate character to the left door
 $('#door1').click(function() {
  $('#character').animate({
   top: 0,
   left: 150
  }, {
   duration: 1000,
   complete: function() {
        alert("entered");
   }
  });
 });

 //click the door to go to next page
 //animate character to the right door
 $('#door2').click(function() {
     $('#character').css({
       'left':''
     }).animate({
   top: 0,
   right: 150
  }, {
   duration: 1000,
   complete: function() {
        alert("entered on 2");
   }
  });
 });

}); // do not delete this line```
<pre class="snippet-code-css lang-css prettyprint-override"><code>#character {
 position: absolute;
/* bottom: 0px;
 left: 0px;
 right: 0px;*/
 z-index: 99;
}

#door1 {
  background:#F00;
 background-image: url(images/closeddoor.png);
 position: absolute;
 width: 80px;
 height: 60px;
 top: -3px;
 left: 130px;
 z-index: 5;
}

#door1:hover {
 background-image: url(images/opendoor.png);
 position: absolute;
 width: 80px;
 height: 60px;
 top: -3px;
 left: 130px;
}

#door2 {
  background:#FF0;
 background-image: url(images/closeddoor.png);
 position: absolute;
 width: 80px;
 height: 60px;
 top: -3px;
 left: 510px;
}

#door2:hover {
 background-image: url(images/opendoor.png);
 position: absolute;
 width: 80px;
 height: 60px;
 top: -3px;
 left: 510px;
 z-index: 5;
}

#stage {
 position: relative;
 width: 720px;
 height: 480px;
 margin: auto;
 margin-top: 100px;
 background-color: black;
 border-style: solid;
 border-width: 5px;
 border-color: white;
}</code>```

<!doctype html>

<meta charset="utf-8">
<title>MAS340</title>
<link href="styles.css" rel="stylesheet" />

```

Body:
I am trying to make my character move diagonally. My aim is to make him move towards the door depending on which door I click. There are two doors on the screen; top-left door and top-right door. Right now when I click on the top-left door he moves towards that door, but when I click on the top-right door he moves straight. I don't know where I'm going wrong with this and I could really use some help.

Here is the code that I have so far:

$(document).ready(function() {

  //center the character
  function centreThing(obj) {
    //this is the height and width of heartless
    h = $(obj).height();
    w = $(obj).width();
    $(obj).css({
      //this is the height and width of the stage
      //height and width of stage by 2 - height and width of heartless by 2
      top: $('#stage').height() / 2 - h / 2,
      left: $('#stage').width() / 2 - w / 2,
      right: $('#stage').width() / 2 - w / 2
    })
  }
  centreThing('#character');

  //speech
  var progress = 0;
  var txt;

  //click the door to go to next page
  //animate character to the left door
  $('#door1').click(function() {
    $('#character').animate({
      top: 0,
      left: 150
    }, {
      duration: 1000,
      complete: function() {
        alert("entered");
      }
    });
  });

  //click the door to go to next page
  //animate character to the right door
  $('#door2').click(function() {
    $('#character').animate({
      top: 0,
      right: 150
    }, {
      duration: 1000,
      complete: function() {
        alert("entered");
      }
    });
  });

}); // do not delete this line

#character {
  position: absolute;
  bottom: 0px;
  left: 0px;
  right: 0px;
  z-index: 99;
}

#door1 {
  background-image: url("https://placehold.it/50x50?text=closeddoor");
  position: absolute;
  width: 80px;
  height: 60px;
  top: -3px;
  left: 130px;
  z-index: 5;
}

#door1:hover {
  background-image: url("https://placehold.it/50x50?text=opendoor");
  position: absolute;
  width: 80px;
  height: 60px;
  top: -3px;
  left: 130px;
}

#door2 {
  background-image: url("https://placehold.it/50x50?text=closeddoor");
  position: absolute;
  width: 80px;
  height: 60px;
  top: -3px;
  left: 510px;
}

#door2:hover {
  background-image: url("https://placehold.it/50x50?text=opendoor");
  position: absolute;
  width: 80px;
  height: 60px;
  top: -3px;
  left: 510px;
  z-index: 5;
}

#stage {
  position: relative;
  width: 720px;
  height: 480px;
  margin: auto;
  margin-top: 100px;
  background-color: black;
  border-style: solid;
  border-width: 5px;
  border-color: white;
}

<!doctype html>

  <meta charset="utf-8">
  <title>MAS340</title>

Body:
Try it like this.Reset the left position on clicking the #door2.It happens baecause you have set the left position of the character in centreThing().So on clicking the #door2 the character has left,right and top value.So it is starting at the left value.I have removed the  left value on clicking on  #door2 and it worked

$(document).ready(function() {

 //center the character
 function centreThing(obj) {
 //this is the height and width of heartless
  h = $(obj).height();
  w = $(obj).width();
  $(obj).css({
   //this is the height and width of the stage
   //height and width of stage by 2 - height and width of heartless by 2
   top: $('#stage').height()/2-h/2,
   left: $('#stage').width()/2-w/2,
   right: $('#stage').width()/2-w/2
  })
 }
 centreThing('#character');

 //speech
 var progress = 0;
 var txt;

 //click the door to go to next page
 //animate character to the left door
 $('#door1').click(function() {
  $('#character').animate({
   top: 0,
   left: 150
  }, {
   duration: 1000,
   complete: function() {
        alert("entered");
   }
  });
 });

 //click the door to go to next page
 //animate character to the right door
 $('#door2').click(function() {
     $('#character').css({
       'left':''
     }).animate({
   top: 0,
   right: 150
  }, {
   duration: 1000,
   complete: function() {
        alert("entered on 2");
   }
  });
 });

}); // do not delete this line

#character {
 position: absolute;
/* bottom: 0px;
 left: 0px;
 right: 0px;*/
 z-index: 99;
}

#door1 {
  background:#F00;
 background-image: url(images/closeddoor.png);
 position: absolute;
 width: 80px;
 height: 60px;
 top: -3px;
 left: 130px;
 z-index: 5;
}

#door1:hover {
 background-image: url(images/opendoor.png);
 position: absolute;
 width: 80px;
 height: 60px;
 top: -3px;
 left: 130px;
}

#door2 {
  background:#FF0;
 background-image: url(images/closeddoor.png);
 position: absolute;
 width: 80px;
 height: 60px;
 top: -3px;
 left: 510px;
}

#door2:hover {
 background-image: url(images/opendoor.png);
 position: absolute;
 width: 80px;
 height: 60px;
 top: -3px;
 left: 510px;
 z-index: 5;
}

#stage {
 position: relative;
 width: 720px;
 height: 480px;
 margin: auto;
 margin-top: 100px;
 background-color: black;
 border-style: solid;
 border-width: 5px;
 border-color: white;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>MAS340</title>
<link href="styles.css" rel="stylesheet" />
<script src="jquery-3.1.1.min.js"></script>
<script>
</script>
</head>
<body>
 <div id="stage">
  <img src="images/character.png" id="character" class="center">
  <div id='door1'></div>
  <div id='door2'></div>
 </div>
</body>
</html>


问:
using numpy arrays for integer and array inputs
I am a Matlab user, and trying to move into Python. I tried to code a minimal example of de2bi function (which converts a decimal into binary as right-msb) in Python which I had before in Matlab. But, I am confused with numpy arrays.

Python code:

```<code>import numpy as np

def de2bi(d, n)
    d = np.array(d)
    power = 2**np.arange(n)
    d = d * np.ones((1,n))
    b = np.floor((d%(2*power))/power)
    return b
</code>```

Python output:

```<code>>>> print(de2bi(13,8))
[[ 1.  0.  1.  1.  0.  0.  0.  0.]]

print(de2bi([13,15],8)) #This line fails
</code>```

Matlab code:

```<code>function b = d2b( d, n )
    d = d(:);
    power = ones(length(d), 1)*(2.^(0 : n-1));
    d = d * ones(1, n);
    b = floor(rem(d, 2*power)./power);
end
</code>```

Matlab output:

```<code>>> d2b(13,8)

ans =

     1     0     1     1     0     0     0     0

>> d2b([13,15],8)

ans =

     1     0     1     1     0     0     0     0
     1     1     1     1     0     0     0     0
</code>```

Matlab code is working both for integer inputs and array of integers. But python code works for integer inputs, but keeps failing for arrays. How to manage operations both for integers and integer arrays in Python automatically? It may be a very easy question, excuse me, but I am a very newbie in python.

Thanks in advance.

答:
Your problem is with the multiplication: d = d * np.ones((1,n)). NumPy attemps to perform an element-wise multiplication, which would fail because of dimension mismatch (your ones array has only one row). When d is scalar though, NumPy can infer that you mean multiply to scalar, hence the code would run.

What you really want to do (as I understand) is to expand each element to an n-length row. A possible solution would be to create an intermediate array to hold the new values, since the size of an array is not changeable:

```<code>def d2b(d, n):
    d = np.array(d)
    d = np.reshape(d, (1, -1))
    power = np.flipud(2**np.arange(n))

    g = np.zeros((np.shape(d)[1], n))

    for i, num in enumerate(d[0]):
        g[i] = num * np.ones((1,n))
    b = np.floor((g%(2*power))/power)
    return b
</code>```

Body:
I am a Matlab user, and trying to move into Python. I tried to code a minimal example of de2bi function (which converts a decimal into binary as right-msb) in Python which I had before in Matlab. But, I am confused with numpy arrays.

Python code:

import numpy as np

def de2bi(d, n)
    d = np.array(d)
    power = 2**np.arange(n)
    d = d * np.ones((1,n))
    b = np.floor((d%(2*power))/power)
    return b

Python output:

>>> print(de2bi(13,8))
[[ 1.  0.  1.  1.  0.  0.  0.  0.]]

print(de2bi([13,15],8)) #This line fails

Matlab code:

function b = d2b( d, n )
    d = d(:);
    power = ones(length(d), 1)*(2.^(0 : n-1));
    d = d * ones(1, n);
    b = floor(rem(d, 2*power)./power);
end

Matlab output:

>> d2b(13,8)

ans =

     1     0     1     1     0     0     0     0

>> d2b([13,15],8)

ans =

     1     0     1     1     0     0     0     0
     1     1     1     1     0     0     0     0

Matlab code is working both for integer inputs and array of integers. But python code works for integer inputs, but keeps failing for arrays. How to manage operations both for integers and integer arrays in Python automatically? It may be a very easy question, excuse me, but I am a very newbie in python.

Thanks in advance.

Body:
Your problem is with the multiplication: d = d * np.ones((1,n)). NumPy attemps to perform an element-wise multiplication, which would fail because of dimension mismatch (your ones array has only one row). When d is scalar though, NumPy can infer that you mean multiply to scalar, hence the code would run.

What you really want to do (as I understand) is to expand each element to an n-length row. A possible solution would be to create an intermediate array to hold the new values, since the size of an array is not changeable:

def d2b(d, n):
    d = np.array(d)
    d = np.reshape(d, (1, -1))
    power = np.flipud(2**np.arange(n))

    g = np.zeros((np.shape(d)[1], n))

    for i, num in enumerate(d[0]):
        g[i] = num * np.ones((1,n))
    b = np.floor((g%(2*power))/power)
    return b


答:
try this code

html

```<code><div class="row">
    <div class="bg clearfix">
    <div class="col-md-6">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium optio itaque quas ab facere, ipsa cumque consequatur nam id voluptatibus numquam, sapiente suscipit doloremque blanditiis non, ipsam sint vel molestias.</div>
    <div class="col-md-6">two</div>
    </div>
  </div>
</code>```

css

```<code>.bg
{
  background-image:url(http://data.whicdn.com/images/12849966/large.jpg);
  background-position:center;
  background-size:cover;
}
</code>```

hope it helps

Title: How can I display image behind div with bootstrap?

Body:
try this code

html

<div class="row">
    <div class="bg clearfix">
    <div class="col-md-6">Lorem ipsum dolor sit amet, consectetur adipisicing elit. Accusantium optio itaque quas ab facere, ipsa cumque consequatur nam id voluptatibus numquam, sapiente suscipit doloremque blanditiis non, ipsam sint vel molestias.</div>
    <div class="col-md-6">two</div>
    </div>
  </div>

css

.bg
{
  background-image:url(http://data.whicdn.com/images/12849966/large.jpg);
  background-position:center;
  background-size:cover;
}

hope it helps


问:
Implement Gmail-like labels in a Rails app
This is more of an application design question then a specific Rails question. I'm trying to implement a system like "labels" within Gmail. So I want a user to be able to apply a label (or many) to a specific post. However, I also want the user to be able to manage labels using standard Rails CRUD.

Let's say I have a model called Post. So a user has many Posts. A user can create labels which is a separate model from Posts, but these can also be applied to posts with the use of checkboxes in the Post new/edit views. If a user deletes a specific label, it simply gets removed from the Post view and doesn't affect the Post in any other way.

This situation shows my lack of knowledge of db relationships, but is this a case for a has_many_and_belongs_to_many relationship?

If so, would the following design be the way to implement this?

User has_many Posts

User has_many Labels

Post has_many_and_belongs_to_many
Labels

Label has_many_and_belongs_to_many
Posts

Maybe I'm over thinking this and my logic is way off.

答:
You have to decide whether or not you want tags to be "owned" by people or just "used" by people. In gmail, my labels are very specific to me. In SO the tags are not specific to me even though I can create them.

If you want labels as opposed to tags then yes.

```<code>User  ---< Label
Label >--< Post
User  ---< Post
</code>```

You can define these in English if you want.

```<code>A user has zero, one or more Labels
A Label is used by one and only one user
A user has  zero, one or more posts
A post is created by one and only one user
A post has  zero, one or more labels
a label is applied to  zero, one or more posts
</code>```

I wouldn't say you've over-thought this CONCEPTUAL data model.

Body:
You have to decide whether or not you want tags to be "owned" by people or just "used" by people. In gmail, my labels are very specific to me. In SO the tags are not specific to me even though I can create them.

If you want labels as opposed to tags then yes.

User  ---< Label
Label >--< Post
User  ---< Post

You can define these in English if you want.

A user has zero, one or more Labels
A Label is used by one and only one user
A user has  zero, one or more posts
A post is created by one and only one user
A post has  zero, one or more labels
a label is applied to  zero, one or more posts

I wouldn't say you've over-thought this CONCEPTUAL data model.


问:
rails db:create no password supplied (rails with postgresql)
I am new to Rails. I am trying to start my first Rails project. I run on Windows 10 with PostGreSQL installed. Rail and Ruby versions are installed properly. I then run into the no password supplied error.

Here is my database.yml file

```<code>default: &default
adapter: postgresql
encoding: unicode

pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
<<: *default
database: blog_development

test:
<<: *default
database: blog_test

production:
<<: *default
database: blog_production
username: blog
password: password
# old password: <%= ENV['BLOG_DATABASE_PASSWORD'] %>
</code>```

Thanks guys!

No password supplied error

答:
Following is the code of database.yml file for connect with postgres db:</p>

```<code>default: &default
  adapter: postgresql
  pool: 5
  timeout: 5000
  username : username #username of db
  password : password #password of db, if no password then make it blank

development:
  <<: *default
  database: db_name

test:
  <<: *default
  database: db_name

production:
  <<: *default
  database: db_name
</code>```

Body:
I am new to Rails. I am trying to start my first Rails project. I run on Windows 10 with PostGreSQL installed. Rail and Ruby versions are installed properly. I then run into the no password supplied error.

Here is my database.yml file

default: &default
adapter: postgresql
encoding: unicode

pool: <%= ENV.fetch("RAILS_MAX_THREADS") { 5 } %>

development:
<<: *default
database: blog_development

test:
<<: *default
database: blog_test

production:
<<: *default
database: blog_production
username: blog
password: password
# old password: <%= ENV['BLOG_DATABASE_PASSWORD'] %>

Thanks guys!

No password supplied error

Body:
Following is the code of database.yml file for connect with postgres db:

default: &default
  adapter: postgresql
  pool: 5
  timeout: 5000
  username : username #username of db
  password : password #password of db, if no password then make it blank

development:
  <<: *default
  database: db_name

test:
  <<: *default
  database: db_name

production:
  <<: *default
  database: db_name


问:
oracle db column date default value not sysdate
how to set the default value for a date column for something diferent that sysdate? like 01/07/1998, im currently using</p>

```<code>ALTER TABLE XILIADO
ADD (FECHA_AFIL DATE DEFAULT sysdate NOT NULL);
</code>```

答:
For any fixed date, use to_date(date_value, date_mask) along with alter column.</p>
```<code>ALTER TABLE XILIADO
ADD FECHA_AFIL DATE DEFAULT TO_DATE('01-07-1998','DD-MM-YYYY') NOT NULL
</code>```

Body:
how to set the default value for a date column for something diferent that sysdate? like 01/07/1998, im currently using

ALTER TABLE XILIADO
ADD (FECHA_AFIL DATE DEFAULT sysdate NOT NULL);

Body:
For any fixed date, use to_date(date_value, date_mask) along with alter column.

ALTER TABLE XILIADO
ADD FECHA_AFIL DATE DEFAULT TO_DATE('01-07-1998','DD-MM-YYYY') NOT NULL


问:
Swift 3 Extend Range of Specific Type
Having trouble grasping what the syntax would be for extending a Range of a specific type/types. For example, if I only wanted to extend Range<Double> or Range<Int> or both.

答:
I had a similar problem but the other solutions didn't work.  This did

```<code>extension CountableClosedRange where Bound: Integer, Bound == Int {
...
}
</code>```

just using

```<code>extension CountableClosedRange where Bound == Int {
...
}
</code>```

worked fine in coding (code completions) but resulted in Segmentation Fault 11 during compile.

Title: Swift 3 Extend Range of Specific Type

Body:
I had a similar problem but the other solutions didn't work.  This did

extension CountableClosedRange where Bound: Integer, Bound == Int {
...
}

just using

extension CountableClosedRange where Bound == Int {
...
}

worked fine in coding (code completions) but resulted in Segmentation Fault 11 during compile.


问:
Append template after element from a directive
Is it possible to insert a template after some element using an angular directive?

I'm trying to insert the "example.html" template after the text-area.

I made a plunker: https://plnkr.co/edit/bdBjmsi2lIbzxtl0Uw89?p=preview

As you can see the HTML is inside the text-area tag (dev tools).

index.html

```<code><!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <link rel="stylesheet" href="style.css">
    <script data-require="angular.js@1.5.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js" data-semver="1.5.0"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form name="example-form">
        <textarea rows="3" id="goal" name="name" data-ng-model="model.name" example="10"></textarea>
        <example></example> <!-- Directive used here -->
    </form>
  </body>

</html>
</code>```

script.js

```<code>app.directive('example', function() {
    return {
        restrict: 'A',
        scope: {},
        require: ['^form','ngModel'],
        templateUrl: 'example.html',
        link: function(scope, element, attrs, ctrls) {
            console.log(element);
        }
    }
});
</code>```

Thanks!

答:
You didn't use directive anywhere in index.html

```<code><!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <link rel="stylesheet" href="style.css">
    <script data-require="angular.js@1.5.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js" data-semver="1.5.0"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form name="example-form">
        <textarea rows="3" id="goal" name="name" data-ng-model="model.name" example="10"></textarea>
        <example></example> <!-- Directive used here -->
    </form>
  </body>

</html>
</code>```

Body:
Is it possible to insert a template after some element using an angular directive?

I'm trying to insert the "example.html" template after the text-area.

I made a plunker: https://plnkr.co/edit/bdBjmsi2lIbzxtl0Uw89?p=preview

As you can see the HTML is inside the text-area tag (dev tools).

index.html

<!DOCTYPE html>

    <link rel="stylesheet" href="style.css">

    <form name="example-form">
        <textarea rows="3" id="goal" name="name" data-ng-model="model.name" example="10"></textarea>
        <example></example>
    </form>

script.js

app.directive('example', function() {
    return {
        restrict: 'A',
        scope: {},
        require: ['^form','ngModel'],
        templateUrl: 'example.html',
        link: function(scope, element, attrs, ctrls) {
            console.log(element);
        }
    }
});

Thanks!

Body:
You didn't use directive anywhere in index.html

<!DOCTYPE html>
<html ng-app="plunker">

  <head>
    <link rel="stylesheet" href="style.css">
    <script data-require="angular.js@1.5.x" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.min.js" data-semver="1.5.0"></script>
    <script src="script.js"></script>
  </head>

  <body ng-controller="MainCtrl">
    <form name="example-form">
        <textarea rows="3" id="goal" name="name" data-ng-model="model.name" example="10"></textarea>
        <example></example> <!-- Directive used here -->
    </form>
  </body>

</html>


问:
get the whole content from the web site using perl script
I am a new hire in my company and first time I am working on Perl.
   I get a task in which I find IP-Reputation from this link: https://www.talosintelligence.com/reputation_center/lookup?search=27.34.246.62

But in perl when we use:

```<code>#!/bin/perl
use strict;
use warnings;
use WWW::Mechanize;

open FILE1, ">./Reports/Reputation.txt" or die "Cannot open Reputation.txt!";
my $mech = WWW::Mechanize->new( autocheck => 1 );

my $url="https://www.talosintelligence.com/reputation_center/lookup?search=27.34.246.62";
$mech->get($url);
print $mech->status();
my $content = $mech->content();
open FILE1, ">./Reports/Reputation.txt" or die "Cannot open Reputation.txt!";
print FILE1 ($content);
close FILE1;
print "\nIP Reputation Report Generated \n";
</code>```

I don't get the whole content. What can I do to get this?

答:
Contents are loading from JavaScript. So you can't crawl the content using simple methods.

There is two option for this kind of situation.

1) Some API contains the original data and JavaScript loads/formating the data in front end. If you want to parse the JavaScript loading content try to use the
WWW::Mechanize::Firefox

2) Try to figure out from where it is loading, for your IP following link has the corresponding data, which is JSON formated, so parse the content using JSON module. it is so simple compare to using RegEx.

https://www.talosintelligence.com/sb_api/query_lookup?query=%2Fapi%2Fv2%2Frelated_ips%2Fip%2F&query_entry=27.34.246.62

Body:
I am a new hire in my company and first time I am working on Perl.
   I get a task in which I find IP-Reputation from this link: https://www.talosintelligence.com/reputation_center/lookup?search=27.34.246.62

But in perl when we use:

#!/bin/perl
use strict;
use warnings;
use WWW::Mechanize;

open FILE1, ">./Reports/Reputation.txt" or die "Cannot open Reputation.txt!";
my $mech = WWW::Mechanize->new( autocheck => 1 );

my $url="https://www.talosintelligence.com/reputation_center/lookup?search=27.34.246.62";
$mech->get($url);
print $mech->status();
my $content = $mech->content();
open FILE1, ">./Reports/Reputation.txt" or die "Cannot open Reputation.txt!";
print FILE1 ($content);
close FILE1;
print "\nIP Reputation Report Generated \n";

I don't get the whole content. What can I do to get this?


问:
how do i know if nodetool repair is finished
I have a 2 node apache cassandra (2.0.3) cluster with rep factor of 1.  I change rep factor to 2 using the following command in cqlsh

```<code>ALTER KEYSPACE "mykeyspace" WITH REPLICATION =   { 'class' : 'SimpleStrategy', 'replication_factor' : 2 };
</code>```

I then tried to run recommended "nodetool repair" after doing this type of alter.

The problem is that this command sometimes finishes very quickly.  When it does finishes like that it will normally say 'Lost notification...' and exit code is not zero.

So I just repeat this 'nodetool repair' until it finishes without error.  I also check that  'nodetool status' reports expected disk space for each node.  (with rep factor 1, each node has say about 7GB each and I expect after nodetool repair that each is 14GB each assuming no cluster usage in the mean time)

Is there a more correct way to determine that 'nodetool repair' is finished in this case?

Body:
I have a 2 node apache cassandra (2.0.3) cluster with rep factor of 1.  I change rep factor to 2 using the following command in cqlsh

ALTER KEYSPACE "mykeyspace" WITH REPLICATION =   { 'class' : 'SimpleStrategy', 'replication_factor' : 2 };

I then tried to run recommended "nodetool repair" after doing this type of alter.

The problem is that this command sometimes finishes very quickly.  When it does finishes like that it will normally say 'Lost notification...' and exit code is not zero.

So I just repeat this 'nodetool repair' until it finishes without error.  I also check that  'nodetool status' reports expected disk space for each node.  (with rep factor 1, each node has say about 7GB each and I expect after nodetool repair that each is 14GB each assuming no cluster usage in the mean time)

Is there a more correct way to determine that 'nodetool repair' is finished in this case?

Body:
The repair streams can be monitored with option --trace when you start repair command:

nodetool repair --trace <key_space> <table>


问:
Order List of SelectItem based on value in java
I am using Primefaces 5.1 with JSF 2.2.

I need to ordered List of SelectItemList based on selectItem value.

```<code>List<SelectItem>mainList=new ArrayList<SelectItem>();
mainList.add(new SelectItem("1&Val1","Kumar"));
mainList.add(new SelectItem("4&Val4","Raju"));
mainList.add(new SelectItem("5&Val5","Suriya"));
mainList.add(new SelectItem("3&Val3","Kamal"));
</code>```

答:
You need to define a way to order the SelectItem class. You can do that by implementing the Comparable interface and overriding the compareTo method.

```<code>class SelectItem implements Comparable<SelectItem> {

    // constructor, getters, setters

    @Override
    public int compareTo(SelectItem other) {
        // implement logic that compares the values of the class the way that you want

        // maybe like this
        if(this.getValue() > other.getValue()) {
            return 1;
        } else if(this.getValue() < other.getValue()) {
            return -1;
        } else {
            return 0; // values are equal
        }
    }
}
</code>```

Now you can use Collections.sort() to sort your list of items.

```<code>List<SelectItem>mainList=new ArrayList<SelectItem>();
mainList.add(new SelectItem("1&Val1","Kumar"));
mainList.add(new SelectItem("4&Val4","Raju"));
mainList.add(new SelectItem("5&Val5","Suriya"));
mainList.add(new SelectItem("3&Val3","Kamal"));

Collections.sort(mainList); // now they are sorted
</code>```

Body:
I am using Primefaces 5.1 with JSF 2.2.

I need to ordered List of SelectItemList based on selectItem value.

List<SelectItem>mainList=new ArrayList<SelectItem>();
mainList.add(new SelectItem("1&Val1","Kumar"));
mainList.add(new SelectItem("4&Val4","Raju"));
mainList.add(new SelectItem("5&Val5","Suriya"));
mainList.add(new SelectItem("3&Val3","Kamal"));

Body:
You need to define a way to order the SelectItem class. You can do that by implementing the Comparable interface and overriding the compareTo method.

class SelectItem implements Comparable<SelectItem> {

    // constructor, getters, setters

    @Override
    public int compareTo(SelectItem other) {
        // implement logic that compares the values of the class the way that you want

        // maybe like this
        if(this.getValue() > other.getValue()) {
            return 1;
        } else if(this.getValue() < other.getValue()) {
            return -1;
        } else {
            return 0; // values are equal
        }
    }
}

Now you can use Collections.sort() to sort your list of items.

List<SelectItem>mainList=new ArrayList<SelectItem>();
mainList.add(new SelectItem("1&Val1","Kumar"));
mainList.add(new SelectItem("4&Val4","Raju"));
mainList.add(new SelectItem("5&Val5","Suriya"));
mainList.add(new SelectItem("3&Val3","Kamal"));

Collections.sort(mainList); // now they are sorted


问:
MySQL: Log Errors in SP and then Kill/Exit the process that called the SP
In a MySql stored proc I would like to catch and log any error that might occur, then stop/kill/exit the process that called the stored proc. The process being another stored proc one or possibly two levels up, which are executed by a scheduled event.

Currently I have the first part, but not the second:

```<code>DECLARE exit HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
@P1 = MYSQL_ERRNO, @P2 = MESSAGE_TEXT;
insert into ErrorLog
SELECT
now() as datetime
, 'spname' as 'StoredProcName'
,  @P1 as  'MYSQL_ERRNO'
, @P2 as 'MESSAGE_TEXT';

-- something here to kill the process that this SP is part of?

END;
</code>```

答: You can use RETURN or EXIT clause. or just use  a label to the particular query from the procedure and use LEAVE to exit it. You can perhaps refer here</p>

Body:
In a MySql stored proc I would like to catch and log any error that might occur, then stop/kill/exit the process that called the stored proc. The process being another stored proc one or possibly two levels up, which are executed by a scheduled event.

Currently I have the first part, but not the second:

DECLARE exit HANDLER FOR SQLEXCEPTION
BEGIN
GET DIAGNOSTICS CONDITION 1
@P1 = MYSQL_ERRNO, @P2 = MESSAGE_TEXT;
insert into ErrorLog
SELECT
now() as datetime
, 'spname' as 'StoredProcName'
,  @P1 as  'MYSQL_ERRNO'
, @P2 as 'MESSAGE_TEXT';

-- something here to kill the process that this SP is part of?

END;


问:
Firebase REST orderBy seams not work or documentation is really poor?

I'm using Firebase REST API with PHP Curl.

And i'm using Firebase Database with this rules:

```<code>"rules": {
    // ...
    "structure" : {
        "pages" : {
           ".indexOn":["order"]
        }
    }
    // ...
}
</code>```

And my data is:

```<code>// ...
"structure" : {
    "pages" : {
       "Some Random String or UID from Firebase" : {
            "some_data" : "string",
            "order" : 0
       },
       "Some Random String 2 or UID from Firebase 2" : {
            "some_data" : "string",
            "order" : 1
       }
       // ... and so on ...
    }
}
</code>```

I Read the doc. from Firebase here and here.
Trying to filter using orderByChild:

```<code>GET - https://[my-project].firebaseio.com/structure/pages.json?orderByChild="order"&print=pretty
</code>```

And orderBy:

```<code>GET - https://[my-project].firebaseio.com/structure/pages.json?orderBy="order"&print=pretty
</code>```

I get the result, but it is not ordered!
Try to change the rules and put it a $key custom and the result and nothing ordered.

I miss something in the doc ? Because i read it many times the data and rules is like the example "dinosaurs".

If some information is missing, please, tell-me to edit and put here.

Thanks for your patience!

答:
The first documentation page you linked contains this warning (scroll up one screen);

Filtered data is returned unordered: When using the REST API, the
  filtered results are returned in an undefined order since JSON
  interpreters don't enforce any ordering. If the order of your data is
  important you should sort the results in your application after they
  are returned from Firebase.

Ordering's contribution to filtering occurs when used in conjunction with the other filtering options: limitToFirst, limitToLast, startAt, endAt, and equalTo.  The ordering and limiting is done on the server, but when you see the results in a client, they are unordered.

Body:
I'm using Firebase REST API with PHP Curl.

And i'm using Firebase Database with this rules:

"rules": {
    // ...
    "structure" : {
        "pages" : {
           ".indexOn":["order"]
        }
    }
    // ...
}

And my data is:

// ...
"structure" : {
    "pages" : {
       "Some Random String or UID from Firebase" : {
            "some_data" : "string",
            "order" : 0
       },
       "Some Random String 2 or UID from Firebase 2" : {
            "some_data" : "string",
            "order" : 1
       }
       // ... and so on ...
    }
}

I Read the doc. from Firebase here and here.
Trying to filter using orderByChild:

GET - https://[my-project].firebaseio.com/structure/pages.json?orderByChild="order"&print=pretty

And orderBy:

GET - https://[my-project].firebaseio.com/structure/pages.json?orderBy="order"&print=pretty

I get the result, but it is not ordered!
Try to change the rules and put it a $key custom and the result and nothing ordered.

I miss something in the doc ? Because i read it many times the data and rules is like the example "dinosaurs".

If some information is missing, please, tell-me to edit and put here.

Thanks for your patience!


答:
Check if his works for you.

CSS:

```<code>.container{
  border: 4px solid red;
  position: relative;
  overflow: hidden;
}
.contentBox {
  min-height: 300px
}
.imgBox {
  position: absolute;
  top: 0;
  let: 0;
  width: 100%;
  z-index: -1;
}
.imgBox img {
  width: 100%;
  margin: 0;
}
</code>```

HTML:

```<code><div class="container">

  <div class="row contentBox">
    <div class="col-md-6">one</div>
    <div class="col-md-6">two</div>
  </div>
  <div class="imgBox row">
    <img src="imageURL.jpg" alt="" />
  </div>
</div>
</code>```

enter link description here

Body:
I have 2 rows in my container. In the second row I have 2 elements one and two. Now I am trying to display the image behind those too almost like a background. This is the html:

one

two

codepen

Body:
Check if his works for you.

CSS:

.container{
  border: 4px solid red;
  position: relative;
  overflow: hidden;
}
.contentBox {
  min-height: 300px
}
.imgBox {
  position: absolute;
  top: 0;
  let: 0;
  width: 100%;
  z-index: -1;
}
.imgBox img {
  width: 100%;
  margin: 0;
}

HTML:

<div class="container">

  <div class="row contentBox">
    <div class="col-md-6">one</div>
    <div class="col-md-6">two</div>
  </div>
  <div class="imgBox row">
    <img src="imageURL.jpg" alt="" />
  </div>
</div>

enter link description here


问:
How to find latest or most recent AWS RDS snapshot?
I can call aws rds describe-db-snapshots --db-instance-identifier {my_db_instance} and sort all automated snapshots to find the most recently created one but I was hoping someone has a better idea out there.

答:
I know this is old, but I was needing to know the same information and was able to construct the following which will then just give me the snapshot name.  It doesn't totally answer your question about emphatically finding the latest snapshot but in this example might give you some better direction.

```<code>aws rds describe-db-snapshots --db-instance-identifier prd --snapshot-type automated --query "DBSnapshots[?SnapshotCreateTime>='2017-06-05'].DBSnapshotIdentifier"
</code>```

To break it down with the options

--db-instance-identifier (put in your instance name your are looking for)

--snapshot-type (I put in automated to find the automated backups)

--query "DBSnapshots[?SnapshotCreateTime>='2017-06-05'].DBSnapshotIdentifier"

(This is what I used to refine my search as we do daily backups, I just look for the snapshot create time to be greater than today and by giving the .DBSnapshotIdentifier gives me back just the name.

Hopefully this will help somebody else out.

Body:
I know this is old, but I was needing to know the same information and was able to construct the following which will then just give me the snapshot name.  It doesn't totally answer your question about emphatically finding the latest snapshot but in this example might give you some better direction.

aws rds describe-db-snapshots --db-instance-identifier prd --snapshot-type automated --query "DBSnapshots[?SnapshotCreateTime>='2017-06-05'].DBSnapshotIdentifier"

To break it down with the options

--db-instance-identifier (put in your instance name your are looking for)

--snapshot-type (I put in automated to find the automated backups)

--query "DBSnapshots[?SnapshotCreateTime>='2017-06-05'].DBSnapshotIdentifier"

(This is what I used to refine my search as we do daily backups, I just look for the snapshot create time to be greater than today and by giving the .DBSnapshotIdentifier gives me back just the name.

Hopefully this will help somebody else out.


问:
jquery: duplicate and paste html
hmm ok heres the shortened code

```<code> <div id="SideCategoryList">
        <div class="BlockContent">
           <ul>
              <li><a href="#">Link A</a></li>
              <li><a href="#">Link B</a></li>
          </ul>
       </div>
     </div>
    <div id="navcont">
    <ul class="menu" id="menu">
      <li id="hov"><a href="#">Top Link</a></li>
      <li><a href="#">Bottom Link</a></li>
    </ul>
   </div>
</code>```

i want to use jquery to duplicate whats in the first ul into the first li in the #menu so it looks like this

```<code><div id="SideCategoryList">
        <div class="BlockContent">
           <ul>
              <li><a href="#">Link A</a></li>
              <li><a href="#">Link B</a></li>
          </ul>
       </div>
     </div>
    <div id="navcont">
      <ul class="menu" id="menu">
         <li id="hov"><a href="#">Top Link</a>
            <ul>
               <li><a href="#">Link A</a></li>
               <li><a href="#">Link B</a></li>
            </ul>
        </li>
        <li><a href="#">Bottom Link</a></li>
      </ul>
   </div>
</code>```

so the finished product will be a 2 level list... let me know if this is makin sense lol

答:
maybe something like this...</p>

```<code>var copied_html = $('#BlockContent').html();
copied_html.insertAfter($('#menu li#hov a'));
</code>```

Title: jquery: duplicate and paste html

Body:
hmm ok heres the shortened code

Link A

Link B

Top Link

Bottom Link

i want to use jquery to duplicate whats in the first ul into the first li in the #menu so it looks like this

Link A

Link B

Top Link

Link A

Link B

Bottom Link

so the finished product will be a 2 level list... let me know if this is makin sense lol

Body:
maybe something like this...

var copied_html = $('#BlockContent').html();
copied_html.insertAfter($('#menu li#hov a'));


问:
WPF get Content of a treeviewitem
I need to check what treeviewitem the user selected everytime it changes. I used the SelectedItemChangedmethod or whatever this is called. It works fine but now I need to do a switch case for every possible treeviewitem. But I can't do that since I have no idea how to get the name of it. I checked on internet but some people said to use treeview.SelectedItem but it returns System.Windows.Controls.TreeViewItem Header: Items.Count:0. I was wondering if I could do that entirely in the .cs code file or if I had to use data binding and such.

Thanks for your help.

EDIT:

Here is how i setup the treeview and the treeviewitems. They are all like the second example.

```<code><TreeView x:Name="treeview" Margin="10,10,0,4" HorizontalAlignment="Left" Width="192" Background="#FFA45353" SelectedItemChanged="treeview_SelectedItemChanged"">
        <TreeViewItem IsExpanded="False">
            <TreeViewItem.Header>
                <StackPanel Orientation="Horizontal">
                    <Image Source="./Resources/smallicons/icon.jpg"/>
                    <TextBlock Text=" Main" FontSize="14"/>
                </StackPanel>
            </TreeViewItem.Header>
            <!--==============================================================================================-->
            <TreeViewItem>
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="First" Foreground="Black" />
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>
            <!--==============================================================================================-->
</code>```

答:
Ok...As per your treeview and treeview Item setup, you have to code something like this..

```<code>private void treeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
            TreeViewItem selectedNode = (TreeViewItem)treeview.SelectedItem;
            var sp = selectedNode.Header as StackPanel;
            var tb = sp.Children[0] as TextBlock;
            var selecteditem = tb.Text;
            //MessageBox.Show(selecteditem);
            switch (selecteditem)
            {
                case "Main":
                    MessageBox.Show(selecteditem);
                    break;
                case "First":
                    MessageBox.Show(selecteditem);
                    break;
                default:
                    MessageBox.Show("no matching item found");
                    break;
            }
        }
</code>```

Here, I am digging in the selected tree view item to get the Text of selected tree view item. You may have to tweak the code a bit to get it fully operational. Let me know if you need any help with it.

Title: WPF get Content of a treeviewitem

Body:
I need to check what treeviewitem the user selected everytime it changes. I used the SelectedItemChangedmethod or whatever this is called. It works fine but now I need to do a switch case for every possible treeviewitem. But I can't do that since I have no idea how to get the name of it. I checked on internet but some people said to use treeview.SelectedItem but it returns System.Windows.Controls.TreeViewItem Header: Items.Count:0. I was wondering if I could do that entirely in the .cs code file or if I had to use data binding and such.

Thanks for your help.

EDIT:

Here is how i setup the treeview and the treeviewitems. They are all like the second example.

<TreeView x:Name="treeview" Margin="10,10,0,4" HorizontalAlignment="Left" Width="192" Background="#FFA45353" SelectedItemChanged="treeview_SelectedItemChanged"">
        <TreeViewItem IsExpanded="False">
            <TreeViewItem.Header>
                <StackPanel Orientation="Horizontal">
                    <Image Source="./Resources/smallicons/icon.jpg"/>
                    <TextBlock Text=" Main" FontSize="14"/>
                </StackPanel>
            </TreeViewItem.Header>

            <TreeViewItem>
                <TreeViewItem.Header>
                    <StackPanel Orientation="Horizontal">
                        <TextBlock Text="First" Foreground="Black" />
                    </StackPanel>
                </TreeViewItem.Header>
            </TreeViewItem>

Body:
Ok...As per your treeview and treeview Item setup, you have to code something like this..

private void treeview_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
            TreeViewItem selectedNode = (TreeViewItem)treeview.SelectedItem;
            var sp = selectedNode.Header as StackPanel;
            var tb = sp.Children[0] as TextBlock;
            var selecteditem = tb.Text;
            //MessageBox.Show(selecteditem);
            switch (selecteditem)
            {
                case "Main":
                    MessageBox.Show(selecteditem);
                    break;
                case "First":
                    MessageBox.Show(selecteditem);
                    break;
                default:
                    MessageBox.Show("no matching item found");
                    break;
            }
        }

Here, I am digging in the selected tree view item to get the Text of selected tree view item. You may have to tweak the code a bit to get it fully operational. Let me know if you need any help with it.


问:
vb net 2017 error when reading xml file
I created a program were I get xml reponses from google maps. Everything went fine, the respose is OK, I can proper write the xml file, and I can read a specific xml node as well, exept if there is some special character in the xml file. In my case when there is an " ë " in "België" in the file.

What can be done, to be able to read xml files with these type of characters in it. Changing the " ë " in " e " can be a solution, but there will other characters giving this issue as well. I'm looking for a solution so I can use the original response from google.

Thanks a lot

my code looks as follows

write the file

```<code>    WriteXMLResponseFile(strResult)
</code>```

read specific node

```<code>    strStatus = ReadXMLData("/DistanceMatrixResponse/status")
</code>```

de code for writing and reading

```<code>Public Sub WriteXMLResponseFile(ByVal responseData As String, Optional ByVal fileName As String = "\Data\Response.xml")
    Dim intFileNr As Integer
    intFileNr = FreeFile()
    Try
        FileOpen(intFileNr, Application.StartupPath & fileName, OpenMode.Output)
        PrintLine(intFileNr, responseData)
    Catch ex As Exception
        MessageBox.Show("The file :" & vbCrLf & Application.StartupPath & fileName & vbCrLf & "does not exist", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
    End Try
    FileClose(intFileNr)
End Sub

Function ReadXMLData(ByVal dataNode As String, Optional ByVal fileName As String = "\Data\Response.xml") As String

    Dim xDoc As XmlDocument = New XmlDocument()

    Try
        xDoc.Load(Application.StartupPath & fileName)
        ReadXMLData = xDoc.SelectSingleNode(dataNode).InnerText
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try

End Function
</code>```

The XML file looks as follows

```<code><?xml version="1.0" encoding="UTF-8"?>
<DistanceMatrixResponse>
 <status>OK</status>
 <origin_address>Henleykaai, 9000 Gent, Belgi뼯origin_address>
 <destination_address>Nieuwstraat, 1000 Brussel, Belgi뼯destination_address>
 <row>
  <element>
   <status>OK</status>
   <duration>
    <value>2709</value>
    <text>45 min.</text>
   </duration>
   <distance>
    <value>54752</value>
    <text>54,8 km</text>
   </distance>
   <duration_in_traffic>
    <value>2504</value>
    <text>42 min.</text>
   </duration_in_traffic>
  </element>
 </row>
</DistanceMatrixResponse>
</code>```

答:
This works out for me, I'v changed the output of the File.CreateText to the original and it works to.
Thanks a Lot</p>

Title: vb net 2017 error when reading xml file

Body:
I created a program were I get xml reponses from google maps. Everything went fine, the respose is OK, I can proper write the xml file, and I can read a specific xml node as well, exept if there is some special character in the xml file. In my case when there is an " ë " in "België" in the file.

What can be done, to be able to read xml files with these type of characters in it. Changing the " ë " in " e " can be a solution, but there will other characters giving this issue as well. I'm looking for a solution so I can use the original response from google.

Thanks a lot

my code looks as follows

write the file

    WriteXMLResponseFile(strResult)

read specific node

    strStatus = ReadXMLData("/DistanceMatrixResponse/status")

de code for writing and reading

Public Sub WriteXMLResponseFile(ByVal responseData As String, Optional ByVal fileName As String = "\Data\Response.xml")
    Dim intFileNr As Integer
    intFileNr = FreeFile()
    Try
        FileOpen(intFileNr, Application.StartupPath & fileName, OpenMode.Output)
        PrintLine(intFileNr, responseData)
    Catch ex As Exception
        MessageBox.Show("The file :" & vbCrLf & Application.StartupPath & fileName & vbCrLf & "does not exist", "Attention", MessageBoxButtons.OK, MessageBoxIcon.Exclamation, MessageBoxDefaultButton.Button1)
    End Try
    FileClose(intFileNr)
End Sub

Function ReadXMLData(ByVal dataNode As String, Optional ByVal fileName As String = "\Data\Response.xml") As String

    Dim xDoc As XmlDocument = New XmlDocument()

    Try
        xDoc.Load(Application.StartupPath & fileName)
        ReadXMLData = xDoc.SelectSingleNode(dataNode).InnerText
    Catch ex As Exception
        MsgBox(ex.Message)

    End Try

End Function

The XML file looks as follows

<?xml version="1.0" encoding="UTF-8"?>
<DistanceMatrixResponse>
 <status>OK</status>
 <origin_address>Henleykaai, 9000 Gent, Belgi뼯origin_address>
 <destination_address>Nieuwstraat, 1000 Brussel, Belgi뼯destination_address>
 <row>
  <element>
   <status>OK</status>
   <duration>
    <value>2709</value>
    <text>45 min.</text>
   </duration>
   <distance>
    <value>54752</value>
    <text>54,8 km</text>
   </distance>
   <duration_in_traffic>
    <value>2504</value>
    <text>42 min.</text>
   </duration_in_traffic>
  </element>
 </row>
</DistanceMatrixResponse>


问:
I am creating a sample website. How do I check how it looks on mobile devices?
I have not launched the website yet. All the mobile testing websites I have found on the internet are asking for my URL. Is there any way to test a website that has not been launched yet?</p>

答:
You can check it on more number of mobile simulators with chrome Device Toolbar that is inside Developer Tools. it looks great with many inbuild mobile device simulators. (That is second left mobile like icon on the inspect element).

Once you click on the icon you can switch through devices using the top device selector. You can even change width and height of the device and zoom it accordingly