问:
How to solve 'numpy.float64' object has no attribute 'encode' in python 3
I am  trying to do a sentiment analysis in twitter about different car brands,i am using python 3 for this.While running the code i am getting the below exception

```<code>Traceback (most recent call last):
File "C:\Users\Jeet Chatterjee\NLP\Maruti_Toyota_Marcedes_Brand_analysis.py", line 55, in <module>
x = str(x.encode('utf-8','ignore'),errors ='ignore')
AttributeError: 'numpy.float64' object has no attribute 'encode'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Jeet Chatterjee\NLP\Maruti_Toyota_Marcedes_Brand_analysis.py", line 62, in <module>
tweets.set_value(idx,column,'')
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas\core\frame.py", line 1856, in set_value
engine.set_value(series._values, index, value)
 File "pandas\_libs\index.pyx", line 116, in pandas._libs.index.IndexEngine.set_value (pandas\_libs\index.c:4690)
File "pandas\_libs\index.pyx", line 130, in pandas._libs.index.IndexEngine.set_value (pandas\_libs\index.c:4578)
File "pandas\_libs\src\util.pxd", line 101, in util.set_value_at (pandas\_libs\index.c:21043)
  File "pandas\_libs\src\util.pxd", line 93, in util.set_value_at_unsafe (pandas\_libs\index.c:20964)
 ValueError: could not convert string to float:
</code>```

I don't how to represent the encode in python 3 . And here is my code

```<code>from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
import json
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#regular expression in python
import re

#data corpus
tweets_data_path = 'carData.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweets_data.append(tweet)
    except:
        continue
#creating panda dataset
tweets = pd.DataFrame()
index = 0
    for num, line in enumerate(tweets_data):
  try:

     print (num,line['text'])

     tweets.loc[index,'text'] = line['text']
     index = index + 1
  except:
         print(num, "line not parsed")
         continue

   def brand_in_tweet(brand, tweet):
       brand = brand.lower()
       tweet = tweet.lower()
       match = re.search(brand, tweet)
       if match:
        print ('Match Found')
        return brand
    else:
        print ('Match not found')
        return 'none'
for index, row in tweets.iterrows():
temp = TextBlob(row['text'])
tweets.loc[index,'sentscore'] = temp.sentiment.polarity

  for column in tweets.columns:
  for idx in tweets[column].index:
    x = tweets.get_value(idx,column)
    try:
        x = str(x.encode('utf-8','ignore'),errors ='ignore')
        if type(x) == unicode:
            str(str(x),errors='ignore')
        else:
            df.set_value(idx,column,x)
    except Exception:
        print ('encoding error: {0} {1}'.format(idx,column))
        tweets.set_value(idx,column,'')
        continue
tweets.to_csv('tweets_export.csv')

if __name__=='__main__':

  brand_in_tweet()
</code>```

I have posted the full code , i am not getting any clue about this error , that how to solve this . Please help and thanks in advance .

答:
There is a problem in this line:

```<code> x = str(x.encode('utf-8','ignore'),errors ='ignore')
</code>```

x is a numpy.float64. The code is trying to first encode it as utf8, then convert it to a string. But that is the wrong way around, because only strings can be encoded. First convert it to a string, then encode the string:

```<code> x = str(x).encode('utf-8','ignore')
</code>```

Body:
I am  trying to do a sentiment analysis in twitter about different car brands,i am using python 3 for this.While running the code i am getting the below exception

Traceback (most recent call last):
File "C:\Users\Jeet Chatterjee\NLP\Maruti_Toyota_Marcedes_Brand_analysis.py", line 55, in <module>
x = str(x.encode('utf-8','ignore'),errors ='ignore')
AttributeError: 'numpy.float64' object has no attribute 'encode'

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
File "C:\Users\Jeet Chatterjee\NLP\Maruti_Toyota_Marcedes_Brand_analysis.py", line 62, in <module>
tweets.set_value(idx,column,'')
  File "C:\Program Files (x86)\Python36-32\lib\site-packages\pandas\core\frame.py", line 1856, in set_value
engine.set_value(series._values, index, value)
 File "pandas\_libs\index.pyx", line 116, in pandas._libs.index.IndexEngine.set_value (pandas\_libs\index.c:4690)
File "pandas\_libs\index.pyx", line 130, in pandas._libs.index.IndexEngine.set_value (pandas\_libs\index.c:4578)
File "pandas\_libs\src\util.pxd", line 101, in util.set_value_at (pandas\_libs\index.c:21043)
  File "pandas\_libs\src\util.pxd", line 93, in util.set_value_at_unsafe (pandas\_libs\index.c:20964)
 ValueError: could not convert string to float:

I don't how to represent the encode in python 3 . And here is my code

from tweepy.streaming import StreamListener
from tweepy import OAuthHandler
from tweepy import Stream
from textblob import TextBlob
import json
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
#regular expression in python
import re

#data corpus
tweets_data_path = 'carData.txt'
tweets_data = []
tweets_file = open(tweets_data_path, "r")
for line in tweets_file:
    try:
        tweet = json.loads(line)
        tweets_data.append(tweet)
    except:
        continue
#creating panda dataset
tweets = pd.DataFrame()
index = 0
    for num, line in enumerate(tweets_data):
  try:

     print (num,line['text'])

     tweets.loc[index,'text'] = line['text']
     index = index + 1
  except:
         print(num, "line not parsed")
         continue

   def brand_in_tweet(brand, tweet):
       brand = brand.lower()
       tweet = tweet.lower()
       match = re.search(brand, tweet)
       if match:
        print ('Match Found')
        return brand
    else:
        print ('Match not found')
        return 'none'
for index, row in tweets.iterrows():
temp = TextBlob(row['text'])
tweets.loc[index,'sentscore'] = temp.sentiment.polarity

  for column in tweets.columns:
  for idx in tweets[column].index:
    x = tweets.get_value(idx,column)
    try:
        x = str(x.encode('utf-8','ignore'),errors ='ignore')
        if type(x) == unicode:
            str(str(x),errors='ignore')
        else:
            df.set_value(idx,column,x)
    except Exception:
        print ('encoding error: {0} {1}'.format(idx,column))
        tweets.set_value(idx,column,'')
        continue
tweets.to_csv('tweets_export.csv')

if __name__=='__main__':

  brand_in_tweet()

I have posted the full code , i am not getting any clue about this error , that how to solve this . Please help and thanks in advance .

Body:
There is a problem in this line:

 x = str(x.encode('utf-8','ignore'),errors ='ignore')

x is a numpy.float64. The code is trying to first encode it as utf8, then convert it to a string. But that is the wrong way around, because only strings can be encoded. First convert it to a string, then encode the string:

 x = str(x).encode('utf-8','ignore')


来源: stackexchange

问:
Laravel - change specific tr bgcolor in views using controller based on parameter
I'm trying to change the color of my table rows based on my parameter. here's my code:

AdminController.php

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

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }
    return view('walks', compact('$highlightClass'));
}
</code>```

walks.blade.php

```<code><tr class="{{ $highlightClass }}">
</code>```

It didn't work.. :(

Here's the image of table in my views:

enter image description here

答:
Why don't you make a standard to send the data to view file. Create an array and add all the data (that you want to send to view file) in that array with key and fetch data with their key on view file.</p>

```<code>public function table_row(){
  $data = array();
  $data['highlightClass'] = "";
  if ($walk->is_paid && $walk->is_completed) {
    $data['highlightClass'] = 'bg-success';
  }
  elseif (empty($walk->is_paid) && $walk->is_completed) {
    $data['highlightClass'] = 'bg-warning';
  }
  elseif ($walk->is_cancelled) {
    $data['highlightClass'] = 'bg-danger';
  }
  return view('walks',$data);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to change the color of my table rows based on my parameter. here's my code:

AdminController.php

public function table_row(){

    if ($walk->is_paid && $walk->is_completed) {
        $highlightClass = 'bg-success';
    }
    elseif (empty($walk->is_paid) && $walk->is_completed) {
        $highlightClass = 'bg-warning';
    }
    elseif ($walk->is_cancelled) {
        $highlightClass = 'bg-danger';
    }
    return view('walks', compact('$highlightClass'));
}

walks.blade.php

It didn't work.. :(

Here's the image of table in my views:

enter image description here

Body:
Why don't you make a standard to send the data to view file. Create an array and add all the data (that you want to send to view file) in that array with key and fetch data with their key on view file.

public function table_row(){
  $data = array();
  $data['highlightClass'] = "";
  if ($walk->is_paid && $walk->is_completed) {
    $data['highlightClass'] = 'bg-success';
  }
  elseif (empty($walk->is_paid) && $walk->is_completed) {
    $data['highlightClass'] = 'bg-warning';
  }
  elseif ($walk->is_cancelled) {
    $data['highlightClass'] = 'bg-danger';
  }
  return view('walks',$data);
}


问:
Format a Json string from server side in jquery client side
this the fiddle

http://jsfiddle.net/zzk3rgrm/3/

I am getting the json string from server like this below

JS

var myjsonstring = [{"Key":"item1","Value":"problem statement 1"},{"Key":"item1","Value":"problem statement 2 bigstatement  bigstatement bigstatement bigstatement bigstatement"},{"Key":"item2","Value":"problem statement 1"},{"Key":"item3","Value":"problem statement 1"}];

myjsonstring = JSON.stringify(myjsonstring);

alert(myjsonstring);```
</div>
</div>

now as you see in code <code>Key</code>  , <code>Value</code>these words are coming these should be removed .
"," as seperator coming so should be removed and in place of comma , a new line should be there so that each item shows up in seperate line . </p>

<p>also all the {} [] these characters removed . </p>

<p>so that in the alert it comes like below </p>

```item1 - problem statement 1
item1- problem statement 2 bigstatement  bigstatement bigstatement bigstatement bigstatement
item2- problem statement 1
item3 -problem statement 1
```

Please help here

答:
myjsonstring is an array and can be used as it is without using stringify

var myjsonstring = [{"Key":"item1","Value":"problem statement 1"},{"Key":"item1","Value":"problem statement 2 bigstatement  bigstatement bigstatement bigstatement bigstatement"},{"Key":"item2","Value":"problem statement 1"},{"Key":"item3","Value":"problem statement 1"}];

var newJson = "";
myjsonstring.forEach(function(ob){
   newJson += ob.Key + ' - ' + ob.Value + '\n';
});

alert(newJson);```

Body:
this the fiddle

http://jsfiddle.net/zzk3rgrm/3/

I am getting the json string from server like this below

JS

var myjsonstring = [{"Key":"item1","Value":"problem statement 1"},{"Key":"item1","Value":"problem statement 2 bigstatement  bigstatement bigstatement bigstatement bigstatement"},{"Key":"item2","Value":"problem statement 1"},{"Key":"item3","Value":"problem statement 1"}];

myjsonstring = JSON.stringify(myjsonstring);

alert(myjsonstring);

now as you see in code Key  , Valuethese words are coming these should be removed .
"," as seperator coming so should be removed and in place of comma , a new line should be there so that each item shows up in seperate line .

also all the {} [] these characters removed .

so that in the alert it comes like below

item1 - problem statement 1
item1- problem statement 2 bigstatement  bigstatement bigstatement bigstatement bigstatement
item2- problem statement 1
item3 -problem statement 1

Please help here


问:
Weird "406 not acceptable" error
When I try to hit this action via Javascript, I get a 406 Not Acceptable error:

```<code>  def show
    @annotation = Annotation.find_by_id(params[:id])

    respond_to do |format|
      format.html {
         if @annotation.blank?
           redirect_to root_path
         else
           redirect_to inline_annotation_path(@annotation)
         end
       }

       format.js {
         if params[:format] == "raw"
           render :text => @annotation.body.to_s
         else
           render :text => @annotation.body.to_html
         end
       }
    end
  end
</code>```

This is from jQuery, but I'm doing the right beforeSend stuff:

```<code>  $.ajaxSetup({
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Accept", "text/javascript");
    },
    cache: false
  });
</code>```

Here are my request headers:

```<code>Host    localhost:3000
User-Agent  Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3
Accept  text/javascript
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  300
Connection  keep-alive
X-Requested-With    XMLHttpRequest
Content-Type    application/x-www-form-urlencoded
</code>```

答:
Just use this code in controller action method format block:</p>

```<code>format.js   { render :nothing => true }
</code>```

ContentLicense: CC BY-SA 2.5

Title: Weird "406 not acceptable" error

Body:
When I try to hit this action via Javascript, I get a 406 Not Acceptable error:

  def show
    @annotation = Annotation.find_by_id(params[:id])

    respond_to do |format|
      format.html {
         if @annotation.blank?
           redirect_to root_path
         else
           redirect_to inline_annotation_path(@annotation)
         end
       }

       format.js {
         if params[:format] == "raw"
           render :text => @annotation.body.to_s
         else
           render :text => @annotation.body.to_html
         end
       }
    end
  end

This is from jQuery, but I'm doing the right beforeSend stuff:

  $.ajaxSetup({
    beforeSend: function(xhr) {
      xhr.setRequestHeader("Accept", "text/javascript");
    },
    cache: false
  });

Here are my request headers:

Host    localhost:3000
User-Agent  Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10.5; en-US; rv:1.9.1.3) Gecko/20090824 Firefox/3.5.3
Accept  text/javascript
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  300
Connection  keep-alive
X-Requested-With    XMLHttpRequest
Content-Type    application/x-www-form-urlencoded

