问:
rhive.connect error: cannot modify RHIVE_UDF_DIR
I am trying to connect to Hive from R with the latest RHive package in HDP 2.4. The installation seemed to have gone smoothly, since I was able to call the library of RHive. When I execute

```<code>rhive.connect(host="192.168.56.101",port=10000, hiveServer2=TRUE)
</code>```

I got this error message:

Cannot modify mapred.child.env at runtime. It is not in list of params that are allowed to be modified at runtime.

After some googling around, I added the following to the /etc/hive/conf/hive-site.xml file:

```<code><property>
      <name>hive.security.authorization.sqlstd.confwhitelist.append</name>
      <value>mapred.child.env</value>
</property>
</code>```

After restarting hive-server2, the original error message is now replaced by this one:

Cannot modify RHIVE_UDF_DIR at runtime. It is not in list of params
  that are allowed to be modified at runtime.

I tried adding RHIVE_UDF_DIR right next to map.child.env, like this:

```<code> <property>
  <name>hive.security.authorization.sqlstd.confwhitelist.append</name>
  <value>mapred.child.env,RHIVE_UDF_DIR</value>
 </property>
</code>```

But this did not resolve the problem; it brought back the original error message that I was getting at the very beginning. Any thoughts on this? Thanks in advance!

答:
I know this is late reply but I just came across this thread. Using java regex instead of comma separated would work. This worked for me this morning.

Config parameter should be added under hive-site.xml

```<code>hive.security.authorization.sqlstd.confwhitelist.append=mapred\.child\.env|RHIVE_UDF_DIR
</code>```

Ps: Backslash was not displaying above so adding screenshot link.
config parameter with proper java regex for values

Body:
I am trying to connect to Hive from R with the latest RHive package in HDP 2.4. The installation seemed to have gone smoothly, since I was able to call the library of RHive. When I execute

rhive.connect(host="192.168.56.101",port=10000, hiveServer2=TRUE)

I got this error message:

Cannot modify mapred.child.env at runtime. It is not in list of params that are allowed to be modified at runtime.

After some googling around, I added the following to the /etc/hive/conf/hive-site.xml file:

<property>
      <name>hive.security.authorization.sqlstd.confwhitelist.append</name>
      <value>mapred.child.env</value>
</property>

After restarting hive-server2, the original error message is now replaced by this one:

Cannot modify RHIVE_UDF_DIR at runtime. It is not in list of params
  that are allowed to be modified at runtime.

I tried adding RHIVE_UDF_DIR right next to map.child.env, like this:

 <property>
  <name>hive.security.authorization.sqlstd.confwhitelist.append</name>
  <value>mapred.child.env,RHIVE_UDF_DIR</value>
 </property>

But this did not resolve the problem; it brought back the original error message that I was getting at the very beginning. Any thoughts on this? Thanks in advance!

Body:
I know this is late reply but I just came across this thread. Using java regex instead of comma separated would work. This worked for me this morning.

Config parameter should be added under hive-site.xml

hive.security.authorization.sqlstd.confwhitelist.append=mapred\.child\.env|RHIVE_UDF_DIR

Ps: Backslash was not displaying above so adding screenshot link.
config parameter with proper java regex for values


来源: stackexchange

问:
How to solve error message: "Failed to map the path '/'."
I've searched and searched on Google, and I can't find anything that even seems applicable to my situation, let alone solves the problem. It doesn't matter which address in my website I try to navigate to (even addresses that don't exist give this error instead of a 404), I get the exact same message (the path is always '/'). Any ideas?

Server Error in '/' Application.

Failed to map the path '/'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Failed to map the path '/'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: Failed to map the path '/'.]
   System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) +336

