问:
iterating inside a $http.get
I've this block of code which displays 20 items per request.

```<code>.controller('ActorController',function($scope,$http) {

    $scope.getActors = function () {
        var actors = $http.get(https://api.themoviedb.org/3/person/popular&page=1);
        actors.then(
            function (response) {
                $scope.actors = response.data.results;
            }
        );
    }
})
</code>```

Instead of page=1, if i put page=2, I'll get another set of 20 items and so on. How to iterate inside the $http.get if I want more than 1 get request in a single page? I want to display the 2nd 20 items after displaying the 1st 20.

答:
you can use $q.all to send multiple http requests at once

```<code>var fulAr = [];
for (var i = 1; i <= 2; i++) {
    fulAr.push($http.get("https://api.themoviedb.org/3/person/popular&page=" + i))
}
$q.all(fulAr).then(function(response) {
    console.log(response[0].data) //page 1 content
    console.log(response[1].data) //page 2 content

    for(var j = 0; j < response.length; j++) {
       $scope.actors = $scope.actors.concat(response[j].data.results);
    }
})
</code>```

Make sure to inject $q to controller

Title: iterating inside a $http.get

Body:
I've this block of code which displays 20 items per request.

.controller('ActorController',function($scope,$http) {

    $scope.getActors = function () {
        var actors = $http.get(https://api.themoviedb.org/3/person/popular&page=1);
        actors.then(
            function (response) {
                $scope.actors = response.data.results;
            }
        );
    }
})

Instead of page=1, if i put page=2, I'll get another set of 20 items and so on. How to iterate inside the $http.get if I want more than 1 get request in a single page? I want to display the 2nd 20 items after displaying the 1st 20.

Body:
you can use $q.all to send multiple http requests at once

var fulAr = [];
for (var i = 1; i <= 2; i++) {
    fulAr.push($http.get("https://api.themoviedb.org/3/person/popular&page=" + i))
}
$q.all(fulAr).then(function(response) {
    console.log(response[0].data) //page 1 content
    console.log(response[1].data) //page 2 content

    for(var j = 0; j < response.length; j++) {
       $scope.actors = $scope.actors.concat(response[j].data.results);
    }
})

Make sure to inject $q to controller


来源: stackexchange

问:
How to filter null value in Oracle sql
I want to filter the records that COMMENTS attribute is null

I have tried

```<code>SELECT TABLE_NAME, COMMENTS FROM
    (SELECT TABLE_NAME, COMMENTS FROM (select * FROM user_tab_comments))
    WHERE COMMENTS != null;
</code>```

But it didn't return the right output. How can I do it?

答:
NULL is a state not a value, therefore you can't use normal operators on it. Use IS NULL or IS NOT NULL instead.

```<code>SELECT TABLE_NAME, COMMENTS
  FROM (SELECT TABLE_NAME, COMMENTS FROM (select * FROM user_tab_comments))
    WHERE COMMENTS IS NOT NULL;
</code>```

Just saw that you don't need all those subqueries

```<code>SELECT TABLE_NAME, COMMENTS
  FROM user_tab_comments
 WHERE COMMENTS IS NOT NULL;
</code>```

ContentLicense: CC BY-SA 3.0

Title: How to filter null value in Oracle sql

Body:
I want to filter the records that COMMENTS attribute is null

I have tried

SELECT TABLE_NAME, COMMENTS FROM
    (SELECT TABLE_NAME, COMMENTS FROM (select * FROM user_tab_comments))
    WHERE COMMENTS != null;

But it didn't return the right output. How can I do it?

Body:
NULL is a state not a value, therefore you can't use normal operators on it. Use IS NULL or IS NOT NULL instead.

SELECT TABLE_NAME, COMMENTS
  FROM (SELECT TABLE_NAME, COMMENTS FROM (select * FROM user_tab_comments))
    WHERE COMMENTS IS NOT NULL;

Just saw that you don't need all those subqueries

SELECT TABLE_NAME, COMMENTS
  FROM user_tab_comments
 WHERE COMMENTS IS NOT NULL;


答:
So you're saying that you want to make multiple calls to $http.get in a loop? If so you'd do something like this:

```<code>.controller('ActorController',function($scope,$http) {

    $scope.getActors = function () {
        for(var i = 0; i < 5; i++) {
            getPage(i);
        }
    }

    function getPage(i) {
       var actors = $http.get('https://api.themoviedb.org/3/person/popular&page=' + i);
       actors.then(function (response) {
           for(var j = 0; j < response.data.results.length; j++) {
               $scope.actors.push(response.data.results[j]);
           }
       });
    }
})
</code>```

That will put the data for the first 5 pages into the $scope.actors array.

Title: iterating inside a $http.get

Body:
So you're saying that you want to make multiple calls to $http.get in a loop? If so you'd do something like this:

.controller('ActorController',function($scope,$http) {

    $scope.getActors = function () {
        for(var i = 0; i < 5; i++) {
            getPage(i);
        }
    }

    function getPage(i) {
       var actors = $http.get('https://api.themoviedb.org/3/person/popular&page=' + i);
       actors.then(function (response) {
           for(var j = 0; j < response.data.results.length; j++) {
               $scope.actors.push(response.data.results[j]);
           }
       });
    }
})

That will put the data for the first 5 pages into the $scope.actors array.


问:
How can I create binary label from two tables
I'm trying to analyse a trend in data that I have with Pandas. I have a two tables and I'd like to create a new binary column in one if the UID and PID in that row exists in the other table. An example of the tables I currently have would be:

```<code>>>> df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})
>>> df_a
   PID  TIM  UID
0   12   76  123
1   55   54  456
2   56   21  789
3   89   25  010

>>> df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})
>>> df_b
     FOO  PID  UID
0   2347   17  221
1  32447   89  010
2   3234   51  653
3   7999   55  456
</code>```

And I'd like the end result to be:

```<code>>>> df_a
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  010    1
</code>```

But I'm not sure exactly how to go about doing this. I thought a left join would be the way to go but I'm having trouble pulling that off also. Any help would be appreciated

答:
You can do it with a left join but it gets a bit weird if you want to have that result.

```<code>df_b['PUR'] = 1
df_a = pd.merge(df_a, df_b, how='left', on=['PID', 'UID'])
df_a['PUR'] = df_a['PUR'].apply(lambda x: 1 if pd.notnull(x) else 0)
df_a = df_a.drop('FOO', axis=1)
</code>```

I would suggest using a pure apply instead:

```<code>df_a['PUR'] = df_a.apply(lambda x: int(x['UID'] in df_b['UID'].values or
                                       x['PID'] in df_b['PID'].values), axis=1)
</code>```

Body:
I'm trying to analyse a trend in data that I have with Pandas. I have a two tables and I'd like to create a new binary column in one if the UID and PID in that row exists in the other table. An example of the tables I currently have would be:

>>> df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})
>>> df_a
   PID  TIM  UID
0   12   76  123
1   55   54  456
2   56   21  789
3   89   25  010

>>> df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})
>>> df_b
     FOO  PID  UID
0   2347   17  221
1  32447   89  010
2   3234   51  653
3   7999   55  456

And I'd like the end result to be:

>>> df_a
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  010    1

But I'm not sure exactly how to go about doing this. I thought a left join would be the way to go but I'm having trouble pulling that off also. Any help would be appreciated

Body:
You can do it with a left join but it gets a bit weird if you want to have that result.

df_b['PUR'] = 1
df_a = pd.merge(df_a, df_b, how='left', on=['PID', 'UID'])
df_a['PUR'] = df_a['PUR'].apply(lambda x: 1 if pd.notnull(x) else 0)
df_a = df_a.drop('FOO', axis=1)

I would suggest using a pure apply instead:

df_a['PUR'] = df_a.apply(lambda x: int(x['UID'] in df_b['UID'].values or
                                       x['PID'] in df_b['PID'].values), axis=1)


问:
Jenkins not forgetting deleted cucumber test features
I have a Jenkins pipeline build that reports on cucumber tests using the "CucumberReportPublisher".  When I delete tests or refactor a whole feature, many times the old tests hang around in the jenkins test report, showing as "skipped".

Is there a way to make Jenkins/CucmberReportPublisher forget about these old tests and stop reporting them as skipped?

答:
It sounds like you don't have a clean environment when you build your project.

I would make sure that Jenkins deleted the work space for the job and checked out the entire project from scratch for every build. I don't have a Jenkins to look at here, but there are different checkout options available for the job near the version control settings. Choose one that deletes the work space before checkout.

Another option can be to clean as the first step in your build. Assuming that you use Maven, it could look like this

```<code>mvn clean deploy
</code>```

This may solve your problem with ghost tests hanging around after deletion. But it may not solve your problem with a dirty work space.

Body:
It sounds like you don't have a clean environment when you build your project.

I would make sure that Jenkins deleted the work space for the job and checked out the entire project from scratch for every build. I don't have a Jenkins to look at here, but there are different checkout options available for the job near the version control settings. Choose one that deletes the work space before checkout.

Another option can be to clean as the first step in your build. Assuming that you use Maven, it could look like this

mvn clean deploy

This may solve your problem with ghost tests hanging around after deletion. But it may not solve your problem with a dirty work space.


问:
How can I verify a email and a phone number through a single resex?
Well, I have 2 separate regex for verification email and phone number separately. Like

```<code>email = "^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6}"
</code>```

and

```<code>phone = "^[2-9]\d{2}-\d{3}-\d{4}"
</code>```

However,  I want to input input form a field which may b either email and Phone. And I must validate them.
I have tried using a || operator for or between those two resex, but didn't work.

```<code>[Required]
[MaxLength(50)]
[RegularExpression(@"^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6} || ^[2-9]\d{2}-\d{3}-\d{4}$", ErrorMessage = "Invalid Phone number Email Address")]
[Display(Name = "Phone number or Email")]
[System.Web.Mvc.Remote("IsUserExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists")]
public string MobOrEmail { get; set; }
</code>```

So I need a proper regex which can verify both email or a phone number at a time. Or an or operation between them will be perfect and I need it badly. Thanks.

答:
You need a single | (pipe) character (not 2) and without the spaces. It should be

```<code>[RegularExpression(@"^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6}|[2-9]\d{2}-\d{3}-\d{4}", ErrorMessage = "...")
</code>```

Refer regexr

Note that you email regex is not very strong. The one used by jquery.validate.js is

```<code>/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$
</code>```

To make this a bit easier to read in the model, and easier to reuse, you could create your own attribute that extends ReqularExpressionAttribute