Body:
Just use this code in controller action method format block:

format.js   { render :nothing => true }


问:
Docker: Error when executing command docker exec my_container composer php yii migrate --interactive=0
I'm working on a project in Yii2 running under a VM in Docker on a Mac with Sierra Os.
While I execute the migrtion command which is this one:

```<code>docker exec my_container composer PHP Yii migrate --interactive=0enter
</code>```

I receive this error:

```<code>[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "php" is not defined.
</code>```

I have Google that online but I have not found any good solutions.
I really hope to find a solution to my issue.

答:
Am not entirely sure what composer PHP Yii migrate is, but docs at docker says

COMMAND should be an executable, a chained or a quoted command will
  not work.

Maybe this can help you.

Body:
I'm working on a project in Yii2 running under a VM in Docker on a Mac with Sierra Os.
While I execute the migrtion command which is this one:

docker exec my_container composer PHP Yii migrate --interactive=0enter

I receive this error:

[Symfony\Component\Console\Exception\CommandNotFoundException]
Command "php" is not defined.

I have Google that online but I have not found any good solutions.
I really hope to find a solution to my issue.


问:
Mysql MIN() Max() function with JOIN and GROUP BY
i have a problem, i need to find MIN() and MAX() with JOIN and GROUP BY with Mysql.

I have 3 tables :

Parent(parent_id)

Child(child_id, parent_id)

Price(price_id, child_id, price)

One parent can have many childs, and a child has only one price.

Here is my query to get all prices of a Parent:

```<code>select   child.parent_id ,  price.child_id  , price.price
from parent
 inner join  child on child.parent_id = parent.id
 inner join price on price.child_id = child.id
</code>```

I want to find the min price of a Parent. But i don't want only the price, i want the price_id !

Can you help me to make this query to find the price_id of the min() price of each parent ?

Here are data samples :

```<code>parent1 : parent_id=1
parent2 : parent_id=2

child1 : child_id=1 , parent_id=1
child2 : child_id=2 , parent_id=1
child3 : child_id=3 , parent_id=1

child4 : child_id=4 , parent_id=2
child5 : child_id=5 , parent_id=2
child6 : child_id=6 , parent_id=2

price1 : price_id=1 , child_id=1, price=15
price2 : price_id=2 , child_id=2, price=5
price3 : price_id=3 , child_id=3, price=10

price4 : price_id=4 , child_id=4, price=10
price5 : price_id=5 , child_id=5, price=20
price6 : price_id=6 , child_id=6, price=30
</code>```

I want to find for parent1 the id of the min price of his childs, the result is : price_id=2

I want to find for parent2 the id of the min price of his childs, the result is : price_id=4

I want to find for parent1 the id of the MAX price of his childs, the result is : price_id=1

I want to find for parent2 the id of the MAX price of his childs, the result is : price_id=6

Thank you !

答:
You need  some cinner join on selected  table

```<code>  select distinct  t.parent_id, price.price_id
  from price
  inner join child on price.child_id = child.child_id
  inner join (
      select
      parent.parent_id
      min(price) min_price
    from parent
    inner join child on parent.parent_id = child.parent_id
    inner join price on price.child_id = child.child_id
    group by parent.parent_id ) t on t.min_price = price.price
            and t.parent_id = child.parent_id
</code>```

and looking to your result

then group by the result

```<code>    select parent_id, min(price_id), price from (
    select distinct  t.parent_id, price.price_id, price.price
      from price
      inner join child on price.child_id = child.child_id
      inner join (
          select
          parent.parent_id
          min(price) min_price
        from parent
        inner join child on parent.parent_id = child.parent_id
        inner join price on price.child_id = child.child_id
        group by parent.parent_id ) t on t.min_price = price.price
                and t.parent_id = child.parent_id

    ) t
    group by arent_id, price
</code>```

Body:
i have a problem, i need to find MIN() and MAX() with JOIN and GROUP BY with Mysql.

I have 3 tables :

Parent(parent_id)

Child(child_id, parent_id)

Price(price_id, child_id, price)

One parent can have many childs, and a child has only one price.

Here is my query to get all prices of a Parent:

select   child.parent_id ,  price.child_id  , price.price
from parent
 inner join  child on child.parent_id = parent.id
 inner join price on price.child_id = child.id

I want to find the min price of a Parent. But i don't want only the price, i want the price_id !

Can you help me to make this query to find the price_id of the min() price of each parent ?

Here are data samples :

parent1 : parent_id=1
parent2 : parent_id=2

child1 : child_id=1 , parent_id=1
child2 : child_id=2 , parent_id=1
child3 : child_id=3 , parent_id=1

child4 : child_id=4 , parent_id=2
child5 : child_id=5 , parent_id=2
child6 : child_id=6 , parent_id=2

price1 : price_id=1 , child_id=1, price=15
price2 : price_id=2 , child_id=2, price=5
price3 : price_id=3 , child_id=3, price=10

price4 : price_id=4 , child_id=4, price=10
price5 : price_id=5 , child_id=5, price=20
price6 : price_id=6 , child_id=6, price=30

I want to find for parent1 the id of the min price of his childs, the result is : price_id=2

I want to find for parent2 the id of the min price of his childs, the result is : price_id=4

I want to find for parent1 the id of the MAX price of his childs, the result is : price_id=1

I want to find for parent2 the id of the MAX price of his childs, the result is : price_id=6

Thank you !

Body:
You need  some cinner join on selected  table

  select distinct  t.parent_id, price.price_id
  from price
  inner join child on price.child_id = child.child_id
  inner join (
      select
      parent.parent_id
      min(price) min_price
    from parent
    inner join child on parent.parent_id = child.parent_id
    inner join price on price.child_id = child.child_id
    group by parent.parent_id ) t on t.min_price = price.price
            and t.parent_id = child.parent_id

and looking to your result

then group by the result

    select parent_id, min(price_id), price from (
    select distinct  t.parent_id, price.price_id, price.price
      from price
      inner join child on price.child_id = child.child_id
      inner join (
          select
          parent.parent_id
          min(price) min_price
        from parent
        inner join child on parent.parent_id = child.parent_id
        inner join price on price.child_id = child.child_id
        group by parent.parent_id ) t on t.min_price = price.price
                and t.parent_id = child.parent_id

    ) t
    group by arent_id, price


问:
template class specialization : template-id does not match any template declaration
I'm trying to use templates, but couldn't understand what is wrong with below code.

solve.h

```<code>#include "nlp.h"
#include "Ipopt_solve.h"

enum algo_type {IPOPT =1, SQP};

template<int ALG>
class solve
{
public:
    solve()
    {
    }
};

template<>
class solve<IPOPT>
{
public:
    solve(nlp*);

private:
    Ipopt_solve m_ipopt;

};
</code>```

solve.cpp

```<code>template<>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}
</code>```

Ipopt_solve is a sub-class of an abstract class TNLP. Ipopt_solve is initialized with a reference to nlp class.

from main.cpp

```<code>nlp problem(&model);
solve<IPOPT> solution(&problem);
</code>```

I'm getting the error like shown below.

error: template-id 'solve<>' for 'solve<1>::solve(nlp*)' does not match any template declaration
 solve::solve(nlp* problem): m_ipopt(problem)