[HttpException (0x80004005): Failed to map the path '/'.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11556592
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4813333

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225
```

UPDATE: I went back to the site a few minutes after posting this--made no changes to code or configuration--and the error went away. I'm really baffled, but it is no longer a problem.

答:
~I've gone to the Internet Information Services Manager

~Click the sites

~Right click on your website

~Click Manage Website > Advance Settings

~Change the application pool to DefaultAppPool

And it works fine to me.

ContentLicense: CC BY-SA 4.0

Body:
I've searched and searched on Google, and I can't find anything that even seems applicable to my situation, let alone solves the problem. It doesn't matter which address in my website I try to navigate to (even addresses that don't exist give this error instead of a 404), I get the exact same message (the path is always '/'). Any ideas?

Server Error in '/' Application.

Failed to map the path '/'.

Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.

Exception Details: System.InvalidOperationException: Failed to map the path '/'.

Source Error:

An unhandled exception was generated during the execution of the current web request. Information regarding the origin and location of the exception can be identified using the exception stack trace below.

Stack Trace:

[InvalidOperationException: Failed to map the path '/'.]
   System.Web.HttpRuntime.HostingInit(HostingEnvironmentFlags hostingFlags, PolicyLevel policyLevel, Exception appDomainCreationException) +336

[HttpException (0x80004005): Failed to map the path '/'.]
   System.Web.HttpRuntime.FirstRequestInit(HttpContext context) +11556592
   System.Web.HttpRuntime.EnsureFirstRequestInit(HttpContext context) +141
   System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, HttpContext context) +4813333

Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.0.30319.225

UPDATE: I went back to the site a few minutes after posting this--made no changes to code or configuration--and the error went away. I'm really baffled, but it is no longer a problem.


问:
Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT clause?
Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause?

```<code>CREATE TABLE `foo` (
  `ProductID` INT(10) UNSIGNED NOT NULL,
  `AddedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `UpdatedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=INNODB;
</code>```

The error that results:

Error Code : 1293

Incorrect table definition; there can
  be only one TIMESTAMP column with
  CURRENT_TIMESTAMP in DEFAULT or ON
  UPDATE clause

答:
I also wondered that long time ago. I searched a bit in my history and I think that this post: http://lists.mysql.com/internals/34919 represents the semi-official position of MySQL  (before Oracle's intervention ;))

In short:

this limitation stems only from the
  way in which this feature is currently
  implemented in the server and there
  are no other reasons for its
  existence.

So their explanation is "because it is implemented like this". Doesn't sound very scientific. I guess it all comes from some old code. This is suggested in the thread above: "carry-over from when only the first timestamp field was auto-set/update".

Cheers!

ContentLicense: CC BY-SA 2.5

Body:
Why there can be only one TIMESTAMP column with CURRENT_TIMESTAMP in DEFAULT or ON UPDATE clause?

CREATE TABLE `foo` (
  `ProductID` INT(10) UNSIGNED NOT NULL,
  `AddedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  `UpdatedDate` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
) ENGINE=INNODB;

The error that results:

Error Code : 1293

Incorrect table definition; there can
  be only one TIMESTAMP column with
  CURRENT_TIMESTAMP in DEFAULT or ON
  UPDATE clause


问:
Efficiently sample vectors from numpy ndarray
I have a multidimensional numpy array X of shape: (B, dim, H, W) I would like to randomly sample k dim-dimensional vectors out of X.

I can get the sample indices from a msk of shape (B, 1, H, W):

```<code>sIdx = random.sample((msk.flat>=0).nonzero()[0], k)
</code>```

Equivalent sampling code using numpy is:

```<code>sIdx = np.random.choice((msk.flat>=0).nonzero()[0], replace=False, size=(k,))
</code>```

But how can I efficiently slice X according to the "flat" sampled indices sIdx?

That is, is there an efficient way to combine the random sampling of msk with the slicing of X?

答:
Get the respective indices for the rest of those three axes with np.unravel_index from the flattened indices and simply index into X along those axes for the final output, like so -

```<code>I,J,K = np.unravel_index(sIdx, (B, H, W))
out = X[I,:,J,K]
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a multidimensional numpy array X of shape: (B, dim, H, W) I would like to randomly sample k dim-dimensional vectors out of X.

I can get the sample indices from a msk of shape (B, 1, H, W):

sIdx = random.sample((msk.flat>=0).nonzero()[0], k)

Equivalent sampling code using numpy is:

sIdx = np.random.choice((msk.flat>=0).nonzero()[0], replace=False, size=(k,))

But how can I efficiently slice X according to the "flat" sampled indices sIdx?

That is, is there an efficient way to combine the random sampling of msk with the slicing of X?

Body:
Get the respective indices for the rest of those three axes with np.unravel_index from the flattened indices and simply index into X along those axes for the final output, like so -

I,J,K = np.unravel_index(sIdx, (B, H, W))
out = X[I,:,J,K]


问:
Why is the following code throws undefined index while uploading file in PHP?
Marking the question as duplicate is futile, cause I've referred all such questions on SO and none of them did provide a solution.

```<code><?php
if(isset($_POST['submit'])){
$name=$_FILES['filedoc']['name'];
$temp_name=$_FILES['filedoc']['tmp_name'];
if(isset($name)){
    if(!empty($name)){
        $file=file_get_contents($temp_name);
        }
    }
else echo"Please upload file";

echo "<form action=\"";echo htmlentities($_SERVER["PHP_SELF"]);echo "\" method=\"post\">
    <h2>New Paste</h2>
    <label> Upload File?  <input type = \"file\" name = \"filedoc\"/></label><br><span class=\"error\">";echo $fileErr;echo"</span><br>
    <input id=\"button\"class=\"red\" type =\"submit\" class=\"red\" name=\"submit\" value = \"Paste\"/><br><span class=\"error\">";echo $submitErr;echo "</span>
    </form>";
}
?>
</code>```

Form is being displayed correctly. So there are no errors in the second part. But then, I get this error ( ! ) Notice: Undefined index: filedoc in path of the file

答:
The form also needs the following attribute: enctype="multipart/form-data". It specifies which content-type to use when submitting the form
Without the requirement above, the file upload will not work.

Body:
Marking the question as duplicate is futile, cause I've referred all such questions on SO and none of them did provide a solution.

<?php
if(isset($_POST['submit'])){
$name=$_FILES['filedoc']['name'];
$temp_name=$_FILES['filedoc']['tmp_name'];
if(isset($name)){
    if(!empty($name)){
        $file=file_get_contents($temp_name);
        }
    }
else echo"Please upload file";

echo "<form action=\"";echo htmlentities($_SERVER["PHP_SELF"]);echo "\" method=\"post\">

New Paste

     Upload File?  <input type = \"file\" name = \"filedoc\"/>
";echo $fileErr;echo"

    <input id=\"button\"class=\"red\" type =\"submit\" class=\"red\" name=\"submit\" value = \"Paste\"/>
";echo $submitErr;echo "
    </form>";
}
?>

Form is being displayed correctly. So there are no errors in the second part. But then, I get this error ( ! ) Notice: Undefined index: filedoc in path of the file


问:
Azure Functions Table Binding: How do I update a row?
I am trying to update a row in an Azure table based on an Azure Function. I see that the Table bindings can handle an ICollector which has an Add method which will add a row. I also see that you use an IQueryable to read the data.

How do you go about updating a specific row in the data?

I saw in WebJobs something related to InsertOrReplace which is a method of TableOperations but I don't know if or how that comes into play and how to use it with Azure Functions.

答:
With the current version of Functions, I was able to make row updates work with declarative bindings. Here is an example with HTTP trigger, which increments a number in Azure Table row.

function.json:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "route": "HttpTriggerTableUpdate/{partition}/{rowkey}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "table",
      "name": "inputEntity",
      "tableName": "SOTrial",
      "partitionKey": "{partition}",
      "rowKey": "{rowkey}",
      "connection": "my_STORAGE",
      "direction": "in"
    },
    {
      "type": "table",
      "name": "outputEntity",
      "tableName": "SOTrial",
      "partitionKey": "{partition}",
      "rowKey": "{rowkey}",
      "connection": "my_STORAGE",
      "direction": "out"
    }
  ],
  "disabled": false
}
```

<p>C# function:</p>

<pre class="lang-cs prettyprint-override"><code>#r "Microsoft.WindowsAzure.Storage"

using System;
using System.Net;
using Microsoft.WindowsAzure.Storage.Table;

public class Entity : TableEntity
{
    public int Number {get; set;}
}

public static HttpResponseMessage Run(HttpRequestMessage req, string partition,
    string rowkey, Entity inputEntity, out Entity outputEntity)
{
    if (inputEntity == null)
        outputEntity = new Entity { PartitionKey = partition, RowKey = rowkey, Number = 1};
    else
    {
        outputEntity = inputEntity;
        outputEntity.Number += 1;
    }

    return req.CreateResponse(HttpStatusCode.OK, $"Done, Number = {outputEntity.Number}");
}
</code>```

Body:
With the current version of Functions, I was able to make row updates work with declarative bindings. Here is an example with HTTP trigger, which increments a number in Azure Table row.

function.json:

{
  "bindings": [
    {
      "authLevel": "function",
      "name": "req",
      "type": "httpTrigger",
      "direction": "in",
      "route": "HttpTriggerTableUpdate/{partition}/{rowkey}"
    },
    {
      "name": "$return",
      "type": "http",
      "direction": "out"
    },
    {
      "type": "table",
      "name": "inputEntity",
      "tableName": "SOTrial",
      "partitionKey": "{partition}",
      "rowKey": "{rowkey}",
      "connection": "my_STORAGE",
      "direction": "in"
    },
    {
      "type": "table",
      "name": "outputEntity",
      "tableName": "SOTrial",
      "partitionKey": "{partition}",
      "rowKey": "{rowkey}",
      "connection": "my_STORAGE",
      "direction": "out"
    }
  ],
  "disabled": false
}

C# function:

#r "Microsoft.WindowsAzure.Storage"

using System;
using System.Net;
using Microsoft.WindowsAzure.Storage.Table;

public class Entity : TableEntity
{
    public int Number {get; set;}
}

public static HttpResponseMessage Run(HttpRequestMessage req, string partition,
    string rowkey, Entity inputEntity, out Entity outputEntity)
{
    if (inputEntity == null)
        outputEntity = new Entity { PartitionKey = partition, RowKey = rowkey, Number = 1};
    else
    {
        outputEntity = inputEntity;
        outputEntity.Number += 1;
    }

    return req.CreateResponse(HttpStatusCode.OK, $"Done, Number = {outputEntity.Number}");
}


问:
Loop - Accept multiple times input from a single textbox name in PHP
(this might get confusing) i have 2 textboxes which would accept color and amount from a user ten times:

```<code><form action="" method="POST">
  <i> color </i><input type="text" name="text[]">
  <i> color amount </i> <input type="number" name="num[]">
  <input type="submit" value="Go">
</form>
</code>```

Now what i want to happen is that instead of declaring ten text boxes for color and amount i would just want to loop it so that after the first color and amount had been sent it would again ask for 9 times without displaying 10 textboxes for each name. Is there a way in php to loop it?

Thanks.
Regars,
Russel

答:
I would use Ajax. You can store a counter variable in JS and when it reaches 10 you just disable the form or show a message to the user.

jQuery.post()

If Ajax is not an option you always can have the counter in your PHP file. I would sugget storing it in a session. Then when counter reaches 10 you just dont echo the form or something.

```<code>session_start();
$_SESSION['counter'] = (!$_SESSION['counter']) ? 0 : $_SESSION['counter'];
if($_POST['submit']) {
   $_SESSION['counter']++;
}
</code>```

EDITED: a basic idea (not tested yet) I would use button.click to avoid any kind of form submision

```<code><form id="myForm" method="post">
    <i> color </i><input type="text" name="text[]">
    <i> color amount </i><input type="number" name="num[]">
    <input id="button" value="OK" type="button">
</form>

<script>
    var formCounter = 0;

    $("#button").click(function(e) {
        var url = ""; // Whatever
        alert("OK");
        $.ajax({
            type: "POST",
            url: url,
            data: '', // Your data here
            success: function(data) {
                // Do you need to show confirmation?
                formCounter++;
                if(formCounter > 9){
                    // Disable/Hide form here
                }
            }
        });
        e.preventDefault();
    });
</script>
</code>```

Body:
(this might get confusing) i have 2 textboxes which would accept color and amount from a user ten times:

<form action="" method="POST">
   color <input type="text" name="text[]">
   color amount  <input type="number" name="num[]">
  <input type="submit" value="Go">
</form>

Now what i want to happen is that instead of declaring ten text boxes for color and amount i would just want to loop it so that after the first color and amount had been sent it would again ask for 9 times without displaying 10 textboxes for each name. Is there a way in php to loop it?

Thanks.
Regars,
Russel

Body:
I would use Ajax. You can store a counter variable in JS and when it reaches 10 you just disable the form or show a message to the user.

jQuery.post()

If Ajax is not an option you always can have the counter in your PHP file. I would sugget storing it in a session. Then when counter reaches 10 you just dont echo the form or something.

session_start();
$_SESSION['counter'] = (!$_SESSION['counter']) ? 0 : $_SESSION['counter'];
if($_POST['submit']) {
   $_SESSION['counter']++;
}

EDITED: a basic idea (not tested yet) I would use button.click to avoid any kind of form submision

<form id="myForm" method="post">
    <i> color </i><input type="text" name="text[]">
    <i> color amount </i><input type="number" name="num[]">
    <input id="button" value="OK" type="button">
</form>

<script>
    var formCounter = 0;

    $("#button").click(function(e) {
        var url = ""; // Whatever
        alert("OK");
        $.ajax({
            type: "POST",
            url: url,
            data: '', // Your data here
            success: function(data) {
                // Do you need to show confirmation?
                formCounter++;
                if(formCounter > 9){
                    // Disable/Hide form here
                }
            }
        });
        e.preventDefault();
    });
</script>


问:
How to display JSON array
So i have written this code to get a json from API.AI. i want to know how to echo out the decoded JSON file on this form. Currently the decoded JSON is being saved in a new file JSON.php, but instead of saving i want to know how to view it?</p>

```<code>$data = json_decode(file_get_contents("php://input"), true);
file_put_contents("JSON.php", print_r($data, true));
</code>```

答:
As comments state you can use var_dump to view the rough data but if you actually wanna use it for something you might wanna loop over the object and extracte properties.

like so:

```<code>foreach($data as $theData)
{
 echo $theData->property;
}
</code>```

Regards

Title: How to display JSON array

Body:
So i have written this code to get a json from API.AI. i want to know how to echo out the decoded JSON file on this form. Currently the decoded JSON is being saved in a new file JSON.php, but instead of saving i want to know how to view it?

$data = json_decode(file_get_contents("php://input"), true);
file_put_contents("JSON.php", print_r($data, true));

Body:
As comments state you can use var_dump to view the rough data but if you actually wanna use it for something you might wanna loop over the object and extracte properties.

like so:

foreach($data as $theData)
{
 echo $theData->property;
}

Regards


问:
Linking to a file in the Zend Framework
When I link directly to an uploaded file in a Zend Framework based project I get differing results depending on if I'm working in my local environment or my remote environment.

In both cases I want to link to an uploaded photo. The generated URL looks like:

http://whateverserverweareon/projectfiles/project18/photos/aphoto.jpg

On my local machine clicking that link will show me the photo, in my remote machine it gives me a warning about "invalid controller..." (as, while I do not have a "projectfiles" controller, the uploaded photos are in the projectfiles directory on the path specified in that sample url).

So how do I link to these uploaded photos? Create a controller just so I can link to them? Can I bypass the controller altogether and link directly? Is there some sort of custom route I need to create? Should I be doing this in a completely different manner? Any suggestions?

答: The exception means that on remote mashine your file does not exists in specified location. Standard rewrite rules in .htaccess file is written so that if your file exists (i.e. /projectfiles/project18/photos/aphoto.jpg) then index.php file of ZF will not be executed. You should check that your file exists.</p>

Title: Linking to a file in the Zend Framework


问:
How to Drop a Duplicates Column in dataframe while retaining the Unique Column including the only one column among duplicates
I am trying to drop the duplicate column while retaining only the unique columns and only one column among the duplicates after joining.

For Example:
Duplicate DataFrame

```<code>root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

After removing duplicates, the output should be

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
</code>```

Any help will be appreciated?

答:
As Shaido already commented above stating that you should drop all the columns that are not used for join as it would be difficult after you join them. (for example if loc and sal are not used in join then)

```<code>df2.drop("loc", "sal")
</code>```

or

```<code>df1.drop("loc", "sal")
</code>```

If you are using column names (for example id and name) in the join then do as

```<code>df1.join(df2, Seq("id", "name"))
</code>```

Body:
I am trying to drop the duplicate column while retaining only the unique columns and only one column among the duplicates after joining.

For Example:
Duplicate DataFrame

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

After removing duplicates, the output should be

root
|-- id: string (nullable = true)
|-- name: string (nullable = true)
|-- loc: string (nullable = true)
|-- sal: string (nullable = true)

Any help will be appreciated?

Body:
As Shaido already commented above stating that you should drop all the columns that are not used for join as it would be difficult after you join them. (for example if loc and sal are not used in join then)

df2.drop("loc", "sal")

or

df1.drop("loc", "sal")

If you are using column names (for example id and name) in the join then do as

df1.join(df2, Seq("id", "name"))


问:
OpenWeatherMap API HTTPS refusal javascript
I'm working through free code camp and trying to build a weather app using OpenWeatherMap API but It's not working. I'm using codepen because that's what it needs to be submitted on and it has to be a https to use geo location. This has become a problem because I get this error.

Mixed Content: The page at 'https://s.codepen.io/boomerang/8658fc75197c1c3799d7eb446c1be54c1475174843341/index.html?editors=0010' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://api.openweathermap.org/data/2.5/weather?lat=54.757753799999996&lon=-1.6074879&APPID=APIIDHERE'. This request has been blocked; the content must be served over HTTPS.

For some reason I thought it might work if I change the API call to HTTPS but then I get this error

GET https://api.openweathermap.org/data/2.5/weather?lat=54.757775699999996&lon=-1.6074815999999998&APPID=APIIDHERE net::ERR_CONNECTION_REFUSED

I have used an api key but i've just hidden it on here.

I've tried a few different ways of fixing it i've seen on other posts but nothing has worked so far :/

I'm using this code for the request

```<code>function updateLoc (lat, long) {
    var url = "https://api.openweathermap.org/data/2.5/weather?" +
        "lat=" + lat +
        "&lon=" + long +
        "&APPID=" + APPID;
    sendRequest (url);
}

function sendRequest (url) {
    var xmlhttp = new XMLHttpRequest ();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
            var data = JSON.parse (xmlhttp.responseText);

            var weather = {};
            weather.icon = data.weather.icon;
            weather.dir = data.wind.deg;
            weather.wind = data.wind.speed;
            weather.temp = data.main.temp;
            weather.loc = data.name;
            weather.hum = data.main.humidity;

            update (weather);
        }
    };
    xmlhttp.open ("GET", url, true);
    xmlhttp.send ();
}
</code>```

Any help would be appreciated :)

答:
I faced this same issue. I finally solved it by simply using the unsecured HTTP request, instead of the secured, HTTPS request. ie I changed the api url from https://api.openweathermap.org/... to http://api.openweathermap.org/...

Here is the supporting code:

NOT WORKING

```<code>function fetchWeatherInfo(){
     $.ajax({
            type: 'GET',
            url: 'https://api.openweathermap.org/data/2.5/forecast/daily?q=Bamenda&appid=****myid',
            success: function(response) {
                console.log(response);
            },
            error: function(xhr, status, error) {},
            cache: false
        });

}
</code>```

WORKING

```<code>function fetchWeatherInfo(){
     $.ajax({
            type: 'GET',
            url: 'http://api.openweathermap.org/data/2.5/forecast/daily?q=Bamenda&appid=****myid',
            success: function(response) {
                console.log(response);
            },
            error: function(xhr, status, error) {},
            cache: false
        });

}
</code>```

Body:
I'm working through free code camp and trying to build a weather app using OpenWeatherMap API but It's not working. I'm using codepen because that's what it needs to be submitted on and it has to be a https to use geo location. This has become a problem because I get this error.

Mixed Content: The page at 'https://s.codepen.io/boomerang/8658fc75197c1c3799d7eb446c1be54c1475174843341/index.html?editors=0010' was loaded over HTTPS, but requested an insecure XMLHttpRequest endpoint 'http://api.openweathermap.org/data/2.5/weather?lat=54.757753799999996&lon=-1.6074879&APPID=APIIDHERE'. This request has been blocked; the content must be served over HTTPS.

For some reason I thought it might work if I change the API call to HTTPS but then I get this error

GET https://api.openweathermap.org/data/2.5/weather?lat=54.757775699999996&lon=-1.6074815999999998&APPID=APIIDHERE net::ERR_CONNECTION_REFUSED

I have used an api key but i've just hidden it on here.

I've tried a few different ways of fixing it i've seen on other posts but nothing has worked so far :/

I'm using this code for the request

function updateLoc (lat, long) {
    var url = "https://api.openweathermap.org/data/2.5/weather?" +
        "lat=" + lat +
        "&lon=" + long +
        "&APPID=" + APPID;
    sendRequest (url);
}

function sendRequest (url) {
    var xmlhttp = new XMLHttpRequest ();
    xmlhttp.onreadystatechange = function () {
        if (xmlhttp.readystate == 4 && xmlhttp.status == 200) {
            var data = JSON.parse (xmlhttp.responseText);

            var weather = {};
            weather.icon = data.weather.icon;
            weather.dir = data.wind.deg;
            weather.wind = data.wind.speed;
            weather.temp = data.main.temp;
            weather.loc = data.name;
            weather.hum = data.main.humidity;

            update (weather);
        }
    };
    xmlhttp.open ("GET", url, true);
    xmlhttp.send ();
}

Any help would be appreciated :)

Body:
I faced this same issue. I finally solved it by simply using the unsecured HTTP request, instead of the secured, HTTPS request. ie I changed the api url from https://api.openweathermap.org/... to http://api.openweathermap.org/...

Here is the supporting code:

NOT WORKING

function fetchWeatherInfo(){
     $.ajax({
            type: 'GET',
            url: 'https://api.openweathermap.org/data/2.5/forecast/daily?q=Bamenda&appid=****myid',
            success: function(response) {
                console.log(response);
            },
            error: function(xhr, status, error) {},
            cache: false
        });

}

WORKING

function fetchWeatherInfo(){
     $.ajax({
            type: 'GET',
            url: 'http://api.openweathermap.org/data/2.5/forecast/daily?q=Bamenda&appid=****myid',
            success: function(response) {
                console.log(response);
            },
            error: function(xhr, status, error) {},
            cache: false
        });

}


问:
Unicode for icon not working properly, it shows broken icon
In HTML, I'm showing printer icon using Unicode 🖶 , but it is not displaying correct. Also i have used <meta charset="utf-8" />

答:
Use ⎙ instead of 🖶

Refer https://unicode-table.com/en/

Body:
Use &#9113; instead of &#128438;

Refer https://unicode-table.com/en/


问:
Getting bus error while adding ascii values to array characters. Why? (C)
```<code>#include <stdio.h>