```<code>[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EmailOrPhoneAttribute : RegularExpressionAttribute
{

    public EmailOrPhoneAttribute () : base(@"^\w+\@([\da-zA-Z\-]...etc")
    {
        // Add default error message
        ErrorMessage = "Invalid Phone number Email Address";
    }
}
</code>```

and register it in global.asax.cs

```<code>protected void Application_Start()
{
    ....
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailOrPhoneAttribute), typeof(RegularExpressionAttributeAdapter));
    ....
}
</code>```

and then in the model

```<code>[EmailOrPhone]
public string MobOrEmail { get; set; }
</code>```

Body:
Well, I have 2 separate regex for verification email and phone number separately. Like

email = "^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6}"

and

phone = "^[2-9]\d{2}-\d{3}-\d{4}"

However,  I want to input input form a field which may b either email and Phone. And I must validate them.
I have tried using a || operator for or between those two resex, but didn't work.

[Required]
[MaxLength(50)]
[RegularExpression(@"^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6} || ^[2-9]\d{2}-\d{3}-\d{4}$", ErrorMessage = "Invalid Phone number Email Address")]
[Display(Name = "Phone number or Email")]
[System.Web.Mvc.Remote("IsUserExists", "Account", HttpMethod = "POST", ErrorMessage = "This Phone number or Email already exists")]
public string MobOrEmail { get; set; }

So I need a proper regex which can verify both email or a phone number at a time. Or an or operation between them will be perfect and I need it badly. Thanks.

Body:
You need a single | (pipe) character (not 2) and without the spaces. It should be

[RegularExpression(@"^\w+\@([\da-zA-Z\-]{1,}\.){1,}[\da-zA-Z-]{2,6}|[2-9]\d{2}-\d{3}-\d{4}", ErrorMessage = "...")

Refer regexr

Note that you email regex is not very strong. The one used by jquery.validate.js is

/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))$

To make this a bit easier to read in the model, and easier to reuse, you could create your own attribute that extends ReqularExpressionAttribute

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field, AllowMultiple = false)]
public class EmailOrPhoneAttribute : RegularExpressionAttribute
{

    public EmailOrPhoneAttribute () : base(@"^\w+\@([\da-zA-Z\-]...etc")
    {
        // Add default error message
        ErrorMessage = "Invalid Phone number Email Address";
    }
}

and register it in global.asax.cs

protected void Application_Start()
{
    ....
    DataAnnotationsModelValidatorProvider.RegisterAdapter(typeof(EmailOrPhoneAttribute), typeof(RegularExpressionAttributeAdapter));
    ....
}

and then in the model

[EmailOrPhone]
public string MobOrEmail { get; set; }


问:
Writing some numbers on ATmega16 EEPROM memory in assembly
I'm trying to write numbers 0-9 to the EEPROM memory using assembly language in AtmelStudio 7. I made a loop until the counter reaches 8 (which is stored in R17 and a counter which is stored in R16). EEPROM in ATmega16 is 512 bytes so I will need two registers(Low and High bytes) to point to that memory.
everything is working fine except that i cant find a way to track EEPROM memory to check if the data is being written or not. Hope someone gives me a hint with AtmelStudio 7.
Here is my code:</p>

```<code>; Replace with your application code
start:
/* Define a counter in R16 */
ldi R16,0
ldi R17,8
/* EEPROM Address to be written */
ldi R18,0x00
ldi R19,0x00
/* Loop through this untill 9 numbers are written */
EEPROM_WRITE:
/* Wait untill the EEWE gets 0 */
/* Skip next instruction if EEWE is clear in EECR */
sbic EECR,EEWE
rjmp EEPROM_WRITE
/* Write the address to be filled with the number :D */
out EEARL,R18
out EEARH,R19
/* Write the data */
/* Counter can be used itself */
out EEDR,R16
/* Write logical one to the EEMWE */
/* Set bit immediate */
sbi EECR,EEMWE
/* Start write */
sbi EECR,EEWE
/* Add 1 to the counter */
inc R16
/* Go to the next address on EEPROM */
inc R18
/* Check the loop end point */
cp R16,R17
brne EEPROM_WRITE
rjmp EEPROM_WRITE
rjmp start
</code>```

答: If you want to track EEPROM in atmel studio, than you need to start debug session and open memory window (Alt+6). There should be drop down list where should be eepom option. You can verify your data there.</p>

Body:
I'm trying to write numbers 0-9 to the EEPROM memory using assembly language in AtmelStudio 7. I made a loop until the counter reaches 8 (which is stored in R17 and a counter which is stored in R16). EEPROM in ATmega16 is 512 bytes so I will need two registers(Low and High bytes) to point to that memory.
everything is working fine except that i cant find a way to track EEPROM memory to check if the data is being written or not. Hope someone gives me a hint with AtmelStudio 7.
Here is my code:

; Replace with your application code
start:
/* Define a counter in R16 */
ldi R16,0
ldi R17,8
/* EEPROM Address to be written */
ldi R18,0x00
ldi R19,0x00
/* Loop through this untill 9 numbers are written */
EEPROM_WRITE:
/* Wait untill the EEWE gets 0 */
/* Skip next instruction if EEWE is clear in EECR */
sbic EECR,EEWE
rjmp EEPROM_WRITE
/* Write the address to be filled with the number :D */
out EEARL,R18
out EEARH,R19
/* Write the data */
/* Counter can be used itself */
out EEDR,R16
/* Write logical one to the EEMWE */
/* Set bit immediate */
sbi EECR,EEMWE
/* Start write */
sbi EECR,EEWE
/* Add 1 to the counter */
inc R16
/* Go to the next address on EEPROM */
inc R18
/* Check the loop end point */
cp R16,R17
brne EEPROM_WRITE
rjmp EEPROM_WRITE
rjmp start


问:
save google gauge chart as a png
I am using google charts and have a page of mixed charts, some pie, a column chart and a gauge chart

The page has an option to generate a pdf, so I am converting the charts to PNG to use in the pdf..

all the charts are generated in the same manner, using a div to display the google chart and a hidden div to store the png image

```<code> var chart = new google.visualization.Gauge(document.getElementById('gauge'));
    var hidden = new google.visualization.Gauge(document.getElementById('gauge_hidden'));

  // Wait for the chart to finish drawing before calling the getImageURI() method.
    google.visualization.events.addListener(chart, 'ready', function () {
        gauge_hidden.innerHTML = '<img src="' + chart.getImageURI() + '">';

    });
    chart.draw(data, options);
</code>```

this code works fin on he pie and column charts, but on the gauge chart I am seeing

chart.getImageURI is not a function

any ideas how I can get the png?

CHeers

答:
I was facing this same issue, but after some reading i've come to this solution:

I'm using jQuery to make this a little easier.

First, use XMLSerializer to convert the SVG chart to a string and then use btoa to convert that to base64.
You can use this string this way:

```<code>var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);
var base64String = "data:image/svg+xml;base64," + window.btoa(s);
</code>```

In my case i needed to draw the gauge chart to a PDF and DOMPDF doesn't support this format, so if you need a "data:image/png;base64," string, you can continue with this solution.

You need to set the "svg+xml;base64" as src of a new Image and then draw that image to a Canvas. After that you can use toDataURL method from canvas to get the content as base64 png.

var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);
var image = new Image();
image.width = 640;
image.height = 480;
image.src = 'data:image/svg+xml;base64,' + window.btoa(s);
var myCanvas = document.createElement('canvas');
myCanvas.width = 640;
myCanvas.height = 480;
var myCanvasContext = myCanvas.getContext('2d');
myCanvasContext.drawImage(image,0,0);
// get google chart gague to base64, yey!
var base64String = myCanvas.toDataURL();```

Thanks to the author of this answer and this post

Title: save google gauge chart as a png

Body:
I am using google charts and have a page of mixed charts, some pie, a column chart and a gauge chart

The page has an option to generate a pdf, so I am converting the charts to PNG to use in the pdf..

all the charts are generated in the same manner, using a div to display the google chart and a hidden div to store the png image

 var chart = new google.visualization.Gauge(document.getElementById('gauge'));
    var hidden = new google.visualization.Gauge(document.getElementById('gauge_hidden'));

  // Wait for the chart to finish drawing before calling the getImageURI() method.
    google.visualization.events.addListener(chart, 'ready', function () {
        gauge_hidden.innerHTML = '';

    });
    chart.draw(data, options);

this code works fin on he pie and column charts, but on the gauge chart I am seeing

chart.getImageURI is not a function

any ideas how I can get the png?

CHeers

Body:
I was facing this same issue, but after some reading i've come to this solution:

I'm using jQuery to make this a little easier.

First, use XMLSerializer to convert the SVG chart to a string and then use btoa to convert that to base64.
You can use this string this way:

var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);
var base64String = "data:image/svg+xml;base64," + window.btoa(s);

In my case i needed to draw the gauge chart to a PDF and DOMPDF doesn't support this format, so if you need a "data:image/png;base64," string, you can continue with this solution.

You need to set the "svg+xml;base64" as src of a new Image and then draw that image to a Canvas. After that you can use toDataURL method from canvas to get the content as base64 png.

var s = new XMLSerializer().serializeToString($(chart_div).find('svg')[0]);
var image = new Image();
image.width = 640;
image.height = 480;
image.src = 'data:image/svg+xml;base64,' + window.btoa(s);
var myCanvas = document.createElement('canvas');
myCanvas.width = 640;
myCanvas.height = 480;
var myCanvasContext = myCanvas.getContext('2d');
myCanvasContext.drawImage(image,0,0);
// get google chart gague to base64, yey!
var base64String = myCanvas.toDataURL();

Thanks to the author of this answer and this post


问:
C# Parse XML with repeated pattern of nodes
Hi I have the following xml file:

```<code><?xml version="1.0" encoding="utf-8"?>
<Resources>
    <Category Cause="ONE">
        <Resource Component="AAA" Name="cBackgroundTextA" />
        <Resource Component="BBB" Name="cBackgroundTextB" />
        <Resource Component="CCC" Name="cBackgroundTextC" />
    </Category>
    <Category Cause="TWO">
        <Resource Component="DDD" Name="cBackgroundTextD" />
        <Resource Component="EEE" Name="cBackgroundTextE" />
        <Resource Component="FFF" Name="cBackgroundTextF" />
    </Category>
    <Category Cause="THREE">
        <Resource Component="GGG" Name="cBackgroundTextG" />
        <Resource Component="HHH" Name="cBackgroundTextH" />
        <Resource Component="III" Name="cBackgroundTextI" />
    </Category>