答:
You should remove template<>, i.e.

```<code>// template <>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}
</code>```

template<> is used for template specialization (for a template); but you're just defining a non-template member function (of a class template specialization). (That's why the compiler complains that the template declaration can't be found.)

Body:
I'm trying to use templates, but couldn't understand what is wrong with below code.

solve.h

#include "nlp.h"
#include "Ipopt_solve.h"

enum algo_type {IPOPT =1, SQP};

template<int ALG>
class solve
{
public:
    solve()
    {
    }
};

template<>
class solve<IPOPT>
{
public:
    solve(nlp*);

private:
    Ipopt_solve m_ipopt;

};

solve.cpp

template<>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}

Ipopt_solve is a sub-class of an abstract class TNLP. Ipopt_solve is initialized with a reference to nlp class.

from main.cpp

nlp problem(&model);
solve<IPOPT> solution(&problem);

I'm getting the error like shown below.

error: template-id 'solve<>' for 'solve<1>::solve(nlp*)' does not match any template declaration
 solve::solve(nlp* problem): m_ipopt(problem)

Body:
You should remove template<>, i.e.

// template <>
solve<IPOPT>::solve(nlp* problem): m_ipopt(problem)
{
}

template<> is used for template specialization (for a template); but you're just defining a non-template member function (of a class template specialization). (That's why the compiler complains that the template declaration can't be found.)


问:
Handling tensorflow session in a class
I'm using tensorflow to predict outputs of a neural network. I have a class where I have described the neural network and I have a main file where the predictions are being made, and based on the results, the weights are updated. However, the predictions seem to be really slow. Here is how my code looks like:

```<code>class NNPredictor():
    def __init__(self):
        self.input = tf.placeholder(...)
        ...
        self.output = (...) #Neural network output
    def predict_output(self, sess, input):
        return sess.run(tf.squeeze(self.output), feed_dict = {self.input: input})
</code>```

Here's how the main file looks like:

```<code>sess = tf.Session()
predictor = NNPredictor()

input = #some initial value
for i in range(iter):
    output = predictor.predict_output(sess, input)
    input = #some function of output
</code>```

However, if I use the following function definition in the class:

```<code>    def predict_output(self):
        return self.output
</code>```

And have the main file as follows:

```<code>sess = tf.Session()
predictor = NNPredictor()

input = #some initial value
output_op = predictor.predict_value()
for i in range(iter):
    output = np.squeeze(sess.run(output_op, feed_dict = {predictor.input: input}))
    input = #some function of output
</code>```

The code runs almost 20-30x faster. I don't seem to understand how things are working here, and I'd like to know what the best practice would be.

答:
This has to do with the underlying memory accesses masked by Python. Here's some sample code to illustrate this idea:

```<code>import time

runs = 10000000

class A:
    def __init__(self):
    self.val = 1

    def get_val(self):
    return self.val

# Using method to then call object attribute
obj = A()
start = time.time()
total = 0
for i in xrange(runs):
    total += obj.get_val()
end = time.time()
print end - start

# Using object attribute directly
start = time.time()
total = 0
for i in xrange(runs):
    total += obj.val
end = time.time()
print end - start

# Assign to local_var first
start = time.time()
total = 0
local_var = obj.get_val()
for i in xrange(runs):
    total += local_var
end = time.time()
print end - start
</code>```

On my computer, it runs in the following timing:

```<code>1.49576115608
0.656110048294
0.551875114441
</code>```

Specific to your case, you're calling the object method in the first case but not doing it in the second case. If you're calling your code many times in this way, there would be significant performance differences.

Title: Handling tensorflow session in a class

Body:
I'm using tensorflow to predict outputs of a neural network. I have a class where I have described the neural network and I have a main file where the predictions are being made, and based on the results, the weights are updated. However, the predictions seem to be really slow. Here is how my code looks like:

class NNPredictor():
    def __init__(self):
        self.input = tf.placeholder(...)
        ...
        self.output = (...) #Neural network output
    def predict_output(self, sess, input):
        return sess.run(tf.squeeze(self.output), feed_dict = {self.input: input})

Here's how the main file looks like:

sess = tf.Session()
predictor = NNPredictor()

input = #some initial value
for i in range(iter):
    output = predictor.predict_output(sess, input)
    input = #some function of output

However, if I use the following function definition in the class:

    def predict_output(self):
        return self.output

And have the main file as follows:

sess = tf.Session()
predictor = NNPredictor()

input = #some initial value
output_op = predictor.predict_value()
for i in range(iter):
    output = np.squeeze(sess.run(output_op, feed_dict = {predictor.input: input}))
    input = #some function of output

The code runs almost 20-30x faster. I don't seem to understand how things are working here, and I'd like to know what the best practice would be.

Body:
This has to do with the underlying memory accesses masked by Python. Here's some sample code to illustrate this idea:

import time

runs = 10000000

class A:
    def __init__(self):
    self.val = 1

    def get_val(self):
    return self.val

# Using method to then call object attribute
obj = A()
start = time.time()
total = 0
for i in xrange(runs):
    total += obj.get_val()
end = time.time()
print end - start

# Using object attribute directly
start = time.time()
total = 0
for i in xrange(runs):
    total += obj.val
end = time.time()
print end - start

# Assign to local_var first
start = time.time()
total = 0
local_var = obj.get_val()
for i in xrange(runs):
    total += local_var
end = time.time()
print end - start

On my computer, it runs in the following timing:

1.49576115608
0.656110048294
0.551875114441

Specific to your case, you're calling the object method in the first case but not doing it in the second case. If you're calling your code many times in this way, there would be significant performance differences.


问:
Ionic Create Project Error - Cannot find module
When I create ionic project with below command, I got a error

Command : ionic start --v2 myApp tabs

Error: Cannot find module 'C:\Users\İbrahim Aker\AppData\Roaming\npm\ode_modules\ionic\bin\ionic'

I noticed that try to find path "ode_modules", but ionic path is "node_modules"

How can I solve this problem

thank you

答:
Your windows user name causing this problem because it has non-English character('İ'). You can solve this with creating new windows user.
For example :Ibrahim

'C:\Users\Ibrahim Aker\AppData\Roaming\npm\node_modules\ionic\bin\ionic'


问:
Oracle SQL: error not a single-group group function in Select with Xmlagg
I have a table setup that returns multiple rows of column i.AIN for each column p.S_ID so I am trying to aggregate these to get just one row for each unique i.AIN record.

I cannot use Listagg as I am exceeding the character limit there.

With information from this website I created the below query but I get the following error:

```<code>"ORA-00937: not a single-group group function"
</code>```

Can someone tell me how I have to change my GROUP BY here to make this work or if there is anything else wrong with my query ?

My query (shortened):

```<code>ALTER SESSION ENABLE PARALLEL QUERY;
SELECT
    p.S_ID AS ID
    , XMLELEMENT
    (
        "AINs", XMLAGG
        (
            XMLELEMENT
            (
                "AIN", i.AIN ||
                '-nl-Article: ' || SUBSTR(a.AIN_NAME, 1, 50) || '...' ||
                '-nl-Quantity: ' || SUM(i.UNITS) ||
                '-nl-Price: ' || TO_CHAR(i.PRICE, 'FM9,990.00') || ' + ' || TO_CHAR(i.PRICE_TAX, 'FM9,990.00') || ' USt = ' || TO_CHAR((i.PRICE + i.PRICE_TAX), 'FM9,990.00') ||
                '-nl------' ||
                '-nl-Subtotal: ' || TO_CHAR((i.PRICE * SUM(i.UNITS)), 'FM9,990.00') || ' + ' || TO_CHAR((i.PRICE_TAX * SUM(i.UNITS)), 'FM9,990.00') || ' USt = ' || TO_CHAR(((i.PRICE + i.PRICE_TAX) * SUM(i.UNITS)), 'FM9,990.00')
            )
        )
    )/*.EXTRACT('//text()')*/ AS Details
FROM
    ITEMS i
LEFT JOIN
    AINS a
    ON i.AIN = a.AIN
LEFT JOIN
    PKGS p
    ON i.SHIPMENT = p.SHIPMENT
WHERE
    /*...*/
GROUP BY
    p.S_ID
    , i.AIN
    , a.AIN_NAME
    , i.UNITS
    , i.PRICE
    , i.PRICE_TAX
ORDER BY
    p.S_ID
</code>```

Many thanks for any help with this - it is much appreciated,

Mike

答:
Without real data and tables, it is difficult to provide working an example.
You have to split your aggregation in two level. First, create inline view and calculate subtotals, and in next level aggregate results into one string.</p>

```<code>  select xmlagg(....
            )
            from (
            select i.AIN as ain,  SUBSTR(a.AIN_NAME, 1, 50) as ain_name
                , SUM(i.UNITS) sum_units
                , TO_CHAR(max(i.PRICE), 'FM9,990.00') || ' + ' || TO_CHAR(max(i.PRICE_TAX), 'FM9,990.00') || ' USt = ' || TO_CHAR((max(i.PRICE) + max(i.PRICE_TAX)), 'FM9,990.00')
               ... etc
               from /*joins*/
               GROUP BY
              p.S_ID
            , i.AIN
            , a.AIN_NAME

            )
</code>```

Body:
I have a table setup that returns multiple rows of column i.AIN for each column p.S_ID so I am trying to aggregate these to get just one row for each unique i.AIN record.

I cannot use Listagg as I am exceeding the character limit there.

With information from this website I created the below query but I get the following error:

"ORA-00937: not a single-group group function"

Can someone tell me how I have to change my GROUP BY here to make this work or if there is anything else wrong with my query ?

My query (shortened):

ALTER SESSION ENABLE PARALLEL QUERY;
SELECT
    p.S_ID AS ID
    , XMLELEMENT
    (
        "AINs", XMLAGG
        (
            XMLELEMENT
            (
                "AIN", i.AIN ||
                '-nl-Article: ' || SUBSTR(a.AIN_NAME, 1, 50) || '...' ||
                '-nl-Quantity: ' || SUM(i.UNITS) ||
                '-nl-Price: ' || TO_CHAR(i.PRICE, 'FM9,990.00') || ' + ' || TO_CHAR(i.PRICE_TAX, 'FM9,990.00') || ' USt = ' || TO_CHAR((i.PRICE + i.PRICE_TAX), 'FM9,990.00') ||
                '-nl------' ||
                '-nl-Subtotal: ' || TO_CHAR((i.PRICE * SUM(i.UNITS)), 'FM9,990.00') || ' + ' || TO_CHAR((i.PRICE_TAX * SUM(i.UNITS)), 'FM9,990.00') || ' USt = ' || TO_CHAR(((i.PRICE + i.PRICE_TAX) * SUM(i.UNITS)), 'FM9,990.00')
            )
        )
    )/*.EXTRACT('//text()')*/ AS Details