char    *ft_strupcase(char *str);

char    *ft_strupcase(char *str)
{
    int i;

    i = 0;
    while (str[i])
    {
        if (str[i] >= 'a' && str[i] <= 'z')
        {
             str[i] -= 32;
        }
        i++;
    }
    return (str);
}

int main(void)
{
    char *test = ft_strupcase("fdfFEhk");
    for (int k = 0; test[k] != '\0'; k++)
    {
        printf("%c", test[k]);
    }
    return (0);
}
</code>```

The expected result is to print the string passed to the function, all in capital letters. Instead, I get a bus error. Why and how can I fix this?

答:
In your ft_strupcase() function, you're trying to modify the content of a string literal. This causes undefined behavior.

To quote the standard, C11, chapter §6.4.5/P7, String literals

[...] If the program attempts to modify such an array, the behavior is
  undefined.

The argument you received is a string literal and you are not allowed to change the content. To avoid, you have to either

Pass a modifiable memory as the actual argument.

Inside the function, create a block (need to take care of the lifetime, either static storage or allocated via memory allocator functions), copy the content, perform the modify operations and return the address.

Body:
#include <stdio.h>

char    *ft_strupcase(char *str);

char    *ft_strupcase(char *str)
{
    int i;

    i = 0;
    while (str[i])
    {
        if (str[i] >= 'a' && str[i] <= 'z')
        {
             str[i] -= 32;
        }
        i++;
    }
    return (str);
}

int main(void)
{
    char *test = ft_strupcase("fdfFEhk");
    for (int k = 0; test[k] != '\0'; k++)
    {
        printf("%c", test[k]);
    }
    return (0);
}

The expected result is to print the string passed to the function, all in capital letters. Instead, I get a bus error. Why and how can I fix this?


问:
Simultaneous TCP Open
I am implementing "simultaneous TCP Open".That means both peer will try to connect each other at the same time. I confused whether listen is rquired or not in this case.

or tell me the sequence of socket need to be called for each client.

I am implementing this for TCp hole Punching.

thanks,

答:
From Wikipedia's article on TCP hole punching:

Because both parties are connection TO
  each other (e.g. 2 x CONNECT(), no
  LISTEN(), ACCEPT(), etc.) to generate
  OUTBOUND traffic there is however a
  problem with:

TCP Sequence numbers

Acknowledgment numbers

The required state is just like after
  the three-way-handshake: Each host
  must have an acknowledge number ==
  other sequence number + 1. This is
  achieved through Sequence and
  Acknowledgement Number coordination.

listen() is not needed.  The sequence depends on what is available.

Title: Simultaneous TCP Open


问:
Field seems to be missing in some responses in Active Collab 4 API
I am looking for fields in task called is_completed and completed_on.

When I do the /projects/#PROJECT-ID#/tasks API call I see is_completed but I do not see completed_on.

We are using the Cloud based version of Active Collab 4.

Any reason why I am not seeing completed_on?

答:
In Active Collab 4, there is a difference between "brief" API responses (used when returning large lists of objects), and detailed responses (used when a single object is returned via API).

When you are listing a list of tasks, you will get all individual tasks in brief format, but when you fetch details of each task, you'll get a detailed response.

In brief task responses, completed_on timestamp is not included, only whether tasks is completed or not (is_completed). To get the timestamp of completed tasks, make an additional call to task API for each task that is completed:

https://activecollab.com/help-classic/books/api/tasks#s-task-id

PS: In Active Collab 5, we removed brief and detailed concept, so each object always returns a single set of properties.


问:
java Run-length encoding
I have no idea how to start my assignment.

We got to make a Run-length encoding program,

for example, the users enters this string:

aaaaPPPrrrrr

is replaced with

4a3P5r

Can someone help me get started with it?

答:
```<code>import java.util.Scanner;
/**
 * @author jyotiv
 *
 */
 public class RunLengthEncoding {
 /**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter line to encode:");
    Scanner s=new Scanner(System.in);
    String input=s.nextLine();
            int len = input.length();
            int i = 0;
            int noOfOccurencesForEachChar = 0;
            char storeChar = input.charAt(0);

            String outputString = "";
            for(;i<len;i++)
            {
                if(i+1<len)
                {
                    if(input.charAt(i) == input.charAt(i+1))
                    {
                        noOfOccurencesForEachChar++;
                    }
                    else
                    {
                        outputString = outputString +
   Integer.toHexString(noOfOccurencesForEachChar+1) + storeChar;
                        noOfOccurencesForEachChar = 0;
                        storeChar = input.charAt(i+1);
                    }
                }
                else
                {
                    outputString = outputString +
 Integer.toHexString(noOfOccurencesForEachChar+1) + storeChar;
                }
            }

            System.out.println("Encoded line is: " + outputString);

        }

}
</code>```

I have tried this one. It will work for sure.

Title: java Run-length encoding

Body:
import java.util.Scanner;
/**
 * @author jyotiv
 *
 */
 public class RunLengthEncoding {
 /**
 * @param args
 */
public static void main(String[] args) {
    // TODO Auto-generated method stub
    System.out.println("Enter line to encode:");
    Scanner s=new Scanner(System.in);
    String input=s.nextLine();
            int len = input.length();
            int i = 0;
            int noOfOccurencesForEachChar = 0;
            char storeChar = input.charAt(0);

            String outputString = "";
            for(;i<len;i++)
            {
                if(i+1<len)
                {
                    if(input.charAt(i) == input.charAt(i+1))
                    {
                        noOfOccurencesForEachChar++;
                    }
                    else
                    {
                        outputString = outputString +
   Integer.toHexString(noOfOccurencesForEachChar+1) + storeChar;
                        noOfOccurencesForEachChar = 0;
                        storeChar = input.charAt(i+1);
                    }
                }
                else
                {
                    outputString = outputString +
 Integer.toHexString(noOfOccurencesForEachChar+1) + storeChar;
                }
            }

            System.out.println("Encoded line is: " + outputString);

        }

}

I have tried this one. It will work for sure.


问:
Location of public class method 'new' of 'Class'
Ruby's Class class lists two methods named 'new':

Class::new is a public class method

Class#new is a public instance method

But when I do:

```<code>Class.methods(false)
#=> []
</code>```

which is supposed to list singleton methods (which I am assuming what class methods are), I get an empty array. Why is this so? Where is Class::new defined?

答:
The methods shown as ::new in the documentation are usually #initialize, for example Range::new:

new(begin, end, exclude_end=false) → rng

Constructs a range using the given begin and end. If the exclude_end parameter is omitted or is false, the rng will include the end object; otherwise, it will be excluded.

This is because you create instances via:

```<code>r = Range.new(0, 2)       #=> 0..2
</code>```

Rather than:

```<code>r = Range.allocate        #=> nil..nil
r.send(:initialize, 0, 2) #=> nil
r                         #=> 0..2
</code>```

That's exactly what ::new does – it creates a new instance via allocate, sends it initialize (passing arguments) and returns the instance.

The actual new method is inherited from Class (since Range is an instance of Class) – Class#new:

new(args, ...) → obj

Calls allocate to create a new object of class’s class, then invokes that object’s initialize method, passing it args. This is the method that ends up getting called whenever an object is constructed using .new.

Just like allocate, inherited and superclass (and the instance methods from Class' ancestors like Module as well):

```<code>Range.method(:new)
#=> #<Method: Class#new>

Range.method(:allocate)
#=> #<Method: Class#allocate>

Range.method(:ancestors)
#=> #<Method: Class(Module)#ancestors>
</code>```

So if you call Class.new:

```<code>my_string_class = Class.new(String)
#=> #<Class:0x007fdf5485b200>
</code>```

you just invoke Class#new which is (again) equivalent to:

```<code>my_string_class = Class.allocate
my_string_class.send(:initialize, String)
my_string_class
#=> #<Class:0x007fdf5484beb8>
</code>```

One notable exception is Struct which in fact provide its own new class method:

```<code>Struct.method(:new)
#=> #<Method: Struct.new>
</code>```

Unlike other classes, Struct::new does not return instances of Struct but instances of Class (which are subclasses of Struct).

Body:
Ruby's Class class lists two methods named 'new':

Class::new is a public class method

Class#new is a public instance method

But when I do:

Class.methods(false)
#=> []

which is supposed to list singleton methods (which I am assuming what class methods are), I get an empty array. Why is this so? Where is Class::new defined?

Body:
The methods shown as ::new in the documentation are usually #initialize, for example Range::new:

new(begin, end, exclude_end=false) → rng

Constructs a range using the given begin and end. If the exclude_end parameter is omitted or is false, the rng will include the end object; otherwise, it will be excluded.

This is because you create instances via:

r = Range.new(0, 2)       #=> 0..2

Rather than:

r = Range.allocate        #=> nil..nil
r.send(:initialize, 0, 2) #=> nil
r                         #=> 0..2

That's exactly what ::new does – it creates a new instance via allocate, sends it initialize (passing arguments) and returns the instance.

The actual new method is inherited from Class (since Range is an instance of Class) – Class#new:

new(args, ...) → obj

Calls allocate to create a new object of class’s class, then invokes that object’s initialize method, passing it args. This is the method that ends up getting called whenever an object is constructed using .new.

Just like allocate, inherited and superclass (and the instance methods from Class' ancestors like Module as well):

Range.method(:new)
#=> #<Method: Class#new>

Range.method(:allocate)
#=> #<Method: Class#allocate>

Range.method(:ancestors)
#=> #<Method: Class(Module)#ancestors>

So if you call Class.new:

my_string_class = Class.new(String)
#=> #<Class:0x007fdf5485b200>

you just invoke Class#new which is (again) equivalent to:

my_string_class = Class.allocate
my_string_class.send(:initialize, String)
my_string_class
#=> #<Class:0x007fdf5484beb8>

One notable exception is Struct which in fact provide its own new class method:

Struct.method(:new)
#=> #<Method: Struct.new>

Unlike other classes, Struct::new does not return instances of Struct but instances of Class (which are subclasses of Struct).


问:
How to make Android phone's back button work using Ajax in Javascript?
I have the following code to handle the back button of devices from Framework 7 in Javascript. I'd like to know if all subsequent pages are using Ajax, how do I use the back button to move back to my earlier page. At the moment, pressing the Back button, always prompts for the user if he wants to exit the app. The app has 20 pages, but they are all shown as Ajax pages and not a HTML page.

```<code><!-- We don't need full layout here, because this page will be parsed with Ajax-->
</code>```

Please help.  Thanks for the help!

```<code>        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }
        // device APIs are available
        function onDeviceReady() {
            // Register the event listener
            document.addEventListener("backbutton", onBackKeyDown, false);
            document.addEventListener("menubutton", onMenuKeyDown, false);
        }
        // Handle the back button
        function onBackKeyDown(e) {
            e.preventDefault();
            navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
            //navigator.app.backHistory();

            if (document.getElementById('#homepage')) {
                e.preventDefault();
                navigator.app.exitApp();
                navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
            } else {
                navigator.app.backHistory();//This line doesn't work when tried on the if function - it seems useless - maybe not supported anymore?
                //the code never gets here coz other pages are simply loaded as Ajax, and there is only 1 index.html - how to fix?
            }
        }

        function onConfirm(button) {
            if (button == 2) { //If the user selected No, then we just do nothing
                return;
            } else {
                navigator.app.exitApp(); // Otherwise we quit the app.
            }
        }
        // Handle the menu button
        function onMenuKeyDown() {}
</code>```

答:
I think the problem here is the page is in the DOM, but is not being shown.

if (document.getElementById('#homepage')) {

You could check if this HTML Element has a class or a specific style when you're on another page.

If you're using ajax, I suppose this HTML Element will have a hidden class or a display: none style, so I hope one of these will work for you:

document.querySelectorAll('#content[style="display: none;"]')
document.querySelectorAll('#content.hidden')

Body:
I have the following code to handle the back button of devices from Framework 7 in Javascript. I'd like to know if all subsequent pages are using Ajax, how do I use the back button to move back to my earlier page. At the moment, pressing the Back button, always prompts for the user if he wants to exit the app. The app has 20 pages, but they are all shown as Ajax pages and not a HTML page.

Please help.  Thanks for the help!

        function onLoad() {
            document.addEventListener("deviceready", onDeviceReady, false);
        }
        // device APIs are available
        function onDeviceReady() {
            // Register the event listener
            document.addEventListener("backbutton", onBackKeyDown, false);
            document.addEventListener("menubutton", onMenuKeyDown, false);
        }
        // Handle the back button
        function onBackKeyDown(e) {
            e.preventDefault();
            navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
            //navigator.app.backHistory();

            if (document.getElementById('#homepage')) {
                e.preventDefault();
                navigator.app.exitApp();
                navigator.notification.confirm("Are you sure you want to exit?", onConfirm, "Confirmation", "Yes,No");
            } else {
                navigator.app.backHistory();//This line doesn't work when tried on the if function - it seems useless - maybe not supported anymore?
                //the code never gets here coz other pages are simply loaded as Ajax, and there is only 1 index.html - how to fix?
            }
        }

        function onConfirm(button) {
            if (button == 2) { //If the user selected No, then we just do nothing
                return;
            } else {
                navigator.app.exitApp(); // Otherwise we quit the app.
            }
        }
        // Handle the menu button
        function onMenuKeyDown() {}


问:
ListView displaying image on rows that shouldn't have one
I have a listView that is implemented with a custom adapter I created, which includes an imageView. Throughout the list each item may or may not have an image attached(It's not necessary).
To load the image into the imageView I use Picasso library, in the getView method.

When it comes to rows that do have an image associated, my code works fine.
The problem is when the list is being displayed, rows that should not have an image are displaying one.

Here is my getView() method:

```<code>public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    ReportHolder holder = null;

    if(convertView==null){
        LayoutInflater inflater=((Activity)context).getLayoutInflater();
        convertView = inflater.inflate(layoutResourceId,null);
        holder = new ReportHolder();
        holder.imageReportView=(ImageView)convertView.findViewById(R.id.reportImage);
        holder.reportLocation=(TextView) convertView.findViewById(R.id.report_location);
        holder.reportDescription=(TextView) convertView.findViewById(R.id.report_description);
        holder.reportStatus=(TextView) convertView.findViewById(R.id.report_status);
        convertView.setTag(holder);
    }
    else
        holder=(ReportHolder)convertView.getTag();

    ReportData data = reportDataList.get(position);
    holder.reportLocation.setText(data.address);
    holder.reportDescription.setText(data.description);
    holder.reportStatus.setText(data.status);
    Picasso picasso = Picasso.with(this.context);
    if(data.url!=null)
        picasso.load("https://fourth-landing-159416.appspot.com/gcs/"+data.url+"_thumbnail").into(holder.imageReportView);
    return convertView;
}
</code>```

I know I'm fetching my information well because no information between rows repeats itself except the pictures. So what am I missing here?

FMI My adapter is created in a nested ASyncTask, because I´m required to fetch the information through an HTTP connection before I can insert it in the adapter:

```<code>@Override
    protected void onPostExecute(final String result) {
        mFeedTask = null;
        mFeed.removeFooterView(mProgressView);
        if(result!=null){
            if(result.contains("HTTP error code: 403")){
                Toast.makeText(mContext,"Token invalid. Please login again.", Toast.LENGTH_SHORT).show();
            }
            else if(result.equals("[]"))
                Toast.makeText(mContext,"Nothing more to show.", Toast.LENGTH_SHORT).show();
            else{
                try {
                    Gson gson = new Gson();
                    JSONArray reports = new JSONArray(result);
                    LinkedList<ReportData> tmpList = new LinkedList<ReportData>();
                    for(int i=0; i < reports.length(); i++){
                        ReportData data = gson.fromJson(reports.getString(i), ReportData.class);
                        tmpList.add(data);
                    }
                    reportDataList.addAll(tmpList);
                    if(reportDataList.size()==tmpList.size()){
                    // First, we set the empty adapter and set up the item click listeners
                    adapter = new CustomAdapter(mContext,R.layout.custom_feed_row,reportDataList);
                    mFeed.setAdapter(adapter);
                    }
                    else {
                        updateTriggered=false;
                        adapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }
</code>```

And as I have a relatively large amount of information to transfer I have to call this task multiple times. On the first time called the adapter is created and from then on notifyDataSetChanged is called to update it.

Much Help Appreciated!

I thank you in advance!
Cheers

答:
Because listview recycling same views, so you should remove the image if this row shouldn't contain image

Do something like this in your getView:

```<code>if(data.url!=null)
        picasso.load("https://fourth-landing-159416.appspot.com/gcs/"+data.url+"_thumbnail").into(holder.imageReportView);
    else {
holder.imageReportView.setImageDrawable(null);;
    }
</code>```

Body:
I have a listView that is implemented with a custom adapter I created, which includes an imageView. Throughout the list each item may or may not have an image attached(It's not necessary).
To load the image into the imageView I use Picasso library, in the getView method.

When it comes to rows that do have an image associated, my code works fine.
The problem is when the list is being displayed, rows that should not have an image are displaying one.

Here is my getView() method:

public View getView(int position, @Nullable View convertView, @NonNull ViewGroup parent) {
    ReportHolder holder = null;

    if(convertView==null){
        LayoutInflater inflater=((Activity)context).getLayoutInflater();
        convertView = inflater.inflate(layoutResourceId,null);
        holder = new ReportHolder();
        holder.imageReportView=(ImageView)convertView.findViewById(R.id.reportImage);
        holder.reportLocation=(TextView) convertView.findViewById(R.id.report_location);
        holder.reportDescription=(TextView) convertView.findViewById(R.id.report_description);
        holder.reportStatus=(TextView) convertView.findViewById(R.id.report_status);
        convertView.setTag(holder);
    }
    else
        holder=(ReportHolder)convertView.getTag();

    ReportData data = reportDataList.get(position);
    holder.reportLocation.setText(data.address);
    holder.reportDescription.setText(data.description);
    holder.reportStatus.setText(data.status);
    Picasso picasso = Picasso.with(this.context);
    if(data.url!=null)
        picasso.load("https://fourth-landing-159416.appspot.com/gcs/"+data.url+"_thumbnail").into(holder.imageReportView);
    return convertView;
}

I know I'm fetching my information well because no information between rows repeats itself except the pictures. So what am I missing here?

FMI My adapter is created in a nested ASyncTask, because I´m required to fetch the information through an HTTP connection before I can insert it in the adapter:

@Override
    protected void onPostExecute(final String result) {
        mFeedTask = null;
        mFeed.removeFooterView(mProgressView);
        if(result!=null){
            if(result.contains("HTTP error code: 403")){
                Toast.makeText(mContext,"Token invalid. Please login again.", Toast.LENGTH_SHORT).show();
            }
            else if(result.equals("[]"))
                Toast.makeText(mContext,"Nothing more to show.", Toast.LENGTH_SHORT).show();
            else{
                try {
                    Gson gson = new Gson();
                    JSONArray reports = new JSONArray(result);
                    LinkedList<ReportData> tmpList = new LinkedList<ReportData>();
                    for(int i=0; i < reports.length(); i++){
                        ReportData data = gson.fromJson(reports.getString(i), ReportData.class);
                        tmpList.add(data);
                    }
                    reportDataList.addAll(tmpList);
                    if(reportDataList.size()==tmpList.size()){
                    // First, we set the empty adapter and set up the item click listeners
                    adapter = new CustomAdapter(mContext,R.layout.custom_feed_row,reportDataList);
                    mFeed.setAdapter(adapter);
                    }
                    else {
                        updateTriggered=false;
                        adapter.notifyDataSetChanged();
                    }
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }
        }
    }

And as I have a relatively large amount of information to transfer I have to call this task multiple times. On the first time called the adapter is created and from then on notifyDataSetChanged is called to update it.

Much Help Appreciated!

I thank you in advance!
Cheers

Body:
Because listview recycling same views, so you should remove the image if this row shouldn't contain image

Do something like this in your getView:

if(data.url!=null)
        picasso.load("https://fourth-landing-159416.appspot.com/gcs/"+data.url+"_thumbnail").into(holder.imageReportView);
    else {
holder.imageReportView.setImageDrawable(null);;
    }


问:
How to use horizontal and vertical scrolling together
Here I have a code

```<code><ul id="card-container">
    <li>
        <div class="card-wrap">
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </div>
</li>
<li>
    <div class="card-wrap">
    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
    </div>
</li>
</code>```

I want the #card-container to be horizontally scrolled on mousewheel but if I hover on the .card-wrap and scroll with mousewheel the .card-wrap should scroll vertically.

Right now from my code both of the scrolls are taking place together.

```<code> $('#card-container').mousewheel(function(e, delta) {
    this.scrollLeft -= (delta * 40);
    e.preventDefault();
});
$('.card-wrap').mousewheel(function(e, delta) {
    this.scrollTop -= (delta * 40);
    e.preventDefault();
});
</code>```

Need some assistance.

答:
One of my friend helped me out with this thus sharing it to you all.
Here is the jQuery code:

```<code>$('#card-container').mousewheel(function(e, delta) {
     this.scrollLeft -= (delta * 40);
     e.preventDefault();
 });
$('.card-wrap').mouseenter(function(){
    $('#card-container').unmousewheel();
});
$('.card-wrap').mouseleave(function(){
    $('#card-container').mousewheel(function(e, delta) {
        this.scrollLeft -= (delta * 40);
        e.preventDefault();
    });
});
</code>```

Thanks.

Body:
Here I have a code

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

    "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."

I want the #card-container to be horizontally scrolled on mousewheel but if I hover on the .card-wrap and scroll with mousewheel the .card-wrap should scroll vertically.

Right now from my code both of the scrolls are taking place together.

 $('#card-container').mousewheel(function(e, delta) {
    this.scrollLeft -= (delta * 40);
    e.preventDefault();
});
$('.card-wrap').mousewheel(function(e, delta) {
    this.scrollTop -= (delta * 40);
    e.preventDefault();
});

Need some assistance.

Body:
One of my friend helped me out with this thus sharing it to you all.
Here is the jQuery code:

$('#card-container').mousewheel(function(e, delta) {
     this.scrollLeft -= (delta * 40);
     e.preventDefault();
 });
$('.card-wrap').mouseenter(function(){
    $('#card-container').unmousewheel();
});
$('.card-wrap').mouseleave(function(){
    $('#card-container').mousewheel(function(e, delta) {
        this.scrollLeft -= (delta * 40);
        e.preventDefault();
    });
});

Thanks.


问:
How can I make the background color of a node in a TreeView goes all the way out to the right edge?
How can I make the background color of a node in a TreeView goes all the way out to the right edge?

Background

I have a TreeView where all nodes that have children are gray. Leaf nodes have an icon with descriptive text.

答:
It's an easy fix. Unfortunately it'll require pretty much code since you'll have to re-template the TreeViewItem. The TreeViewItem's template looks like this

```<code><ControlTemplate TargetType="{x:Type TreeViewItem}">
    <Grid>
        <Grid.ColumnDefinitions>
            <!-- The Expand/Collapse ToggleButton -->
            <ColumnDefinition MinWidth="19" Width="Auto"/>
            <!-- The TreeViewItem -->
            <ColumnDefinition Width="Auto"/>
            <!-- The Children -->
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ExpandCollapseToggleStyle}"/>
        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.Column="1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
            <ContentPresenter x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        </Border>
        <ItemsPresenter x:Name="ItemsHost" Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1"/>
    </Grid>
</code>```

As you can see, the TreeViewItem itself is in Column 1 which has Width set to Auto while the children (ItemsPresenter) is in Grid.Column 1 and 2 and the Column 2 has Width set to *. To get the TreeViewItem itself to get the same Width as its children we can remove the middle Column (Column 1) and just use Grid.Column="1" for both.

Here's the default Template for TreeViewItem with this "Horizontal Stretch" fix. You'll have to add a reference to PresentationFramework.Aero

```<code><Style x:Key="TreeViewItemFocusVisual">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <Rectangle/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<PathGeometry x:Key="TreeArrow" Figures="M0,0 L0,6 L6,0 z"/>
<Style x:Key="ExpandCollapseToggleStyle" TargetType="{x:Type ToggleButton}">
    <Setter Property="Focusable" Value="False"/>
    <Setter Property="Width" Value="16"/>
    <Setter Property="Height" Value="16"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ToggleButton}">
                <Border Background="Transparent" Height="16" Padding="5,5,5,5" Width="16">
                    <Path x:Name="ExpandPath" Data="{StaticResource TreeArrow}" Fill="Transparent" Stroke="#FF989898">
                        <Path.RenderTransform>
                            <RotateTransform Angle="135" CenterY="3" CenterX="3"/>
                        </Path.RenderTransform>
                    </Path>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Stroke" TargetName="ExpandPath" Value="#FF1BBBFA"/>
                        <Setter Property="Fill" TargetName="ExpandPath" Value="Transparent"/>
                    </Trigger>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="RenderTransform" TargetName="ExpandPath">
                            <Setter.Value>
                                <RotateTransform Angle="180" CenterY="3" CenterX="3"/>
                            </Setter.Value>
                        </Setter>
                        <Setter Property="Fill" TargetName="ExpandPath" Value="#FF595959"/>
                        <Setter Property="Stroke" TargetName="ExpandPath" Value="#FF262626"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style x:Key="StretchTreeViewItemStyle"
       TargetType="{x:Type TreeViewItem}"
       xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="Padding" Value="1,0,0,0"/>
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="FocusVisualStyle" Value="{StaticResource TreeViewItemFocusVisual}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TreeViewItem}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition MinWidth="19" Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ExpandCollapseToggleStyle}"/>
                    <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.Column="1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                        <ContentPresenter x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </Border>
                    <ItemsPresenter x:Name="ItemsHost" Grid.Column="1" Grid.Row="1"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsExpanded" Value="false">
                        <Setter Property="Visibility" TargetName="ItemsHost" Value="Collapsed"/>
                    </Trigger>
                    <Trigger Property="HasItems" Value="false">
                        <Setter Property="Visibility" TargetName="Expander" Value="Hidden"/>
                    </Trigger>
                    <Trigger Property="IsSelected" Value="true">
                        <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsSelected" Value="true"/>
                            <Condition Property="IsSelectionActive" Value="false"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
                    </MultiTrigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="VirtualizingStackPanel.IsVirtualizing" Value="true">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel/>
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>
</code>```

And then you can use it like this

```<code><TreeView ...>
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource StretchTreeViewItemStyle}">
            <!-- Add your own setters if applicable -->
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>
</code>```

Body:
It's an easy fix. Unfortunately it'll require pretty much code since you'll have to re-template the TreeViewItem. The TreeViewItem's template looks like this

<ControlTemplate TargetType="{x:Type TreeViewItem}">
    <Grid>
        <Grid.ColumnDefinitions>
            <!-- The Expand/Collapse ToggleButton -->
            <ColumnDefinition MinWidth="19" Width="Auto"/>
            <!-- The TreeViewItem -->
            <ColumnDefinition Width="Auto"/>
            <!-- The Children -->
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition/>
        </Grid.RowDefinitions>
        <ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ExpandCollapseToggleStyle}"/>
        <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.Column="1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
            <ContentPresenter x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
        </Border>
        <ItemsPresenter x:Name="ItemsHost" Grid.ColumnSpan="2" Grid.Column="1" Grid.Row="1"/>
    </Grid>

As you can see, the TreeViewItem itself is in Column 1 which has Width set to Auto while the children (ItemsPresenter) is in Grid.Column 1 and 2 and the Column 2 has Width set to *. To get the TreeViewItem itself to get the same Width as its children we can remove the middle Column (Column 1) and just use Grid.Column="1" for both.

Here's the default Template for TreeViewItem with this "Horizontal Stretch" fix. You'll have to add a reference to PresentationFramework.Aero

<Style x:Key="TreeViewItemFocusVisual">
    <Setter Property="Control.Template">
        <Setter.Value>
            <ControlTemplate>
                <Rectangle/>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<PathGeometry x:Key="TreeArrow" Figures="M0,0 L0,6 L6,0 z"/>
<Style x:Key="ExpandCollapseToggleStyle" TargetType="{x:Type ToggleButton}">
    <Setter Property="Focusable" Value="False"/>
    <Setter Property="Width" Value="16"/>
    <Setter Property="Height" Value="16"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type ToggleButton}">
                <Border Background="Transparent" Height="16" Padding="5,5,5,5" Width="16">
                    <Path x:Name="ExpandPath" Data="{StaticResource TreeArrow}" Fill="Transparent" Stroke="#FF989898">
                        <Path.RenderTransform>
                            <RotateTransform Angle="135" CenterY="3" CenterX="3"/>
                        </Path.RenderTransform>
                    </Path>
                </Border>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsMouseOver" Value="True">
                        <Setter Property="Stroke" TargetName="ExpandPath" Value="#FF1BBBFA"/>
                        <Setter Property="Fill" TargetName="ExpandPath" Value="Transparent"/>
                    </Trigger>
                    <Trigger Property="IsChecked" Value="True">
                        <Setter Property="RenderTransform" TargetName="ExpandPath">
                            <Setter.Value>
                                <RotateTransform Angle="180" CenterY="3" CenterX="3"/>
                            </Setter.Value>
                        </Setter>
                        <Setter Property="Fill" TargetName="ExpandPath" Value="#FF595959"/>
                        <Setter Property="Stroke" TargetName="ExpandPath" Value="#FF262626"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
</Style>
<Style x:Key="StretchTreeViewItemStyle"
       TargetType="{x:Type TreeViewItem}"
       xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero">
    <Setter Property="Background" Value="Transparent"/>
    <Setter Property="HorizontalContentAlignment" Value="{Binding HorizontalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="VerticalContentAlignment" Value="{Binding VerticalContentAlignment, RelativeSource={RelativeSource AncestorType={x:Type ItemsControl}}}"/>
    <Setter Property="Padding" Value="1,0,0,0"/>
    <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
    <Setter Property="FocusVisualStyle" Value="{StaticResource TreeViewItemFocusVisual}"/>
    <Setter Property="Template">
        <Setter.Value>
            <ControlTemplate TargetType="{x:Type TreeViewItem}">
                <Grid>
                    <Grid.ColumnDefinitions>
                        <ColumnDefinition MinWidth="19" Width="Auto"/>
                        <ColumnDefinition Width="*"/>
                    </Grid.ColumnDefinitions>
                    <Grid.RowDefinitions>
                        <RowDefinition Height="Auto"/>
                        <RowDefinition/>
                    </Grid.RowDefinitions>
                    <ToggleButton x:Name="Expander" ClickMode="Press" IsChecked="{Binding IsExpanded, RelativeSource={RelativeSource TemplatedParent}}" Style="{StaticResource ExpandCollapseToggleStyle}"/>
                    <Border x:Name="Bd" BorderBrush="{TemplateBinding BorderBrush}" BorderThickness="{TemplateBinding BorderThickness}" Background="{TemplateBinding Background}" Grid.Column="1" Padding="{TemplateBinding Padding}" SnapsToDevicePixels="true">
                        <ContentPresenter x:Name="PART_Header" ContentSource="Header" HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}"/>
                    </Border>
                    <ItemsPresenter x:Name="ItemsHost" Grid.Column="1" Grid.Row="1"/>
                </Grid>
                <ControlTemplate.Triggers>
                    <Trigger Property="IsExpanded" Value="false">
                        <Setter Property="Visibility" TargetName="ItemsHost" Value="Collapsed"/>
                    </Trigger>
                    <Trigger Property="HasItems" Value="false">
                        <Setter Property="Visibility" TargetName="Expander" Value="Hidden"/>
                    </Trigger>
                    <Trigger Property="IsSelected" Value="true">
                        <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.HighlightBrushKey}}"/>
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.HighlightTextBrushKey}}"/>
                    </Trigger>
                    <MultiTrigger>
                        <MultiTrigger.Conditions>
                            <Condition Property="IsSelected" Value="true"/>
                            <Condition Property="IsSelectionActive" Value="false"/>
                        </MultiTrigger.Conditions>
                        <Setter Property="Background" TargetName="Bd" Value="{DynamicResource {x:Static SystemColors.ControlBrushKey}}"/>
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
                    </MultiTrigger>
                    <Trigger Property="IsEnabled" Value="false">
                        <Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.GrayTextBrushKey}}"/>
                    </Trigger>
                </ControlTemplate.Triggers>
            </ControlTemplate>
        </Setter.Value>
    </Setter>
    <Style.Triggers>
        <Trigger Property="VirtualizingStackPanel.IsVirtualizing" Value="true">
            <Setter Property="ItemsPanel">
                <Setter.Value>
                    <ItemsPanelTemplate>
                        <VirtualizingStackPanel/>
                    </ItemsPanelTemplate>
                </Setter.Value>
            </Setter>
        </Trigger>
    </Style.Triggers>
