问:
Tensorflow error on Android
I am learning Tensorflow and following a tutorial I was able to make a custom model to run it in an Android App but I am having problems with it. I have the following code:

```<code>    public void testModel(Context ctx) {
        String model_file = "file:///android_asset/model_graph.pb";
        int[] result = new int[2];
        float[] input = new float[]{0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F};
        TensorFlowInferenceInterface inferenceInterface;
        inferenceInterface = new TensorFlowInferenceInterface(ctx.getAssets(), model_file);
        inferenceInterface.feed("input", input, 68);
        inferenceInterface.run(new String[]{"output"});
        inferenceInterface.fetch("output", result);
        Log.v(TAG, Arrays.toString(result));
    }
</code>```

I got an error when the app try to run the inferenceInterface.run(new String[]{"output"}) method:

```<code>java.lang.IllegalArgumentException: In[0] is not a matrix
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_input_0_0, W1)]]
</code>```

I don't believe the model I created is the problem because I was able to use it in a Python code with positive result.

答:
From the error message (In[0] is not a matrix), it appears that your model requires the input to be a matrix (i.e., a two dimensional tensor), while you are feeding a one dimensional tensor (vector) with 68 elements.

In particular, the dims argument to TensorFlowInferenceInterface.feed seems incorrect in the line:

```<code>inferenceInterface.feed("input", input, 68);
</code>```

Instead, it should be something like:

```<code>inferenceInterface.feed("input", input, 68, 1);
</code>```

if your model expects a 68x1 matrix (or 34, 2 if it expects a 34x2 matrix, 17, 4 for a 17x4 matrix etc.)

Hope that helps.

Title: Tensorflow error on Android

Body:
I am learning Tensorflow and following a tutorial I was able to make a custom model to run it in an Android App but I am having problems with it. I have the following code:

    public void testModel(Context ctx) {
        String model_file = "file:///android_asset/model_graph.pb";
        int[] result = new int[2];
        float[] input = new float[]{0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 1.0F, 0.0F, 1.0F, 0.0F, 0.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F, 1.0F, 0.0F};
        TensorFlowInferenceInterface inferenceInterface;
        inferenceInterface = new TensorFlowInferenceInterface(ctx.getAssets(), model_file);
        inferenceInterface.feed("input", input, 68);
        inferenceInterface.run(new String[]{"output"});
        inferenceInterface.fetch("output", result);
        Log.v(TAG, Arrays.toString(result));
    }

I got an error when the app try to run the inferenceInterface.run(new String[]{"output"}) method:

java.lang.IllegalArgumentException: In[0] is not a matrix
[[Node: MatMul = MatMul[T=DT_FLOAT, transpose_a=false, transpose_b=false, _device="/job:localhost/replica:0/task:0/device:CPU:0"](_arg_input_0_0, W1)]]

I don't believe the model I created is the problem because I was able to use it in a Python code with positive result.

Body:
From the error message (In[0] is not a matrix), it appears that your model requires the input to be a matrix (i.e., a two dimensional tensor), while you are feeding a one dimensional tensor (vector) with 68 elements.

In particular, the dims argument to TensorFlowInferenceInterface.feed seems incorrect in the line:

inferenceInterface.feed("input", input, 68);

Instead, it should be something like:

inferenceInterface.feed("input", input, 68, 1);

if your model expects a 68x1 matrix (or 34, 2 if it expects a 34x2 matrix, 17, 4 for a 17x4 matrix etc.)

Hope that helps.


来源: stackexchange

问:
C++: Undefined function error when I have defined the function
I am trying to implement a linkedlist in C++. I defined the linkedlist and node classes and the methods for the linkedlist class in the same file. Here is my linkedlist class:

```<code>template <class T>
class  LinkedList{
    public:
        Node<T> *head;
        int size;

        LinkedList();
        void push(T data);
        T pop();
        T remove(T *target, int (*compfunc)(T *, T *));
        void clear();
        int getSize();
        void printList();
};
</code>```

I define the push method:

```<code>template <class T>
void LinkedList<T>::push(T data){
    Node<T> *n = new Node<T>;
    n -> data = data;
    n->next = this->head;
    this->head = n;
    this->size++;
}
</code>```

But when I try to run the main method, I get an error saying that LinkedList::push(T data) is undefined.

Main function:

```<code>int main(){
    LinkedList<int> list;

    for (int i = 0; i < 5; ++i)
    {
        list.push(i);
    }

    list.printList();

    return 0;
}
</code>```

All other methods except push seem to work fine. The error I get is:

Undefined symbols for architecture x86_64:
    "operator new(unsigned long)", referenced from:
        LinkedList::push(int) in linkedList-1c3a85.o
  ld: symbol(s) not found for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)`

答:
Stubbing out the function not supplied and a basic Node

```<code>template<typename T>
struct Node
{
    T data;
    Node* next;
};
</code>```

compiles fine with g++ 5.4 & clang 3.8
Are you missing the definition of the node class template?

ContentLicense: CC BY-SA 3.0

Body:
I am trying to implement a linkedlist in C++. I defined the linkedlist and node classes and the methods for the linkedlist class in the same file. Here is my linkedlist class:

template <class T>
class  LinkedList{
    public:
        Node<T> *head;
        int size;

        LinkedList();
        void push(T data);
        T pop();
        T remove(T *target, int (*compfunc)(T *, T *));
        void clear();
        int getSize();
        void printList();
};

I define the push method:

template <class T>
void LinkedList<T>::push(T data){
    Node<T> *n = new Node<T>;
    n -> data = data;
    n->next = this->head;
    this->head = n;
    this->size++;
}

But when I try to run the main method, I get an error saying that LinkedList::push(T data) is undefined.

Main function:

int main(){
    LinkedList<int> list;

    for (int i = 0; i < 5; ++i)
    {
        list.push(i);
    }

    list.printList();

    return 0;
}

All other methods except push seem to work fine. The error I get is:

Undefined symbols for architecture x86_64:
    "operator new(unsigned long)", referenced from:
        LinkedList::push(int) in linkedList-1c3a85.o
  ld: symbol(s) not found for architecture x86_64
  clang: error: linker command failed with exit code 1 (use -v to see invocation)`

Body:
Stubbing out the function not supplied and a basic Node

template<typename T>
struct Node
{
    T data;
    Node* next;
};

compiles fine with g++ 5.4 & clang 3.8
Are you missing the definition of the node class template?


问:
TestNG console output into log4j.log
I need to get output result (FAIL or SUCCESS) into log4j output.

```<code>Assert.assertTrue(availresponse);
</code>```

Is there any way to add TestNG console output into log4j.log file?

答:
Finally found the easiest way to log the Assert error in log4j

In catch block it should be Throwable, if it is Exception that will not work.

```<code>try {
    Assert.assertTrue(hotel.getAmenitiesList().size() < 0, "Hotel Amenities Available!");

} catch (Throwable e) {
    e.printStackTrace();
    logger.error("FAILED: testRoomAmenities ", e);
    Assert.fail();
</code>```

When this implement that will not invoke as FAIL. It will show that scenario is PASSED. Therefore you should use Assert.fail() to make that is FAILED

Title: TestNG console output into log4j.log

Body:
I need to get output result (FAIL or SUCCESS) into log4j output.

Assert.assertTrue(availresponse);

Is there any way to add TestNG console output into log4j.log file?

Body:
Finally found the easiest way to log the Assert error in log4j

In catch block it should be Throwable, if it is Exception that will not work.

