问:
Struts2 + Sitemesh + Freemarker doesn't work
I've tried every example i could find and I can't get struts2 + sitemesh + freemarker to work on a simple jsp.

I have a very simple web.xml, a single action that just goes to index.jsp, and a simple .ftl decorator that just adds some text to the result.

When I hit index.action, the page "seems" to be decorated, but I get the literal ${body} instead of the actual contents.

Here's my setup:

web.xml

```<code><web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <description>struts2 test</description>
    <display-name>struts 2 test</display-name>

    <filter>
        <filter-name>struts-prepare</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
    </filter>

    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>org.apache.struts2.sitemesh.FreeMarkerPageFilter</filter-class>
    </filter>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts-prepare</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.action</welcome-file>
    </welcome-file-list>

</web-app>
</code>```

struts.xml

```<code><struts>
    <constant name="struts.devMode" value="true"/>
    <package name="basicstruts2" extends="struts-default">
        <action name="index">
            <result>/index.jsp</result>
        </action>
    </package>
</struts>
</code>```

sitemesh.xml

```<code><sitemesh>
    <property name="decorators-file" value="/WEB-INF/decorators.xml" />
    <excludes file="${decorators-file}" />

    <page-parsers>
        <parser default="true" class="com.opensymphony.module.sitemesh.parser.DefaultPageParser"/>
        <parser content-type="text/html" class="com.opensymphony.module.sitemesh.parser.HTMLPageParser"/>
    </page-parsers>

    <decorator-mappers>

        <mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">
            <param name="config" value="${decorators-file}" />
        </mapper>
    </decorator-mappers>
</sitemesh>
</code>```

decorators.xml

```<code><decorators defaultdir="/decorators">
    <decorator name="main" page="main.ftl">
          <pattern>/*</pattern>
    </decorator>
</decorators>
</code>```

main.ftl

```<code><html>
<head>
<title>${title}</title>
${head}
</head>
<body>
I'm Fancy!<br>
    ${body}<br />
</body>
</html>
</code>```

index.jsp

```<code><html>
<head>
    <title>my title</title>
    </head>
<body>
my body
</body>
</html>
</code>```

Any ideas???

答:
See http://struts.apache.org/2.x/docs/sitemesh-plugin.html for working docs.  You probably need to add:

```<code><servlet-mapping>
     <servlet-name>sitemesh-freemarker</servlet-name>
     <url-pattern>*.ftl</url-pattern>
</servlet-mapping>
</code>```

to your web.xml.

And rename index.jsp to index.ftl.  Incidentally if you're going to go with sitemesh + freemarker I usually prefer the convention of *.dec for the decorators and *.ftl for the freemarker templates.

Body:
I've tried every example i could find and I can't get struts2 + sitemesh + freemarker to work on a simple jsp.

I have a very simple web.xml, a single action that just goes to index.jsp, and a simple .ftl decorator that just adds some text to the result.

When I hit index.action, the page "seems" to be decorated, but I get the literal ${body} instead of the actual contents.

Here's my setup:

web.xml