</Style>

And then you can use it like this

<TreeView ...>
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}" BasedOn="{StaticResource StretchTreeViewItemStyle}">
            <!-- Add your own setters if applicable -->
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>


问:
Firefox source code analysis; lines of code per component
I am currently trying to analyse Bugzilla in order to find the ratio of number of bugs : lines of code for each Firefox component. However, I have never worked with Bugzilla before and have no knowledge of Firefox's codebase.

How would I go about finding lines of code per Firefox component (as they appear on Bugzilla under Comp header)? I have made an attempt at looking through mozilla central, but have no idea which source files relate to which components.

EDIT: Dexter pointed out that there is a directive BUG_COMPONENT in the mozilla-central tree, but this directive seems extremely incomplete and is not helpful. Any other advice, or pointers as to where I could get such advice would be much appreciated.

答:
Great question! We recently added the BUG_COMPONENT directive (see the meta bug) to the Firefox code: it's in the moz.build file contained in each directory in the source. This directive allows linking each file in the repository to the related Bugzilla component.

For example, the following directive found here, tells that all the files in test/browser containing the Telemetry word belong to the Toolkit::Telemetry component on Bugzilla.

```<code>with Files("test/browser/*Telemetry*"):
    BUG_COMPONENT = ("Toolkit", "Telemetry")
</code>```