FROM
    ITEMS i
LEFT JOIN
    AINS a
    ON i.AIN = a.AIN
LEFT JOIN
    PKGS p
    ON i.SHIPMENT = p.SHIPMENT
WHERE
    /*...*/
GROUP BY
    p.S_ID
    , i.AIN
    , a.AIN_NAME
    , i.UNITS
    , i.PRICE
    , i.PRICE_TAX
ORDER BY
    p.S_ID

Many thanks for any help with this - it is much appreciated,

Mike

Body:
Without real data and tables, it is difficult to provide working an example.
You have to split your aggregation in two level. First, create inline view and calculate subtotals, and in next level aggregate results into one string.

  select xmlagg(....
            )
            from (
            select i.AIN as ain,  SUBSTR(a.AIN_NAME, 1, 50) as ain_name
                , SUM(i.UNITS) sum_units
                , TO_CHAR(max(i.PRICE), 'FM9,990.00') || ' + ' || TO_CHAR(max(i.PRICE_TAX), 'FM9,990.00') || ' USt = ' || TO_CHAR((max(i.PRICE) + max(i.PRICE_TAX)), 'FM9,990.00')
               ... etc
               from /*joins*/
               GROUP BY
              p.S_ID
            , i.AIN
            , a.AIN_NAME

            )


问:
How to pass String From IntentService To Activity
How to pass String From IntentService To Activity.

MyService.java

```<code>protected void onHandleIntent(Intent intent) {

   String abc ="XYZ"; // pass this string to Activity class
}
</code>```

Activity is same which is calling Service class.

答:
Use ResultReceiver class to send data from IntentService to Activity.
Please refer this link.
How to get results from an IntentService back into an Activity?</p>

Body:
How to pass String From IntentService To Activity.

MyService.java

protected void onHandleIntent(Intent intent) {

   String abc ="XYZ"; // pass this string to Activity class
}

Activity is same which is calling Service class.


问:
How to feed multiple inputs through feed_dict in tensorflow
I have a network consist of multiple sub-network (multiple convolution net and at last one fully connected + soft max layer). Every ConvNet feed with specific region and size of images. so, to feed my network I write image place holder for every convnet input and one label place holder to feed label of all images in one batch (all of the input images in all convnet inputs have the same labels).
Unfortunately I don't have any idea for feed_dict part.
for example this code is for only one convnet training:

```<code>    images_r, labels_r = sess.run([images, labels])
    train_feed = {images_placeholder: images_r,
              labels_placeholder: labels_r}
    _, loss_value = sess.run([train_op, loss_func], feed_dict=train_feed)
</code>```

How can I extend above code for feed all conv nets?

答: You should split/slice your images inside computation graph and use a single input instead.</p>

Body:
I have a network consist of multiple sub-network (multiple convolution net and at last one fully connected + soft max layer). Every ConvNet feed with specific region and size of images. so, to feed my network I write image place holder for every convnet input and one label place holder to feed label of all images in one batch (all of the input images in all convnet inputs have the same labels).
Unfortunately I don't have any idea for feed_dict part.
for example this code is for only one convnet training:

    images_r, labels_r = sess.run([images, labels])
    train_feed = {images_placeholder: images_r,
              labels_placeholder: labels_r}
    _, loss_value = sess.run([train_op, loss_func], feed_dict=train_feed)

How can I extend above code for feed all conv nets?


答:
You could replace your code by this</p>

```<code>var result = '';
myjsonstring.forEach(function(obj) {
    result = result + obj.Key + " - " + obj.Value + "\n";
});
</code>```

Title: Format a Json string from server side in jquery client side

Body:
You could replace your code by this

var result = '';
myjsonstring.forEach(function(obj) {
    result = result + obj.Key + " - " + obj.Value + "\n";
});


问:
AutoMapper returns NULL when returning a list
Code without AutoMapper:

List<CountryDM> countryDMList = _countryRepo.GetCountry();
List<CountryVM> countryVMList = new List<CountryVM>();
foreach (CountryDM countryDM in countryDMList)
{
    countryVMList.Add(CountryVM.ToViewModel(countryDM));
}
return countryVMList;
```

<p>I used AutoMapper for the above task. But it returns a <code>NULL</code> list. Please refer the below code:</p>

<pre class="lang-cs prettyprint-override"><code>List<CountryDM> countryDMList = _countryRepo.GetCountry();
Mapper.CreateMap<List<CountryDM>, List<CountryVM>>();
List<CountryVM> countryVMList = new List<CountryVM>();
return Mapper.Map<List<CountryVM>>(countryDMList);

public class CountryDM
{
    public int ID { get; set; }
    public string CountryCode { get; set; }
    public string Description { get; set; }
}

public class CountryVM
{
    public int ID { get; set; }
    public string CountryCode { get; set; }
    public string Description { get; set; }
}
</code>```

答:
You don't need to define a mapping between lists, just between objects, AutoMapper will know how to extrapolate that:

Mapper.CreateMap<CountryDM, CountryVM>();
```

the rest stays the same

Body:
Code without AutoMapper:

List<CountryDM> countryDMList = _countryRepo.GetCountry();
List<CountryVM> countryVMList = new List<CountryVM>();
foreach (CountryDM countryDM in countryDMList)
{
    countryVMList.Add(CountryVM.ToViewModel(countryDM));
}
return countryVMList;

I used AutoMapper for the above task. But it returns a NULL list. Please refer the below code:

List<CountryDM> countryDMList = _countryRepo.GetCountry();
Mapper.CreateMap<List<CountryDM>, List<CountryVM>>();
List<CountryVM> countryVMList = new List<CountryVM>();
return Mapper.Map<List<CountryVM>>(countryDMList);

public class CountryDM
{
    public int ID { get; set; }
    public string CountryCode { get; set; }
    public string Description { get; set; }
}

public class CountryVM
{
    public int ID { get; set; }
    public string CountryCode { get; set; }
    public string Description { get; set; }
}

Body:
You don't need to define a mapping between lists, just between objects, AutoMapper will know how to extrapolate that:

Mapper.CreateMap<CountryDM, CountryVM>();

the rest stays the same


问:
Python: How to create log file everyday using logging module?
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.

```<code>log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59
</code>```

On next day I want to create a new log file with next day's date -

```<code>log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59
</code>```

I'm using logging module of python.

I'm using like below -

```<code>log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)
</code>```

Is their any configurations in logging module of python to create a log on daily basis?

答:
Finally, I got the correct answer and I want to share this answer.

Basically, need to create a TimedRotatingFileHandler like below -

```<code>log_format = "%(asctime)s - %(levelname)s - %(message)s"
log_level = 10
handler = TimedRotatingFileHandler("my_app.log", when="midnight", interval=1)
handler.setLevel(log_level)
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)

# add a suffix which you want
handler.suffix = "%Y%m%d"

#need to change the extMatch variable to match the suffix for it
handler.extMatch = re.compile(r"^\d{8}$")

# finally add handler to logger
logger.addHandler(handler)
</code>```

This above code will generate file like my_app.log for current day and my_app.log.20170704 for previous day.

Hope it helps.

Body:
I'm new to logging module of python. I want to create a new log file everyday while my application is in running condition.

log file name - my_app_20170622.log
log file entries within time - 00:00:01 to 23:59:59

On next day I want to create a new log file with next day's date -

log file name - my_app_20170623.log
log file entries within time - 00:00:01 to 23:59:59

I'm using logging module of python.

I'm using like below -

log_level = int(log_level)
logger = logging.getLogger('simple')
logger.setLevel(log_level)
fh = logging.FileHandler(log_file_name)
fh.setLevel(log_level)
formatter = logging.Formatter(log_format)
fh.setFormatter(formatter)
logger.addHandler(fh)

Is their any configurations in logging module of python to create a log on daily basis?

Body:
Finally, I got the correct answer and I want to share this answer.

Basically, need to create a TimedRotatingFileHandler like below -

log_format = "%(asctime)s - %(levelname)s - %(message)s"
log_level = 10
handler = TimedRotatingFileHandler("my_app.log", when="midnight", interval=1)
handler.setLevel(log_level)
formatter = logging.Formatter(log_format)
handler.setFormatter(formatter)

# add a suffix which you want
handler.suffix = "%Y%m%d"

#need to change the extMatch variable to match the suffix for it
handler.extMatch = re.compile(r"^\d{8}$")

# finally add handler to logger
logger.addHandler(handler)

This above code will generate file like my_app.log for current day and my_app.log.20170704 for previous day.

Hope it helps.


问:
html picture element not honoring small media query
I've got a thing like this:

```<code><picture>
  <source media="(min-width:1200)" srcset="big.jpg">
  <source media="(min-width:840)" srcset="small.jpg">
  <img srcset="big.jpg" alt="Test" />
</picture>
</code>```

I'm also using picturefill.

My issue is that both firefox and chrome (the 2 I'm currently testing on), will load only big.jpg, even in small screens. Checked also on console's network trace.

My css sets img as basic fluid:

```<code>img{
  display: block;
  max-width: 100%;
  height:auto;
}
</code>```

So what's wrong in my code?

答:
As for I haz kode's comment, the answer is: my code lacked unit declaration in media queries.

As for completeness, I also write here a better code for my use case: having a default image for small screens and different one from 840px up.

```<code><picture>
  <source media="(min-width:840px)" srcset="big.jpg">
  <img srcset="small.jpg" alt="Foradori">