</Resources>
</code>```

How can i get the following:

ONE , AAA , cBackgroundTextA

ONE , BBB , cBackgroundTextB

ONE , CCC , cBackgroundTextC

TWO , DDD , cBackgroundTextD

TWO , EEE , cBackgroundTextE

...

答:
I finally managed to get the values by:</p>

```<code>xmlDocument = new XDocument();
xmlDocument = XDocument.Load(filePath, LoadOptions.None);

var categoryNodeList = XmlDocument.Descendants("Category");

    foreach (XElement categoryItem in categoryNodeList)
    {
        foreach (XElement resourceItem in categoryItem.Elements())
        {
            var XmlObject = new ResultDetail
            {
                Cause = categoryItem.Attribute("Cause").Value,
                Component = resourceItem.Attribute("Component").Value,
                Name = resourceItem.Attribute("Name").Value
            };
        }
    }
</code>```

Body:
Hi I have the following xml file:

<?xml version="1.0" encoding="utf-8"?>
<Resources>
    <Category Cause="ONE">
        <Resource Component="AAA" Name="cBackgroundTextA" />
        <Resource Component="BBB" Name="cBackgroundTextB" />
        <Resource Component="CCC" Name="cBackgroundTextC" />
    </Category>
    <Category Cause="TWO">
        <Resource Component="DDD" Name="cBackgroundTextD" />
        <Resource Component="EEE" Name="cBackgroundTextE" />
        <Resource Component="FFF" Name="cBackgroundTextF" />
    </Category>
    <Category Cause="THREE">
        <Resource Component="GGG" Name="cBackgroundTextG" />
        <Resource Component="HHH" Name="cBackgroundTextH" />
        <Resource Component="III" Name="cBackgroundTextI" />
    </Category>
</Resources>

How can i get the following:

ONE , AAA , cBackgroundTextA

ONE , BBB , cBackgroundTextB

ONE , CCC , cBackgroundTextC

TWO , DDD , cBackgroundTextD

TWO , EEE , cBackgroundTextE

...

Body:
I finally managed to get the values by:

xmlDocument = new XDocument();
xmlDocument = XDocument.Load(filePath, LoadOptions.None);

var categoryNodeList = XmlDocument.Descendants("Category");

    foreach (XElement categoryItem in categoryNodeList)
    {
        foreach (XElement resourceItem in categoryItem.Elements())
        {
            var XmlObject = new ResultDetail
            {
                Cause = categoryItem.Attribute("Cause").Value,
                Component = resourceItem.Attribute("Component").Value,
                Name = resourceItem.Attribute("Name").Value
            };
        }
    }


问:
How to enable price and inventory for custom product type in WooCommerce
I created a custom product type in my WooCommerce application

```<code>function register_variable_bulk_product_type() {

    class WC_Product_Variable_bulk extends WC_Product_Simple {

        public function __construct($product) {

            $this->product_type = 'variable_bulk';
            parent::__construct($product);
        }

    }

}

add_action('init', 'register_variable_bulk_product_type');

function add_variable_bulk_product($types) {

    $types['variable_bulk'] = __('Variable Bulk');

    return $types;
}

add_filter('product_type_selector', 'add_variable_bulk_product');
</code>```

This shows product type in product data dropdown like as follows,

My problem is

The new product don't have an option for adding inventory and prices, How can I enable these options?

答:
You need a small JS trick to show Price and Inventory tab, i.e. you
  need to add class show_if_{your_custom_product_type} in your case it
  will be show_if_variable_bulk.

Here is the working code:

```<code>function wh_variable_bulk_admin_custom_js() {

    if ('product' != get_post_type()) :
        return;
    endif;
    ?>
    <script type='text/javascript'>
        jQuery(document).ready(function () {
            //for Price tab
            jQuery('.product_data_tabs .general_tab').addClass('show_if_variable_bulk').show();
            jQuery('#general_product_data .pricing').addClass('show_if_variable_bulk').show();
            //for Inventory tab
            jQuery('.inventory_options').addClass('show_if_variable_bulk').show();
            jQuery('#inventory_product_data ._manage_stock_field').addClass('show_if_variable_bulk').show();
            jQuery('#inventory_product_data ._sold_individually_field').parent().addClass('show_if_variable_bulk').show();
            jQuery('#inventory_product_data ._sold_individually_field').addClass('show_if_variable_bulk').show();
        });
    </script>
    <?php

}

add_action('admin_footer', 'wh_variable_bulk_admin_custom_js');
</code>```

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin PHP files.

Code is tested and works.

This is how your general tab will look:

and this is how inventory tab will look

Hope this helps!

Body:
I created a custom product type in my WooCommerce application

function register_variable_bulk_product_type() {

    class WC_Product_Variable_bulk extends WC_Product_Simple {

        public function __construct($product) {

            $this->product_type = 'variable_bulk';
            parent::__construct($product);
        }

    }

}

add_action('init', 'register_variable_bulk_product_type');

function add_variable_bulk_product($types) {

    $types['variable_bulk'] = __('Variable Bulk');

    return $types;
}

add_filter('product_type_selector', 'add_variable_bulk_product');

This shows product type in product data dropdown like as follows,

My problem is

The new product don't have an option for adding inventory and prices, How can I enable these options?

Body:
You need a small JS trick to show Price and Inventory tab, i.e. you
  need to add class show_if_{your_custom_product_type} in your case it
  will be show_if_variable_bulk.

Here is the working code:

function wh_variable_bulk_admin_custom_js() {

    if ('product' != get_post_type()) :
        return;
    endif;
    ?>
    <script type='text/javascript'>
        jQuery(document).ready(function () {
            //for Price tab
            jQuery('.product_data_tabs .general_tab').addClass('show_if_variable_bulk').show();
            jQuery('#general_product_data .pricing').addClass('show_if_variable_bulk').show();
            //for Inventory tab
            jQuery('.inventory_options').addClass('show_if_variable_bulk').show();
            jQuery('#inventory_product_data ._manage_stock_field').addClass('show_if_variable_bulk').show();
            jQuery('#inventory_product_data ._sold_individually_field').parent().addClass('show_if_variable_bulk').show();
            jQuery('#inventory_product_data ._sold_individually_field').addClass('show_if_variable_bulk').show();
        });
    </script>
    <?php

}

add_action('admin_footer', 'wh_variable_bulk_admin_custom_js');

Code goes in functions.php file of your active child theme (or theme). Or also in any plugin PHP files.

Code is tested and works.

This is how your general tab will look:

and this is how inventory tab will look

Hope this helps!


问:
WPF XAML StringFormat assign amount of decimal places through binding
I have the need to give the user the ability to set their own Decimal Formating option in XAML.

I know how to set StringFormat into Binding, but I only know how to do it manually. How can I Bind the String Format value inside a binding.

答:
You can use ContentStringFormat property.

URL: https://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.contentstringformat.aspx

Use it like this:

```<code><TextBox Text="{Binding MyFormat, UpdateSourceTrigger=PropertyChanged}" />
<Label Content="{Binding ValueToFormat}"
       ContentStringFormat="{Binding MyFormat}" />
</code>```

Body:
You can use ContentStringFormat property.

URL: https://msdn.microsoft.com/en-us/library/system.windows.controls.contentcontrol.contentstringformat.aspx

Use it like this:

<TextBox Text="{Binding MyFormat, UpdateSourceTrigger=PropertyChanged}" />
<Label Content="{Binding ValueToFormat}"
       ContentStringFormat="{Binding MyFormat}" />


问:
Angular2 addArticle is not a function
When clicked on the submit button, I encounter this msg in the console and also if someone can help me how to import the moment from node_modules to angula2 project!!

My app.component.html

```<code><form class="ui large form segment">
  <h3 class="ui header">Add a Link</h3>
  <div class="field">
    <label for="title">Title:</label>
    <input name="title" #newtitle>
  </div>
  <div class="field">
    <label for="link">Link:</label>
    <input name="link" #newlink>
  </div>
  <div>
    <button (click) ="addArticle(newtitle, newlink)" class="ui positive button">Submit link</button>
  </div>

</form>
</code>```

My app.module.ts

```<code>export class AppModule {
  addArticle(title: HTMLInputElement, link:HTMLInputElement): boolean{
    console.log('title: ${title.value} and link: ${link.value}');
    return false;
  }
 }
</code>```

答:
You have written the addArticle method in app.module.ts you should put that in app.component.ts

```<code>export class AppModule {
  addArticle(title: HTMLInputElement, link:HTMLInputElement): boolean{
    console.log('title: ${title.value} and link: ${link.value}');
    return false;
  }
 }