You can use either DXR or searchfox to quickly search the Firefox repository.

Updated the answer to account for the questions in the comments.

As noted in the comments, some components are tracked on Bugzilla (e.g. Activity Stream) but do not have a direct mapping to source files within the mozilla-central repository (the one Firefox is built from). That's because some newer components do not ride "the trains" (~6 weeks development cycle), but are rather updated more frequently and deployed as addons.

The code for these components usually lives under the Mozilla github account, along with other project. Since there are quite a number of projects, one way to identify the ones you might be interested in is to restrict them to JavaScript ones. If you follow this last link, you'll see the repository for both the test-pilot and Activity Stream (plus other addons).

I'm afraid the only way to match GitHub projects to Bugzilla components is to look at the name of the repository on GitHub and find the matching component in Bugzilla: you can type the name here to get some component suggestions. If you want to get fancy, you might also leverage the Bugzilla REST API:

Get a list of the JS GitHub project.

Extract the name of the project.

Use the REST API to get the component suggestion.

I would personally just consider the mozilla-central repository as a starting point, as it is mostly annotated: scrape the BUG_COMPONENT from the source files, map them to the paths then use the REST API to get the list of bugs.

Sidenote: the Download Panel seems to be correctly annotated in the main repo.

Body:
Great question! We recently added the BUG_COMPONENT directive (see the meta bug) to the Firefox code: it's in the moz.build file contained in each directory in the source. This directive allows linking each file in the repository to the related Bugzilla component.