</picture>
</code>```

This will work correctly and download only the right image for the current breakpoint.
Also remember we need picturefill to ensure crossbrowser support.

Body:
I've got a thing like this:

<picture>
  <source media="(min-width:1200)" srcset="big.jpg">
  <source media="(min-width:840)" srcset="small.jpg">

</picture>

I'm also using picturefill.

My issue is that both firefox and chrome (the 2 I'm currently testing on), will load only big.jpg, even in small screens. Checked also on console's network trace.

My css sets img as basic fluid:

img{
  display: block;
  max-width: 100%;
  height:auto;
}

So what's wrong in my code?

Body:
As for I haz kode's comment, the answer is: my code lacked unit declaration in media queries.

As for completeness, I also write here a better code for my use case: having a default image for small screens and different one from 840px up.

<picture>
  <source media="(min-width:840px)" srcset="big.jpg">
  <img srcset="small.jpg" alt="Foradori">
</picture>

This will work correctly and download only the right image for the current breakpoint.
Also remember we need picturefill to ensure crossbrowser support.


问:
Are modern GPUs considered to be RISC based or CISC based?
I'm trying to figure out if modern GPUs have a reduced instruction set, or a complex instruction set.

Wikipedia says that it's not the size of the instruction set, rather how many cycles it takes to complete an instruction.

In RISC processors, each instruction can be completed in one cycle.

In CISC processors, it takes several cycles to complete some instructions.

I'm trying to figure out what the case is for modern GPUs.

答:
RISC instruction set : the load/store unit is independent from other units so basically for loading and storing specific instruction are used

CISC insruction set : the ad/store unit in embedded in the instrction execution routine , therfore the instruction is more comlex than RISC instruction because CISC instruction beside the operation it will perform the load and store stage and this require more transistor logic to be used for one ibstruction

ContentLicense: CC BY-SA 4.0


问:
How do I make a Mahalanobis distance matrix in MATLAB?
I have a data set with 5 repeats for each sample and 25 variables.
I am trying to make a Mahalanobis distance matrix between all of the samples using these parameters. I used the "mahal" function, but this gives a vector of all of the distances for each repeat. How can I make a matrix of distances between samples (38*38) and not a vector (1*190)?

答:
For some test data:

```<code>X = rand(38,25); % some random test data with 38 observations and 25 variables
X = repmat(X,5,1); % 5 duplicates of each observation
</code>```

You could use:

```<code>X = unique(X,'rows'); % remove duplicate observations
D = pdist(X,'mahalanobis'); % distance between all remaining observations
Z = squareform(D); % to square matrix format
</code>```

Body:
For some test data:

X = rand(38,25); % some random test data with 38 observations and 25 variables
X = repmat(X,5,1); % 5 duplicates of each observation

You could use:

X = unique(X,'rows'); % remove duplicate observations
D = pdist(X,'mahalanobis'); % distance between all remaining observations
Z = squareform(D); % to square matrix format


问:
Angular 4: Infinite scroll not working
I have tried using ngx-infinite-scroll (https://www.npmjs.com/package/angular2-infinite-scroll) and also some other directives but none seem to work.

package.json

```<code>"dependencies": {
"@angular/animations": "^4.0.2",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/compiler-cli": "^4.0.2",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/platform-server": "^4.0.2",
"@angular/router": "^4.0.0",
"absurd": "^0.3.8",
"angular2-masonry": "^0.4.0",
"animate.css": "^3.5.2",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"font-awesome": "^4.7.0",
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"metismenu": "^2.7.0",
"ng2-bs3-modal": "^0.10.4",
"ngx-infinite-scroll": "^0.5.1",
"rxjs": "^5.1.0"
}
</code>```

user.component.html

```<code><div class="row" infiniteScroll [infiniteScrollDistance]="0"
  [infiniteScrollThrottle]="300" (scrolled)="loadMore()">
   <div class="col-md-3 col-sm-4" *ngFor="let user of userList">
     <span>{{user.name}} ({{user.email}})</span>
   </div>
</div>
</code>```

user.module.ts

The import is done

```<code>import { InfiniteScrollModule } from 'ngx-infinite-scroll';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    InfiniteScrollModule
  ],
  declarations: [UserComponent],
  providers: [],
  exports: [],
})
export class UserModule { }
</code>```

user.component.ts

```<code>export class UserComponent {

  constructor() {}

  loadMore() {
    console.log('method begins');
  }
}
</code>```

Tried using host listener as well but the scroll event just doesn't seem to occur.
Has it got anything to do with the class i'm using on which the infinite scroll is applied?

答:
Inside the document has mentioned about.

By default, the directive listens to the window scroll event and
  invoked the callback. To trigger the callback when the actual element
  is scrolled, these settings should be configured:

[scrollWindow]="false"

set an explict css "height" value to the element

Therefore, just put the height: 100% on your container and you will see the scrolled fired.

```<code>import { Component } from '@angular/core';

@Component({
    selector: 'app',
    styles: [
        `.search-results {
            height: 20rem;
            overflow: scroll;
        }`
    ],
    template: `
        <div class="search-results"
            infiniteScroll
            [infiniteScrollDistance]="2"
            [infiniteScrollThrottle]="500"
            (scrolled)="onScroll()"
            [scrollWindow]="false">
        </div>
    `
})
export class AppComponent {
    onScroll () {
        console.log('scrolled!!')
    }
}
</code>```

Title: Angular 4: Infinite scroll not working

Body:
I have tried using ngx-infinite-scroll (https://www.npmjs.com/package/angular2-infinite-scroll) and also some other directives but none seem to work.

package.json

"dependencies": {
"@angular/animations": "^4.0.2",
"@angular/common": "^4.0.0",
"@angular/compiler": "^4.0.0",
"@angular/compiler-cli": "^4.0.2",
"@angular/core": "^4.0.0",
"@angular/forms": "^4.0.0",
"@angular/http": "^4.0.0",
"@angular/platform-browser": "^4.0.0",
"@angular/platform-browser-dynamic": "^4.0.0",
"@angular/platform-server": "^4.0.2",
"@angular/router": "^4.0.0",
"absurd": "^0.3.8",
"angular2-masonry": "^0.4.0",
"animate.css": "^3.5.2",
"bootstrap": "^3.3.7",
"core-js": "^2.4.1",
"font-awesome": "^4.7.0",
"jquery": "^3.2.1",
"jquery-slimscroll": "^1.3.8",
"metismenu": "^2.7.0",
"ng2-bs3-modal": "^0.10.4",
"ngx-infinite-scroll": "^0.5.1",
"rxjs": "^5.1.0"
}

user.component.html

     {{user.name}} ({{user.email}})

user.module.ts

The import is done

import { InfiniteScrollModule } from 'ngx-infinite-scroll';

@NgModule({
  imports: [
    CommonModule,
    FormsModule,
    InfiniteScrollModule
  ],
  declarations: [UserComponent],
  providers: [],
  exports: [],
})
export class UserModule { }

user.component.ts

export class UserComponent {

  constructor() {}

  loadMore() {
    console.log('method begins');
  }
}

Tried using host listener as well but the scroll event just doesn't seem to occur.
Has it got anything to do with the class i'm using on which the infinite scroll is applied?

Body:
Inside the document has mentioned about.

By default, the directive listens to the window scroll event and
  invoked the callback. To trigger the callback when the actual element
  is scrolled, these settings should be configured:

[scrollWindow]="false"

set an explict css "height" value to the element

Therefore, just put the height: 100% on your container and you will see the scrolled fired.

import { Component } from '@angular/core';

@Component({
    selector: 'app',
    styles: [
        `.search-results {
            height: 20rem;
            overflow: scroll;
        }`
    ],
    template: `
        <div class="search-results"
            infiniteScroll
            [infiniteScrollDistance]="2"
            [infiniteScrollThrottle]="500"
            (scrolled)="onScroll()"
            [scrollWindow]="false">
        </div>
    `
})
export class AppComponent {
    onScroll () {
        console.log('scrolled!!')
    }
}


问:
Is there any alternate to acquire dependencies without using POM.xml?
My question is, I don't want to write XML code for dependencies in the POM.xml again and again.
For example, I want to use the log4j JAR in my project. instead of writing XML code is there any option to download the related JAR files?

答:
First you could download jars you need in your project from corresponding websites.

Next,follow the steps below:

Step 1： Create a folder under the project to save the JAR package.We usually store jar packages from the outside in the [lib] folder.

Step 2: Copy the jar to the lib folder.

Step 3: Right-click on the project name, and select it in turn [Build Path] - > [Configure Build Path...]

Step 4: In the open window, select the Libraries page and click on the right button the [add JARs...] then select the jar package we just copied into the project, and then click [OK] to close the window.

Finally, we can use this jar package in Eclipse


问:
Xamarin iOS: BackgroundTask, Do I need to set task object to invalid
I am using the background task. The task working fine but will force close at some point. I have test application and keep it open for whole afternoon, if I remove the background task I have in the code, the crash didn't happen.

After I looked closely, probably missing a line of code to assign the task object invalid.

```<code>var siteId = Settings.CurrentSiteId;
        if (siteId > 0 && !(new EntityBLL().IsInitial(siteId)))
        {
            var task = nint.MinValue;
            task = UIApplication.SharedApplication.BeginBackgroundTask("bgEntityDownload", () =>
            {
                ServerEntity.TerminateAutoDownload(true);
                UIApplication.SharedApplication.EndBackgroundTask(task);
                task = UIApplication.BackgroundTaskInvalid;

                completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
            });

            AppLogger.Instance.AddLog(AppLogLevel.Information,
                                      nameof(TimerDownload),
                                      nameof(DownloadEntityFromServer),
                                      "Background download starts", "");

            var result = await ServerEntity.AutoDownload(siteId);
            UIApplication.SharedApplication.EndBackgroundTask(task);
            task = UIApplication.BackgroundTaskInvalid;

            completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
        }
</code>```

The line here :

```<code>var result = await ServerEntity.AutoDownload(siteId);
            UIApplication.SharedApplication.EndBackgroundTask(task);
            task = UIApplication.BackgroundTaskInvalid;