</code>```

move the addArticle method to app.component.ts as you're using that in app.component.html

```<code>export class AppComponent {
  title = 'Okay, proceed .!';
  names = [];
 // myDate = Date;

  constructor(){
    this.names = ['Tuan','Mark','Kevin'];
  //  this.myDate = new Date();
  }
 addArticle(title: HTMLInputElement, link:HTMLInputElement): boolean{
        console.log('title: ${title.value} and link: ${link.value}');
        return false;
      }
}
</code>```

For moment  use the below import

```<code>import {MomentModule} from 'angular2-moment/module';
</code>```

after npm install angular2-moment..  http://ngmodules.org/modules/angular2-moment

Title: Angular2 addArticle is not a function

Body:
When clicked on the submit button, I encounter this msg in the console and also if someone can help me how to import the moment from node_modules to angula2 project!!

My app.component.html

<form class="ui large form segment">

Add a Link

    Title:
    <input name="title" #newtitle>

    Link:
    <input name="link" #newlink>

    <button (click) ="addArticle(newtitle, newlink)" class="ui positive button">Submit link</button>

</form>

My app.module.ts

export class AppModule {
  addArticle(title: HTMLInputElement, link:HTMLInputElement): boolean{
    console.log('title: ${title.value} and link: ${link.value}');
    return false;
  }
 }

Body:
You have written the addArticle method in app.module.ts you should put that in app.component.ts

export class AppModule {
  addArticle(title: HTMLInputElement, link:HTMLInputElement): boolean{
    console.log('title: ${title.value} and link: ${link.value}');
    return false;
  }
 }

move the addArticle method to app.component.ts as you're using that in app.component.html

export class AppComponent {
  title = 'Okay, proceed .!';
  names = [];
 // myDate = Date;

  constructor(){
    this.names = ['Tuan','Mark','Kevin'];
  //  this.myDate = new Date();
  }
 addArticle(title: HTMLInputElement, link:HTMLInputElement): boolean{
        console.log('title: ${title.value} and link: ${link.value}');
        return false;
      }
}

For moment  use the below import

import {MomentModule} from 'angular2-moment/module';

after npm install angular2-moment..  http://ngmodules.org/modules/angular2-moment

ContentLicense: CC BY-SA 4.0


问:
How do I use external assemblies with Microsoft Azure Function Apps?
The documentation says that you can put a DLL in a bin folder and reference it using a special #r syntax, however in the Azure portal I cannot find how to upload these DLLs. Is this possible, and if so, how is that supposed to be accomplished?

答:
Azure functions now has runtime support for precompiled functions.
https://blogs.msdn.microsoft.com/appserviceteam/2017/03/16/publishing-a-net-class-library-as-a-function-app/

You’ll need to use a web project which will provide the full development experience of IntelliSense, local debugging, and publishing to Azure. The instructions above detail how.


问:
react + react-bootstrap. is it better to create function or fine to write function as a property
I am looking at the react-bootstrap components site, and specifically the <FormControl> component.

For validating whether the input value is OK, is it acceptable to write it inline or as a function?

For example,

```<code><FormControl
  onChange={() => {this.setState({ /* do some ternary check here */ })}
/>
</code>```

I've noticed in a lot of tutorials that authors will either move a lot of these out to functions (ie. onChange={this.doSomething}), or sometimes it seems to make sense to do them the way above.

How can I know which way is preferable?

答:
it's good to add a function or make a function.
It would be preferable because using function that function can be called anywhere anytime you wanted but if you use inline then every time you have to write the same thing which makes the code even more complex and clumpsy</p>

Body:
I am looking at the react-bootstrap components site, and specifically the <FormControl> component.

For validating whether the input value is OK, is it acceptable to write it inline or as a function?

For example,

<FormControl
  onChange={() => {this.setState({ /* do some ternary check here */ })}
/>

I've noticed in a lot of tutorials that authors will either move a lot of these out to functions (ie. onChange={this.doSomething}), or sometimes it seems to make sense to do them the way above.

How can I know which way is preferable?


问:
whats the CSS selector for a label that does not have a sibling input type=checkbox||radio?
I need to set it with CSS, not jquery.

The selector is for

all labels which do not have a sibling that is a checkbox or radio component.

a sample is:

```<code><span>
  <input id="item" type="checkbox">
  <label for="item">Data</label>
</span>
</code>```

This is because i have CSS which sets label to 12px, BUT it affects asp:checkboxes and asp:radio..., but i do not want them to be affected.

答:
I submitted an answer to a question that I feel is extremely valuable and along the lines to what you're asking for in this question. Here is the permalink to that question/answer.

https://stackoverflow.com/a/43132408/6167697

The key thing that is missing that may not work for your case is I propose keeping the inputs a child only to what they need to be so that other content can be selector'd using generic sibling selectors. Hypothetically you could still keep them in the span, and then use the labels in various elements inside the span, and that would still allow you treat those labels separate from any others I would think. I'll copy in a code snippet for a working example that demonstrates label elements that are not siblings to their inputs that can still be styled.

* {
  padding: 0;
  margin: 0;
  background-color: #262626;
  color: white;
}

.radio-button {
  display: none;
}

#filter {
  padding: 5% 0;
  display: flex;
  justify-content: center;
}

.filter-label {
  display: inline-block;
  border: 4px solid green;
  padding: 10px 20px;
  font-size: 1.4em;
  text-align: center;
  cursor: pointer;
}

main {
  clear: left;
}

.content {
  padding: 3% 10%;
  display: none;
}

h1 {
  font-size: 2em;
}

.date {
  padding: 5px 30px;
  font-style: italic;
}

.filter-label:hover {
  background-color: #505050;
}

#featured-radio:checked~#filter .featured,
#personal-radio:checked~#filter .personal,
#tech-radio:checked~#filter .tech {
  background-color: green;
}

#featured-radio:checked~main .featured {
  display: block;
}

#personal-radio:checked~main .personal {
  display: block;
}

#tech-radio:checked~main .tech {
  display: block;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">

<header id="filter">
  <label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>
  <label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>
  <label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>
</header>

<main>
  <article class="content featured tech">
    <header>
      <h1>Cool Stuff</h1>
      <h3 class="date">Today</h3>
    </header>

    <p>
      I'm showing cool stuff in this article!
    </p>
  </article>

  <article class="content personal">
    <header>
      <h1>Not As Cool</h1>
      <h3 class="date">Tuesday</h3>
    </header>

    <p>
      This stuff isn't nearly as cool for some reason :(;
    </p>
  </article>

  <article class="content tech">
    <header>
      <h1>Cool Tech Article</h1>
      <h3 class="date">Last Monday</h3>
    </header>

    <p>
      This article has awesome stuff all over it!
    </p>
  </article>

  <article class="content featured personal">
    <header>
      <h1>Cool Personal Article</h1>
      <h3 class="date">Two Fridays Ago</h3>
    </header>

    <p>
      This article talks about how I got a job at a cool startup because I rock!
    </p>
  </article>
</main></code>```

That has the added benefit of being pure CSS too! And as per the other post, here's the JSFIDDLE so you can play around with it yourselves.

Body:
I need to set it with CSS, not jquery.

The selector is for

all labels which do not have a sibling that is a checkbox or radio component.

a sample is:

  <input id="item" type="checkbox">
  Data

This is because i have CSS which sets label to 12px, BUT it affects asp:checkboxes and asp:radio..., but i do not want them to be affected.

Body:
I submitted an answer to a question that I feel is extremely valuable and along the lines to what you're asking for in this question. Here is the permalink to that question/answer.

https://stackoverflow.com/a/43132408/6167697

The key thing that is missing that may not work for your case is I propose keeping the inputs a child only to what they need to be so that other content can be selector'd using generic sibling selectors. Hypothetically you could still keep them in the span, and then use the labels in various elements inside the span, and that would still allow you treat those labels separate from any others I would think. I'll copy in a code snippet for a working example that demonstrates label elements that are not siblings to their inputs that can still be styled.

* {
  padding: 0;
  margin: 0;
  background-color: #262626;
  color: white;
}

.radio-button {
  display: none;
}

#filter {
  padding: 5% 0;
  display: flex;
  justify-content: center;
}

.filter-label {
  display: inline-block;
  border: 4px solid green;
  padding: 10px 20px;
  font-size: 1.4em;
  text-align: center;
  cursor: pointer;
}

main {
  clear: left;
}

.content {
  padding: 3% 10%;
  display: none;
}

h1 {
  font-size: 2em;
}

.date {
  padding: 5px 30px;
  font-style: italic;
}

.filter-label:hover {
  background-color: #505050;
}

#featured-radio:checked~#filter .featured,
#personal-radio:checked~#filter .personal,
#tech-radio:checked~#filter .tech {
  background-color: green;
}

#featured-radio:checked~main .featured {
  display: block;
}

#personal-radio:checked~main .personal {
  display: block;
}

#tech-radio:checked~main .tech {
  display: block;
}

<input type="radio" id="featured-radio" class="radio-button" name="content-filter" checked="checked">
<input type="radio" id="personal-radio" class="radio-button" name="content-filter" value="Personal">
<input type="radio" id="tech-radio" class="radio-button" name="content-filter" value="Tech">

<header id="filter">
  <label for="featured-radio" class="filter-label featured" id="feature-label">Featured</label>
  <label for="personal-radio" class="filter-label personal" id="personal-label">Personal</label>
  <label for="tech-radio" class="filter-label tech" id="tech-label">Tech</label>
</header>

<main>
  <article class="content featured tech">
    <header>
      <h1>Cool Stuff</h1>
      <h3 class="date">Today</h3>
    </header>

    <p>
      I'm showing cool stuff in this article!
    </p>
  </article>

  <article class="content personal">
    <header>
      <h1>Not As Cool</h1>
      <h3 class="date">Tuesday</h3>
    </header>

    <p>
      This stuff isn't nearly as cool for some reason :(;
    </p>
  </article>

  <article class="content tech">
    <header>
      <h1>Cool Tech Article</h1>
      <h3 class="date">Last Monday</h3>
    </header>

    <p>
      This article has awesome stuff all over it!
    </p>
  </article>

  <article class="content featured personal">
    <header>
      <h1>Cool Personal Article</h1>
      <h3 class="date">Two Fridays Ago</h3>
    </header>

    <p>
      This article talks about how I got a job at a cool startup because I rock!
    </p>
  </article>
</main>

That has the added benefit of being pure CSS too! And as per the other post, here's the JSFIDDLE so you can play around with it yourselves.


问:
Appending the code onto "jsoninput.json" file in Server.MapPath using FileStream and StreamWriter
"jsonr" has been appended to from its original form jsoninput.json.

jsoninput.json:

[count:[{first:1,second:1,third:1},{first:2,second:2,third:2}]]

I want to be able to save the changes made to "jsoninput.json" by appending the code into jsonr onto jsoninput.json in Server.MapPath using FileStream and StreamWriter as below:

```<code>jsonr="[count:[{first:1,second:2,third:3},{first:11,second:22,third:33},{first:111,second:222,third:333}]]"
using (FileStream fsAppend = new FileStream(Server.MapPath("~/jsoninput.json"), FileMode.Append, FileAccess.Write))
{
    StreamWriter sw = new StreamWriter(fsAppend);
    sw.Write(jsonr);
    sw.Flush();
    sw.Close();
    StreamWriter Stream = File.AppendText(Server.MapPath("~/jsoninput.json"),jsonr);
    Stream.Close();
    fsAppend.Close();
}
</code>```

答:
JsonString.json file contens before add new json array is below:

```<code> {
 "data": [
          {
          "name": "Person 1",
          "email": "test@test.com",
          "address": {
          "address1": "my address 1",
          "address2": "my address 2"
        }
      },
    {
      "name": "Person 2",
      "email": "example@example.com",
      "address": {
        "address1": "my address 1",
        "address2": "my address 2"
          }
        }
      ]
 }
</code>```

Target json array to add:

```<code>string jsonr="{
                count:[
                        {first:1,
                         second:2,
                         third:3
                        },
                        {first:11,
                         second:22,
                         third:33
                        },
                        {first:111,
                         second:222,
                         third:333
                        }
                      ]
              }";
</code>```

C# code to add jsonr to JsonString.json:

```<code>string jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "JsonString.json");
string jsonString = File.ReadAllText(jsonPath);
var jsonrObject = JObject.Parse(jsonr)["count"];
JObject o = JObject.Parse(jsonString);
string resultJson = o.Property("data").AddAfterSelf(new JProperty("count", jsonrObject)).ToString();
</code>```

Code is tested

Body:
"jsonr" has been appended to from its original form jsoninput.json.

jsoninput.json:

[count:[{first:1,second:1,third:1},{first:2,second:2,third:2}]]