For example, the following directive found here, tells that all the files in test/browser containing the Telemetry word belong to the Toolkit::Telemetry component on Bugzilla.

with Files("test/browser/*Telemetry*"):
    BUG_COMPONENT = ("Toolkit", "Telemetry")

You can use either DXR or searchfox to quickly search the Firefox repository.

Updated the answer to account for the questions in the comments.

As noted in the comments, some components are tracked on Bugzilla (e.g. Activity Stream) but do not have a direct mapping to source files within the mozilla-central repository (the one Firefox is built from). That's because some newer components do not ride "the trains" (~6 weeks development cycle), but are rather updated more frequently and deployed as addons.

The code for these components usually lives under the Mozilla github account, along with other project. Since there are quite a number of projects, one way to identify the ones you might be interested in is to restrict them to JavaScript ones. If you follow this last link, you'll see the repository for both the test-pilot and Activity Stream (plus other addons).

I'm afraid the only way to match GitHub projects to Bugzilla components is to look at the name of the repository on GitHub and find the matching component in Bugzilla: you can type the name here to get some component suggestions. If you want to get fancy, you might also leverage the Bugzilla REST API:

Get a list of the JS GitHub project.

Extract the name of the project.

Use the REST API to get the component suggestion.

I would personally just consider the mozilla-central repository as a starting point, as it is mostly annotated: scrape the BUG_COMPONENT from the source files, map them to the paths then use the REST API to get the list of bugs.