</code>```

Is the line with task = UIApplicaition.BackgroundTaskInvalid is required after the work done.

答: It's not required, but a good practice that allows a system to spend its resources on different processes. Your background task will be force terminated after 180 seconds. </p>

Body:
I am using the background task. The task working fine but will force close at some point. I have test application and keep it open for whole afternoon, if I remove the background task I have in the code, the crash didn't happen.

After I looked closely, probably missing a line of code to assign the task object invalid.

var siteId = Settings.CurrentSiteId;
        if (siteId > 0 && !(new EntityBLL().IsInitial(siteId)))
        {
            var task = nint.MinValue;
            task = UIApplication.SharedApplication.BeginBackgroundTask("bgEntityDownload", () =>
            {
                ServerEntity.TerminateAutoDownload(true);
                UIApplication.SharedApplication.EndBackgroundTask(task);
                task = UIApplication.BackgroundTaskInvalid;

                completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
            });

            AppLogger.Instance.AddLog(AppLogLevel.Information,
                                      nameof(TimerDownload),
                                      nameof(DownloadEntityFromServer),
                                      "Background download starts", "");

            var result = await ServerEntity.AutoDownload(siteId);
            UIApplication.SharedApplication.EndBackgroundTask(task);
            task = UIApplication.BackgroundTaskInvalid;

            completionHandler?.Invoke(UIBackgroundFetchResult.NewData);
        }

The line here :

var result = await ServerEntity.AutoDownload(siteId);
            UIApplication.SharedApplication.EndBackgroundTask(task);
            task = UIApplication.BackgroundTaskInvalid;

Is the line with task = UIApplicaition.BackgroundTaskInvalid is required after the work done.


问:
Qt QQmlApplicationEngine refuse to display qml code
I have this pro file

```<code>QT += qml quick widgets
TARGET = sPassKeeper
include(src/src.pri)
include(qml/qml.pri)
RESOURCES += \
    resources.qrc
</code>```

in src pri and qml pri only single lines
qml.pri

```<code>OTHER_FILES += \
    qml/main.qml
</code>```

src.pri

```<code>SOURCES += \
    src/main.cpp
</code>```

In main.cpp got this code

```<code>#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtDebug>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine(QUrl("qrc:/new/prefix1/qml/main.qml"));
    qDebug() << "Ok engine created";
//    Q_UNUSED(engine)
    return app.exec();
}
</code>```

main.qml

```<code>import QtQuick 2.0
import QtQuick.Controls 1.1

ApplicationWindow{
    title: "sPassKeeper"
    Button{
        text: "Hello"
    }
}
</code>```

As a result got this output

QML debugging is enabled. Only use this in a safe environment. Ok
  engine created

Nothing displayed and process is not completed.

答:
If you want to display root object (Window or ApplicationWindow) in foolscreen mode, then you may do the following:

```<code>import QtQuick.Window 2.3
import QtQuick.Controls 2.2

ApplicationWindow {
    visible: true
    visibility: Window.FullScreen
}
</code>```

Possible useful values for visibility are: Window.FullScreen and Window.Windowed.

Body:
I have this pro file

QT += qml quick widgets
TARGET = sPassKeeper
include(src/src.pri)
include(qml/qml.pri)
RESOURCES += \
    resources.qrc

in src pri and qml pri only single lines
qml.pri

OTHER_FILES += \
    qml/main.qml

src.pri

SOURCES += \
    src/main.cpp

In main.cpp got this code

#include <QApplication>
#include <QQmlApplicationEngine>
#include <QtDebug>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);
    QQmlApplicationEngine engine(QUrl("qrc:/new/prefix1/qml/main.qml"));
    qDebug() << "Ok engine created";
//    Q_UNUSED(engine)
    return app.exec();
}

main.qml

import QtQuick 2.0
import QtQuick.Controls 1.1

ApplicationWindow{
    title: "sPassKeeper"
    Button{
        text: "Hello"
    }
}

As a result got this output

QML debugging is enabled. Only use this in a safe environment. Ok
  engine created

Nothing displayed and process is not completed.

Body:
If you want to display root object (Window or ApplicationWindow) in foolscreen mode, then you may do the following:

import QtQuick.Window 2.3
import QtQuick.Controls 2.2

ApplicationWindow {
    visible: true
    visibility: Window.FullScreen
}

Possible useful values for visibility are: Window.FullScreen and Window.Windowed.


问:
How can i read data from LAN port and display on applet?
Basically.. I can read my data from LAN port when i am running from command promp.

```<code>javac XYZ.java
appletviewer XYZ.html
</code>```

This is work on My computer. I can read data and display on my applet.

But When I am Uploading my applet on ASPX page and run. It is load and running. But it is not diplay data read from port.

This is my code:

```<code>import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.*;

import java.net.*;

public class FCApplet extends JApplet implements ActionListener , Runnable
{
    Thread th = new Thread(this);
    TextField txtID,txtName,txtResult;
    Label lblID,lblName,lblResult;

    String MemberID;
    Panel p2;

    public void init()
    {
        setBackground(Color.decode("#BFBFBF"));
        lblID = new Label(" ID ");
        lblID.setFont(new Font("Verdana", Font.BOLD , 12));
        txtID= new TextField();

        lblName= new Label(" Name ");
        lblName.setFont(new Font("Verdana", Font.BOLD , 12));
        txtName= new TextField();

        lblResult= new Label(" Result ");
        lblResult.setFont(new Font("Verdana", Font.BOLD , 12));
        txtResult= new TextField();

        Button b = new Button("Connect");
        b.setFont(new Font("Verdana", Font.BOLD , 12));
        b.addActionListener(this);

        p2=new Panel();
                    p2.setLayout(new GridLayout(1,10,5,5));
        p2.setPreferredSize(new Dimension(900, 20));
                    p2.add(lblID);
                  p2.add(txtID);
                p2.add(lblName);
                  p2.add(txtName);
        p2.add(lblResult);
                  p2.add(txtResult);
                  p2.add(b);

        GridBagLayout gbl = new GridBagLayout();
        setLayout(gbl);
            GridBagConstraints c = new GridBagConstraints();
            c.anchor = GridBagConstraints.WEST;
            c.fill=GridBagConstraints.HORIZONTAL;
            c.insets = new Insets(10,10,10,10);
        c.fill=GridBagConstraints.HORIZONTAL;
            c.gridy=1;
            gbl.setConstraints(p2,c);
        add(p2);
    }
    public void StartTest()
    {
        DatagramSocket sock = null;
        try
                {
                    //1. creating a server socket, parameter is local port number
                    sock = new DatagramSocket(8001);

                    //buffer to receive incoming data
                    byte[] buffer = new byte[65536];
                    DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

                    //2. Wait for an incoming data
                    System.out.println("Server socket created. Waiting for incoming data...");

                    //communication loop
                    while(true)
                    {
                        sock.receive(incoming);
                        byte[] data = incoming.getData();
                        String s = new String(data, 0, incoming.getLength());

                        //echo the details of incoming data - client ip : client port - client message
                        System.out.println(incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " : " + s);

              if(s != "" )
             {

                String R = incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " : " + s;
                //lblResultTest.setText(R);
                String[] words = s.split("&");

                txtResult.setText(words[2]);
                this.getAppletContext().showDocument( this.getDocumentBase() );

             }
                        //s = "OK : " + s;
                        //DatagramPacket dp = new DatagramPacket(s.getBytes() , s.getBytes().length , incoming.getAddress() , incoming.getPort());
                        //sock.send(dp);
                        }
        }

                catch(IOException e)
        {
                    System.err.println("IOException " + e);
                }

    }
    public void run()
    {
        try
        {
            Thread.sleep(1000);
        }
        catch(InterruptedException ex)
        {
            Thread.currentThread().interrupt();
        }
    }
    public void actionPerformed(ActionEvent e)
    {
        Button source = (Button)e.getSource();
        if(source.getLabel() == "Connect")
        {
            StartTest();
        }
        else{
            JOptionPane.showMessageDialog(null,"Please Provide Input","alert",JOptionPane.WARNING_MESSAGE);
        }
    }

}
</code>```

Below images is my output from command prompt

enter image description here

enter image description here

Below are web browser output.

[enter image description here][3]

答:
Yes. finally get solution. I had made mistake while creating applet jar file.
after R & D

finally get result successfully.

http://www.pawlan.com/monica/articles/signedapps/

http://www.onjava.com/pub/a/onjava/2001/03/22/plugin.html?page=3

Body:
Basically.. I can read my data from LAN port when i am running from command promp.

javac XYZ.java
appletviewer XYZ.html

This is work on My computer. I can read data and display on my applet.

But When I am Uploading my applet on ASPX page and run. It is load and running. But it is not diplay data read from port.

This is my code:

import javax.swing.JApplet;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.*;
import java.awt.event.*;
import java.applet.*;
import java.awt.*;
import java.util.*;
import java.sql.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.io.*;

import java.net.*;

public class FCApplet extends JApplet implements ActionListener , Runnable
{
    Thread th = new Thread(this);
    TextField txtID,txtName,txtResult;
    Label lblID,lblName,lblResult;

    String MemberID;
    Panel p2;

    public void init()
    {
        setBackground(Color.decode("#BFBFBF"));
        lblID = new Label(" ID ");
        lblID.setFont(new Font("Verdana", Font.BOLD , 12));
        txtID= new TextField();

        lblName= new Label(" Name ");
        lblName.setFont(new Font("Verdana", Font.BOLD , 12));
        txtName= new TextField();

        lblResult= new Label(" Result ");
        lblResult.setFont(new Font("Verdana", Font.BOLD , 12));
        txtResult= new TextField();

        Button b = new Button("Connect");
        b.setFont(new Font("Verdana", Font.BOLD , 12));
        b.addActionListener(this);

        p2=new Panel();
                    p2.setLayout(new GridLayout(1,10,5,5));
        p2.setPreferredSize(new Dimension(900, 20));
                    p2.add(lblID);
                  p2.add(txtID);
                p2.add(lblName);
                  p2.add(txtName);
        p2.add(lblResult);
                  p2.add(txtResult);
                  p2.add(b);

        GridBagLayout gbl = new GridBagLayout();
        setLayout(gbl);
            GridBagConstraints c = new GridBagConstraints();
            c.anchor = GridBagConstraints.WEST;
            c.fill=GridBagConstraints.HORIZONTAL;
            c.insets = new Insets(10,10,10,10);
        c.fill=GridBagConstraints.HORIZONTAL;
            c.gridy=1;
            gbl.setConstraints(p2,c);
        add(p2);
    }
    public void StartTest()
    {
        DatagramSocket sock = null;
        try
                {
                    //1. creating a server socket, parameter is local port number
                    sock = new DatagramSocket(8001);

                    //buffer to receive incoming data
                    byte[] buffer = new byte[65536];
                    DatagramPacket incoming = new DatagramPacket(buffer, buffer.length);

                    //2. Wait for an incoming data
                    System.out.println("Server socket created. Waiting for incoming data...");

                    //communication loop
                    while(true)
                    {
                        sock.receive(incoming);
                        byte[] data = incoming.getData();
                        String s = new String(data, 0, incoming.getLength());

                        //echo the details of incoming data - client ip : client port - client message
                        System.out.println(incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " : " + s);

              if(s != "" )
             {

                String R = incoming.getAddress().getHostAddress() + " : " + incoming.getPort() + " : " + s;
                //lblResultTest.setText(R);
                String[] words = s.split("&");

                txtResult.setText(words[2]);
                this.getAppletContext().showDocument( this.getDocumentBase() );

             }
                        //s = "OK : " + s;
                        //DatagramPacket dp = new DatagramPacket(s.getBytes() , s.getBytes().length , incoming.getAddress() , incoming.getPort());
                        //sock.send(dp);
                        }
        }

                catch(IOException e)
        {
                    System.err.println("IOException " + e);
                }

    }
    public void run()
    {
        try
        {
            Thread.sleep(1000);
        }
        catch(InterruptedException ex)
        {
            Thread.currentThread().interrupt();
        }
    }
    public void actionPerformed(ActionEvent e)
    {
        Button source = (Button)e.getSource();
        if(source.getLabel() == "Connect")
        {
            StartTest();
        }
        else{
            JOptionPane.showMessageDialog(null,"Please Provide Input","alert",JOptionPane.WARNING_MESSAGE);
        }
    }

}

Below images is my output from command prompt

enter image description here

enter image description here

Below are web browser output.

[enter image description here][3]


问:
Creating object throws NullPointerException
I've the below code in Java that throws java.lang.NullPointerException at the line where I create new instance.

```<code>import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

    public static void main(final String... args) {

        Properties seleniumProperties = new Properties();
        seleniumProperties.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        System.setProperties(seleniumProperties);

        WebDriver driver = new FirefoxDriver();

    }

}
</code>```

Line no. 14 is WebDriver driver = new FirefoxDriver(); and here's the stack trace of the exception:

```<code>Exception in thread "main" java.lang.NullPointerException
    at java.lang.String.startsWith(String.java:1405)
    at java.lang.String.startsWith(String.java:1434)
    at java.util.jar.JarFile.isKnownNotToHaveSpecialAttributes(JarFile.java:594)
    at java.util.jar.JarFile.checkForSpecialAttributes(JarFile.java:552)
    at java.util.jar.JarFile.hasClassPathAttribute(JarFile.java:518)
    at java.util.jar.JavaUtilJarAccessImpl.jarFileHasClassPathAttribute(JavaUtilJarAccessImpl.java:37)
    at sun.misc.URLClassPath$JarLoader.getClassPath(URLClassPath.java:1186)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:522)
    at sun.misc.URLClassPath.getNextLoader(URLClassPath.java:484)
    at sun.misc.URLClassPath.getResource(URLClassPath.java:238)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:365)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at Test.main(Test.java:14)
