问:
System font "Hiragino Sans" is show with clipped ascender and descenders
I need to use the iOS's system font "Hiragino Sans W3" in my app, but no matter which size/style or the UILabel's dimensions I choose, the font's ascenders and descenders always appear clipped:

It seems that this can this fixed by creating a subclass of UILabel and overwriting method textRectForBounds:limitedToNumberOfLines: to return the "correct" value. So the following code...

```<code>- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
    CGRect result = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    result = CGRectInset(result, 0, -5);
    return result;
}
</code>```

...results in both the ascender and descenders not being clipped anymore:

I know it's also possible to adjust font ascender and descender positions using an external editor. But this is a system font, shouldn't it work correctly without any modifications? Is there something I'm missing here?

Thanks in advance for any answers.

答:
I think this issue really boils down to the font itself ("Hiragino Sans"). Using a font editor it is possible to see that the glyphs go beyond the ascender and descender values, which is what iOS seems to assume as the vertical "bounding box" for displayed text.

For the lack of a better solution, I've been using a (pretty ugly) hack which modifies the values for UIFont read-only properties ascender and lineHeight.

File UIFont+Alignment.h:

```<code>#import <UIKit/UIKit.h>

@interface UIFont (Alignment)

- (void)ensureCorrectFontAlignment;

@end
</code>```

File UIFont+Alignment.m:

```<code>#import "UIFont+Alignment.h"
#import <objc/runtime.h>
#import <objc/message.h>

static NSHashTable *adjustedFontsList;

@implementation UIFont (Alignment)

- (void)ensureCorrectFontAlignment
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        adjustedFontsList = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory];
    });

    @synchronized (adjustedFontsList) {

        if ([adjustedFontsList containsObject:self]) {
            return;
        }
        else if ([self.fontName containsString:@"Hiragino"]) {

            SEL originalAscenderSelector = @selector(ascender);
            Method originalAscenderMethod = class_getInstanceMethod([UIFont class], originalAscenderSelector);
            SEL originalLineHeightSelector = @selector(lineHeight);
            Method originalLineHeightMethod = class_getInstanceMethod([UIFont class], originalLineHeightSelector);

            id result = method_invoke(self, originalAscenderMethod, nil);
            CGFloat originalValue = [[result valueForKey:@"ascender"] floatValue];
            [result setValue:@(originalValue * 1.15) forKey:@"ascender"];

            result = method_invoke(self, originalLineHeightMethod, nil);
            originalValue = [[result valueForKey:@"lineHeight"] floatValue];
            [result setValue:@(originalValue * 1.25) forKey:@"lineHeight"];

            [adjustedFontsList addObject:self];
        }
    }
}

@end
</code>```

To apply, just import the header and invoke [myUIFont ensureCorrectFontAlignment] after creating a new font instance.

Body:
I need to use the iOS's system font "Hiragino Sans W3" in my app, but no matter which size/style or the UILabel's dimensions I choose, the font's ascenders and descenders always appear clipped:

It seems that this can this fixed by creating a subclass of UILabel and overwriting method textRectForBounds:limitedToNumberOfLines: to return the "correct" value. So the following code...

- (CGRect)textRectForBounds:(CGRect)bounds limitedToNumberOfLines:(NSInteger)numberOfLines
{
    CGRect result = [super textRectForBounds:bounds limitedToNumberOfLines:numberOfLines];
    result = CGRectInset(result, 0, -5);
    return result;
}

...results in both the ascender and descenders not being clipped anymore:

I know it's also possible to adjust font ascender and descender positions using an external editor. But this is a system font, shouldn't it work correctly without any modifications? Is there something I'm missing here?

Thanks in advance for any answers.

Body:
I think this issue really boils down to the font itself ("Hiragino Sans"). Using a font editor it is possible to see that the glyphs go beyond the ascender and descender values, which is what iOS seems to assume as the vertical "bounding box" for displayed text.

For the lack of a better solution, I've been using a (pretty ugly) hack which modifies the values for UIFont read-only properties ascender and lineHeight.

File UIFont+Alignment.h:

#import <UIKit/UIKit.h>

@interface UIFont (Alignment)

- (void)ensureCorrectFontAlignment;

@end

File UIFont+Alignment.m:

#import "UIFont+Alignment.h"
#import <objc/runtime.h>
#import <objc/message.h>

static NSHashTable *adjustedFontsList;

@implementation UIFont (Alignment)

- (void)ensureCorrectFontAlignment
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        adjustedFontsList = [NSHashTable hashTableWithOptions:NSHashTableWeakMemory];
    });

    @synchronized (adjustedFontsList) {

        if ([adjustedFontsList containsObject:self]) {
            return;
        }
        else if ([self.fontName containsString:@"Hiragino"]) {

            SEL originalAscenderSelector = @selector(ascender);
            Method originalAscenderMethod = class_getInstanceMethod([UIFont class], originalAscenderSelector);
            SEL originalLineHeightSelector = @selector(lineHeight);
            Method originalLineHeightMethod = class_getInstanceMethod([UIFont class], originalLineHeightSelector);

            id result = method_invoke(self, originalAscenderMethod, nil);
            CGFloat originalValue = [[result valueForKey:@"ascender"] floatValue];
            [result setValue:@(originalValue * 1.15) forKey:@"ascender"];

            result = method_invoke(self, originalLineHeightMethod, nil);
            originalValue = [[result valueForKey:@"lineHeight"] floatValue];
            [result setValue:@(originalValue * 1.25) forKey:@"lineHeight"];

            [adjustedFontsList addObject:self];
        }
    }
}

@end

To apply, just import the header and invoke [myUIFont ensureCorrectFontAlignment] after creating a new font instance.


来源: stackexchange

问:
What is the meaning of data_shape in CSVIter of MXNet
if I have a input matrix of 400 rows with 20 features and I have 10 labels then what should be my data_shape and label_shape tuples</p>

答:
Each row of your input CSV file can be viewed as a vector and it will be reshaped into the data_shape. So, if a row in an input file is 1,2,3,4,5,6 and data_shape is (3,2), that row will be reshaped, yielding the array [[1,2],[3,4],[5,6]] of shape (3,2).

You can see CSVIter doc for more details.

ContentLicense: CC BY-SA 3.0


问:
Firebase Android retrieve specific child
My firebase looks like this

I have this code to retrieve my data and it does print out all my data in my logcat here , but I only want to grab (Annotation_City:) and print it to the device.  I've tried other stack questions and answers but still haven't figured it out :) thank you if you can help! :)

```<code>public void AllLocationMarkers() {
        grabMarkersFromDb = new Firebase("***");
        grabMarkersFromDb.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                    String location = locationSnapshot.getValue().toString();
                    Log.d("Locations updated", "location: " + location + "-----------------------------------------------------------------------------------------------------");
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

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

答:
To solve this, change this line:

```<code>String location = locationSnapshot.getValue().toString();
</code>```

with this:

```<code>String location = (String) locationSnapshot.child("Annotation_City").getValue();
</code>```

Hope it helps.

Body:
My firebase looks like this

I have this code to retrieve my data and it does print out all my data in my logcat here , but I only want to grab (Annotation_City:) and print it to the device.  I've tried other stack questions and answers but still haven't figured it out :) thank you if you can help! :)

public void AllLocationMarkers() {
        grabMarkersFromDb = new Firebase("***");
        grabMarkersFromDb.addValueEventListener(new ValueEventListener() {
            @Override
            public void onDataChange(DataSnapshot dataSnapshot) {
                for (DataSnapshot locationSnapshot : dataSnapshot.getChildren()) {
                    String location = locationSnapshot.getValue().toString();
                    Log.d("Locations updated", "location: " + location + "-----------------------------------------------------------------------------------------------------");
                }
            }

            @Override
            public void onCancelled(FirebaseError firebaseError) {

            }
        });
    }

Body:
To solve this, change this line:

String location = locationSnapshot.getValue().toString();

with this:

String location = (String) locationSnapshot.child("Annotation_City").getValue();

Hope it helps.


问:
How to print matrix values in octave using printf
Suppose I have a matrix A=[1,2] if I try to print it with command

```<code>fprintf("A ", A)
</code>```

Output

```<code>A
</code>```

Blank A is printed without values?

答:
It's:

```<code>fprintf('A:\n');
fprintf('%f\n', A);
</code>```

You need to specify a valid format specifier when displaying a variable.  Doing %f\n will print out a single value per line.  Please read up on how to use format specifiers from the docs: https://www.gnu.org/software/octave/doc/v4.0.0/Formatted-Output.html#XREFsprintf

Body:
Suppose I have a matrix A=[1,2] if I try to print it with command

fprintf("A ", A)

Output

A

Blank A is printed without values?

Body:
It's:

fprintf('A:\n');
fprintf('%f\n', A);

You need to specify a valid format specifier when displaying a variable.  Doing %f\n will print out a single value per line.  Please read up on how to use format specifiers from the docs: https://www.gnu.org/software/octave/doc/v4.0.0/Formatted-Output.html#XREFsprintf


问:
Does array assignment create a new reference
I am running into the following situation. I am initializing an array, and assigning it to an object's property.

```<code>var arr = [1,2,3,4,5];
var obj = { 'numbers': arr };
</code>```

I understand that I passed a reference to my array arr to my object obj. So I can do the following:

```<code>arr.push(6);
console.log(obj);
</code>```

will display the following, as expected:

```<code>{ numbers: [ 1, 2, 3, 4, 5, 6] }
</code>```

Now for the unexpected part. The value of arr changes, through an external event, and I want the value of obj.numbers to change at the same time. But it does not:

```<code>arr = [0,0,0,0,0];
console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [ 1, 2, 3, 4, 5, 6] }
</code>```

So the value of my arr variable changed, but not the numbers property in my obj variable.

So, my only explanation is, that as soon as you perform an assignment to an array, you break the old reference and create a new reference. Is that so?

And how would I assign my new values [0,0,0,0,0] to my arr variable and the obj.numbers (at the same time)?

答:
I haven't found the exact documentation on this, but after some experimentation, I concluded that an assignment indeed creates a new reference.

This is the way I ended up solving this.

```<code>arr.splice(0);
[0,0,0,0,0].map(el => arr.push(el);
</code>```

This gives me the following expected result.

```<code>console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [0,0,0,0,0] }
</code>```

By the way, the same is true for objects, which would be logical, since arrays are a type of object.

Body:
I am running into the following situation. I am initializing an array, and assigning it to an object's property.

var arr = [1,2,3,4,5];
var obj = { 'numbers': arr };

I understand that I passed a reference to my array arr to my object obj. So I can do the following:

arr.push(6);
console.log(obj);

will display the following, as expected:

{ numbers: [ 1, 2, 3, 4, 5, 6] }

Now for the unexpected part. The value of arr changes, through an external event, and I want the value of obj.numbers to change at the same time. But it does not:

arr = [0,0,0,0,0];
console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [ 1, 2, 3, 4, 5, 6] }

So the value of my arr variable changed, but not the numbers property in my obj variable.

So, my only explanation is, that as soon as you perform an assignment to an array, you break the old reference and create a new reference. Is that so?

And how would I assign my new values [0,0,0,0,0] to my arr variable and the obj.numbers (at the same time)?

Body:
I haven't found the exact documentation on this, but after some experimentation, I concluded that an assignment indeed creates a new reference.

This is the way I ended up solving this.

arr.splice(0);
[0,0,0,0,0].map(el => arr.push(el);

This gives me the following expected result.

console.log(arr);
console.log(obj);
arr --> [0,0,0,0,0]
obj --> { numbers: [0,0,0,0,0] }

By the way, the same is true for objects, which would be logical, since arrays are a type of object.


问:
vis.js timeline items at wrong position
I'm using vis.js to create a timeline, but I'm having a weird issue. I'm using the same code to create all the timelines, but on some it positions the items almost a month too early. I've checked and the dates are entered correctly (and the tooltips are right), but for some reason the positioning is wrong.

I've added the images below to show both results when it behaves as expected (first one), and when I have positioning issues (second one). I removed some info but the dates and items are still there to show the behavior. Both timelines use the exact same code, only the data fed to it is different.

Case where it seems correct:

Case with wrong positioning:

I was wondering if the css I added to te vis timeline (margins, or paddings...) was causing an issue, but removing it didn't solve anything.

Is there a known issue about this? Could it be linked to the greater number of items or some css somewhere on the page? I couldn't seem to find anything online about positioning issues.

If it helps, here's an example of the js code I used for some of the elements (others are similar):

```<code>var date = new Date(parseInt(item.Date.substr(6))); //date is in json with a format like /Date(xxxxx)/
        list.push({
            id: index++,
            content: item.Label,
            type: "box",
            start: date,
            title: "<p class='timeline-tooltip'><b>" + dateToString(date) + "</b><br/>" + item.AmountLabel + "</p>"
        });