I want to be able to save the changes made to "jsoninput.json" by appending the code into jsonr onto jsoninput.json in Server.MapPath using FileStream and StreamWriter as below:

jsonr="[count:[{first:1,second:2,third:3},{first:11,second:22,third:33},{first:111,second:222,third:333}]]"
using (FileStream fsAppend = new FileStream(Server.MapPath("~/jsoninput.json"), FileMode.Append, FileAccess.Write))
{
    StreamWriter sw = new StreamWriter(fsAppend);
    sw.Write(jsonr);
    sw.Flush();
    sw.Close();
    StreamWriter Stream = File.AppendText(Server.MapPath("~/jsoninput.json"),jsonr);
    Stream.Close();
    fsAppend.Close();
}

Body:
JsonString.json file contens before add new json array is below:

 {
 "data": [
          {
          "name": "Person 1",
          "email": "test@test.com",
          "address": {
          "address1": "my address 1",
          "address2": "my address 2"
        }
      },
    {
      "name": "Person 2",
      "email": "example@example.com",
      "address": {
        "address1": "my address 1",
        "address2": "my address 2"
          }
        }
      ]
 }

Target json array to add:

string jsonr="{
                count:[
                        {first:1,
                         second:2,
                         third:3
                        },
                        {first:11,
                         second:22,
                         third:33
                        },
                        {first:111,
                         second:222,
                         third:333
                        }
                      ]
              }";

C# code to add jsonr to JsonString.json:

string jsonPath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "JsonString.json");
string jsonString = File.ReadAllText(jsonPath);
var jsonrObject = JObject.Parse(jsonr)["count"];
JObject o = JObject.Parse(jsonString);
string resultJson = o.Property("data").AddAfterSelf(new JProperty("count", jsonrObject)).ToString();

Code is tested


问:
Is it possible to set PlaceAutocompleteFragment dropdown as font family
Is it possible to set dropdown list as font family:

I am using PlaceAutocompleteFragment ,In this When I type something the dropdownlist need to be shown in roboto-medium or any font family .

答:
My suggestion is to don't go for it if it's not much necessary. For your question, Google provides Place Auto Complete Service which you can use to have your task done. But it's very complex and long method.

You can follow this tutorial. It uses AutoCompleteTextView and TextView on which you can easily apply your font either using custom views or setting Typeface.


问:
On your very first program, which construct hooked you on programming?
To me it was the If statement, I'm psyched up, since then I believed that computers are very intelligent, or I can at least make it appear intelligent because of it.</p>

答:
I really fell in love with programming languages once I discovered comments. You can do all kind of stuff with it, like </p>

```<code>// a commment!
int /* whoa, an inline comment! */ a;
</code>```

<p>;)</p>

OwnerDisplayName: Michael Buen

ContentLicense: CC BY-SA 2.5

LastEditorDisplayName: Triptych

Body:
I really fell in love with programming languages once I discovered comments. You can do all kind of stuff with it, like

// a commment!
int /* whoa, an inline comment! */ a;

;)

OwnerDisplayName: Quiark


答:
You can use numpy's in1d(). You can use it to implement in further cases too, where left join might fail</p>

```<code>    import pandas as pd
    import numpy as np

    df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})

    df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})

    UID_a = df_a['UID'].values
    UID_b = df_b['UID'].values
    PID_a = df_a['PID'].values
    PID_b = df_b['PID'].values

    x = np.in1d(UID_a, UID_b)
    y = np.in1d(PID_a, PID_b)

    PUR = x + y

    df_a['PUR'] = PUR
    df_b['PUR'] = PUR
</code>```

Title: How can I create binary label from two tables

Body:
I'm trying to analyse a trend in data that I have with Pandas. I have a two tables and I'd like to create a new binary column in one if the UID and PID in that row exists in the other table. An example of the tables I currently have would be:

>>> df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})
>>> df_a
   PID  TIM  UID
0   12   76  123
1   55   54  456
2   56   21  789
3   89   25  010

>>> df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})
>>> df_b
     FOO  PID  UID
0   2347   17  221
1  32447   89  010
2   3234   51  653
3   7999   55  456

And I'd like the end result to be:

>>> df_a
   PID  TIM  UID  PUR
0   12   76  123    0
1   55   54  456    1
2   56   21  789    0
3   89   25  010    1

But I'm not sure exactly how to go about doing this. I thought a left join would be the way to go but I'm having trouble pulling that off also. Any help would be appreciated

Body:
You can use numpy's in1d(). You can use it to implement in further cases too, where left join might fail

    import pandas as pd
    import numpy as np

    df_a = pd.DataFrame({"UID": [123, 456, 789, 012], "PID": [12, 55, 56, 89], "TIM": [76, 54, 21, 25]})

    df_b = pd.DataFrame({'UID': [221, 012, 653, 456], 'PID': [17, 89, 51, 55], 'FOO': [2347, 32447, 3234, 7999]})

    UID_a = df_a['UID'].values
    UID_b = df_b['UID'].values
    PID_a = df_a['PID'].values
    PID_b = df_b['PID'].values

    x = np.in1d(UID_a, UID_b)
    y = np.in1d(PID_a, PID_b)

    PUR = x + y

    df_a['PUR'] = PUR
    df_b['PUR'] = PUR


问:
html - size of ordered list numbers in front of linked list items on iPhone
I made a site that has an ordered list, for which some items on the list are links, and others are not. Everything renders fine on a PC. On my iPhone, however, the numbers in the ordered list show up smaller than they are supposed to if the list item is a link.

To make sure that it wasn't just some obscure issue with my particular html, css, etc., I made the following html document, called test_1.html:

```<code><!DOCTYPE html>
<html>
<head>
</head>
<body>
   <ol>
   <li>here.</li>
   <li><a href="test_1.html">here.</a></li>
   </ol>
</body>
</html>
</code>```

The issue persists even with this extremely minimal example.

Does anyone know how to fix this?

Thanks!

答:
I stumbled onto a fix for this issue here. The solution was the following CSS code:

```<code>body {
    -webkit-text-size-adjust: 100%;
}
</code>```

Incidentally, this also fixed an issue with the site on my iPhone where one of the fonts on the page would not always load at its assigned size, but would seemingly randomly change sizes sometimes when I refreshed the page. E.g., it would sometimes load at its assigned font-size: 34px;, but other times load at e.g., 14px.

Body:
I made a site that has an ordered list, for which some items on the list are links, and others are not. Everything renders fine on a PC. On my iPhone, however, the numbers in the ordered list show up smaller than they are supposed to if the list item is a link.

To make sure that it wasn't just some obscure issue with my particular html, css, etc., I made the following html document, called test_1.html:

<!DOCTYPE html>

here.

here.

The issue persists even with this extremely minimal example.

Does anyone know how to fix this?

Thanks!

Body:
I stumbled onto a fix for this issue here. The solution was the following CSS code:

body {
    -webkit-text-size-adjust: 100%;
}

Incidentally, this also fixed an issue with the site on my iPhone where one of the fonts on the page would not always load at its assigned size, but would seemingly randomly change sizes sometimes when I refreshed the page. E.g., it would sometimes load at its assigned font-size: 34px;, but other times load at e.g., 14px.


问:
Retrieve the first day of the last month for a given date
Given a string like 2016-05-25 I want to get the first day of the previous month (e.x 2016-04-01).

I have tried this

```<code>$month_ini = new DateTime("first day of last month");
$month_end = new DateTime("last day of last month");
</code>```

but I get the first day of the previous month relative with the current month, which is not what I want.

Specifically I will get random dates from clients (with format 'Y-m-d') and I have to display the first day of the previous months relative with the client's requested month.

答:
Pre-Request: System should be in UTC

```<code>$firstDayLastMonth = date('Y-m-d', strtotime('first day of last month'));
$lastDayLastMonth = date('Y-m-d', strtotime('last day of last month'));
echo $firstDayLastMonth .'<br>'. $lastDayLastMonth ;
</code>```

Body:
Given a string like 2016-05-25 I want to get the first day of the previous month (e.x 2016-04-01).

I have tried this

$month_ini = new DateTime("first day of last month");
$month_end = new DateTime("last day of last month");

but I get the first day of the previous month relative with the current month, which is not what I want.

Specifically I will get random dates from clients (with format 'Y-m-d') and I have to display the first day of the previous months relative with the client's requested month.

Body:
Pre-Request: System should be in UTC

$firstDayLastMonth = date('Y-m-d', strtotime('first day of last month'));
$lastDayLastMonth = date('Y-m-d', strtotime('last day of last month'));
echo $firstDayLastMonth .'<br>'. $lastDayLastMonth ;


问:
Environment properties not getting read in spring boot
I have a utility class to read the environment variables.

```<code>import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public final class PropertyUtil {

    /** The system environment. */
    private static Environment environment;

    public static String getConfigProp(final String key) {
        return environment.getProperty(key);
    }

    @Autowired
    public void setEnvironment(Environment environment) {
        PropertyUtil.environment = environment;
    }
}
</code>```

And I use it in one bean while initialization. The problem is that it runs file if I deploy the war file on tomcat but if I run the same application as a spring boot application from eclipse, it does not read the environment properties and the return values are therefore null.

Any idea what could be the cause of this problem?

答:
```<code>package com.myspringboot.controller;

import org.springframework.context.EnvironmentAware;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;
@Component
public final  class PropertyUtil  implements EnvironmentAware {

    /** The system environment. */
    public static  Environment environment;

    public static  String getConfigProp(String key) {
        return environment.getProperty(key);
    }
    @Override
    public void setEnvironment(Environment arg0) {
        if(environment==null){
            environment=arg0;
        }

    }
}
</code>```

Body:
I have a utility class to read the environment variables.

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.stereotype.Component;

@Component
public final class PropertyUtil {

    /** The system environment. */
    private static Environment environment;

    public static String getConfigProp(final String key) {
        return environment.getProperty(key);
    }

    @Autowired
    public void setEnvironment(Environment environment) {
        PropertyUtil.environment = environment;
    }
}

And I use it in one bean while initialization. The problem is that it runs file if I deploy the war file on tomcat but if I run the same application as a spring boot application from eclipse, it does not read the environment properties and the return values are therefore null.

Any idea what could be the cause of this problem?


问:
Jquery Datatables how to sort a custom formatted numeric column?
I have a column in a data table which renders numeric values as formatted currency values e.g "$5,66666.77 USD".
Here is the part of the Jquery table definition for this column,

```<code>            data: "amount",
            orderable: true,
            searchable: false,
            render: (data, type, row) => {
                var formattedAmount = "$" + data.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") + " " + "USD";
                return formattedAmount;
            }
</code>```