<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
         http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
         version="2.4">

    <description>struts2 test</description>
    <display-name>struts 2 test</display-name>

    <filter>
        <filter-name>struts-prepare</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareFilter</filter-class>
    </filter>

    <filter>
        <filter-name>sitemesh</filter-name>
        <filter-class>org.apache.struts2.sitemesh.FreeMarkerPageFilter</filter-class>
    </filter>

    <filter>
        <filter-name>struts2</filter-name>
        <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsExecuteFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>struts-prepare</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <filter-mapping>
        <filter-name>sitemesh</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <filter-mapping>
        <filter-name>struts2</filter-name>
        <url-pattern>/*</url-pattern>
        <dispatcher>REQUEST</dispatcher>
        <dispatcher>FORWARD</dispatcher>
    </filter-mapping>

    <welcome-file-list>
        <welcome-file>index.action</welcome-file>
    </welcome-file-list>

</web-app>

struts.xml

<struts>
    <constant name="struts.devMode" value="true"/>
    <package name="basicstruts2" extends="struts-default">
        <action name="index">
            <result>/index.jsp</result>
        </action>
    </package>
</struts>

sitemesh.xml

<sitemesh>
    <property name="decorators-file" value="/WEB-INF/decorators.xml" />
    <excludes file="${decorators-file}" />

    <page-parsers>
        <parser default="true" class="com.opensymphony.module.sitemesh.parser.DefaultPageParser"/>
        <parser content-type="text/html" class="com.opensymphony.module.sitemesh.parser.HTMLPageParser"/>
    </page-parsers>

    <decorator-mappers>

        <mapper class="com.opensymphony.module.sitemesh.mapper.ConfigDecoratorMapper">
            <param name="config" value="${decorators-file}" />
        </mapper>
    </decorator-mappers>
</sitemesh>

decorators.xml

<decorators defaultdir="/decorators">
    <decorator name="main" page="main.ftl">
          <pattern>/*</pattern>
    </decorator>
</decorators>

main.ftl

<title>${title}</title>
${head}

I'm Fancy!

    ${body}

index.jsp

    <title>my title</title>

my body

Any ideas???

Body:
See http://struts.apache.org/2.x/docs/sitemesh-plugin.html for working docs.  You probably need to add:

<servlet-mapping>
     <servlet-name>sitemesh-freemarker</servlet-name>
     <url-pattern>*.ftl</url-pattern>
</servlet-mapping>

to your web.xml.

And rename index.jsp to index.ftl.  Incidentally if you're going to go with sitemesh + freemarker I usually prefer the convention of *.dec for the decorators and *.ftl for the freemarker templates.


来源: stackexchange

问:
TextView with different textSize
Is this possible to set different textSize in one TextView?  I know that I can change text style using:

```<code>TextView textView = (TextView) findViewById(R.id.textView);
Spannable span = new SpannableString(textView.getText());
span.setSpan(arg0, 1, 10, arg3);
textView.setText(span)
</code>```

I know the range start...end of text I want to change size. But what can I use as arg0 and arg3?

答:
Try with AbsoluteSizeSpan

```<code>snackbarText.setSpan(new AbsoluteSizeSpan(fontsize, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
</code>```

The complete code is:

```<code>SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Your text");
snackbarText.setSpan(new AbsoluteSizeSpan(fontsize, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Snackbar.make(getCurrentFocus(), snackbarText, Snackbar.LENGTH_LONG).setAction("Action", null).show();`
</code>```

ContentLicense: CC BY-SA 3.0

Title: TextView with different textSize

Body:
Is this possible to set different textSize in one TextView?  I know that I can change text style using:

TextView textView = (TextView) findViewById(R.id.textView);
Spannable span = new SpannableString(textView.getText());
span.setSpan(arg0, 1, 10, arg3);
textView.setText(span)

I know the range start...end of text I want to change size. But what can I use as arg0 and arg3?

Body:
Try with AbsoluteSizeSpan

snackbarText.setSpan(new AbsoluteSizeSpan(fontsize, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

The complete code is:

SpannableStringBuilder snackbarText = new SpannableStringBuilder();
snackbarText.append("Your text");
snackbarText.setSpan(new AbsoluteSizeSpan(fontsize, true), start, end, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
Snackbar.make(getCurrentFocus(), snackbarText, Snackbar.LENGTH_LONG).setAction("Action", null).show();`


问:
Spring boot web configuration
I've configured in my spring boot project (code provides most interesting part)

```<code>public class WebConfiguration extends WebMvcConfigurerAdapter {
  // ...
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("googleb54ababeddd1718e.html")
            .addResourceLocations("classpath:/static/googleb54ababeddd1718e.html");
    registry.addResourceHandler("google7160e5f82e26983b.html")
            .addResourceLocations("classpath:/static/google7160e5f82e26983b.html");
    registry.addResourceHandler("google06bd5e270f77943e.html")
            .addResourceLocations("classpath:/static/google06bd5e270f77943e.html");
    //...
  }
</code>```

this configuration works fine. If you've payed your attention, some resources different, but can be grouped by mask and handler. File names: googleb54ababeddd1718e.html, google7160e5f82e26983b.html, google06bd5e270f77943e.html. So I've tried next part:

```<code>public class WebConfiguration extends WebMvcConfigurerAdapter {
  // ...
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("google.html")
            .addResourceLocations("classpath:/static/google*.html");
    //...
  }
</code>```

and this case does not work. I believe I very close to correct solution, but I can't detect one. Can someone provide fix of this issue or explain why the approach is incorrect?

答:
v1 Move all google** files to google folder and remove google prefix.

```<code>@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/google/**")
            .addResourceLocations("classpath:/static/");
}
</code>```

v2

```<code>@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/{google**.html}")
        .addResourceLocations("classpath:/static/");
}
</code>```

Title: Spring boot web configuration

Body:
I've configured in my spring boot project (code provides most interesting part)

public class WebConfiguration extends WebMvcConfigurerAdapter {
  // ...
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("googleb54ababeddd1718e.html")
            .addResourceLocations("classpath:/static/googleb54ababeddd1718e.html");
    registry.addResourceHandler("google7160e5f82e26983b.html")
            .addResourceLocations("classpath:/static/google7160e5f82e26983b.html");
    registry.addResourceHandler("google06bd5e270f77943e.html")
            .addResourceLocations("classpath:/static/google06bd5e270f77943e.html");
    //...
  }

this configuration works fine. If you've payed your attention, some resources different, but can be grouped by mask and handler. File names: googleb54ababeddd1718e.html, google7160e5f82e26983b.html, google06bd5e270f77943e.html. So I've tried next part:

public class WebConfiguration extends WebMvcConfigurerAdapter {
  // ...
  @Override
  public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("google.html")
            .addResourceLocations("classpath:/static/google*.html");
    //...
  }

and this case does not work. I believe I very close to correct solution, but I can't detect one. Can someone provide fix of this issue or explain why the approach is incorrect?

Body:
v1 Move all google** files to google folder and remove google prefix.

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/google/**")
            .addResourceLocations("classpath:/static/");
}

v2

@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
    registry.addResourceHandler("/{google**.html}")
        .addResourceLocations("classpath:/static/");
}


问:
Typeerror: view must be callable
When I run my server I get a type error message telling me that:

my view must be callable or a list/tuple

and from what I gathered django version differs and for clarity sake, I am using django latest version... Anyways here's my views.py and urls.py for my project:

url.py

```<code>from django.conf.urls import url
from . import views
urlpatterns = [

 url(r'^login/$',
    'django.contrib.auth.views.login',name='login'),
 url(r'^logout/$',
    'django.contrib.auth.views.logout',name='logout'),
 url(r'^logout-then-login/$',
    'django.contrib.auth.views.logout_then_login',name='logout_then_login'),

]
</code>```

views.py

```<code>from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
from django.contrib.auth.decorators import login_required

def user_login(request):
 if request.method == 'POST':
  form = LoginForm(request.POST)
  if form.is_valid():
   cd = form.cleaned_data
   user = authenticate(username=cd['username'],password=cd['password'])
   if user is not None:
    if user.is_active:
     login(request, user)
     return HttpResponse('Authenticated  successfully')
   else:
    return HttpResponse('Disabled account')

  else:
   return HttpResponse('Invalid login')
 else:
  form = LoginForm()
 return render(request, 'account/login.html', {'form': form})

@login_required
def dashboard(request):
 return render(request,
              'account/dashboard.html',{'section': 'dashboard'})
</code>```

答:
Try changing your url patterns to below:

```<code>urlpatterns = [

 url(r'^login/$',
    django.contrib.auth.views.login,name='login'),
 url(r'^logout/$',
    django.contrib.auth.views.logout,name='logout'),
 url(r'^logout-then-login/$',
    django.contrib.auth.views.logout_then_login,name='logout_then_login'),

]
</code>```

From the docs for latest django version, the views are function and not strings.

Title: Typeerror: view must be callable

Body:
When I run my server I get a type error message telling me that:

my view must be callable or a list/tuple

and from what I gathered django version differs and for clarity sake, I am using django latest version... Anyways here's my views.py and urls.py for my project:

url.py

from django.conf.urls import url
from . import views
urlpatterns = [

 url(r'^login/$',
    'django.contrib.auth.views.login',name='login'),
 url(r'^logout/$',
    'django.contrib.auth.views.logout',name='logout'),
 url(r'^logout-then-login/$',
    'django.contrib.auth.views.logout_then_login',name='logout_then_login'),

]

views.py

from django.http import HttpResponse
from django.shortcuts import render
from django.contrib.auth import authenticate, login
from .forms import LoginForm
from django.contrib.auth.decorators import login_required

def user_login(request):
 if request.method == 'POST':
  form = LoginForm(request.POST)
  if form.is_valid():
   cd = form.cleaned_data
   user = authenticate(username=cd['username'],password=cd['password'])
   if user is not None:
    if user.is_active:
     login(request, user)
     return HttpResponse('Authenticated  successfully')
   else:
    return HttpResponse('Disabled account')

  else:
   return HttpResponse('Invalid login')
 else:
  form = LoginForm()
 return render(request, 'account/login.html', {'form': form})

@login_required
def dashboard(request):
 return render(request,
              'account/dashboard.html',{'section': 'dashboard'})

Body:
Try changing your url patterns to below:

urlpatterns = [

 url(r'^login/$',
    django.contrib.auth.views.login,name='login'),
 url(r'^logout/$',
    django.contrib.auth.views.logout,name='logout'),
 url(r'^logout-then-login/$',
    django.contrib.auth.views.logout_then_login,name='logout_then_login'),

]

From the docs for latest django version, the views are function and not strings.


问:
convert string to normal html tag
I am missing out something here. I am trying to get the image during execution and display in pophover. This pophover is on table row.

The basic flow is, user will hover on one row so this will show a popover on right holding the product image along with some description.

I was able to track the image but while returning the whole image tag is appending as string. Therefore, the code is parsed as string and displayed as it is.

How can I fix this?

```<code>$('body').popover({
    placement:"right",
    trigger:"hover",
    selector:'tr[id=popover]',
    content:function(){
        return '<img src = "' + $(this).children("td").children("img")[0].currentSrc + '" width="200" height="200">'
    }
});
</code>```

I am thinking if I can convert the return part to normal image tag then that can solve this issue.

Hope this screenshots helps.

答:
Render it inside of jQuery so for example</p>

```<code>var x = $(content);
parentEl.append(x)
</code>```

Title: convert string to normal html tag

Body:
I am missing out something here. I am trying to get the image during execution and display in pophover. This pophover is on table row.

The basic flow is, user will hover on one row so this will show a popover on right holding the product image along with some description.

I was able to track the image but while returning the whole image tag is appending as string. Therefore, the code is parsed as string and displayed as it is.

How can I fix this?

$('body').popover({
    placement:"right",
    trigger:"hover",
    selector:'tr[id=popover]',
    content:function(){
        return ''
    }
});

I am thinking if I can convert the return part to normal image tag then that can solve this issue.

Hope this screenshots helps.

Body:
Render it inside of jQuery so for example

var x = $(content);
parentEl.append(x)


问:
Capture event of children in parent component React with no markup of own
```<code>var React = require('react');
var {Col} = require('react-bootstrap/lib');

var Segment = require('../util/segment-data');

module.exports = React.createClass({
    displayName: 'MyFilter',
    propTypes: {
        children: React.PropTypes.node,
        component: React.PropTypes.string
    },
    render(){
        return (
            this.props.children
        );
    },
    captureEventHandler(){
        var data = {
            label: e.target.innerText ? e.target.innerText : e.target.textContent
        };
        Segment.track(this.props.component, data);
    }
});
</code>```

Then

```<code><SegmentFilter component={Events.sailing_schedules}>
                        <div onClick={this.handleSort.bind(null, 'departure_date')}>Departure Date <span className='caret'></span></div>
                    </SegmentFilter>
</code>```

My question is that how do I capture click, enter or any event happening in children in the component SegmentFilter?
Is it possible to not specify any DOM element inside render ? So basically I am asking how can I do it without doing the following.

```<code>return (
        <div onClick={this.handleClick}>
            {this.props.children}
        </div>
    );
handleClick(e){
    var data = {
        label: e.target.innerText ? e.target.innerText : e.target.textContent
    };
    Segment.track(this.props.component, data);
}
</code>```

The reason I am avoiding this is because I don't want to specify any html of my wrapper component. Or at worst even if I use the div how can I capture any event of child element inside parent component.

So I am looking to write a global event handler in Segment wrapper which will be called no matter which event fires and not only click in child elements. Let's say it should bubble upto that function handleClick

UPDATE -
I referred this but couldn't find my case.

Example for Bubbling and Capturing in React.js

答:
The reason I am avoiding this is because I don't want to specify any
  html of my wrapper component.

You can use the render callback pattern for this. You specify an event callback for the child. Here is an example of this pattern.

```<code>const Child = ({onClick, children}) => (
  <div className="child">
    <button onClick={onClick}>Click</button>
    <div>value is: {children}</div>
  </div>
);

class Parent extends React.Component {
  constructor(props){
    super(props);
    this.state = {};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(event){
    this.setState({value: new Date().toString()});
  }
  render(){
    return this.props.children({onClick: this.handleClick, value: this.state.value});
  }
}
</code>```

You use the components like this.

```<code><Parent>
  {({onClick, value}) => <Child onClick={onClick}>{value}</Child>}
</Parent>
</code>```

Only the child markup will be rendered.

Body:
var React = require('react');
var {Col} = require('react-bootstrap/lib');

var Segment = require('../util/segment-data');

module.exports = React.createClass({
    displayName: 'MyFilter',
    propTypes: {
        children: React.PropTypes.node,
        component: React.PropTypes.string
    },
    render(){
        return (
            this.props.children
        );
    },
    captureEventHandler(){
        var data = {
            label: e.target.innerText ? e.target.innerText : e.target.textContent
        };
        Segment.track(this.props.component, data);
    }
});

Then

<SegmentFilter component={Events.sailing_schedules}>

Departure Date

                    </SegmentFilter>

My question is that how do I capture click, enter or any event happening in children in the component SegmentFilter?
Is it possible to not specify any DOM element inside render ? So basically I am asking how can I do it without doing the following.

return (

            {this.props.children}

    );
handleClick(e){
    var data = {
        label: e.target.innerText ? e.target.innerText : e.target.textContent
    };
    Segment.track(this.props.component, data);
}

The reason I am avoiding this is because I don't want to specify any html of my wrapper component. Or at worst even if I use the div how can I capture any event of child element inside parent component.

So I am looking to write a global event handler in Segment wrapper which will be called no matter which event fires and not only click in child elements. Let's say it should bubble upto that function handleClick

UPDATE -
I referred this but couldn't find my case.

Example for Bubbling and Capturing in React.js

Body:
The reason I am avoiding this is because I don't want to specify any
  html of my wrapper component.

You can use the render callback pattern for this. You specify an event callback for the child. Here is an example of this pattern.

const Child = ({onClick, children}) => (
  <div className="child">
    <button onClick={onClick}>Click</button>
    <div>value is: {children}</div>
  </div>
);

class Parent extends React.Component {
  constructor(props){
    super(props);
    this.state = {};
    this.handleClick = this.handleClick.bind(this);
  }
  handleClick(event){
    this.setState({value: new Date().toString()});
  }
  render(){
    return this.props.children({onClick: this.handleClick, value: this.state.value});
  }
}

You use the components like this.

<Parent>
  {({onClick, value}) => <Child onClick={onClick}>{value}</Child>}
</Parent>

Only the child markup will be rendered.


问:
What's the best strategy to provide different comparison operators for the same class?
Consider this simple class storing a value and a time.

```<code>class A
{
public:
    boost::posix_time::ptime when;
    double value;
};
</code>```

Depending on the context, I need to compare two instances of A by value or by time (and/or store them in set/map, sometimes sorted by value, sometimes by time).

Providing operator<  will be confusing, because you can't tell if it will compare by value or by time.

Now, what's the best strategy?

Is it possible to provide an operator< taking a parameter? (would be used as a <(ByTime) b)?

Should I have a lowerThan (comparing values) method and a earlierThan (comparing time) method taking the right operand as parameter? But then, what would be the best practice to handle <, <=, >, >=, ==, !=, should I have one method for each comparator? Or may they take parameters (like bool isLower(bool strict, const A& right) const, bool isGreater(bool strict, const A& right) const, bool isEarlier(bool strict, const A& right) const, bool isLater(bool strict, const A& right) const...

What would be the best practice?

答:
Reacting to UKMonkey comment, would defining what I understand could be named "comparator classes" be a good approach/practice?</p>

```<code>class A
{
public:
    boost::posix_time::ptime when;
    double value;

    const boost::posix_time::ptime& getTime() const { return when; }
    double getValue() const { return value; }
};

template <typename T>
class CompareBy
{
public:
    CompareBy( const A& a, T (A::*getter)() const ) : a(a), getter(getter)
    {}

    bool operator<( const CompareBy& right ) const
    {
        return (a.*getter)() < (right.a.*getter)();
    }

    // you may also declare >, <=, >=, ==, != operators here

private:
    const A& a;
    T (A::*getter)() const;
};

class CompareByTime : public CompareBy<const boost::posix_time::ptime&>
{
public:
    CompareByTime(const A& a) : CompareBy(a, &A::getTime)
    {
    }
};

class CompareByValue : public CompareBy<double>
{
public:
    CompareByValue( const A& a ) : CompareBy(a, &A::getValue)
    {
    }
};

struct byTime_compare {
    bool operator() (const A& lhs, const A& rhs) const {
        return CompareByTime(lhs) < CompareByTime(rhs);
    }
};

int main()
{
    A a, b;

    ...

    if (CompareByValue(a) < CompareByValue(b))
    {
        ...
    }

    std::set<A, byTime_compare> mySet;
}
</code>```

Body:
Consider this simple class storing a value and a time.

class A
{
public:
    boost::posix_time::ptime when;
    double value;
};

Depending on the context, I need to compare two instances of A by value or by time (and/or store them in set/map, sometimes sorted by value, sometimes by time).

Providing operator<  will be confusing, because you can't tell if it will compare by value or by time.

Now, what's the best strategy?

Is it possible to provide an operator< taking a parameter? (would be used as a <(ByTime) b)?

Should I have a lowerThan (comparing values) method and a earlierThan (comparing time) method taking the right operand as parameter? But then, what would be the best practice to handle <, <=, >, >=, ==, !=, should I have one method for each comparator? Or may they take parameters (like bool isLower(bool strict, const A& right) const, bool isGreater(bool strict, const A& right) const, bool isEarlier(bool strict, const A& right) const, bool isLater(bool strict, const A& right) const...

What would be the best practice?

Body:
Reacting to UKMonkey comment, would defining what I understand could be named "comparator classes" be a good approach/practice?

class A
{
public:
    boost::posix_time::ptime when;
    double value;

    const boost::posix_time::ptime& getTime() const { return when; }
    double getValue() const { return value; }
};

template <typename T>
class CompareBy
{
public:
    CompareBy( const A& a, T (A::*getter)() const ) : a(a), getter(getter)
    {}

    bool operator<( const CompareBy& right ) const
    {
        return (a.*getter)() < (right.a.*getter)();
    }

    // you may also declare >, <=, >=, ==, != operators here

private:
    const A& a;
    T (A::*getter)() const;
};

class CompareByTime : public CompareBy<const boost::posix_time::ptime&>
{
public:
    CompareByTime(const A& a) : CompareBy(a, &A::getTime)
    {
    }
};

class CompareByValue : public CompareBy<double>
{
public:
    CompareByValue( const A& a ) : CompareBy(a, &A::getValue)
    {
    }
};

struct byTime_compare {
    bool operator() (const A& lhs, const A& rhs) const {
        return CompareByTime(lhs) < CompareByTime(rhs);
    }
};

int main()
{
    A a, b;

    ...

    if (CompareByValue(a) < CompareByValue(b))
    {
        ...
    }

    std::set<A, byTime_compare> mySet;
}


问:
An error occurred on insert in GroceryCrud
I face this error when I'm trying to save the add form from Grocery Crud..

this error only show up at my server where i change the http port into 88 for port forwarding issue, but the script were working normally in my localhost at my own laptop..

did the port change impact the grocery crud? can some one tell me how to fix it since I really have to change the port since port 80 and 8080 is already used..

答:
I had the same issue, but I'm using bootstrap theme

1.first set bootstrap theme:

$crud->set_theme('bootstrap');

2.in the file grocery_crud/themes/bootstrap/js/form/add.min.js
replace the code:
error:function(){alert(message_insert_error),a("#FormLoading").hide()}
with the code:
error:function(data){alert(JSON.stringify(data)),a("#FormLoading").hide()}

and it will show you what the error is about


问:
Checking if object is a DOM-element
Passing DOM elements to WebWorkers gets tricky since all references to the DOM are 'lost'. I need to check objects that are passed before the WebWorker's message is sent.

What is the fastest way to check if an instance of an object is a DOM-element OR/AND part of the DOM tree, OR has 'children' that contain any references to the DOM tree?

piece of the usage:

```<code>var a = new SharedWorker("bigdatahandler.js");
a.postMessage(s);

s //<--should not be a DOM object
</code>```

答:
To check whether an object is an Element instance, use instanceof:

```<code>s instanceof Element
</code>```

And to check its owner document, use ownerDocument:

```<code>s.ownerDocument == document
</code>```

ContentLicense: CC BY-SA 2.5

Title: Checking if object is a DOM-element

Body:
Passing DOM elements to WebWorkers gets tricky since all references to the DOM are 'lost'. I need to check objects that are passed before the WebWorker's message is sent.

What is the fastest way to check if an instance of an object is a DOM-element OR/AND part of the DOM tree, OR has 'children' that contain any references to the DOM tree?

piece of the usage:

var a = new SharedWorker("bigdatahandler.js");
a.postMessage(s);

s //<--should not be a DOM object

Body:
To check whether an object is an Element instance, use instanceof:

s instanceof Element

And to check its owner document, use ownerDocument:

s.ownerDocument == document


问:
Testing Pillow Image against Tensorflow model created from MNIST?
I went through the basic example on MNIST For ML Beginners, and they've created a simple digit classifier from the MNIST database which is pretty cool.

The tutorial code they have is mnist_softmax.py, but they use the classifier against their own test images. I want to try it on my own image loaded from Pillow.

Here is the part I've modified:

```<code>  from PIL import Image

  # Test trained model
  img = Image.open("09.png").convert('L')
  data = np.ndarray.flatten(np.array(img))
  result = sess.run(tf.argmax(y,1), feed_dict={x: [data]})
  print (' '.join(map(str,result)))
</code>```

But this errors with:

```<code>ValueError: Cannot feed value of shape (1, 1568) for Tensor u'Placeholder:0', which has shape '(?, 784)'
</code>```

The images I'm using are 28x28:

As 9 and 14 respectively.

I might be misunderstanding how the classifier works since I've just started to read a few tutorials on the subject of Machine Learning. My question is how can I load these images from Pillow into the classifier, and have the classifier determine the correct digits?

EDIT:
Based on @sascha's comments, I've updated the code, but am getting incorrect results. I tried cleaning up the 9 image:

But now the result is either 7 or 3.

答:
I can see that you have figured out the shape mismatch issue by converting your image to 1 channel. Now the problem is that your test prediction is wrong. So this explains that your ML model has failed for that test case.

Always calculate train and test accuracy to analyze the model performance and to know what problem your model is facing.

So look for solutions on how you can improve your model. Try Convolutional Neural Network, increase the number of layers, ensembling etc.

Check this link where I have written a simple CNN model for digit recognition which has a 99.45 accuracy.

Refer to other kernels in Kaggle to know more about different approaches to the same problem.

Hope this helps!

Body:
I went through the basic example on MNIST For ML Beginners, and they've created a simple digit classifier from the MNIST database which is pretty cool.

The tutorial code they have is mnist_softmax.py, but they use the classifier against their own test images. I want to try it on my own image loaded from Pillow.

Here is the part I've modified:

  from PIL import Image

  # Test trained model
  img = Image.open("09.png").convert('L')
  data = np.ndarray.flatten(np.array(img))
  result = sess.run(tf.argmax(y,1), feed_dict={x: [data]})
  print (' '.join(map(str,result)))

But this errors with:

ValueError: Cannot feed value of shape (1, 1568) for Tensor u'Placeholder:0', which has shape '(?, 784)'

The images I'm using are 28x28:

As 9 and 14 respectively.

I might be misunderstanding how the classifier works since I've just started to read a few tutorials on the subject of Machine Learning. My question is how can I load these images from Pillow into the classifier, and have the classifier determine the correct digits?

EDIT:
Based on @sascha's comments, I've updated the code, but am getting incorrect results. I tried cleaning up the 9 image:

But now the result is either 7 or 3.


问:
mongdb TypeError: db.collection is not a function
When I run this code it has a Error 'TypeError: db.collection is not a function'. How to solve this problem and where is wrong in this code.

const MongoClient = require('mongodb').MongoClient;

// Connection url
const url = 'mongodb://localhost:27017/blog';

// Connect using MongoClient
MongoClient.connect(url, (err, db) => {
  const note = {
    text: 'Note content text',
    title: 'Note title'
  };

  db.collection('notes').insert(note, (err, result) => {
    if (err) {
      console.log('An error has occurred!')
    } else {
      console.log('Insert success!')
    }
  });
});```

答: It's mongodb version error which you have installed in your project. You should run npm install mongodb@2.2.5 --save in your project


问:
Remove data from list after few hours
I have one type of data collection which is having eventDateTime field. For 6 hours data should display in list after 6 hours it should not be listed. Here I am sending you query,

```<code>  Events.find({$and: [{eventDateTime: {$lt: 21600}}, {isDisabled: false}, {isDeleted: false} ]}, function (error, data) {
               callback((error) ?   {} : data);
              }) ;
</code>```

How can I convert eventDateTime in seconds and compare with seconds as it is 6 hours?

答:
I think this solution it will help you.</p>

```<code>Events.find({$and: [{eventDateTime: {$gte: new Date(Date.now() - 6  60  60 * 1000)}},  {isDisabled: false}, {isDeleted: false} ]}, function (error, data) {
                callback((error) ? {}   : data);
            }) ;
</code>```

ContentLicense: CC BY-SA 4.0

Title: Remove data from list after few hours

Body:
I have one type of data collection which is having eventDateTime field. For 6 hours data should display in list after 6 hours it should not be listed. Here I am sending you query,

  Events.find({$and: [{eventDateTime: {$lt: 21600}}, {isDisabled: false}, {isDeleted: false} ]}, function (error, data) {
               callback((error) ?   {} : data);
              }) ;

How can I convert eventDateTime in seconds and compare with seconds as it is 6 hours?

Body:
I think this solution it will help you.

Events.find({$and: [{eventDateTime: {$gte: new Date(Date.now() - 6  60  60 * 1000)}},  {isDisabled: false}, {isDeleted: false} ]}, function (error, data) {
                callback((error) ? {}   : data);
            }) ;


问:
Create a method in an eloquent relationship
I have two models. One is Order and the other is Item. An order can have many items, and an item can have only one order.

I have this inside of my Order model:

```<code>public function items() {
    return $this->hasMany('App\Item', 'OrderNumber', 'OrderNumber');
}
</code>```

And here's my Item model:

```<code>function order() {
    return $this->belongsTo('App\Order');
}
</code>```

I'd like to have a function that can get the total of all of the items for an order. For example, I want to be able to use $order->items->totalPrice() to retrieve the total.

I've tried adding this to the Item model, with no luck.

```<code>public function totalPrice() {

    $total = 0;

    foreach($this as $item) {
        $total += $item->AmountPaid;
    }

    return $total;

}
</code>```

Here's the error I'm getting:

```<code>Undefined property: Illuminate\Database\Eloquent\Collection::$totalPrice
</code>```

What is the best/cleanest way to do what I'm trying to achieve? Even better, does Laravel have a built in method for totalling up?

答:
You could access this from Order (since the dynamic property for this relationship is going to return a Collection we can use the sum method to help us out):

```<code>public function totalPrice()
{
    return $this->items->sum('AmountPaid');
}
</code>```

Then call it on an Order instance.

```<code>$order->totalPrice();
</code>```

If you are going to be retrieving numerous Order records and spinning through them to get these totals you will want to eager load the relationship to avoid the N+1.

```<code>$orders = Order::with('items')->....->get();
</code>```

Body:
I have two models. One is Order and the other is Item. An order can have many items, and an item can have only one order.

I have this inside of my Order model:

public function items() {
    return $this->hasMany('App\Item', 'OrderNumber', 'OrderNumber');
}

And here's my Item model:

function order() {
    return $this->belongsTo('App\Order');
}

I'd like to have a function that can get the total of all of the items for an order. For example, I want to be able to use $order->items->totalPrice() to retrieve the total.

I've tried adding this to the Item model, with no luck.

public function totalPrice() {

    $total = 0;

    foreach($this as $item) {
        $total += $item->AmountPaid;
    }

    return $total;

}

Here's the error I'm getting:

Undefined property: Illuminate\Database\Eloquent\Collection::$totalPrice

What is the best/cleanest way to do what I'm trying to achieve? Even better, does Laravel have a built in method for totalling up?

Body:
You could access this from Order (since the dynamic property for this relationship is going to return a Collection we can use the sum method to help us out):

public function totalPrice()
{
    return $this->items->sum('AmountPaid');
}

Then call it on an Order instance.

$order->totalPrice();

If you are going to be retrieving numerous Order records and spinning through them to get these totals you will want to eager load the relationship to avoid the N+1.

$orders = Order::with('items')->....->get();


问:
i am not able to query the sub document in mongodb
i am not able to query results in this query,
i want result based on detail.type (like fetch record where detail.type="one") and fetch only first 10 records in detail.numbers array       </p>

```<code>{
            "_id" : ObjectId("5a27b609e101b6092b4ebf91"),
            "city" : "Mumbai",
            "detail" : [
                {
                    "type" : "One",
                    "name" : "Some name",
                    "_id" : ObjectId("5a27b609e101b6092b4ebf92"),
                    "numbers" : [
                        "72598xxx78",
                        "81301xxx88",
                        "83302xxx30",
                        "84309xxx43",
                        "85309xxx77",
                        "86309xxx61",
                        "87270xxx88",
                        "85272xxx36",
                        "88272xxx23",
                        "85276xxx01"
                    ]
                },
                {
                    "name" : "Some name",
                    "type" : "two",
                    "_id" : ObjectId("5a28e954d4f5a30527d92a32"),
                    "contact" : [
                        "72598xxx78",
                        "81301xxx88",
                        "83302xxx30",
                        "84309xxx43",
                        "85309xxx77",
                        "86309xxx61",
                        "87270xxx88",
                        "85272xxx36",
                        "88272xxx23",
                        "85276xxx01"
                    ]
                },
    ]
    }
</code>```

答:
```<code>db.collection.aggregate([

{
 $project:{
  detail:{
   $map:{
    input:{$filter:{input:"$detail",as:"d",cond:{$eq:["$$d.type","One"]}}},
    as:"d",
    in:{
     "type" : "$$d.type",
      "name" : "$$d.name",
      "numbers":{$slice:["$$d.numbers",10]}
    }

   }

  }
 }
}

])
</code>```

Body:
i am not able to query results in this query,
i want result based on detail.type (like fetch record where detail.type="one") and fetch only first 10 records in detail.numbers array

{
            "_id" : ObjectId("5a27b609e101b6092b4ebf91"),
            "city" : "Mumbai",
            "detail" : [
                {
                    "type" : "One",
                    "name" : "Some name",
                    "_id" : ObjectId("5a27b609e101b6092b4ebf92"),
                    "numbers" : [
                        "72598xxx78",
                        "81301xxx88",
                        "83302xxx30",
                        "84309xxx43",
                        "85309xxx77",
                        "86309xxx61",
                        "87270xxx88",
                        "85272xxx36",
                        "88272xxx23",
                        "85276xxx01"
                    ]
                },
                {
                    "name" : "Some name",
                    "type" : "two",
                    "_id" : ObjectId("5a28e954d4f5a30527d92a32"),
                    "contact" : [
                        "72598xxx78",
                        "81301xxx88",
                        "83302xxx30",
                        "84309xxx43",
                        "85309xxx77",
                        "86309xxx61",
                        "87270xxx88",
                        "85272xxx36",
                        "88272xxx23",
                        "85276xxx01"
                    ]
                },
    ]
    }


问:
Collapsible Navbar Angular 4 Bootstrap 4
Been struggling for a bit trying to get something working the exact way I want it. I have a Angular Universal App that has a navigation bar (vertical on top) and I want it to be responsive for mobile. I am targeting Bootstrap 4 Alpha 6 and sing ngx-bootstrap to wire it up. However no matter what I do, I cannot get all parts to work as expected.

Here is my template file (no custom styles here)

```<code><div class="pos-f-t fixed-top">
     <nav class="navbar navbar-inverse navbar-toggleable-md">
        <div class="collapse navbar-collapse">
           <a class="navbar-brand" routerLink="">Blog</a>
           <ul class="navbar-nav ml-auto mt-2 mt-md-0">
              <li class="nav-item hidden-lg-down">
                  <a routerLink="/blog" [routerLinkActive]="['router-link-active']" class="list-group-item">Blog</a>
              </li>
              <li class="nav-item">
                  <a routerLink="/about" [routerLinkActive]="['router-link-active']" class="list-group-item">About</a>
              </li>
              <li class="nav-item">
                  <a routerLink="/search" [routerLinkActive]="['router-link-active']" class="list-group-item">Search</a>
              </li>
          </ul>
       </div>
     </nav>
</div>
</code>```

I have tried a few SO posts as well as MISC walkthroughs in GitHub Issues, but I am not able at this time. On small viewfinders, I want there to be an icon that hides/shows the menu onclick (whether assigning a css class to a div or using something else). The issue that I am running into is that Since I am using Universal, I have no jQuery access, so I assume out of the box Bootstrap Nav will not work. Anyone who can help would be my hero.

答:
Just add in your ts file:

```<code>export class HeaderComponent implements OnInit {
    public isCollapsed = true;
    constructor() {
    }
    ngOnInit() {
    }
}
</code>```

Then In your component.html add (click)="isCollapsed = !isCollapsed" in button

```<code><div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar" (click)="isCollapsed = !isCollapsed"
        [attr.aria-expanded]="!isCollapsed">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#"><img class="navbar-logo" src="../../assets/images/3.png"></a>
</div>
</code>```

Then in your div where you have to show collapse item add [ngbCollapse]="isCollapsed"

```<code><div class="collapse navbar-collapse" id="myNavbar" [ngbCollapse]="isCollapsed">
</code>```

Body:
Been struggling for a bit trying to get something working the exact way I want it. I have a Angular Universal App that has a navigation bar (vertical on top) and I want it to be responsive for mobile. I am targeting Bootstrap 4 Alpha 6 and sing ngx-bootstrap to wire it up. However no matter what I do, I cannot get all parts to work as expected.

Here is my template file (no custom styles here)

           Blog

                  Blog

                  About

                  Search

I have tried a few SO posts as well as MISC walkthroughs in GitHub Issues, but I am not able at this time. On small viewfinders, I want there to be an icon that hides/shows the menu onclick (whether assigning a css class to a div or using something else). The issue that I am running into is that Since I am using Universal, I have no jQuery access, so I assume out of the box Bootstrap Nav will not work. Anyone who can help would be my hero.

Body:
Just add in your ts file:

export class HeaderComponent implements OnInit {
    public isCollapsed = true;
    constructor() {
    }
    ngOnInit() {
    }
}

Then In your component.html add (click)="isCollapsed = !isCollapsed" in button

<div class="navbar-header">
    <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar" (click)="isCollapsed = !isCollapsed"
        [attr.aria-expanded]="!isCollapsed">
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
        <span class="icon-bar"></span>
    </button>
    <a class="navbar-brand" href="#"><img class="navbar-logo" src="../../assets/images/3.png"></a>
</div>

Then in your div where you have to show collapse item add [ngbCollapse]="isCollapsed"

<div class="collapse navbar-collapse" id="myNavbar" [ngbCollapse]="isCollapsed">


问:
Jquery on hover add class to another element simply not working
I appreciate there are many similar posts on here but none seem to address why this code is not working.

The idea is, when a menu li is hovered the background of the menu should change using CSS.

I found the code on StackOverflow

add class to a div when hover another one (Javascript)

but in my case, it simply does not work even when running at the very end of the footer.

```<code><script>
   jQuery(document).ready(function() {
     jQuery('#responsive-menu-item-48473').hover(function(){
           jQuery('#responsive-menu-container').addClass('blue');
       },function(){
          jQuery('#responsive-menu-container').removeClass('blue');
       });
   });
</script>
</code>```

Additional info...

cut down html for the menu:

```<code><button id="responsive-menu-button" class="responsive-menu-button responsive-menu-boring responsive-menu-accessible" type="button" aria-label="Menu">
    <span class="responsive-menu-label responsive-menu-label-left">
        <span class="responsive-menu-button-text">Menu</span>
    </span>

    <span class="responsive-menu-box">
        <span class="responsive-menu-inner"></span>
    </span>
</button>

<div id="responsive-menu-container" class="slide-left">
    <div id="responsive-menu-wrapper">
        <div id="responsive-menu-title">
            Main Menu
        </div>

        <ul id="responsive-menu" class="">
            <li id="responsive-menu-item-57071" class=" menu-item menu-item-type-custom menu-item-object-custom responsive-menu-item"><a href="http://localhost/wordpress-updates/fx/my-account/customer-logout/" class="responsive-menu-item-link">Logout</a></li>
            <li id="responsive-menu-item-48473" class=" menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-16137 current_page_item responsive-menu-item responsive-menu-current-item"><a title="Home" href="http://localhost/wordpress-updates/" class="responsive-menu-item-link">Home</a></li>
        </ul>
    </div>
</div>
</code>```

Haven't got as far creating the classes yet, not that that should matter?

答:
Looks like the code is correct.....

The CSS rules might not be correct to reflect the changes. Try inspecting elements and hover over jQuery('#responsive-menu-item-48473')

Body:
I appreciate there are many similar posts on here but none seem to address why this code is not working.

The idea is, when a menu li is hovered the background of the menu should change using CSS.

I found the code on StackOverflow

add class to a div when hover another one (Javascript)

but in my case, it simply does not work even when running at the very end of the footer.

Additional info...

cut down html for the menu:

<button id="responsive-menu-button" class="responsive-menu-button responsive-menu-boring responsive-menu-accessible" type="button" aria-label="Menu">

        Menu

</button>

            Main Menu

Logout

Home

Haven't got as far creating the classes yet, not that that should matter?


问:
How do you split a list by space in python?
How do you split a list by space? With the code below, it reads a file with 4 lines of 7 numbers separated by spaces. When it takes the file and then splits it, it splits it by number so if i print item[0], 5 will print instead of 50. here is the code

```<code>def main():
    filename = input("Enter the name of the file: ")
    infile = open(filename, "r")
    for i in range(4):
        data = infile.readline()
        print(data)
        item = data.split()
        print(data[0])

main()
</code>```

the file looks like this

50 60 15 100 60 15 40 /n
100 145 20 150 145 20 45 /n
50 245 25 120 245 25 50 /n
100 360 30 180 360 30 55 /n

答:
There's not a lot wrong with what you are doing, except that you are printing the wrong thing.

Instead of

```<code>print(data[0])
</code>```

use

```<code>print(item[0])
</code>```

data[0] is the first character of the string you read from file. You split this string into a variable called item so that's what you should print.

Body:
How do you split a list by space? With the code below, it reads a file with 4 lines of 7 numbers separated by spaces. When it takes the file and then splits it, it splits it by number so if i print item[0], 5 will print instead of 50. here is the code

def main():
    filename = input("Enter the name of the file: ")
    infile = open(filename, "r")
    for i in range(4):
        data = infile.readline()
        print(data)
        item = data.split()
        print(data[0])

main()

the file looks like this

50 60 15 100 60 15 40 /n
100 145 20 150 145 20 45 /n
50 245 25 120 245 25 50 /n
100 360 30 180 360 30 55 /n

Body:
There's not a lot wrong with what you are doing, except that you are printing the wrong thing.

Instead of

print(data[0])

use

print(item[0])

data[0] is the first character of the string you read from file. You split this string into a variable called item so that's what you should print.


问:
LazyInitialisationException - failed to lazily initialise a collection of role
The purpose of this code is to allow a user to check an ID; in this case it would be an ID to check a competition of a specific sport, in order to view the relevant match and it's details. The whole purpose of doing this was to inform the user that if they had entered an incorrect ID, I simply wanted to generate a message within the SOAP request informing that the entered competitionID was incorrect. When I am debugging my code, I am faced with an error "LazyInitialisationException: failed to lazily initialise a collection of role", any ideas?</p>

```<code>public void CompetitionIdChecker(Set<RestrictionFailure> failures, CompetitionSetup competition) {
    Long compId21 = Long.valueOf(competition.getCompetitionId());
    try {
        Node competitionNode = nodeDao.findById(competition.getCompetitionId());
        Set<Node> childNodes = competitionNode.getChildNodes();
        Iterator<Node> nodeItr = childNodes.iterator();
        Node feedNode = nodeItr.next();
        Feed incidentFeed = competition.getIncidentProvider();
        Node Node = null;
        if (incidentFeed.name().equalsIgnoreCase(feedNode.getSys().getCode())) {
            Node = feedNode.findLinkedNode(new SystemKey(incidentFeed.name()));
        }
        if (Node != null) {
            // as node is set as final level in nodes hierarchy
            if (Node.getChildNodes().size() > 0) {
                System.out.println("it is not valid");
                failures.add(new RestrictionFailure("Competition ID does not exist in Nodes table"));
            } else {
                System.out.println("compId is valid");
            }

        }
    } catch (Exception e) {
        LOGGER.error("Error getting competition id", e);
        // rollback(tx);
    }
}
</code>```

答:
The default mapping of a many-to-one relation is set to lazy loading. This means that child nodes are not queried when you get the parent object. This makes sense because otherwise you would query all relations of a parent object even if you would never use it. So when you access such child objects you get a LazyLoadingException.
To overcome this you can either set the mapping to non-lazy or make a query that fetches the children. Please take a look at fetch joins. https://docs.jboss.org/hibernate/orm/3.5/reference/de-DE/html/queryhql.html#queryhql-joins</p>

Body:
The purpose of this code is to allow a user to check an ID; in this case it would be an ID to check a competition of a specific sport, in order to view the relevant match and it's details. The whole purpose of doing this was to inform the user that if they had entered an incorrect ID, I simply wanted to generate a message within the SOAP request informing that the entered competitionID was incorrect. When I am debugging my code, I am faced with an error "LazyInitialisationException: failed to lazily initialise a collection of role", any ideas?

public void CompetitionIdChecker(Set<RestrictionFailure> failures, CompetitionSetup competition) {
    Long compId21 = Long.valueOf(competition.getCompetitionId());
    try {
        Node competitionNode = nodeDao.findById(competition.getCompetitionId());
        Set<Node> childNodes = competitionNode.getChildNodes();
        Iterator<Node> nodeItr = childNodes.iterator();
        Node feedNode = nodeItr.next();
        Feed incidentFeed = competition.getIncidentProvider();
        Node Node = null;
        if (incidentFeed.name().equalsIgnoreCase(feedNode.getSys().getCode())) {
            Node = feedNode.findLinkedNode(new SystemKey(incidentFeed.name()));
        }
        if (Node != null) {
            // as node is set as final level in nodes hierarchy
            if (Node.getChildNodes().size() > 0) {
                System.out.println("it is not valid");
                failures.add(new RestrictionFailure("Competition ID does not exist in Nodes table"));
            } else {
                System.out.println("compId is valid");
            }

        }
    } catch (Exception e) {
        LOGGER.error("Error getting competition id", e);
        // rollback(tx);
    }
}


问:
AWS CodeDeploy ymal file error
I am deploying an application using AWS code deploy to Windows environment. I use an apspec.yml yaml file. When I deploy the application I get following error

The deployment failed because an invalid version value () was entered in the application specification file. Make sure your AppSpec file specifies "0.0" as the version, and then try again.

It seems like there is a problem with encoding or line ending. All the materials in the internet are for linux but not for windows. I use visual studio editor to edit this file.  How to fix this issue?

答:
In my case the encoding was wrong. appspec.yml should be saved as UTF-8 and not UTF-8 BOM.

BTW: The encoding can be changed in VS 2017 using File > Save as.., then the down arrow at the Save-Button ... Save with encoding...

Title: AWS CodeDeploy ymal file error


问:
Error: Execution failed for task ':app:clean'. Unable to delete file
I'm trying to rebuild my Android Studio Gradle project (containing mostly Kotlin code), but it started to throw an UnableToDeleteFileException during the cleaning/rebuilding process:

```<code>Execution failed for task ':app:clean'.
> Unable to delete file: C:\Users\User\KotlinGameEngine\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.1\jars\classes.jar
</code>```

This started happening after I tried to change my project's package structure. Unfortunately, I did it by renaming and moving the source folders rather than refactoring through Android Studio, which was a bad idea.

I've been searching for a solution to this problem all day, and these are the things I have tried to no avail:

Doing a Gradle sync;

Reinstalling Java JRE and Java SDK;

Reinstalling the latest version of Android Studio (1.4);

Rolling back to the previous AS version (1.3);

Invalidating the AS cache and restarting;

Deleting the gradle and .gradle directories in the project directory;

Deleting the .gradle directory in my user directory;

Running gradlew clean from the AS terminal;

Manually copying the sources over to a new project (weird that it somehow persists across projects...)

Things that I've tried with a little success, but only let me perform one more clean and rebuild before the error occurs again:

Closing AS, manually deleting the build files, and opening it again;

Killing the java.exe process while AS is running (this could technically be done every time, but it's tedious and slows down the build process)

So it seems that compile the Java process may put a lock on the build files for some reason, but it might also be something to do with Kotlin. I have a (more mature) Java Android project that I'm working on, though I can't reproduce this error when cleaning it. It seems to only happen to my Kotlin project.

Update:

I've found that the problem is being caused by the Kotlin Android plugin. The problem disappears when I remove apply plugin: 'kotlin-android' from the module's build.gradle file and comes back when I reinsert it. Feel free to offer any insight into this.

Update 2:

The last update isn't the cause. I found that if a project contains a Kotlin file then rebuilding and cleaning fails. It continues to fail, even if all the Kotlin files are removed, until the background Java process is killed, meaning it has some kind of lock on the build files. I submitted a bug here with more details and steps to reproduce the bug: KT-9440

答: For me, this happened because of an active debugging process. So, before cleaning or rebuilding, make sure to kill all active processes. To nail down the success, execute Invalidate Caches/Restart.

Body:
I'm trying to rebuild my Android Studio Gradle project (containing mostly Kotlin code), but it started to throw an UnableToDeleteFileException during the cleaning/rebuilding process:

Execution failed for task ':app:clean'.
> Unable to delete file: C:\Users\User\KotlinGameEngine\app\build\intermediates\exploded-aar\com.android.support\appcompat-v7\23.0.1\jars\classes.jar

This started happening after I tried to change my project's package structure. Unfortunately, I did it by renaming and moving the source folders rather than refactoring through Android Studio, which was a bad idea.

I've been searching for a solution to this problem all day, and these are the things I have tried to no avail:

Doing a Gradle sync;

Reinstalling Java JRE and Java SDK;

Reinstalling the latest version of Android Studio (1.4);

Rolling back to the previous AS version (1.3);

Invalidating the AS cache and restarting;

Deleting the gradle and .gradle directories in the project directory;

Deleting the .gradle directory in my user directory;

Running gradlew clean from the AS terminal;

Manually copying the sources over to a new project (weird that it somehow persists across projects...)

Things that I've tried with a little success, but only let me perform one more clean and rebuild before the error occurs again:

Closing AS, manually deleting the build files, and opening it again;

Killing the java.exe process while AS is running (this could technically be done every time, but it's tedious and slows down the build process)

So it seems that compile the Java process may put a lock on the build files for some reason, but it might also be something to do with Kotlin. I have a (more mature) Java Android project that I'm working on, though I can't reproduce this error when cleaning it. It seems to only happen to my Kotlin project.

Update:

I've found that the problem is being caused by the Kotlin Android plugin. The problem disappears when I remove apply plugin: 'kotlin-android' from the module's build.gradle file and comes back when I reinsert it. Feel free to offer any insight into this.

Update 2:

The last update isn't the cause. I found that if a project contains a Kotlin file then rebuilding and cleaning fails. It continues to fail, even if all the Kotlin files are removed, until the background Java process is killed, meaning it has some kind of lock on the build files. I submitted a bug here with more details and steps to reproduce the bug: KT-9440


问:
How to clean a class correcly
I have a class with functions to read data files. When read the class stores this datas in public properties.

After that I write the content of the puplic properties into a database.

Then it repeates. This means I read again datas with this class.

Before it repeates I want to clean the class.

What is the best way to do it?

Is it better to clear the content of the public properties manually or is it better to dispose the class. Maybe this is the more elegant way to do it?

答:
Let's assume your class looks similar to:

```<code>public class MyClass
{
  public double IntField { get; set; }
  public string StringField { get; set; }
}
</code>```

And your application something like:

```<code>public class MyApp
{
  public void Execute() {
    var myClass = new MyClass();

    // set properties
    myClass.IntField = 123;
    myClass.StringField = "Hello";

    // save to DB
  }
}
</code>```

Each time your application runs, it will run the Execute method which will create a new instance of your class. This way all class properties will be empty or "clean" as you call it.

Title: How to clean a class correcly

Body:
Let's assume your class looks similar to:

public class MyClass
{
  public double IntField { get; set; }
  public string StringField { get; set; }
}

And your application something like:

public class MyApp
{
  public void Execute() {
    var myClass = new MyClass();

    // set properties
    myClass.IntField = 123;
    myClass.StringField = "Hello";

    // save to DB
  }
}

Each time your application runs, it will run the Execute method which will create a new instance of your class. This way all class properties will be empty or "clean" as you call it.


答:
It is working check her, I think you missed to add jquery

jQuery(document).ready(function() {
     jQuery('#responsive-menu-item-48473').hover(function(){
           jQuery('#responsive-menu-container').addClass('blue');
       },function(){
          jQuery('#responsive-menu-container').removeClass('blue');
       });
   });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.blue{
background-color:#0000ff;}</code>```

<button id="responsive-menu-button" class="responsive-menu-button responsive-menu-boring responsive-menu-accessible" type="button" aria-label="Menu">

                Menu

        </button>

                    Main Menu

Logout

Home

```

Title: Jquery on hover add class to another element simply not working

Body:
It is working check her, I think you missed to add jquery

jQuery(document).ready(function() {
     jQuery('#responsive-menu-item-48473').hover(function(){
           jQuery('#responsive-menu-container').addClass('blue');
       },function(){
          jQuery('#responsive-menu-container').removeClass('blue');
       });
   });

.blue{
background-color:#0000ff;}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="responsive-menu-button" class="responsive-menu-button responsive-menu-boring responsive-menu-accessible" type="button" aria-label="Menu">
            <span class="responsive-menu-label responsive-menu-label-left">
                <span class="responsive-menu-button-text">Menu</span>
            </span>

            <span class="responsive-menu-box">
                <span class="responsive-menu-inner"></span>
            </span>
        </button>

        <div id="responsive-menu-container" class="slide-left">
            <div id="responsive-menu-wrapper">
                <div id="responsive-menu-title">
                    Main Menu
                </div>

        <ul id="responsive-menu" class="">
            <li id="responsive-menu-item-57071" class=" menu-item menu-item-type-custom menu-item-object-custom responsive-menu-item"><a href="http://localhost/wordpress-updates/fx/my-account/customer-logout/" class="responsive-menu-item-link">Logout</a></li>
            <li id="responsive-menu-item-48473" class=" menu-item menu-item-type-post_type menu-item-object-page menu-item-home current-menu-item page_item page-item-16137 current_page_item responsive-menu-item responsive-menu-current-item"><a title="Home" href="http://localhost/wordpress-updates/" class="responsive-menu-item-link">Home</a></li>
        </ul>
    </div>
    </div>


问:
Write a function that adds lists elements using *args
I would like to write a function that calculates scalar sum of several vectors. It should take several lists as arguments eg.

```<code>def add_lists(x, y, z):
   # return sum of x, y, z

x = add_lists([1, 2],[2, 1],[3, 1])
# x returns [6, 4]
</code>```

It is easy to do it for only two arguments, but how can I do it using *args if they are more than two, so that my add_lists will return [6, 4]?

答:
If I am understanding your question correctly, you wish to write a function that can take any amount of vectors and return the sum? Then yes, you would need to use *args like so:

```<code>def add_lists(*args):
    final_vector = [0, 0]
    for vector in args:
        final_vector[0] += vector[0]
        final_vector[1] += vector[1]
    return final_vector
</code>```

Basically, treat args as a list - containing all the arguments passed through when you call the function.

Body:
I would like to write a function that calculates scalar sum of several vectors. It should take several lists as arguments eg.

def add_lists(x, y, z):
   # return sum of x, y, z

x = add_lists([1, 2],[2, 1],[3, 1])
# x returns [6, 4]

It is easy to do it for only two arguments, but how can I do it using *args if they are more than two, so that my add_lists will return [6, 4]?

Body:
If I am understanding your question correctly, you wish to write a function that can take any amount of vectors and return the sum? Then yes, you would need to use *args like so:

def add_lists(*args):
    final_vector = [0, 0]
    for vector in args:
        final_vector[0] += vector[0]
        final_vector[1] += vector[1]
    return final_vector

Basically, treat args as a list - containing all the arguments passed through when you call the function.


问:
iPhone Development - My application crashes when I change the orientation
I'm bumping into this problem where my application gets EXC_BAD_ACCESS error and stucks/stops. I'm using "Rotate Left" & "Rotate Right" options of simulator to simulate the orientation change behavior. What can be the possible reasons for this error? Since I'm not getting details about the error, I can't trace it.

All my controller classes have:

```<code>- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);    // Return YES for supported orientations
}
</code>```

Any ideas, pointers? Thanks.

But my code does not have a call to [UIDevice setOrientation:] method.

This is the trace that i get in debug window:

```<code>objc_msgSend
-[UIWindow _handleDeviceOrientationChange:]
_nsnote_callback
__CFXNotificationPost
_CFXNotificationPostNotification
-[NSNotificationCenter postNotificationName:object:userInfo:]
-[UIDevice setOrientation:]
-[UIApplication handleEvent:withNewEvent:]
_[UIApplication sendEvent:]
_UIApplicationHandleEvent
SendEvent
PurpleEventTimerCallBack
CFRunLoopRunSpecific
CFRunLookRunInMode
GSEventRunModel
GSEventRun
-[UIApplication _run]
UIApplicationMain
main
</code>```

Note that the error appears when my view contains a tab bar. Since no one is replying, i guess this is not a common problem, and i cannot find any resource addressing this issue.

Can i somehow tell my application to run in single orientation (portrait), and don't send events for orientation change.? This might solve my problem, but this is the alternate that i'm looking for.

Thanks Paul, your comment was helpful, and i was able to fix the problem but with the cost of retaining memory for the view i don't need. Here's whats happening:

I have a view (View A) which opens another view (View B). App Delegate method is responsible for opening both View A and View B. Application does not crashes on View A. I remove View A from window, and release it's controller object, and add View B to the window. I believe this is where i'm doing something wrong. Can you help me out with the code?

Here's the code for releasing View A and opening View B:

```<code>- (void)openViewB {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:window cache:YES];

    // Remove viewControllerA from the window's view
    [window removeFromSuperview];

    // !-- Commenting out this block fixes the issue --!
    // Release memory wired for viewControllerA view
    if(viewControllerA) {
        [viewControllerA release];
        viewControllerA = nil;
    }

    // We call window:addSubView to add the viewB to the main window.
    // You can use this call to add other views as child views not only to windows
    // but to other views as well. (UIWindow is a subclass of UIView).
    [window addSubview:viewControllerB.view];
    [UIView commitAnimations];

    // Override point for customization after application launch
    [window makeKeyAndVisible];
}
</code>```

I started the application with tab bar application template, and viewControllerB is of type UITabBarController. I'm definitely doing something wrong here. Any pointers?

答:
Set a breakpoint on -[UIDevice setOrientation:] and step through your code in the debugger.

To make debugging easier, you can type call (void)instrumentObjcMessageSends(YES) right in the debugger console to begin logging objc_msgSends to /tmp/, then continue execution and it will trace all the messages that are sent right up until the crash.

OwnerDisplayName: Mustafa

Body:
I'm bumping into this problem where my application gets EXC_BAD_ACCESS error and stucks/stops. I'm using "Rotate Left" & "Rotate Right" options of simulator to simulate the orientation change behavior. What can be the possible reasons for this error? Since I'm not getting details about the error, I can't trace it.

All my controller classes have:

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return (interfaceOrientation == UIInterfaceOrientationPortrait);    // Return YES for supported orientations
}

Any ideas, pointers? Thanks.

But my code does not have a call to [UIDevice setOrientation:] method.

This is the trace that i get in debug window:

objc_msgSend
-[UIWindow _handleDeviceOrientationChange:]
_nsnote_callback
__CFXNotificationPost
_CFXNotificationPostNotification
-[NSNotificationCenter postNotificationName:object:userInfo:]
-[UIDevice setOrientation:]
-[UIApplication handleEvent:withNewEvent:]
_[UIApplication sendEvent:]
_UIApplicationHandleEvent
SendEvent
PurpleEventTimerCallBack
CFRunLoopRunSpecific
CFRunLookRunInMode
GSEventRunModel
GSEventRun
-[UIApplication _run]
UIApplicationMain
main

Note that the error appears when my view contains a tab bar. Since no one is replying, i guess this is not a common problem, and i cannot find any resource addressing this issue.

Can i somehow tell my application to run in single orientation (portrait), and don't send events for orientation change.? This might solve my problem, but this is the alternate that i'm looking for.

Thanks Paul, your comment was helpful, and i was able to fix the problem but with the cost of retaining memory for the view i don't need. Here's whats happening:

I have a view (View A) which opens another view (View B). App Delegate method is responsible for opening both View A and View B. Application does not crashes on View A. I remove View A from window, and release it's controller object, and add View B to the window. I believe this is where i'm doing something wrong. Can you help me out with the code?

Here's the code for releasing View A and opening View B:

- (void)openViewB {
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDuration:1.0];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:window cache:YES];

    // Remove viewControllerA from the window's view
    [window removeFromSuperview];

    // !-- Commenting out this block fixes the issue --!
    // Release memory wired for viewControllerA view
    if(viewControllerA) {
        [viewControllerA release];
        viewControllerA = nil;
    }

    // We call window:addSubView to add the viewB to the main window.
    // You can use this call to add other views as child views not only to windows
    // but to other views as well. (UIWindow is a subclass of UIView).
    [window addSubview:viewControllerB.view];
    [UIView commitAnimations];

    // Override point for customization after application launch
    [window makeKeyAndVisible];
}

I started the application with tab bar application template, and viewControllerB is of type UITabBarController. I'm definitely doing something wrong here. Any pointers?

LastEditorDisplayName: Mustafa

OwnerDisplayName: rpetrich


问:
"cannot create instance defined in assembly" when creating a new System.Drawing.Icon
I am trying to create a system tray icon in WPF using the lines of code below:

```<code>System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
ni.Icon = new System.Drawing.Icon("main.ico");
</code>```

XAML:

```<code>> <Window x:Class="WpfExample.Window1"
>     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
>     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>     Title="Window1" Height="300" Width="300">
>     <Grid>
>         <Button Height="23" Margin="103,0,100,100" Name="button1"
> VerticalAlignment="Bottom">Submit</Button>
>         <TextBox Height="23" Margin="77,75,81,0" Name="textBox1"
> VerticalAlignment="Top" />
>     </Grid> </Window>
</code>```

I've searched for a solution on Google but I'm trying to learn WPF and this is a problem I have hit when creating a system tray icon. The message I get is shown below:

Cannot create instance of 'Window1'
  defined in assembly 'WpfExample,
  Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null'. Exception has
  been thrown by the target of an
  invocation.  Error in markup file
  'Window1.xaml' Line 1 Position 9.

Can anyone point me in the right direction?

答:
I created a small sample application that displays a tray icon. You can try to run it and study how the code works. I uploaded it to the SkyDrive:

http://cid-1fe4c9928da08eaa.office.live.com/self.aspx/P%c3%bablico/Tray-WpfApplication1.zip

Body:
I am trying to create a system tray icon in WPF using the lines of code below:

System.Windows.Forms.NotifyIcon ni = new System.Windows.Forms.NotifyIcon();
ni.Icon = new System.Drawing.Icon("main.ico");

XAML:

> <Window x:Class="WpfExample.Window1"
>     xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
>     xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
>     Title="Window1" Height="300" Width="300">
>     <Grid>
>         <Button Height="23" Margin="103,0,100,100" Name="button1"
> VerticalAlignment="Bottom">Submit</Button>
>         <TextBox Height="23" Margin="77,75,81,0" Name="textBox1"
> VerticalAlignment="Top" />
>     </Grid> </Window>

I've searched for a solution on Google but I'm trying to learn WPF and this is a problem I have hit when creating a system tray icon. The message I get is shown below:

Cannot create instance of 'Window1'
  defined in assembly 'WpfExample,
  Version=1.0.0.0, Culture=neutral,
  PublicKeyToken=null'. Exception has
  been thrown by the target of an
  invocation.  Error in markup file
  'Window1.xaml' Line 1 Position 9.

Can anyone point me in the right direction?


问:
Problem creating foreign keys in mySql
I created a foreign key in my sql by the following statemnt..

```<code>ALTER TABLE `users` ADD FOREIGN KEY ( `id`)
REFERENCES `user_login` (`user_id`)
ON DELETE CASCADE ;
</code>```

The creation appears to succeed then after that I execute a delete statement

```<code>DELETE From user_login WHERE user_id = 1576;
</code>```

yet in users the row still exists that is referencing that. I open up the mysql workbench and it doesn't show any signs that the foreign key was created. Does anyone know why this would be? Or what I am doing wrong? It is a one-to-one relationship in the two tables.

答:
The table may be in MyISAM format, which does not support foreign keys.

Try converting it to InnoDB first:

```<code>alter table users engine=InnoDB;
</code>```

Title: Problem creating foreign keys in mySql

Body:
I created a foreign key in my sql by the following statemnt..

ALTER TABLE `users` ADD FOREIGN KEY ( `id`)
REFERENCES `user_login` (`user_id`)
ON DELETE CASCADE ;

The creation appears to succeed then after that I execute a delete statement

DELETE From user_login WHERE user_id = 1576;

yet in users the row still exists that is referencing that. I open up the mysql workbench and it doesn't show any signs that the foreign key was created. Does anyone know why this would be? Or what I am doing wrong? It is a one-to-one relationship in the two tables.

Body:
The table may be in MyISAM format, which does not support foreign keys.

Try converting it to InnoDB first:

alter table users engine=InnoDB;


问:
Python - Remove any element from a list of strings that is a substring of another element
So starting with a list of strings, as below

string_list = ['rest', 'resting', 'look', 'looked', 'it', 'spit']

I want to remove any element from the list that is a substring of another element, giving the result for instance...

string_list = ['resting', 'looked', 'spit']

I have some code that acheives this but it's embarrassingly ugly and probably needlessly complex. Is there a simple way to do this in Python?

答:
Here's another way to do it. Assuming you have a sorted list to start with and you don't have to do the sieving inplace, we can just choose the longest strings in one pass:</p>

```<code>string_list = sorted(string_list)
sieved = []
for i in range(len(string_list) - 1):
    if string_list[i] not in string_list[i+1]:
        sieved.append(string_list[i])
</code>```

Body:
Here's another way to do it. Assuming you have a sorted list to start with and you don't have to do the sieving inplace, we can just choose the longest strings in one pass:

string_list = sorted(string_list)
sieved = []
for i in range(len(string_list) - 1):
    if string_list[i] not in string_list[i+1]:
        sieved.append(string_list[i])


问:
Excluding subdirectory from gulp-watch throwing type error
I'm running the following watch task:

```<code>gulp.task('watch', function() {

    gulp.watch('./ui/scss/*.scss', ['styles']);
    gulp.watch('./js/*.js', '!./js/vendor/*.js', ['scripts']);
    gulp.watch('./**/*.html', ['html']);

});
</code>```

But it seems to throw the following error?...

```<code>TypeError: Cannot assign to read only property 'mark' of !./js/vendor/*.js at new Gaze
</code>```

答:
the second parameter of the watch must declare as array</p>

```<code>gulp.watch('src...', ['taskname', ......];
</code>```

Body:
I'm running the following watch task:

gulp.task('watch', function() {

    gulp.watch('./ui/scss/*.scss', ['styles']);
    gulp.watch('./js/*.js', '!./js/vendor/*.js', ['scripts']);
    gulp.watch('./**/*.html', ['html']);

});