//... later ...//
var items = new vis.DataSet(list);
</code>```

Thanks in advance for your help!

答:
Turns out I didn't look hard enough and it is a known bug in version 4.20.0 of vis.js .
Switching back to 4.19.1 while waiting for the issue to be resolved.</p>

Title: vis.js timeline items at wrong position

Body:
I'm using vis.js to create a timeline, but I'm having a weird issue. I'm using the same code to create all the timelines, but on some it positions the items almost a month too early. I've checked and the dates are entered correctly (and the tooltips are right), but for some reason the positioning is wrong.

I've added the images below to show both results when it behaves as expected (first one), and when I have positioning issues (second one). I removed some info but the dates and items are still there to show the behavior. Both timelines use the exact same code, only the data fed to it is different.

Case where it seems correct:

Case with wrong positioning:

I was wondering if the css I added to te vis timeline (margins, or paddings...) was causing an issue, but removing it didn't solve anything.

Is there a known issue about this? Could it be linked to the greater number of items or some css somewhere on the page? I couldn't seem to find anything online about positioning issues.

If it helps, here's an example of the js code I used for some of the elements (others are similar):

var date = new Date(parseInt(item.Date.substr(6))); //date is in json with a format like /Date(xxxxx)/
        list.push({
            id: index++,
            content: item.Label,
            type: "box",
            start: date,
            title: "
" + dateToString(date) + "
" + item.AmountLabel + "
"
        });

//... later ...//
var items = new vis.DataSet(list);

Thanks in advance for your help!


问:
How to filter $ value on php
i want to filter value

example:
112 to be 01:12

from script

```<code>$duration = get_post_meta( $post->ID, 'TMDB_Runtime', true );
if ( ! empty( $duration ) ) {
echo '<div class="gmr-duration-item" property="duration">' . $duration . __( ' <a class="fa fa-clock-o" aria-hidden="true"></a>','movies' ) . '</div>';
</code>```

I've tried using substr and str_replace and put it into function.php

```<code><?php
$text = '$duration';
$text = substr($text, 0, 3);
echo $text =str_replace("1","01:", $text);
?>
</code>```

But always display parse error.

答:
You could do it this way, statically:</p>

```<code><?php
$duration = "112";
$exploded = str_split($duration);
$exploded[0] = "0".$exploded[0].":";

$final = implode($exploded);
echo $final;
?>
</code>```

Title: How to filter $ value on php

Body:
i want to filter value

example:
112 to be 01:12

from script

$duration = get_post_meta( $post->ID, 'TMDB_Runtime', true );
if ( ! empty( $duration ) ) {
echo '
' . $duration . __( ' ','movies' ) . '
';

I've tried using substr and str_replace and put it into function.php

<?php
$text = '$duration';
$text = substr($text, 0, 3);
echo $text =str_replace("1","01:", $text);
?>

But always display parse error.

Body:
You could do it this way, statically:

<?php
$duration = "112";
$exploded = str_split($duration);
$exploded[0] = "0".$exploded[0].":";

$final = implode($exploded);
echo $final;
?>


问:
PHP - Inconsistency with "Undefined offset" error
Why does PHP throw a "Notice: Undefined offset" error here:

```<code><?php
$MyVar = array();
echo $MyVar[0]; //Notice: Undefined offset: 0
?>
</code>```

But not here:

```<code><?php
$MyVar = false;
echo $MyVar[0]; //No error
?>
</code>```

答:
Undefined offset is provided when there are no values in an array and you're trying to reference an uninitialised index.

In case of the 2nd code, you've assigned(initialised) a value to the variable which is not different from variable[0].

If you assign values for 1st two indexes in 1st example, and refer to the 3rd index, you should get the undefined offset error.

I dont think it is about null or not, but a case of assigning values to indexes.
If you take a C parlance, array is an equivalent of malloc(upto a certain extent). Thankfully PHP does not crash, just throws an undefined index[offset] error

Body:
Why does PHP throw a "Notice: Undefined offset" error here:

<?php
$MyVar = array();
echo $MyVar[0]; //Notice: Undefined offset: 0
?>

But not here:

<?php
$MyVar = false;
echo $MyVar[0]; //No error
?>


问:
Detect Chrome running in headless mode from JavaScript
With the release of Chrome 59, "headless" mode is now available in stable builds for Linux and macOS (and soon also Windows with Chrome 60). This allows us to run a full-featured version of Chrome without any visible UI, a great capability to have for automated testing. Here are examples.

chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/
```

<p>In my JavaScript test runner, I like to record as much information as possible about the browser being used, to help isolate issues. For example, I record many of the properties of <code>navigator</code>, including the current browser plugins:</p>

<pre class="lang-js prettyprint-override"><code>JSON.stringify(Array.from(navigator.plugins).map(p => p.name))
</code>```

["Chrome PDF Viewer","Widevine Content Decryption Module","Shockwave Flash","Native Client","Chrome PDF Viewer"]
```

My understanding is that Chrome should behave identically in headless mode, but I have enough experience to be skeptical of a new feature that may significantly change the rendering pipeline.

For now, I am going to run tests in both modes. I would like to the test runner to record whether headless mode is being used. I could pass this information in the test configurations, but I'd rather have a pure JavaScript solution that I can build into the test runner itself. However, I haven't been able to find any browser interface that reveals whether headless mode is active.

Is there any way to detect if Chrome is running in headless mode from JavaScript?

答:
navigator.plugins should contain an array of plugins that are present within the browser (like Flash, ActiveX, or Java applets). For headless browser it'll be nullable.

As a part of security check it can be used alert, for headless it'll be ignored:

```<code>var start = Date.now();
alert('Press OK');
var elapse = Date.now() - start;
if (elapse < 15) {
    console.log("headless environment detected");
}
</code>```

Several techniques for detecting headless browsers are discussed in the OWASP AppSecUSA 2014 talk Headless Browser Hide & Seek (video, slides) by Sergey Shekyan and Bei Zhang.

ContentLicense: CC BY-SA 4.0

Body:
With the release of Chrome 59, "headless" mode is now available in stable builds for Linux and macOS (and soon also Windows with Chrome 60). This allows us to run a full-featured version of Chrome without any visible UI, a great capability to have for automated testing. Here are examples.

chrome --headless --disable-gpu --dump-dom https://stackoverflow.com/

In my JavaScript test runner, I like to record as much information as possible about the browser being used, to help isolate issues. For example, I record many of the properties of navigator, including the current browser plugins:

JSON.stringify(Array.from(navigator.plugins).map(p => p.name))

["Chrome PDF Viewer","Widevine Content Decryption Module","Shockwave Flash","Native Client","Chrome PDF Viewer"]

My understanding is that Chrome should behave identically in headless mode, but I have enough experience to be skeptical of a new feature that may significantly change the rendering pipeline.

For now, I am going to run tests in both modes. I would like to the test runner to record whether headless mode is being used. I could pass this information in the test configurations, but I'd rather have a pure JavaScript solution that I can build into the test runner itself. However, I haven't been able to find any browser interface that reveals whether headless mode is active.

Is there any way to detect if Chrome is running in headless mode from JavaScript?

Body:
navigator.plugins should contain an array of plugins that are present within the browser (like Flash, ActiveX, or Java applets). For headless browser it'll be nullable.

As a part of security check it can be used alert, for headless it'll be ignored:

var start = Date.now();
alert('Press OK');
var elapse = Date.now() - start;
if (elapse < 15) {
    console.log("headless environment detected");
}

Several techniques for detecting headless browsers are discussed in the OWASP AppSecUSA 2014 talk Headless Browser Hide & Seek (video, slides) by Sergey Shekyan and Bei Zhang.


问:
CSS: resize div width according to parents width
Ok, I am basically building a fluid layout.
My HTML is like this:

```<code><div id="container">
    <div class="box" id="left">Left</div>
    <div class="box" id="center">This text is long and can get longer</div>
    <div class="box" id="right">Right</div>
    <div class="clear"></div>
</div>
</code>```

Here is the css:

```<code>#container{
    width: 100%;
}
.box{
    float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}
</code>```

What I need to know is how do I get the #center to re-size when #container is re-sized without the elements moving underneath each other.

答:
The easiest way to do this and completely avoid the float issues that arise would be to
use padding on the container and absolute position the left/right elements in the padding area. (demo at  http://www.jsfiddle.net/gaby/8gKWq/1)

Html

```<code><div id="container">
    <div class="box" id="left">Left</div>
    <div class="box" id="right">Right</div>
    <div class="box" id="centre">This text is long and can get longer</div>
</div>
</code>```

The order of the divs does not matter anymore..

Css

```<code>#container{
    padding:0 100px;
    position:relative;
}
.box{
   /*style the boxes here*/
}
#left, #right{
    width: 100px;
    position:absolute;
}
#left{left:0;top:0;}
#right{right:0;top:0;}

#center{
   /*anything specific to the center box should go here.*/
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Ok, I am basically building a fluid layout.
My HTML is like this:

Left

This text is long and can get longer

Right

Here is the css:

#container{
    width: 100%;
}
.box{
    float: left;
}
#left, #right{
    width: 100px;
}
#center{
    width: auto; /* ? */
    overflow: hidden;
}
.clear{
    clear:both;
}

What I need to know is how do I get the #center to re-size when #container is re-sized without the elements moving underneath each other.

Body:
The easiest way to do this and completely avoid the float issues that arise would be to
use padding on the container and absolute position the left/right elements in the padding area. (demo at  http://www.jsfiddle.net/gaby/8gKWq/1)

Html

<div id="container">
    <div class="box" id="left">Left</div>
    <div class="box" id="right">Right</div>
    <div class="box" id="centre">This text is long and can get longer</div>
</div>

The order of the divs does not matter anymore..

Css

#container{
    padding:0 100px;
    position:relative;
}
.box{
   /*style the boxes here*/
}
#left, #right{
    width: 100px;
    position:absolute;
}
#left{left:0;top:0;}
#right{right:0;top:0;}

#center{
   /*anything specific to the center box should go here.*/
}


问:
How to Write Multiple CSV from List of Dataframe at once in R?
I have thousands .csv files which consists this information:

```<code>Year  HS
1956  1.098
1956  1.785
1956  0.987
....
2012  1.341
</code>```

What I should be doing are:

Found Maximum HS for each Year on each file

Write thousands separate .csv files which hold information of point 1

As far (also by help in this forum), I've a list of thousands dataframes of point 1 with this script:

```<code>    temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f)
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))
</code>```

The list look like this:

```<code>[[1]]
   Year    HS