</code>```

答:
I think I found the problem. Using System.setProperties probably removes all crucial properties used by JVM. I replaced the code with System.setProperty as shown below and now it works fine.

```<code>import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

    public static void main(final String... args) {

        /*
        Properties seleniumProperties = new Properties();
        seleniumProperties.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        System.setProperties(seleniumProperties);
        */
        System.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        WebDriver driver = new FirefoxDriver();

    }

}
</code>```

Body:
I've the below code in Java that throws java.lang.NullPointerException at the line where I create new instance.

import java.util.Properties;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

    public static void main(final String... args) {

        Properties seleniumProperties = new Properties();
        seleniumProperties.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        System.setProperties(seleniumProperties);

        WebDriver driver = new FirefoxDriver();

    }

}

Line no. 14 is WebDriver driver = new FirefoxDriver(); and here's the stack trace of the exception:

Exception in thread "main" java.lang.NullPointerException
    at java.lang.String.startsWith(String.java:1405)
    at java.lang.String.startsWith(String.java:1434)
    at java.util.jar.JarFile.isKnownNotToHaveSpecialAttributes(JarFile.java:594)
    at java.util.jar.JarFile.checkForSpecialAttributes(JarFile.java:552)
    at java.util.jar.JarFile.hasClassPathAttribute(JarFile.java:518)
    at java.util.jar.JavaUtilJarAccessImpl.jarFileHasClassPathAttribute(JavaUtilJarAccessImpl.java:37)
    at sun.misc.URLClassPath$JarLoader.getClassPath(URLClassPath.java:1186)
    at sun.misc.URLClassPath.getLoader(URLClassPath.java:522)
    at sun.misc.URLClassPath.getNextLoader(URLClassPath.java:484)
    at sun.misc.URLClassPath.getResource(URLClassPath.java:238)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:365)
    at java.net.URLClassLoader$1.run(URLClassLoader.java:362)
    at java.security.AccessController.doPrivileged(Native Method)
    at java.net.URLClassLoader.findClass(URLClassLoader.java:361)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:424)
    at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:335)
    at java.lang.ClassLoader.loadClass(ClassLoader.java:357)
    at Test.main(Test.java:14)

Body:
I think I found the problem. Using System.setProperties probably removes all crucial properties used by JVM. I replaced the code with System.setProperty as shown below and now it works fine.

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;

public class Test {

    public static void main(final String... args) {

        /*
        Properties seleniumProperties = new Properties();
        seleniumProperties.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        System.setProperties(seleniumProperties);
        */
        System.setProperty("webdriver.gecko.driver", "<PATH_TO_DRIVER>");
        WebDriver driver = new FirefoxDriver();

    }

}


问:
Cookie based authentication doesnt allow access of https secure cookies when working with switching between MVC and single page application
We are following cookie based authentication in the SPA and we have the concept of switching from MVC (OLD SITE) to SPA (NEW SITE) ie: A single sign on concept.

Note: In SPA the navigations are completely built using cookies - Angular 1.5 code.

Everything worked fine when in development and staging which was HTTP. But after release to production which runs as HTTPS on a secure SSL certification, we are not able to read the cookies from the spa that was set by MVC, hence switching is not successful.

Could you suggest what are we missing here, or any quick fix that can do be done so we can access the HTTPS secure  cookies and easily redirect them to dashboard in SPA.

答: I believe your issue is not with cookie being secure, your issue is with cookie being set to 'http only' thus not accessible with client side code (angular). Removing http only from cookie is a quick fix though i would never recommend having auth cookie read from client side code for security reason.</p>


问:
My date-picker is not working
Following is my code....
Whenever i click on input element then date-picker doesn't display. Where I am going wrong??? Is my css n js are wrong or jquery? Is there any ambiguity between js and css??</p>

```<code><link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"/>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<div class="form-group">
<label class="col-sm-3 control-label no-padding-right" for="form-field-4">Portfolio Date</label>
<div class="col-sm-3">
@*<input class="input-sm" type="text" id="form-field-4" placeholder=".input-sm" />*@
<div class="input-group">
@*@Html.TextBoxFor(model => model.portfolioProjectDate,
new {@class="form-control", type="text",  placeholder="Portfolio Date", required="required" })*@
<input type='text' id="fiscalYear" name="FiscalYear"  class="form-control" placeholder="Booking Date" />
@*<input id="fiscalYear" name="FiscalYear" type="text" value="6/30/2015 7:12:21 AM">*@

<span class="input-group-addon">
<span class="fa fa-calendar"></span>
</span>
</div>
@*<div class="space-2"></div>
<div class="help-block" id="input-size-slider"></div>*@
</div>
</div>
<script>
   $(function () {
      alert("O");
      $("#fiscalYear").datepicker(
      {
         dateFormat: "mm/dd/yy",
         showOtherMonths: true,
         selectOtherMonths: true,
         autoclose: true,
         changeMonth: true,
         changeYear: true,
         //gotoCurrent: true,
       });
     });
</script>
</code>```

答:
Try initializing datepicker inside document.ready

```<code>$(document).ready(function() {
    $('#fiscalYear').datepicker();
})
</code>```

Be careful that you have included the datepicker library and css,

```<code><link href="css/bootstrap.css" rel="stylesheet">
<link href="css/datepicker.css" rel="stylesheet">

<script src="js/bootstrap.js"></script>
<script src="js/jquery-1.7.1.js"></script>
<script src="js/bootstrap-datepicker.js"></script>
</code>```

If your datepicker works by this then customize it by your configurations,

```<code> $("#fiscalYear").datepicker(

            {
                dateFormat: "mm/dd/yy",
                showOtherMonths: true,
                selectOtherMonths: true,
                autoclose: true,
                changeMonth: true,
                changeYear: true,
                //gotoCurrent: true,
            });
