问:
How to publish/subscribe a python “list of list” as topic in ROS
I am new to ROS and rospy, and I am not familiar with non-simple data type as topic.

I want to build a ROS node as both a subscriber and publisher: it receives a topic (a list of two float64), and uses a function (say my_function) which returns a list of lists of float64, then publish this list of list as a topic.

To do this, I built a node as following:

```<code>from pymongo import MongoClient
from myfile import my_function
import rospy
import numpy as np

pub = None
sub = None

def callback(req):
    client = MongoClient()
    db = client.block
    lon = np.float64(req.b)
    lat = np.float64(req.a)
    point_list = my_function(lon, lat, db)
    pub.publish(point_list)

def calculator():
    global sub, pub
    rospy.init_node('calculator', anonymous=True)
    pub = rospy.Publisher('output_data', list)
    # Listen
    sub = rospy.Subscriber('input_data', list, callback)
    print "Calculation finished. \n"
    ros.spin()

if __name__ == '__main__':
    try:
        calculator()
    except rospy.ROSInterruptException:
        pass
</code>```

I know clearly that list in Subscriber and Publisher is not a message data, but I cannot figure out how to fix it since it is not an integer nor list of integer.

答:
You can complicate yourself by defining a new ros Type in the msg OR use the default and easy to implement std_msgs Type, maybe will be useful to use a json module, so you serialize the data before publishing and deserialize it back on the other side after receiving...

the rest Pub/Sub , topic and handlers remain the same :)

Body:
I am new to ROS and rospy, and I am not familiar with non-simple data type as topic.

I want to build a ROS node as both a subscriber and publisher: it receives a topic (a list of two float64), and uses a function (say my_function) which returns a list of lists of float64, then publish this list of list as a topic.

To do this, I built a node as following:

from pymongo import MongoClient
from myfile import my_function
import rospy
import numpy as np

pub = None
sub = None

def callback(req):
    client = MongoClient()
    db = client.block
    lon = np.float64(req.b)
    lat = np.float64(req.a)
    point_list = my_function(lon, lat, db)
    pub.publish(point_list)

def calculator():
    global sub, pub
    rospy.init_node('calculator', anonymous=True)
    pub = rospy.Publisher('output_data', list)
    # Listen
    sub = rospy.Subscriber('input_data', list, callback)
    print "Calculation finished. \n"
    ros.spin()

if __name__ == '__main__':
    try:
        calculator()
    except rospy.ROSInterruptException:
        pass

I know clearly that list in Subscriber and Publisher is not a message data, but I cannot figure out how to fix it since it is not an integer nor list of integer.


来源: stackexchange

问:
Difference between Module and Class in Python
Can I assign value to a variable in the module? If yes, what is the difference between a class and module?

PS: I'm a Java guy (in case it helps in the way of explaining). Thanks.

答:
There are huge differences between classes and modules in Python.

Classes are blueprints that allow you to create instances with attributes and bound functionality. Classes support inheritance, metaclasses, and descriptors.

Modules can't do any of this, modules are essentially singleton instances of an internal module class, and all their globals are attributes on the module instance. You can manipulate those attributes as needed (add, remove and update), but take into account that these still form the global namespace for all code defined in that module.

From a Java perspective, classes are not all that different here. Modules can contain more than just one class however; functions and any the result of any other Python expression can be globals in a module too.

So as a general ballpark guideline:

Use classes as blueprints for objects that model your problem domain.

Use modules to collect functionality into logical units.

Then store data where it makes sense to your application. Global state goes in modules (and functions and classes are just as much global state, loaded at the start). Everything else goes into other data structures, including instances of classes.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 3.0


问:
Python format default rounding when formatting float number
I'm trying to solve some floating-point problems in my code in Python 2.7.10. When testing I've encountered a strange behaviour with the format method:

```<code>print "{}".format(0.3000000000004) # 13 decimals
</code>```

Prints: 0.3

But:

```<code>print "{}".format(0.300000000004) # 12 decimals
</code>```

Prints: 0.300000000004

Since I'm not specifying the format, why does it round the first number? Is there a default number of allowed decimal places?

答:
Since you do not specify a format, the default type coercion to string is used. So this isn't really an issue with format. Python 2 truncates to a precision of 12 characters (excluding the leading zero, if any) for float.__str__, and after truncation in this case, all trailing zeros are cleaned up:

```<code>>>> str(0.3000000000004) # unlike str(0.3000000000014) -> '0.300000000001'
'0.3'
</code>```

Adding the format_spec :f gives you the default precision of 6:

```<code>>>> '{:f}'.format(0.3000000000004)
'0.300000'
</code>```

Specify the width and precision or use repr to get a good representation:

```<code>>>> '{!r}'.format(0.3000000000004)
'0.3000000000004'
</code>```

The behavior is different in Python 3 though:

```<code>>>> str(0.3000000000004)
'0.3000000000004'
</code>```

The formatting of floats is handled by just one function float_repr in Python 3 (it does not have a special float_str function):

```<code>(reprfunc)float_repr,                       /* tp_repr */
...
(reprfunc)float_repr,                        /* tp_str */
</code>```

whereas Python2.7 defines a separate handler float_str and float_repr for __str__ and __repr__ respectively:

```<code>(reprfunc)float_repr,                       /* tp_repr */
...
(reprfunc)float_str,                        /* tp_str */
</code>```

The deciding variable here which I think is the reason for the precision loss beyond 12d.p. is PyFloat_STR_PRECISION (defined in Python 2):

```<code>#define PyFloat_STR_PRECISION 12
</code>```

It reverses to a truncation for floats taking more than 12 characters in the default conversion.

Body:
I'm trying to solve some floating-point problems in my code in Python 2.7.10. When testing I've encountered a strange behaviour with the format method:

print "{}".format(0.3000000000004) # 13 decimals

Prints: 0.3

But:

print "{}".format(0.300000000004) # 12 decimals

Prints: 0.300000000004

Since I'm not specifying the format, why does it round the first number? Is there a default number of allowed decimal places?

Body:
Since you do not specify a format, the default type coercion to string is used. So this isn't really an issue with format. Python 2 truncates to a precision of 12 characters (excluding the leading zero, if any) for float.__str__, and after truncation in this case, all trailing zeros are cleaned up:

>>> str(0.3000000000004) # unlike str(0.3000000000014) -> '0.300000000001'
'0.3'

Adding the format_spec :f gives you the default precision of 6:

>>> '{:f}'.format(0.3000000000004)
'0.300000'

Specify the width and precision or use repr to get a good representation:

>>> '{!r}'.format(0.3000000000004)
'0.3000000000004'

The behavior is different in Python 3 though:

>>> str(0.3000000000004)
'0.3000000000004'

The formatting of floats is handled by just one function float_repr in Python 3 (it does not have a special float_str function):

(reprfunc)float_repr,                       /* tp_repr */
...
(reprfunc)float_repr,                        /* tp_str */

whereas Python2.7 defines a separate handler float_str and float_repr for __str__ and __repr__ respectively:

(reprfunc)float_repr,                       /* tp_repr */
...
(reprfunc)float_str,                        /* tp_str */

The deciding variable here which I think is the reason for the precision loss beyond 12d.p. is PyFloat_STR_PRECISION (defined in Python 2):

#define PyFloat_STR_PRECISION 12

It reverses to a truncation for floats taking more than 12 characters in the default conversion.


问:
dismiss progress dialog in asyntask
I have search box in my page,I added onTextChangeListener() too. When I am add/removing letters/characters from search box ,every time I am calling same asyntask.Suppose 3 times called then 3 times progress dialog instances getting created and need to dismissed.Here progress dialog is not getting dismissed.

```<code>search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchresult = search.getText().toString();

                if (count == 0) {
                    pageCount = 1;
                    productsList.clear();
                    mCount = 0;
                    if (isTextWatcherVisible) {
//                        GetProductsTask();
                        new GetProductsTask().execute();
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
class GetProductsTask extends AsyncTask<Void, Void, Void> {

    final String pcid = Preferences.getString(Preferences.PrefType.enum_company_id, getActivity());

    String url1 = getContext().getString(R.string.url) + "products?company_id=" + pcid + "&page=" + pageCount;

    public GetProductsTask() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Loading...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
    }
    protected void onPreExecute() {
        super.onPreExecute();
//                progressDialog = new ProgressDialog(getActivity());
//                progressDialog.setMessage("Loading...");
//                progressDialog.setIndeterminate(false);
//                progressDialog.setCancelable(false);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {
      // somthig here
    }
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ProductslistAdapter adapter = new ProductslistAdapter(getActivity(), R.layout.vendor_products_item, productsList, searchresult);

        list.setAdapter(adapter);
        int count = pageCount - 1;
        list.setSelection(count * 24);
        if (progressDialog.isShowing())
            progressDialog.dismiss();

    }
</code>```

答:
just create one method like:

```<code>private static ProgressDialog progressDialog;

public static void showProgressDialog(Context context) {

        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("Loading...");
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

}
</code>```

call showProgressDialog method into onPreExecute().

To dismiss dialog:

```<code>if(progressdailog.isShowing()){
    progressdialog.dismiss();
}
</code>```

Title: dismiss progress dialog in asyntask

Body:
I have search box in my page,I added onTextChangeListener() too. When I am add/removing letters/characters from search box ,every time I am calling same asyntask.Suppose 3 times called then 3 times progress dialog instances getting created and need to dismissed.Here progress dialog is not getting dismissed.