1  1956 2.172
2  1957 1.831
3  1958 1.713
.....
56  2011 2.332
57  2012 2.917

[[2]]
   Year    HS
1  1956 2.111
2  1957 1.864
3  1958 1.135
.....
56  2011 1.032
57  2012 2.341
.....
until thousands dataframes
</code>```

I am trying to write .csv files from those list by applying these script:

```<code>    temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f)
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))
for(i in 1:length(ag)){
  write.csv(ag[i],file="out[i].csv")
}
</code>```

But it only create out[i].csv which consists information of first dataframe of ag

I am also trying this script:

```<code>temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f)
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))
lapply(ag, function(a)
  write.csv(a, file="out[a].csv"))
</code>```

And again, it only create out[a].csv which consists information of first dataframe of ag.

It seems that I fail to set the loop both to 'call' the dataframes on the list and to create sequential output .csv name. Is there any suggestion for this issue?

Thank you.

答:
Try

```<code>write.csv(ag[i],file=sprintf("out%d.csv",i))
</code>```

or

```<code>write.csv(ag[i],file=paste0("out",i,".csv"))
</code>```

I wasn't sure whether you wanted to square brackets in the file name.  I would advise against it.

Body:
I have thousands .csv files which consists this information:

Year  HS
1956  1.098
1956  1.785
1956  0.987
....
2012  1.341

What I should be doing are:

Found Maximum HS for each Year on each file

Write thousands separate .csv files which hold information of point 1

As far (also by help in this forum), I've a list of thousands dataframes of point 1 with this script:

    temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f)
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))

The list look like this:

[[1]]
   Year    HS
1  1956 2.172
2  1957 1.831
3  1958 1.713
.....
56  2011 2.332
57  2012 2.917

[[2]]
   Year    HS
1  1956 2.111
2  1957 1.864
3  1958 1.135
.....
56  2011 1.032
57  2012 2.341
.....
until thousands dataframes

I am trying to write .csv files from those list by applying these script:

    temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f)
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))
for(i in 1:length(ag)){
  write.csv(ag[i],file="out[i].csv")
}

But it only create out[i].csv which consists information of first dataframe of ag

I am also trying this script:

temp <- Sys.glob("*.csv")
ag <- lapply(temp, function(f)
  aggregate(HS ~ Year, read.table(f, header = TRUE, sep = ";"), max))
lapply(ag, function(a)
  write.csv(a, file="out[a].csv"))

And again, it only create out[a].csv which consists information of first dataframe of ag.

It seems that I fail to set the loop both to 'call' the dataframes on the list and to create sequential output .csv name. Is there any suggestion for this issue?

Thank you.

Body:
Try

write.csv(ag[i],file=sprintf("out%d.csv",i))

or

write.csv(ag[i],file=paste0("out",i,".csv"))

I wasn't sure whether you wanted to square brackets in the file name.  I would advise against it.


问:
Android - How to open image in new activity by buttons id?
I'm trying to create an app; when I click a button it will open an image on second activity.

For example

```<code>"button1"->"image1" ,

 "button2"->"image2"
</code>```

but I couldn't. Have a method to do it?

答:
In your MainActivity implement an OnClickListener for the button:

```<code>private Button button1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button1 = (Button) findViewById(R.id.yourItemIdInXml);

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // put Intent here
        }
    });
}
</code>```

Inside the onClick create an intent:

```<code>Intent intent = new Intent (CurrentActivity.this, ImageActivity.class);
</code>```

and put your imageId (supposing your image is in the drawables folder and has and ID) into intent:

```<code>intent.putExtra("IMAGE", imageId);
startActivity(intent);
</code>```

And in the receiving activitys onCreate method accept this intent:

```<code>private ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image);

    int imageId = getIntent().getIntExtra("IMAGE", 0); // 0 is a default value
                                                       // IMAGE is a string that serves as a key, can be anything just make sure it's the same as in putExtra()
}
</code>```

And after you can create an imageview and set it using the imageId:

```<code>ImageView image = (ImageView) findViewById(R.id.imageIdInXml);
image.setImageResource(imageId);
</code>```

And do the same for the second button.

It's basically the same answer as here just a bit more detailed.

Body:
I'm trying to create an app; when I click a button it will open an image on second activity.

For example

"button1"->"image1" ,

 "button2"->"image2"

but I couldn't. Have a method to do it?

Body:
In your MainActivity implement an OnClickListener for the button:

private Button button1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    button1 = (Button) findViewById(R.id.yourItemIdInXml);

    button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // put Intent here
        }
    });
}

Inside the onClick create an intent:

Intent intent = new Intent (CurrentActivity.this, ImageActivity.class);

and put your imageId (supposing your image is in the drawables folder and has and ID) into intent:

intent.putExtra("IMAGE", imageId);
startActivity(intent);

And in the receiving activitys onCreate method accept this intent:

private ImageView image;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_image);

    int imageId = getIntent().getIntExtra("IMAGE", 0); // 0 is a default value
                                                       // IMAGE is a string that serves as a key, can be anything just make sure it's the same as in putExtra()
}

And after you can create an imageview and set it using the imageId:

ImageView image = (ImageView) findViewById(R.id.imageIdInXml);
image.setImageResource(imageId);

And do the same for the second button.

It's basically the same answer as here just a bit more detailed.


问:
Drop Duplicates and Add Values Pandas
I have a dataframe below. I would like to drop the duplicates, but add the duplicated value from the E column to the non-duplicated record

```<code>import pandas as pd
import numpy as np
dfp = pd.DataFrame({'A' : [np.NaN,np.NaN,3,4,5,5,3,1,6,7],
                    'B' : [1,1,3,5,0,0,np.NaN,9,0,0],
                    'C' : ['AA1233445','AA1233445', 'rmacy','Idaho Rx','Ab123455','TV192837','RX','Ohio Drugs','RX12345','USA Pharma'],
                    'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
                    'E' : ['Assign','Allign','Hello','Ugly','Appreciate','Undo','Testing','Unicycle','Pharma','Unicorn',]})
print(dfp)
</code>```

I'm grabbing all the duplicates:

```<code>df2 = dfp.loc[(dfp['A'].duplicated(keep=False))].copy()

     A    B          C           D           E
0  NaN  1.0  AA1233445    123456.0      Assign
1  NaN  1.0  AA1233445    123456.0      Allign
2  3.0  3.0      rmacy   1234567.0       Hello
4  5.0  0.0   Ab123455     12345.0  Appreciate
5  5.0  0.0   TV192837     12345.0        Undo
6  3.0  NaN         RX  12345678.0     Testing
</code>```

and would like my outcome to be:

```<code>     A    B          C           D           E
0  NaN  1.0  AA1233445    123456.0      Assign Allign
2  3.0  3.0      rmacy   1234567.0      Hello Testing
4  5.0  0.0   Ab123455     12345.0      Appreciate Undo
</code>```

I know I need to use dfp.loc[(dfp['A'].duplicated(keep='last'))].copy() to grab the first occurrence, but I'm failing to set the value of the E column to include the other duplicated values.

I'm thinking I need to try something like:

```<code>df3 = dfp.loc[(dfp['A'].duplicated(keep='last'))].copy()
df3['E'] = df3['E'] + dfp.loc[(dfp['A'].duplicated(keep=False).copy()),'E']
</code>```

but my output is:

```<code>     A    B          C          D                     E
0  NaN  1.0  AA1233445   123456.0          AssignAssign
2  3.0  3.0      rmacy  1234567.0            HelloHello
4  5.0  0.0   Ab123455    12345.0  AppreciateAppreciate
</code>```

I'm stumped. Am I over complicating it? How can I get the output I'm looking for so that I can later drop all the duplicates, except the first, but 'save' the values of the dropped vlaues in the E Column?

答:
Here is my ugly solution:</p>

```<code>In [263]: (dfp.reset_index()
     ...:     .assign(A=dfp.A.fillna(-1))
     ...:     .groupby('A')
     ...:     .filter(lambda x: len(x) > 1)
     ...:     .groupby('A', as_index=False)
     ...:     .apply(lambda x: x.head(1).assign(E=x.E.str.cat(sep=' ')))
     ...:     .replace({'A':{-1:np.nan}})
     ...:     .set_index('index'))
     ...:
Out[263]:
         A    B          C          D                E