Sidenote: the Download Panel seems to be correctly annotated in the main repo.


问:
Scala different outputs of logically same programs
```<code>val a = List(1, 2, 3, 4, 5)
val b = a.grouped(2).filter(_.length == 2).map(x => (x(0), x(1)))

//b.foreach(x => println(x))

val r = b.foldLeft((0, 0)) {
    case ((m, n), (x, y)) => {
        (m + x, n + y)
    }
}

println(r)
</code>```

The program gives correct output (4, 6) for the above program. But when I uncomment the foreach statement above it outputs (0, 0). What's wrong here?

答:
val b = a.grouped(2).filter(_.length == 2).map(x => (x(0), x(1))), b's type is Iterator:

```<code>scala> :type b
Iterator[(Int, Int)]
</code>```

so when you have iterated b by b.foreach(x => println(x)), after this the current iterator b is empty, Since Iterator only can be iterated once.

Body:
val a = List(1, 2, 3, 4, 5)
val b = a.grouped(2).filter(_.length == 2).map(x => (x(0), x(1)))

//b.foreach(x => println(x))

val r = b.foldLeft((0, 0)) {
    case ((m, n), (x, y)) => {
        (m + x, n + y)
    }
}

println(r)

The program gives correct output (4, 6) for the above program. But when I uncomment the foreach statement above it outputs (0, 0). What's wrong here?

Body:
val b = a.grouped(2).filter(_.length == 2).map(x => (x(0), x(1))), b's type is Iterator:

scala> :type b
Iterator[(Int, Int)]

so when you have iterated b by b.foreach(x => println(x)), after this the current iterator b is empty, Since Iterator only can be iterated once.


问:
Drupal 7 Search Module Increase snippet result
I want to increase my snippet result. When I'm going to print . It display few data from the content along with "..." 3 dots. Please help me to increase the snippet result.

Thanks

答:
I found an answer. In your search-result.tpl.php file.
Try to find the value of your body from result array and mentioned in under node_load function. For ex:- node_load($result['node']->entity_id)->body['und'][0]['value'];

This will fetch all the results. :)


问:
symfony composer update "don't install symfony/symfony"
I’m getting a flood of messages when I run ‘composer.phar update’
on my Centos 6.4 / PHP 5.5.36 server
starting with:

```<code>Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of
packages.

  Problem 1
- Conclusion: don't install symfony/symfony v3.0.9
- Conclusion: don't install symfony/symfony v3.0.8
- Conclusion: don't install symfony/symfony v3.0.7
- Conclusion: don't install symfony/symfony v3.0.6
- Conclusion: don't install symfony/symfony v3.0.5
- Conclusion: don't install symfony/symfony v3.0.4
- Conclusion: don't install symfony/symfony v3.0.3
- Conclusion: don't install symfony/symfony v3.0.2
- Conclusion: don't install symfony/symfony v3.0.1
- phpunit/phpunit 4.0.0 requires symfony/yaml ~2.0 -> satisfiable by symfony/yaml[2.0.4, 2.0.5, 2.0.6, 2.0.7, v2.0.10, v2.0.12, v2.0.13, v2.0.14, v2.0.15, v2.0.16, v2.0.17, v2.0.18, v2.0.19, v2.0.20, v2.0.21, v2.0.22, v2.0.23, v2.0.24, v2.0.25, v2.0.9, v2.1.0, v2.1.1, v2.1.10, v2.1.11, v2.1.12, v2.1.13, v2.1.2, v2.1.3, v2.1.4, v2.1.5, v2.1.6, v2.1.7, v2.1.8, v2.1.9, v2.2.0, v2.2.1, v2.2.10, v2.2.11, v2.2.2, v2.2.3, v2.2.4, v2.2.5, v2.2.6, v2.2.7, v2.2.8, v2.2.9, v2.
</code>```

http://pastebin.centos.org/119091/

composer.json is:
http://pastebin.centos.org/119096/

答:
Here's a hint:

```<code>- phpunit/phpunit 4.0.0 requires symfony/yaml ~2.0
</code>```

You're using Symfony in version 3.0.*, which requires symfony/yaml package in the same version.

In the same time you're using PHPUnit in version 4.0.* which requires symfony/yaml, but in version  ~2.0 (which means >=2.0.0 and <3.0.0).

So you have a conflict here.

I would suggest to update PHPUnit package to 4.8 version, which requires symfony/yaml in version ~2.1|~3.0, which is compatible with Symfony 3.

Body:
I’m getting a flood of messages when I run ‘composer.phar update’
on my Centos 6.4 / PHP 5.5.36 server
starting with:

Loading composer repositories with package information
Updating dependencies (including require-dev)
Your requirements could not be resolved to an installable set of
packages.

  Problem 1
- Conclusion: don't install symfony/symfony v3.0.9
- Conclusion: don't install symfony/symfony v3.0.8
- Conclusion: don't install symfony/symfony v3.0.7
- Conclusion: don't install symfony/symfony v3.0.6
- Conclusion: don't install symfony/symfony v3.0.5
- Conclusion: don't install symfony/symfony v3.0.4
- Conclusion: don't install symfony/symfony v3.0.3
- Conclusion: don't install symfony/symfony v3.0.2
- Conclusion: don't install symfony/symfony v3.0.1
- phpunit/phpunit 4.0.0 requires symfony/yaml ~2.0 -> satisfiable by symfony/yaml[2.0.4, 2.0.5, 2.0.6, 2.0.7, v2.0.10, v2.0.12, v2.0.13, v2.0.14, v2.0.15, v2.0.16, v2.0.17, v2.0.18, v2.0.19, v2.0.20, v2.0.21, v2.0.22, v2.0.23, v2.0.24, v2.0.25, v2.0.9, v2.1.0, v2.1.1, v2.1.10, v2.1.11, v2.1.12, v2.1.13, v2.1.2, v2.1.3, v2.1.4, v2.1.5, v2.1.6, v2.1.7, v2.1.8, v2.1.9, v2.2.0, v2.2.1, v2.2.10, v2.2.11, v2.2.2, v2.2.3, v2.2.4, v2.2.5, v2.2.6, v2.2.7, v2.2.8, v2.2.9, v2.

http://pastebin.centos.org/119091/

composer.json is:
http://pastebin.centos.org/119096/

Body:
Here's a hint:

- phpunit/phpunit 4.0.0 requires symfony/yaml ~2.0

You're using Symfony in version 3.0.*, which requires symfony/yaml package in the same version.

In the same time you're using PHPUnit in version 4.0.* which requires symfony/yaml, but in version  ~2.0 (which means >=2.0.0 and <3.0.0).

So you have a conflict here.

I would suggest to update PHPUnit package to 4.8 version, which requires symfony/yaml in version ~2.1|~3.0, which is compatible with Symfony 3.


问:
Interop issue in .NET
I have a 32 bit managed assembly that access a 32 bit COM component. When i compile the assembly using the 64 bit flag, i get an error when i try to access the 32 bit COM component from it.

Is there a way around this problem?

答:
In addition to the already given answers:

In Windows x64 a process may be started as 32-bit or 64-bit process. A 64-bit process can only load 64-bit dlls and a 32bit process only 32-bit dlls.

If your platform target (e.g. specified in the project properties) of your .Net application is set to "Any CPU", the intermediate code will be compiled to 32bit or 64bit code depending on the target platform, i.e. on a x64 system 64bit code will be generated.

Therefore the code can no longer load a 32-bit dll on a 64-bit system.

If your code loads unmanaged assemblies you should always specify the target platform explicitly.

OwnerDisplayName: Nick

Title: Interop issue in .NET

OwnerDisplayName: divo


问:
File.getCanonicalPath() failure examples
Does anyone have an experience or know when the method File.getCanonicalPath() will throw an IOException

I have tried to look up from the Internet and the best answer is in File API which says

"IOException - If an I/O error occurs, which is possible because the construction of the canonical pathname may require filesystem queries"

However, it is not clear to me because I still cannot think of a case which this might fail. Can anyone give me concrete examples which can happen on Linux, Windows and other OS (optional)?

I reason I want to know is because I want to handle this exception accordingly. Thus, it will be best if I know all the possible failures that can happen.

答:
Here is a Windows example:

Try calling getCanonicalFile on a file in your CD-drive, but without a CD loaded. For example:

```<code>new File("D:\\dummy.txt").getCanonicalFile();
</code>```

you will get:

```<code>Exception in thread "main" java.io.IOException: The device is not ready
    at java.io.WinNTFileSystem.canonicalize0(Native Method)
    at java.io.Win32FileSystem.canonicalize(Win32FileSystem.java:396)
    at java.io.File.getCanonicalPath(File.java:559)
    at java.io.File.getCanonicalFile(File.java:583)
</code>```

Body:
Here is a Windows example:

Try calling getCanonicalFile on a file in your CD-drive, but without a CD loaded. For example:

new File("D:\\dummy.txt").getCanonicalFile();

you will get:

Exception in thread "main" java.io.IOException: The device is not ready
    at java.io.WinNTFileSystem.canonicalize0(Native Method)
    at java.io.Win32FileSystem.canonicalize(Win32FileSystem.java:396)
    at java.io.File.getCanonicalPath(File.java:559)
    at java.io.File.getCanonicalFile(File.java:583)


问:
exec with empty string or space
I just want to know whats happening behind this. If i execute the following SQL statement.

```<code>exec('')
</code>```

It says,

Command(s) completed successfully.

Same for the exec('           ')

Also, when you execute a space in SMSS directly

As of my knowledge, exec expects a SQL Statement or a stored procedure to run. But here if i passed the Empty string or one or more than one character space, How it has been handled?

答:
Parsing of the command happens :

Nothing to be executed.

End of the command : success.

Title: exec with empty string or space

Body:
I just want to know whats happening behind this. If i execute the following SQL statement.

exec('')

It says,

Command(s) completed successfully.

Same for the exec('           ')

Also, when you execute a space in SMSS directly

As of my knowledge, exec expects a SQL Statement or a stored procedure to run. But here if i passed the Empty string or one or more than one character space, How it has been handled?


问:
Turn dictionary into custom type
I turn all my custom classes into dictionaries using Mirror in order to save them with a plist like structure. With the Mirrors I simply store each value by its name, so a class with a variable "title" would turn into a dictionary with the key "title" and its value in the dictionary.

The question is, how to reverse this? I store a "type" information in every dictionary so I know which type should a dictionary turn into, but I don't know how to do the transition. I used to make use of setValue: forKey: in Objective-C but as I moved to Swift I have many structs for which this no longer works.

The only solution I can think of is to have all custom types conform to a protocol that describes an init(dictionary: [String: Any]) function and then manually translate the dictionary into the type there. In my general converter function I then get the type and through a switch statement simply call the init on the right type. It seems downright stupid though, to manually write

```<code>title = dictionary["title"]
</code>```

for the thousands of properties I have throughout the whole app. Is there an easier way?

答:
Based on the comment by tbogosia I looked at what Swift 4 offers and it looks like the new Codable is the way to go.

Apple doc right here:

https://developer.apple.com/documentation/foundation/archives_and_serialization/encoding_and_decoding_custom_types

It would seem that for lower version of Swift there is no other option but to use custom init functions for every custom type.

Title: Turn dictionary into custom type

Body:
I turn all my custom classes into dictionaries using Mirror in order to save them with a plist like structure. With the Mirrors I simply store each value by its name, so a class with a variable "title" would turn into a dictionary with the key "title" and its value in the dictionary.

The question is, how to reverse this? I store a "type" information in every dictionary so I know which type should a dictionary turn into, but I don't know how to do the transition. I used to make use of setValue: forKey: in Objective-C but as I moved to Swift I have many structs for which this no longer works.

The only solution I can think of is to have all custom types conform to a protocol that describes an init(dictionary: [String: Any]) function and then manually translate the dictionary into the type there. In my general converter function I then get the type and through a switch statement simply call the init on the right type. It seems downright stupid though, to manually write

title = dictionary["title"]

for the thousands of properties I have throughout the whole app. Is there an easier way?