</code>```

Title: My date-picker is not working

Body:
Following is my code....
Whenever i click on input element then date-picker doesn't display. Where I am going wrong??? Is my css n js are wrong or jquery? Is there any ambiguity between js and css??

<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css"/>

Portfolio Date

@*<input class="input-sm" type="text" id="form-field-4" placeholder=".input-sm" />*@

@*@Html.TextBoxFor(model => model.portfolioProjectDate,
new {@class="form-control", type="text",  placeholder="Portfolio Date", required="required" })*@
<input type='text' id="fiscalYear" name="FiscalYear"  class="form-control" placeholder="Booking Date" />
@*<input id="fiscalYear" name="FiscalYear" type="text" value="6/30/2015 7:12:21 AM">*@

@*

*@

Body:
Try initializing datepicker inside document.ready

$(document).ready(function() {
    $('#fiscalYear').datepicker();
})

Be careful that you have included the datepicker library and css,

<link href="css/bootstrap.css" rel="stylesheet">
<link href="css/datepicker.css" rel="stylesheet">

<script src="js/bootstrap.js"></script>
<script src="js/jquery-1.7.1.js"></script>
<script src="js/bootstrap-datepicker.js"></script>

If your datepicker works by this then customize it by your configurations,

 $("#fiscalYear").datepicker(

            {
                dateFormat: "mm/dd/yy",
                showOtherMonths: true,
                selectOtherMonths: true,
                autoclose: true,
                changeMonth: true,
                changeYear: true,
                //gotoCurrent: true,
            });


问:
List of <MatofPoints> array in Android
I am creating OMR scanner in java.
I have List of  which contains contours from image.
i want to create array of List. how can i accomplish it?

this is what i have right now

```<code>List<MatOfPoint> questions = new ArrayList<MatOfPoint>();
</code>```

What i want to do is

```<code>List<MatOfPoint>[] questions = new ArrayList<MatOfPoint>[];
</code>```

so that i can store array of countours() for each question.
Like

[1] contour1,contour2,contour3,contour4,contour5

[2] contour1,contour2,contour3,contour4,contour5

[3] contour1,contour2,contour3,contour4,contour5

...............................

答:
It's probably better to just use a list of list. But you can do something like this:</p>

```<code>List<MatOfPoint>[] questions = (ArrayList<MatOfPoint>[]) new ArrayList[n];
</code>```

Title: List of <MatofPoints> array in Android

Body:
I am creating OMR scanner in java.
I have List of  which contains contours from image.
i want to create array of List. how can i accomplish it?

this is what i have right now

List<MatOfPoint> questions = new ArrayList<MatOfPoint>();

What i want to do is

List<MatOfPoint>[] questions = new ArrayList<MatOfPoint>[];

so that i can store array of countours() for each question.
Like

[1] contour1,contour2,contour3,contour4,contour5

[2] contour1,contour2,contour3,contour4,contour5

[3] contour1,contour2,contour3,contour4,contour5

...............................

Body:
It's probably better to just use a list of list. But you can do something like this:

List<MatOfPoint>[] questions = (ArrayList<MatOfPoint>[]) new ArrayList[n];


问:
Deserialize JSON object xamarin C#
I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.

```<code>Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.
</code>```

My JSON Object Class:

```<code>public class jsonobjectclass
{
    public class User
    {
        public string name { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
        public string current_group { get; set; }
        public List<UserGroups> user_groups { get; set; }
    }

    public class UserGroups
    {
        [JsonProperty("10")]
        public string Student { get; set; }
        [JsonProperty("15")]
        public string Tutor { get; set; }
        [JsonProperty("11")]
        public string Parent { get; set; }
    }

    public class Token
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
        public string scope { get; set; }
        public string refresh_token { get; set; }
        public string error { get; set; }
    }

    public class UserResponse
    {
        public string msg { get; set; }
        public List<User> data { get; set; }
        public bool error { get; set; }
    }
}
</code>```

My Code to Deserialize JSON:

```<code>public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
    {
        var jsonObject = new jsonobjectclass.UserResponse();
        string readHttpResponse;

        using (var httpClient = new HttpClient())
        {
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
            {
                httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
                using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                {
                    readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var jObject = JObject.Parse(readHttpResponse);
                    try
                    {
                        jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
                    }
                    catch(Exception ex)
                    {
                        string excep = ex.ToString();
                        readHttpResponse = excep;
                    }
                }
            }
        }
        return jsonObject;
    }
</code>```

My JSON String:

```<code>{{
  "msg": null,
  "data": {
  "name": "geoit",
  "email": "rokesh@geoit.in",
  "phone": null,
  "current_group": "11",
  "user_groups": {
   "11": "Parent"
   }
},
"error": false
}}
</code>```

Please Help me to solve this.

Thanks,
Rokesh

答:
You have mismatch between the string and the object you are trying to deserialize into. The data object is not an array and there is an additional nested object which is not named in the JSON separately containing the msg field and the user data, but the error field is not part of that object:

As the comments have pointed out the JSON is not valid as is, so if you have control of the source I would fix that.

If not you could implement a reader and parse it as token by token, something like this:

```<code>using (var response = await client.GetAsync(_url, HttpCompletionOption.ResponseHeadersRead))
using (var stream = await response.Content.ReadAsStreamAsync())
using (var streamReader = new StreamReader(stream))
using (var reader = new JsonTextReader(streamReader))
{

    var serializer = new JsonSerializer();

    while (reader.Read())
    {
        switch (reader.TokenType)
        {
            case JsonToken.Start:
            // code to handle it
            break;
            case JsonToken.PropertyName:
            // code to handle it
            break;

            // more options
        }
    }
}
</code>```

although this approach is more fragile. You can take a look at The JSON.Net JsonToken docs for more info.

Based on your comment and using https://jsonlint.com/ the response string

```<code>"{\"msg\":null,\"data\":{\"name\":\"geoit\",\"email\":\"rokesh@geoit.in\",\"phone\":null,\"current_group\":\"11\",\"user_groups\":{\"11\":\"Parent\"}},\"error\":false}"
</code>```

is actually valid JSON, but the object is a little bizarre. I think it looks something like this in C#

```<code>public class UserGroup
{
    public string 11 { get; set; }
}

public class UserData {
    public string name  { get; set; }
    public string email  { get; set; }
    public string phone  { get; set; }
    public string current_group  { get; set; }
    public UserGroup user_groups  { get; set; }
}

public class ResponseObject
{
    public string msg { get; set; }
    public UserData data  { get; set; }
    public bool error  { get; set; }
}
</code>```

Title: Deserialize JSON object xamarin C#

Body:
I am getting the following error in Xamarin cross platform while deserializing the JSON Object. I have tried to do it with dictionary. But, everything gives me the same exception.

Newtonsoft.Json.JsonSerializationException: Cannot deserialize the current JSON object (e.g. {\"name\":\"value\"}) into type 'System.Collections.Generic.List`1[NBStudents.Models.jsonobjectclass+User]' because the type requires a JSON array (e.g. [1,2,3]) to deserialize correctly.
To fix this error either change the JSON to a JSON array (e.g. [1,2,3]) or change the deserialized type so that it is a normal .NET type (e.g. not a primitive type like integer, not a collection type like an array or List<T>) that can be deserialized from a JSON object. JsonObjectAttribute can also be added to the type to force it to deserialize from a JSON object.Path 'data.name', line 4, position 11.

My JSON Object Class:

public class jsonobjectclass
{
    public class User
    {
        public string name { get; set; }
        public string email { get; set; }
        public string phone { get; set; }
        public string current_group { get; set; }
        public List<UserGroups> user_groups { get; set; }
    }

    public class UserGroups
    {
        [JsonProperty("10")]
        public string Student { get; set; }
        [JsonProperty("15")]
        public string Tutor { get; set; }
        [JsonProperty("11")]
        public string Parent { get; set; }
    }

    public class Token
    {
        public string access_token { get; set; }
        public int expires_in { get; set; }
        public string token_type { get; set; }
        public string scope { get; set; }
        public string refresh_token { get; set; }
        public string error { get; set; }
    }

    public class UserResponse
    {
        public string msg { get; set; }
        public List<User> data { get; set; }
        public bool error { get; set; }
    }
}

My Code to Deserialize JSON:

public static async Task<jsonobjectclass.UserResponse> UserRetrievalTask(string token, string apiUrl)
    {
        var jsonObject = new jsonobjectclass.UserResponse();
        string readHttpResponse;

        using (var httpClient = new HttpClient())
        {
            using (var httpRequestMessage = new HttpRequestMessage(HttpMethod.Get, apiUrl))
            {
                httpRequestMessage.Headers.Add("Authorization", "Bearer " + token);
                using (var httpResponse = await httpClient.SendAsync(httpRequestMessage).ConfigureAwait(false))
                {
                    readHttpResponse = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);
                    var jObject = JObject.Parse(readHttpResponse);
                    try
                    {
                        jsonObject = JsonConvert.DeserializeObject<jsonobjectclass.UserResponse>(jObject.ToString());
                    }
                    catch(Exception ex)
                    {
                        string excep = ex.ToString();
                        readHttpResponse = excep;
                    }
                }
            }
        }
        return jsonObject;
    }

My JSON String:

{{
  "msg": null,
  "data": {
  "name": "geoit",
  "email": "rokesh@geoit.in",
  "phone": null,
  "current_group": "11",
  "user_groups": {
   "11": "Parent"
   }
},
"error": false
}}

Please Help me to solve this.

Thanks,
Rokesh

Body:
You have mismatch between the string and the object you are trying to deserialize into. The data object is not an array and there is an additional nested object which is not named in the JSON separately containing the msg field and the user data, but the error field is not part of that object:

As the comments have pointed out the JSON is not valid as is, so if you have control of the source I would fix that.

If not you could implement a reader and parse it as token by token, something like this:

using (var response = await client.GetAsync(_url, HttpCompletionOption.ResponseHeadersRead))
using (var stream = await response.Content.ReadAsStreamAsync())
using (var streamReader = new StreamReader(stream))
using (var reader = new JsonTextReader(streamReader))
{

    var serializer = new JsonSerializer();

    while (reader.Read())
    {
        switch (reader.TokenType)
        {
            case JsonToken.Start:
            // code to handle it
            break;
            case JsonToken.PropertyName:
            // code to handle it
            break;

            // more options
        }
    }
}

although this approach is more fragile. You can take a look at The JSON.Net JsonToken docs for more info.

Based on your comment and using https://jsonlint.com/ the response string

"{\"msg\":null,\"data\":{\"name\":\"geoit\",\"email\":\"rokesh@geoit.in\",\"phone\":null,\"current_group\":\"11\",\"user_groups\":{\"11\":\"Parent\"}},\"error\":false}"

is actually valid JSON, but the object is a little bizarre. I think it looks something like this in C#

public class UserGroup
{
    public string 11 { get; set; }
}

public class UserData {
    public string name  { get; set; }
    public string email  { get; set; }
    public string phone  { get; set; }
    public string current_group  { get; set; }
    public UserGroup user_groups  { get; set; }
}

public class ResponseObject
{
    public string msg { get; set; }
    public UserData data  { get; set; }
    public bool error  { get; set; }
}


问:
Standard process for creating complex xpath in protractor
I am looking for standard ways to arrive at complex xpath expressions in protractor.

For e.g. I have a complex xpath as follows:

```<code>(//*[contains(@class,'day')][normalize-space(text())='2'])[1]
</code>```

Here I have to get first access to elements matching xpath

```<code>//*[contains(@class,'day')][normalize-space(text())='2']
</code>```

and then pick the first from the matching ones. Any pointers?

答:
Protractor in its documentation clearly describes any process for creating xpaths:
http://www.protractortest.org/#/style-guide [section Locator strategies].

Body:
I am looking for standard ways to arrive at complex xpath expressions in protractor.

For e.g. I have a complex xpath as follows:

(//*[contains(@class,'day')][normalize-space(text())='2'])[1]

Here I have to get first access to elements matching xpath

//*[contains(@class,'day')][normalize-space(text())='2']

and then pick the first from the matching ones. Any pointers?