index
0      NaN  1.0  AA1233445   123456.0    Assign Allign
2      3.0  3.0      rmacy  1234567.0    Hello Testing
4      5.0  0.0   Ab123455    12345.0  Appreciate Undo
</code>```

Title: Drop Duplicates and Add Values Pandas

Body:
I have a dataframe below. I would like to drop the duplicates, but add the duplicated value from the E column to the non-duplicated record

import pandas as pd
import numpy as np
dfp = pd.DataFrame({'A' : [np.NaN,np.NaN,3,4,5,5,3,1,6,7],
                    'B' : [1,1,3,5,0,0,np.NaN,9,0,0],
                    'C' : ['AA1233445','AA1233445', 'rmacy','Idaho Rx','Ab123455','TV192837','RX','Ohio Drugs','RX12345','USA Pharma'],
                    'D' : [123456,123456,1234567,12345678,12345,12345,12345678,123456789,1234567,np.NaN],
                    'E' : ['Assign','Allign','Hello','Ugly','Appreciate','Undo','Testing','Unicycle','Pharma','Unicorn',]})
print(dfp)

I'm grabbing all the duplicates:

df2 = dfp.loc[(dfp['A'].duplicated(keep=False))].copy()

     A    B          C           D           E
0  NaN  1.0  AA1233445    123456.0      Assign
1  NaN  1.0  AA1233445    123456.0      Allign
2  3.0  3.0      rmacy   1234567.0       Hello
4  5.0  0.0   Ab123455     12345.0  Appreciate
5  5.0  0.0   TV192837     12345.0        Undo
6  3.0  NaN         RX  12345678.0     Testing

and would like my outcome to be:

     A    B          C           D           E
0  NaN  1.0  AA1233445    123456.0      Assign Allign
2  3.0  3.0      rmacy   1234567.0      Hello Testing
4  5.0  0.0   Ab123455     12345.0      Appreciate Undo

I know I need to use dfp.loc[(dfp['A'].duplicated(keep='last'))].copy() to grab the first occurrence, but I'm failing to set the value of the E column to include the other duplicated values.

I'm thinking I need to try something like:

df3 = dfp.loc[(dfp['A'].duplicated(keep='last'))].copy()
df3['E'] = df3['E'] + dfp.loc[(dfp['A'].duplicated(keep=False).copy()),'E']

but my output is:

     A    B          C          D                     E
0  NaN  1.0  AA1233445   123456.0          AssignAssign
2  3.0  3.0      rmacy  1234567.0            HelloHello
4  5.0  0.0   Ab123455    12345.0  AppreciateAppreciate

I'm stumped. Am I over complicating it? How can I get the output I'm looking for so that I can later drop all the duplicates, except the first, but 'save' the values of the dropped vlaues in the E Column?

Body:
Here is my ugly solution:

In [263]: (dfp.reset_index()
     ...:     .assign(A=dfp.A.fillna(-1))
     ...:     .groupby('A')
     ...:     .filter(lambda x: len(x) > 1)
     ...:     .groupby('A', as_index=False)
     ...:     .apply(lambda x: x.head(1).assign(E=x.E.str.cat(sep=' ')))
     ...:     .replace({'A':{-1:np.nan}})
     ...:     .set_index('index'))
     ...:
Out[263]:
         A    B          C          D                E
index
0      NaN  1.0  AA1233445   123456.0    Assign Allign
2      3.0  3.0      rmacy  1234567.0    Hello Testing
4      5.0  0.0   Ab123455    12345.0  Appreciate Undo


问:
How to use Google Natural Language Processing Cloud API in Android
Hello I guys I want to use Google's Natural Language Processing Cloud API for my android Application. What are the steps for getting the reference to the api and what all things is to be downloaded and what are the steps to be followed</p>

答: We do have a sample currently published on our web site (cloud.google.com/natural-language/docs/samples) with the source on github. You can use the sample but that it is in the process of being updated. It is not a step by step but more of a learn by example approach. Please take a look. It might be enough to unblock you now, and we're working on updating it as well.</p>


问:
SQLAlchemy Postgres query is key exists in JSON
I have a model Definition:

```<code>class Definition:
    meta = Column(MutableDict.as_mutable(JSON))
</code>```

It stores any JSON so I want to query if a given key exists in this field.

I need something like:

```<code>defs = db.query(Definition).filter(
    Definition.meta.has_key('translation')).all()
</code>```

MySQL for example has a function named json_contains and I could use it:

```<code>defs = db.query(Definition).filter(
    func.json_contains(
        Definition.meta, 'translation') == 1).all()
</code>```

How can I achieve this in PostgreSQL

答:
Whenever I am unsure of how to use the sqlalchemy bits, I hack a version together, and go from there:

```<code>json_select = '''SELECT jdoc->'key_name1', jdoc->'translation'
FROM Definition
WHERE jdoc @> '{"translation": 1, "key_name1": "hello there"}'
;
'''

print([x for x in db.engine.execute(json_select)])
</code>```

note:

psycopg2 changed in version 2.5.4: added jsonb support.

Referenced:

http://initd.org/psycopg/docs/extras.html#json-adaptation

https://www.postgresql.org/docs/9.4/static/datatype-json.html

Body:
I have a model Definition:

class Definition:
    meta = Column(MutableDict.as_mutable(JSON))

It stores any JSON so I want to query if a given key exists in this field.

I need something like:

defs = db.query(Definition).filter(
    Definition.meta.has_key('translation')).all()

MySQL for example has a function named json_contains and I could use it:

defs = db.query(Definition).filter(
    func.json_contains(
        Definition.meta, 'translation') == 1).all()

How can I achieve this in PostgreSQL

Body:
Whenever I am unsure of how to use the sqlalchemy bits, I hack a version together, and go from there:

json_select = '''SELECT jdoc->'key_name1', jdoc->'translation'
FROM Definition
WHERE jdoc @> '{"translation": 1, "key_name1": "hello there"}'
;
'''

print([x for x in db.engine.execute(json_select)])

note:

psycopg2 changed in version 2.5.4: added jsonb support.

Referenced:

http://initd.org/psycopg/docs/extras.html#json-adaptation

https://www.postgresql.org/docs/9.4/static/datatype-json.html


问:
Best way to inherit methods from a parent class to multiple subclasses in django
I have multiple subclasses that uses very similar methods with differing arguments I want to pass. For instance I'm using the parent subclass  SportsSentiment that contains a function that returns all the rows for an individual league (NBA, NFL, MLB...etc).

Here is the Parent Class:

```<code>from django.db import models
from sports_sentiment.main.models import SentimentPoint

class SportsSentimentMixin(models.Model):
    test = "abc"

    # I want my subclasses to inherit this method!
    def get_league_sentimental_points(self, league):
        return SentimentPoint.objects.all().filter(league=league)

    class Meta:
        abstract = True
</code>```

An example of a subclass:

```<code>from sports_sentiment.custom_mixins import SportsSentimentMixin

class NBASportsSentimentView(TemplateView, SportsSentimentMixin):
    template_name = 'NBA/sports_sentiment.html'

    # This doesn't work, but I'm trying to get the the
    # the function get_league_sentimental_points from the parent
    # class
    nba_data = self.get_league_sentimental_points("NBA")
</code>```

答:
I think you're going at it kind of backwards. First, your mixin does not need to be a model. Why not just make it a base view that queries for the sentiment points based on the league. Then you can just inherit from that view and override the template_name and league!

```<code>from django.views.generic import TemplateView
from sports_sentiment.main.models import SentimentPoint

class SportsSentimentView(TemplateView):
    template_name = 'ABC/sports_sentiment.html'
    league = 'ABC'

    def get_context_data(self, **kwargs):
        # This method builds a dictionary of variables that will be passed
        # to the template for rendering
        context = super(SportsSentimentView, self).get_context_data(**kwargs)
        context['points'] = SentimentPoint.objects.filter(league=self.league)
        return context

class NBASportsSentimentView(SportsSentimentView):
    template_name = 'NBA/sports_sentiment.html'
    league = 'NBA'

# Adding more leagues is now super simple!
class NHLSportsSentimentView(SportsSentimentView):
    template_name = 'NHL/sports_sentiment.html'
    league = 'NHL'
</code>```

Body:
I have multiple subclasses that uses very similar methods with differing arguments I want to pass. For instance I'm using the parent subclass  SportsSentiment that contains a function that returns all the rows for an individual league (NBA, NFL, MLB...etc).

Here is the Parent Class:

from django.db import models
from sports_sentiment.main.models import SentimentPoint

class SportsSentimentMixin(models.Model):
    test = "abc"

    # I want my subclasses to inherit this method!
    def get_league_sentimental_points(self, league):
        return SentimentPoint.objects.all().filter(league=league)

    class Meta:
        abstract = True

An example of a subclass:

from sports_sentiment.custom_mixins import SportsSentimentMixin

class NBASportsSentimentView(TemplateView, SportsSentimentMixin):
    template_name = 'NBA/sports_sentiment.html'

    # This doesn't work, but I'm trying to get the the
    # the function get_league_sentimental_points from the parent
    # class
    nba_data = self.get_league_sentimental_points("NBA")

Body:
I think you're going at it kind of backwards. First, your mixin does not need to be a model. Why not just make it a base view that queries for the sentiment points based on the league. Then you can just inherit from that view and override the template_name and league!

from django.views.generic import TemplateView
from sports_sentiment.main.models import SentimentPoint

class SportsSentimentView(TemplateView):
    template_name = 'ABC/sports_sentiment.html'
    league = 'ABC'

    def get_context_data(self, **kwargs):
        # This method builds a dictionary of variables that will be passed
        # to the template for rendering
        context = super(SportsSentimentView, self).get_context_data(**kwargs)
        context['points'] = SentimentPoint.objects.filter(league=self.league)
        return context

class NBASportsSentimentView(SportsSentimentView):
    template_name = 'NBA/sports_sentiment.html'
    league = 'NBA'

# Adding more leagues is now super simple!
class NHLSportsSentimentView(SportsSentimentView):
    template_name = 'NHL/sports_sentiment.html'
    league = 'NHL'


问:
Azure Kubernetes Private Key Location
I've used this command to deploy a Kubernetes cluster in Azure:

```<code>az acs create -n acs-cluster -g acsrg1 -d applink789 --generate-ssh-keys
</code>```

Everything is working- I can connect to the cluster with kubectl.  Now I want to define an SSH step in a Continuous Delivery pipeline.  The documentation indicates that this command created a public/private key pair.  Where is the private key stored?  I've looked in the .ssh, .kube, and .azure folders in my home directory but I can't tell if any of those values are the private key.

答: Figured it out- the documentation says the keys will be generated if they are missing.  If the id_rsa keypair is present in the .ssh hidden directory, it is used.  Connected with Putty using the azureuser default account.

Title: Azure Kubernetes Private Key Location

Body:
I've used this command to deploy a Kubernetes cluster in Azure:

az acs create -n acs-cluster -g acsrg1 -d applink789 --generate-ssh-keys

Everything is working- I can connect to the cluster with kubectl.  Now I want to define an SSH step in a Continuous Delivery pipeline.  The documentation indicates that this command created a public/private key pair.  Where is the private key stored?  I've looked in the .ssh, .kube, and .azure folders in my home directory but I can't tell if any of those values are the private key.


问:
How to git cherry-pick a commit with binary files
I am trying to cherry-pick a commit from a different branch that is mostly binary files.  It seems it is mostly successful, except for one file where I get the message:

```<code>warning: Cannot merge binary files: XXXX.so (HEAD vs. d8ef550... Add support for 32-bit apk)
error: could not apply d8ef550... Add support for 32-bit apk
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'
</code>```

I can do a 'git add' on that file, but the results are not what I was expecting.  I expected it to be a modification, but it turned out to remove that file in question.  The commit I am trying to cherry pick modifies some binary files as well as deletes a few.

So, the question is...what is the best way to cherry-pick a commit w binary files ?

答:
You can do this with git cherry-pick --strategy=recursive -X theirs {Imported_Commit}

(You may need to abort the current cherry-pick first; git cherry-pick --abort)

Body:
I am trying to cherry-pick a commit from a different branch that is mostly binary files.  It seems it is mostly successful, except for one file where I get the message:

warning: Cannot merge binary files: XXXX.so (HEAD vs. d8ef550... Add support for 32-bit apk)
error: could not apply d8ef550... Add support for 32-bit apk
hint: after resolving the conflicts, mark the corrected paths
hint: with 'git add <paths>' or 'git rm <paths>'
hint: and commit the result with 'git commit'

I can do a 'git add' on that file, but the results are not what I was expecting.  I expected it to be a modification, but it turned out to remove that file in question.  The commit I am trying to cherry pick modifies some binary files as well as deletes a few.

So, the question is...what is the best way to cherry-pick a commit w binary files ?


问:
How to increment between pages using Selenium and BeautifulSoup?
I'm trying to get my code to increment through the pages of this website and I can't seem to get it to loop and increment, instead doing the first page, and giving up. Is there something I'm doing wrong?

```<code>         if(pageExist is not None):
              if(countitup != pageNum):
                 countitup = countitup + 1
                 driver.get('http://800notes.com/Phone.aspx/%s/%s' % (tele800,countitup))
                 delay = 4
                 scamNum = soup.find_all(text=re.compile(r"Scam"))
                 spamNum = soup.find_all(text=re.compile(r"Call type: Telemarketer"))
                 debtNum = soup.find_all(text=re.compile(r"Call type: Debt Collector"))
                 hospitalNum = soup.find_all(text=re.compile(r"Hospital"))
                 scamCount = len(scamNum) + scamCount
                 spamCount = len(spamNum) + spamCount
                 debtCount = len(debtNum) + debtCount
                 hospitalCount = len(hospitalNum) + hospitalCount
                 block = soup.find(text=re.compile(r"OctoNet HTTP filter"))
                 extrablock = soup.find(text=re.compile(r"returning an unknown error"))
                 type(block) is str
                 type(extrablock) is str
                 if(block is not None or extrablock is not None):
                    print("\n Damn. Gimme an hour to fix this.")
                    time.sleep(2000)