try {
    Assert.assertTrue(hotel.getAmenitiesList().size() < 0, "Hotel Amenities Available!");

} catch (Throwable e) {
    e.printStackTrace();
    logger.error("FAILED: testRoomAmenities ", e);
    Assert.fail();

When this implement that will not invoke as FAIL. It will show that scenario is PASSED. Therefore you should use Assert.fail() to make that is FAILED


问:
How to convert date to unix format
How to convert below date to unix format using python ?

I have checked for date month and year format but it is not working

Date: "10 Nov 2017"

Please help.

答:
the problem can be solved as follows </p>

```<code>import time
import datetime
s = "01/dec/2011"
time.mktime(datetime.datetime.strptime(s, "%d/%b/%Y").timetuple())
output:
1322697600.0
</code>```

Title: How to convert date to unix format

Body:
the problem can be solved as follows

import time
import datetime
s = "01/dec/2011"
time.mktime(datetime.datetime.strptime(s, "%d/%b/%Y").timetuple())
output:
1322697600.0


问:
I have two values on the first row of the table it_courses field course_branch. When i join branch table with it_courses table result only one value
these are the tables

and it results
I have two values on the first row of the table it_courses field course_branch. When i join branch table with it_courses table result is like this.it doesnt shows the second value in the 1st row that was entered in the it_coursestable

Query :

```<code>SELECT branch.branch_name
FROM `branch`
JOIN `it_courses` ON it_courses.course_branch = branch.branch_id
</code>```

答:
Try this.</p>

```<code>SELECT branch.branch_id,it_courses.course_name
FROM `branch`
left JOIN `it_courses` ON LOCATE(branch.branch_name,it_courses.course_branch) > 0
</code>```

Body:
these are the tables

and it results
I have two values on the first row of the table it_courses field course_branch. When i join branch table with it_courses table result is like this.it doesnt shows the second value in the 1st row that was entered in the it_coursestable

Query :

SELECT branch.branch_name
FROM `branch`
JOIN `it_courses` ON it_courses.course_branch = branch.branch_id

Body:
Try this.

SELECT branch.branch_id,it_courses.course_name
FROM `branch`
left JOIN `it_courses` ON LOCATE(branch.branch_name,it_courses.course_branch) > 0


问:
Can't install a library to open audio files in Anaconda
I've been working on fixing this problem since really early Monday (yesterday) morning.

I'm using Anaconda and trying to use tensorflow to create neural networks and I've reached the stage where I'm supposed to create the functions that feed audio into a neural network. The problem is that to do that properly, I need a library that I can use to convert MP3 files to WAVE files automatically, but I can't seem to get hold of said library. Pydub installs, but can't be imported, ffmpeg won't even install and tinytag installs, but seems to not have a save or export function. I tried installing or using each of these libraries in Anaconda Python 3.6 and Anaconda Python 3.3. I also tried to install other audio libraries and failed.

```<code>ModuleNotFoundError: No module named 'pydub'

Could not find a version that satisfies the requirement ffmpeg (from versions: )
No matching distribution found for ffmpeg
</code>```

I'm on Windows 10 Home. How do I solve this problem? Thank you. :)

答:
Go to https://pypi.python.org/pypi/pydub and load the wheel for your python version.

Go to downloads and try: pip install wheel_name or conda install wheel

It can be that you have to insert some data in your sitepackage folder manually using full anaconda installation

Body:
I've been working on fixing this problem since really early Monday (yesterday) morning.

I'm using Anaconda and trying to use tensorflow to create neural networks and I've reached the stage where I'm supposed to create the functions that feed audio into a neural network. The problem is that to do that properly, I need a library that I can use to convert MP3 files to WAVE files automatically, but I can't seem to get hold of said library. Pydub installs, but can't be imported, ffmpeg won't even install and tinytag installs, but seems to not have a save or export function. I tried installing or using each of these libraries in Anaconda Python 3.6 and Anaconda Python 3.3. I also tried to install other audio libraries and failed.

ModuleNotFoundError: No module named 'pydub'

Could not find a version that satisfies the requirement ffmpeg (from versions: )
No matching distribution found for ffmpeg

I'm on Windows 10 Home. How do I solve this problem? Thank you. :)


问:
How to show a dynamic content in the same page using Angularjs 1.6?
I'm a newbie to Angular. I need to render a dynamic content from JSON file using AngularJS 1.6. Here is what I have.

News.json

```<code>   {
  "Articles": [
    {
      "Title": "News 1",
      "Abstract": "News 1 abstract ...",
      "Body": "News 1 starts here.... ",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here",
          "comment 3" : "Comment 3 goes here"
        }]
    },

    {
      "Title": "News 2",
      "Abstract": "News 2 abstract ... ",
      "Body": "News 2 starts here...",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here"
        }]
    }
  ]
}
</code>```

Script.js

```<code>app.config(function ($routeProvider) {
    $routeProvider
        .when("/News", {
            templateUrl: "NewsViewer.html",
            controller: "showNews"
        });
});

app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data;
    });
}]);
</code>```

News.html

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

    <div class="row">

        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="NewsRendering">
                <div ng-repeat="NewsData in News.Articles">
                    <h3>{{NewsData.Title}}</h3>
                    <p>{{NewsData.Abstract}}</p>
                    <a data-ng-href="/AngularTask/NewsViewer.html">more</a>
                </div>
            </div>
        </div>

        <div class="col-md-4 questionnaire">
            <h3>Questionnaire of the day</h3>
        </div>

    </div>

</div>
</code>```

NewsViewer.html

```<code><div class="container-fluid">
    <div class="row">
        <div class="col-md-offset-1 col-md-6">
            <div ng-controller="showNews">
                <div>
                    <h3>{{News.Articles[0].Title}}</h3>
                    <p>{{News.Articles[0].Abstract}}</p>
                    <p>{{News.Articles[0].Body}}</p>
                </div>

                <div class="comments">
                    <h4>Comments</h4>
                    <hr>
                    <p>{{News.Articles[0].Comments[0]}}</p>
                </div>
            </div>
        </div>
    </div>
</div>
</code>```

This code is working fine, but this code is not dynamic. My problem how to make it dynamic and can show whatever in json file. What should I do in JS code to pass the index of the array of the JSON File.

As you can see
{{News.Articles[0].Title}}
 is showing only the first Title of the JSON file. I need to write it to be
{{News.Articles[index of whatever].Title}}

Note: News.json has around 100,000 records. I make it two, just to show the code and describe the problem.

答:
Few observations as per your code :

This line of code more will break the pupose of AngularJS which is Single page application (SPA).

Use ui-router instead of ngRoute to get better as ngRoute is outdated.

Instead of redirecting a user to a html template (/AngularTask/NewsViewer.html) directly, change the state of the view using ui-sref with params and pass the $index as param value.

Try below approach to get result as per the expectation :

News.html

```<code>  <div ng-repeat="NewsData in News.Articles">
    <h3>{{NewsData.Title}}</h3>
    <p>{{NewsData.Abstract}}</p>
    <a href="javascript:void(0)" ui-sref="newsdetails({index: $index})">more</a>
  </div>
</code>```

routes.js :

```<code>$stateProvider
    .state('newsdetails', {
      url: '/news-details/:index',
      controller: 'showNews',
      templateUrl: 'NewsViewer.html'
    })
    ....
</code>```

Controller :

```<code>.controller('showNews', function($scope, $stateParams) {
    $scope.indexVal = $stateParams.index; // getting index value passed from news.html
});
</code>```

NewsViewer.html :

```<code> <div ng-controller="showNews">
     <div>
         <h3>{{News.Articles[indexVal].Title}}</h3>
         <p>{{News.Articles[indexVal].Abstract}}</p>
         <p>{{News.Articles[indexVal].Body}}</p>
     </div>
 </div>
</code>```

Working demo : https://plnkr.co/edit/jfzm00ksZMAC8sGGUZSR?p=preview

Body:
I'm a newbie to Angular. I need to render a dynamic content from JSON file using AngularJS 1.6. Here is what I have.

News.json

   {
  "Articles": [
    {
      "Title": "News 1",
      "Abstract": "News 1 abstract ...",
      "Body": "News 1 starts here.... ",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here",
          "comment 3" : "Comment 3 goes here"
        }]
    },

    {
      "Title": "News 2",
      "Abstract": "News 2 abstract ... ",
      "Body": "News 2 starts here...",
      "Comments": [
        {
          "comment 1" : "Comment 1 goes here",
          "comment 2" : "Comment 2 goes here"
        }]
    }
  ]
}

Script.js

app.config(function ($routeProvider) {
    $routeProvider
        .when("/News", {
            templateUrl: "NewsViewer.html",
            controller: "showNews"
        });
});

app.controller("showNews", ["$scope", "$http", function ($scope, $http) {
    $http({
        method: 'GET',
        url: 'News/News.json'
    }).then(function success(data) {
        $scope.News = data.data;
    });
}]);

News.html

{{NewsData.Title}}

{{NewsData.Abstract}}

                    more

Questionnaire of the day

NewsViewer.html

{{News.Articles[0].Title}}

{{News.Articles[0].Abstract}}

{{News.Articles[0].Body}}

Comments

{{News.Articles[0].Comments[0]}}

This code is working fine, but this code is not dynamic. My problem how to make it dynamic and can show whatever in json file. What should I do in JS code to pass the index of the array of the JSON File.

As you can see
{{News.Articles[0].Title}}
 is showing only the first Title of the JSON file. I need to write it to be
{{News.Articles[index of whatever].Title}}

Note: News.json has around 100,000 records. I make it two, just to show the code and describe the problem.

Body:
Few observations as per your code :

This line of code <a data-ng-href="/AngularTask/NewsViewer.html">more</a> will break the pupose of AngularJS which is Single page application (SPA).

Use ui-router instead of ngRoute to get better as ngRoute is outdated.

Instead of redirecting a user to a html template (/AngularTask/NewsViewer.html) directly, change the state of the view using ui-sref with params and pass the $index as param value.

Try below approach to get result as per the expectation :

News.html

  <div ng-repeat="NewsData in News.Articles">
    <h3>{{NewsData.Title}}</h3>
    <p>{{NewsData.Abstract}}</p>
    <a href="javascript:void(0)" ui-sref="newsdetails({index: $index})">more</a>
  </div>

routes.js :

$stateProvider
    .state('newsdetails', {
      url: '/news-details/:index',
      controller: 'showNews',
      templateUrl: 'NewsViewer.html'
    })
    ....

Controller :

.controller('showNews', function($scope, $stateParams) {
    $scope.indexVal = $stateParams.index; // getting index value passed from news.html
});

NewsViewer.html :

 <div ng-controller="showNews">
     <div>
         <h3>{{News.Articles[indexVal].Title}}</h3>
         <p>{{News.Articles[indexVal].Abstract}}</p>
         <p>{{News.Articles[indexVal].Body}}</p>
     </div>
 </div>

Working demo : https://plnkr.co/edit/jfzm00ksZMAC8sGGUZSR?p=preview


问:
how to modify json Object in javascript
I am trying to load sample csv files into project read the content and display according to the filed. I done uploading and file writing but could not optimize the json structure properly for future use case

Here is my sample code :

```<code>let csvToJson = require('convert-csv-to-json');
let json = csvToJson.getJsonFromCsv(filepath);
var lines = [];
for(let i=0; i<json.length;i++){
console.log(json[i]);
lines.push(json[i])
}
console.log(lines);
var result3=JSON.stringify(lines);
result3 = result3.replace(/\r?\n|\r/g, " ");
console.log(result3);
</code>```

My output:

console.log(json[i]) =

```<code>Object {name,age,address: "asd,20,"12/76, 11th cross"
"}
browser.js:5358 Object {name,age,address: "dff,30,"33, 11th cross"
"}
browser.js:5358 Object {name,age,address: "f,22,"7g/22, 12th cross"
"}
browser.js:5358 Object {name,age,address: "ghth,55,"4h, 13th cross"
"}
</code>```

console.log(lines) = [Object, Object, Object, Object, Object]

console.log(result3)

```<code>[{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}]
</code>```

My expected output:

```<code>{name:[],age:[],address:[]}
</code>```

i.e I want all "name" values should store in the  name key similar to "age" and "address". Can anybody help me how to do this?

答:
As evident from console.log(json[i]) output, the module convert-csv-to-json is converting your csv file as an array of a single key value pair which means name, age, address are joined into one unit, same goes for their value.
At this point of time your file has less key and you can manually map this key.

For the problem above, you can use array#reduce and split() values on comma.

const data = [{"name,age,address": "asd,20,\"12/76, 11th cross\""},{"name,age,address": "dff,30,\"33, 11th cross\""},{"name,age,address": "f,22,\"7g/22, 12th cross\""},{"name,age,address": "ghth,55,\"4h, 13th cross\""}];
var result = data.reduce((res, obj) => {
  let [name, age, ...address] = obj["name,age,address"].split(',');
  res.name.push(name);
  res.age.push(age);
  res.address.push(address.join(''));
  return res;
},{name:[],age:[],address:[]});
console.log(result);```

Title: how to modify json Object in javascript

Body:
I am trying to load sample csv files into project read the content and display according to the filed. I done uploading and file writing but could not optimize the json structure properly for future use case

Here is my sample code :

let csvToJson = require('convert-csv-to-json');
let json = csvToJson.getJsonFromCsv(filepath);
var lines = [];
for(let i=0; i<json.length;i++){
console.log(json[i]);
lines.push(json[i])
}
console.log(lines);
var result3=JSON.stringify(lines);
result3 = result3.replace(/\r?\n|\r/g, " ");
console.log(result3);

My output:

console.log(json[i]) =

Object {name,age,address: "asd,20,"12/76, 11th cross"
"}
browser.js:5358 Object {name,age,address: "dff,30,"33, 11th cross"
"}
browser.js:5358 Object {name,age,address: "f,22,"7g/22, 12th cross"
"}
browser.js:5358 Object {name,age,address: "ghth,55,"4h, 13th cross"
"}

console.log(lines) = [Object, Object, Object, Object, Object]

console.log(result3)

[{"name,age,address":"asd,20,\"12/76, 11th cross\"\r"},
{"name,age,address":"dff,30,\"33, 11th cross\"\r"},
{"name,age,address":"f,22,\"7g/22, 12th cross\"\r"},
{"name,age,address":"ghth,55,\"4h, 13th cross\"\r"},
{"name,age,address":"fhg,44,\"6t, 10th cross\"\r"}]

My expected output:

{name:[],age:[],address:[]}

i.e I want all "name" values should store in the  name key similar to "age" and "address". Can anybody help me how to do this?


问:
I cannot sort JTable--Jave
When I click columns, the sorted results are wrong:

Here is my code:

```<code>DefaultTableModel tableModel = new DefaultTableModel(data, columns) {

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };
    JTable table = new JTable();
    table.setModel(tableModel);

    //Sort table
    table.setAutoCreateRowSorter(true);
</code>```

Here is code for columns and data:

couponArray: It is Object

```<code>        // Columns of table
    String[] columns = {"Name of Coupon Provider", "Name of product", "Price of product",
            "Discount rate of the coupon (%)", "Final price", "Expiration Period", "Status of a coupon"};

    //Data of table
    int lengthArray = couponArray.size();
    String data[][] = new String [lengthArray][7];
    for (int i = 0; i < lengthArray; i++){
        Coupon sTmp = (Coupon)couponArray.get(i);
        data[i][0] = sTmp.getNameOfCouponProvider();
        data[i][1] = sTmp.getNameOfProduct();
        data[i][2] = Double.toString(sTmp.getPriceOfProduct());
        data[i][3] = Integer.toString(sTmp.getDiscountRateOfCoupon());

        //Get final price
        double finalPrice = sTmp.getPriceOfProduct() -
                sTmp.getPriceOfProduct()*((double)sTmp.getDiscountRateOfCoupon()/100);
        data[i][4] = new Formatter().format("%.2f", finalPrice).toString();
        data[i][5] = Integer.toString(sTmp.getExpirationPeriod());
        data[i][6] = sTmp.getStatusOfCoupon();
    }
</code>```

答:
See my solution below. Now it sorts "Price of product" correctly. Main change is to override getColumnClass() in table model. With this change, "Price of product" values are treated as numbers. Earlier they were treated as strings.

I also changed the type of data array to Object[][]. And set double value to data[i][2] without converting it to String.

```<code>import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
import java.util.Arrays;
import java.util.Formatter;
import java.util.List;

public class TableSorting
{
  public static void main(String[] args)
  {
    // Columns of table
    String[] columns = {"Name of Coupon Provider", "Name of product", "Price of product",
        "Discount rate of the coupon (%)", "Final price", "Expiration Period", "Status of a coupon"};

    //Data of table
    List<Coupon> couponArray = Arrays.asList(
        new Coupon("aaa", "bbb", 100.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 60.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 160.4, 1, 1, "a"),
        new Coupon("aaa", "bbb", 220.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 70.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 150.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 160.3, 1, 1, "a"),
        new Coupon("aaa", "bbb", 210.3, 1, 1, "a"));

    int lengthArray = couponArray.size();
    Object data[][] = new Object[lengthArray][7];
    for (int i = 0; i < lengthArray; i++){
      Coupon sTmp = couponArray.get(i);
      data[i][0] = sTmp.getNameOfCouponProvider();
      data[i][1] = sTmp.getNameOfProduct();
      data[i][2] = sTmp.getPriceOfProduct();//Double.toString(sTmp.getPriceOfProduct());
      data[i][3] = Integer.toString(sTmp.getDiscountRateOfCoupon());

      //Get final price
      double finalPrice = sTmp.getPriceOfProduct() -
          sTmp.getPriceOfProduct()*((double)sTmp.getDiscountRateOfCoupon()/100);
      data[i][4] = new Formatter().format("%.2f", finalPrice).toString();
      data[i][5] = Integer.toString(sTmp.getExpirationPeriod());
      data[i][6] = sTmp.getStatusOfCoupon();
    }

    DefaultTableModel tableModel = new DefaultTableModel(data, columns) {

      @Override
      public boolean isCellEditable(int row, int column) {
        //all cells false
        return false;
      }

      //This makes values in "Price" column treated as numerical values
      // instead of String values.
      @Override
      public Class<?> getColumnClass(int columnIndex)
      {
        if (columnIndex == 2)
        {
          return Double.class;
        }
        return super.getColumnClass(columnIndex);
      }
    };
    JTable table = new JTable();
    table.setModel(tableModel);

    //Sort table
    table.setAutoCreateRowSorter(true);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}

class Coupon
{
  private String nameOfCouponProvider;
  private String nameOfProduct;
  private double priceOfProduct;
  private int discountRateOfCoupon;
  private int expirationPeriod;
  private String statusOfCoupon;

  Coupon(String nameOfCouponProvider, String nameOfProduct,
         double priceOfProduct, int discountRateOfCoupon,
         int expirationPeriod, String statusOfCoupon)
  {
    this.nameOfCouponProvider = nameOfCouponProvider;
    this.nameOfProduct = nameOfProduct;
    this.priceOfProduct = priceOfProduct;
    this.discountRateOfCoupon = discountRateOfCoupon;
    this.expirationPeriod = expirationPeriod;
    this.statusOfCoupon = statusOfCoupon;
  }

  String getNameOfCouponProvider() { return nameOfCouponProvider; }
  String getNameOfProduct() { return nameOfProduct; }
  double getPriceOfProduct() { return priceOfProduct; }
  int getDiscountRateOfCoupon() { return discountRateOfCoupon; }
  int getExpirationPeriod() { return expirationPeriod; }
  String getStatusOfCoupon() { return statusOfCoupon; }
}
</code>```

Title: I cannot sort JTable--Jave

Body:
When I click columns, the sorted results are wrong:

Here is my code:

DefaultTableModel tableModel = new DefaultTableModel(data, columns) {

        @Override
        public boolean isCellEditable(int row, int column) {
            //all cells false
            return false;
        }
    };
    JTable table = new JTable();
    table.setModel(tableModel);

    //Sort table
    table.setAutoCreateRowSorter(true);

Here is code for columns and data:

couponArray: It is Object

        // Columns of table
    String[] columns = {"Name of Coupon Provider", "Name of product", "Price of product",
            "Discount rate of the coupon (%)", "Final price", "Expiration Period", "Status of a coupon"};

    //Data of table
    int lengthArray = couponArray.size();
    String data[][] = new String [lengthArray][7];
    for (int i = 0; i < lengthArray; i++){
        Coupon sTmp = (Coupon)couponArray.get(i);
        data[i][0] = sTmp.getNameOfCouponProvider();
        data[i][1] = sTmp.getNameOfProduct();
        data[i][2] = Double.toString(sTmp.getPriceOfProduct());
        data[i][3] = Integer.toString(sTmp.getDiscountRateOfCoupon());

        //Get final price
        double finalPrice = sTmp.getPriceOfProduct() -
                sTmp.getPriceOfProduct()*((double)sTmp.getDiscountRateOfCoupon()/100);
        data[i][4] = new Formatter().format("%.2f", finalPrice).toString();
        data[i][5] = Integer.toString(sTmp.getExpirationPeriod());
        data[i][6] = sTmp.getStatusOfCoupon();
    }

Body:
See my solution below. Now it sorts "Price of product" correctly. Main change is to override getColumnClass() in table model. With this change, "Price of product" values are treated as numbers. Earlier they were treated as strings.

I also changed the type of data array to Object[][]. And set double value to data[i][2] without converting it to String.

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTable;
import javax.swing.table.DefaultTableModel;
import java.awt.BorderLayout;
import java.util.Arrays;
import java.util.Formatter;
import java.util.List;

public class TableSorting
{
  public static void main(String[] args)
  {
    // Columns of table
    String[] columns = {"Name of Coupon Provider", "Name of product", "Price of product",
        "Discount rate of the coupon (%)", "Final price", "Expiration Period", "Status of a coupon"};

    //Data of table
    List<Coupon> couponArray = Arrays.asList(
        new Coupon("aaa", "bbb", 100.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 60.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 160.4, 1, 1, "a"),
        new Coupon("aaa", "bbb", 220.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 70.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 150.2, 1, 1, "a"),
        new Coupon("aaa", "bbb", 160.3, 1, 1, "a"),
        new Coupon("aaa", "bbb", 210.3, 1, 1, "a"));

    int lengthArray = couponArray.size();
    Object data[][] = new Object[lengthArray][7];
    for (int i = 0; i < lengthArray; i++){
      Coupon sTmp = couponArray.get(i);
      data[i][0] = sTmp.getNameOfCouponProvider();
      data[i][1] = sTmp.getNameOfProduct();
      data[i][2] = sTmp.getPriceOfProduct();//Double.toString(sTmp.getPriceOfProduct());
      data[i][3] = Integer.toString(sTmp.getDiscountRateOfCoupon());

      //Get final price
      double finalPrice = sTmp.getPriceOfProduct() -
          sTmp.getPriceOfProduct()*((double)sTmp.getDiscountRateOfCoupon()/100);
      data[i][4] = new Formatter().format("%.2f", finalPrice).toString();
      data[i][5] = Integer.toString(sTmp.getExpirationPeriod());
      data[i][6] = sTmp.getStatusOfCoupon();
    }

    DefaultTableModel tableModel = new DefaultTableModel(data, columns) {

      @Override
      public boolean isCellEditable(int row, int column) {
        //all cells false
        return false;
      }

      //This makes values in "Price" column treated as numerical values
      // instead of String values.
      @Override
      public Class<?> getColumnClass(int columnIndex)
      {
        if (columnIndex == 2)
        {
          return Double.class;
        }
        return super.getColumnClass(columnIndex);
      }
    };
    JTable table = new JTable();
    table.setModel(tableModel);

    //Sort table
    table.setAutoCreateRowSorter(true);

    JFrame frame = new JFrame();
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    frame.getContentPane().add(new JScrollPane(table), BorderLayout.CENTER);
    frame.pack();
    frame.setVisible(true);
  }
}

class Coupon
{
  private String nameOfCouponProvider;
  private String nameOfProduct;
  private double priceOfProduct;
  private int discountRateOfCoupon;
  private int expirationPeriod;
  private String statusOfCoupon;

  Coupon(String nameOfCouponProvider, String nameOfProduct,
         double priceOfProduct, int discountRateOfCoupon,
         int expirationPeriod, String statusOfCoupon)
  {
    this.nameOfCouponProvider = nameOfCouponProvider;
    this.nameOfProduct = nameOfProduct;
    this.priceOfProduct = priceOfProduct;
    this.discountRateOfCoupon = discountRateOfCoupon;
    this.expirationPeriod = expirationPeriod;
    this.statusOfCoupon = statusOfCoupon;
  }

  String getNameOfCouponProvider() { return nameOfCouponProvider; }
  String getNameOfProduct() { return nameOfProduct; }
  double getPriceOfProduct() { return priceOfProduct; }
  int getDiscountRateOfCoupon() { return discountRateOfCoupon; }
  int getExpirationPeriod() { return expirationPeriod; }
  String getStatusOfCoupon() { return statusOfCoupon; }
}


问:
Discern contextmenu events which are result of touch action?
I have an application where elements inside of a SVG element can be drag and dropped (thanks to d3-drag and d3-zoom, see https://bl.ocks.org/mbostock/3127661b6f13f9316be745e77fdfb084 as an example for such a page) which can be also used on touch-enabled devices but what happens is that after a long press a context menu pops up (at least in IE11, Edge and Firefox) and is in the way, therefore I want to prevent the context menu from showing up in this case.

I could just disallow showing the context menu in general by handling the contextmenu event and doing .preventDefault() on the event object but I wonder whether a solution exists where the context menu is just blocked from showing in the touch case and it would still show up for e.g. right-clicks or when the menu key is pressed while the element has focus.

I thought at first I could look at the .button and .buttons properties of the event object but it seems like those values are arbitrarily 0 or 2 and it looks like it can be found in any combination when testing in various browsers on different systems.

The element already has touch-action: none.

Is there some working way to make the context menu just not show up a result of a touch long-presses?

It looks like .preventDefault() on the relevant touch events wouldn't be an option.

答:
jQuery UI Touch Punch just solves it all.

It's a Touch Event Support for jQuery UI. Basically, it just wires touch event back to jQuery UI. Tested on iPad, iPhone, Android and other touch-enabled mobile devices. I used jQuery UI sortable and it works like a charm.

http://touchpunch.furf.com/


问:
Picasso - can't find "context"
First of all,  I am a beginner and this may be a stupid question for you. I need to pass context to the following code in order to load an image in the recyclerview. Tried several options but any of them is not a success. My problem is how to find the context that to pass in the following code.

```<code>Picasso.with(context here).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
</code>```

Here is the full code which causes the problem(I am trying to pass an image to an recyclerview)

```<code>public class WishListAdapter extends RecyclerView.Adapter<WishListAdapter.DerpHolder> {

    private List<WishListItem> listData;
    private LayoutInflater inflater;

    public WishListAdapter(List<WishListItem> listData, Context c) {
        inflater = LayoutInflater.from(c);
        this.listData = listData;
    }

    @Override
    public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.wish_list_item, parent, false);
        return new DerpHolder(view);
    }

    @Override
    public void onBindViewHolder(DerpHolder holder, int position) {

    }

    public void setListData(ArrayList<WishListItem> exerciseList) {
        this.listData.clear();
        this.listData.addAll(exerciseList);
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ImageView thumbnail;
        TextView title;
        TextView subTitle;
        View container;

        public DerpHolder(View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.im_item_icon);

            //subTitle = itemView.findViewById(R.id.lbl_item_sub_title);

            //title = itemView.findViewById(R.id.lbl_item_text);

            container = itemView.findViewById(R.id.cont_item_root);
            container.setOnClickListener(this);
            Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
        }

        @Override
        public void onClick(View v) {
            Log.d("janitha", "item clicked");

        }
</code>```

Also I have read following too:-Picasso and context

Expect help from somebody.

答:
You haven't saved context from your constructor. Do as like as this: </p>

```<code>public class WishListAdapter extends
     RecyclerView.Adapter<WishListAdapter.DerpHolder> {

    private List<WishListItem> listData;
    private LayoutInflater inflater;
    Context context;

    public WishListAdapter(List<WishListItem> listData, Context c) {
        inflater = LayoutInflater.from(c);
        this.listData = listData;
        this.context = c;
    }

    @Override
    public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.wish_list_item, parent, false);
        return new DerpHolder(view);
    }

    @Override
    public void onBindViewHolder(DerpHolder holder, int position) {

    }

    public void setListData(ArrayList<WishListItem> exerciseList) {
        this.listData.clear();
        this.listData.addAll(exerciseList);
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ImageView thumbnail;
        TextView title;
        TextView subTitle;
        View container;

        public DerpHolder(View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.im_item_icon);

            //subTitle = itemView.findViewById(R.id.lbl_item_sub_title);

            //title = itemView.findViewById(R.id.lbl_item_text);

            container = itemView.findViewById(R.id.cont_item_root);
            container.setOnClickListener(this);
            Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
        }

        @Override
        public void onClick(View v) {
            Log.d("janitha", "item clicked");

        }
</code>```

ContentLicense: CC BY-SA 4.0

Title: Picasso - can't find "context"

Body:
First of all,  I am a beginner and this may be a stupid question for you. I need to pass context to the following code in order to load an image in the recyclerview. Tried several options but any of them is not a success. My problem is how to find the context that to pass in the following code.

Picasso.with(context here).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);

Here is the full code which causes the problem(I am trying to pass an image to an recyclerview)

public class WishListAdapter extends RecyclerView.Adapter<WishListAdapter.DerpHolder> {

    private List<WishListItem> listData;
    private LayoutInflater inflater;

    public WishListAdapter(List<WishListItem> listData, Context c) {
        inflater = LayoutInflater.from(c);
        this.listData = listData;
    }

    @Override
    public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.wish_list_item, parent, false);
        return new DerpHolder(view);
    }

    @Override
    public void onBindViewHolder(DerpHolder holder, int position) {

    }

    public void setListData(ArrayList<WishListItem> exerciseList) {
        this.listData.clear();
        this.listData.addAll(exerciseList);
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ImageView thumbnail;
        TextView title;
        TextView subTitle;
        View container;

        public DerpHolder(View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.im_item_icon);

            //subTitle = itemView.findViewById(R.id.lbl_item_sub_title);

            //title = itemView.findViewById(R.id.lbl_item_text);

            container = itemView.findViewById(R.id.cont_item_root);
            container.setOnClickListener(this);
            Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
        }

        @Override
        public void onClick(View v) {
            Log.d("janitha", "item clicked");

        }

Also I have read following too:-Picasso and context

Expect help from somebody.

Body:
You haven't saved context from your constructor. Do as like as this:

public class WishListAdapter extends
     RecyclerView.Adapter<WishListAdapter.DerpHolder> {

    private List<WishListItem> listData;
    private LayoutInflater inflater;
    Context context;

    public WishListAdapter(List<WishListItem> listData, Context c) {
        inflater = LayoutInflater.from(c);
        this.listData = listData;
        this.context = c;
    }

    @Override
    public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.wish_list_item, parent, false);
        return new DerpHolder(view);
    }

    @Override
    public void onBindViewHolder(DerpHolder holder, int position) {

    }

    public void setListData(ArrayList<WishListItem> exerciseList) {
        this.listData.clear();
        this.listData.addAll(exerciseList);
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ImageView thumbnail;
        TextView title;
        TextView subTitle;
        View container;

        public DerpHolder(View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.im_item_icon);

            //subTitle = itemView.findViewById(R.id.lbl_item_sub_title);

            //title = itemView.findViewById(R.id.lbl_item_text);

            container = itemView.findViewById(R.id.cont_item_root);
            container.setOnClickListener(this);
            Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
        }

        @Override
        public void onClick(View v) {
            Log.d("janitha", "item clicked");

        }


问:
How to make friendly custom URL for deployed app
After deploying an App Maker app, how does one set a friendly URL, or custom domain, or make it appear in the list of your G Suite domain apps?

I've looked through App Settings and Edit Deployment, but there is nothing to be found, the unique deployment URL's a fairly difficult to remember.

答:
I ended up embedding it in a G Suite "new" sites page with the "embed URL" tool.
This isn't ideal, as it has a large header that takes up some room at the top, and the AppMaker web app already has a header.
But it does provide a quick friendly URL.</p>


答:
Try,

```<code>private Context context;
</code>```

and in your constructor,

```<code>this.context = c;
</code>```

now you can use 'context' as a parameter.

Title: Picasso - can't find "context"

Body:
Try,

private Context context;

and in your constructor,

this.context = c;

now you can use 'context' as a parameter.


问:
Javascript dynamic nested objects
I was looking into how to create a dynamic nested objects from a string, for example, a string "obj1.obj2.obj3.obj4", how do you turn that into nested objects with the same order.

I googled around and i found this nice and clean code, but i did not understand how it worked, and there was no explanation on the page where it was written, can someone explain how this works please?

here is the code:

var s = "key1.key2.key3.key4";

var a = s.split('.');

var obj = {};
var temp = obj;

for (var k =0; k < a.length; k++) {
 temp = temp[a[k]] = {};
  console.log(temp);
}

console.log(obj);```
</div>
</div>
</p>

<p>why is there a <code>var temp = obj</code>?</p>

<p>what does this line do?:</p>

```temp = temp[a[k]] = {};
```

also, the console.log(temp) inside the loop always logs an empty object {}, why?

Thanks for the feedback!

答:
It seems where you are iterating the array, in that temp object is newly creating and assigning key to obj.

```<code>temp = temp[a[k]] = {};
</code>```

above line simply assigns a[index] value as a key to the new object and as a reference to obj the nested object is created.

for your question,

why is there a var temp = obj?

it copies obj object into temp variable

also, the console.log(temp) inside the loop always logs an empty object {}, why?

since you are recreating an empty object (or reassigning).

Title: Javascript dynamic nested objects

Body:
I was looking into how to create a dynamic nested objects from a string, for example, a string "obj1.obj2.obj3.obj4", how do you turn that into nested objects with the same order.

I googled around and i found this nice and clean code, but i did not understand how it worked, and there was no explanation on the page where it was written, can someone explain how this works please?

here is the code:

var s = "key1.key2.key3.key4";

var a = s.split('.');

var obj = {};
var temp = obj;

for (var k =0; k < a.length; k++) {
 temp = temp[a[k]] = {};
  console.log(temp);
}

console.log(obj);

why is there a var temp = obj?

what does this line do?:

temp = temp[a[k]] = {};

also, the console.log(temp) inside the loop always logs an empty object {}, why?

Thanks for the feedback!

Body:
It seems where you are iterating the array, in that temp object is newly creating and assigning key to obj.

temp = temp[a[k]] = {};

above line simply assigns a[index] value as a key to the new object and as a reference to obj the nested object is created.

for your question,

why is there a var temp = obj?

it copies obj object into temp variable

also, the console.log(temp) inside the loop always logs an empty object {}, why?

since you are recreating an empty object (or reassigning).


问:
Triggering the other component function from my component using @viewChild
In my app I have multiple components, in that I have to trigger the other component function from one component. There is no relationship between two components.In this case tried with @viewChild.

While calling the function getting the TypeError: Cannot read property 'showHelp' of undefined error.

Is @viewChild only for parent and child component interaction, is this possible only via service?

```<code>import { ChangeListComponent } from '../change-list/change-list.component';
    export class WeatherReportComponent {
        @ViewChild(ChangeListComponent) private changeListComponent:ChangeListComponent;
        showHelp(){
            this.changeListComponent.showHelp();
        }
    }
</code>```

答:
Below is the Child component where you can send some values on button click, drop down selection to parent component. On button click we will trigger childToParent event from child component with name as value

```<code>import { Component, Input, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <input type="textbox" [(ngModel)]='masterName'>
    <button (click)="sendToParent(masterName)" >sendToParent</button>
  `
})
export class AppChildComponent {
  //getting value from parent to child
  @Input('master') masterName: string;

  @Output() childToParent = new EventEmitter<String>();

  sendToParent(name){
    this.childToParent.emit(name);
  }
}
</code>```

Below is the master component where childToParent method is triggered from child component with the emitted value.

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  //passing values from parent to child
  master = "child";

  //Getting value from child
  childToParent(name){
    this.master=name;
  }

}
</code>```

You can refer this link for working version

Body:
In my app I have multiple components, in that I have to trigger the other component function from one component. There is no relationship between two components.In this case tried with @viewChild.

While calling the function getting the TypeError: Cannot read property 'showHelp' of undefined error.

Is @viewChild only for parent and child component interaction, is this possible only via service?

import { ChangeListComponent } from '../change-list/change-list.component';
    export class WeatherReportComponent {
        @ViewChild(ChangeListComponent) private changeListComponent:ChangeListComponent;
        showHelp(){
            this.changeListComponent.showHelp();
        }
    }

Body:
Below is the Child component where you can send some values on button click, drop down selection to parent component. On button click we will trigger childToParent event from child component with name as value

import { Component, Input, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  template: `
    <input type="textbox" [(ngModel)]='masterName'>
    <button (click)="sendToParent(masterName)" >sendToParent</button>
  `
})
export class AppChildComponent {
  //getting value from parent to child
  @Input('master') masterName: string;

  @Output() childToParent = new EventEmitter<String>();

  sendToParent(name){
    this.childToParent.emit(name);
  }
}

Below is the master component where childToParent method is triggered from child component with the emitted value.

import { Component, Output,EventEmitter } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  //passing values from parent to child
  master = "child";

  //Getting value from child
  childToParent(name){
    this.master=name;
  }

}

You can refer this link for working version


问:
Angular4 *ngFor how to loop nested array using its key name
I have the following data sample:

for now i have two nested loop, but what i want to do is, Is it possible to loop through specific key, such as *ngFor="let key of myArray.functionalArea"

My current code is:

```<code><span *ngFor="let jobByField of countOfJobsByFields">
  <span  *ngFor="let jobByWorkType of countOfJobsByFields?.workType">
    <li (click)="searchByWorkType(jobByWorkType?._id)"><a>{{ jobByWorkType?._id }}<span class="badge badge-default pull-right item-plus-icon-custom-style">{{ jobByWorkType.total }}</span></a></li>
 </span>
</code>```

and for second key i have this:

```<code><span *ngFor="let jobByField of countOfJobsByFields">
  <span  *ngFor="let jobByFunctionalArea of countOfJobsByFields?.functionalArea">
    <li (click)="searchByFunctionalArea(jobByFunctionalArea?._id)"><a>{{ jobByWorkType?._id }}<span class="badge badge-default pull-right item-plus-icon-custom-style">{{ jobByFunctionalArea.total }}</span></a></li>
 </span>
</code>```

Note i can not use the same  for both because they are separate element in my html.

答:
Use following code with ng-container ,it will avoid the extra div that has been used with *ngIf</p>

```<code><span *ngFor="let jobByField of countOfJobsByFields">
    <ng-container *ngIf='jobByField.workType'>
        <span  *ngFor="let jobByWorkType of jobByField.workType">
            {{jobByWorkType._id}}
        </span>
    </ng-container>

    <ng-container *ngIf='jobByField.functionalArea'>
        <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
            {{jobByWorkType._id}}
        </span>
    </ng-container>
</span>`
</code>```

Body:
I have the following data sample:

for now i have two nested loop, but what i want to do is, Is it possible to loop through specific key, such as *ngFor="let key of myArray.functionalArea"

My current code is:

{{ jobByWorkType?._id }}{{ jobByWorkType.total }}

and for second key i have this:

{{ jobByWorkType?._id }}{{ jobByFunctionalArea.total }}

Note i can not use the same  for both because they are separate element in my html.

Body:
Use following code with ng-container ,it will avoid the extra div that has been used with *ngIf

<span *ngFor="let jobByField of countOfJobsByFields">
    <ng-container *ngIf='jobByField.workType'>
        <span  *ngFor="let jobByWorkType of jobByField.workType">
            {{jobByWorkType._id}}
        </span>
    </ng-container>

    <ng-container *ngIf='jobByField.functionalArea'>
        <span  *ngFor="let jobByWorkType of jobByField.functionalArea">
            {{jobByWorkType._id}}
        </span>
    </ng-container>
</span>`


答:
Modify your code as following:

```<code>private List<WishListItem> listData;
private LayoutInflater inflater;
private Context mContext;

public WishListAdapter(List<WishListItem> listData, Context c) {
    inflater = LayoutInflater.from(c);
    this.listData = listData;
    this.mContext = c;
}
</code>```

Then use mContext with Picasso:

```<code>Picasso.with(mContext).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
</code>```

Title: Picasso - can't find "context"

Body:
Modify your code as following:

private List<WishListItem> listData;
private LayoutInflater inflater;
private Context mContext;

public WishListAdapter(List<WishListItem> listData, Context c) {
    inflater = LayoutInflater.from(c);
    this.listData = listData;
    this.mContext = c;
}

Then use mContext with Picasso:

Picasso.with(mContext).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);


问:
How to programmatically set WCF client maxBufferSize parameters?
I am setting wcf client parameters programmatically like below:

```<code>try
{
ServiceReference1.MyDbServiceClient webService =
    new ServiceReference1.MyDbServiceClient(new System.ServiceModel.BasicHttpBinding(),
    new System.ServiceModel.EndpointAddress((string)((App)Application.Current).Resources["wcfMyDBServiceEndPoint"]));

    webService.GetSeriesImagesCompleted += new EventHandler<ServiceReference1.GetSeriesImagesCompletedEventArgs>(webService_GetSeriesImagesCompleted);
    webService.GetSeriesImagesAsync(index);
}
</code>```

It works just fine for the default maxBufferSize.  However when a client exceeds the default size, an exception is throughn: "the maximum message size quota for incoming messages (65536) has been exceeded."

How to set this parameter in code?
Thanks.

答:
```<code>BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.CloseTimeout = new TimeSpan(00, 05, 00);
binding.OpenTimeout = new TimeSpan(00, 05, 00);
binding.ReceiveTimeout = new TimeSpan(00, 05, 00);
binding.SendTimeout = new TimeSpan(00, 05, 00);
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;

binding.GetType().GetProperty("ReaderQuotas").SetValue(binding, XmlDictionaryReaderQuotas.Max, null);
</code>```

Create binding based on your requirement.

ContentLicense: CC BY-SA 2.5

Body:
I am setting wcf client parameters programmatically like below:

try
{
ServiceReference1.MyDbServiceClient webService =
    new ServiceReference1.MyDbServiceClient(new System.ServiceModel.BasicHttpBinding(),
    new System.ServiceModel.EndpointAddress((string)((App)Application.Current).Resources["wcfMyDBServiceEndPoint"]));

    webService.GetSeriesImagesCompleted += new EventHandler<ServiceReference1.GetSeriesImagesCompletedEventArgs>(webService_GetSeriesImagesCompleted);
    webService.GetSeriesImagesAsync(index);
}

It works just fine for the default maxBufferSize.  However when a client exceeds the default size, an exception is throughn: "the maximum message size quota for incoming messages (65536) has been exceeded."

How to set this parameter in code?
Thanks.

Body:
BasicHttpBinding binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
binding.CloseTimeout = new TimeSpan(00, 05, 00);
binding.OpenTimeout = new TimeSpan(00, 05, 00);
binding.ReceiveTimeout = new TimeSpan(00, 05, 00);
binding.SendTimeout = new TimeSpan(00, 05, 00);
binding.TextEncoding = System.Text.Encoding.UTF8;
binding.MaxReceivedMessageSize = int.MaxValue;
binding.MaxBufferSize = int.MaxValue;

binding.GetType().GetProperty("ReaderQuotas").SetValue(binding, XmlDictionaryReaderQuotas.Max, null);

Create binding based on your requirement.


问:
How to fill an array with random values from a range? (Duplicates are OK.)
I am new to C++, I have a problem of array manipulation. I have an array of X with length 100, I need to fill the value of X with integer value of 1 to 10 (1,2,3,4,5,6,7,8,9,10) randomly.
I know that there will be duplicate, maybe like 1 printed ten times, etc, but that's really what I want.

Here is what I have:

an array of X:

```<code>int X[100];
</code>```

Here is my code snippet:

```<code>int* X = NULL;
int* val = NULL;
int length1= 100;
int length2= 10;
X = new int[length1];
val = new int[length2];
int i;
int j;

for (i = 0; i < isi; i++) {
    val[i] = i;
    for (j = 0; j < length1; j++) {
        if (j > i) {
            X[j] = val[i];
        } else {
            X[j] = val[0];
        }
        cout << "X[" << j << "] = " << X[j] << "\n";
        Sleep(1);
    }
}
</code>```

Code above makes the array X from index 0 to 99 has value of 0, then index 0 to 99 has value of 1 and so the other index until the index 0 to 99 has value of 9.

This is not what I want, what I want is to make it (if it is not random) index 0 to 9 has value of 0, then 10 to 19 has value of 1 ... until index 90 to 99 has value of 9. Hope my explanation clear.

I have come to a question in stackoverflow: How would you make an array of 10000 with only values of 1-1000 inclusive?

But still can't resolve my problem my self.
Can someone please give me solution to this.

Thank you in advance

答:
I think others have pointed it out but you have to first write the pre-compiler directive #include <ctime> and then use the srand function. Most would say don't use that but since you and I are at the basics our teachers, respectively, start us off with that. And it might work with your compiler as well.
Here is a link to learn more about it. I would have commented but I can't.
http://www.cplusplus.com/reference/cstdlib/srand/

Body:
I am new to C++, I have a problem of array manipulation. I have an array of X with length 100, I need to fill the value of X with integer value of 1 to 10 (1,2,3,4,5,6,7,8,9,10) randomly.
I know that there will be duplicate, maybe like 1 printed ten times, etc, but that's really what I want.

Here is what I have:

an array of X:

int X[100];

Here is my code snippet:

int* X = NULL;
int* val = NULL;
int length1= 100;
int length2= 10;
X = new int[length1];
val = new int[length2];
int i;
int j;

for (i = 0; i < isi; i++) {
    val[i] = i;
    for (j = 0; j < length1; j++) {
        if (j > i) {
            X[j] = val[i];
        } else {
            X[j] = val[0];
        }
        cout << "X[" << j << "] = " << X[j] << "\n";
        Sleep(1);
    }
}

Code above makes the array X from index 0 to 99 has value of 0, then index 0 to 99 has value of 1 and so the other index until the index 0 to 99 has value of 9.

This is not what I want, what I want is to make it (if it is not random) index 0 to 9 has value of 0, then 10 to 19 has value of 1 ... until index 90 to 99 has value of 9. Hope my explanation clear.

I have come to a question in stackoverflow: How would you make an array of 10000 with only values of 1-1000 inclusive?

But still can't resolve my problem my self.
Can someone please give me solution to this.

Thank you in advance


答:
Please declare context variable like below and use it :</p>

```<code>public class WishListAdapter extends RecyclerView.Adapter<WishListAdapter.DerpHolder> {

    private List<WishListItem> listData;
    private LayoutInflater inflater;
    private Context context

    public WishListAdapter(List<WishListItem> listData, Context c) {
        inflater = LayoutInflater.from(c);
        this.listData = listData;
        this.context = c;
    }

    @Override
    public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.wish_list_item, parent, false);
        return new DerpHolder(view);
    }

    @Override
    public void onBindViewHolder(DerpHolder holder, int position) {

    }

    public void setListData(ArrayList<WishListItem> exerciseList) {
        this.listData.clear();
        this.listData.addAll(exerciseList);
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ImageView thumbnail;
        TextView title;
        TextView subTitle;
        View container;

        public DerpHolder(View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.im_item_icon);

            //subTitle = itemView.findViewById(R.id.lbl_item_sub_title);

            //title = itemView.findViewById(R.id.lbl_item_text);

            container = itemView.findViewById(R.id.cont_item_root);
            container.setOnClickListener(this);
            Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
        }

        @Override
        public void onClick(View v) {
            Log.d("janitha", "item clicked");

        }
</code>```

Title: Picasso - can't find "context"

Body:
Please declare context variable like below and use it :

public class WishListAdapter extends RecyclerView.Adapter<WishListAdapter.DerpHolder> {

    private List<WishListItem> listData;
    private LayoutInflater inflater;
    private Context context

    public WishListAdapter(List<WishListItem> listData, Context c) {
        inflater = LayoutInflater.from(c);
        this.listData = listData;
        this.context = c;
    }

    @Override
    public WishListAdapter.DerpHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        View view = inflater.inflate(R.layout.wish_list_item, parent, false);
        return new DerpHolder(view);
    }

    @Override
    public void onBindViewHolder(DerpHolder holder, int position) {

    }

    public void setListData(ArrayList<WishListItem> exerciseList) {
        this.listData.clear();
        this.listData.addAll(exerciseList);
    }

    @Override
    public int getItemCount() {
        return listData.size();
    }

    class DerpHolder extends RecyclerView.ViewHolder implements View.OnClickListener {

        ImageView thumbnail;
        TextView title;
        TextView subTitle;
        View container;

        public DerpHolder(View itemView) {
            super(itemView);
            thumbnail = itemView.findViewById(R.id.im_item_icon);

            //subTitle = itemView.findViewById(R.id.lbl_item_sub_title);

            //title = itemView.findViewById(R.id.lbl_item_text);

            container = itemView.findViewById(R.id.cont_item_root);
            container.setOnClickListener(this);
            Picasso.with(context ).load("http://i.imgur.com/DvpvklR.png").into(thumbnail);
        }

        @Override
        public void onClick(View v) {
            Log.d("janitha", "item clicked");

        }


问:
Angular - close modal window with event
I would like to fire an event when the close button is clicked within the modal window.
The button has the attribute data-dismiss="modal" and doesn't call the click event. Is it possible to have data-dismiss and click event or only click event and close modal from class?

```<code><div class="modal-dialog">
 <div class="modal-content">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal" (click)="close()">×</button>
    <h4 class="modal-title">{{modalHeader}}</h4>
  </div>
 </div>
</div>

close() {
    //Can I close modal window manually?
    this.onClose.emit();
  }
</code>```

Method close dont call because button has data-dismiss attribute.

Thank you

答:
You cannot have the data-dismiss="modal" and call a function, instead inside your close function do the following:

```<code>close() {
    $('.modal').modal('hide');
}
</code>```

I'm assuming you're using bootstrap, so you're using jQuery.

Title: Angular - close modal window with event

Body:
I would like to fire an event when the close button is clicked within the modal window.
The button has the attribute data-dismiss="modal" and doesn't call the click event. Is it possible to have data-dismiss and click event or only click event and close modal from class?

    <button type="button" class="close" data-dismiss="modal" (click)="close()">×</button>

{{modalHeader}}

close() {
    //Can I close modal window manually?
    this.onClose.emit();
  }

Method close dont call because button has data-dismiss attribute.

Thank you

Body:
You cannot have the data-dismiss="modal" and call a function, instead inside your close function do the following:

close() {
    $('.modal').modal('hide');
}

I'm assuming you're using bootstrap, so you're using jQuery.


问:
how use serach box in select type jqgrid when edit inline
15.1
i use select in jqGrid. i need to be able search into  select .
this demo:
      https://jsfiddle.net/dnfk8hmr/95/

```<code>colModel: [
    { name: "act", template: "actions" },
    { name: "id", width: 50 },
    { name: "PackageCode", width: 110 , editable: true },
    { name: "Name", width: 200, editable: true },
    { name: "d", width: 100, editable: true ,edittype: 'select',
      editoptions: { value: 'FE:FedEx;TN:TNT;IN:Intim;FE2:FedEx2;TN2:TNT2;IN2:Intim2'}
    },
],
</code>```

I think use  dataInit:function(el){} jqGrid

答:
i want Able to search combox .This solution

```<code>   dataInit: function (domElem) {
            $(domElem).addClass("js-example-basic-single");
           $('.js-example-basic-single').select2();
                                    }
</code>```

please see demo

Body:
15.1
i use select in jqGrid. i need to be able search into  select .
this demo:
      https://jsfiddle.net/dnfk8hmr/95/

colModel: [
    { name: "act", template: "actions" },
    { name: "id", width: 50 },
    { name: "PackageCode", width: 110 , editable: true },
    { name: "Name", width: 200, editable: true },
    { name: "d", width: 100, editable: true ,edittype: 'select',
      editoptions: { value: 'FE:FedEx;TN:TNT;IN:Intim;FE2:FedEx2;TN2:TNT2;IN2:Intim2'}
    },
],

I think use  dataInit:function(el){} jqGrid

Body:
i want Able to search combox .This solution

   dataInit: function (domElem) {
            $(domElem).addClass("js-example-basic-single");
           $('.js-example-basic-single').select2();
                                    }

please see demo


问:
How to take different types of elements from Map
Here I got two hash sets:

```<code>var vertexes = new HashSet[String]()
var edges = new HashSet[RDFTriple]() //RDFTriple is a class
</code>```

I want to put them into a map like this:

```<code>var graph = Map[String, HashSet[_]]()
graph.put("e", edges)
graph.put("v", vertexes)
</code>```

But now I want to take vertexes and edges respectively but failed. I have tried something like the following:

```<code>val a = graph.get("v")
a match {
  case _ => val v = a
}
val b = graph.get("e")
b match {
  case _ => val e = b
}
</code>```

But v and e are recognized as Option[HashSet[_]] while I want are HashSet[String] and HashSet[RDFTriple].

How can I do this?

I will apprecicate it so much cuz it bothers me too long.

答:
It is not recommended to use different types in the same Map, however you could some the problem by using Some and asInstanceOf like this:

```<code>val v = a match {
  case Some(a) => a.asInstanceOf[HashSet[String]]
  case None    => // do something
}
</code>```

Note that the assignment val v = ... is done outside the match to allow usage of the variable afterwards. The match for the edges is similar.

However, a better solution would be to use a case class for the graph. Then you would avoid a lot of hassle.

```<code>case class Graph(vertexes: HashSet[String], edges: HashSet[RDFTriple])

val graph = Graph(vertexes, edges)
val v = graph.vertexes // HashSet[String]
val e = graph.edges    // HashSet[RDFTriple]
</code>```

Body:
Here I got two hash sets:

var vertexes = new HashSet[String]()
var edges = new HashSet[RDFTriple]() //RDFTriple is a class

I want to put them into a map like this:

var graph = Map[String, HashSet[_]]()
graph.put("e", edges)
graph.put("v", vertexes)

But now I want to take vertexes and edges respectively but failed. I have tried something like the following:

val a = graph.get("v")
a match {
  case _ => val v = a
}
val b = graph.get("e")
b match {
  case _ => val e = b
}

But v and e are recognized as Option[HashSet[_]] while I want are HashSet[String] and HashSet[RDFTriple].

How can I do this?

I will apprecicate it so much cuz it bothers me too long.

Body:
It is not recommended to use different types in the same Map, however you could some the problem by using Some and asInstanceOf like this:

val v = a match {
  case Some(a) => a.asInstanceOf[HashSet[String]]
  case None    => // do something
}

Note that the assignment val v = ... is done outside the match to allow usage of the variable afterwards. The match for the edges is similar.

However, a better solution would be to use a case class for the graph. Then you would avoid a lot of hassle.

case class Graph(vertexes: HashSet[String], edges: HashSet[RDFTriple])

val graph = Graph(vertexes, edges)
val v = graph.vertexes // HashSet[String]
val e = graph.edges    // HashSet[RDFTriple]


问:
Show single category Axis For Amchart Multi Panel Horizon Chart
I'm trying to show category axis for Amcharts Multi Panel Horizon chart. I tried setting the category axis property to true, but it enabled the x axis for all the charts.

```<code> "showCategoryAxis": true,
</code>```

Is there a work around to show Multi horizon chart with a single x axis.
Here is demo with "showCategoryAxis": true,.

答:
Modify the buildPanel function so that showCategoryAxis is set to false by default for all panels and then set one of them (presumably the last one) at the end of the init handler loop to false. You'll also want to set axisHeight to 0 in categoryAxesSettings so that the height of the last panel, or whichever one has the category axis enabled, doesn't shrink.

```<code>function buildPanel( dim ) {
  return {
    // ...
    "showCategoryAxis": false,
    // ...
  };
}

//in addInitHandler:
  for ( var i = 0; i < dimensions.length; i++ ) {
    // ...
  }

  chartPanels[chartPanels.length - 1].showCategoryAxis = true;

  chart.panels = chartPanels;
</code>```

Demo

Body:
I'm trying to show category axis for Amcharts Multi Panel Horizon chart. I tried setting the category axis property to true, but it enabled the x axis for all the charts.

 "showCategoryAxis": true,

Is there a work around to show Multi horizon chart with a single x axis.
Here is demo with "showCategoryAxis": true,.

Body:
Modify the buildPanel function so that showCategoryAxis is set to false by default for all panels and then set one of them (presumably the last one) at the end of the init handler loop to false. You'll also want to set axisHeight to 0 in categoryAxesSettings so that the height of the last panel, or whichever one has the category axis enabled, doesn't shrink.

function buildPanel( dim ) {
  return {
    // ...
    "showCategoryAxis": false,
    // ...
  };
}

//in addInitHandler:
  for ( var i = 0; i < dimensions.length; i++ ) {
    // ...
  }

  chartPanels[chartPanels.length - 1].showCategoryAxis = true;

  chart.panels = chartPanels;

Demo


问:
How to use INTO and GROUP BY clause together
```<code>SELECT cast ( SUBSTRING ( CAST ("ProcessingDate" AS text), 5, 2 ) as integer),
    COUNT(*) INTO resultValue1,resultValue2
FROM "DemoLogs"."Project"
WHERE "Addr" = 'Y' AND "ProcessingDate" >= 20160110
GROUP BY 1
ORDER BY 1;
</code>```

In my database, the ProcessingDate is stored as YYYYMMDD. So, I am extracting its month from it.

This query is working fine if we remove the INTO clause but, I want to store the result to use it further.

So what should be the datatype of the variable resultValue1 and  resultValue2 how to store the data(because data will be multiple).

As I am new to PostgreSQL I don't know how to do this can anybody help me out.

答:
Try this:</p>

```<code>SELECT cast ( SUBSTRING ( cast ("ProcessingDate" as text),5 , 2 ) as integer)resultValue1,
    COUNT(*)resultValue2
INTO <Table Name>
FROM "DemoLogs"."Project"
WHERE "Addr" = 'Y'
AND "ProcessingDate" >= '20160110'
Group By 1
Order By 1;
</code>```

Body:
SELECT cast ( SUBSTRING ( CAST ("ProcessingDate" AS text), 5, 2 ) as integer),
    COUNT(*) INTO resultValue1,resultValue2
FROM "DemoLogs"."Project"
WHERE "Addr" = 'Y' AND "ProcessingDate" >= 20160110
GROUP BY 1
ORDER BY 1;

In my database, the ProcessingDate is stored as YYYYMMDD. So, I am extracting its month from it.

This query is working fine if we remove the INTO clause but, I want to store the result to use it further.

So what should be the datatype of the variable resultValue1 and  resultValue2 how to store the data(because data will be multiple).

As I am new to PostgreSQL I don't know how to do this can anybody help me out.

Body:
Try this:

SELECT cast ( SUBSTRING ( cast ("ProcessingDate" as text),5 , 2 ) as integer)resultValue1,
    COUNT(*)resultValue2
INTO <Table Name>
FROM "DemoLogs"."Project"
WHERE "Addr" = 'Y'
AND "ProcessingDate" >= '20160110'
Group By 1
Order By 1;


问:
Intent couldnt be initialized even after multiple tries
I have created this small program but i cant seem to make it run. It gives an error saying that intent hasnt been initialized. What should i do?

```<code>Spinner mySpinner1 = (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter<String> myAdapter1 = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.which));
    myAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner1.setAdapter(myAdapter1);

    mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0,
                                   View view,
                                   int position,
                                   long id) {
           Intent intent = new Intent(MainActivity.this, intent.class);
            switch (position) {
                case 1:
                    intent = new Intent(MainActivity.this, MainActivity2.class);
                    break;
            }
            startActivity(intent);
        }
</code>```

EDIT 1 : Added few more lines of code to make the whole situation clearer

答:
The problem is with the below line:

```<code>Intent intent = new Intent(MainActivity.this, intent.class)
</code>```

You have to pass the class of a valid Activity here, not the class of the intent.

You get the error because intent object is not yet created. So you can't use intent in that statement. You can't access an object until the object is created. In this statement you are trying to create the intent object, by using intent. That's not possible.

Body:
I have created this small program but i cant seem to make it run. It gives an error saying that intent hasnt been initialized. What should i do?

Spinner mySpinner1 = (Spinner) findViewById(R.id.spinner1);

    ArrayAdapter<String> myAdapter1 = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_list_item_1, getResources().getStringArray(R.array.which));
    myAdapter1.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    mySpinner1.setAdapter(myAdapter1);

    mySpinner1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> arg0,
                                   View view,
                                   int position,
                                   long id) {
           Intent intent = new Intent(MainActivity.this, intent.class);
            switch (position) {
                case 1:
                    intent = new Intent(MainActivity.this, MainActivity2.class);
                    break;
            }
            startActivity(intent);
        }

EDIT 1 : Added few more lines of code to make the whole situation clearer

Body:
The problem is with the below line:

Intent intent = new Intent(MainActivity.this, intent.class)

You have to pass the class of a valid Activity here, not the class of the intent.

You get the error because intent object is not yet created. So you can't use intent in that statement. You can't access an object until the object is created. In this statement you are trying to create the intent object, by using intent. That's not possible.


问:
Square each number in an array in javascript
I'm trying to square each number in an array and my original code didn't work. I looked up another way to do it, but I'd like to know WHY the original code didn't work.

Original code:

```<code>function(arr) {

    ret= [];

    for (var i = 0, len = arr.length; i < len; i++) {
        root = Math.sqrt(arr[i]);
        ret.push(root);
    }

    return ret;
}
</code>```

Working Code:

```<code>function(arr) {

    ret= [];

    for (var i = 0, len = arr.length; i < len; i++) {
        ret.push(arr[i] * arr[i]);
    }

    return ret;
}
</code>```

答:
Declarative Programming :)

let list = [1,2,3,4,5,6,7,8,9,10];
let result = list.map(x => x*x);
console.log(result);```

Body:
I'm trying to square each number in an array and my original code didn't work. I looked up another way to do it, but I'd like to know WHY the original code didn't work.

Original code:

function(arr) {

    ret= [];

    for (var i = 0, len = arr.length; i < len; i++) {
        root = Math.sqrt(arr[i]);
        ret.push(root);
    }

    return ret;
}

Working Code:

function(arr) {

    ret= [];

    for (var i = 0, len = arr.length; i < len; i++) {
        ret.push(arr[i] * arr[i]);
    }

    return ret;
}


问:
Pattern to get string between two specific words/characters using grep
I need to extract email address from a string like this (I'm making a log parser):
<some text> from=someuser@somedomain.com, <some text>

with egrep (or grep -Eo). So the string needs to be pulled out only between "from=" and "," , because the other parts of log contain email addresses too, like to= and etc

答:
A purely bash solution, requires two steps to strip prefix & suffix separately (but probably runs faster, because no subprocesses):

```<code>#!/bin/bash
orig='from=someuser@somedomain.com, <some text>'
one=${orig#*from=}
two=${one%,*}

printf "Result:\n"
printf "$orig\n"
printf "$one\n"
printf "$two\n"
</code>```

Output:

```<code>Result:
from=someuser@somedomain.com, <some text>
someuser@somedomain.com, <some text>
someuser@somedomain.com
</code>```

Notes:

${var#*pattern} using # strips from the start of $var up to pattern

${var%pattern*} using % strips from end of $var, up to pattern

similar could be accomplished with ${var/pattern/replace} (and leaving replace blank), but it's trickier since full regexp isn't supported (ie, can't use ^ or '$'), so you can't do (for example) /^from=//, but you could do in step one ${var/*from=/} and then in step two, do ${var/,*/} (depending on your data, of course).

see also: http://www.tldp.org/LDP/abs/html/parameter-substitution.html

Body:
A purely bash solution, requires two steps to strip prefix & suffix separately (but probably runs faster, because no subprocesses):

#!/bin/bash
orig='from=someuser@somedomain.com, <some text>'
one=${orig#*from=}
two=${one%,*}

printf "Result:\n"
printf "$orig\n"
printf "$one\n"
printf "$two\n"

Output:

Result:
from=someuser@somedomain.com, <some text>
someuser@somedomain.com, <some text>
someuser@somedomain.com

Notes:

${var#*pattern} using # strips from the start of $var up to pattern

${var%pattern*} using % strips from end of $var, up to pattern

similar could be accomplished with ${var/pattern/replace} (and leaving replace blank), but it's trickier since full regexp isn't supported (ie, can't use ^ or '$'), so you can't do (for example) /^from=//, but you could do in step one ${var/*from=/} and then in step two, do ${var/,*/} (depending on your data, of course).

see also: http://www.tldp.org/LDP/abs/html/parameter-substitution.html


问:
Java Server Socket failure
```<code>while (true) {

    ServerSocket myServerSocket = new ServerSocket(9999);
    Socket skt = myServerSocket.accept();

    Handling obj = new Handling();
    obj.handle(skt);

}
</code>```

When i first try this it works fine and accepts the Socket but then when it loops back it says the address is in use. How do I fix this?

答:
Don't create a new ServerSocket in the loop - you only need to accept in the loop:

```<code>ServerSocket myServerSocket = new ServerSocket(9999);
while (true) {
    Socket skt = myServerSocket.accept();
    Handling obj = new Handling();
    obj.handle(skt);
}
</code>```

Title: Java Server Socket failure

Body:
while (true) {

    ServerSocket myServerSocket = new ServerSocket(9999);
    Socket skt = myServerSocket.accept();

    Handling obj = new Handling();
    obj.handle(skt);

}

When i first try this it works fine and accepts the Socket but then when it loops back it says the address is in use. How do I fix this?

Body:
Don't create a new ServerSocket in the loop - you only need to accept in the loop:

ServerSocket myServerSocket = new ServerSocket(9999);
while (true) {
    Socket skt = myServerSocket.accept();
    Handling obj = new Handling();
    obj.handle(skt);
}


答:
Here resultValue1 & resultValue2 will be tables not variables. you can group by using the column names.

Give some column alias names for both columns and group by using them.

You probably want this.

```<code>SELECT cast ( SUBSTRING ( cast ("ProcessingDate" as text),5 , 2 ) as
integer) AS resultValue1, COUNT(*) AS resultValue2
INTO <NewTable>  --NewTable will be created with those two columns
FROM "DemoLogs"."Project"
-- conditions
Group By 1
-- other contitions/clauses
;
</code>```

Kindly refer this INTO Documentation.

Hope this helps.

Title: How to use INTO and GROUP BY clause together

Body:
Here resultValue1 & resultValue2 will be tables not variables. you can group by using the column names.

Give some column alias names for both columns and group by using them.

You probably want this.

SELECT cast ( SUBSTRING ( cast ("ProcessingDate" as text),5 , 2 ) as
integer) AS resultValue1, COUNT(*) AS resultValue2
INTO <NewTable>  --NewTable will be created with those two columns
FROM "DemoLogs"."Project"
-- conditions
Group By 1
-- other contitions/clauses
;

Kindly refer this INTO Documentation.

Hope this helps.


问:
Bootstrap datepicker in TypeScript is not working
I am a newbie to Angular 4 and I am trying to make a sort of jQuery call from my HTML. I have tried wrapping this jQuery call in a TypeScript method. Upon clicking the calendar button nothing appears.

I am unsure what line to exactly add in my index.html.

Below is my code snippet :

home.component.html

```<code><h2>As of date</h2>
<div class="input-group" style="width: 230px">
    <input class="form-control date" type='text' placeholder="dd/mm/yyyy" id="date-picker"/>
    <span class="input-group-btn">
      <button class="btn btn-primary btn-icon" (click)="pickDate()">
        <i class="fa fa-calendar-o"></i>
      </button>
    </span>
</div>
</code>```

home.component.ts

```<code> import { Component, OnInit } from '@angular/core';
    import { TranslateService } from '@ngx-translate/core';
    import { TasksService } from 'app/shared';

        @Component({
          selector: 'MyFirstAngularApplication-home',
          styleUrls: [ './home.component.scss' ],
          templateUrl: './home.component.html'
        })

        export class HomeComponent {
          pickDate() {
            $('#date-picker').datepicker('show');
          }
        }
</code>```

Where exactly am I going wrong?

答:
Import jquery.min.js in home.component.html .

In home.component.ts declare jquery and $ vars like:

declare var jquery:any;
declare var $ :any;

You should be through now

Body:
I am a newbie to Angular 4 and I am trying to make a sort of jQuery call from my HTML. I have tried wrapping this jQuery call in a TypeScript method. Upon clicking the calendar button nothing appears.

I am unsure what line to exactly add in my index.html.

Below is my code snippet :

home.component.html

As of date

    <input class="form-control date" type='text' placeholder="dd/mm/yyyy" id="date-picker"/>

      <button class="btn btn-primary btn-icon" (click)="pickDate()">

      </button>

home.component.ts

 import { Component, OnInit } from '@angular/core';
    import { TranslateService } from '@ngx-translate/core';
    import { TasksService } from 'app/shared';

        @Component({
          selector: 'MyFirstAngularApplication-home',
          styleUrls: [ './home.component.scss' ],
          templateUrl: './home.component.html'
        })

        export class HomeComponent {
          pickDate() {
            $('#date-picker').datepicker('show');
          }
        }

Where exactly am I going wrong?


问:
Watson Personality insight minimum number of words required Issue
I'm following this Personality insight starter but always get below error message for API call

```<code>{"help":"http:\/\/www.ibm.com\/smarterplanet\/us\/en\/ibmwatson\/developercloud\/doc\/personality-insights\/#overviewInput","code":400,"sub_code":"S00014","error":"The number of words 2 is less than the minimum number of words required for analysis: 100"}
</code>```

Here is the curl request

```<code>curl -X POST --user xxxx:yyyy --header "Content-Type: text/plain;charset=utf-8" --data-binary "profile.txt" "https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2017-11-14"
</code>```

Am I missing something here?

答:
Personality insights requires a minimum of 100 words to work. But you won’t get a true insight until around 1,200 words (IIRC). </p>

<p>It’s telling you that you only supplied two words. If this isn’t the case, ensure that you JSON data is correctly escaped. </p>

Body:
I'm following this Personality insight starter but always get below error message for API call

{"help":"http:\/\/www.ibm.com\/smarterplanet\/us\/en\/ibmwatson\/developercloud\/doc\/personality-insights\/#overviewInput","code":400,"sub_code":"S00014","error":"The number of words 2 is less than the minimum number of words required for analysis: 100"}

Here is the curl request

curl -X POST --user xxxx:yyyy --header "Content-Type: text/plain;charset=utf-8" --data-binary "profile.txt" "https://gateway.watsonplatform.net/personality-insights/api/v3/profile?version=2017-11-14"

Am I missing something here?

Body:
Personality insights requires a minimum of 100 words to work. But you won’t get a true insight until around 1,200 words (IIRC).

It’s telling you that you only supplied two words. If this isn’t the case, ensure that you JSON data is correctly escaped.


问:
NodeJS Change variable from within a function
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

```<code>app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});
</code>```

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

答:
@Zenderx let breif this .

Node.js is Async programming , if you do any I/O event like database call ,http , timeout call .
It send then in event pool and execute in sequence .

See the comment what happens step by step.
What is happing in your code it this.

This is your api call

```<code>  app.get('/:steamid', function(req, res) {

    // excution comes inside
    var steamID;
     // then you call an I/O event and iniallized streamID but what happen here is this ,
    //this is I/O event so went to event loop for excution
    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });
    // while the block is in event loop or excution this statement run because of Async nature

    console.log(steamID); //<--- This returns undefined

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

if you want to print StreamID print it inside the block only .

```<code> steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
            console.log('Steam64: ' + res); // <- this prints out my result
            steamID = res;
        console.log(steamID);
        });
</code>```

Too study in depth of async , you can look to promise and async library in node.js .

The simplest thing to do for newbie is this .

```<code>app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, resu) {
        console.log('Steam64: ' + resu); // <- this prints out my result
        steamID = resu;
       steamAPI.getAvatarUrl(req.params.steamid, function(err, resu) {
          console.log('Avatar URL: ' + resu); // <- this prints out my result
          steamAvatarUrl = resu;
         steamAPI.registerDate(req.params.steamid, function(err, resu) {
            console.log('Registered: ' + resu); // <- this prints out my result
             steamRegisterDate = resu;
                console.log(steamID); //<--- This returns undefined

            res.render('steamid.hbs', {
           "title": steamID,
           "avatarURL": steamAvatarUrl,
           "registerDate": steamRegisterDate
              });
          });
        });
    });

});
</code>```

If you need it to be solve by promise and async module ping.

Body:
Long story short, im newish to NodeJS and im trying to change a variable after a function has been executed, however I cant return a result like I thought I could.

app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });

    steamAPI.getAvatarUrl(req.params.steamid, function(err, res) {
        console.log('Avatar URL: ' + res); // <- this prints out my result
        steamAvatarUrl = res;
    });

    steamAPI.memberSince(req.params.steamid, function(err, res) {
        console.log('Registered: ' + res); // <- this prints out my result
        steamRegisterDate = res;
    });

    console.log(steamID); //<--- This returns undefined

    res.render('steamid.hbs', {
        "title": steamID,
        "avatarURL": steamAvatarUrl,
        "registerDate": steamRegisterDate
    });
});

An help with an example/resolution of how I accomplish this would be amazing. I am a visual learner so please dont say "use this or do that" without giving some sort of example to it or I honestly wont get it lol.

Thanks ahead of time.

Body:
@Zenderx let breif this .

Node.js is Async programming , if you do any I/O event like database call ,http , timeout call .
It send then in event pool and execute in sequence .

See the comment what happens step by step.
What is happing in your code it this.

This is your api call

  app.get('/:steamid', function(req, res) {

    // excution comes inside
    var steamID;
     // then you call an I/O event and iniallized streamID but what happen here is this ,
    //this is I/O event so went to event loop for excution
    steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
        console.log('Steam64: ' + res); // <- this prints out my result
        steamID = res;
    });
    // while the block is in event loop or excution this statement run because of Async nature

    console.log(steamID); //<--- This returns undefined

    (...)
});

if you want to print StreamID print it inside the block only .

 steamAPI.ResolveVanityURL(req.params.steamid, function(err, res) {
            console.log('Steam64: ' + res); // <- this prints out my result
            steamID = res;
        console.log(steamID);
        });

Too study in depth of async , you can look to promise and async library in node.js .

The simplest thing to do for newbie is this .

app.get('/:steamid', function(req, res) {

    var steamID;
    var steamAvatarUrl;
    var steamRegisterDate;

    steamAPI.ResolveVanityURL(req.params.steamid, function(err, resu) {
        console.log('Steam64: ' + resu); // <- this prints out my result
        steamID = resu;
       steamAPI.getAvatarUrl(req.params.steamid, function(err, resu) {
          console.log('Avatar URL: ' + resu); // <- this prints out my result
          steamAvatarUrl = resu;
         steamAPI.registerDate(req.params.steamid, function(err, resu) {
            console.log('Registered: ' + resu); // <- this prints out my result
             steamRegisterDate = resu;
                console.log(steamID); //<--- This returns undefined

            res.render('steamid.hbs', {
           "title": steamID,
           "avatarURL": steamAvatarUrl,
           "registerDate": steamRegisterDate
              });
          });
        });
    });

});

If you need it to be solve by promise and async module ping.