But it seems to throw the following error?...

TypeError: Cannot assign to read only property 'mark' of !./js/vendor/*.js at new Gaze

Body:
the second parameter of the watch must declare as array

gulp.watch('src...', ['taskname', ......];


答:
You can use zip and *args:

```<code>def add_lists(*args):
    return [sum(x) for x in zip(*args)]

x = add_lists([1, 2],[2, 1],[3, 1])
# x is [6, 4]
</code>```

Title: Write a function that adds lists elements using *args

Body:
You can use zip and *args:

def add_lists(*args):
    return [sum(x) for x in zip(*args)]

x = add_lists([1, 2],[2, 1],[3, 1])
# x is [6, 4]


问:
convert string to normal html tag
I am missing out something here. I am trying to get the image during execution and display in pophover. This pophover is on table row.

The basic flow is, user will hover on one row so this will show a popover on right holding the product image along with some description.

I was able to track the image but while returning the whole image tag is appending as string. Therefore, the code is parsed as string and displayed as it is.

How can I fix this?

```<code>$('body').popover({
    placement:"right",
    trigger:"hover",
    selector:'tr[id=popover]',
    content:function(){
        return '<img src = "' + $(this).children("td").children("img")[0].currentSrc + '" width="200" height="200">'
    }
});
</code>```

I am thinking if I can convert the return part to normal image tag then that can solve this issue.

Hope this screenshots helps.

答:
https://getbootstrap.com/docs/3.3/javascript/#popovers-options:

html | boolean | false

  Insert HTML into the popover. If false, jQuery's text method will be used to insert content into the DOM. Use text if you're worried about XSS attacks.

Title: convert string to normal html tag

Body:
I am missing out something here. I am trying to get the image during execution and display in pophover. This pophover is on table row.

The basic flow is, user will hover on one row so this will show a popover on right holding the product image along with some description.

I was able to track the image but while returning the whole image tag is appending as string. Therefore, the code is parsed as string and displayed as it is.

How can I fix this?

$('body').popover({
    placement:"right",
    trigger:"hover",
    selector:'tr[id=popover]',
    content:function(){
        return ''
    }
});

I am thinking if I can convert the return part to normal image tag then that can solve this issue.

Hope this screenshots helps.


答: create new method , name it let say "clear_data" , call it before load data from function that do it . also may be you will need call it from destructor to prevent memory leaks (in case you have pointers that point to some allocated memory ). </p>

Title: How to clean a class correcly

Body:
I have a class with functions to read data files. When read the class stores this datas in public properties.

After that I write the content of the puplic properties into a database.

Then it repeates. This means I read again datas with this class.

Before it repeates I want to clean the class.

What is the best way to do it?

Is it better to clear the content of the public properties manually or is it better to dispose the class. Maybe this is the more elegant way to do it?


问:
Firestore listener initialized with LifeCycleOwner argument misses updates when activity is paused
In my app I'm using a Firestore listener to listen for changes to a certain document. I init this listener using a LifeCycleOwner argument:

```<code>FireUtil.Events.getEvent( mEventKey ).addSnapshotListener( EventMainActivity.this, (documentSnapshot, e)
</code>```

When I make change to this document in another activity (the one in which I added the listener is paused), and return to the initial activity, changes are not visible (a restart of the activity is required).

When I remove the life-cycle owner argument, the listener is triggered and changes are visible (but I need to manually clean the listener).

Is this intended behavior, or am I missing something?

答:
When you are using addSnapshotListener you attach a listener that gets triggered for any changes. See here the offical documentation. Apparently you detach the listeners in onPause() method.

When you are passing in the EventMainActivity, Cloud Firestore will clean up the listeners automatically for you when the activity is stopped.

There is an altenative way for doing this and would be to use get() method to get the desired documents, which just reads that particular document once. Since it only reads once, there is no listener to clean up.

Body:
In my app I'm using a Firestore listener to listen for changes to a certain document. I init this listener using a LifeCycleOwner argument:

FireUtil.Events.getEvent( mEventKey ).addSnapshotListener( EventMainActivity.this, (documentSnapshot, e)

When I make change to this document in another activity (the one in which I added the listener is paused), and return to the initial activity, changes are not visible (a restart of the activity is required).

When I remove the life-cycle owner argument, the listener is triggered and changes are visible (but I need to manually clean the listener).

Is this intended behavior, or am I missing something?


问:
How to define that float is half of the number?
What would be the most efficient way to say that float value is half of integer for example 0.5, 1.5, 10.5?

First what coming on my mind is:

```<code>$is_half = (($number - floor($number)) === 0.5);
</code>```

Is there any better solutions?

答:
Due to floating point precision errors, you usually should check to see that the difference is below some low amount (but note that 0.5 is representable exactly, so it shouldn't be a problem, but it is in general with floats).

So your code is good for your specific sense, in general, you might want to do:

```<code>if (abs($number - floor($number) - $decimal) < 0.0001) {
</code>```

Where $decimal is your looking difference: 0.5.

Body:
What would be the most efficient way to say that float value is half of integer for example 0.5, 1.5, 10.5?

First what coming on my mind is:

$is_half = (($number - floor($number)) === 0.5);

Is there any better solutions?

Body:
Due to floating point precision errors, you usually should check to see that the difference is below some low amount (but note that 0.5 is representable exactly, so it shouldn't be a problem, but it is in general with floats).

So your code is good for your specific sense, in general, you might want to do:

if (abs($number - floor($number) - $decimal) < 0.0001) {

Where $decimal is your looking difference: 0.5.


问:
Android - startActivityForResult immediately triggering onActivityResult
I am launching activities from the main activity in my app using the call startActivityForResult(intent, ACTIVITY_TYPE), and they are all working but one.

This one, when called, launches the activity as desired, but in the log I can see that onActivityResult() is immediately being triggered.  The activity shows up but RESULT_CANCELED is immediately returned to onActivityResult().

I then interact with the activity, press a button which calls finish(), and onActivityResult() is not called this time (because apparently a result has already been returned).

Does this make sense to anyone?  Has anyone seen this behavior before?

答:
Android 4.4 has a small problem about waiting for the return at the end of the actvity closure
To solve this behavior it is important to set :

all activities will have the same task Affinity attribute. (TaskAffinity = "[SAME STRING]")

launchmode=singleTop,

launchIntent.SetFlags(0); // for reset default Intent flags if you launch from package manager

This solution works with all version of Android

See this for taskAffinity:
https://asyoulook.com/computers%20&%20internet/android-onactivityresult-being-called-instantly/1004072


问:
How to change the line thickness in a polar jfreechart graph?
I am trying to change the line thickness in some jfreechart graphs; in case of
XY graphs, I am using the following code:

```<code>chartPanel.getChart().getXYPlot().getRenderer().setSeriesStroke(i, new BasicStroke(2.0f));
</code>```

and it works properly. In case of polar graphs I tried the following code:

```<code>PolarPlot plot = (PolarPlot) chartPanel.getChart().getPlot();
DefaultPolarItemRenderer renderer = (DefaultPolarItemRenderer) plot.getRenderer();
renderer.setSeriesStroke(i, new BasicStroke(2.0f));
</code>```

but it does not work, the line thickness is always the same. Do you have a clue?

答:
At the end I sorted out the problem. My code was correct and the problem was not the line thickness but the rounded bullets that jfreechart puts (by default) in every point of the polar diagram. The points were very closed to each other and the bullets made the effect of a very thick line! To remove them I used the following code:</p>

```<code>renderer.setShapesVisible(false);
</code>```

Body:
I am trying to change the line thickness in some jfreechart graphs; in case of
XY graphs, I am using the following code:

chartPanel.getChart().getXYPlot().getRenderer().setSeriesStroke(i, new BasicStroke(2.0f));

and it works properly. In case of polar graphs I tried the following code:

PolarPlot plot = (PolarPlot) chartPanel.getChart().getPlot();
DefaultPolarItemRenderer renderer = (DefaultPolarItemRenderer) plot.getRenderer();
renderer.setSeriesStroke(i, new BasicStroke(2.0f));

but it does not work, the line thickness is always the same. Do you have a clue?

Body:
At the end I sorted out the problem. My code was correct and the problem was not the line thickness but the rounded bullets that jfreechart puts (by default) in every point of the polar diagram. The points were very closed to each other and the bullets made the effect of a very thick line! To remove them I used the following code:

renderer.setShapesVisible(false);


答:
You can also do it this way:

```<code>def add_lists(*args):
    s1 = sum(i[0] for i in args)
    s2 = sum(i[1] for i in args)
    return [s1,s2]

res = add_lists([1, 2],[2, 1],[3, 1])
print(res)
</code>```

Output:

```<code>[6, 4]
</code>```

Body:
I would like to write a function that calculates scalar sum of several vectors. It should take several lists as arguments eg.

def add_lists(x, y, z):
   # return sum of x, y, z

x = add_lists([1, 2],[2, 1],[3, 1])
# x returns [6, 4]

It is easy to do it for only two arguments, but how can I do it using *args if they are more than two, so that my add_lists will return [6, 4]?

Body:
You can also do it this way:

def add_lists(*args):
    s1 = sum(i[0] for i in args)
    s2 = sum(i[1] for i in args)
    return [s1,s2]

res = add_lists([1, 2],[2, 1],[3, 1])
print(res)

Output:

[6, 4]


问:
Why does spark-submit fail with "IllegalArgumentException: Missing application resource."?
When I create the jar of my Spark application and try to run it using spark-submit, I am getting the following error.

This is the command I used to run.

```<code>spark-submit --executor-memory 1g --jars s3://test-data-lab-users/spachari/test/test_2.10-1.0.jar
</code>```

This is the error i am getting. Does this mean I have not passed correct parameters in my spark-submit?

```<code>Exception in thread "main" java.lang.IllegalArgumentException: Missing application resource.
    at org.apache.spark.launcher.CommandBuilderUtils.checkArgument(CommandBuilderUtils.java:241)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitArgs(SparkSubmitCommandBuilder.java:160)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitCommand(SparkSubmitCommandBuilder.java:276)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildCommand(SparkSubmitCommandBuilder.java:151)
    at org.apache.spark.launcher.Main.main(Main.java:86)
Command exiting with ret '1'
</code>```

答:
tl;dr Remove --jars option and start over.

java.lang.IllegalArgumentException: Missing application resource.

You missed your...well...Spark application that the message refers to as "application resource".

That's more obvious when you execute spark-submit and see the different command-line options and their meanings.

```<code>./bin/spark-submit
Usage: spark-submit [options] <app jar | python file | R file> [app arguments]
</code>```

That part <app jar | python file | R file> is what you missed.

To reproduce your issue you can simply execute spark-submit with --jars options without specifying the main jar or class of a Spark application.

```<code>$ ./bin/spark-submit --jars target/spark-parent_2.11-2.3.0-SNAPSHOT-tests.jar
Exception in thread "main" java.lang.IllegalArgumentException: Missing application resource.
    at org.apache.spark.launcher.CommandBuilderUtils.checkArgument(CommandBuilderUtils.java:241)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitArgs(SparkSubmitCommandBuilder.java:160)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitCommand(SparkSubmitCommandBuilder.java:274)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildCommand(SparkSubmitCommandBuilder.java:151)
    at org.apache.spark.launcher.Main.main(Main.java:86)
</code>```

Quoting spark-submit --help, --jars is...

--jars JARS Comma-separated list of jars to include on the driver and executor classpaths.

--jars can be very helpful when a Spark application depends on additional jar files (aka dependencies), i.e. mysql-connect.jar that you cannot (or most likely don't want to) "assembly" to your uber jar.

Body:
When I create the jar of my Spark application and try to run it using spark-submit, I am getting the following error.

This is the command I used to run.

spark-submit --executor-memory 1g --jars s3://test-data-lab-users/spachari/test/test_2.10-1.0.jar

This is the error i am getting. Does this mean I have not passed correct parameters in my spark-submit?

Exception in thread "main" java.lang.IllegalArgumentException: Missing application resource.
    at org.apache.spark.launcher.CommandBuilderUtils.checkArgument(CommandBuilderUtils.java:241)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitArgs(SparkSubmitCommandBuilder.java:160)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitCommand(SparkSubmitCommandBuilder.java:276)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildCommand(SparkSubmitCommandBuilder.java:151)
    at org.apache.spark.launcher.Main.main(Main.java:86)
Command exiting with ret '1'

Body:
tl;dr Remove --jars option and start over.

java.lang.IllegalArgumentException: Missing application resource.

You missed your...well...Spark application that the message refers to as "application resource".

That's more obvious when you execute spark-submit and see the different command-line options and their meanings.

./bin/spark-submit
Usage: spark-submit [options] <app jar | python file | R file> [app arguments]

That part <app jar | python file | R file> is what you missed.

To reproduce your issue you can simply execute spark-submit with --jars options without specifying the main jar or class of a Spark application.

$ ./bin/spark-submit --jars target/spark-parent_2.11-2.3.0-SNAPSHOT-tests.jar
Exception in thread "main" java.lang.IllegalArgumentException: Missing application resource.
    at org.apache.spark.launcher.CommandBuilderUtils.checkArgument(CommandBuilderUtils.java:241)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitArgs(SparkSubmitCommandBuilder.java:160)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildSparkSubmitCommand(SparkSubmitCommandBuilder.java:274)
    at org.apache.spark.launcher.SparkSubmitCommandBuilder.buildCommand(SparkSubmitCommandBuilder.java:151)
    at org.apache.spark.launcher.Main.main(Main.java:86)

Quoting spark-submit --help, --jars is...

--jars JARS Comma-separated list of jars to include on the driver and executor classpaths.

--jars can be very helpful when a Spark application depends on additional jar files (aka dependencies), i.e. mysql-connect.jar that you cannot (or most likely don't want to) "assembly" to your uber jar.