</code>```

Repo: https://github.com/GarnetSunset/Haircuttery/tree/Experimental

答:
pageExist is not None this seems to be the problem.
Since it checks whether the page is None and it will most likely never be none.  There is no official way to check for HTTP responses but we can use something like this.

```<code>if (soup.find_element_by_xpath('/html/body/p'[contains(text(),'400')])
#this will check if there's a 400 code in the p tag.
</code>```

or

```<code>if ('400' in soup.find_element_by_xpath('/html/body/p[1]').text)
</code>```

I'm sure there are other ways that one can do this but this is one of those and so that's the only issue here. You can then increment or keep the rest of your code pretty much as soon as you fix the first if .

I might have made some mistakes (syntax) in my code since I'm not testing it but the logic applies), great code tho!

Also instead of

```<code>             type(block) is str
             type(extrablock) is str
</code>```

the pythonic way is using
isinstace

```<code>isinstance(block, str)
isinstance(extrablock, str)
</code>```

and as for time.sleep you can use WebDriverWait there are two available methods, implicit and explicit wait, please take a look here.

Body:
I'm trying to get my code to increment through the pages of this website and I can't seem to get it to loop and increment, instead doing the first page, and giving up. Is there something I'm doing wrong?

         if(pageExist is not None):
              if(countitup != pageNum):
                 countitup = countitup + 1
                 driver.get('http://800notes.com/Phone.aspx/%s/%s' % (tele800,countitup))
                 delay = 4
                 scamNum = soup.find_all(text=re.compile(r"Scam"))
                 spamNum = soup.find_all(text=re.compile(r"Call type: Telemarketer"))
                 debtNum = soup.find_all(text=re.compile(r"Call type: Debt Collector"))
                 hospitalNum = soup.find_all(text=re.compile(r"Hospital"))
                 scamCount = len(scamNum) + scamCount
                 spamCount = len(spamNum) + spamCount
                 debtCount = len(debtNum) + debtCount
                 hospitalCount = len(hospitalNum) + hospitalCount
                 block = soup.find(text=re.compile(r"OctoNet HTTP filter"))
                 extrablock = soup.find(text=re.compile(r"returning an unknown error"))
                 type(block) is str
                 type(extrablock) is str
                 if(block is not None or extrablock is not None):
                    print("\n Damn. Gimme an hour to fix this.")
                    time.sleep(2000)

Repo: https://github.com/GarnetSunset/Haircuttery/tree/Experimental

Body:
pageExist is not None this seems to be the problem.
Since it checks whether the page is None and it will most likely never be none.  There is no official way to check for HTTP responses but we can use something like this.

if (soup.find_element_by_xpath('/html/body/p'[contains(text(),'400')])
#this will check if there's a 400 code in the p tag.

or

if ('400' in soup.find_element_by_xpath('/html/body/p[1]').text)

I'm sure there are other ways that one can do this but this is one of those and so that's the only issue here. You can then increment or keep the rest of your code pretty much as soon as you fix the first if .

I might have made some mistakes (syntax) in my code since I'm not testing it but the logic applies), great code tho!

Also instead of

             type(block) is str
             type(extrablock) is str

the pythonic way is using
isinstace

isinstance(block, str)
isinstance(extrablock, str)

and as for time.sleep you can use WebDriverWait there are two available methods, implicit and explicit wait, please take a look here.


问:
Equivalent of RelativeLayout in Flutter
Is there a way to implement something similar to what RelativeLayout does on Android?

In particular I'm looking for something similar to centerInParent, layout_below:<layout_id>, layout_above:<layout_id>, and alignParentLeft

For more reference on RelativeLayout: https://developer.android.com/reference/android/widget/RelativeLayout.LayoutParams.html

EDIT: here is an example of a layout relying on RelativeLayout

So in the image above, on top, the "tofu's Songs" text is aligned as centerInParent inside a RelativeLayout. Whereas the other 2 are alignParentLeft and alignParentRight

On each cell, where the fire icon is at, the number of likes on the bottom of it is aligned around the center of the flame icon. Also, the top and bottom title on each cell are aligned to the right and to the top and bottom of the image avatar, respectively.

答:
Flutter layouts are usually built using a tree of Column, Row and Stack widgets. These widgets take constructor arguments that specify rules for how the children are laid out relative to the parent, and you can also influence layout of individual children by wrapping them in Expanded, Flexible, Positioned, Align, or Center widgets.

It is also possible to build complex layouts using CustomMultiChildLayout. This is how Scaffold is implemented internally, and an example of how to use it in an app appears in the Shrine demo. You can also use LayoutBuilder or CustomPaint, or go down a layer and extend RenderObject as shown in the sector example. Doing your layouts manually like this is more work and creates more potential for errors in corner cases, so I would try to get by with the high-level layout primitives if you can.

To answer your specific questions:

Use the leading and trailing arguments to AppBar to position your app bar elements. If you want to use a Row instead, use a mainAxisAlignment of MainAxisAlignment.spaceBetween.

Use a Row with a crossAxisAlignment of CrossAxisAlignment.center to position the fire icon and number underneath.

Use a Column with a mainAxisAlignment of MainAxisAlignment.spaceBetween to position your top and bottom title. (You should consider using ListTile to lay out the list tiles, but you'll lose control over the exact positioning if you do this.)

Here is a code snippet that implements the design you provided. In this example I used an IntrinsicHeight to determine the height of the song tiles, but you can improve the performance by hard coding them to a fixed height.

```<code>import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        brightness: Brightness.dark,
        primaryColorBrightness: Brightness.dark,
      ),
      home: new HomeScreen(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class Song extends StatelessWidget {
  const Song({ this.title, this.author, this.likes });

  final String title;
  final String author;
  final int likes;

  @override
  Widget build(BuildContext context) {
    TextTheme textTheme = Theme
      .of(context)
      .textTheme;
    return new Container(
      margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
      padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0),
      decoration: new BoxDecoration(
        color: Colors.grey.shade200.withOpacity(0.3),
        borderRadius: new BorderRadius.circular(5.0),
      ),
      child: new IntrinsicHeight(
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            new Container(
              margin: const EdgeInsets.only(top: 4.0, bottom: 4.0, right: 10.0),
              child: new CircleAvatar(
                backgroundImage: new NetworkImage(
                  'http://thecatapi.com/api/images/get?format=src'
                    '&size=small&type=jpg#${title.hashCode}'
                ),
                radius: 20.0,
              ),
            ),
            new Expanded(
              child: new Container(
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    new Text(title, style: textTheme.subhead),
                    new Text(author, style: textTheme.caption),
                  ],
                ),
              ),
            ),
            new Container(
              margin: new EdgeInsets.symmetric(horizontal: 5.0),
              child: new InkWell(
                child: new Icon(Icons.play_arrow, size: 40.0),
                onTap: () {
                  // TODO(implement)
                },
              ),
            ),
            new Container(
              margin: new EdgeInsets.symmetric(horizontal: 5.0),
              child: new InkWell(
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    new Icon(Icons.favorite, size: 25.0),
                    new Text('${likes ?? ''}'),
                  ],
                ),
                onTap: () {
                  // TODO(implement)
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Feed extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new ListView(
      children: [
        new Song(title: 'Trapadelic lobo', author: 'lillobobeats', likes: 4),
        new Song(title: 'Different', author: 'younglowkey', likes: 23),
        new Song(title: 'Future', author: 'younglowkey', likes: 2),
        new Song(title: 'ASAP', author: 'tha_producer808', likes: 13),
        new Song(title: '', author: 'TraphousePeyton'),
        new Song(title: 'Something sweet...', author: '6ryan'),
        new Song(title: 'Sharpie', author: 'Fergie_6'),
      ],
    );
  }
}

class CustomTabBar extends AnimatedWidget implements PreferredSizeWidget {
  CustomTabBar({ this.pageController, this.pageNames })
    : super(listenable: pageController);

  final PageController pageController;
  final List<String> pageNames;

  @override
  final Size preferredSize = new Size(0.0, 40.0);

  @override
  Widget build(BuildContext context) {
    TextTheme textTheme = Theme
      .of(context)
      .textTheme;
    return new Container(
      height: 40.0,
      margin: const EdgeInsets.all(10.0),
      padding: const EdgeInsets.symmetric(horizontal: 20.0),
      decoration: new BoxDecoration(
        color: Colors.grey.shade800.withOpacity(0.5),
        borderRadius: new BorderRadius.circular(20.0),
      ),
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: new List.generate(pageNames.length, (int index) {
          return new InkWell(
            child: new Text(
              pageNames[index],
              style: textTheme.subhead.copyWith(
                color: Colors.white.withOpacity(
                  index == pageController.page ? 1.0 : 0.2,
                ),
              )
            ),
            onTap: () {
              pageController.animateToPage(
                index,
                curve: Curves.easeOut,
                duration: const Duration(milliseconds: 300),
              );
            }
          );
        })
          .toList(),
      ),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => new _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  PageController _pageController = new PageController(initialPage: 2);

  @override
  build(BuildContext context) {
    final Map<String, Widget> pages = <String, Widget>{
      'My Music': new Center(
        child: new Text('My Music not implemented'),
      ),
      'Shared': new Center(
        child: new Text('Shared not implemented'),
      ),
      'Feed': new Feed(),
    };
    TextTheme textTheme = Theme
      .of(context)
      .textTheme;
    return new Stack(
      children: [
        new Container(
          decoration: new BoxDecoration(
            gradient: new LinearGradient(
              begin: FractionalOffset.topCenter,
              end: FractionalOffset.bottomCenter,
              colors: [
                const Color.fromARGB(255, 253, 72, 72),
                const Color.fromARGB(255, 87, 97, 249),
              ],
              stops: [0.0, 1.0],
            )
          ),
          child: new Align(
            alignment: FractionalOffset.bottomCenter,
            child: new Container(
              padding: const EdgeInsets.all(10.0),
              child: new Text(
                'T I Z E',
                style: textTheme.headline.copyWith(
                  color: Colors.grey.shade800.withOpacity(0.8),
                  fontWeight: FontWeight.bold,
                ),
              ),
            )
          )
        ),
        new Scaffold(
          backgroundColor: const Color(0x00000000),
          appBar: new AppBar(
            backgroundColor: const Color(0x00000000),
            elevation: 0.0,
            leading: new Center(
              child: new ClipOval(
                child: new Image.network(
                  'http://i.imgur.com/TtNPTe0.jpg',
                ),
              ),
            ),
            actions: [
              new IconButton(
                icon: new Icon(Icons.add),
                onPressed: () {
                  // TODO: implement
                },
              ),
            ],
            title: const Text('tofu\'s songs'),
            bottom: new CustomTabBar(
              pageController: _pageController,
              pageNames: pages.keys.toList(),
            ),
          ),
          body: new PageView(
            controller: _pageController,
            children: pages.values.toList(),
          ),
        ),
      ],
    );
  }
}
</code>```

Final note: In this example, I used a regular AppBar, but you could also use a CustomScrollView with a pinned SliverAppBar that has an elevation of 0.0. That would make the content visible as it scrolls behind your app bar. It is tricky to get this to play nicely with PageView, because it's expecting a fixed size area to lay itself out into.

Title: Equivalent of RelativeLayout in Flutter

Body:
Flutter layouts are usually built using a tree of Column, Row and Stack widgets. These widgets take constructor arguments that specify rules for how the children are laid out relative to the parent, and you can also influence layout of individual children by wrapping them in Expanded, Flexible, Positioned, Align, or Center widgets.

It is also possible to build complex layouts using CustomMultiChildLayout. This is how Scaffold is implemented internally, and an example of how to use it in an app appears in the Shrine demo. You can also use LayoutBuilder or CustomPaint, or go down a layer and extend RenderObject as shown in the sector example. Doing your layouts manually like this is more work and creates more potential for errors in corner cases, so I would try to get by with the high-level layout primitives if you can.

To answer your specific questions:

Use the leading and trailing arguments to AppBar to position your app bar elements. If you want to use a Row instead, use a mainAxisAlignment of MainAxisAlignment.spaceBetween.

Use a Row with a crossAxisAlignment of CrossAxisAlignment.center to position the fire icon and number underneath.

Use a Column with a mainAxisAlignment of MainAxisAlignment.spaceBetween to position your top and bottom title. (You should consider using ListTile to lay out the list tiles, but you'll lose control over the exact positioning if you do this.)

Here is a code snippet that implements the design you provided. In this example I used an IntrinsicHeight to determine the height of the song tiles, but you can improve the performance by hard coding them to a fixed height.

import 'package:flutter/material.dart';

void main() {
  runApp(new MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new MaterialApp(
      title: 'Flutter Demo',
      theme: new ThemeData(
        brightness: Brightness.dark,
        primaryColorBrightness: Brightness.dark,
      ),
      home: new HomeScreen(),
      debugShowCheckedModeBanner: false,
    );
  }
}

class Song extends StatelessWidget {
  const Song({ this.title, this.author, this.likes });

  final String title;
  final String author;
  final int likes;

  @override
  Widget build(BuildContext context) {
    TextTheme textTheme = Theme
      .of(context)
      .textTheme;
    return new Container(
      margin: const EdgeInsets.symmetric(horizontal: 10.0, vertical: 5.0),
      padding: const EdgeInsets.symmetric(horizontal: 15.0, vertical: 10.0),
      decoration: new BoxDecoration(
        color: Colors.grey.shade200.withOpacity(0.3),
        borderRadius: new BorderRadius.circular(5.0),
      ),
      child: new IntrinsicHeight(
        child: new Row(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            new Container(
              margin: const EdgeInsets.only(top: 4.0, bottom: 4.0, right: 10.0),
              child: new CircleAvatar(
                backgroundImage: new NetworkImage(
                  'http://thecatapi.com/api/images/get?format=src'
                    '&size=small&type=jpg#${title.hashCode}'
                ),
                radius: 20.0,
              ),
            ),
            new Expanded(
              child: new Container(
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: <Widget>[
                    new Text(title, style: textTheme.subhead),
                    new Text(author, style: textTheme.caption),
                  ],
                ),
              ),
            ),
            new Container(
              margin: new EdgeInsets.symmetric(horizontal: 5.0),
              child: new InkWell(
                child: new Icon(Icons.play_arrow, size: 40.0),
                onTap: () {
                  // TODO(implement)
                },
              ),
            ),
            new Container(
              margin: new EdgeInsets.symmetric(horizontal: 5.0),
              child: new InkWell(
                child: new Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    new Icon(Icons.favorite, size: 25.0),
                    new Text('${likes ?? ''}'),
                  ],
                ),
                onTap: () {
                  // TODO(implement)
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Feed extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return new ListView(
      children: [
        new Song(title: 'Trapadelic lobo', author: 'lillobobeats', likes: 4),
        new Song(title: 'Different', author: 'younglowkey', likes: 23),
        new Song(title: 'Future', author: 'younglowkey', likes: 2),
        new Song(title: 'ASAP', author: 'tha_producer808', likes: 13),
        new Song(title: '', author: 'TraphousePeyton'),
        new Song(title: 'Something sweet...', author: '6ryan'),
        new Song(title: 'Sharpie', author: 'Fergie_6'),
      ],
    );
  }
}

class CustomTabBar extends AnimatedWidget implements PreferredSizeWidget {
  CustomTabBar({ this.pageController, this.pageNames })
    : super(listenable: pageController);

  final PageController pageController;
  final List<String> pageNames;

  @override
  final Size preferredSize = new Size(0.0, 40.0);

  @override
  Widget build(BuildContext context) {
    TextTheme textTheme = Theme
      .of(context)
      .textTheme;
    return new Container(
      height: 40.0,
      margin: const EdgeInsets.all(10.0),
      padding: const EdgeInsets.symmetric(horizontal: 20.0),
      decoration: new BoxDecoration(
        color: Colors.grey.shade800.withOpacity(0.5),
        borderRadius: new BorderRadius.circular(20.0),
      ),
      child: new Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        children: new List.generate(pageNames.length, (int index) {
          return new InkWell(
            child: new Text(
              pageNames[index],
              style: textTheme.subhead.copyWith(
                color: Colors.white.withOpacity(
                  index == pageController.page ? 1.0 : 0.2,
                ),
              )
            ),
            onTap: () {
              pageController.animateToPage(
                index,
                curve: Curves.easeOut,
                duration: const Duration(milliseconds: 300),
              );
            }
          );
        })
          .toList(),
      ),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => new _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {

  PageController _pageController = new PageController(initialPage: 2);

  @override
  build(BuildContext context) {
    final Map<String, Widget> pages = <String, Widget>{
      'My Music': new Center(
        child: new Text('My Music not implemented'),
      ),
      'Shared': new Center(
        child: new Text('Shared not implemented'),
      ),
      'Feed': new Feed(),
    };
    TextTheme textTheme = Theme
      .of(context)
      .textTheme;
    return new Stack(
      children: [
        new Container(
          decoration: new BoxDecoration(
            gradient: new LinearGradient(
              begin: FractionalOffset.topCenter,
              end: FractionalOffset.bottomCenter,
              colors: [
                const Color.fromARGB(255, 253, 72, 72),
                const Color.fromARGB(255, 87, 97, 249),
              ],
              stops: [0.0, 1.0],
            )
          ),
          child: new Align(
            alignment: FractionalOffset.bottomCenter,
            child: new Container(
              padding: const EdgeInsets.all(10.0),
              child: new Text(
                'T I Z E',
                style: textTheme.headline.copyWith(
                  color: Colors.grey.shade800.withOpacity(0.8),
                  fontWeight: FontWeight.bold,
                ),
              ),
            )
          )
        ),
        new Scaffold(
          backgroundColor: const Color(0x00000000),
          appBar: new AppBar(
            backgroundColor: const Color(0x00000000),
            elevation: 0.0,
            leading: new Center(
              child: new ClipOval(
                child: new Image.network(
                  'http://i.imgur.com/TtNPTe0.jpg',
                ),
              ),
            ),
            actions: [
              new IconButton(
                icon: new Icon(Icons.add),
                onPressed: () {
                  // TODO: implement
                },
              ),
            ],
            title: const Text('tofu\'s songs'),
            bottom: new CustomTabBar(
              pageController: _pageController,
              pageNames: pages.keys.toList(),
            ),
          ),
          body: new PageView(
            controller: _pageController,
            children: pages.values.toList(),
          ),
        ),
      ],
    );
  }
}

Final note: In this example, I used a regular AppBar, but you could also use a CustomScrollView with a pinned SliverAppBar that has an elevation of 0.0. That would make the content visible as it scrolls behind your app bar. It is tricky to get this to play nicely with PageView, because it's expecting a fixed size area to lay itself out into.


问:
VsHub failed to locate/start service
When I start visual studio and debug aplication and open Diagnostic tool, I get the following message: The diagnostic tools failed unexpectedly.

When I open Output window for Diagnostic Hub, I see this message:
VsHub failed to locate/start service.

Any idea, how can I force diagnostic tool to start working?
From windows services I can see that "Visual Studio Standard Collector Service"
is started with "Local System Account" and Visual studio is started with "Run as administrator".

答: Restarting VS didn't address the issue?  Try disabling your anti-virus and see if that makes a difference.  VsHub might be falsely identified as malware by some of the antivirus apps (such as Avast)</p>

Title: VsHub failed to locate/start service


问:
React Navigation - Animating, Replacing screens and Tabs
I'm using React-Navigation inside my application and I couldn't find a way to do a couple of things.
First, I want to change the transition animation, but I couldn't find anyway to do so, would glad if you guys could help me.

Second, I have a login screen, When logging in, the user is moved to the Homescreen, in the Homescreen I get a back button on it so I can go to login again (which I don't want) I tried using this code:

handlePress(navigate){
    firebaseRef.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(firebaseUser){
      //Success, move to homepage.
      navigate.replace("Home");
    }).catch(function(error){
      //Failed to log in, print error.
    });
}
```

<p>but it won't work, nothing happens (it won't navigate to the home), only if I use <code>navigate("Home");</code> it navigates to home.</p>

<p>this is navigate (inside render): </p>

<pre class="lang-js prettyprint-override"><code>const { navigate } = this.props.navigation;
</code>```

Third, I have few screens (Login, Register, Home and Friends),This is my StackNavigator:

const Stylelist = StackNavigator({
  Login:{
     screen: LoginScreen,
     navigationOptions: ({navigation}) =>({
       header: null,
     }),
  },
  Register:{
      screen: RegisterScreen,
      navigationOptions: ({navigation}) =>({
        header: null,
      }),
  },
  Home:{
     screen: HomeScreen,
     navigationOptions: ({navigation}) =>({
       header: "float",
       title: "Home",
     }),
  },
});
```

I want the Home screen to be part of a TabNavigator as well (with Friends screen.)
I searched the web but couldn't find how to do this.
Can you guys help me out? giving me information sources/examples.
Thanks in advance!

答:
This should remove the back button see  doc

import { NavigationActions } from 'react-navigation';

     handlePress(){
        firebaseRef.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(firebaseUser){
          //Success, move to homepage.
          const resetAction = NavigationActions.reset({
          index: 0,
          actions: [
            NavigationActions.navigate({ routeName: 'Home'})
          ]
        })
        this.props.navigation.dispatch.(resetAction);
        }).catch(function(error){
          //Failed to log in, print error.
        });
       }