search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchresult = search.getText().toString();

                if (count == 0) {
                    pageCount = 1;
                    productsList.clear();
                    mCount = 0;
                    if (isTextWatcherVisible) {
//                        GetProductsTask();
                        new GetProductsTask().execute();
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
class GetProductsTask extends AsyncTask<Void, Void, Void> {

    final String pcid = Preferences.getString(Preferences.PrefType.enum_company_id, getActivity());

    String url1 = getContext().getString(R.string.url) + "products?company_id=" + pcid + "&page=" + pageCount;

    public GetProductsTask() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Loading...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
    }
    protected void onPreExecute() {
        super.onPreExecute();
//                progressDialog = new ProgressDialog(getActivity());
//                progressDialog.setMessage("Loading...");
//                progressDialog.setIndeterminate(false);
//                progressDialog.setCancelable(false);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {
      // somthig here
    }
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ProductslistAdapter adapter = new ProductslistAdapter(getActivity(), R.layout.vendor_products_item, productsList, searchresult);

        list.setAdapter(adapter);
        int count = pageCount - 1;
        list.setSelection(count * 24);
        if (progressDialog.isShowing())
            progressDialog.dismiss();

    }

Body:
just create one method like:

private static ProgressDialog progressDialog;

public static void showProgressDialog(Context context) {

        if (progressDialog == null) {
            progressDialog = new ProgressDialog(getActivity());
            progressDialog.setMessage("Loading...");
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(false);
            progressDialog.show();
        }

}

call showProgressDialog method into onPreExecute().

To dismiss dialog:

if(progressdailog.isShowing()){
    progressdialog.dismiss();
}


问:
React router only works with / path

Why work only root path and when i get to localhost:8090/about it
  say's. Can not get localhost:8090/about

```<code>import React,{Component} from "react"
    import {BrowserRouter as Router,Route} from "react-router-dom"

var About =()=>{
    return <div>About us{}</div>
}

class App extends Component{
render(){
return (
    <Router>
 <div>
      <Route path ="/" component={About}/>
      <Route path ='/about'component={About}/>
</div>
    </Router>
);
}
}
export default App;
</code>```

main.js entry point(webpack)

```<code>import React from "react"
import ReactDOM from "react-dom"
import App from "./components/App.jsx"

ReactDOM.render(

       <App />,
      document.getElementById('table')
);
</code>```

I'am use "react-router-dom": "^4.0.0-beta.7"

答:
Add a Link to your component, to change the route, Write it like this:

```<code>import {BrowserRouter as Router,Route, Link} from "react-router-dom"

class App extends Component{
  render(){
    return (
      <Router>
        <div>
           <Link to='/about'>About </Link>
           <Route path ="/" component={About}/>
           <Route path ='/about'component={About}/>
        </div>
      </Router>
    );
  }
}
export default App;
</code>```

Title: React router only works with / path

Body:
Why work only root path and when i get to localhost:8090/about it
  say's. Can not get localhost:8090/about

import React,{Component} from "react"
    import {BrowserRouter as Router,Route} from "react-router-dom"

var About =()=>{
    return
About us{}

}

class App extends Component{
render(){
return (
    <Router>

      <Route path ="/" component={About}/>
      <Route path ='/about'component={About}/>

    </Router>
);
}
}
export default App;

main.js entry point(webpack)

import React from "react"
import ReactDOM from "react-dom"
import App from "./components/App.jsx"

ReactDOM.render(

       <App />,
      document.getElementById('table')
);

I'am use "react-router-dom": "^4.0.0-beta.7"

Body:
Add a Link to your component, to change the route, Write it like this:

import {BrowserRouter as Router,Route, Link} from "react-router-dom"

class App extends Component{
  render(){
    return (
      <Router>
        <div>
           <Link to='/about'>About </Link>
           <Route path ="/" component={About}/>
           <Route path ='/about'component={About}/>
        </div>
      </Router>
    );
  }
}
export default App;


问:
jQuery 101 - Change CSS not working with advanced selectors
This is across IE and Firefox.

I have an unordered list of 5 items within li tags.

```<code><script type="text/javascript">
$(function() //when doc is ready
    {
                $("li:first").css('color', 'red');

    });

</script>
</code>```

That does absolutely nothing, however if I leave out the :first part, it makes all li's red, unsure of why since I'm following a tutorial.

Here is the html:

```<code><div id="container">
<script type="text/javascript"><!--
$(function() //when doc is ready
{
    $("li:first").css('color', 'red');
});//--></script>

<div id="leftcontent">
<center><img src="http://www.dmu.com/5f/images/thiszis.png"></center>
<div id="hoastdears">
<ul>

<li>item1</li>
<li>item2</li>
<li>item3</li>
<li>item4</li>
<li>item5</li>
</ul>
</code>```

With

in the header.

答:
Specify a context for your li:first selector. Something like:

```<code>$("li:first", "ul:first").css("color", "red");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
This is across IE and Firefox.

I have an unordered list of 5 items within li tags.

That does absolutely nothing, however if I leave out the :first part, it makes all li's red, unsure of why since I'm following a tutorial.

Here is the html:

item1

item2

item3

item4

item5

With

in the header.

Body:
Specify a context for your li:first selector. Something like:

$("li:first", "ul:first").css("color", "red");


问:
How to solve the 'Unable to find Asm for stackmap generation' error on startup of STS?
I am trying to use the Spring Tool Suite 3.8.3 on Ubuntu 16.04. Upon startup I get this error:

An internal error occured during: "Initializing Java Tooling"

with the detailed message:

An internal error occurred during: "Initializing Java Tooling". Unable
  to find Asm for stackmap generation (Looking for
  'aj.org.objectweb.asm.ClassReader'). Stackmap generation for woven
  code is required to avoid verify errors on a Java 1.7 or higher
  runtime when weaving type org.eclipse.jdt.core.search.SearchPattern
  when weaving classes  when weaving

I have to admit that I have no idea what I should do here and I failed to find any pointers online. Any advice or hint is welcome.

答:
I think you have installed Java 9 on your system. That's why you are facing compatibility issue and getting the stated errors. I therefore suggest you to degrade your java version to 8 for which it will work well and you wont be facing any error issue in that.
You can install java8 from this link!</p>


问:
Description linebreaks on YouTube v3 API
I've been playing around with the YouTube API but when I try to get the video description, it appears as one long string with no line breaks. Is there a method to get line breaks?

The API does not have any documentation to explain this matter.

答:
Please use the PHP_EOL, like so:</p>

```<code>$desp='Cette vidéo et trouvée sur: http://localhost/ '.PHP_EOL;
$desp.='Pour plus d\'infos visitez: http://localhost/123 '.PHP_EOL;
$desp.='CopyRight to: http://localhost/789';
$snippet->setDescription($desp);
</code>```

Body:
Please use the PHP_EOL, like so:

$desp='Cette vidéo et trouvée sur: http://localhost/ '.PHP_EOL;
$desp.='Pour plus d\'infos visitez: http://localhost/123 '.PHP_EOL;
$desp.='CopyRight to: http://localhost/789';
$snippet->setDescription($desp);


问:
monitor and increase android performance of android applications
can anyone advice me some tools that can help me monitor the performance of my application ?

and tips that also can help me increasing the memory and gui usage of my application ?

some users complain that the application is too slow and I can not reproduce this issue on my device.

答:
There are many ways to enhance performance but we should apply the following:

Use RecyclerView in place of ListView

Use RetroFit to fetch Data

Don't forget to Destroy objects who don't have any uses in app

Instead of using library. I'll recommend you to use only classes that u wish to use. As you know to adding Library into our project, sometimes they make heavy app and also increases our app size.

Always use those library that you want to use ....
for eg: when we add firebase library. google-play-services are automatically plugged in so there is no need to define that dependency

Keep your layout file smooth and lightweight.

To load images, you can use Glide library... It gives smoothness to app

Note: For more info, you can read this official tips from android=>  https://developer.android.com/training/articles/perf-tips.html


问:
How to properly initialize interface in Activity?
I have this interface:

```<code>public interface SomeInterface {

    void doSomething();
}
</code>```

I am trying to initialize it in Main activity and I am trying to "send it" to second activity:

```<code>private SomeInterface someInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    someInterface = (SomeInterface) this;
    someInterface.doSomething();
}
</code>```

I implemented interface into second activity.

```<code>public class SecondActivity extends Activity implements SomeInterface  {

    @Override
    public void doSomething() {

    }
}
</code>```

But this is not working, I am getting follwing error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{package.name/package.name.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to package.name.AppInterface
</code>```

What I am doing wrong? Thank you in advance.

答:
You need to implement the SomeInterface in your Activity class

someInterface = (SomeInterface) this;

here this refer to your Activity not the Interface as you haven't implemented it.
Hence ClassCastException

Body:
I have this interface:

public interface SomeInterface {

    void doSomething();
}

I am trying to initialize it in Main activity and I am trying to "send it" to second activity:

private SomeInterface someInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    someInterface = (SomeInterface) this;
    someInterface.doSomething();
}

I implemented interface into second activity.

public class SecondActivity extends Activity implements SomeInterface  {

    @Override
    public void doSomething() {

    }
}

