问:
Typescript "cannot find module <module>" error using ES6 modules
I have a file in src/shared/components/A.tsx that does import B from 'components/B' (src/shared/components/B.tsx)

Typescript gives me an error cannot find module 'components/B'

This is my tsconfig.json file which is in the root directory:

```<code>{
  "compilerOptions": {
      "outDir": "./dist/",
      "sourceMap": true,
      "module": "es6",
      "target": "es6",
      "jsx": "react",
      "allowJs": true,
      "moduleResolution": "node"
  },
  "include": [
      "src/**/*"
  ],
  "exclude": [
      "node_modules"
  ],
  "baseUrl": ".",
  "paths": {
      "*": [
        "*",
        "src/shared/*" //this doesn't seem to work
      ]
  }
}
</code>```

My understanding from https://www.typescriptlang.org/docs/handbook/tsconfig-json.html is that it will try to find ./components/B first, which does not exist, then go into <baseUrl>/src/shared/components/B, which is where the file exists, so I'm not sure why I'm still seeing an error.

答: Well this was silly, paths / baseUrl belong inside compilerOptions.

Body:
I have a file in src/shared/components/A.tsx that does import B from 'components/B' (src/shared/components/B.tsx)

Typescript gives me an error cannot find module 'components/B'

This is my tsconfig.json file which is in the root directory:

{
  "compilerOptions": {
      "outDir": "./dist/",
      "sourceMap": true,
      "module": "es6",
      "target": "es6",
      "jsx": "react",
      "allowJs": true,
      "moduleResolution": "node"
  },
  "include": [
      "src/**/*"
  ],
  "exclude": [
      "node_modules"
  ],
  "baseUrl": ".",
  "paths": {
      "*": [
        "*",
        "src/shared/*" //this doesn't seem to work
      ]
  }
}

My understanding from https://www.typescriptlang.org/docs/handbook/tsconfig-json.html is that it will try to find ./components/B first, which does not exist, then go into <baseUrl>/src/shared/components/B, which is where the file exists, so I'm not sure why I'm still seeing an error.


来源: stackexchange

问:
What is the point of encrypting web.config if user can just decrypt it?
Oi, some vendor is telling my bosses that not encrypting the web.config is big security hole. This sounds like bunk to me. I mean, if someone compromises the server aren't we screwed anyways?</p>

答:
Sort of. In my case, I host on a shared hosting account. So a lot of people have access to my account and the files stored there.

Personally, I don't worry about it too much. But, if someone had a mind to, they could access that information. And even if you own the server, if it's a company then there could be a lot of people who have access to it.

For critical data, encrypting it makes sense.

ContentLicense: CC BY-SA 4.0

ContentLicense: CC BY-SA 2.5


问:
Putting image in table using innerHTML (Javascript / Html)
Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :

|item__  | price | category | category | category | category | picture |

|chicken| $20   | _______ |_ ______        | _______        | _______        | 1000.png|

```<code>        var array = csvpls();
        var table = "<tr>";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                if (j == 6) {
                table += "<td>" + "<img src='CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";
                } else if {
                table += "<td>" + array[i][j];
                }
        table += "<tr>";
        table += "</tr>";
        }

    document.getElementById("Invtable").innerHTML = table;
</code>```

This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.

In the code below

```<code>        var array = csvpls();
        var table = "<tr>";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                table += "<td>" + array[i][j];
                }
        table += "<tr>";
        table += "</tr>";
        }

    document.getElementById("Invtable").innerHTML = table;
</code>```

Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.

Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";

答:
I think there are several problems in your code that needs to be fixed :

You are not appending the td elements inside the tr but directly
inside the table, you need to move the  line table += "
";
before the nested loop.

And you are not specifying closing tags for  elements so when
you include the img tag it will mess up the layout.

Another thing just inverse the use of " and ' in your img tag
definition because HTML uses ".." to define attributes.

Here's how should be your code:

```<code>var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
  table += "<tr>";
  for (var j = 0; j < array[i].length; j++) {
    if (j == 6) {
      table += "<td>" + '<img src="CSV_Photos/' + array[i][j] + '" style ="width:500px;height:300px"></td>';
    } else if {
      table += "<td>" + array[i][j] + "</td>";
    }
  }
  table += "</tr>";
}

document.getElementById("Invtable").innerHTML = table;
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Alright, some information right off the bat, I have a table that is dynamically being created.
The table looks roughly like this :

|item__  | price | category | category | category | category | picture |

|chicken| $20   | _______ |_ ______        | _______        | _______        | 1000.png|

        var array = csvpls();
        var table = "
";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                if (j == 6) {
                table += "" + "";
                } else if {
                table += "" + array[i][j];
                }
        table += "
";
        table += "
";
        }

    document.getElementById("Invtable").innerHTML = table;

This is the code that I have at the moment, where array is a 2D array. And every (6th column in the row, I want it to be an image) When runned, this does not display any table whatsoever.

In the code below

        var array = csvpls();
        var table = "
";
        for (var i = 0; i < array.length; i++) {
            for (var j = 0; j < array[i].length; j++) {
                table += "" + array[i][j];
                }
        table += "
";
        table += "
";
        }

    document.getElementById("Invtable").innerHTML = table;

Without the if statement and the additional img content, the table displays perfectly, but obviously 1000.png shows up instead of the actual image.
CSV_Photos is a folder where the image is stored at, essentially in the same folder. I don't know what is wrong, any help or leads are appreciated.

Edit: So the 2nd part of the code I have works perfectly, It generates a table for me. But at every 6th column of a row is a picture name (1000.png) and its in the folder CSV_Photo. I want it to no display as 1000.png, but instead the picture. The 1st section of code is my attempt to make it an image, but no table is created so I'm guessing there is something wrong with this line table += "" + <"img src= 'CSV_Photos/" + array[i][j] +"'style ='width:500px;height:300px'>";

Body:
I think there are several problems in your code that needs to be fixed :

You are not appending the td elements inside the tr but directly
inside the table, you need to move the  line table += "<tr>";
before the nested loop.

And you are not specifying closing tags for <td> elements so when
you include the img tag it will mess up the layout.

Another thing just inverse the use of " and ' in your img tag
definition because HTML uses ".." to define attributes.

Here's how should be your code:

var array = csvpls();
var table = "<tr>";
for (var i = 0; i < array.length; i++) {
  table += "<tr>";
  for (var j = 0; j < array[i].length; j++) {
    if (j == 6) {
      table += "<td>" + '<img src="CSV_Photos/' + array[i][j] + '" style ="width:500px;height:300px"></td>';
    } else if {
      table += "<td>" + array[i][j] + "</td>";
    }
  }
  table += "</tr>";
}

document.getElementById("Invtable").innerHTML = table;


问:
Loading/Updating new data to a webpage and using Knockout to dynamically update UI
Working with the dynamic JavaScript Technology called Knockout, I would like to send new data to my webpage and ask Knockout to do the dynamic UI update for me.

The below example shows a very simple webpage that shows two Scores (P1 and P2). The JavaScript creates a ViewModel() using Knockout. Unfortunately, I only achieved this by providing a JSON-data property. And I don't know how to dynamically load and also dynamically update new score-data.

Now my question: How can I "inject" (i.e. load at first and update at any time) new data to my webpage and Knockout would update the Scores UI dynamically ?

I guess, I would need some sort of...

a) $.getJSON(".... for the initial loading!

b) Post-request (REST) call from anywhere for the data-update

But how do I do a) and b) ???
Thanks for any help on this.

```<code><!doctype html>
<html>
<head>
<meta charset="UTF-8">
<title>iKK_ScoreMirror</title>
</head>

<script type='text/javascript' src='Knockout/knockout-3.4.2.js'></script>

<body>

<h3>Game</h3>

    <p>Score P1 =  <span data-bind="text: scoreP1"></span> </p>
    <p>Score P2 =  <span data-bind="text: scoreP2"></span> </p>

</body>

<script>

    function ViewModel() {
        var self = this;

        // !!!!!!! Here is the json-data given fix
        var jsonData = {
            sP1: 13,
            sP2: 23
        };

        self.scoreP1 = ko.observable(jsonData.sP1)
        self.scoreP2 = ko.observable(jsonData.sP2)
    };

    var vm = new ViewModel();
    ko.applyBindings(vm);

</script>

</html>
</code>```

答:
you mean something like this?  here is a runnable fiddle  https://jsfiddle.net/ca0xv62w/2/</p>

```<code>function ViewModel() {
  var self = this;
  self.scoreP1 = ko.observable('13')
  self.scoreP2 = ko.observable('23')
  self.loadDataFromServer = function() {
    $.ajax({
      type: 'POST',
      cache: false,
      data: {
        json: JSON.stringify(data)
      },
      url: '/echo/json/',
      success: function(response) {
       self.scoreP1(response.sP1);
       self.scoreP2(response.sP2);
      }
    });
  }
}
</code>```

Body:
Working with the dynamic JavaScript Technology called Knockout, I would like to send new data to my webpage and ask Knockout to do the dynamic UI update for me.

The below example shows a very simple webpage that shows two Scores (P1 and P2). The JavaScript creates a ViewModel() using Knockout. Unfortunately, I only achieved this by providing a JSON-data property. And I don't know how to dynamically load and also dynamically update new score-data.

Now my question: How can I "inject" (i.e. load at first and update at any time) new data to my webpage and Knockout would update the Scores UI dynamically ?

I guess, I would need some sort of...

a) $.getJSON(".... for the initial loading!

b) Post-request (REST) call from anywhere for the data-update

But how do I do a) and b) ???
Thanks for any help on this.

<!doctype html>

<meta charset="UTF-8">
<title>iKK_ScoreMirror</title>

Game

Score P1 =

Score P2 =

Body:
you mean something like this?  here is a runnable fiddle  https://jsfiddle.net/ca0xv62w/2/

function ViewModel() {
  var self = this;
  self.scoreP1 = ko.observable('13')
  self.scoreP2 = ko.observable('23')
  self.loadDataFromServer = function() {
    $.ajax({
      type: 'POST',
      cache: false,
      data: {
        json: JSON.stringify(data)
      },
      url: '/echo/json/',
      success: function(response) {
       self.scoreP1(response.sP1);
       self.scoreP2(response.sP2);
      }
    });
  }
}


问:
msyql not connect with sphinxsearch
I am unable to connect with sphinxsearch mysql
mysql -h0 -P3306

ERROR 2003 (HY000): Can't connect to MySQL server on '0' (111)

How can I remove this error

this is my config file code sphinx.conf

is we need to start any service?

```<code>source src1
{
    type            = mysql
    sql_host        = localhost
    sql_user        = root
    sql_pass        = india@123
    sql_db          = test
    sql_port        = 3306

    sql_query       = \
        SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content \
        FROM documents

    sql_attr_uint       = group_id

    sql_attr_timestamp  = date_added
    sql_ranged_throttle = 0
    sql_query_info        = SELECT * FROM documents WHERE id=$id

}