When I don't have the "USD" suffix it gets sorted correctly. But when I have USD it sorts like a string. Is there a work around for this? Can I define a different value for sort data?

I am using this the Typescript typings.

"data" attribute accepts ObjectColumnData, I tried to use this but it's not using the sort field I define.

```<code> interface ObjectColumnData {
        _: string;
        filter?: string;
        display?: string;
        type?: string;
        sort?: string;
    }
</code>```

Do I have to write a custom sort for this?

答:
You can return formatted value only when data would be displayed, otherwise you can return unformatted value for sorting, filtering or type detection.

For example, in JavaScript:

```<code>render: function(data, type, row){
    if(type === 'display'){
        data = "$" + data.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") + " " + "USD";
    }

    return data;
}
</code>```

Body:
I have a column in a data table which renders numeric values as formatted currency values e.g "$5,66666.77 USD".
Here is the part of the Jquery table definition for this column,

            data: "amount",
            orderable: true,
            searchable: false,
            render: (data, type, row) => {
                var formattedAmount = "$" + data.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") + " " + "USD";
                return formattedAmount;
            }

When I don't have the "USD" suffix it gets sorted correctly. But when I have USD it sorts like a string. Is there a work around for this? Can I define a different value for sort data?

I am using this the Typescript typings.

"data" attribute accepts ObjectColumnData, I tried to use this but it's not using the sort field I define.

 interface ObjectColumnData {
        _: string;
        filter?: string;
        display?: string;
        type?: string;
        sort?: string;
    }

Do I have to write a custom sort for this?

Body:
You can return formatted value only when data would be displayed, otherwise you can return unformatted value for sorting, filtering or type detection.

For example, in JavaScript:

render: function(data, type, row){
    if(type === 'display'){
        data = "$" + data.toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, "$1,") + " " + "USD";
    }

    return data;
}


问:
JSLint - Unexpected '\' before '.'
I am getting the following warning in JSLint for my regex expression.

```<code>Unexpected '\' before '.'.
var regexForEmail = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;
</code>```

Can someone help me how to fix it or is there any other way to suppress the warning?

Thanks in advance

Dinesh.

答:
. doesn't have special meaning when it's inside square brackets, so there's no need to escape it there. " has no special meaning at all in regular expressions, so you never need to escape it.

```<code>var regexForEmail = /^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()\[\].,;:\s@"]+\.)+[^<>()\[\].,;:\s@"]{2,})$/i;
</code>```

The only characters that are special inside square brackets are backslash, hyphen, right square bracket, and caret at the beginning.

See What special characters must be escaped in regular expressions?

Title: JSLint - Unexpected '\' before '.'

Body:
I am getting the following warning in JSLint for my regex expression.