But this is not working, I am getting follwing error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{package.name/package.name.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to package.name.AppInterface

What I am doing wrong? Thank you in advance.


问:
Dockerfile, Nodejs, mongodb import
I am doing my Dockerfile, and when I want to import my bbd.json inside mongodb I have an error.
I have searched about this error, and I found this : add --host localhost or add --host=localhost (or 127.0.0.0) I have tried both but none of them is working.
Here my Dockerfile:

```<code>FROM node:argon

RUN apt-get update
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
#RUN echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN apt-get update
RUN apt-get -y install vim-tiny
#RUN vim /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN apt-get update
RUN apt-get install -y mongodb-org=3.2.10 mongodb-org-server=3.2.10 mongodb-org-shell=3.2.10 mongodb-org-mongos=3.2.10 mongodb-org-tools=3.2.10
RUN npm install mongoose
RUN npm install body-parser

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app
RUN npm install

COPY . /usr/src/app

RUN mongod&
RUN mkdir /usr/test
RUN mkdir -p /data/db
RUN mongod --dbpath /usr/test --fork --syslog
RUN mongoimport --db bdd --collection users --file bdd.json
RUN cp /usr/test/* .

EXPOSE 3000
CMD ["npm", "start"]
</code>```

And here the error :

```<code>Step 17/19 : RUN mongoimport --host localhost --db apirest --collection users --file bdd.json
 ---> Running in 028f35e6e2ab
2017-04-03T11:40:57.406+0000    [........................] apirest.users        0B/23.9KB (0.0%)
2017-04-03T11:40:57.910+0000    Failed: error connecting to db server: no reachable servers0.0%)
2017-04-03T11:40:57.911+0000    imported 0 documents
The command '/bin/sh -c mongoimport --host localhost --db apirest --collection users --file bdd.json' returned a non-zero code: 1
</code>```

Have you any ideas ? Thank you.

答:
This isn't working because, at build time, the mongod process is not running.

I won't advise you on how to get it working because your approach, building both mongod and node processes into the same container, goes against the standard docker philosophy: you should built your app with one service per container i.e.  a separate service for mongod.

Title: Dockerfile, Nodejs, mongodb import

Body:
I am doing my Dockerfile, and when I want to import my bbd.json inside mongodb I have an error.
I have searched about this error, and I found this : add --host localhost or add --host=localhost (or 127.0.0.0) I have tried both but none of them is working.
Here my Dockerfile:

FROM node:argon

RUN apt-get update
RUN apt-key adv --keyserver hkp://keyserver.ubuntu.com:80 --recv EA312927
#RUN echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN apt-get update
RUN apt-get -y install vim-tiny
#RUN vim /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN echo "deb http://repo.mongodb.org/apt/ubuntu xenial/mongodb-org/3.2 multiverse" | tee /etc/apt/sources.list.d/mongodb-org-3.2.list
RUN apt-get update
RUN apt-get install -y mongodb-org=3.2.10 mongodb-org-server=3.2.10 mongodb-org-shell=3.2.10 mongodb-org-mongos=3.2.10 mongodb-org-tools=3.2.10
RUN npm install mongoose
RUN npm install body-parser

RUN mkdir -p /usr/src/app
WORKDIR /usr/src/app
COPY package.json /usr/src/app
RUN npm install

COPY . /usr/src/app

RUN mongod&
RUN mkdir /usr/test
RUN mkdir -p /data/db
RUN mongod --dbpath /usr/test --fork --syslog
RUN mongoimport --db bdd --collection users --file bdd.json
RUN cp /usr/test/* .

EXPOSE 3000
CMD ["npm", "start"]

And here the error :

Step 17/19 : RUN mongoimport --host localhost --db apirest --collection users --file bdd.json
 ---> Running in 028f35e6e2ab
2017-04-03T11:40:57.406+0000    [........................] apirest.users        0B/23.9KB (0.0%)
2017-04-03T11:40:57.910+0000    Failed: error connecting to db server: no reachable servers0.0%)
2017-04-03T11:40:57.911+0000    imported 0 documents
The command '/bin/sh -c mongoimport --host localhost --db apirest --collection users --file bdd.json' returned a non-zero code: 1

Have you any ideas ? Thank you.


问:
print the diagonal of a matrix
I used the awk command to print the diagonal

```<code>awk '{ for (i=1; i<=NF; i++) if (NR >= 1 && NR == i) print $(i - 0) }' matrix
</code>```

and the output was like :

```<code>1
2
3
4
</code>```

how can it be displayed like :

```<code>1
 2
  3
   4
</code>```

matrix :

```<code>1 0 3 5
0 2 6 7
3 0 3 5
8 7 2 4
</code>```

答:
with some shortcut (i put a output as string (%s) to be more exhaustif but (%d) is enough for $i printing and without replacing content of each element</p>

```<code>awk '{ printf( "%" ( i++ * 2 ) "s%s\n", "", $i)}' YourFile
</code>```

Title: print the diagonal of a matrix

Body:
I used the awk command to print the diagonal

awk '{ for (i=1; i<=NF; i++) if (NR >= 1 && NR == i) print $(i - 0) }' matrix

and the output was like :

1
2
3
4

how can it be displayed like :

1
 2
  3
   4

matrix :

1 0 3 5
0 2 6 7
3 0 3 5
8 7 2 4

Body:
with some shortcut (i put a output as string (%s) to be more exhaustif but (%d) is enough for $i printing and without replacing content of each element

awk '{ printf( "%" ( i++ * 2 ) "s%s\n", "", $i)}' YourFile


问:
C# Ghostscript Wrapper
Has anyone encountered a nice wrapper for GhostScript in C#.
My specific use is to take postscript and turn it into a pdf</p>

答:
Matthew Ephraim has created a pretty simple C# wrapper called GhostScriptSharp that uses P/Invoke to access the unmanaged Ghostscript DLL in your C# application:

http://mattephraim.com/blog/2009/01/06/a-simple-c-wrapper-for-ghostscript/

Title: C# Ghostscript Wrapper


问:
Merging and appending data on SPSS
I am collecting data on cspro and export it to spss and I want append new data on to the old data, so I won't have the same files that I worked on on my last data.

Is there any syntax to sort that out?

答:
If you are looking for a way to add up two SPSS files (after exporting your new data to a new file), the syntax is:

```<code>add files
   /file="path1/filename1.sav"
   /file="path2/filename2.sav".
</code>```

you may have trouble if the same string variables have different widths in the two files. If so you need to choose the appropriate width and force it on all relevant variables before adding the files:

```<code>get file="path1/filename1.sav".
alter type stringVar1 (a50) stringVar2 (a150).
dataset name fil1.
get file="path2/filename2.sav".
alter type stringVar1 (a50) stringVar2 (a150).
dataset name fil2.
add files /file=fil1 /file=fil2.
execute.
</code>```

Title: Merging and appending data on SPSS

Body:
If you are looking for a way to add up two SPSS files (after exporting your new data to a new file), the syntax is:

add files
   /file="path1/filename1.sav"
   /file="path2/filename2.sav".

you may have trouble if the same string variables have different widths in the two files. If so you need to choose the appropriate width and force it on all relevant variables before adding the files:

get file="path1/filename1.sav".
alter type stringVar1 (a50) stringVar2 (a150).
dataset name fil1.
get file="path2/filename2.sav".
alter type stringVar1 (a50) stringVar2 (a150).
dataset name fil2.
add files /file=fil1 /file=fil2.
execute.


问:
GKE randomly dropping connections
We're running a Kubernetes cluster on GKE, with an NGINX ingress controller (so that we can accept WS connections), and a network load balancer connected to it through a service to make it accessible from the internet.

Everything works perfectly fine most of the time. But we get "connection refused" at seemingly random intervals.

Looking at the logs, it seems as if the dropped requests never hit NGINX (NGINX doesn't log anything at all for these requests). We've tried recreating the external load balancer, the service and so on but without success. Not sure where to go from here or where the issue lies.

Does anyone recognise the problem? Or have any potential solution? Help greatly appreciated!

答: Have you tried creating a new cluster? Strange things might happen sometimes in the world of GKE</p>

Title: GKE randomly dropping connections


问:
Can ThreadLocal be used as Key in HashMap?
Can ThreadLocal be used as Key in HashMap? </p>

<p>If so, how does it work and is it generally a bad idea? What should I look out for and be aware of? </p>

答:
As Jaroslaw Pawlak commented, since ThreadLocal doesn't implement hashCode() and equals() it is not suitable for the key in HashMap, at least if you expect it to be well behaved.

Even if it did, it would be useless. Considering the use-case of ThreadLocal, it would be far clearer to use the contained object as the key.

Having a map with one ThreadLocal (with thread specific contents) mapping just ends up with having the internal map of ThreadLocal (the one that maps the thread to the value) being used for the actual mappings.

Not to mention that ThreadLocal instances are somewhat recommended against. The common use cases they have are solved by introducing "native" threadlocal classes, such as java.util.concurrent.ThreadSafeRandom.

Body:
Can ThreadLocal be used as Key in HashMap?

If so, how does it work and is it generally a bad idea? What should I look out for and be aware of?


答:
Use this where you want to dismiss dialog.</p>

```<code>ProgressDialog pDialog = new ProgressDialog(this);
pDialog.dismiss();
</code>```

Title: dismiss progress dialog in asyntask

Body:
Use this where you want to dismiss dialog.

ProgressDialog pDialog = new ProgressDialog(this);
pDialog.dismiss();


问:
How to come up with this percent error with Rectangular integration method
I'm reviewing some numerical methods for integration. I came across Rectangular integration method (i.e. Euler's method). According to the book I'm reading, the actual algorithm is

The code is self-explanatory. The author provides this example dxdt=cos(t) with an initial value x(0)=0. The analytical solution is x=sin(t). We can compute the error at t=1 and indeed the author provides it in the following table:

The problem is that in my following code, the error is 9.1% but in the preceding table, the error actually is 2.6. Did I make a mistake?

```<code>#include <iostream>
#include <cmath>

int main()
{
    double x(0.0), dxdt, t(0.0), T(0.1), stopTime(1.0);

    for ( ; t <= stopTime; t += T ){
        dxdt = cos(t);
          x += dxdt*T;

          if ( t > 0.9 )
            std::cout << "Time: " << t << "  Error: " << fabs( (x - sin(t)) /sin(t) )*100.0 <<  std::endl;
    }

    return 0;
}
</code>```

答:
You need to take into account that while x is updated to an approximation of x(t+T), the loop variable t will only be incremented at the very end of the loop, so retains it value t during the output. This time mismatch introduces an additional relative error of abs(sin(t+T)/sin(t)-1) which for t=1, T=0.1 is about 5.91 %.

You should also make the loop stable under rounding errors in the t incrementation, either by computing the exact number of loops or by choosing bounds in the inequality that are in-between the steps as in

```<code>while ( t < stopTime-0.5*T ){
    dxdt = cos(t);
      x += dxdt*T;
      t += T;

    if ( t > stopTime -2.5*T )
        std::cout << "Time: " << t << "  Error: " << fabs( (x - sin(t)) /sin(t) )*100.0 <<  std::endl;

}
</code>```

Body:
I'm reviewing some numerical methods for integration. I came across Rectangular integration method (i.e. Euler's method). According to the book I'm reading, the actual algorithm is

The code is self-explanatory. The author provides this example dxdt=cos(t) with an initial value x(0)=0. The analytical solution is x=sin(t). We can compute the error at t=1 and indeed the author provides it in the following table:

The problem is that in my following code, the error is 9.1% but in the preceding table, the error actually is 2.6. Did I make a mistake?

#include <iostream>
#include <cmath>

int main()
{
    double x(0.0), dxdt, t(0.0), T(0.1), stopTime(1.0);

    for ( ; t <= stopTime; t += T ){
        dxdt = cos(t);
          x += dxdt*T;

          if ( t > 0.9 )
            std::cout << "Time: " << t << "  Error: " << fabs( (x - sin(t)) /sin(t) )*100.0 <<  std::endl;
    }

    return 0;
}

Body:
You need to take into account that while x is updated to an approximation of x(t+T), the loop variable t will only be incremented at the very end of the loop, so retains it value t during the output. This time mismatch introduces an additional relative error of abs(sin(t+T)/sin(t)-1) which for t=1, T=0.1 is about 5.91 %.

You should also make the loop stable under rounding errors in the t incrementation, either by computing the exact number of loops or by choosing bounds in the inequality that are in-between the steps as in

while ( t < stopTime-0.5*T ){
    dxdt = cos(t);
      x += dxdt*T;
      t += T;

    if ( t > stopTime -2.5*T )
        std::cout << "Time: " << t << "  Error: " << fabs( (x - sin(t)) /sin(t) )*100.0 <<  std::endl;

}


问:
Query to retrive rows with words starting and ending with same character in sql server
I need to write a SQL Server query to filter the rows with sentences containing first and last character of the sentence being same like

Thanks in advance.

答:
```<code>Declare @Searchstring Varchar(2)='b'--Search charecter
;with cte1(Id, Searchstring)
As
(
SELECT 1,'EventName'                                    Union All
SELECT 2,'US colonies declare independence'             Union All
SELECT 3,'Daily Mail launched'                          Union All
SELECT 4,'India gains independence'                     Union All
SELECT 5,'DNA helix unravelled'                         Union All
SELECT 6,'Britain explodes first H bomb'                Union All
SELECT 7,'Charles de Gaulle established Fifth Republic' Union All
SELECT 8,'Harrow & WieldStone rail crash'
)
SELECT Id
    ,Searchstring
FROM cte1
WHERE CHARINDEX(@Searchstring, RIGHT(Searchstring, 1)) > 0
    AND CHARINDEX(@Searchstring, LEFT(Searchstring, 1)) > 0
</code>```


问:
SQL Search Query
I'm currently working on a query to search a specific table.  The requirements say that I need to grab all records where any of a group of fields are like the input value.  As such I have a query that looks similar to

```<code>SELECT * FROM MyTable
WHERE Col1 like @input
    or Col2 like @input
    or Col3 like @input
</code>```

There could be any number of columns in the where clause.  One particular customer is going to have 50 columns. As such, this where clause is going to get fairly expensive.

Is there another syntax or method that can be used so that I could say "does the input value exist in any of x columns?"

Would you write the query differently?

答:
Depending on which and where wildcards are allowed these queries could be expensive indeed, because the optimizer will have trouble using indexes on many of them to speed them up.

If you are running this on MS SQL Server you might consider using the Fulltext searching features and the CONTAINS keyword to implement this.

```<code>SELECT *
FROM MyTable
WHERE CONTAINS
((col1,col2,col3) ,@input)
</code>```

Or to search all text-indexed columns

```<code>SELECT *
FROM MyTable
WHERE CONTAINS
(* ,@input)
</code>```

Title: SQL Search Query

Body:
I'm currently working on a query to search a specific table.  The requirements say that I need to grab all records where any of a group of fields are like the input value.  As such I have a query that looks similar to

SELECT * FROM MyTable
WHERE Col1 like @input
    or Col2 like @input
    or Col3 like @input

There could be any number of columns in the where clause.  One particular customer is going to have 50 columns. As such, this where clause is going to get fairly expensive.

Is there another syntax or method that can be used so that I could say "does the input value exist in any of x columns?"

Would you write the query differently?

Body:
Depending on which and where wildcards are allowed these queries could be expensive indeed, because the optimizer will have trouble using indexes on many of them to speed them up.

If you are running this on MS SQL Server you might consider using the Fulltext searching features and the CONTAINS keyword to implement this.

SELECT *
FROM MyTable
WHERE CONTAINS
((col1,col2,col3) ,@input)

Or to search all text-indexed columns

SELECT *
FROM MyTable
WHERE CONTAINS
(* ,@input)


答:
You can use ThreadLocal as a HashMap key like any other object. Whether it has any meaning is a different topic.

Basically you can have problems if you use a mutable object as a key for things like HashMap, HashSet and so on, because those classes usually use hashCode() (hence the name) to put stuff in buckets and retrieve it. So if you use a mutable object as a key, then change the object (in a way the hashCode changes) and then try to retrieve the entry by key, you will not find the entry anymore as the map will look in the wrong bucket for the entry.

In the case of ThreadLocal this would not be a problem, as it does not override equals() and hashCode() and thus the hashCode() will not change if you change the object, so you could safely use the ThreadLocal as key.

Title: Can ThreadLocal be used as Key in HashMap?


问:
Count where value is 1
I got this SELECT. And I want to count (or sum?) Yellow and Red card of players (Count Yellow cards only where YellowCard = 1, and Count Red cards only where RedCard = 1).. This SELECT does not work correctly. It count card even if there are 0 or NULL.. How can i correct it? </p>

```<code>SELECT Firstname, Lastname, COUNT(YellowCard) AS Yellow, COUNT(RedCard) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC
</code>```

答:
You can't do that because in SQL that will start from group & where clause, so your alias doesn't exist yet.

you have to use SQL subquery as this tutorial : http://www.dofactory.com/sql/subquery

That would work if u try :
SELECT *
FROM PlayerMatch Inner join...
WHERE YellowCard in (SELECT * FROM yourTable WHERE YellowCard = 1)
AND RedCard in (SELECT * FROM yourTable WHERE RedCard = 1)...

Title: Count where value is 1

Body:
I got this SELECT. And I want to count (or sum?) Yellow and Red card of players (Count Yellow cards only where YellowCard = 1, and Count Red cards only where RedCard = 1).. This SELECT does not work correctly. It count card even if there are 0 or NULL.. How can i correct it?

SELECT Firstname, Lastname, COUNT(YellowCard) AS Yellow, COUNT(RedCard) AS Red, Team.Name
FROM PlayerMatch
Inner join Player On PlayerMatch.PlayerId = Player.PlayerId
INNER JOIN Team ON Player.TeamId = Team.TeamId
INNER JOIN Match ON PlayerMatch.MatchId = Match.MatchId
WHERE(YellowCard = 1 OR RedCard = 1)
GROUP BY Lastname, Firstname, Name
ORDER BY Yellow DESC


问:
Extending Prototype, Inheritance, and Super
Consider the following code

```<code>const A = class {
    constructor(...args) {
        A.prototype.constructor.apply(this, args);
    }
};

A.prototype.constructor = function(name) {
    this.name = name;
};

A.prototype.print = function() {
    console.log(this.name);
};

const B = class extends A {};

B.prototype.print = function() {
    super.print();
    console.log('In B!');
};
</code>```

The line of super.print() in B.prototype.print throws a Syntax error of 'super' keyword unexpected here. Why?

Why can I not call the class' super like any other language? What is the correct way of doing this?

答:
In JavaScript, to call the base class' implementation, you call it explicitly by name, i.e.:</p>

```<code>B.prototype.print = function() {
    A.prototype.print.call(this);
    console.log('In B!');
};
</code>```

Body:
Consider the following code

const A = class {
    constructor(...args) {
        A.prototype.constructor.apply(this, args);
    }
};

A.prototype.constructor = function(name) {
    this.name = name;
};

A.prototype.print = function() {
    console.log(this.name);
};

const B = class extends A {};

B.prototype.print = function() {
    super.print();
    console.log('In B!');
};

The line of super.print() in B.prototype.print throws a Syntax error of 'super' keyword unexpected here. Why?

Why can I not call the class' super like any other language? What is the correct way of doing this?

Body:
In JavaScript, to call the base class' implementation, you call it explicitly by name, i.e.:

B.prototype.print = function() {
    A.prototype.print.call(this);
    console.log('In B!');
};


问:
Payemnt Method in Woocommerce how to get meta of this method?
I have added EVERTEC as woocommerce Payment Method https://www.evertecinc.com

As you can see here what I have set as Evertec Username & Evertec Password I want to get Username and Password on Checkout Page how can I get their value and set it on Checkout Page?

答:
You may need to use get_option function to get the details. Place the key as parameter to get_option.

Hope it will work for you.


问:
Storing long text in Datastore
Is Datastore suitable to store really long text, e.g. profile descriptions and articles?

If not, what's the Google Cloud alternative?

If yes, what would be the ideal way to store it in order to maintain formatting such as linebreaks and markdown supported keywords? Simply store as string or convert to byte? And should I be worried about dirty user input?

I need it for a Go project (I don't think language is relevant, but maybe Go have some useful features for this)

答:
Yes, it's suitable if you're OK with certain limitations.

These limitations are:

the overall entity size (properties + indices) must not exceed 1 MB (this should be OK for profiles and most articles)

texts longer than a certain limit (currently 1500 bytes) cannot be indexed, so the entity may store a longer string, but you won't be able to search in it / include it in query filters; don't forget to tag these fields with "noindex"

As for the type, you may simply use string, e.g.:

```<code>type Post struct {
    UserID  int64  `datastore:"uid"`
    Content string `datastore:"content,noindex"`
}
</code>```

string types preserve all formatting, including newlines, HTML, markup and whatever formatting.

"Dirty user input?" That's the issue of rendering / presenting the data. The datastore will not try to interpret it or attempt to perform any action based on its content, nor will transform it. So from the Datastore point of view, you have nothing to worry about (you don't create text GQLs by appending text ever, right?!).

Also note that if you're going to store large texts in your entities, those large texts will be fetched whenever you load / query such entities, and you also must send it when you modify and (re)save such an entity.

Tip #1: Use projection queries if you don't need the whole texts in certain queries to avoid "big" data movement (and so to ultimately speed up queries).

Tip #2: To "ease" the burden of not being able to index large texts, you may add duplicate properties like a short summary or title of the large text, because string values shorter than 1500 bytes can be indexed.

Tip #3: If you want to go over the 1 MB entity size limit, or you just want to generally decrease your datastore size usage, you may opt to store large texts compressed inside entities. Since they are long, you can't search / filter them anyway, but they are very well compressed (often below 40% of the original). So if you have many long texts, you can shrink your datastore size to like 1 third just by storing all texts compressed. Of course this will add to the entity save / load time (as you have to compress / decompress the texts), but often it is still worth it.

Title: Storing long text in Datastore

Body:
Yes, it's suitable if you're OK with certain limitations.

These limitations are:

the overall entity size (properties + indices) must not exceed 1 MB (this should be OK for profiles and most articles)

texts longer than a certain limit (currently 1500 bytes) cannot be indexed, so the entity may store a longer string, but you won't be able to search in it / include it in query filters; don't forget to tag these fields with "noindex"

As for the type, you may simply use string, e.g.:

type Post struct {
    UserID  int64  `datastore:"uid"`
    Content string `datastore:"content,noindex"`
}

string types preserve all formatting, including newlines, HTML, markup and whatever formatting.

"Dirty user input?" That's the issue of rendering / presenting the data. The datastore will not try to interpret it or attempt to perform any action based on its content, nor will transform it. So from the Datastore point of view, you have nothing to worry about (you don't create text GQLs by appending text ever, right?!).

Also note that if you're going to store large texts in your entities, those large texts will be fetched whenever you load / query such entities, and you also must send it when you modify and (re)save such an entity.

Tip #1: Use projection queries if you don't need the whole texts in certain queries to avoid "big" data movement (and so to ultimately speed up queries).

Tip #2: To "ease" the burden of not being able to index large texts, you may add duplicate properties like a short summary or title of the large text, because string values shorter than 1500 bytes can be indexed.

Tip #3: If you want to go over the 1 MB entity size limit, or you just want to generally decrease your datastore size usage, you may opt to store large texts compressed inside entities. Since they are long, you can't search / filter them anyway, but they are very well compressed (often below 40% of the original). So if you have many long texts, you can shrink your datastore size to like 1 third just by storing all texts compressed. Of course this will add to the entity save / load time (as you have to compress / decompress the texts), but often it is still worth it.


问:
onclick in php echo with error invalid unexpected token
I'm trying to add the onclick funtion when user checked the check box, and then the total price will be shown.

All the information including price is retrieve from database (no problem with retrieving data, the data display correctly).

Here is how's the code looks like.

//calculate price
function total() {
  var cal = document.getElementsByName('event');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
}
var checks = document.getElementsByName(event);
for (var i = 0; i < checks.length; i++) checks[i].onclick = total;```
<pre class="snippet-code-html lang-html prettyprint-override"><code><form id="bookingForm" action="javascript:alert('form submitted');" method="get">
  <section id="selectEvent">
   <h2>Select Events</h2>
    <div class ="item">
    <span class="chosen">
   event1 <input type= checkbox name= event data-price = "1" value=eventId1/>
    event2 <input type= checkbox name= event data-price = "2" value=eventId2/>
   </span>
   </div>
  </section>

  <section id="checkCost">
   <h2>Total cost</h2>
   Total <input type="text" name="total"  size="10" readonly />
  </section>

 </form></code>```

here is the java script code,just focus on funtion total()

```<code>window.addEventListener('load', initialise);

    function initialise () {
        'use strict';
        //calculate price
        function total(){
        var cal= document.getElementsByName('event[]');
        var total = 0;
        for (var i = 0; i<cal.length; i++){
            if(cal[i].checked){
                total += parseFloat(cal[i].data-price);
            }
        }
    document.getElementByName("total").value = "$" + total.toFixed(2);
    }
</code>```

here is the link for my reference

[1]: Display total price when checkbox clicked in JS

i also tried but it doesn't work

total += parseFloat(cal[i].getAttribute("data-price")

答:
Don't inline the event handler!

Also getElementsByName is plural and returns a collection:

document.getElementsByName("total")[0].value

Remove the inline event and instead use

//calculate price
function total() {
  var cal = document.getElementsByName('event[]');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
  document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = total;
```

<p>If you do not use total anywhere else, do</p>

```var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
  var cal = document.getElementsByName('event[]');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
  document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
  var cal = document.getElementsByName('event[]');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
  document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}</code>```

  title 1
  1-1-2018
  2-2-2018
  Event 1
  Place 1
  100
  <input type='checkbox' name='event[]' value='id1' data-price='100' />

  title 2
  2-2-2018
  3-3-2018
  Event 2
  Place 2
  200
  <input type='checkbox' name='event[]' value='id1' data-price='200' />

Total cost

  Total <input type="text" name="total"  size="10" readonly />

```

Body:
I'm trying to add the onclick funtion when user checked the check box, and then the total price will be shown.

All the information including price is retrieve from database (no problem with retrieving data, the data display correctly).

Here is how's the code looks like.

//calculate price
function total() {
  var cal = document.getElementsByName('event');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
}
var checks = document.getElementsByName(event);
for (var i = 0; i < checks.length; i++) checks[i].onclick = total;

<form id="bookingForm" action="javascript:alert('form submitted');" method="get">

Select Events

   event1 <input type= checkbox name= event data-price = "1" value=eventId1/>
    event2 <input type= checkbox name= event data-price = "2" value=eventId2/>

Total cost

   Total <input type="text" name="total"  size="10" readonly />

 </form>

here is the java script code,just focus on funtion total()

window.addEventListener('load', initialise);

    function initialise () {
        'use strict';
        //calculate price
        function total(){
        var cal= document.getElementsByName('event[]');
        var total = 0;
        for (var i = 0; i<cal.length; i++){
            if(cal[i].checked){
                total += parseFloat(cal[i].data-price);
            }
        }
    document.getElementByName("total").value = "$" + total.toFixed(2);
    }

here is the link for my reference

[1]: Display total price when checkbox clicked in JS

i also tried but it doesn't work

total += parseFloat(cal[i].getAttribute("data-price")

Body:
Don't inline the event handler!

Also getElementsByName is plural and returns a collection:

document.getElementsByName("total")[0].value

Remove the inline event and instead use

//calculate price
function total() {
  var cal = document.getElementsByName('event[]');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
  document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}
var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = total;

If you do not use total anywhere else, do

var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
  var cal = document.getElementsByName('event[]');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
  document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}

var checks = document.getElementsByName('event[]');
for (var i = 0; i < checks.length; i++) checks[i].onclick = function() {
  var cal = document.getElementsByName('event[]');
  var total = 0;
  for (var i = 0; i < cal.length; i++) {
    if (cal[i].checked) {
      total += parseFloat(cal[i].getAttribute("data-price"));
    }
  }
  document.getElementsByName("total")[0].value = "$" + total.toFixed(2);
}

<div class='item'>
  <span class='eventTitle'>title 1</span>
  <span class='eventStartDate'>1-1-2018</span>
  <span class='eventEndDate'>2-2-2018</span>
  <span class='catDesc'>Event 1</span>
  <span class='venueName'>Place 1</span>
  <span class='eventPrice'>100</span>
  <span class='chosen'><input type='checkbox' name='event[]' value='id1' data-price='100' /></span>
</div>
<div class='item'>
  <span class='eventTitle'>title 2</span>
  <span class='eventStartDate'>2-2-2018</span>
  <span class='eventEndDate'>3-3-2018</span>
  <span class='catDesc'>Event 2</span>
  <span class='venueName'>Place 2</span>
  <span class='eventPrice'>200</span>
  <span class='chosen'><input type='checkbox' name='event[]' value='id1' data-price='200' /></span>
</div>
<section id="checkCost">
  <h2>Total cost</h2>
  Total <input type="text" name="total"  size="10" readonly />
 </section>


问:
SQL query with BETWEEN operator causes "Syntax error in number in query expression"
I'm using a MS Access database. I want to get first and last records that are in between 2 dates. But I get error when using a BETWEEN operator:

Syntax error in number in query expression 'Datum_k BETWEEN 3.4.2017. AND 3.4.2017.'.

My code:

```<code>private void GetPrviZadnjiBrojRacuna()
{
    OleDbCommand commandOD = new OleDbCommand("SELECT Dokument FROM DnevniPromet WHERE (Datum_k BETWEEN " + datumOd + " AND " + datumDo + ") ORDER BY [Datum_k] ASC", dataModel.CS);
    OleDbCommand commandDO = new OleDbCommand("SELECT Dokument FROM DnevniPromet WHERE [Datum_k] >= " + datumOd + " AND [Datum_k] <= " + datumDo + " ORDER BY [Datum_k] DESC", dataModel.CS);

    try
    {
        dataModel.DT.Clear();
        OleDbDataAdapter ODbDA = new OleDbDataAdapter(commandOD);

        if (!dataModel.CS.State.Equals(ConnectionState.Open))
        {
            dataModel.CS.Open();
        }

        // GET OD
        ODbDA.Fill(dataModel.DT);
        odRacuna = dataModel.DT.Rows[0].ToString();

        // GET DO
        ODbDA.SelectCommand = commandDO;
        dataModel.DT.Clear();
        ODbDA.Fill(dataModel.DT);

        doRacuna = dataModel.DT.Rows[0].ToString();

        dataModel.CS.Close();
        dataModel.DataLoaded = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}
</code>```

答:
Addressing two issues with your code snippet:

You should never use string interpolation to build a query. This lends itself to SQL injection. Many, many topics surrounding this. I suggest you read up.

You have missed the ' single quotes around your date strings.

Using parameterised queries, you can kill two birds with one stone:

```<code>OleDbCommand commandOD = new OleDbCommand(@"
    SELECT Dokument
    FROM DnevniPromet
    WHERE (Datum_k BETWEEN @datumOd AND @datumDo)
    ORDER BY [Datum_k] ASC", dataModel.CS);

commandOD.Parameters.AddRange(new OleDbParameter[]
{
    new OleDbParameter("@datumOd", datumOd),
    new OleDbParameter("@datumDo", datumDo)
});
</code>```

Body:
I'm using a MS Access database. I want to get first and last records that are in between 2 dates. But I get error when using a BETWEEN operator:

Syntax error in number in query expression 'Datum_k BETWEEN 3.4.2017. AND 3.4.2017.'.

My code:

private void GetPrviZadnjiBrojRacuna()
{
    OleDbCommand commandOD = new OleDbCommand("SELECT Dokument FROM DnevniPromet WHERE (Datum_k BETWEEN " + datumOd + " AND " + datumDo + ") ORDER BY [Datum_k] ASC", dataModel.CS);
    OleDbCommand commandDO = new OleDbCommand("SELECT Dokument FROM DnevniPromet WHERE [Datum_k] >= " + datumOd + " AND [Datum_k] <= " + datumDo + " ORDER BY [Datum_k] DESC", dataModel.CS);

    try
    {
        dataModel.DT.Clear();
        OleDbDataAdapter ODbDA = new OleDbDataAdapter(commandOD);

        if (!dataModel.CS.State.Equals(ConnectionState.Open))
        {
            dataModel.CS.Open();
        }

        // GET OD
        ODbDA.Fill(dataModel.DT);
        odRacuna = dataModel.DT.Rows[0].ToString();

        // GET DO
        ODbDA.SelectCommand = commandDO;
        dataModel.DT.Clear();
        ODbDA.Fill(dataModel.DT);

        doRacuna = dataModel.DT.Rows[0].ToString();

        dataModel.CS.Close();
        dataModel.DataLoaded = true;
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

Body:
Addressing two issues with your code snippet:

You should never use string interpolation to build a query. This lends itself to SQL injection. Many, many topics surrounding this. I suggest you read up.

You have missed the ' single quotes around your date strings.

Using parameterised queries, you can kill two birds with one stone:

OleDbCommand commandOD = new OleDbCommand(@"
    SELECT Dokument
    FROM DnevniPromet
    WHERE (Datum_k BETWEEN @datumOd AND @datumDo)
    ORDER BY [Datum_k] ASC", dataModel.CS);

commandOD.Parameters.AddRange(new OleDbParameter[]
{
    new OleDbParameter("@datumOd", datumOd),
    new OleDbParameter("@datumDo", datumDo)
});


问:
Nothing handled the action 'addPost' in ember.js
I am creating a post that has a description and created at time stamp.But when I
submit the form i get the error

Nothing handled the action 'addPost'. If you did handle the action, this      error can be caused by returning true from an action handler in a controller, causing the action to bubble.
Error

This is my controller

```<code>import Ember from 'ember';

export default Ember.Controller.extend({
actions: {
    addPost: function(){

        var description = this.get('description');

        //Create New Post
        var newPost = this.store.createRecord('post', {

            description: description,

        });

        // Save to Database
        newPost.save();

        // Clear Form
        this.setProperties({

            description: '',

        });
    }
}
});
</code>```

This is my model

```<code>import Model from 'ember-pouch/model';
import DS from 'ember-data';

const {
  attr,
  hasMany,
  belongsTo
} = DS;

export default Model.extend({
description: DS.attr('string'),
createdAt: DS.attr('date', {
defaultValue() { return new Date(); }
})
});
</code>```

This is the view

```<code><form>
<lable>Enter the post</lable>
{{input type="text" value=title }}
<button {{action 'addPost'}} >post</button>
</form>
</code>```

This is the router.js

```<code>import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
   location: config.locationType,
   rootURL: config.rootURL
});
Router.map(function() {
   this.route('posts', function() {
   this.route('new');
   });
});
export default Router;
</code>```

Unable to figure out what is the error.

答:
We should have same file name for both template hbs and controller js file. suppose if your template is app/templates/login.hbs then corresponding controller would be app/controllers/login.js.

If it's nested, then also it should maintain same hierarchy like
app/templates/dashboard/user.hbs corresponding controller would be app/controllers/dashboard/user.js

In your case, just ensure controller filename is same and following the same hierarchy like I mentioned above.

Body:
I am creating a post that has a description and created at time stamp.But when I
submit the form i get the error

Nothing handled the action 'addPost'. If you did handle the action, this      error can be caused by returning true from an action handler in a controller, causing the action to bubble.
Error

This is my controller

import Ember from 'ember';

export default Ember.Controller.extend({
actions: {
    addPost: function(){

        var description = this.get('description');

        //Create New Post
        var newPost = this.store.createRecord('post', {

            description: description,

        });

        // Save to Database
        newPost.save();

        // Clear Form
        this.setProperties({

            description: '',

        });
    }
}
});

This is my model

import Model from 'ember-pouch/model';
import DS from 'ember-data';

const {
  attr,
  hasMany,
  belongsTo
} = DS;

export default Model.extend({
description: DS.attr('string'),
createdAt: DS.attr('date', {
defaultValue() { return new Date(); }
})
});

This is the view

<form>
<lable>Enter the post</lable>
{{input type="text" value=title }}
<button {{action 'addPost'}} >post</button>
</form>

This is the router.js

import Ember from 'ember';
import config from './config/environment';
const Router = Ember.Router.extend({
   location: config.locationType,
   rootURL: config.rootURL
});
Router.map(function() {
   this.route('posts', function() {
   this.route('new');
   });
});
export default Router;

Unable to figure out what is the error.


问:
monitor and increase android performance of android applications
can anyone advice me some tools that can help me monitor the performance of my application ?

and tips that also can help me increasing the memory and gui usage of my application ?

some users complain that the application is too slow and I can not reproduce this issue on my device.

答:
There could be many issues regarding memory usage.

Too many static memory allocations. Check for static instances that you are creating in your app.

Memory leaks can occur if you pass huge Java objects between your fragments without using the recommended interface design pattern. Memory leaks can also occur if you are not properly maintaining fragment state during device configuration change.

Remove unwanted external libraries that are not being used. Reduce the size of your apk using proguard and lint.

Below are two links that may help you.

Manage Your App's Memory

Overview of Android Memory Management


问:
dismiss progress dialog in asyntask
I have search box in my page,I added onTextChangeListener() too. When I am add/removing letters/characters from search box ,every time I am calling same asyntask.Suppose 3 times called then 3 times progress dialog instances getting created and need to dismissed.Here progress dialog is not getting dismissed.

```<code>search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchresult = search.getText().toString();

                if (count == 0) {
                    pageCount = 1;
                    productsList.clear();
                    mCount = 0;
                    if (isTextWatcherVisible) {
//                        GetProductsTask();
                        new GetProductsTask().execute();
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
class GetProductsTask extends AsyncTask<Void, Void, Void> {

    final String pcid = Preferences.getString(Preferences.PrefType.enum_company_id, getActivity());

    String url1 = getContext().getString(R.string.url) + "products?company_id=" + pcid + "&page=" + pageCount;

    public GetProductsTask() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Loading...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
    }
    protected void onPreExecute() {
        super.onPreExecute();
//                progressDialog = new ProgressDialog(getActivity());
//                progressDialog.setMessage("Loading...");
//                progressDialog.setIndeterminate(false);
//                progressDialog.setCancelable(false);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {
      // somthig here
    }
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ProductslistAdapter adapter = new ProductslistAdapter(getActivity(), R.layout.vendor_products_item, productsList, searchresult);

        list.setAdapter(adapter);
        int count = pageCount - 1;
        list.setSelection(count * 24);
        if (progressDialog.isShowing())
            progressDialog.dismiss();

    }
</code>```

答:
```<code>// here your everytime your creating the dialog box, loosing previous reference. And "progressDialog " is not local to class "GetProductsTask".
   progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Loading...");
    progressDialog.setIndeterminate(false);
    progressDialog.setCancelable(false);
</code>```

solution :

```<code>class GetProductsTask extends AsyncTask<Void, Void, Void> {
//make it local to class
ProgressDialog progressDialog;
</code>```

Title: dismiss progress dialog in asyntask

Body:
I have search box in my page,I added onTextChangeListener() too. When I am add/removing letters/characters from search box ,every time I am calling same asyntask.Suppose 3 times called then 3 times progress dialog instances getting created and need to dismissed.Here progress dialog is not getting dismissed.

search.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }
            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                searchresult = search.getText().toString();

                if (count == 0) {
                    pageCount = 1;
                    productsList.clear();
                    mCount = 0;
                    if (isTextWatcherVisible) {
//                        GetProductsTask();
                        new GetProductsTask().execute();
                    }
                }
            }
            @Override
            public void afterTextChanged(Editable s) {
            }
        });
class GetProductsTask extends AsyncTask<Void, Void, Void> {

    final String pcid = Preferences.getString(Preferences.PrefType.enum_company_id, getActivity());

    String url1 = getContext().getString(R.string.url) + "products?company_id=" + pcid + "&page=" + pageCount;

    public GetProductsTask() {
        progressDialog = new ProgressDialog(getActivity());
        progressDialog.setMessage("Loading...");
        progressDialog.setIndeterminate(false);
        progressDialog.setCancelable(false);
    }
    protected void onPreExecute() {
        super.onPreExecute();
//                progressDialog = new ProgressDialog(getActivity());
//                progressDialog.setMessage("Loading...");
//                progressDialog.setIndeterminate(false);
//                progressDialog.setCancelable(false);
        progressDialog.show();

    }

    @Override
    protected Void doInBackground(Void... params) {
      // somthig here
    }
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        ProductslistAdapter adapter = new ProductslistAdapter(getActivity(), R.layout.vendor_products_item, productsList, searchresult);

        list.setAdapter(adapter);
        int count = pageCount - 1;
        list.setSelection(count * 24);
        if (progressDialog.isShowing())
            progressDialog.dismiss();

    }

Body:
// here your everytime your creating the dialog box, loosing previous reference. And "progressDialog " is not local to class "GetProductsTask".
   progressDialog = new ProgressDialog(getActivity());
    progressDialog.setMessage("Loading...");
    progressDialog.setIndeterminate(false);
    progressDialog.setCancelable(false);

solution :

class GetProductsTask extends AsyncTask<Void, Void, Void> {
//make it local to class
ProgressDialog progressDialog;


问:
Bootstrap align navbar items to the right
How do I align a navbar item to right?

I want to have the login and register to the right.
But everything I try does not seem to work.

 This is what I have tried so far:

 around the
 with the atribute: style="float: right"

 around the
 with the atribute: style="text-align: right"

tried those two things on the
 tags

tried all those things again with !important added to the end

changed nav-item to nav-right in the

added a pull-sm-right class to the

added a align-content-end class to the

This is my code:

```<code><div id="app" class="container">
  <nav class="navbar navbar-toggleable-md navbar-light bg-faded">
    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">
      <span class="navbar-toggler-icon"></span>
    </button>
    <a class="navbar-brand" href="#">Navbar</a>
    <ul class="navbar-nav">
      <li class="nav-item active">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Features</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Pricingg</a>
      </li>
    </ul>
    <ul class="navbar-nav " >
      <li  class="nav-item">
        <a class="nav-link" href="{{ url('/login') }}">Login</a>
      </li>
      <li  class="nav-item">
        <a class="nav-link" href="{{ url('/register') }}">Register</a>
      </li>
    </ul>
  </nav>
  @yield('content')
</div>
</code>```

答:
I'm new to stack overflow and new to front end development. This is what worked for me. So I did not want list items to be displayed.

.hidden {
  display:none;
  }

 #loginButton{

 margin-right:2px;

 }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  NavBar

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active hidden">
        Home <span class="sr-only">(current)</span>
      </li>
      <li class="nav-item hidden">
        Link
      </li>
      <li class="nav-item hidden">
        Disabled
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="loginButton">Log In</button>
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Register</button>
    </form>
  </div>
</nav></code>```

Body:
How do I align a navbar item to right?

I want to have the login and register to the right.
But everything I try does not seem to work.

 This is what I have tried so far:

 around the
 with the atribute: style="float: right"

 around the
 with the atribute: style="text-align: right"

tried those two things on the
 tags

tried all those things again with !important added to the end

changed nav-item to nav-right in the

added a pull-sm-right class to the

added a align-content-end class to the

This is my code:

    <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarNavDropdown" aria-controls="navbarNavDropdown" aria-expanded="false" aria-label="Toggle navigation">

    </button>
    Navbar

        Home (current)

        Features

        Pricingg

        Login

        Register

  @yield('content')

Body:
I'm new to stack overflow and new to front end development. This is what worked for me. So I did not want list items to be displayed.

.hidden {
  display:none;
  }

 #loginButton{

 margin-right:2px;

 }

<nav class="navbar navbar-toggleable-md navbar-light bg-faded fixed-top">
  <button class="navbar-toggler navbar-toggler-right" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <a class="navbar-brand" href="#">NavBar</a>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active hidden">
        <a class="nav-link" href="#">Home <span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item hidden">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item hidden">
        <a class="nav-link disabled" href="#">Disabled</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit" id="loginButton"><a href="#">Log In</a></button>
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit"><a href="#">Register</a></button>
    </form>
  </div>
</nav>


问:
How to properly initialize interface in Activity?
I have this interface:

```<code>public interface SomeInterface {

    void doSomething();
}
</code>```

I am trying to initialize it in Main activity and I am trying to "send it" to second activity:

```<code>private SomeInterface someInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    someInterface = (SomeInterface) this;
    someInterface.doSomething();
}
</code>```

I implemented interface into second activity.

```<code>public class SecondActivity extends Activity implements SomeInterface  {

    @Override
    public void doSomething() {

    }
}
</code>```

But this is not working, I am getting follwing error:

```<code>java.lang.RuntimeException: Unable to start activity ComponentInfo{package.name/package.name.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to package.name.AppInterface
</code>```

What I am doing wrong? Thank you in advance.

答:
You need to implement the interface.. Try this</p>

```<code>public class YourActivity extends Activity implements SomeInterface {

  private SomeInterface someInterface;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      someInterface = (SomeInterface) this;
      someInterface.doSomething();
  }
}
</code>```

Body:
I have this interface:

public interface SomeInterface {

    void doSomething();
}

I am trying to initialize it in Main activity and I am trying to "send it" to second activity:

private SomeInterface someInterface;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    someInterface = (SomeInterface) this;
    someInterface.doSomething();
}

I implemented interface into second activity.

public class SecondActivity extends Activity implements SomeInterface  {

    @Override
    public void doSomething() {

    }
}

But this is not working, I am getting follwing error:

java.lang.RuntimeException: Unable to start activity ComponentInfo{package.name/package.name.MainActivity}: java.lang.ClassCastException: android.app.Application cannot be cast to package.name.AppInterface

What I am doing wrong? Thank you in advance.

Body:
You need to implement the interface.. Try this

public class YourActivity extends Activity implements SomeInterface {

  private SomeInterface someInterface;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);

      someInterface = (SomeInterface) this;
      someInterface.doSomething();
  }
}


问:
Ensemble Learning in Unsupervised Learning
I have a question regarding the current literature in ensemble learning (more specifically in unsupervised learning).

For what I read in the literature, Ensemble Learning when applied to Unsupervised Learning resumes basically to Clustering Problems. However, if I have x unsupervised methods that output a score (similar to a regression problem), is there an approach that can combine these results into a single one?

答:
On evaluation of outlier rankings and outlier scores.
 Schubert, E., Wojdanowski, R., Zimek, A., & Kriegel, H. P. (2012, April).
 In Proceedings of the 2012 SIAM International Conference on Data Mining (pp. 1047-1058). Society for Industrial and Applied Mathematics.

In this publication, we not "just normalize" outlier scores, but we also suggest a unsupervised ensemble member selection strategy called "greedy ensemble".

However, normalization is crucial, and difficult. We published some of the earlier progress with respect to score normalization as

Interpreting and unifying outlier scores.
 Kriegel, H. P., Kroger, P., Schubert, E., & Zimek, A. (2011, April).
 In Proceedings of the 2011 SIAM International Conference on Data Mining (pp. 13-24). Society for Industrial and Applied Mathematics.

If you don't normalize your scores (and min-max scaling is not enough), you will usually not be able to combine them in a meaningful way, except with very strong preconditions. Even two different subspaces will usually yield incomparable values because of having a different number of features, and different feature scales.

There is also some work on semi-supervised ensembles, e.g.

Learning Outlier Ensembles: The Best of Both Worlds—Supervised and Unsupervised.
 Micenková, B., McWilliams, B., & Assent, I. (2014).
In Proceedings of the ACM SIGKDD 2014 Workshop on Outlier Detection and Description under Data Diversity (ODD2). New York, NY, USA (pp. 51-54).

Also beware of overfitting. It's quite easy to arrive at a single good result by tweaking parameters and repeated evaluation. But this leaks evaluation information into your experiment, i.e. you tend to overfit. Performing well across a large range of parameters and data sets is very hard. One of the key observations of the following study was that for every algorithm, you'll find at least one data set and parameter set, where it 'outperforms' the others; but if you change parameters a little, or use a different data set, the benefits of the "superior" new methods are not reproducible.

On the evaluation of unsupervised outlier detection: measures, datasets, and an empirical study.
 Campos, G. O., Zimek, A., Sander, J., Campello, R. J., Micenková, B., Schubert, E., ... & Houle, M. E. (2016).
 Data Mining and Knowledge Discovery, 30(4), 891-927.

So you will have to work really hard to do a reliable evaluation. Be careful how to choose parameters.


问:
Is "parsing" a subset of "compiling"?
When I think of "compiling" I think of turning C++ code into a binary. Or perhaps C# into CLR byte code. But "parsing" could be something like parsing Python, or a web template language, where it doesn't need to produce any binaries, but can either execute the code immediately, statement-by-statement, or output HTML directly.

Would you basically be doing the same task in either case? Ignoring the language syntax, would compiling C++ be equally as difficult as parsing a website template file (Django, Smarty, whatever), or Python?

What I'm trying to allude at, is if I study "compiling" or read a book on "compiling" will I necessarily pick up the skills to parse non-compiled languages?

答:
No, parsing and compiling can be completely independent.

A parser may not be emitting any code at all. It could be parsing some data object (JSON, XML, whatever)

A compiler may not have source code to start with - it could be presented with an abstract syntax tree, already parsed, and just have to emit the relevant code

Most compilers include a parsing step, but I don't think it's necessarily a "subset" of compiling, and parsing certainly doesn't have to have anything to do with compilation.

Title: Is "parsing" a subset of "compiling"?


问:
Test Suite failed to run TypeError: Cannot read property 'bind' of undefined
Working on a React Native project. I am trying to test one of the bigger components using Jest. I'm getting this test failed to run error with a property on undefined, which doesn't make any sense because a few lines later it says all the tests ran fine.

I've tried removing my node modules and running npm install again.

You can see the error here:

and the test here:

```<code>import React from 'react';
import ReactNative, {
  Image,
  Text,
  View
} from 'react-native';
import renderer from 'react-test-renderer';
import TeamDetail from '../../app/scenes/TeamDetail/TeamDetail';

const mockFn = () => 'THIS IS A MOCK!!!!';

describe('<TeamDetail />', () => {
  it('renders correctly', () => {
    const team = {};
    const captains = {
      count: 1,
      items: [],
      links: { next: 'next link', prev: 'prev link', },
    };
    const leagueTeamCount = 1;
    const games = {
      count: 1,
      items: [],
      links: { next: 'next link', prev: 'prev link', },
    };
    const roster = {
      count: 1,
      items: [],
      links: { next: 'next link', prev: 'prev link', },
    };
    const fetchPendingPlayers = mockFn;
    const pendingPlayers = {
      count: 1,
      items: [],
      links: { next: 'next link', prev: 'prev link', },
    };
    const updateTeam = mockFn;
    const addPlayerToTeam = mockFn;
    const addCaptainToTeam = mockFn;
    const approvePlayer = mockFn;
    const canManageTeam = true;
    const canMessage = true;
    const clearSearchResults = mockFn;
    const fetchTeamGames = mockFn;
    const fetchTeamPlayers = mockFn;
    const fetchUserProfile = mockFn;

    const tree = renderer.create(
      <TeamDetail
        team={team}
        captains={captains}
        leagueTeamCount={leagueTeamCount}
        games={games}
        roster={roster}
        fetchPendingPlayers={fetchPendingPlayers}
        pendingPlayers={pendingPlayers}
        updateTeam={updateTeam}
        addPlayerToTeam={addPlayerToTeam}
        addCaptainToTeam={addCaptainToTeam}
        approvePlayer={approvePlayer}
        canManageTeam={canManageTeam}
        canMessage={canMessage}
        clearSearchResults={clearSearchResults}
        fetchTeamGames={fetchTeamGames}
        fetchTeamPlayers={fetchTeamPlayers}
        fetchUserProfile={fetchUserProfile}
        searchResults={searchResults}
        searchUsers={searchUsers}
        setLocationAlert={setLocationAlert}
        viewTeamMessageFeed={viewTeamMessageFeed}
      />
    ).toJSON();

    expect(tree).toMatchSnapshot();
  });
});
</code>```

and here is package.json

```<code>{
  "name": "APPNAME",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "flow": "flow",
    "jest": "jest",
    "lint": "eslint . --ext .js --ext .jsx --ignore-path .gitignore --ignore-path .eslintignore --cache",
    "packager": "remotedev-debugger --port 8000 --injectserver && node_modules/react-native/packager/packager.sh",
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "mocha --require babel-register $(find app/tests -name \"*_test.js\")",
    "bundle-android": "react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --sourcemap-output android/app/src/main/assets/index.android.map --assets-dest android/app/src/main/res/"
  },
  "pre-commit": [
    "lint",
    "flow",
    "test",
    "jest"
  ],
  "dependencies": {
    "apsl-react-native-button": "^3.0.2",
    "bugsnag-react-native": "^1.2.1",
    "flow": "^0.2.3",
    "flow-typed": "^2.0.0",
    "immutable": "^3.8.1",
    "jsrsasign": "^6.2.0",
    "jwt-decode": "^2.1.0",
    "momentjs": "^2.0.0",
    "phoenix": "^1.2.1",
    "ramda": "^0.22.1",
    "react": "~15.4.0-rc.4",
    "react-native": "0.40.0",
    "react-native-button": "^1.7.1",
    "react-native-drawer": "^2.3.0",
    "react-native-experimental-navigation": "^0.26.10",
    "react-native-fbsdk": "0.5",
    "react-native-fetch-blob": "v0.10.2-beta.8",
    "react-native-geocoder": "https://github.com/smartlogic/react-native-geocoder.git",
    "react-native-image-picker": "0.25",
    "react-native-invertible-scroll-view": "^1.0.0",
    "react-native-router-flux": "^3.36.0",
    "react-redux": "^4.4.5",
    "redux": "^3.6.0",
    "redux-action-buffer": "^1.0.1",
    "redux-persist": "^4.0.0-alpha7",
    "redux-saga": "^0.12.1"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "babel-eslint": "^7.1.0",
    "babel-jest": "16.0.0",
    "babel-plugin-ramda": "^1.1.6",
    "babel-plugin-syntax-flow": "^6.18.0",
    "babel-plugin-transform-flow-strip-types": "^6.22.0",
    "babel-preset-react-native": "1.9.0",
    "babel-register": "^6.18.0",
    "chai": "^3.5.0",
    "eslint": "^3.9.1",
    "eslint-plugin-flowtype": "^2.25.0",
    "eslint-plugin-react": "^6.4.1",
    "eslint-plugin-react-native": "^2.0.0",
    "flow-bin": "0.38",
    "jest": "^18.1.0",
    "jest-cli": "^19.0.2",
    "jest-react-native": "^17.1.0",
    "jsverify": "^0.7.4",
    "mocha": "^3.2.0",
    "pre-commit": "^1.1.3",
    "react-test-renderer": "^15.4.2",
    "remote-redux-devtools": "^0.5.7",
    "remote-redux-devtools-on-debugger": "^0.7.0"
  }
}
</code>```

答:
Try to install both jest and jest babel last versions

```<code>npm install --save-dev jest

npm install --save-dev babel-jest regenerator-runtime
</code>```

And re-run the test, it works for me

Body:
Working on a React Native project. I am trying to test one of the bigger components using Jest. I'm getting this test failed to run error with a property on undefined, which doesn't make any sense because a few lines later it says all the tests ran fine.

I've tried removing my node modules and running npm install again.

You can see the error here:

and the test here:

import React from 'react';
import ReactNative, {
  Image,
  Text,
  View
} from 'react-native';
import renderer from 'react-test-renderer';
import TeamDetail from '../../app/scenes/TeamDetail/TeamDetail';

const mockFn = () => 'THIS IS A MOCK!!!!';

describe('<TeamDetail />', () => {
  it('renders correctly', () => {
    const team = {};
    const captains = {
      count: 1,
      items: [],
      links: { next: 'next link', prev: 'prev link', },
    };
    const leagueTeamCount = 1;
    const games = {
      count: 1,
      items: [],
      links: { next: 'next link', prev: 'prev link', },
    };
    const roster = {
      count: 1,
      items: [],
      links: { next: 'next link', prev: 'prev link', },
    };
    const fetchPendingPlayers = mockFn;
    const pendingPlayers = {
      count: 1,
      items: [],
      links: { next: 'next link', prev: 'prev link', },
    };
    const updateTeam = mockFn;
    const addPlayerToTeam = mockFn;
    const addCaptainToTeam = mockFn;
    const approvePlayer = mockFn;
    const canManageTeam = true;
    const canMessage = true;
    const clearSearchResults = mockFn;
    const fetchTeamGames = mockFn;
    const fetchTeamPlayers = mockFn;
    const fetchUserProfile = mockFn;

    const tree = renderer.create(
      <TeamDetail
        team={team}
        captains={captains}
        leagueTeamCount={leagueTeamCount}
        games={games}
        roster={roster}
        fetchPendingPlayers={fetchPendingPlayers}
        pendingPlayers={pendingPlayers}
        updateTeam={updateTeam}
        addPlayerToTeam={addPlayerToTeam}
        addCaptainToTeam={addCaptainToTeam}
        approvePlayer={approvePlayer}
        canManageTeam={canManageTeam}
        canMessage={canMessage}
        clearSearchResults={clearSearchResults}
        fetchTeamGames={fetchTeamGames}
        fetchTeamPlayers={fetchTeamPlayers}
        fetchUserProfile={fetchUserProfile}
        searchResults={searchResults}
        searchUsers={searchUsers}
        setLocationAlert={setLocationAlert}
        viewTeamMessageFeed={viewTeamMessageFeed}
      />
    ).toJSON();

    expect(tree).toMatchSnapshot();
  });
});

and here is package.json

{
  "name": "APPNAME",
  "version": "0.0.1",
  "private": true,
  "scripts": {
    "flow": "flow",
    "jest": "jest",
    "lint": "eslint . --ext .js --ext .jsx --ignore-path .gitignore --ignore-path .eslintignore --cache",
    "packager": "remotedev-debugger --port 8000 --injectserver && node_modules/react-native/packager/packager.sh",
    "start": "node node_modules/react-native/local-cli/cli.js start",
    "test": "mocha --require babel-register $(find app/tests -name \"*_test.js\")",
    "bundle-android": "react-native bundle --platform android --dev false --entry-file index.android.js --bundle-output android/app/src/main/assets/index.android.bundle --sourcemap-output android/app/src/main/assets/index.android.map --assets-dest android/app/src/main/res/"
  },
  "pre-commit": [
    "lint",
    "flow",
    "test",
    "jest"
  ],
  "dependencies": {
    "apsl-react-native-button": "^3.0.2",
    "bugsnag-react-native": "^1.2.1",
    "flow": "^0.2.3",
    "flow-typed": "^2.0.0",
    "immutable": "^3.8.1",
    "jsrsasign": "^6.2.0",
    "jwt-decode": "^2.1.0",
    "momentjs": "^2.0.0",
    "phoenix": "^1.2.1",
    "ramda": "^0.22.1",
    "react": "~15.4.0-rc.4",
    "react-native": "0.40.0",
    "react-native-button": "^1.7.1",
    "react-native-drawer": "^2.3.0",
    "react-native-experimental-navigation": "^0.26.10",
    "react-native-fbsdk": "0.5",
    "react-native-fetch-blob": "v0.10.2-beta.8",
    "react-native-geocoder": "https://github.com/smartlogic/react-native-geocoder.git",
    "react-native-image-picker": "0.25",
    "react-native-invertible-scroll-view": "^1.0.0",
    "react-native-router-flux": "^3.36.0",
    "react-redux": "^4.4.5",
    "redux": "^3.6.0",
    "redux-action-buffer": "^1.0.1",
    "redux-persist": "^4.0.0-alpha7",
    "redux-saga": "^0.12.1"
  },
  "jest": {
    "preset": "jest-react-native"
  },
  "devDependencies": {
    "babel-eslint": "^7.1.0",
    "babel-jest": "16.0.0",
    "babel-plugin-ramda": "^1.1.6",
    "babel-plugin-syntax-flow": "^6.18.0",
    "babel-plugin-transform-flow-strip-types": "^6.22.0",
    "babel-preset-react-native": "1.9.0",
    "babel-register": "^6.18.0",
    "chai": "^3.5.0",
    "eslint": "^3.9.1",
    "eslint-plugin-flowtype": "^2.25.0",
    "eslint-plugin-react": "^6.4.1",
    "eslint-plugin-react-native": "^2.0.0",
    "flow-bin": "0.38",
    "jest": "^18.1.0",
    "jest-cli": "^19.0.2",
    "jest-react-native": "^17.1.0",
    "jsverify": "^0.7.4",
    "mocha": "^3.2.0",
    "pre-commit": "^1.1.3",
    "react-test-renderer": "^15.4.2",
    "remote-redux-devtools": "^0.5.7",
    "remote-redux-devtools-on-debugger": "^0.7.0"
  }
}

Body:
Try to install both jest and jest babel last versions

npm install --save-dev jest

npm install --save-dev babel-jest regenerator-runtime

And re-run the test, it works for me


问:
Alloy - Remove middle atom from tuple
I currently have three atoms class, pupil, grade and a tuple mark in the format class->pupil->grade. How can I return a tuple in the format class->grade so that I can see the grades a specific pupil has got in each class as a class/grade binary relation? Assume there is only one pupil in the system. Thanks!

答:
One way I can imagine to achieve this is using set comprehension as follows:</p>

```<code>fun getGrade[p:Pupil]: Class->Grade {
  {c:Class,g:Grade|c->p->g in mark}
}
</code>```

Title: Alloy - Remove middle atom from tuple

Body:
One way I can imagine to achieve this is using set comprehension as follows:

fun getGrade[p:Pupil]: Class->Grade {
  {c:Class,g:Grade|c->p->g in mark}
}


问:
iOS 10/Xcode 8 TestFairy not logging
I tried googling and reading newest TestFairy documentation, but nothing worth of mention there. My problem is next: I upgraded Xcode to 8, and created new build that I uploaded on TestFairy. Everything is working normal, except now I don't see application logs. Anyone else experienced same issue?

Note: Everything worked fine with Xcode 7 and iOS 10.

答:
Disclosure: I work for TestFairy

Apple changed their log apis with iOS 10 effectively barring libraries from ours from collecting logs from a device. We've suggested a workaround which asks developers to either use TFLog instead of NSLog, or create a macro forwarding all calls to NSLog to TFLog. This is described in our docs which are available here.

Title: iOS 10/Xcode 8 TestFairy not logging


问:
Read a json file from Capistrano 3
I have a json file that holds some configuration settings.  I want to read that file and then set values in my recipe.  Is that possible?

Thanks

Grant

答:
Yes. In the top of your deploy.rb, you can use the Ruby JSON library.

Something like:

```<code>require 'json'

my_hash = JSON.parse(File.read('filename.json'))
set :branch, my_hash["branch"]
</code>```

Title: Read a json file from Capistrano 3

Body:
Yes. In the top of your deploy.rb, you can use the Ruby JSON library.

Something like:

require 'json'

my_hash = JSON.parse(File.read('filename.json'))
set :branch, my_hash["branch"]


问:
Laravel: Output from database
I must be missing something, since my code isn't working, but I have tried to figure it out for a while now without any luck.

I am trying to output a single column content from a table, which represents all the text-bits throughout a simple website, which I want to be able to edit and update in the table, with a simple cms, which I have created.

These are my controllers

And my Model

I would like to do this in my index.blade.php
{{ $indexHeading }}

I get the error message: undefined variable: texts, I must be missing a link between something.

I am a beginner, and I'm hoping I just made a simple mistake, which I am not skilled enough to see :)

Thanks in advance!

答: In your MainController you are passing texts without creating it.

Title: Laravel: Output from database