source src1throttled : src1
{
    sql_ranged_throttle = 100
}
index test1
{
    source          = src1
    path            = /var/lib/sphinxsearch/data/test1
    docinfo         = extern
    dict            = keywords
    mlock           = 0
    morphology      = none
    min_word_len    = 1
    html_strip      = 0
}
index test1stemmed : test1
{
    path            = /var/lib/sphinxsearch/data/test1stemmed
    morphology      = stem_en
}
index dist1
{
    type            = distributed
    local           = test1
    local           = test1stemmed
    agent           = localhost:9313:remote1
    agent           = localhost:9314:remote2,remote3
    agent_connect_timeout   = 1000
    agent_query_timeout     = 3000
}
index rt
{
    type            = rt
    path            = /var/lib/sphinxsearch/data/rt
    rt_field        = title
    rt_field        = content
    rt_attr_uint        = gid
}
indexer
{
    mem_limit       = 128M
}

searchd
{
    listen          = 9312
    listen          = 9306:mysql41
    log         = /var/log/sphinxsearch/searchd.log
    query_log       = /var/log/sphinxsearch/query.log
    read_timeout        = 5
    client_timeout      = 300
    max_children        = 30
    persistent_connections_limit    = 30
    pid_file        = /var/run/sphinxsearch/searchd.pid
    seamless_rotate     = 1
    preopen_indexes     = 1
    unlink_old      = 1
    mva_updates_pool    = 1M
    max_packet_size     = 8M
    max_filters     = 256
    max_filter_values   = 4096
    max_batch_queries   = 32
    workers         = threads # for RT to work
}
common
{
}
</code>```

答:
Make sure the sphinx user has permission to this folder!

chown -R sphinx:sphinx /var/lib/sphinxsearch/

Title: msyql not connect with sphinxsearch

Body:
I am unable to connect with sphinxsearch mysql
mysql -h0 -P3306

ERROR 2003 (HY000): Can't connect to MySQL server on '0' (111)

How can I remove this error

this is my config file code sphinx.conf

is we need to start any service?

source src1
{
    type            = mysql
    sql_host        = localhost
    sql_user        = root
    sql_pass        = india@123
    sql_db          = test
    sql_port        = 3306

    sql_query       = \
        SELECT id, group_id, UNIX_TIMESTAMP(date_added) AS date_added, title, content \
        FROM documents

    sql_attr_uint       = group_id

    sql_attr_timestamp  = date_added
    sql_ranged_throttle = 0
    sql_query_info        = SELECT * FROM documents WHERE id=$id

}

source src1throttled : src1
{
    sql_ranged_throttle = 100
}
index test1
{
    source          = src1
    path            = /var/lib/sphinxsearch/data/test1
    docinfo         = extern
    dict            = keywords
    mlock           = 0
    morphology      = none
    min_word_len    = 1
    html_strip      = 0
}
index test1stemmed : test1
{
    path            = /var/lib/sphinxsearch/data/test1stemmed
    morphology      = stem_en
}
index dist1
{
    type            = distributed
    local           = test1
    local           = test1stemmed
    agent           = localhost:9313:remote1
    agent           = localhost:9314:remote2,remote3
    agent_connect_timeout   = 1000
    agent_query_timeout     = 3000
}
index rt
{
    type            = rt
    path            = /var/lib/sphinxsearch/data/rt
    rt_field        = title
    rt_field        = content
    rt_attr_uint        = gid
}
indexer
{
    mem_limit       = 128M
}

searchd
{
    listen          = 9312
    listen          = 9306:mysql41
    log         = /var/log/sphinxsearch/searchd.log
    query_log       = /var/log/sphinxsearch/query.log
    read_timeout        = 5
    client_timeout      = 300
    max_children        = 30
    persistent_connections_limit    = 30
    pid_file        = /var/run/sphinxsearch/searchd.pid
    seamless_rotate     = 1
    preopen_indexes     = 1
    unlink_old      = 1
    mva_updates_pool    = 1M
    max_packet_size     = 8M
    max_filters     = 256
    max_filter_values   = 4096
    max_batch_queries   = 32
    workers         = threads # for RT to work
}
common
{
}


问:
Multitasking latency and throughput
I have been doing some experimentation around multi-threading and multi-tasking and I have a few questions.

1) Consider a machine with just one CPU core/processor. Running multiple threads parallely is achieved by time slicing (each thread is given a few milliseconds to run on the CPU) and if one thread is blocked on I/O, the others can run, thus giving an impression of doing multiple things concurrently.

Consider the same single processor CPU and say there are two threads, both of which is CPU intensive and does no I/O.
Each takes 5 seconds to complete its operation. Running it sequentially will take obviously 10 secs.

Will running it parallely (using executor service) also take 10 seconds since the threads are CPU intensive only? (given that there is only one CPU core)

2) On a machine with four cores, I have a task that will take 5 seconds to complete when run independently. I wanted to run a couple of them in parallel as separate processes using Java's ProcessBuilder (I don't want to run as parallel threads as the object that they share is not thread safe and cost of synchronization is too much).
I expected it to complete around 5 seconds.

Starting two parallel process did not yield much improvement as they still took around 9 seconds to complete. Why is that? (the task is both CPU intensive and consumes significant memory).
  Note: As I start three or four processes, the latency is more and more affected (worse or equivalent to running them in sequence).

EDIT

My intention/ question is more around why the performance is not improved when using processes rather than whether I should use multiple threads/process for my second question.
For question 2, (for the sake of discussion) you can simple imagine the task like this: (Although the numbers mentioned in the question above is not from the below snippet)

```<code>String s;
for (int i = 0; i < 50000; i++) {
 s += i; //consumes a lot of memory
}

long result = 0;
for(int j = 0; j < 3; j++) {
  for (double i = 0; i < 500000000; i++) { //Lot of CPU
    result += i;
   }
}
</code>```

答: How many operations are you running? The performance might not improve by much because of the overhead in communication. Because everything has a cost, the amount of time required to coordinate parallel tasks may have dominated the time spent on actually solving the problem, making it no longer favorable to parallelize your code.</p>

Title: Multitasking latency and throughput

Body:
I have been doing some experimentation around multi-threading and multi-tasking and I have a few questions.

1) Consider a machine with just one CPU core/processor. Running multiple threads parallely is achieved by time slicing (each thread is given a few milliseconds to run on the CPU) and if one thread is blocked on I/O, the others can run, thus giving an impression of doing multiple things concurrently.

Consider the same single processor CPU and say there are two threads, both of which is CPU intensive and does no I/O.
Each takes 5 seconds to complete its operation. Running it sequentially will take obviously 10 secs.

Will running it parallely (using executor service) also take 10 seconds since the threads are CPU intensive only? (given that there is only one CPU core)

2) On a machine with four cores, I have a task that will take 5 seconds to complete when run independently. I wanted to run a couple of them in parallel as separate processes using Java's ProcessBuilder (I don't want to run as parallel threads as the object that they share is not thread safe and cost of synchronization is too much).
I expected it to complete around 5 seconds.

Starting two parallel process did not yield much improvement as they still took around 9 seconds to complete. Why is that? (the task is both CPU intensive and consumes significant memory).
  Note: As I start three or four processes, the latency is more and more affected (worse or equivalent to running them in sequence).

EDIT

My intention/ question is more around why the performance is not improved when using processes rather than whether I should use multiple threads/process for my second question.
For question 2, (for the sake of discussion) you can simple imagine the task like this: (Although the numbers mentioned in the question above is not from the below snippet)

String s;
for (int i = 0; i < 50000; i++) {
 s += i; //consumes a lot of memory
}

long result = 0;
for(int j = 0; j < 3; j++) {
  for (double i = 0; i < 500000000; i++) { //Lot of CPU
    result += i;
   }
}


问:
Why variables start out with random values in C
I think this is wrong, it should start as NULL and not with a random value. In the case that you have a pointer with a random memory address as its default value it could be a very dangerous thing, no?</p>

答: The design choice is performance, and it is one of the many reasons why C isn't the preferred language for most projects.</p>


问:
Dynamically Updating A Tab Bar Item In the More ViewController Table
OK. I haven't actually seen how to do this anywhere. It may be a question of "You can't get there from here." or "Holy #@$! That is such a disgusting hack it should be taken behind the woodshed and shot!".

I have a tabbed Swift 3 iOS app that will dynamically update the Tab Bar images of selected pages as the page state changes.

I do that sort of like this:

```<code>if let navController = self.navigationController as? MyNavController {
    navController.tabBarItem.image = navController.tabBarImage
    navController.tabBarItem.selectedImage = navController.tabBarImage
}
</code>```

The tabBarImage is actually a calculated property. This snippet is called within a UI callback that updates when the state changes.

This works great.

When in the MoreViewController, though, not so great. Those images remain stubbornly static, no matter what I do.

I have done some exploration of the MoreViewController. I can get at the tableView and the cells, but that smells like the kind of hack that will get my app taken behind the woodshed by the Blue Meanies at App Review.

Is there a proper way to do this?

答:
OK. I figured out how to do it.

I was crawling back along the navigation controller path; which worked fine for items not in the more space.

I fixed it by crawling forward from the tab bar controller, instead:

```<code>self.tabBarController?.viewControllers?[MySelectionIndex].tabBarItem.image = self.tabBarImage
self.tabBarController?.viewControllers?[MySelectionIndex].tabBarItem.selectedImage = self.tabBarImage
</code>```

Body:
OK. I haven't actually seen how to do this anywhere. It may be a question of "You can't get there from here." or "Holy #@$! That is such a disgusting hack it should be taken behind the woodshed and shot!".

I have a tabbed Swift 3 iOS app that will dynamically update the Tab Bar images of selected pages as the page state changes.

I do that sort of like this:

if let navController = self.navigationController as? MyNavController {
    navController.tabBarItem.image = navController.tabBarImage
    navController.tabBarItem.selectedImage = navController.tabBarImage
}

The tabBarImage is actually a calculated property. This snippet is called within a UI callback that updates when the state changes.

This works great.

When in the MoreViewController, though, not so great. Those images remain stubbornly static, no matter what I do.

I have done some exploration of the MoreViewController. I can get at the tableView and the cells, but that smells like the kind of hack that will get my app taken behind the woodshed by the Blue Meanies at App Review.

Is there a proper way to do this?

Body:
OK. I figured out how to do it.

I was crawling back along the navigation controller path; which worked fine for items not in the more space.

I fixed it by crawling forward from the tab bar controller, instead:

self.tabBarController?.viewControllers?[MySelectionIndex].tabBarItem.image = self.tabBarImage
self.tabBarController?.viewControllers?[MySelectionIndex].tabBarItem.selectedImage = self.tabBarImage


问:
How to colorize one attribute in ruby hash
I need to colorize only one value in hash, like that

```<code>require 'colorize'
h = {a: 'a', b: 'b'.colorize(:red), c: 'c'}
</code>```

h[:b] returns this

```<code>"\e[0;31;49mb\e[0m"
</code>```

therefore puts h[:b] works as expected, whereas h.to_s or h.inspect gives this

```<code>"{:a=>\"\\e[0;31;49ma\\e[0m\", :b=>\"\\e[0;34;49mb\\e[0m\"}"
</code>```

As you can see all the control sequences has been escaped.

As the h is being implicitly transformed into string while using puts h, all I get in terminal is this:

```<code>{:a=>"a", :b=>"\e[0;31;49mb\e[0m", :c=>"c"}
</code>```

without any colours.

What should I do to get correct colorized output?

答:
If you can live without style points:

```<code>def _d(*args)
  result = []
  args.each do |arg|
    if arg.is_a?(Hash)
      temp_string = "{"
      parts = []
      arg.each { |k,v| parts << ":#{k}=>\"#{v}\""}
      temp_string += parts.join(", ")
      temp_string += "}"
      result << temp_string
    else
     result << "#{arg}"
    end
  end
  puts result.join(" ")