```

Body:
I'm using React-Navigation inside my application and I couldn't find a way to do a couple of things.
First, I want to change the transition animation, but I couldn't find anyway to do so, would glad if you guys could help me.

Second, I have a login screen, When logging in, the user is moved to the Homescreen, in the Homescreen I get a back button on it so I can go to login again (which I don't want) I tried using this code:

handlePress(navigate){
    firebaseRef.auth().signInWithEmailAndPassword(this.state.email, this.state.password).then(function(firebaseUser){
      //Success, move to homepage.
      navigate.replace("Home");
    }).catch(function(error){
      //Failed to log in, print error.
    });
}

but it won't work, nothing happens (it won't navigate to the home), only if I use navigate("Home"); it navigates to home.

this is navigate (inside render):

const { navigate } = this.props.navigation;

Third, I have few screens (Login, Register, Home and Friends),This is my StackNavigator:

const Stylelist = StackNavigator({
  Login:{
     screen: LoginScreen,
     navigationOptions: ({navigation}) =>({
       header: null,
     }),
  },
  Register:{
      screen: RegisterScreen,
      navigationOptions: ({navigation}) =>({
        header: null,
      }),
  },
  Home:{
     screen: HomeScreen,
     navigationOptions: ({navigation}) =>({
       header: "float",
       title: "Home",
     }),
  },
});

I want the Home screen to be part of a TabNavigator as well (with Friends screen.)
I searched the web but couldn't find how to do this.
Can you guys help me out? giving me information sources/examples.
Thanks in advance!


问:
How can I set a textview's style programmatically?
How can I add a style to a textview in java? I am trying to add one under my values/styles.xml, not to add each attribute individually.</p>

```<code>LinearLayout messagesLayout = (LinearLayout) findViewById(R.id.messages_layout);
TextView sentOne = new TextView(this);
sentOne.setText(sentMessage);