Unexpected '\' before '.'.
var regexForEmail = /^(([^<>()\[\]\.,;:\s@\"]+(\.[^<>()\[\]\.,;:\s@\"]+)*)|(\".+\"))@(([^<>()[\]\.,;:\s@\"]+\.)+[^<>()[\]\.,;:\s@\"]{2,})$/i;

Can someone help me how to fix it or is there any other way to suppress the warning?

Thanks in advance

Dinesh.

Body:
. doesn't have special meaning when it's inside square brackets, so there's no need to escape it there. " has no special meaning at all in regular expressions, so you never need to escape it.

var regexForEmail = /^(([^<>()\[\].,;:\s@"]+(\.[^<>()\[\].,;:\s@"]+)*)|(".+"))@(([^<>()\[\].,;:\s@"]+\.)+[^<>()\[\].,;:\s@"]{2,})$/i;

The only characters that are special inside square brackets are backslash, hyphen, right square bracket, and caret at the beginning.

See What special characters must be escaped in regular expressions?


问:
android studio designer preview: how to include device frame?
There seems to be tons of answers to the opposite question "how to remove device frame" which instructs user to click the "settings" button inside preview to uncheck "include device frame (if available)". But for me using 2.2.2 on a mac and 2.2.1 earlier, such a button with that option never was available. Out of the box (dmg) Android Studio Designer always only shows the viewport without any device frame.

This explanation of the Designer settings suggests that option is only available if "include device frame" option is selected, but for me that is a chicken & egg issue. I'm using the default Nexus 6P AVD which already has "enable device frame" selected. The only settings button I see (which is outside the preview pane, not inside) only shows these options.

How can I make the device frame show? Thanks

答:
In Android Studio 2.2 and above you can enable and disable designer preview device frame as follows

1- Click on designer preview window

2 - press F button from your keyboard

this will enable and disable the designer preview device frame every time you press F button from your keyboard. this works for me. I hope its work for you as well.

It does not work with latest version of Android Studio 3.1


问:
How to set .htaccess so link in side html file will read from a base directory
Right now, I have put my html files under public/views folder,
libraries under public/libs, and customized files in public/src

I am using the DictoryIndex to set the default home page. Like DirectoryIndex public/views/index.html

but inside the index.html file, I have to use  to open the file under the same directory as the index.html, otherwise it could not find the file. And then the URL will look ugly, like site.com/public/views/product.html.

Can I ask, how could I set the .htaccess file to get rid of the public/views in the URL address?

One more question, when i write the code to import the libraries in index.html, it seems like it will read from the base folder (like where I put the .htaccess file). But in the other html files, they will read from their own directory, like the html file in public/view will start to read from folder views. Is there anyway to solve this problem?

Thank you

答:
Do you need to access your libs and custom files through HTTP too? If not, just set your document root to public/views

Otherwise, you could rewrite *.html to public/views using something like

```<code>Options +FollowSymLinks -Multiviews

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule (.+\.html)$ /public/views/$1 [L]
</code>```

Anyway, using a fullpath instead of just a filename in the DirectoryIndex directive is not a good idea, for obvious reasons.

It also solves your second issue. For now, public/views/index.html is considered as / so anything relative to this file is relative to /, not the views folder. On the other hand, any other file is still considered as "itself", therefore includes are relative to the views folder.

Body:
Do you need to access your libs and custom files through HTTP too? If not, just set your document root to public/views

Otherwise, you could rewrite *.html to public/views using something like

Options +FollowSymLinks -Multiviews

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-s
RewriteRule (.+\.html)$ /public/views/$1 [L]

Anyway, using a fullpath instead of just a filename in the DirectoryIndex directive is not a good idea, for obvious reasons.

It also solves your second issue. For now, public/views/index.html is considered as / so anything relative to this file is relative to /, not the views folder. On the other hand, any other file is still considered as "itself", therefore includes are relative to the views folder.


问:
Add values inside the Java while loop and stop it using a sentinel
I want to make a loop where the user inputs multiple values and when they want to stop input their values they input -1. I know it has to use a sentinel but I don't know how.</p>

```<code>Scanner myInput = new Scanner(System.in);
int total = 0;
int count = 0;

while(values >= 0)
{
    int values;
    total += values;
    count ++;

    System.out.println("Please input your value, type - 1 to stop entering values.");
    values = myInput.nextInt();
}

System.out.println ("The sum of all your values is " + total);
</code>```

答:
I think your main problem is that values is declared inside the while loop. Try putting the declaration before the loop.

```<code>int values = 0;
while(values >= 0)
{
    ...
}
</code>```

Body:
I want to make a loop where the user inputs multiple values and when they want to stop input their values they input -1. I know it has to use a sentinel but I don't know how.

Scanner myInput = new Scanner(System.in);
int total = 0;
int count = 0;

while(values >= 0)
{
    int values;
    total += values;
    count ++;

    System.out.println("Please input your value, type - 1 to stop entering values.");
    values = myInput.nextInt();
}

System.out.println ("The sum of all your values is " + total);

Body:
I think your main problem is that values is declared inside the while loop. Try putting the declaration before the loop.

int values = 0;
while(values >= 0)
{
    ...
}


问:
How to know if lazy loading worked via hibernate mapping?
I have a Person object with 5 columns and i used following properties:

```<code> property name="firstName" column="FirstName" type="string" lazy="false"
 property name="lastName" column="LastName" type="string" lazy="true"
 property name="city" column="City" type="string" lazy="true"
 property name="country" column="Country" type="string" lazy="true"
 property name="phone" column="Phone" type="string" lazy="true"
</code>```

Now how do i find out if the object i get back using "From Person" contains only rows of data with the FIRSTNAME within it - assuming the other 4 are lazy loaded. I tried debugger but when i dive in i see all values has already been there... is there something missing? thanks

答:
This might be helpful :When asked to load a lazy field, Hibernate loads all lazy fields

But, I thing it will not improve performance significantly, if it is a goal, unless you have hundreds of columns in the table. Leazy loading makes a big difference when featching collections.

Body:
I have a Person object with 5 columns and i used following properties:

 property name="firstName" column="FirstName" type="string" lazy="false"
 property name="lastName" column="LastName" type="string" lazy="true"
 property name="city" column="City" type="string" lazy="true"
 property name="country" column="Country" type="string" lazy="true"
 property name="phone" column="Phone" type="string" lazy="true"

Now how do i find out if the object i get back using "From Person" contains only rows of data with the FIRSTNAME within it - assuming the other 4 are lazy loaded. I tried debugger but when i dive in i see all values has already been there... is there something missing? thanks


问:
DC.js numberDisplay with crossfilter get total records
I am trying to understand how to use crossfilter with dc.js. I have the following data and I would just like to start by populating a numberDisplay with the total number of objects within the data. Then secondly populating how many records there are for bills losses.

```<code>var data = [
  {
    "team": "bills",
    "location": "home",
    "outcome": "loss"
  },
  {
    "team": "dolphins",
    "location": "away",
    "outcome": "loss"
  },
  {
    "team": "jets",
    "location": "home",
    "outcome": "loss"
  },
  {
    "team": "jets",
    "location": "home",
    "outcome": "win"
  },
  {
    "team": "dolphins",
    "location": "home",
    "outcome": "loss"
  },
  {
    "team": "dolphins",
    "location": "away",
    "outcome": "win"
  },
  {
    "team": "dolphins",
    "location": "home",
    "outcome": "win"
  },
  {
    "team": "dolphins",
    "location": "away",
    "outcome": "loss"
  }
]
</code>```

DC.JS numberDisplay takes a group but I have not been able to figure out how to simply count the number of records to start with.

```<code>var cf = crossfilter(data);
var team = cf.dimension(function(d) { return d.team })
var teams = team.group().reduceCount();
</code>```

this seems to only return the value for the first key? reduceSum() and groupAll() haven't worked either.

```<code>var numberDisplayElem = dc.numberDisplay("#number-display-elem");
    numberDisplayElem
        .group(teams);
</code>```

Basically just trying to get the total to populate the numberDisplay, and then a single numberBack of filtered values like total bills losses, etc. Having trouble getting started. TIA.

答:
An ordinary crossfilter group has multiple bins based on the key function.

If you want to count all the records without binning them, try using a groupAll instead:

```<code>var numRecords = cf.groupAll();
numberDisplayElem
  .group(numRecords)
  .valueAccessor(x => x);
</code>```

Body:
I am trying to understand how to use crossfilter with dc.js. I have the following data and I would just like to start by populating a numberDisplay with the total number of objects within the data. Then secondly populating how many records there are for bills losses.

var data = [
  {
    "team": "bills",
    "location": "home",
    "outcome": "loss"
  },
  {
    "team": "dolphins",
    "location": "away",
    "outcome": "loss"
  },
  {
    "team": "jets",
    "location": "home",
    "outcome": "loss"
  },
  {
    "team": "jets",
    "location": "home",
    "outcome": "win"
  },
  {
    "team": "dolphins",
    "location": "home",
    "outcome": "loss"
  },
  {
    "team": "dolphins",
    "location": "away",
    "outcome": "win"
  },
  {
    "team": "dolphins",
    "location": "home",
    "outcome": "win"
  },
  {
    "team": "dolphins",
    "location": "away",
    "outcome": "loss"
  }
]

DC.JS numberDisplay takes a group but I have not been able to figure out how to simply count the number of records to start with.

var cf = crossfilter(data);
var team = cf.dimension(function(d) { return d.team })
var teams = team.group().reduceCount();

this seems to only return the value for the first key? reduceSum() and groupAll() haven't worked either.

var numberDisplayElem = dc.numberDisplay("#number-display-elem");
    numberDisplayElem
        .group(teams);

Basically just trying to get the total to populate the numberDisplay, and then a single numberBack of filtered values like total bills losses, etc. Having trouble getting started. TIA.

Body:
An ordinary crossfilter group has multiple bins based on the key function.

If you want to count all the records without binning them, try using a groupAll instead:

var numRecords = cf.groupAll();
numberDisplayElem
  .group(numRecords)
  .valueAccessor(x => x);


问:
How do I import a JSON string into R as a dataframe when vectors in the JSON are different lengths?
I have the following JSON stored locally on my PC.

```<code>{
     "modprod": "1",
     "values": ["top opt", "5 adjustable shelves", "stl top", "gls door", "Bookcase"],
     "common": ["lam top", "wood top"]
}
</code>```

I want to read this into R as a dataframe that looks like...

```<code>modprod,feature,common
1,top_opt,0
1,5 adjustable shelves,0
1,stl top,0
1,gls door,0
1,bookcase,0
1,lam top,1
1,wood top,1
</code>```

I have searched extensively on Stack Overflow, but can find no solution. The problems I'm running into:

Obviously the lengths of "modprod", "values", and "common" are all different. In this case there is one entry for "modprod", five entries for "values", and two entries for "common".

I believe I have demonstrated exactly the starting and ending points. Can someone help me please?

答:
```<code>library(jsonlite)
library(purrr)
library(dplyr)

fromJSON('{
     "modprod": "1",
     "values": ["top opt", "5 adjustable shelves", "stl top", "gls door", "Bookcase"],
     "common": ["lam top", "wood top"]
}') -> js

data_frame(
  modprod = rep(js$modprod, length(js$values) + length(js$common)),
  feature = c(js$values, js$common),
  common = c(rep(0, length(js$values)), rep(1, length(js$common)))
)
## # A tibble: 7 × 3
##   modprod              feature common
##     <chr>                <chr>  <dbl>
## 1       1              top opt      0
## 2       1 5 adjustable shelves      0
## 3       1              stl top      0
## 4       1             gls door      0
## 5       1             Bookcase      0
## 6       1              lam top      1
## 7       1             wood top      1
</code>```

but you shld consider being clearer in your question and add a larger example

Body:
I have the following JSON stored locally on my PC.

{
     "modprod": "1",
     "values": ["top opt", "5 adjustable shelves", "stl top", "gls door", "Bookcase"],
     "common": ["lam top", "wood top"]
}

I want to read this into R as a dataframe that looks like...

modprod,feature,common
1,top_opt,0
1,5 adjustable shelves,0
1,stl top,0
1,gls door,0
1,bookcase,0
1,lam top,1
1,wood top,1

I have searched extensively on Stack Overflow, but can find no solution. The problems I'm running into:

Obviously the lengths of "modprod", "values", and "common" are all different. In this case there is one entry for "modprod", five entries for "values", and two entries for "common".

I believe I have demonstrated exactly the starting and ending points. Can someone help me please?

Body:
library(jsonlite)
library(purrr)
library(dplyr)

fromJSON('{
     "modprod": "1",
     "values": ["top opt", "5 adjustable shelves", "stl top", "gls door", "Bookcase"],
     "common": ["lam top", "wood top"]
}') -> js

data_frame(
  modprod = rep(js$modprod, length(js$values) + length(js$common)),
  feature = c(js$values, js$common),
  common = c(rep(0, length(js$values)), rep(1, length(js$common)))
)
## # A tibble: 7 × 3
##   modprod              feature common
##     <chr>                <chr>  <dbl>
## 1       1              top opt      0
## 2       1 5 adjustable shelves      0
## 3       1              stl top      0
## 4       1             gls door      0
## 5       1             Bookcase      0
## 6       1              lam top      1
## 7       1             wood top      1

but you shld consider being clearer in your question and add a larger example


问:
$ionicLoading.hide() not working
I have this Ionic code. The problem is    $ionicLoading.hide();  is not hiding the popup. I cant make the "waiting" icon Disappear

function ($scope, $q, $state, $rootScope, $stateParams, $firebaseArray, $window, $ionicLoading) {

```<code>var palabras =  $rootScope.textAreaOfrecer.replace(/[.#$/]/g,'').toLowerCase().split(' ');

if($rootScope.flag == 1){
    return true;
}else{
    $rootScope.flag = 1;
}

console.log("0");

$ionicLoading.show();

setMyNewArray().then( function (){

                        console.log("3");
                        $ionicLoading.hide();
                        $rootScope.flag = 0;
                        console.log("4");
                    });

 function setMyNewArray() {

        var deferred = $q.defer();

          console.log("1");

          Promise.all(
                $scope.solicitudes = palabras.map(palabra => $firebaseArray(firebase.database().ref().child("solCompras").orderByChild("palabras/" +
                                            palabra).equalTo(true) ) )
                ).then( function (){

                                   $scope.solicitudes = multiDimensionalUnique($scope.solicitudes).reduce(function(prev, curr) {

                                       return prev.concat(curr);
                                   });

                                    console.log("2");

                                    deferred.resolve();

                        });

       return deferred.promise;

 }

        function multiDimensionalUnique(arr) {
            var uniques = [];
            var itemsFound = {};
            for(var i = 0, l = arr.length; i < l; i++) {
                var stringified = JSON.stringify(arr[i]);
                if(itemsFound[stringified]) { continue; }
                uniques.push(arr[i]);
                itemsFound[stringified] = true;
            }
            return uniques;
        }
</code>```

}

答:
I have changed location of show loader and hide loader.. try it once </p>

```<code> function ($scope, $q, $state, $rootScope, $stateParams, $firebaseArray, $window, $ionicLoading) {

    var palabras =  $rootScope.textAreaOfrecer.replace(/[.#$/]/g,'').toLowerCase().split(' ');

    if($rootScope.flag == 1){
        return true;
    }else{
        $rootScope.flag = 1;
    }

    console.log("0");

    setMyNewArray().then( function (){

                            console.log("3");

                            $rootScope.flag = 0;
                            console.log("4");
                            $ionicLoading.hide();  //use hide here
                        });

     function setMyNewArray() {

           $ionicLoading.show();   //use loader here.

            var deferred = $q.defer();

              console.log("1");

              Promise.all(
                    $scope.solicitudes = palabras.map(palabra => $firebaseArray(firebase.database().ref().child("solCompras").orderByChild("palabras/" +
                                                palabra).equalTo(true) ) )
                    ).then( function (){

                                       $scope.solicitudes = multiDimensionalUnique($scope.solicitudes).reduce(function(prev, curr) {

                                           return prev.concat(curr);
                                       });

                                        console.log("2");

                                        deferred.resolve();

                            });

           return deferred.promise;

     }

            function multiDimensionalUnique(arr) {
                var uniques = [];
                var itemsFound = {};
                for(var i = 0, l = arr.length; i < l; i++) {
                    var stringified = JSON.stringify(arr[i]);
                    if(itemsFound[stringified]) { continue; }
                    uniques.push(arr[i]);
                    itemsFound[stringified] = true;
                }
                return uniques;
            }
    }
</code>```

Title: $ionicLoading.hide() not working

Body:
I have this Ionic code. The problem is    $ionicLoading.hide();  is not hiding the popup. I cant make the "waiting" icon Disappear

function ($scope, $q, $state, $rootScope, $stateParams, $firebaseArray, $window, $ionicLoading) {

var palabras =  $rootScope.textAreaOfrecer.replace(/[.#$/]/g,'').toLowerCase().split(' ');

if($rootScope.flag == 1){
    return true;
}else{
    $rootScope.flag = 1;
}

console.log("0");

$ionicLoading.show();

setMyNewArray().then( function (){

                        console.log("3");
                        $ionicLoading.hide();
                        $rootScope.flag = 0;
                        console.log("4");
                    });

 function setMyNewArray() {

        var deferred = $q.defer();

          console.log("1");

          Promise.all(
                $scope.solicitudes = palabras.map(palabra => $firebaseArray(firebase.database().ref().child("solCompras").orderByChild("palabras/" +
                                            palabra).equalTo(true) ) )
                ).then( function (){

                                   $scope.solicitudes = multiDimensionalUnique($scope.solicitudes).reduce(function(prev, curr) {

                                       return prev.concat(curr);
                                   });

                                    console.log("2");

                                    deferred.resolve();

                        });

       return deferred.promise;

 }

        function multiDimensionalUnique(arr) {
            var uniques = [];
            var itemsFound = {};
            for(var i = 0, l = arr.length; i < l; i++) {
                var stringified = JSON.stringify(arr[i]);
                if(itemsFound[stringified]) { continue; }
                uniques.push(arr[i]);
                itemsFound[stringified] = true;
            }
            return uniques;
        }

}

Body:
I have changed location of show loader and hide loader.. try it once

 function ($scope, $q, $state, $rootScope, $stateParams, $firebaseArray, $window, $ionicLoading) {

    var palabras =  $rootScope.textAreaOfrecer.replace(/[.#$/]/g,'').toLowerCase().split(' ');

    if($rootScope.flag == 1){
        return true;
    }else{
        $rootScope.flag = 1;
    }

    console.log("0");

    setMyNewArray().then( function (){

                            console.log("3");

                            $rootScope.flag = 0;
                            console.log("4");
                            $ionicLoading.hide();  //use hide here
                        });

     function setMyNewArray() {

           $ionicLoading.show();   //use loader here.

            var deferred = $q.defer();

              console.log("1");

              Promise.all(
                    $scope.solicitudes = palabras.map(palabra => $firebaseArray(firebase.database().ref().child("solCompras").orderByChild("palabras/" +
                                                palabra).equalTo(true) ) )
                    ).then( function (){

                                       $scope.solicitudes = multiDimensionalUnique($scope.solicitudes).reduce(function(prev, curr) {

                                           return prev.concat(curr);
                                       });

                                        console.log("2");

                                        deferred.resolve();

                            });

           return deferred.promise;

     }

            function multiDimensionalUnique(arr) {
                var uniques = [];
                var itemsFound = {};
                for(var i = 0, l = arr.length; i < l; i++) {
                    var stringified = JSON.stringify(arr[i]);
                    if(itemsFound[stringified]) { continue; }
                    uniques.push(arr[i]);
                    itemsFound[stringified] = true;
                }
                return uniques;
            }
    }


问:
question on displaying UIProgressView in each table cell
I'm trying to upload a few files to a server. The files are listed on the UItableview. My question is:

What should i do to display UIProgressView in each table cell and show the progress of each file being uploaded.

My current code is able to show the UIProgressView in each cell but when i try to upload, the progress bar did not move. The program is suppose to upload 1 file at a time which after the first file is completed, the second will start to upload. In response, when the first file is done, the progress bar of the first file will stop and the progress bar for the secong file will start to move. Hope this is clear. I really need some help on this and i can't find it on the web.Thanks in advance. Thanks

答:
You will have to maintain the progress value of each cell in an array.

I guess you must be setting the progress value of UIProgressView object at cellForRowAtIndexPath method, so you need to call [self.tableView reloadData] whenever you get callback from you network code which is uploading file to server with current upload size...


问:
Trouble fixing an image to the top of a bootstrap navbar
Alright, so I'm having some absolute positioning issues here.

This is what I'm trying to accomplish.

If you look closely at the top of this black nav there is a transparent brush effect that is accomplished by black brush stroke PNG. Which I've situated within it's own div. All I'm trying to do is fix this div on top of the default black bootstrap navbar.

To do this I used absolute positioning relative to the a div that wraps around the navbar (which it is relative to)

, but I'm having weird issues pop up like the overflow hidden not working. Can someone look at my code and tell me what I'm doing wrong? Thanks.

HTML

```<code>  <nav class="navbar navbar-inverse">

    <div class="container-fluid">

      <div class="navbar-header">

      <!-- BrushStroke PNG Shit -->

      <div class="img-wrap">
        <img class="image-responsive black-brush" src="img/blackbrushnew.png">
      </div>

    <!-- BrushStroke PNG Shit -->

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
          <span class="icon-bar"></span>
        </button>
        <a class="navbar-brand" href="#">Italian Joe's</a>
        <p class="navbar-text text-center" id="NavHours" style="color:white; width: 230px;"> Open 6am to 5pm </p>
      </div>

      <div class="collapse navbar-collapse" id="myNavbar">

        <ul class="nav navbar-nav navbar-right">
          <li id="Home" class="active"><a href="#">Home</a></li>
          <li><a href="#">Menu</a></li>
          <li><a href="#">About</a></li>
          <li id="location"><a href="#">Location</a></li>
        </ul>
      </div>
    </div>
  </nav>
</div>

  <!-- End Navbar -->
</code>```

CSS

```<code>.blackbrush{
            position: absolute;
            top: -135%;
            text-align: center;
            margin: 0 -1000px;
            z-index: 100;
            mix-blend-mode: multiply;
                }
.img-wrap {
  overflow: hidden;
}
</code>```

答:
Add a class to your navbar-header div. say some xyz class
then add your backgound image like below

```<code> .xyz
 {
  background-image:url('img/blackbrushnew.png');
 }
</code>```

Delete your div with the img-wrap class.

Body:
Alright, so I'm having some absolute positioning issues here.

This is what I'm trying to accomplish.

If you look closely at the top of this black nav there is a transparent brush effect that is accomplished by black brush stroke PNG. Which I've situated within it's own div. All I'm trying to do is fix this div on top of the default black bootstrap navbar.

To do this I used absolute positioning relative to the a div that wraps around the navbar (which it is relative to)

, but I'm having weird issues pop up like the overflow hidden not working. Can someone look at my code and tell me what I'm doing wrong? Thanks.

HTML

        <button type="button" class="navbar-toggle" data-toggle="collapse" data-target="#myNavbar">

        </button>
        Italian Joe's

 Open 6am to 5pm

Home

Menu

About

Location

CSS

.blackbrush{
            position: absolute;
            top: -135%;
            text-align: center;
            margin: 0 -1000px;
            z-index: 100;
            mix-blend-mode: multiply;
                }
.img-wrap {
  overflow: hidden;
}

Body:
Add a class to your navbar-header div. say some xyz class
then add your backgound image like below

 .xyz
 {
  background-image:url('img/blackbrushnew.png');
 }

Delete your div with the img-wrap class.


问:
How do I access a struct nested inside a struct
I've created a struct with another struct nested inside of it, like this:

```<code>struct Theme {
    var ID: Int
    var name: String
    struct color {
        var tint: String
        var tintDisabled: String
        var accent: String
        var background: String
        var items: [String]
    }
}
</code>```

I thought I'd be able to address the "tint" item like this:

```<code>aTheme.color.tint
</code>```

But aTheme doesn't have a member "color".

How can I get at it? Or is this just no-go and I should use a different structure?

答: Updated: with Swift 3.1 you can use nested type with Struct.

Body:
I've created a struct with another struct nested inside of it, like this:

struct Theme {
    var ID: Int
    var name: String
    struct color {
        var tint: String
        var tintDisabled: String
        var accent: String
        var background: String
        var items: [String]
    }
}

I thought I'd be able to address the "tint" item like this:

aTheme.color.tint

But aTheme doesn't have a member "color".

How can I get at it? Or is this just no-go and I should use a different structure?


问:
Natural Feature Tracking - augmented reality
I want to build an app for Google Android that uses natural feature tracking to create some cool augmented reality. Now what I need is a good library that for Android that does some serious natural feature tracking.

Can anyone help me out?

Thanks you.

答: It looks like the windage project might be close to what you need. The project is GPL and not so nasty about distribution. As far as an Android port, that is another matter altogether.</p>


问:
Volley UnknownHostExeption
I have a problem with using Volley. I'm trying to send request to site  http://lawbite_api.codebnb.me but results differ from phone to phone (depends on Android version). For some reason on Android 6 all OK, but on Android 4.4 I'm getting java.net.UnknownHostException.

Here is stacktrace:

```<code> com.android.volley.NoConnectionError: java.net.UnknownHostException: http://lawbite_api.codebnb.me/api/login
 at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:151)
 at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
 Caused by: java.net.UnknownHostException: http://lawbite_api.codebnb.me/api/login
 at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:279)
 at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
 at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
 at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
 at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
 at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
 at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:264)
 at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
 at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
 at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)
</code>```

答: I don't think url will change as per API level in Volley. I have already use same URL for all devices with API greater than Android 4.4 and there is no issue regarding to URL there is something else. Please provide Volley request code</p>

Title: Volley UnknownHostExeption

Body:
I have a problem with using Volley. I'm trying to send request to site  http://lawbite_api.codebnb.me but results differ from phone to phone (depends on Android version). For some reason on Android 6 all OK, but on Android 4.4 I'm getting java.net.UnknownHostException.

Here is stacktrace:

 com.android.volley.NoConnectionError: java.net.UnknownHostException: http://lawbite_api.codebnb.me/api/login
 at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:151)
 at com.android.volley.NetworkDispatcher.run(NetworkDispatcher.java:112)
 Caused by: java.net.UnknownHostException: http://lawbite_api.codebnb.me/api/login
 at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:279)
 at com.android.okhttp.internal.http.HttpEngine.sendSocketRequest(HttpEngine.java:255)
 at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:206)
 at com.android.okhttp.internal.http.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:345)
 at com.android.okhttp.internal.http.HttpURLConnectionImpl.connect(HttpURLConnectionImpl.java:89)
 at com.android.okhttp.internal.http.HttpURLConnectionImpl.getOutputStream(HttpURLConnectionImpl.java:197)
 at com.android.volley.toolbox.HurlStack.addBodyIfExists(HurlStack.java:264)
 at com.android.volley.toolbox.HurlStack.setConnectionParametersForRequest(HurlStack.java:234)
 at com.android.volley.toolbox.HurlStack.performRequest(HurlStack.java:107)
 at com.android.volley.toolbox.BasicNetwork.performRequest(BasicNetwork.java:96)


问:
Segmentation fault in conversion operator (reference to member)
Why is this causing segmentation fault?

```<code>#include <iostream>

struct A
{
    std::string str;

    A(std::string const& pstr) : str(pstr)
    {}

    operator std::string const&() const { return str; }
};

bool operator==(A const& a, A const& b)
{ return std::string(a) == b; }

int main()
{
    A a1("hola"), a2("adios");

    std::cout << (a1 == a2) << std::endl;

    return 0;
}
</code>```

After all, the member str is still alive when doing the conversion.

http://coliru.stacked-crooked.com/a/e7453471bc1af93e

答:
Just edited your code and it worked for me:</p>

```<code>return std::string(a) == std::string(b);
</code>```

Body:
Why is this causing segmentation fault?

#include <iostream>

struct A
{
    std::string str;

    A(std::string const& pstr) : str(pstr)
    {}

    operator std::string const&() const { return str; }
};

bool operator==(A const& a, A const& b)
{ return std::string(a) == b; }

int main()
{
    A a1("hola"), a2("adios");

    std::cout << (a1 == a2) << std::endl;

    return 0;
}

After all, the member str is still alive when doing the conversion.

http://coliru.stacked-crooked.com/a/e7453471bc1af93e

Body:
Just edited your code and it worked for me:

return std::string(a) == std::string(b);


答: You have an recursive call to your operator==. Your constructor of A defines an implicit cast of string to A. To not allow that, add explicit to the constructor, but then you are missing a operator== for string and A;

Title: Segmentation fault in conversion operator (reference to member)