end
</code>```

Hitting _d h will return the output you expect.

Body:
I need to colorize only one value in hash, like that

require 'colorize'
h = {a: 'a', b: 'b'.colorize(:red), c: 'c'}

h[:b] returns this

"\e[0;31;49mb\e[0m"

therefore puts h[:b] works as expected, whereas h.to_s or h.inspect gives this

"{:a=>\"\\e[0;31;49ma\\e[0m\", :b=>\"\\e[0;34;49mb\\e[0m\"}"

As you can see all the control sequences has been escaped.

As the h is being implicitly transformed into string while using puts h, all I get in terminal is this:

{:a=>"a", :b=>"\e[0;31;49mb\e[0m", :c=>"c"}

without any colours.

What should I do to get correct colorized output?

Body:
If you can live without style points:

def _d(*args)
  result = []
  args.each do |arg|
    if arg.is_a?(Hash)
      temp_string = "{"
      parts = []
      arg.each { |k,v| parts << ":#{k}=>\"#{v}\""}
      temp_string += parts.join(", ")
      temp_string += "}"
      result << temp_string
    else
     result << "#{arg}"
    end
  end
  puts result.join(" ")
end

Hitting _d h will return the output you expect.


问:
jQuery-UI - .append from .droppable into p.array (almost there!)
The site is using .draggable and .droppable UI to append the players ID from the span tag. This is appended into the following paragraphs:

```<code>           <p class="array goals"></p>
           <p class="array assist"></p>
           <p class="array yellow"></p>
           <p class="array red"></p>
           <p class="array cap"></p>
</code>```

From these divs

```<code>           <h2>DROP PLAYERS INTO AREAS BELOW</h2>
           <p>Goals</p>
           <div class="droppable goals"><p></p></div>
           <p>Assists</p>
           <div class="droppable assist"><p></p></div>
           <p>Yellow card</p>
           <div class="droppable yellow"><p></p></div>
           <p>Red card</p>
           <div class="droppable red"><p></p></div>
           <p>Captain</p>
           <div class="droppable cap"><p></p></div>