messagesLayout.addView(sentOne);
</code>```

答:
You may find this answer by Benjamin Piette handy. To change this into working code for a TextView just change it up a bit:

```<code>TextView tv = new TextView (new ContextThemeWrapper(this, R.style.mystyle), null, 0);
</code>```

EDIT: to set other things like margins, height & width and others, use LayoutParams. To set the params throrin19's answer can be helpful.

```<code>LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
tv.setLayoutParams(params);
</code>```

Body:
How can I add a style to a textview in java? I am trying to add one under my values/styles.xml, not to add each attribute individually.

LinearLayout messagesLayout = (LinearLayout) findViewById(R.id.messages_layout);
TextView sentOne = new TextView(this);
sentOne.setText(sentMessage);

messagesLayout.addView(sentOne);

Body:
You may find this answer by Benjamin Piette handy. To change this into working code for a TextView just change it up a bit:

TextView tv = new TextView (new ContextThemeWrapper(this, R.style.mystyle), null, 0);

EDIT: to set other things like margins, height & width and others, use LayoutParams. To set the params throrin19's answer can be helpful.

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
        LinearLayout.LayoutParams.WRAP_CONTENT,
        LinearLayout.LayoutParams.WRAP_CONTENT
);
params.setMargins(left, top, right, bottom);
tv.setLayoutParams(params);


问:
java read a web page using url
how to read next page of the same URL

the  URL of the page contain many pages i read the first page using

```<code>URL(url).openStream()
</code>```

but it just reading the first page

for example this site i read the first page how can i read the second culture.gov.uk/news/news_stories/6832.aspx

答: You will need the URL scheme for paging. For example it can be url + "?page=" + page. It depends on the site. Note that scraping is not always legal.

Title: java read a web page using url

Body:
how to read next page of the same URL

the  URL of the page contain many pages i read the first page using

URL(url).openStream()

but it just reading the first page

for example this site i read the first page how can i read the second culture.gov.uk/news/news_stories/6832.aspx


问:
SQL query to match a comma-separated string against a comma-separated string?
The MySQL query below uses PHP to pull in the $sector, which is a single digit,   and the $subsector_text, which is a comma separated string.  The $subsector_text could be a single digit or a list of several IDs, such as "3,4,7,9".

```<code>  $sql = "
SELECT DISTINCT a.id
              , a.name
              , a.category_id
              , a.sector
              , a.subsector
              , a.year_in_operation
              , a.state
              , a.total_value
              , b.country_id
              , b.project_id
              , c.isocode_3
              , c.name
           FROM com_barchan_project a
           JOIN com_barchan_location b
             ON b.project_id = a.id
           JOIN com_barchan_country c
             ON c.id = b.country_id
           JOIN com_barchan_project_value_join d
             ON a.id = d.project_id
          WHERE a.state = 1
            AND a.sector = '$sector'
            AND a.subsector REGEXP '^{$subsector_text}[,]|[,]{$subsector_text}[,]|[,]{$subsector_text}$|^{$subsector_text}$'
          ORDER
             BY a.total_value DESC
              , a.category_id ASC
              , a.name ASC
";
</code>```

The problem I'm having with the query above is with the line:

```<code>AND a.subsector REGEXP '^{$subsector_text}[,]|[,]{$subsector_text}[,]|[,]{$subsector_text}$|^{$subsector_text}$'
</code>```

If the $subsector_text = "3,4,5,9", then it's only returning records that contain exactly "3,4,5,9" in the $subsector field.

The desired result is that it would return any record that has any of the values in the $subsector_text.  For instance, all these should be returned, but are currently not. This list is an example and by no means exact.

```<code>1,3
1,5
1,3,7,9
3,5
3,4,5,9
9
3
5
4
</code>```

How do I change the query to select any records that has a value in that's in the $subsector_text string?

Please NOTE:  That if the $subsector_text = 11, then the following, as an example, should not be selected.

```<code>1
12
21
</code>```

Any help would be greatly appreciated.

答: The solution was to refactor the app. It took a couple days, but the offending code is gone and a new subsector table was created.  Thanks everyone.  </p>

Body:
The MySQL query below uses PHP to pull in the $sector, which is a single digit,   and the $subsector_text, which is a comma separated string.  The $subsector_text could be a single digit or a list of several IDs, such as "3,4,7,9".

  $sql = "
SELECT DISTINCT a.id
              , a.name
              , a.category_id
              , a.sector
              , a.subsector
              , a.year_in_operation
              , a.state
              , a.total_value
              , b.country_id
              , b.project_id
              , c.isocode_3
              , c.name
           FROM com_barchan_project a
           JOIN com_barchan_location b
             ON b.project_id = a.id
           JOIN com_barchan_country c
             ON c.id = b.country_id
           JOIN com_barchan_project_value_join d
             ON a.id = d.project_id
          WHERE a.state = 1
            AND a.sector = '$sector'
            AND a.subsector REGEXP '^{$subsector_text}[,]|[,]{$subsector_text}[,]|[,]{$subsector_text}$|^{$subsector_text}$'
          ORDER
             BY a.total_value DESC
              , a.category_id ASC
              , a.name ASC
";

The problem I'm having with the query above is with the line:

AND a.subsector REGEXP '^{$subsector_text}[,]|[,]{$subsector_text}[,]|[,]{$subsector_text}$|^{$subsector_text}$'

If the $subsector_text = "3,4,5,9", then it's only returning records that contain exactly "3,4,5,9" in the $subsector field.

The desired result is that it would return any record that has any of the values in the $subsector_text.  For instance, all these should be returned, but are currently not. This list is an example and by no means exact.

1,3
1,5
1,3,7,9
3,5
3,4,5,9
9
3
5
4

How do I change the query to select any records that has a value in that's in the $subsector_text string?

Please NOTE:  That if the $subsector_text = 11, then the following, as an example, should not be selected.

1
12
21

Any help would be greatly appreciated.


问:
Why doesnt "i" get incremented in the following code
I am new to coding and just stumbled upon these lines of code in "python"

```<code>a = [1,2,3,4,"hello"]

for i in a:
   try:
       print(i)
       i + 1
       print (("i is :  %d") %(i))
   except:
       print("nope " + i  + " is a string")
</code>```

The output is:

```<code>1
i is :  1
2
i is :  2
3
i is :  3
4
i is :  4
hello
nope hello is a string
</code>```

1) My question is why doesnt i get incremented?
2) why doesnt i=2 i in the second print statement?
3) Does "i" get incremented at all?

答:
Because you are not over writing the variable. What you want is:

i += 1

What your code do is actually computing i+1 but it does not update the variable.

But the idea of a for loop is not to have to increment the variable yourself. It is incremented the next iteration. It you want a more complicated iteration pattern it is preferable that you create it before.

Body:
I am new to coding and just stumbled upon these lines of code in "python"

a = [1,2,3,4,"hello"]

for i in a:
   try:
       print(i)
       i + 1
       print (("i is :  %d") %(i))
   except:
       print("nope " + i  + " is a string")

The output is:

1
i is :  1
2
i is :  2
3
i is :  3
4
i is :  4
hello
nope hello is a string

1) My question is why doesnt i get incremented?
2) why doesnt i=2 i in the second print statement?
3) Does "i" get incremented at all?


问:
How to turn my JSON result into an array or object
I have been searching every where, but cannot get to the right answer. I receive a Json result with the following structure

```<code>    {
    result =     {
        "2ab5a003-0120-4c01-80f2-a237dcf4ba14" =         {
            icon = garden;
            id = "2ab5a003-0120-4c01-80f2-a237dcf4ba14";
            index = 1;
            name = "Tafel hoek";
            parent = "855113f1-f488-4223-b675-2f01270f573e";
        };
        "2afd6093-ca6d-4e52-aaca-336ab76ea454" =         {
            icon = default;
            id = "2afd6093-ca6d-4e52-aaca-336ab76ea454";
            index = 11;
            name = Badkamer;
            parent = "9919ee1e-ffbc-480b-bc4b-77fb047e9e68";
        };
};
    status = 200;
}
</code>```

Because I don't know the 1st key in the result I am lost to get the separate items. Is there any one who can help me ? Thanks in advance

my code is:

{               print("Error: ")
                print(error!)

```<code>        } else {  // no error

            if let urlContent = data {  // 3

                do {  // 4

                    let json = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                    print(json)

                } catch {

                    print("JSON processing failed")

                }  // end 4 do

            }  // end 3 let urlContent

        }  // end 2 if error}
</code>```

答: Can you post your code ,i think that is not  a valid json format and tell me where you are struggling to parse.ignore that key and try as usual </p>

Body:
I have been searching every where, but cannot get to the right answer. I receive a Json result with the following structure

    {
    result =     {
        "2ab5a003-0120-4c01-80f2-a237dcf4ba14" =         {
            icon = garden;
            id = "2ab5a003-0120-4c01-80f2-a237dcf4ba14";
            index = 1;
            name = "Tafel hoek";
            parent = "855113f1-f488-4223-b675-2f01270f573e";
        };
        "2afd6093-ca6d-4e52-aaca-336ab76ea454" =         {
            icon = default;
            id = "2afd6093-ca6d-4e52-aaca-336ab76ea454";
            index = 11;
            name = Badkamer;
            parent = "9919ee1e-ffbc-480b-bc4b-77fb047e9e68";
        };
};
    status = 200;
}

Because I don't know the 1st key in the result I am lost to get the separate items. Is there any one who can help me ? Thanks in advance

my code is:

{               print("Error: ")
                print(error!)

        } else {  // no error

            if let urlContent = data {  // 3

                do {  // 4

                    let json = try JSONSerialization.jsonObject(with: urlContent, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject

                    print(json)

                } catch {

                    print("JSON processing failed")

                }  // end 4 do

            }  // end 3 let urlContent

        }  // end 2 if error}


问:
Validate URL query string with regex
I'm trying to validate a query string with regex. Note that I'm not trying to match out the values, but validate its syntax. I'm doing this to practice regex, so I'd appreciate help rather than "use this lib", although seing how it may have been done in a lib would help me, so show me if you've got one.

So, this would be the prerequisites:

It must start with a questionmark.

It may contain keys with or without values separated by an equals-sign, pairs separated by ampersand.

I've got pretty far, but I'm having trouble matching in regex that the equals-sign and ampersand must be in a certain order without having to repeat match groups. This is what I've got so far:

```<code>#^\?([\w\-]+((&|=)([\w\-]+)*)*)?$#
</code>```

It correctly matches ?abc=123&def=345, but it also incorrectly matches for example ?abc=123=456.

I could go overkill and do something like...

```<code>/^\?([\w\-]+=?([\w\-]+)?(&[\w\-]+(=?[\w\-]*)?)*)?$/
</code>```

... but I don't want to repeat the match groups which are the same anyway.

How can I tell regex that the separators between values must iterate between & and = without repeating match groups or catastrophic back tracking?

Thank you.

Edit:

I'd like to clarify that this is not meant for a real-world implementation; for that, the built-in library in your language, which is most likely available should be used. This question is asked because I want to improve my regex skills, and parsing a query string seemed like a rewarding challenge.

Title: Validate URL query string with regex

Body:
I'm trying to validate a query string with regex. Note that I'm not trying to match out the values, but validate its syntax. I'm doing this to practice regex, so I'd appreciate help rather than "use this lib", although seing how it may have been done in a lib would help me, so show me if you've got one.

So, this would be the prerequisites:

It must start with a questionmark.

It may contain keys with or without values separated by an equals-sign, pairs separated by ampersand.

I've got pretty far, but I'm having trouble matching in regex that the equals-sign and ampersand must be in a certain order without having to repeat match groups. This is what I've got so far:

#^\?([\w\-]+((&|=)([\w\-]+)*)*)?$#

It correctly matches ?abc=123&def=345, but it also incorrectly matches for example ?abc=123=456.

I could go overkill and do something like...

/^\?([\w\-]+=?([\w\-]+)?(&[\w\-]+(=?[\w\-]*)?)*)?$/

... but I don't want to repeat the match groups which are the same anyway.

How can I tell regex that the separators between values must iterate between & and = without repeating match groups or catastrophic back tracking?

Thank you.

Edit:

I'd like to clarify that this is not meant for a real-world implementation; for that, the built-in library in your language, which is most likely available should be used. This question is asked because I want to improve my regex skills, and parsing a query string seemed like a rewarding challenge.

Body:
I made this.

function isValidURL(url) {
  // based off https://mathiasbynens.be/demo/url-regex. testing https://regex101.com/r/pyrDTK/2
  var pattern = /^(?:(?:https?|ftp):\/\/)(?:\S+(?::\S*)?@)?(?:(?!10(?:\.\d{1,3}){3})(?!127(?:\.\d{1,3}){3})(?!169\.254(?:\.\d{1,3}){2})(?!192\.168(?:\.\d{1,3}){2})(?!172\.(?:1[6-9]|2\d|3[0-1])(?:\.\d{1,3}){2})(?:[1-9]\d?|1\d\d|2[01]\d|22[0-3])(?:\.(?:1?\d{1,2}|2[0-4]\d|25[0-5])){2}(?:\.(?:[1-9]\d?|1\d\d|2[0-4]\d|25[0-4]))|(?:(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)(?:\.(?:[a-z\x{00a1}-\x{ffff}0-9]+-?)*[a-z\x{00a1}-\x{ffff}0-9]+)*(?:\.(?:[a-z\x{00a1}-\x{ffff}]{2,})))(?::\d{2,5})?(?:\/?)(?:(?:\?(?:(?!&|\?)(?:\S))+=(?:(?!&|\?)(?:\S))+)(?:&(?:(?!&|\?)(?:\S))+=(?:(?!&|\?)(?:\S))+)*)?$/iuS;
  return pattern.test(url);
}

Base: https://mathiasbynens.be/demo/url-regex

Testing: https://regex101.com/r/pyrDTK/4/


问:
Tomcat Maximum No. of concurrent File Uploads
I have a Tomcat Server with 250 connection threads. When I simulate concurrent file upload for 30 files (each 100 MB), the CPU and RAM Memory of the server machine goes to peak i.e., 95% usage.

I use following block of code to read the file data from HTTP Post.

```<code>// request is instance of HTTPServletRequest
int nDataLength = request.getContentLength();

byte dataBytes[] = new byte[nDataLength];

int bytesRead = 0;
int totalBytesRead = 0;
int bytesLimit = 1024;

InputStream in = new InputStream(request.getInputStream());
try
{
    while(totalBytesRead < nDataLength)
    {
        bytesRead = in.read(dataBytes, totalBytesRead, bytesLimit);
        totalBytesRead  += bytesRead;
    }
}
catch(Exception ex)
{
    throw ex;
}
finally
{
    in.close();
}
</code>```

My doubts are:

What could be the maximum number of concurrent File Uploads (each 100 MB files) that a Tomcat Server can handle ?

Is there any optimization required in my code to make use of all 250 connection threads ?

Introducing sleep can cause lengthy uploads. How to write efficient code ?

Thanks in advance.

regards,
Kingsley Reuben J

NOTE: I wont be able to use third party applications to resolve this problem

答: You should write the received data to a temporary file (in smaller blocks, say 8KB) since 30 * 100MB = 3GB and probably you machine starts paging out memory. The throughput is limited by you interface adapter.</p>

Body:
I have a Tomcat Server with 250 connection threads. When I simulate concurrent file upload for 30 files (each 100 MB), the CPU and RAM Memory of the server machine goes to peak i.e., 95% usage.

I use following block of code to read the file data from HTTP Post.

// request is instance of HTTPServletRequest
int nDataLength = request.getContentLength();

byte dataBytes[] = new byte[nDataLength];

int bytesRead = 0;
int totalBytesRead = 0;
int bytesLimit = 1024;

InputStream in = new InputStream(request.getInputStream());
try
{
    while(totalBytesRead < nDataLength)
    {
        bytesRead = in.read(dataBytes, totalBytesRead, bytesLimit);
        totalBytesRead  += bytesRead;
    }
}
catch(Exception ex)
{
    throw ex;
}
finally
{
    in.close();
}

My doubts are:

What could be the maximum number of concurrent File Uploads (each 100 MB files) that a Tomcat Server can handle ?

Is there any optimization required in my code to make use of all 250 connection threads ?

Introducing sleep can cause lengthy uploads. How to write efficient code ?

Thanks in advance.

regards,
Kingsley Reuben J

NOTE: I wont be able to use third party applications to resolve this problem