</code>```

By this javascript (cut down to needed code)

```<code>    <script type="text/javascript">
$(function() {
    $(".droppable").droppable({
        activeClass: 'dragactive',
        hoverClass: 'drophover',
        drop: function(event, ui) {
            $(".array").append(ui.draggable.children("span").text() + ', ')
        }
    });

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

I need the dropped items to get into the right p.array based on the second class. Now, the result from .droppable is appended to EVERY array class.

This is an example of the draggable player's mark-up:

```<code><div class="drakt spiller draggable">
   <span style="visibility: hidden;">58</span>
   <div class="draktnummer">17</div><p>Traoré</p>
</div>
</code>```

Hope you can help me with this.

Thanks in advance.

答:
Am not really sure what this code means...

```<code> $(this).find('p')
            $(".array").append(ui.draggable.children("span").text())
</code>```

Try changing to this:

```<code>$(this).find('p.array').append(ui.draggable.children("span").text())
</code>```

EDIT: I think I see what you need now. Did not read so carefully earlier. What you need is to append the text from s in the draggable to to the paragraphs in the first code block after they are dropped in their corresponding divs in the second block, right?

If so, you could add your own attribute to the draggables, say 'myattr'. If this is is your draggable:

```<code><div id="mydrag" myattr="goals" class="draggable"><span>text to append</span></div>
</code>```

and this is the code for your droppable

```<code>drop: function(event, ui) {
    var myattrVal = ui.draggable.attr('myattr');
    //Finds the p with the class goals from if the div above was the draggable
    $('p.' + myattrVal).append(ui.draggable.find('span').text() + ',');
}
</code>```

Body:
The site is using .draggable and .droppable UI to append the players ID from the span tag. This is appended into the following paragraphs:

From these divs

DROP PLAYERS INTO AREAS BELOW

Goals

Assists

Yellow card

Red card

Captain

By this javascript (cut down to needed code)

I need the dropped items to get into the right p.array based on the second class. Now, the result from .droppable is appended to EVERY array class.

This is an example of the draggable player's mark-up:

   58

17

Traoré

Hope you can help me with this.

Thanks in advance.

Body:
Am not really sure what this code means...

 $(this).find('p')
            $(".array").append(ui.draggable.children("span").text())

Try changing to this:

$(this).find('p.array').append(ui.draggable.children("span").text())

EDIT: I think I see what you need now. Did not read so carefully earlier. What you need is to append the text from s in the draggable to to the paragraphs in the first code block after they are dropped in their corresponding divs in the second block, right?

If so, you could add your own attribute to the draggables, say 'myattr'. If this is is your draggable:

<div id="mydrag" myattr="goals" class="draggable"><span>text to append</span></div>

and this is the code for your droppable

drop: function(event, ui) {
    var myattrVal = ui.draggable.attr('myattr');
    //Finds the p with the class goals from if the div above was the draggable
    $('p.' + myattrVal).append(ui.draggable.find('span').text() + ',');
}


问:
If else statement to define an NSPredicate
I am trying to define a predicate based on a segment controller switch.

```<code>if self.streamtype == "case1" {
    let predicatearray = defaults.object(forKey: "case1") as! [String]
    let predicate = NSPredicate(format: "UserID IN %@" , predicatearray)
} else if self.streamtype == "case2" {
    let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
} else {
    let predicatearray = defaults.object(forKey: "case3") as! [String]
    let predicate = NSPredicate(format: "UserID IN %@", predicatearray)
}

let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "Post", predicate: predicate)
</code>```

I am getting an error saying:

"Cannot be sent to an abstract object of class NSPredicate: Create a concrete instance!"

Also, it is telling me that the initialization of the predicate variable was never used. I've tried writing the function a couple of different ways but this made the most sense to me since I need to update the predicate only when loading new info so I just put both functions into one.

答:
You are defining predicate inside of if {} or else {} scope, that's why it is not visible outside of the scope.

```<code>var predicate : NSPredicate!
if self.streamtype == "case1" {
    let predicatearray = defaults.object(forKey: "case1") as! [String]
    predicate = NSPredicate(format: "UserID IN %@", predicatearray)
} else if self.streamtype == "case2" {
    predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
} else {
    let predicatearray = defaults.object(forKey: "case3") as! [String]
    predicate = NSPredicate(format: "UserID IN %@", predicatearray)
}

let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "Post", predicate: predicate)
</code>```

Body:
I am trying to define a predicate based on a segment controller switch.

if self.streamtype == "case1" {
    let predicatearray = defaults.object(forKey: "case1") as! [String]
    let predicate = NSPredicate(format: "UserID IN %@" , predicatearray)
} else if self.streamtype == "case2" {
    let predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
} else {
    let predicatearray = defaults.object(forKey: "case3") as! [String]
    let predicate = NSPredicate(format: "UserID IN %@", predicatearray)
}

let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "Post", predicate: predicate)

I am getting an error saying:

"Cannot be sent to an abstract object of class NSPredicate: Create a concrete instance!"

Also, it is telling me that the initialization of the predicate variable was never used. I've tried writing the function a couple of different ways but this made the most sense to me since I need to update the predicate only when loading new info so I just put both functions into one.

Body:
You are defining predicate inside of if {} or else {} scope, that's why it is not visible outside of the scope.

var predicate : NSPredicate!
if self.streamtype == "case1" {
    let predicatearray = defaults.object(forKey: "case1") as! [String]
    predicate = NSPredicate(format: "UserID IN %@", predicatearray)
} else if self.streamtype == "case2" {
    predicate = NSPredicate(format: "TRUEPREDICATE", argumentArray: nil)
} else {
    let predicatearray = defaults.object(forKey: "case3") as! [String]
    predicate = NSPredicate(format: "UserID IN %@", predicatearray)
}

let publicData = CKContainer.default().publicCloudDatabase
let query = CKQuery(recordType: "Post", predicate: predicate)


问:
'xmlParseEntityRef: no name' warnings while loading xml into a php file
I am reading an xml in php using simplexml_load_file. However while trying to load the xml it displays a list of warnings

```<code>Warning: simplexml_load_file() [function.simplexml-load-file]: <project orderno="6" campaign_name="International Relief & Development" project in /home/bluecard1/public_html/test.php on line 3
Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in /home/bluecard1/public_html/test.php on line 3
Warning: simplexml_load_file() [function.simplexml-load-file]: http://..../index.php/site/projects/:15: parser error : xmlParseEntityRef: no name in /home/bluecard1/public_html/test.php on line 3

Warning: simplexml_load_file() [function.simplexml-load-file]: ional Relief & Development" project_id="313" client_name="International Relief & in /home/bluecard1/public_html/test.php on line 3
Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in /home/bluecard1/public_html/test.php on line 3
Warning: simplexml_load_file() [function.simplexml-load-file]: http://..../index.php/site/projects/:15: parser error : xmlParseEntityRef: no name in /home/bluecard1/public_html/test.php on line 3
</code>```

How do I rectify to remove these warnings?

(XML is generated from url http://..../index.php/site/projects & loaded into  a variable in the test.php. I dont have write priveleges to index.php)

答:
PROBLEM

PHP function simplexml_load_file is throwing parsing error parser
error : xmlParseEntityRef while trying to load the XML file from a URL.

CAUSE

XML returned by the URL is not a valid XML. It contains & value
instead of &. It is quite possible that there are other errors which aren't obvious at this point of time.

THINGS OUT OF OUR CONTROL

Ideally, we should make sure that a valid XML is feed into PHP simplexml_load_file function, but it looks like we don't have any control over how the XML is created.

It is also not possible to force simplexml_load_file to process an
invalid XML file. It does not leave us with many options, other than
fixing the XML file itself.

POSSIBLE SOLUTION

Convert Invalid XML to Valid XML. It can be done using PHP tidy extension. Further instructions can be found from http://php.net/manual/en/book.tidy.php

Once you are sure that the extension exists or is installed, please do the following.

```<code>/**
 * As per the question asked, the URL is loaded into a variable first,
 * which we can assume to be $xml
 */
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<project orderno="6" campaign_name="International Relief & Development for under developed nations">
    <invalid-data>Some other data containing & in it</invalid-data>
    <unclosed-tag>
</project>
XML;

/**
 * Whenever we use tidy it is best to pass some configuration options
 * similar to $tidyConfig. In this particular case we are making sure that
 * tidy understands that our input and output is XML.
 */
$tidyConfig = array (
    'indent' => true,
    'input-xml' => true,
    'output-xml' => true,
    'wrap' => 200
);

/**
 * Now we can use tidy to parse the string and then repair it.
 */
$tidy = new tidy;
$tidy->parseString($xml, $tidyConfig, 'utf8');
$tidy->cleanRepair();

/**
 * If we try to output the repaired XML string by echoing $tidy it should look like.

 <?xml version="1.0" encoding="utf-8"?>
 <project orderno="6" campaign_name="International Relief & Development for under developed nations">
      <invalid-data>Some other data containing & in it</invalid-data>
      <unclosed-tag></unclosed-tag>
 </project>

 * As you can see that & is now fixed in campaign_name attribute
 * and also with-in invalid-data element. You can also see that the
 * <unclosed-tag> which didn't had a close tag, has been fixed too.
 */
echo $tidy;

/**
 * Now when we try to use simplexml_load_string to load the clean XML. When we
 * try to print_r it should look something like below.

 SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [orderno] => 6
            [campaign_name] => International Relief & Development for under developed nations
        )

    [invalid-data] => Some other data containing & in it
    [unclosed-tag] => SimpleXMLElement Object
        (
        )

)

 */
 $simpleXmlElement = simplexml_load_string($tidy);
 print_r($simpleXmlElement);
</code>```

CAUTION

The developer should try to compare the invalid XML with a valid XML (generated by tidy), to see there are no adverse side effects after using tidy. Tidy does an extremely good job of doing it correctly, but it never hurts to see it visually and to be 100% sure. In our case it should be as simple as comparing $xml with $tidy.

Body:
I am reading an xml in php using simplexml_load_file. However while trying to load the xml it displays a list of warnings

Warning: simplexml_load_file() [function.simplexml-load-file]: <project orderno="6" campaign_name="International Relief & Development" project in /home/bluecard1/public_html/test.php on line 3
Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in /home/bluecard1/public_html/test.php on line 3
Warning: simplexml_load_file() [function.simplexml-load-file]: http://..../index.php/site/projects/:15: parser error : xmlParseEntityRef: no name in /home/bluecard1/public_html/test.php on line 3

Warning: simplexml_load_file() [function.simplexml-load-file]: ional Relief & Development" project_id="313" client_name="International Relief & in /home/bluecard1/public_html/test.php on line 3
Warning: simplexml_load_file() [function.simplexml-load-file]: ^ in /home/bluecard1/public_html/test.php on line 3
Warning: simplexml_load_file() [function.simplexml-load-file]: http://..../index.php/site/projects/:15: parser error : xmlParseEntityRef: no name in /home/bluecard1/public_html/test.php on line 3

How do I rectify to remove these warnings?

(XML is generated from url http://..../index.php/site/projects & loaded into  a variable in the test.php. I dont have write priveleges to index.php)

Body:
PROBLEM

PHP function simplexml_load_file is throwing parsing error parser
error : xmlParseEntityRef while trying to load the XML file from a URL.

CAUSE

XML returned by the URL is not a valid XML. It contains & value
instead of &amp;. It is quite possible that there are other errors which aren't obvious at this point of time.

THINGS OUT OF OUR CONTROL

Ideally, we should make sure that a valid XML is feed into PHP simplexml_load_file function, but it looks like we don't have any control over how the XML is created.

It is also not possible to force simplexml_load_file to process an
invalid XML file. It does not leave us with many options, other than
fixing the XML file itself.

POSSIBLE SOLUTION

Convert Invalid XML to Valid XML. It can be done using PHP tidy extension. Further instructions can be found from http://php.net/manual/en/book.tidy.php

Once you are sure that the extension exists or is installed, please do the following.

/**
 * As per the question asked, the URL is loaded into a variable first,
 * which we can assume to be $xml
 */
$xml = <<<XML
<?xml version="1.0" encoding="UTF-8"?>
<project orderno="6" campaign_name="International Relief & Development for under developed nations">
    <invalid-data>Some other data containing & in it</invalid-data>
    <unclosed-tag>
</project>
XML;

/**
 * Whenever we use tidy it is best to pass some configuration options
 * similar to $tidyConfig. In this particular case we are making sure that
 * tidy understands that our input and output is XML.
 */
$tidyConfig = array (
    'indent' => true,
    'input-xml' => true,
    'output-xml' => true,
    'wrap' => 200
);

/**
 * Now we can use tidy to parse the string and then repair it.
 */
$tidy = new tidy;
$tidy->parseString($xml, $tidyConfig, 'utf8');
$tidy->cleanRepair();

/**
 * If we try to output the repaired XML string by echoing $tidy it should look like.

 <?xml version="1.0" encoding="utf-8"?>
 <project orderno="6" campaign_name="International Relief &amp; Development for under developed nations">
      <invalid-data>Some other data containing &amp; in it</invalid-data>
      <unclosed-tag></unclosed-tag>
 </project>

 * As you can see that & is now fixed in campaign_name attribute
 * and also with-in invalid-data element. You can also see that the
 * <unclosed-tag> which didn't had a close tag, has been fixed too.
 */
echo $tidy;

/**
 * Now when we try to use simplexml_load_string to load the clean XML. When we
 * try to print_r it should look something like below.

 SimpleXMLElement Object
(
    [@attributes] => Array
        (
            [orderno] => 6
            [campaign_name] => International Relief & Development for under developed nations
        )

    [invalid-data] => Some other data containing & in it
    [unclosed-tag] => SimpleXMLElement Object
        (
        )

)

 */
 $simpleXmlElement = simplexml_load_string($tidy);
 print_r($simpleXmlElement);

CAUTION

The developer should try to compare the invalid XML with a valid XML (generated by tidy), to see there are no adverse side effects after using tidy. Tidy does an extremely good job of doing it correctly, but it never hurts to see it visually and to be 100% sure. In our case it should be as simple as comparing $xml with $tidy.


问:
Issue with matplotlib accepting different color forms
So this is a simplified version, but as you can see I create a graph with matplotlib and display it. I display it with 'gray21' which has worked for Tkinter objects, but its not working here. The color 'white' is the only one I have found that works. How can I get a variety of colors? Can I use RGB or some form of exact color specification, because I have a color in mind (R:70 G:70 B:70). What forms of colors does .patch.set_facecolor() take?</p>

```<code>import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from Tkinter import *

root=Tk()
root.geometry('1000x700')
root.configure(bg="gray21")
root.title("My Graph")

one_day_fig=plt.figure()

one_day_fig.patch.set_facecolor('gray21')
plt.plot([1,2,3], [2,4,6])
my_canvas = FigureCanvasTkAgg(one_day_fig,master=root)
plot_widget = my_canvas.get_tk_widget()
plot_widget.place(x=50, y=50)

root.mainloop()
</code>```

答:
RGB values can be specified as 3-tuples of integers between 0 and 255 or as 3-tuples of floats between 0 and 1.

The tuple (70,70,70) would thus correspond to (70/255., 70/255., 70/255.).

This can be used as a color specification to matplotlib.

```<code>figure.set_facecolor((70/255., 70/255., 70/255.))
</code>```

Body:
So this is a simplified version, but as you can see I create a graph with matplotlib and display it. I display it with 'gray21' which has worked for Tkinter objects, but its not working here. The color 'white' is the only one I have found that works. How can I get a variety of colors? Can I use RGB or some form of exact color specification, because I have a color in mind (R:70 G:70 B:70). What forms of colors does .patch.set_facecolor() take?

import matplotlib.pyplot as plt
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg
from Tkinter import *

root=Tk()
root.geometry('1000x700')
root.configure(bg="gray21")
root.title("My Graph")

one_day_fig=plt.figure()

one_day_fig.patch.set_facecolor('gray21')
plt.plot([1,2,3], [2,4,6])
my_canvas = FigureCanvasTkAgg(one_day_fig,master=root)
plot_widget = my_canvas.get_tk_widget()
plot_widget.place(x=50, y=50)

root.mainloop()

Body:
RGB values can be specified as 3-tuples of integers between 0 and 255 or as 3-tuples of floats between 0 and 1.

The tuple (70,70,70) would thus correspond to (70/255., 70/255., 70/255.).

This can be used as a color specification to matplotlib.

figure.set_facecolor((70/255., 70/255., 70/255.))


问:
How to make operations between part of array with part of array?
```<code>import numpy as np
a=np.array([2,3,4,6,7,4,5,3,2,1,9,8,7,6,4,2])
## a has 16 elements
b=np.array([1,5,3,7])
""" i want this:
 a[:4] - b[1], a[4:8]-b[2], a[8:12]-b[3], a[12:16]-b[4] in one array
and it should look like
c=numpy.array[1,2,3,5,2,-1,0,-2....]
</code>```

This is just a simple example for my problem. So can not be done with using groups. I need a loop to solve this.

Body:
import numpy as np
a=np.array([2,3,4,6,7,4,5,3,2,1,9,8,7,6,4,2])
## a has 16 elements
b=np.array([1,5,3,7])
""" i want this:
 a[:4] - b[1], a[4:8]-b[2], a[8:12]-b[3], a[12:16]-b[4] in one array
and it should look like
c=numpy.array[1,2,3,5,2,-1,0,-2....]

This is just a simple example for my problem. So can not be done with using groups. I need a loop to solve this.

Body:
You can reshape your array a, make operations on that and than flatten back.

In [24]: import numpy as np

In [25]: a=np.array([2,3,4,6,7,4,5,3,2,1,9,8,7,6,4,2])

In [26]: b=np.array([1,5,3,7])

In [27]: (a.reshape(4,4).T - b).T.ravel()
Out[27]: array([ 1,  2,  3,  5,  2, -1,  0, -2, -1, -2,  6,  5,  0, -1, -3, -5])


问:
Getting GD2 to work on Windows 2000 SP4 (PHP 5.1.6)
I have tried everything.. GD will not enable! Essentially, I have

```<code>extension_dir="C:\PHP\ext"
extension=php_gd2.dll
</code>```

I've added c:\php\ext and c:\php to my windows path variable. I copied php_gd2.dll to my system32 folder.. I've scanned my entire INI file to see if there was any other reference to the extension_dir, or GD2.dll extension line, and nothing... GD Still will not enable.

UPDATE

I changed the php.ini files in my C:\PHP folder as well as my C:\WINNT folders - actually they both show that GD should be enabled - I also upped the memory from 8M to 32M in both files and no luck, still.

UPDATE 2

We are moving the darn thing to a different server. It's not worth all of the time trying to get this darn thing working. Thanks to all that contributed.

phpinfo() Link (http://netcomdevelopment.com/test.php)

答:
I had this problem once upon a time.  IIRC PHP was not using the php.INI file I thought it was using, so all my edits had no effect.

Oh!  I even blogged about another difficulty I had with GD on Windows, after I convinced it to find the GD2 DLL in the first place.  That was on Windows 2003 but I think it applies even more in 2000land.

Body:
I have tried everything.. GD will not enable! Essentially, I have

extension_dir="C:\PHP\ext"
extension=php_gd2.dll

I've added c:\php\ext and c:\php to my windows path variable. I copied php_gd2.dll to my system32 folder.. I've scanned my entire INI file to see if there was any other reference to the extension_dir, or GD2.dll extension line, and nothing... GD Still will not enable.

UPDATE

I changed the php.ini files in my C:\PHP folder as well as my C:\WINNT folders - actually they both show that GD should be enabled - I also upped the memory from 8M to 32M in both files and no luck, still.

UPDATE 2

We are moving the darn thing to a different server. It's not worth all of the time trying to get this darn thing working. Thanks to all that contributed.

phpinfo() Link (http://netcomdevelopment.com/test.php)


问:
Laravel on some kind of Model Ready method
Well i don't know how to format the title of this post in very clear way, but here's my question:

Say i have

```<code>Posts::find('1);
Photos:find('1');
... and so on, every mode db request
</code>```

now by default i can access db columns, for instance the id: through model->id

```<code>$Photos = Photos::find('1')->first();
echo $Photos->id; // will return 1
</code>```

what i want is that i need all those kind of requests to add a custom field automatically like hashed_id, which is not in the database, which in return will make all models have a hashed_id as well, i know i can add that field to database and then grab it but i need it for different reasons/implementations

i did create a BaseModel and every Model will extend that BaseModel, so Photos extends BaseModel, BaseModel extends Model... and all that etc etc.

but i need some kind of constructor, upon retrieving data to process the data automatically without having to add -let's say- a hash_id() after retrieving the data.

something like, onAfterGet(), onReady()....sort of commands.

i hope my question is clear.

Thanks.

答:
If I understand you right, all you need to do is to define mutator, for example:

```<code><?php
class Photo extends Model
{
    /* ... model implementation ... */

    public function getHashedIdAttribute()
    {
        return md5($this->id);
    }
}
</code>```

Then you can access property like it was in database:

```<code>echo Photo::find(5)->hashed_id;
</code>```

Body:
Well i don't know how to format the title of this post in very clear way, but here's my question:

Say i have

Posts::find('1);
Photos:find('1');
... and so on, every mode db request

now by default i can access db columns, for instance the id: through model->id

$Photos = Photos::find('1')->first();
echo $Photos->id; // will return 1

what i want is that i need all those kind of requests to add a custom field automatically like hashed_id, which is not in the database, which in return will make all models have a hashed_id as well, i know i can add that field to database and then grab it but i need it for different reasons/implementations

i did create a BaseModel and every Model will extend that BaseModel, so Photos extends BaseModel, BaseModel extends Model... and all that etc etc.

but i need some kind of constructor, upon retrieving data to process the data automatically without having to add -let's say- a hash_id() after retrieving the data.

something like, onAfterGet(), onReady()....sort of commands.

i hope my question is clear.

Thanks.

Body:
If I understand you right, all you need to do is to define mutator, for example:

<?php
class Photo extends Model
{
    /* ... model implementation ... */

    public function getHashedIdAttribute()
    {
        return md5($this->id);
    }
}

Then you can access property like it was in database:

echo Photo::find(5)->hashed_id;


问:
Parsing a long JSON using GSON
I'm trying to parse a very long JSON like this.

```<code>{
  "BlastOutput2": [
    {
      "report": {
        "program": "blastn",
        "version": "BLASTN 2.6.0+",
        "reference": "Stephen F. Altschul, Thomas L. Madden, Alejandro A. Schäffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), \"Gapped BLAST and PSI-BLAST: a new generation of protein database search programs\", Nucleic Acids Res. 25:3389-3402.",
        "search_target": {
          "subjects": [
            "Subject_1"
          ]
        },
        "params": {
          "expect": 0.0001,
          "sc_match": 1,
          "sc_mismatch": -2,
          "gap_open": 5,
          "gap_extend": 2,
          "filter": "F"
        },
        "results": {
          "bl2seq": [
            {
              "query_id": "Query_1",
              "query_title": "F1-125",
              "query_len": 806,
              "hits": [
                {
                  "num": 1,
                  "description": [
                    {
                      "id": "gi|251831106|ref|NC_012920.1|",
                      "title": "gi|251831106|ref|NC_012920.1| Homo sapiens mitochondrion, complete genome"
                    }
                  ],
                  "len": 16569,
                  "hsps": [
                    {
                      "num": 1,
                      "bit_score": 619.793,
                      "score": 322,
                      "evalue": 3.47859e-180,
                      "identity": 458,
                      "query_from": 57,
                      "query_to": 572,
                      "query_strand": "Plus",
                      "hit_from": 16060,
                      "hit_to": 16569,
                      "hit_strand": "Plus",
                      "align_len": 516,
                      "gaps": 6,
                      "qseq": "GTATTGACTCACCGCTTAACAACGGCAATGTATTTCGTACATTACTGCCAGCCACAAAGAAAGTTGTACAGTACCATAAATACTTGACTACCTGTAGTACATAAAAACTCAACCCACATCAAAACCCCAAAAGACGAGACAGAAAAGCAAGTTTTTCAATCAACCTTCAACTGTCACACATCAACTGCAACTCCAAAGCCACCCCTCACCCACTAGGATATCAACAAACCTACCCGCCCTTAACAGTACATAGCACATAAAGTCATTTACCGTACATAGCACATTACAGTCAAATCCCTTCTCGTCCCCATGGATGACCCCCCTTTTTTTTGTGGTCCCCTGACCACCATCCTCCGTGTTTTTTTTTTTTCTCGCACAAGAGTGCTACTCTCCTCGTTCTGGGCCCATAACACTTGGGGGTAGCTAAAGTGAACTGTATCCGACATCTGGTTCCTACTTCAGGGTCATAAAGCCTAAATAGCCCACACGTTCCCCTTTTTATAAGACATCACGATG",
                      "hseq": "GTATTGACTCACCCATCAACAACCGCTATGTATTTCGTACATTACTGCCAGCCACCATGAATATTGTACGGTACCATAAATACTTGACCACCTGTAGTACATAAAAACCCAATCCACATCAAAACCCCCTCC--CCATGCTTACAAGCAAGTACAGCAATCAACCCTCAACTATCACACATCAACTGCAACTCCAAAGCCACCCCTCACCCACTAGGATACCAACAAACCTACCCACCCTTAACAGTACATAGTACATAAAGCCATTTACCGTACATAGCACATTACAGTCAAATCCCTTCTCGTCCCCATGGATGACCCCCCTCAGATAGG-GGTCCCTTGACCACCATCCTCCGTG--AAATCAATATCCCGCACAAGAGTGCTACTCTCCTCGCTCCGGGCCCATAACACTTGGGGGTAGCTAAAGTGAACTGTATCCGACATCTGGTTCCTACTTCAGGGTCATAAAGCCTAAATAGCCCACACGTTCCCC-TTAAATAAGACATCACGATG",
                      "midline": "|||||||||||||  | |||||| || |||||||||||||||||||||||||||| | |||  |||||| |||||||||||||||||| ||||||||||||||||||| ||| |||||||||||||||      | |  |  | ||||||||    ||||||||| |||||| ||||||||||||||||||||||||||||||||||||||||||||||| |||||||||||||| ||||||||||||||||| |||||||| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||    |  | |||||| ||||||||||||||||||     |   | || |||||||||||||||||||||||| || ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ||  ||||||||||||||||"
                    },
                    {
                      "num": 2,
                      "bit_score": 108.358,
                      "score": 56,
                      "evalue": 3.15269e-026,
                      "identity": 88,
                      "query_from": 573,
                      "query_to": 666,
                      "query_strand": "Plus",
                      "hit_from": 1,
                      "hit_to": 89,
                      "hit_strand": "Plus",
                      "align_len": 94,
                      "gaps": 5,
                      "qseq": "GATCACAGGTCTATCACCCTATTAAACCACTCACGGGGAGCTCTCCATGCATTTGGTATTTTTCGTCTGGGGGGGGTATGCACGCGATAACATT",
                      "hseq": "GATCACAGGTCTATCACCCTATTAA-CCACTCACGGG-AGCTCTCCATGCATTTGGTA-TTTTCGTCT--GGGGGGTATGCACGCGATAGCATT",
                      "midline": "||||||||||||||||||||||||| ||||||||||| |||||||||||||||||||| |||||||||  ||||||||||||||||||| ||||"
                    }
                  ]
                }
              ],
              "stat": {
                "hsp_len": 14,
                "eff_space": 13111560,
                "kappa": 0.620991117264206,
                "lambda": 1.33270576282382,
                "entropy": 1.12409184650114
              }
            }
          ]
        }
      }
    }
  ]
}
</code>```

I'm using GSON and by looking at some examples some people use Class to define everything into the JSON file, but I don't know if this is the best way to aproch this particula case, because I just want the results part from this JSON, can anyone help me with this?

答:
You don't need to create a bunch of class to parse your complicated JSON string. Let's parse it to a HashMap then iterate through it to get what you want.

```<code>Type type = new TypeToken<HashMap<String, Object>>(){}.getType();
HashMap<String, Object> myMap = gson.fromJson("your_json_string", type);
</code>```

By this way, you have a HashMap with multiple level, let's iterate through myMap by using a recursive method to get the result you want.

Sample code:

```<code>public static void main(String[] args) throws ParseException, JsonSyntaxException, IOException {
    Type type = new TypeToken<HashMap<String, Object>>() {
    }.getType();
    Gson gson = new Gson();
    HashMap<String, Object> map = gson.fromJson("your_json_string", type);
    for (String key : map.keySet()) {
        Object obj = map.get(key);
        if (obj instanceof List) {
            for (Object o : (List) obj) {
                if (o instanceof Map) {
                    loop((Map) o);
                } else {
                    System.out.println(key + " : " + o);
                }
            }
        } else if (obj instanceof Map) {
            loop((Map) obj);
        } else {
            System.out.println(key + " : " + obj);
        }
    }
}

private static void loop(Map<String, Object> map) {
    for (String key : map.keySet()) {
        Object obj = map.get(key);
        if (obj instanceof List) {
            for (Object o : (List) obj) {
                if (o instanceof Map) {
                    loop((Map) o);
                } else {
                    System.out.println(key + " : " + o);
                }
            }
        } else if (obj instanceof Map) {
            loop((Map) obj);
        } else {
            System.out.println(key + " : " + obj);
        }
    }
}
</code>```

Title: Parsing a long JSON using GSON

Body:
I'm trying to parse a very long JSON like this.

{
  "BlastOutput2": [
    {
      "report": {
        "program": "blastn",
        "version": "BLASTN 2.6.0+",
        "reference": "Stephen F. Altschul, Thomas L. Madden, Alejandro A. Schäffer, Jinghui Zhang, Zheng Zhang, Webb Miller, and David J. Lipman (1997), \"Gapped BLAST and PSI-BLAST: a new generation of protein database search programs\", Nucleic Acids Res. 25:3389-3402.",
        "search_target": {
          "subjects": [
            "Subject_1"
          ]
        },
        "params": {
          "expect": 0.0001,
          "sc_match": 1,
          "sc_mismatch": -2,
          "gap_open": 5,
          "gap_extend": 2,
          "filter": "F"
        },
        "results": {
          "bl2seq": [
            {
              "query_id": "Query_1",
              "query_title": "F1-125",
              "query_len": 806,
              "hits": [
                {
                  "num": 1,
                  "description": [
                    {
                      "id": "gi|251831106|ref|NC_012920.1|",
                      "title": "gi|251831106|ref|NC_012920.1| Homo sapiens mitochondrion, complete genome"
                    }
                  ],
                  "len": 16569,
                  "hsps": [
                    {
                      "num": 1,
                      "bit_score": 619.793,
                      "score": 322,
                      "evalue": 3.47859e-180,
                      "identity": 458,
                      "query_from": 57,
                      "query_to": 572,
                      "query_strand": "Plus",
                      "hit_from": 16060,
                      "hit_to": 16569,
                      "hit_strand": "Plus",
                      "align_len": 516,
                      "gaps": 6,
                      "qseq": "GTATTGACTCACCGCTTAACAACGGCAATGTATTTCGTACATTACTGCCAGCCACAAAGAAAGTTGTACAGTACCATAAATACTTGACTACCTGTAGTACATAAAAACTCAACCCACATCAAAACCCCAAAAGACGAGACAGAAAAGCAAGTTTTTCAATCAACCTTCAACTGTCACACATCAACTGCAACTCCAAAGCCACCCCTCACCCACTAGGATATCAACAAACCTACCCGCCCTTAACAGTACATAGCACATAAAGTCATTTACCGTACATAGCACATTACAGTCAAATCCCTTCTCGTCCCCATGGATGACCCCCCTTTTTTTTGTGGTCCCCTGACCACCATCCTCCGTGTTTTTTTTTTTTCTCGCACAAGAGTGCTACTCTCCTCGTTCTGGGCCCATAACACTTGGGGGTAGCTAAAGTGAACTGTATCCGACATCTGGTTCCTACTTCAGGGTCATAAAGCCTAAATAGCCCACACGTTCCCCTTTTTATAAGACATCACGATG",
                      "hseq": "GTATTGACTCACCCATCAACAACCGCTATGTATTTCGTACATTACTGCCAGCCACCATGAATATTGTACGGTACCATAAATACTTGACCACCTGTAGTACATAAAAACCCAATCCACATCAAAACCCCCTCC--CCATGCTTACAAGCAAGTACAGCAATCAACCCTCAACTATCACACATCAACTGCAACTCCAAAGCCACCCCTCACCCACTAGGATACCAACAAACCTACCCACCCTTAACAGTACATAGTACATAAAGCCATTTACCGTACATAGCACATTACAGTCAAATCCCTTCTCGTCCCCATGGATGACCCCCCTCAGATAGG-GGTCCCTTGACCACCATCCTCCGTG--AAATCAATATCCCGCACAAGAGTGCTACTCTCCTCGCTCCGGGCCCATAACACTTGGGGGTAGCTAAAGTGAACTGTATCCGACATCTGGTTCCTACTTCAGGGTCATAAAGCCTAAATAGCCCACACGTTCCCC-TTAAATAAGACATCACGATG",
                      "midline": "|||||||||||||  | |||||| || |||||||||||||||||||||||||||| | |||  |||||| |||||||||||||||||| ||||||||||||||||||| ||| |||||||||||||||      | |  |  | ||||||||    ||||||||| |||||| ||||||||||||||||||||||||||||||||||||||||||||||| |||||||||||||| ||||||||||||||||| |||||||| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||    |  | |||||| ||||||||||||||||||     |   | || |||||||||||||||||||||||| || ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| ||  ||||||||||||||||"
                    },
                    {
                      "num": 2,
                      "bit_score": 108.358,
                      "score": 56,
                      "evalue": 3.15269e-026,
                      "identity": 88,
                      "query_from": 573,
                      "query_to": 666,
                      "query_strand": "Plus",
                      "hit_from": 1,
                      "hit_to": 89,
                      "hit_strand": "Plus",
                      "align_len": 94,
                      "gaps": 5,
                      "qseq": "GATCACAGGTCTATCACCCTATTAAACCACTCACGGGGAGCTCTCCATGCATTTGGTATTTTTCGTCTGGGGGGGGTATGCACGCGATAACATT",
                      "hseq": "GATCACAGGTCTATCACCCTATTAA-CCACTCACGGG-AGCTCTCCATGCATTTGGTA-TTTTCGTCT--GGGGGGTATGCACGCGATAGCATT",
                      "midline": "||||||||||||||||||||||||| ||||||||||| |||||||||||||||||||| |||||||||  ||||||||||||||||||| ||||"
                    }
                  ]
                }
              ],
              "stat": {
                "hsp_len": 14,
                "eff_space": 13111560,
                "kappa": 0.620991117264206,
                "lambda": 1.33270576282382,
                "entropy": 1.12409184650114
              }
            }
          ]
        }
      }
    }
  ]
}

I'm using GSON and by looking at some examples some people use Class to define everything into the JSON file, but I don't know if this is the best way to aproch this particula case, because I just want the results part from this JSON, can anyone help me with this?

Body:
You don't need to create a bunch of class to parse your complicated JSON string. Let's parse it to a HashMap then iterate through it to get what you want.

Type type = new TypeToken<HashMap<String, Object>>(){}.getType();
HashMap<String, Object> myMap = gson.fromJson("your_json_string", type);

By this way, you have a HashMap with multiple level, let's iterate through myMap by using a recursive method to get the result you want.

Sample code:

public static void main(String[] args) throws ParseException, JsonSyntaxException, IOException {
    Type type = new TypeToken<HashMap<String, Object>>() {
    }.getType();
    Gson gson = new Gson();
    HashMap<String, Object> map = gson.fromJson("your_json_string", type);
    for (String key : map.keySet()) {
        Object obj = map.get(key);
        if (obj instanceof List) {
            for (Object o : (List) obj) {
                if (o instanceof Map) {
                    loop((Map) o);
                } else {
                    System.out.println(key + " : " + o);
                }
            }
        } else if (obj instanceof Map) {
            loop((Map) obj);
        } else {
            System.out.println(key + " : " + obj);
        }
    }
}

private static void loop(Map<String, Object> map) {
    for (String key : map.keySet()) {
        Object obj = map.get(key);
        if (obj instanceof List) {
            for (Object o : (List) obj) {
                if (o instanceof Map) {
                    loop((Map) o);
                } else {
                    System.out.println(key + " : " + o);
                }
            }
        } else if (obj instanceof Map) {
            loop((Map) obj);
        } else {
            System.out.println(key + " : " + obj);
        }
    }
}


问:
Show character limit under input in React Js
I am creating a react input component and need to show the character limit underneath the input ex: (0/500 characters remaining). I have passed the maxLength as a prop into the input component but am unsure of how to show the number of characters remaining before the limit is reached.

The max length works properly - how can I add the visual feedback of showing how many characters are remaining (2/500 characters... etc).

```<code><input
    {...customAttributes}
    maxLength={maxLength}
    required={required}
/>
</code>```

And then I call my component like so:

```<code><InputComponent maxLength={10} />
</code>```

答:
The question does not have enough information to answer correctly, but based on the reaction to the comment, something like this should work:

```<code><div>
    {this.props.maxLength - this.state.whateverYouNamedTheValue.length}/{this.props.maxLength}
</div>
</code>```

In the context of a component, cleaned up with ES6 a bit:

```<code>class InputComponent extends React.Component {
    // ... class and state stuff ...
    render() {
        const { maxLength } = this.props;
        const { whateverYouNamedTheValue } = this.state;

        return (
            <div>
                <input
                    {...customAttributes}
                    maxLength={maxLength}
                    required={required}
                />
                { whateverYouNamedTheValue ? (
                    <div>
                        ({ maxLength - whateverYouNamedTheValue.length }/{ maxLength })
                    </div>
                ) : null }
            </div>
        );
    }
}
</code>```

Body:
I am creating a react input component and need to show the character limit underneath the input ex: (0/500 characters remaining). I have passed the maxLength as a prop into the input component but am unsure of how to show the number of characters remaining before the limit is reached.

The max length works properly - how can I add the visual feedback of showing how many characters are remaining (2/500 characters... etc).

<input
    {...customAttributes}
    maxLength={maxLength}
    required={required}
/>

And then I call my component like so:

<InputComponent maxLength={10} />

Body:
The question does not have enough information to answer correctly, but based on the reaction to the comment, something like this should work:

<div>
    {this.props.maxLength - this.state.whateverYouNamedTheValue.length}/{this.props.maxLength}
</div>

In the context of a component, cleaned up with ES6 a bit:

class InputComponent extends React.Component {
    // ... class and state stuff ...
    render() {
        const { maxLength } = this.props;
        const { whateverYouNamedTheValue } = this.state;

        return (
            <div>
                <input
                    {...customAttributes}
                    maxLength={maxLength}
                    required={required}
                />
                { whateverYouNamedTheValue ? (
                    <div>
                        ({ maxLength - whateverYouNamedTheValue.length }/{ maxLength })
                    </div>
                ) : null }
            </div>
        );
    }
}


问:
InsertionSort on Linked List , with Data from text file. Java
I'm doing insertion sort with my Linked List, and I have faced an issue.

My Data file:

```<code>Myjob 66
Junk   17
Fun    25
Vital       99
Important   96
MoreFun    28
Work      69
Assignment  44
</code>```

Here is my code for Insertion Sort

```<code>public Node insertSort(Node node){
   Node sortedNode = null;
   while(node != null){
    Node current = node;
    node = node.next;
    Node x;
    Node previous = null;
    for(x = sortedNode; x != null; x = x.next){
        if(current.getData().getNum() > x.getData().getNum()){
                break;
         }
         previous = x;
    }
    if(previous == null){
          current.next = sortedNode;
          sortedNode = current;
    }
    else{
       current.next = previous.next;
       previous.next = current;
    }
  }
   sortedNode=head;
  return sortedNode; }
</code>```

My currently output:

```<code>Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null
</code>```

they skip whatever greater than 66. Do anyone have any ideas how to fix this issue, so it can display from 99 down to 17? I tried rearranging the order in the text file a little bit, with the highest first. then the program can perform sorting from 99 back to 17 perfectly. But with the original order, my program just can perform sorting from 66 to lowest. I don't know why, and how to fix it? Please help.  I'm very new in Java. Thank you so much.

My Data Class

```<code>public class Data {

private String name;
private int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name=name;
}

public int getNum(){
    return num;
}

public void setNume(int num){
    this.num=num;
}

public String toString()
{
    return "Name = " + name + "            Priority=" + num ;
}

}
</code>```

Here is my LinkedList Class:

```<code>public class LinkedList {
Node head;
Node prev;
Node cur;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

public void printLinkedList(){
    System.out.println(head);
}

public void initializeLL(){
    Node currentNode = head;
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            if(currentNode == null){
                currentNode = n;
                head = n;
            }else{
                currentNode.setNext(n);
                currentNode = n;
            }
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        l1.initializeLL();
        l1.insertSort(l1.head);
        l1.printLinkedList();
        System.out.println("************");
}
}
</code>```

Here is my Node Class:

```<code>public class Node{
Data dt;
Node next;

public Node(){

}
public Node(Data dt){
    this.dt=dt;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt;
}

public void setData(Data dt){
    this.dt=dt;
}

public String toString()
{
    StringBuilder sb = new StringBuilder();
    sb.append(dt).append(System.getProperty("line.separator"));
    sb.append(next).append(System.getProperty("line.separator"));

    return sb.toString();

}
}
</code>```

The insertionSort method is inside the LinkedList Class.

答:
Are you sure your code here is correct?
I trace your code and I find that for loop is not run anyway because x is always null in each run of insertSort() function.

How you call insertSort() function to sort data?

EDIT:

Ok. I review your code. I found that your sort is correct but after sorting function head of LinkList is not update. So your code prints sorted list from old head.
You should update head of linkedlist after sort function.

Body:
I'm doing insertion sort with my Linked List, and I have faced an issue.

My Data file:

Myjob 66
Junk   17
Fun    25
Vital       99
Important   96
MoreFun    28
Work      69
Assignment  44

Here is my code for Insertion Sort

public Node insertSort(Node node){
   Node sortedNode = null;
   while(node != null){
    Node current = node;
    node = node.next;
    Node x;
    Node previous = null;
    for(x = sortedNode; x != null; x = x.next){
        if(current.getData().getNum() > x.getData().getNum()){
                break;
         }
         previous = x;
    }
    if(previous == null){
          current.next = sortedNode;
          sortedNode = current;
    }
    else{
       current.next = previous.next;
       previous.next = current;
    }
  }
   sortedNode=head;
  return sortedNode; }

My currently output:

Name = Myjob            Priority=66
Name = Assignment            Priority=44
Name = MoreFun            Priority=28
Name = Fun            Priority=25
Name = Junk            Priority=17
null

they skip whatever greater than 66. Do anyone have any ideas how to fix this issue, so it can display from 99 down to 17? I tried rearranging the order in the text file a little bit, with the highest first. then the program can perform sorting from 99 back to 17 perfectly. But with the original order, my program just can perform sorting from 66 to lowest. I don't know why, and how to fix it? Please help.  I'm very new in Java. Thank you so much.

My Data Class

public class Data {

private String name;
private int num;

public Data(){
}

public Data(String name,int num){
    this.name=name;
    this.num=num;
}

public String getName(){
    return name;
}

public void setName(String name){
    this.name=name;
}

public int getNum(){
    return num;
}

public void setNume(int num){
    this.num=num;
}

public String toString()
{
    return "Name = " + name + "            Priority=" + num ;
}

}

Here is my LinkedList Class:

public class LinkedList {
Node head;
Node prev;
Node cur;

public LinkedList(){

}

public LinkedList(Node head){
    head = null;
}

//getter to get head
public Node gethead(){
    return head;
}

public void printLinkedList(){
    System.out.println(head);
}

public void initializeLL(){
    Node currentNode = head;
    try
    {
        File file = new File("Asg2Data.txt");
        Scanner sc = new Scanner(file);
        while (sc.hasNext())
        {
            Data d = new Data(sc.next(), sc.nextInt());
            Node n = new Node(d);

            if(currentNode == null){
                currentNode = n;
                head = n;
            }else{
                currentNode.setNext(n);
                currentNode = n;
            }
        }
        sc.close();
    }
    catch (Exception ex)
    {
        ex.printStackTrace();
    }
}

public static void main(String[] args) throws FileNotFoundException{

        LinkedList l1 = new LinkedList();
        l1.initializeLL();
        l1.insertSort(l1.head);
        l1.printLinkedList();
        System.out.println("************");
}
}

Here is my Node Class:

public class Node{
Data dt;
Node next;

public Node(){

}
public Node(Data dt){
    this.dt=dt;
}

public Node getNext(){
    return next;
}

public void setNext(Node next){
    this.next=next;
}

public Data getData(){
    return dt;
}

public void setData(Data dt){
    this.dt=dt;
}

public String toString()
{
    StringBuilder sb = new StringBuilder();
    sb.append(dt).append(System.getProperty("line.separator"));
    sb.append(next).append(System.getProperty("line.separator"));

    return sb.toString();

}
}

The insertionSort method is inside the LinkedList Class.


问:
Caffe and Tensorflow on a Dell 7559 with nvidia optimus technology
I bought a dell 7559 laptop for deep learning. I got ubuntu 16.04 installed on it but I am having trouble getting caffe and tensorflow on it. The laptop used Nvidia Optimus technology to switch between gpu and cpu to save battery usage. I checked the bios to see if I can set it to use only gpu but there is no option for it. Using bumblebee or nvidia-prime didnt work either. I now have ubuntu 16 with mate desktop environment it is preventing from getting the black screen but didnt help with the cuda issue. I was able to install the drivers and cuda but when I build caffe and tensorflow they fail saying that it didnt detect a gpu. And I wasnt able to install opengl. I tried using several versions of nvidia drivers but it didnt help. Any help would be great. thanks.</p>

答:
I think Bumblebee can enable you to run Caffe/Tensorflow in GPU mode. More generally, it also allows you to run other CUDA programs on a laptop with Optimus technology .

When you have installed Bumblebee correctly (tutorial: Bumblebee Wiki for Ubuntu ), you can invoke the Caffe binary by pepending optirun before the caffe binary. So it goes like the following:

```<code>optirun ../../caffe-master/build/tools/caffe train --solver=solver.prototxt
</code>```

This works for the NVidia DIGITS server as well:

```<code>optirun ./digits-devserver
</code>```

In addition, Bumblebee also works on my dual-graphics desktop PC (Intel HD 4600 + GTX 750 Ti) as well. The display on my PC is driven by the Intel HD 4600 through the HDMI port on the motherboard. The NVidia GTX 750 Ti is only used for CUDA programs.

In fact, for my desktop PC, the "nvidia-prime" (it's actually invoked through the command line program prime-select) is used to choose the GPU that drives the desktop. I have the integrated GPU connect to the display with the HDMI port and the NVidia GPU through a DisplayPort. Currently, the DisplayPort is inactive. The display signal comes from the HDMI port.

As far as I understand, PRIME does so by modifying /etc/X11/Xorg.conf to make either the Intel integrated GPU or the NVidia GPU the current display adapter available to X. I think the PRIME settings only makes sense when both GPUs are connected to some display, which means there need not be an Optimus link between the two GPUs like in a laptop (or, for a laptop with a Mux such as Dell Precision M4600, the Optimus is disabled in BIOS).

More information about the Display Mux and Optimus may be found here: Using the NVIDIA Driver with Optimus Laptops

Hope this helps!

Body:
I think Bumblebee can enable you to run Caffe/Tensorflow in GPU mode. More generally, it also allows you to run other CUDA programs on a laptop with Optimus technology .

When you have installed Bumblebee correctly (tutorial: Bumblebee Wiki for Ubuntu ), you can invoke the Caffe binary by pepending optirun before the caffe binary. So it goes like the following:

optirun ../../caffe-master/build/tools/caffe train --solver=solver.prototxt

This works for the NVidia DIGITS server as well:

optirun ./digits-devserver

In addition, Bumblebee also works on my dual-graphics desktop PC (Intel HD 4600 + GTX 750 Ti) as well. The display on my PC is driven by the Intel HD 4600 through the HDMI port on the motherboard. The NVidia GTX 750 Ti is only used for CUDA programs.

In fact, for my desktop PC, the "nvidia-prime" (it's actually invoked through the command line program prime-select) is used to choose the GPU that drives the desktop. I have the integrated GPU connect to the display with the HDMI port and the NVidia GPU through a DisplayPort. Currently, the DisplayPort is inactive. The display signal comes from the HDMI port.

As far as I understand, PRIME does so by modifying /etc/X11/Xorg.conf to make either the Intel integrated GPU or the NVidia GPU the current display adapter available to X. I think the PRIME settings only makes sense when both GPUs are connected to some display, which means there need not be an Optimus link between the two GPUs like in a laptop (or, for a laptop with a Mux such as Dell Precision M4600, the Optimus is disabled in BIOS).

More information about the Display Mux and Optimus may be found here: Using the NVIDIA Driver with Optimus Laptops

Hope this helps!


问:
meaning of wine.classes in r code
Looking at some of the code here:

```<code>data(wines)
set.seed(7)

training <- sample(nrow(wines), 120)
Xtraining <- scale(wines[training, ])
Xtest <- scale(wines[-training, ],
               center = attr(Xtraining, "scaled:center"),
               scale = attr(Xtraining, "scaled:scale"))

som.wines <- som(Xtraining, grid = somgrid(5, 5, "hexagonal"))

som.prediction <- predict(som.wines, newdata = Xtest,
          trainX = Xtraining,
          trainY = factor(wine.classes[training]))
table(wine.classes[-training], som.prediction$prediction)
</code>```

Everything makes total sense, but I just do not understand the meaning of:

```<code>wine.classes
</code>```

and where it comes from? Any pointers would be very much appreciated. Thanks!

答:
Look at the sample in the documentation of package ‘kohonen’ version 3.0.2:

```<code>data(wines)
## som
som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal"))
summary(som.wines)

## xyf
xyf.wines <- xyf(scale(wines), vintages, grid = somgrid(5, 5, "hexagonal"))
summary(xyf.wines)
</code>```

When you load the wines dataset, it is loaded a variable named vintages. This is the same wine.classes you may need.

By the way, SOM (Self organizing Maps) do not requires label values because it is a non-supervised algorithm.  xyf requires label values because it is indeed a supervised algorithm.

Title: meaning of wine.classes in r code

Body:
Looking at some of the code here:

data(wines)
set.seed(7)

training <- sample(nrow(wines), 120)
Xtraining <- scale(wines[training, ])
Xtest <- scale(wines[-training, ],
               center = attr(Xtraining, "scaled:center"),
               scale = attr(Xtraining, "scaled:scale"))

som.wines <- som(Xtraining, grid = somgrid(5, 5, "hexagonal"))

som.prediction <- predict(som.wines, newdata = Xtest,
          trainX = Xtraining,
          trainY = factor(wine.classes[training]))
table(wine.classes[-training], som.prediction$prediction)

Everything makes total sense, but I just do not understand the meaning of:

wine.classes

and where it comes from? Any pointers would be very much appreciated. Thanks!

Body:
Look at the sample in the documentation of package ‘kohonen’ version 3.0.2:

data(wines)
## som
som.wines <- som(scale(wines), grid = somgrid(5, 5, "hexagonal"))
summary(som.wines)

## xyf
xyf.wines <- xyf(scale(wines), vintages, grid = somgrid(5, 5, "hexagonal"))
summary(xyf.wines)

When you load the wines dataset, it is loaded a variable named vintages. This is the same wine.classes you may need.

By the way, SOM (Self organizing Maps) do not requires label values because it is a non-supervised algorithm.  xyf requires label values because it is indeed a supervised algorithm.


问:
How do you set the height and width of a UIButton with image
This is driving me nuts. I have looked everywhere and cannot figure this out. Check it out...

```<code>    let findMeButton = UIButton(type: UIButtonType.System)

    findMeButton.translatesAutoresizingMaskIntoConstraints = false

    findMeButton.setImage(UIImage(named: "locateMe"), forState: UIControlState.Normal)

    findMeButton.addTarget(self, action: #selector(MapViewController.findUserLocation(_:)), forControlEvents: UIControlEvents.TouchUpInside)

    view.addSubview(findMeButton)

    // I added this line of code and it still doesn't work.
    findMeButton.frame.size = CGSizeMake(50, 50)

    findMeButton.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -10).active = true

    findMeButton.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor, constant: 5).active = true
</code>```

I am still learning iOS. How do you set the Height and Width of this UIButton with an Image. Everything I have tried has given me an error or just didn't work. I am still trying to rap my head around what  translatesAutoresizingMaskIntoConstraints does. I just simply want to have the Button where it is but change its size (Height & Width).

Thanks in advance

EDIT: I have changed the bit of code to this

```<code>    // Locate user button
    let locateButton = UIButton(type: UIButtonType.System) as UIButton

    locateButton.frame = CGRectMake(0, 0, 50, 50)

    locateButton.setBackgroundImage(UIImage(named: "locateMe"), forState: UIControlState.Normal)

    locateButton.addTarget(self, action: #selector(MapViewController.findUserLocation(_:)), forControlEvents: UIControlEvents.TouchUpInside)

    view.addSubview(locateButton)
</code>```

I want to position the button to the windows bottom and right margin. I also want to set the image dimensions to height 50 x width 50. How would I accomplish this?

EDIT 2: I figure you have to use Auto Layout to do so but can someone show me how. Everything I have done hasn't worked.

答:
Swift 3

```<code>findMeButton.frame.size = CGSize(width, height)
</code>```

Body:
This is driving me nuts. I have looked everywhere and cannot figure this out. Check it out...

    let findMeButton = UIButton(type: UIButtonType.System)

    findMeButton.translatesAutoresizingMaskIntoConstraints = false

    findMeButton.setImage(UIImage(named: "locateMe"), forState: UIControlState.Normal)

    findMeButton.addTarget(self, action: #selector(MapViewController.findUserLocation(_:)), forControlEvents: UIControlEvents.TouchUpInside)

    view.addSubview(findMeButton)

    // I added this line of code and it still doesn't work.
    findMeButton.frame.size = CGSizeMake(50, 50)

    findMeButton.bottomAnchor.constraintEqualToAnchor(bottomLayoutGuide.topAnchor, constant: -10).active = true

    findMeButton.trailingAnchor.constraintEqualToAnchor(margins.trailingAnchor, constant: 5).active = true

I am still learning iOS. How do you set the Height and Width of this UIButton with an Image. Everything I have tried has given me an error or just didn't work. I am still trying to rap my head around what  translatesAutoresizingMaskIntoConstraints does. I just simply want to have the Button where it is but change its size (Height & Width).

Thanks in advance

EDIT: I have changed the bit of code to this

    // Locate user button
    let locateButton = UIButton(type: UIButtonType.System) as UIButton

    locateButton.frame = CGRectMake(0, 0, 50, 50)

    locateButton.setBackgroundImage(UIImage(named: "locateMe"), forState: UIControlState.Normal)

    locateButton.addTarget(self, action: #selector(MapViewController.findUserLocation(_:)), forControlEvents: UIControlEvents.TouchUpInside)

    view.addSubview(locateButton)

I want to position the button to the windows bottom and right margin. I also want to set the image dimensions to height 50 x width 50. How would I accomplish this?

EDIT 2: I figure you have to use Auto Layout to do so but can someone show me how. Everything I have done hasn't worked.

Body:
Swift 3

findMeButton.frame.size = CGSize(width, height)


问:
why IdleConnectionMonitorThread need to synchronize
I see many examples of IdleConnectionMonitorThread using 'synchronized' in implement of 'run'. In my mind, it makes no sense.
The implement in

              edu.uci.ics
              crawler4j
              4.2

```<code>public class IdleConnectionMonitorThread extends Thread {

  private final PoolingHttpClientConnectionManager connMgr;
  private volatile boolean shutdown;

  public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
    super("Connection Manager");
    this.connMgr = connMgr;
  }

  @Override
  public void run() {
    try {
      while (!shutdown) {
        synchronized (this) {
          wait(5000);
          // Close expired connections
          connMgr.closeExpiredConnections();
          // Optionally, close connections that have been idle longer than 30 sec
          connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
        }
      }
    } catch (InterruptedException ignored) {
      // terminate
    }
  }

  public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
        log.warn("newPosition: shutdown idleMonitorThread");

    }

}
</code>```

Since in most cases we only have one IdleConnectionMonitorThread and use it in this way, synchronized (this) has no meaning.

```<code>IdleConnectionMonitorThread idleConnectionMonitorThread = new IdleConnectionMonitorThread(poolingHttpClientConnectionManager)
</code>```

I wonder the benefit of using 'synchronized', can use implement run in this way (delete the synchronized)

```<code>      @Override
      public void run() {
        try {
          while (!shutdown) {
              wait(5000);
              // Close expired connections
              connMgr.closeExpiredConnections();
              // Optionally, close connections that have been idle longer than 30 sec
              connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
          }
        } catch (InterruptedException ignored) {
          // terminate
        }
      }
</code>```

答:
Read the javadocs for Object.wait(long).

If you call it when you don't hold the mutex you are waiting on, you will get an exception.  The javadoc states:

Throws: IllegalMonitorStateException - if the current thread is not the owner of the object's monitor.

In general, locking the mutex in the "wait/notify" protocol is essential to ensure that the shared state that is being managed is visible to all threads that are participating.  In this case the shutdown variable is declared as volatile so that isn't a concern.  However, the "wait/notify" protocol requires locking anyway; see above.

I wonder the benefit of using synchronized, can use implement run in this way (delete the synchronized).

Nope.  If you deleted the synchronized you would get an exception.  But you could replace Object.wait(...) with Thread.sleep(...) ... and then the synchronized would be unnecessary.

As to the "oddness" of this code, who knows why the author ended up with this.  But does it really matter?  There is an Engineering principle: "If it ain't broken, don't fix it".  Nobody has proposed a reason why this code is broken.

Body:
I see many examples of IdleConnectionMonitorThread using 'synchronized' in implement of 'run'. In my mind, it makes no sense.
The implement in

              edu.uci.ics
              crawler4j
              4.2

public class IdleConnectionMonitorThread extends Thread {

  private final PoolingHttpClientConnectionManager connMgr;
  private volatile boolean shutdown;

  public IdleConnectionMonitorThread(PoolingHttpClientConnectionManager connMgr) {
    super("Connection Manager");
    this.connMgr = connMgr;
  }

  @Override
  public void run() {
    try {
      while (!shutdown) {
        synchronized (this) {
          wait(5000);
          // Close expired connections
          connMgr.closeExpiredConnections();
          // Optionally, close connections that have been idle longer than 30 sec
          connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
        }
      }
    } catch (InterruptedException ignored) {
      // terminate
    }
  }

  public void shutdown() {
        shutdown = true;
        synchronized (this) {
            notifyAll();
        }
        log.warn("newPosition: shutdown idleMonitorThread");

    }

}

Since in most cases we only have one IdleConnectionMonitorThread and use it in this way, synchronized (this) has no meaning.

IdleConnectionMonitorThread idleConnectionMonitorThread = new IdleConnectionMonitorThread(poolingHttpClientConnectionManager)

I wonder the benefit of using 'synchronized', can use implement run in this way (delete the synchronized)

      @Override
      public void run() {
        try {
          while (!shutdown) {
              wait(5000);
              // Close expired connections
              connMgr.closeExpiredConnections();
              // Optionally, close connections that have been idle longer than 30 sec
              connMgr.closeIdleConnections(30, TimeUnit.SECONDS);
          }
        } catch (InterruptedException ignored) {
          // terminate
        }
      }


问:
Google foobar minion labor shifts challenge
I have a Google foobar challenge:

Write a function called answer(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully-planned shift rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1, answer(data, n) would return the list [5, 15, 7] because 10 occurs twice, and thus was removed from the list entirely.

And this was my answer:

```<code>def answer(data=[], n=0):
    for id in data:
        num = data.count(id)
        if num > n:
            for i in data:
                if i == id:
                    data.remove (id)
                else:
                    continue
        else:
            continue
    return data
</code>```

But it didn't pass the test.

答:
You can answer this by using list comprehensions in one line (not optimal for larger data set):

```<code>def answer(data, n):
    return [x for x in data if x not in [y for y in set(data) if data.count(y) > n]]
</code>```

Normal way:

```<code>def answer(data, n):
    data_set = set(data)
    for d in data_set:
        if data.count(d) > n:
            data = filter(lambda a: a != d, data)
    return data
</code>```

Body:
I have a Google foobar challenge:

Write a function called answer(data, n) that takes in a list of less than 100 integers and a number n, and returns that same list but with all of the numbers that occur more than n times removed entirely. The returned list should retain the same ordering as the original list - you don't want to mix up those carefully-planned shift rotations! For instance, if data was [5, 10, 15, 10, 7] and n was 1, answer(data, n) would return the list [5, 15, 7] because 10 occurs twice, and thus was removed from the list entirely.

And this was my answer:

def answer(data=[], n=0):
    for id in data:
        num = data.count(id)
        if num > n:
            for i in data:
                if i == id:
                    data.remove (id)
                else:
                    continue
        else:
            continue
    return data

But it didn't pass the test.

Body:
You can answer this by using list comprehensions in one line (not optimal for larger data set):

def answer(data, n):
    return [x for x in data if x not in [y for y in set(data) if data.count(y) > n]]

Normal way:

def answer(data, n):
    data_set = set(data)
    for d in data_set:
        if data.count(d) > n:
            data = filter(lambda a: a != d, data)
    return data