问:
Creating a UInt16 from 2 UInt8s
In order to illustrate a concept to use later for larger data types like UInt128, and UInt256, I'm trying to do the following function:

My function takes 2 UInt8s, shifts the first (theoretically the more significant bits), to the left 8 and then adds int2, (theoretically the lower bits)

```<code>func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
   let x: UInt16 = (int1 << 8) + int2
   return x
}
</code>```

Is there something that I need to do to avoid the error: (int1 << 8) + int2 isn't equal to the specified type UInt16?

答:
Here is how I would do this, in a way that is endian-correct:

```<code>extension UInt16 {
    init(high: UInt8, low: UInt8) {
        self.init(littleEndian: UInt16(high) << 8 | UInt16(low))
    }
}

let i = UInt16(high: 0xAB, low: 0xCD)
// Represented on Little Endian platforms as 0xABCD
// Represented on    Big Endian platforms as 0xCDAB
</code>```

Here's a more involved, generic solution:

```<code>protocol PairedUnsignedInteger: UnsignedInteger {
    associatedtype SignedSelf: PairedSignedInteger
}

protocol PairedSignedInteger: SignedInteger {
    associatedtype UnsignedSelf: PairedUnsignedInteger
}

protocol BitPattternInitializable: FixedWidthInteger {
    associatedtype BitPatternSource: FixedWidthInteger
    init(bitPattern: BitPatternSource)
}

protocol UnsignedBitPattternInitializable: BitPattternInitializable, PairedSignedInteger
    where BitPatternSource == UnsignedSelf {}

protocol SignedBitPattternInitializable: BitPattternInitializable, PairedUnsignedInteger
    where BitPatternSource == SignedSelf {}

extension UInt:   PairedUnsignedInteger { typealias   SignedSelf =  Int   }
extension UInt8:  PairedUnsignedInteger { typealias   SignedSelf =  Int8  }
extension UInt16: PairedUnsignedInteger { typealias   SignedSelf =  Int16 }
extension UInt32: PairedUnsignedInteger { typealias   SignedSelf =  Int32 }
extension UInt64: PairedUnsignedInteger { typealias   SignedSelf =  Int64 }
extension  Int:     PairedSignedInteger { typealias UnsignedSelf = UInt   }
extension  Int8:    PairedSignedInteger { typealias UnsignedSelf = UInt8  }
extension  Int16:   PairedSignedInteger { typealias UnsignedSelf = UInt16 }
extension  Int32:   PairedSignedInteger { typealias UnsignedSelf = UInt32 }
extension  Int64:   PairedSignedInteger { typealias UnsignedSelf = UInt64 }

extension UInt:     SignedBitPattternInitializable {}
extension UInt8:    SignedBitPattternInitializable {}
extension UInt16:   SignedBitPattternInitializable {}
extension UInt32:   SignedBitPattternInitializable {}
extension UInt64:   SignedBitPattternInitializable {}
extension  Int:   UnsignedBitPattternInitializable {}
extension  Int8:  UnsignedBitPattternInitializable {}
extension  Int16: UnsignedBitPattternInitializable {}
extension  Int32: UnsignedBitPattternInitializable {}
extension  Int64: UnsignedBitPattternInitializable {}

protocol UnsignedHalfWidthInitializable: UnsignedInteger, FixedWidthInteger {
    associatedtype UnsignedHalfWidth: FixedWidthInteger
    init(high: UnsignedHalfWidth, low: UnsignedHalfWidth)
}

extension UnsignedHalfWidthInitializable {
    init(high: UnsignedHalfWidth, low: UnsignedHalfWidth) {
        self.init(littleEndian: Self(high) << UnsignedHalfWidth.bitWidth | Self(low))
    }
}

protocol SignedHalfWidthInitializable: UnsignedBitPattternInitializable {
    associatedtype UnsignedHalfWidth: UnsignedInteger, FixedWidthInteger
    init(high: UnsignedHalfWidth, low: UnsignedHalfWidth)
}

extension SignedHalfWidthInitializable {
    init(high: UnsignedHalfWidth, low: UnsignedHalfWidth) {
        let unsignedPromotedHigh = UnsignedSelf(high)
        let unsignedPromotedLow = UnsignedSelf(low)
        let unsignedLittleEndian = unsignedPromotedHigh << UnsignedHalfWidth.bitWidth | unsignedPromotedLow
        let signedLittleEndian = Self.init(bitPattern: unsignedLittleEndian)
        self.init(littleEndian: signedLittleEndian)
    }
}

extension UInt16: UnsignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt8  }
extension UInt32: UnsignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt16 }
extension UInt64: UnsignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt32 }
extension  Int16:   SignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt8  }
extension  Int32:   SignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt16 }
extension  Int64:   SignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt32 }

assert(UInt16(high: 0x12        as UInt8 ,  low: 0x34           as UInt8 ) == 0x1234                )
assert(UInt32(high: 0x1234      as UInt16,  low: 0x5678         as UInt16) == 0x1234_5678           )
assert(UInt64(high: 0x1234_5678 as UInt32,  low: 0x90AB_CDEF    as UInt32) == 0x1234_5678_90AB_CDEF )
assert( Int16(high: 0x12        as UInt8 ,  low: 0x34           as UInt8 ) == 0x1234                )
assert( Int32(high: 0x1234      as UInt16,  low: 0x5678         as UInt16) == 0x1234_5678           )
assert( Int64(high: 0x1234_5678 as UInt32,  low: 0x90AB_CDEF    as UInt32) == 0x1234_5678_90AB_CDEF )
</code>```

Title: Creating a UInt16 from 2 UInt8s

Body:
In order to illustrate a concept to use later for larger data types like UInt128, and UInt256, I'm trying to do the following function:

My function takes 2 UInt8s, shifts the first (theoretically the more significant bits), to the left 8 and then adds int2, (theoretically the lower bits)

func combineBits(int1: UInt8, int2: UInt8) -> UInt16 {
   let x: UInt16 = (int1 << 8) + int2
   return x
}

Is there something that I need to do to avoid the error: (int1 << 8) + int2 isn't equal to the specified type UInt16?

Body:
Here is how I would do this, in a way that is endian-correct:

extension UInt16 {
    init(high: UInt8, low: UInt8) {
        self.init(littleEndian: UInt16(high) << 8 | UInt16(low))
    }
}

let i = UInt16(high: 0xAB, low: 0xCD)
// Represented on Little Endian platforms as 0xABCD
// Represented on    Big Endian platforms as 0xCDAB

Here's a more involved, generic solution:

protocol PairedUnsignedInteger: UnsignedInteger {
    associatedtype SignedSelf: PairedSignedInteger
}

protocol PairedSignedInteger: SignedInteger {
    associatedtype UnsignedSelf: PairedUnsignedInteger
}

protocol BitPattternInitializable: FixedWidthInteger {
    associatedtype BitPatternSource: FixedWidthInteger
    init(bitPattern: BitPatternSource)
}

protocol UnsignedBitPattternInitializable: BitPattternInitializable, PairedSignedInteger
    where BitPatternSource == UnsignedSelf {}

protocol SignedBitPattternInitializable: BitPattternInitializable, PairedUnsignedInteger
    where BitPatternSource == SignedSelf {}

extension UInt:   PairedUnsignedInteger { typealias   SignedSelf =  Int   }
extension UInt8:  PairedUnsignedInteger { typealias   SignedSelf =  Int8  }
extension UInt16: PairedUnsignedInteger { typealias   SignedSelf =  Int16 }
extension UInt32: PairedUnsignedInteger { typealias   SignedSelf =  Int32 }
extension UInt64: PairedUnsignedInteger { typealias   SignedSelf =  Int64 }
extension  Int:     PairedSignedInteger { typealias UnsignedSelf = UInt   }
extension  Int8:    PairedSignedInteger { typealias UnsignedSelf = UInt8  }
extension  Int16:   PairedSignedInteger { typealias UnsignedSelf = UInt16 }
extension  Int32:   PairedSignedInteger { typealias UnsignedSelf = UInt32 }
extension  Int64:   PairedSignedInteger { typealias UnsignedSelf = UInt64 }

extension UInt:     SignedBitPattternInitializable {}
extension UInt8:    SignedBitPattternInitializable {}
extension UInt16:   SignedBitPattternInitializable {}
extension UInt32:   SignedBitPattternInitializable {}
extension UInt64:   SignedBitPattternInitializable {}
extension  Int:   UnsignedBitPattternInitializable {}
extension  Int8:  UnsignedBitPattternInitializable {}
extension  Int16: UnsignedBitPattternInitializable {}
extension  Int32: UnsignedBitPattternInitializable {}
extension  Int64: UnsignedBitPattternInitializable {}

protocol UnsignedHalfWidthInitializable: UnsignedInteger, FixedWidthInteger {
    associatedtype UnsignedHalfWidth: FixedWidthInteger
    init(high: UnsignedHalfWidth, low: UnsignedHalfWidth)
}

extension UnsignedHalfWidthInitializable {
    init(high: UnsignedHalfWidth, low: UnsignedHalfWidth) {
        self.init(littleEndian: Self(high) << UnsignedHalfWidth.bitWidth | Self(low))
    }
}

protocol SignedHalfWidthInitializable: UnsignedBitPattternInitializable {
    associatedtype UnsignedHalfWidth: UnsignedInteger, FixedWidthInteger
    init(high: UnsignedHalfWidth, low: UnsignedHalfWidth)
}

extension SignedHalfWidthInitializable {
    init(high: UnsignedHalfWidth, low: UnsignedHalfWidth) {
        let unsignedPromotedHigh = UnsignedSelf(high)
        let unsignedPromotedLow = UnsignedSelf(low)
        let unsignedLittleEndian = unsignedPromotedHigh << UnsignedHalfWidth.bitWidth | unsignedPromotedLow
        let signedLittleEndian = Self.init(bitPattern: unsignedLittleEndian)
        self.init(littleEndian: signedLittleEndian)
    }
}

extension UInt16: UnsignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt8  }
extension UInt32: UnsignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt16 }
extension UInt64: UnsignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt32 }
extension  Int16:   SignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt8  }
extension  Int32:   SignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt16 }
extension  Int64:   SignedHalfWidthInitializable { typealias UnsignedHalfWidth = UInt32 }

assert(UInt16(high: 0x12        as UInt8 ,  low: 0x34           as UInt8 ) == 0x1234                )
assert(UInt32(high: 0x1234      as UInt16,  low: 0x5678         as UInt16) == 0x1234_5678           )
assert(UInt64(high: 0x1234_5678 as UInt32,  low: 0x90AB_CDEF    as UInt32) == 0x1234_5678_90AB_CDEF )
assert( Int16(high: 0x12        as UInt8 ,  low: 0x34           as UInt8 ) == 0x1234                )
assert( Int32(high: 0x1234      as UInt16,  low: 0x5678         as UInt16) == 0x1234_5678           )
assert( Int64(high: 0x1234_5678 as UInt32,  low: 0x90AB_CDEF    as UInt32) == 0x1234_5678_90AB_CDEF )


来源: stackexchange

问:
Start new numbered list using jQuery
```<code><ul>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
    <li>test</li>
</ul>

<script>
$(document).ready(function(){
    var increment=3;
    var start=8;
    $("ul").children().each(function(i) {
        $(this).prepend('<tag>'+(start+i*increment).toString()+'.</tag>');
    });
});
</script>
</code>```

Is there a way to start a new count for another ul list?
With the code above this is what i get!

```<code><ul>
<li> test
<li> test
<li> test
<ul/>
</code>```

Output

```<code>1. test
2. test
3. test
</code>```

second ul list

```<code><ul>
<li> test
<li> test
<li> test
<ul/>
</code>```

Output

```<code>4. test
5. test
6. test
</code>```

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So is it possible to reset the count and star it all over again for another ul tag?
If it is possible how?

答:
Use an ordered list:

HTML

```<code><ol id="num_list">
  <li>How</li>
  <li>Now</li>
  <li>Brown</li>
  <li>Cow</li>
</ol>
</code>```

CSS

```<code>#num_list { list-style-type: decimal; }
</code>```

EDIT: if indeed you cannot use an ordered list, then use some JavaScript, like this:

```<code>$(function() {
  $('ul').each(function() {
     $(this).children().prepend(function(index, html) {
        return '<span>' + (index+1) + '. </span>';
     });
  });
});
</code>```

jsFiddle example

ContentLicense: CC BY-SA 2.5

Title: Start new numbered list using jQuery

Body:
test

test

test

test

test

test

test

Is there a way to start a new count for another ul list?
With the code above this is what i get!

 test

 test

 test

Output

1. test
2. test
3. test

second ul list

 test

 test

 test

Output

4. test
5. test
6. test

Instead of starting the second ul tag with 1. 2. 3. it continues to count using the first ul 5. 6. 7.

So is it possible to reset the count and star it all over again for another ul tag?
If it is possible how?

Body:
Use an ordered list:

HTML

<ol id="num_list">
  <li>How</li>
  <li>Now</li>
  <li>Brown</li>
  <li>Cow</li>
</ol>

CSS

#num_list { list-style-type: decimal; }

EDIT: if indeed you cannot use an ordered list, then use some JavaScript, like this:

$(function() {
  $('ul').each(function() {
     $(this).children().prepend(function(index, html) {
        return '<span>' + (index+1) + '. </span>';
     });
  });
});

jsFiddle example


问:
Scrape URL provided by CSV
I have a CSV containing some columns with data, the 15th column reports a list of URLs.  Now, I need to select each URL from the column, scrape a new price from the target webpage, and then store that in the price column to update the old price.

Without the same column enumeration, here is an approximate CSV:

```<code>asin,title,product URL,price
KSKFUSH01,Product Title,http://....,56.00
</code>```

Below is the sample code I wrote, but it merely prints URLs :(

```<code>import csv

with open('some.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)

for line in csv_reader:
    print(line[15])
</code>```

Any help or suggestions about accomplishing this goal?

Thanks

答:
It looks like you want to use a csv writer.  You can access the URL in each line.  Here is how you can write the new price.</p>

```<code>import csv
import urllib2
from bs4 import BeautifulSoup
with open('some.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)

with open('newPricedata.csv', 'w', newline='') as Newcsvfile:
Pricewriter = csv.writer(Newcsvfile, delimiter=' ',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
for line in csv_reader:
page = urllib2.urlopen(line[15])
soup = BeautifulSoup(page, ‘html.parser’)
price = soup.find(‘td’, attrs={‘class’: ‘a-size-mini a-color-price ebooks-price-savings a-text-normal'})
Pricewriter.writerow(line[0]+','+,line[1]+','....+price.text)
</code>```

ContentLicense: CC BY-SA 3.0

Title: Scrape URL provided by CSV

Body:
I have a CSV containing some columns with data, the 15th column reports a list of URLs.  Now, I need to select each URL from the column, scrape a new price from the target webpage, and then store that in the price column to update the old price.

Without the same column enumeration, here is an approximate CSV:

asin,title,product URL,price
KSKFUSH01,Product Title,http://....,56.00

Below is the sample code I wrote, but it merely prints URLs :(

import csv

with open('some.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)

for line in csv_reader:
    print(line[15])

Any help or suggestions about accomplishing this goal?

Thanks

Body:
It looks like you want to use a csv writer.  You can access the URL in each line.  Here is how you can write the new price.

import csv
import urllib2
from bs4 import BeautifulSoup
with open('some.csv', 'r') as csv_file:
csv_reader = csv.reader(csv_file)

with open('newPricedata.csv', 'w', newline='') as Newcsvfile:
Pricewriter = csv.writer(Newcsvfile, delimiter=' ',
                        quotechar='|', quoting=csv.QUOTE_MINIMAL)
for line in csv_reader:
page = urllib2.urlopen(line[15])
soup = BeautifulSoup(page, ‘html.parser’)
price = soup.find(‘td’, attrs={‘class’: ‘a-size-mini a-color-price ebooks-price-savings a-text-normal'})
Pricewriter.writerow(line[0]+','+,line[1]+','....+price.text)


问:
Typescript TS2322 error when using lookup types
I'm racking my brain why the following code doesn't compile:

```<code>interface Circle { type: "circle"; }
interface Rectangle { type: "rectangle"; }
type Shape = Circle | Rectangle;

interface Circle { type: "circle"; }
interface Rectangle { type: "rectangle"; }
type ShapeTemplate = {
  type: Shape["type"];
};

const fromTemplate = (template: ShapeTemplate): Shape => template;
</code>```

It breaks with:

TS2322: Type 'ShapeTemplate' is not assignable to type 'Shape'. Type 'ShapeTemplate' is not assignable to type 'Rectangle'. Types of property 'type' are incompatible. Type '"circle" | "rectangle"' is not assignable to type '"rectangle"'. Type '"circle"' is not assignable to type '"rectangle"'.

答:
The short answer is that it is generally too complex for the TypeScript compiler to reduce {x: A} | {x: B} to {x: A|B}.

You can read about this in the discussion at Microsoft/TypeScript#7553 and some other places I can't find right now. (Edit: also see Microsoft/TypeScript#18230.) I think the maintainers of the language don't consider it worthwhile to try to implement this, because most of the time it isn't useful in practice; types people really use generally have more than one property, and as soon as you have {x: A, y: P } | {x: B, y: Q}, a reduction to something like {x: A|B, y: P|Q} is not valid.

In practice, the workaround here is to just assert that a ShapeTemplate is assignable to Shape, like so:

```<code>const fromTemplate = (template: ShapeTemplate): Shape => template as Shape;
</code>```

Hope that helps; good luck!

Body:
I'm racking my brain why the following code doesn't compile:

interface Circle { type: "circle"; }
interface Rectangle { type: "rectangle"; }
type Shape = Circle | Rectangle;

interface Circle { type: "circle"; }
interface Rectangle { type: "rectangle"; }
type ShapeTemplate = {
  type: Shape["type"];
};

const fromTemplate = (template: ShapeTemplate): Shape => template;

It breaks with:

TS2322: Type 'ShapeTemplate' is not assignable to type 'Shape'. Type 'ShapeTemplate' is not assignable to type 'Rectangle'. Types of property 'type' are incompatible. Type '"circle" | "rectangle"' is not assignable to type '"rectangle"'. Type '"circle"' is not assignable to type '"rectangle"'.

Body:
The short answer is that it is generally too complex for the TypeScript compiler to reduce {x: A} | {x: B} to {x: A|B}.

You can read about this in the discussion at Microsoft/TypeScript#7553 and some other places I can't find right now. (Edit: also see Microsoft/TypeScript#18230.) I think the maintainers of the language don't consider it worthwhile to try to implement this, because most of the time it isn't useful in practice; types people really use generally have more than one property, and as soon as you have {x: A, y: P } | {x: B, y: Q}, a reduction to something like {x: A|B, y: P|Q} is not valid.

In practice, the workaround here is to just assert that a ShapeTemplate is assignable to Shape, like so:

const fromTemplate = (template: ShapeTemplate): Shape => template as Shape;

Hope that helps; good luck!


问:
Protecting against rapid ajax calls
I have a very simple game where a user clicks a button that calls some php function via ajax. The php function logs the call and decrements the users ability to click the button by 1.

If a user spam clicks the button or forces calls to the php function then the user can run the php function hundreds of times in 1 minute.

Is there a way to stop this?

Simple server-side code to limit calls every 1500ms, or not as it turns out :)

```<code>$user = Utils::getUser();
$now = round(microtime(true) * 1000);
// run spin
if($user){
    $dif = $now - $user->last_spin;
    if($user->spins > 0 && $dif > 1500){
        $user->last_spin = $now;
        $user->decrement('spins');
        $user->increment('spin_count');
        $user->save();

        //do stuff
     }
 }
</code>```

答:
To each request, store the microtime in session and check that session before executing the php code:</p>

```<code>if(!isset($_SESSION)) session_start();
if(!isset($_SESSION['ajax_call']) || $_SERVER['REQUEST_TIME_FLOAT'] >($_SESSION['ajax_call']+1.5)){
  //ok, your code to run
}
$_SESSION['ajax_call'] = $_SERVER['REQUEST_TIME_FLOAT'];
</code>```

Title: Protecting against rapid ajax calls

Body:
I have a very simple game where a user clicks a button that calls some php function via ajax. The php function logs the call and decrements the users ability to click the button by 1.

If a user spam clicks the button or forces calls to the php function then the user can run the php function hundreds of times in 1 minute.

Is there a way to stop this?

Simple server-side code to limit calls every 1500ms, or not as it turns out :)

$user = Utils::getUser();
$now = round(microtime(true) * 1000);
// run spin
if($user){
    $dif = $now - $user->last_spin;
    if($user->spins > 0 && $dif > 1500){
        $user->last_spin = $now;
        $user->decrement('spins');
        $user->increment('spin_count');
        $user->save();

        //do stuff
     }
 }

Body:
To each request, store the microtime in session and check that session before executing the php code:

if(!isset($_SESSION)) session_start();
if(!isset($_SESSION['ajax_call']) || $_SERVER['REQUEST_TIME_FLOAT'] >($_SESSION['ajax_call']+1.5)){
  //ok, your code to run
}
$_SESSION['ajax_call'] = $_SERVER['REQUEST_TIME_FLOAT'];


问:
Drop Pandas DataFrame lines according to a GropuBy property
I have some DataFrames with information about some elements, for instance:

```<code>my_df1=pd.DataFrame([[1,12],[1,15],[1,3],[1,6],[2,8],[2,1],[2,17]],columns=['Group','Value'])
my_df2=pd.DataFrame([[1,5],[1,7],[1,23],[2,6],[2,4]],columns=['Group','Value'])
</code>```

I have used something like dfGroups = df.groupby('group').apply(my_agg).reset_index(), so now I have DataFrmaes with informations on groups of the previous elements, say

```<code>my_df1_Group=pd.DataFrame([[1,57],[2,63]],columns=['Group','Group_Value'])
my_df2_Group=pd.DataFrame([[1,38],[2,49]],columns=['Group','Group_Value'])
</code>```

Now I want to clean my groups according to properties of their elements. Let's say that I want to discard groups containing an element with Value  greater than 16. So in my_df1_Group, there should only be the first group left, while both groups qualify to stay in my_df2_Group.

As I don't know how to get my_df1_Group and my_df2_Group from my_df1 and my_df2 in Python (I know other languages where it would simply be name+"_Group" with name looping in [my_df1,my_df2], but how do you do that in Python?), I build a list of lists:

```<code>SampleList = [[my_df1,my_df1_Group],[my_df2,my_df2_Group]]
</code>```

Then, I simply try this:

```<code>my_max=16
Bad=[]
for Sample in SampleList:
    for n in Sample[1]['Group']:
        df=Sample[0].loc[Sample[0]['Group']==n] #This is inelegant, but trying to work
                                                #with Sample[1] in the for doesn't work
        if (df['Value'].max()>my_max):
            Bad.append(1)
        else:
            Bad.append(0)
    Sample[1] = Sample[1].assign(Bad_Row=pd.Series(Bad))
    Sample[1] = Sample[1].query('Bad_Row == 0')
</code>```

Which runs without errors, but doesn't work. In particular, this doesn't add the column Bad_Row to my df, nor modifies my DataFrame (but the query runs smoothly even if Bad_Rowcolumn doesn't seem to exist...). On the other hand, if I run this technique manually on a df (i.e. not in a loop), it works.

How should I do?

答:
Based on dubbbdan idea, there is a code that works:</p>

```<code>my_max=16
def my_func(row,grouped_df1):
    if (grouped_df1.get_group(row['Group'])['Value']>my_max).any():
        return 1
    else:
        return 0

SampleList = [[my_df1,my_df1_Group],[my_df2,my_df2_Group]]

for Sample in SampleList:
    grouped_df = Sample[0].groupby('Group')
    Sample[1]['Bad_Row'] = Sample[1].apply(lambda x: my_func(x,grouped_df), axis=1)
    Sample[1].drop(Sample[1][Sample[1]['Bad_Row']!=0].index, inplace=True)
    Sample[1].drop(['Bad_Row'], axis = 1, inplace = True)
</code>```

Body:
I have some DataFrames with information about some elements, for instance:

my_df1=pd.DataFrame([[1,12],[1,15],[1,3],[1,6],[2,8],[2,1],[2,17]],columns=['Group','Value'])
my_df2=pd.DataFrame([[1,5],[1,7],[1,23],[2,6],[2,4]],columns=['Group','Value'])

I have used something like dfGroups = df.groupby('group').apply(my_agg).reset_index(), so now I have DataFrmaes with informations on groups of the previous elements, say

my_df1_Group=pd.DataFrame([[1,57],[2,63]],columns=['Group','Group_Value'])
my_df2_Group=pd.DataFrame([[1,38],[2,49]],columns=['Group','Group_Value'])

Now I want to clean my groups according to properties of their elements. Let's say that I want to discard groups containing an element with Value  greater than 16. So in my_df1_Group, there should only be the first group left, while both groups qualify to stay in my_df2_Group.

As I don't know how to get my_df1_Group and my_df2_Group from my_df1 and my_df2 in Python (I know other languages where it would simply be name+"_Group" with name looping in [my_df1,my_df2], but how do you do that in Python?), I build a list of lists:

SampleList = [[my_df1,my_df1_Group],[my_df2,my_df2_Group]]

Then, I simply try this:

my_max=16
Bad=[]
for Sample in SampleList:
    for n in Sample[1]['Group']:
        df=Sample[0].loc[Sample[0]['Group']==n] #This is inelegant, but trying to work
                                                #with Sample[1] in the for doesn't work
        if (df['Value'].max()>my_max):
            Bad.append(1)
        else:
            Bad.append(0)
    Sample[1] = Sample[1].assign(Bad_Row=pd.Series(Bad))
    Sample[1] = Sample[1].query('Bad_Row == 0')

Which runs without errors, but doesn't work. In particular, this doesn't add the column Bad_Row to my df, nor modifies my DataFrame (but the query runs smoothly even if Bad_Rowcolumn doesn't seem to exist...). On the other hand, if I run this technique manually on a df (i.e. not in a loop), it works.

How should I do?

Body:
Based on dubbbdan idea, there is a code that works:

my_max=16
def my_func(row,grouped_df1):
    if (grouped_df1.get_group(row['Group'])['Value']>my_max).any():
        return 1
    else:
        return 0

SampleList = [[my_df1,my_df1_Group],[my_df2,my_df2_Group]]

for Sample in SampleList:
    grouped_df = Sample[0].groupby('Group')
    Sample[1]['Bad_Row'] = Sample[1].apply(lambda x: my_func(x,grouped_df), axis=1)
    Sample[1].drop(Sample[1][Sample[1]['Bad_Row']!=0].index, inplace=True)
    Sample[1].drop(['Bad_Row'], axis = 1, inplace = True)


问:
Uncaught TypeError: Cannot read property '0' of undefined "Javascript"
I am working on eight tile puzzle problem.

I am getting an

"Uncaught TypeError: Cannot read property '0' of undefined" error
  while running this code:

```<code>for ( i = 0; i <= 2; i++ ) {
    for ( j = 0; j <= 2; j++ ) {
        startStateArr[i][j] = document.getElementById("start" + i + j).value;
    }
}
</code>```

Div ID's are as follows: start00, start01, start02, start10, start11, start12, start20, start21, start22.

答:
You need to initialize your second level arrays - startStateArr[i] = []. Do the same for the main array if not

```<code>var startStateArr = []; // If not done

for ( i = 0; i <= 2; i++ ) {
    startStateArr[i] = []; // Look at this line
    for ( j = 0; j <= 2; j++ ) {
        startStateArr[i][j] = document.getElementById("start" + i + j).value;
    }
}
</code>```

Body:
I am working on eight tile puzzle problem.

I am getting an

"Uncaught TypeError: Cannot read property '0' of undefined" error
  while running this code:

for ( i = 0; i <= 2; i++ ) {
    for ( j = 0; j <= 2; j++ ) {
        startStateArr[i][j] = document.getElementById("start" + i + j).value;
    }
}

Div ID's are as follows: start00, start01, start02, start10, start11, start12, start20, start21, start22.

Body:
You need to initialize your second level arrays - startStateArr[i] = []. Do the same for the main array if not

var startStateArr = []; // If not done

for ( i = 0; i <= 2; i++ ) {
    startStateArr[i] = []; // Look at this line
    for ( j = 0; j <= 2; j++ ) {
        startStateArr[i][j] = document.getElementById("start" + i + j).value;
    }
}


问:
Grails String to BigDecimal
I can't figure out how to transform a String into a BigDecimal inside a Grails Application.

I'm doing:

```<code>person.salary = params.number
</code>```

But I got a error.

```<code>*salary is a BigDecimal and params.number is always a string.
</code>```

答:
I can't figure out how to transform a String into a BigDecimal inside
  a Grails Application.

BigDecimal has a String constructor so one thing you could do is new BigDecimal(params.number).

You have other options...

You could do params.number as BigDecimal.

You could use one of the type converting convenience methods like params.double('number') as BigDecimal or you could provide a default value like params.double('number', 21.12) as BigDecimal).  Be aware that you could lose precision while converting to a double so if that is an issue, don't do that.

Title: Grails String to BigDecimal

Body:
I can't figure out how to transform a String into a BigDecimal inside a Grails Application.

I'm doing:

person.salary = params.number

But I got a error.

*salary is a BigDecimal and params.number is always a string.


问:
PlayerPaddle won't stop spinning
I'm trying to rotate my paddle once at a keypress, but at the moment, my turnLeft() won't stop spinning my paddle, while my turnRight() won't even start.

Here is where I call this in my GameScene.

```<code>class GameScreen(SceneBase):

    def __init__(self):
        SceneBase.__init__(self)

        self.player_paddle = classes.PlayerPaddle(screen_size)
        self.my_font = pygame.font.SysFont("Arial", 50)

    def ProcessInput(self, events, pressed_keys):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.player_paddle.direction = -1
                elif event.key == pygame.K_DOWN:
                    self.player_paddle.direction = 1
                elif event.key == pygame.K_LEFT:
                    self.player_paddle.turnLeft()
                elif event.key == pygame.K_RIGHT:
                    self.player_paddle.turnRight()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP and self.player_paddle.direction == -1:
                    self.player_paddle.direction = 0
                elif event.key == pygame.K_DOWN and self.player_paddle.direction == 1:
                    self.player_paddle.direction = 0

    def Update(self):
        self.player_paddle.update()
</code>```

And Here is my image class, which PlayerPaddle inherits from.

```<code>class Image(pygame.sprite.Sprite):

    def __init__(self, screen_size, color=(255,0,0)):
        super().__init__()
        self.screen_size = screen_size

        self.angle = 0
        #self.dir = 0

        self.original_image = pygame.image.load('naruto.png').convert()
        self.colorkey = self.original_image.get_at((0,0))

        self.original_image = pygame.transform.scale(self.original_image, (20, 100))
        self.rect = self.original_image.get_rect()

        self.update()

    def turnLeft(self):

        self.angle = (self.angle - 45) % 360

    def turnRight(self):
        print("entered")
        self.angle = (self.angle + 30) % 360

    def update(self):

        self.image = pygame.transform.rotate(self.original_image, self.angle).convert()
        self.image.set_colorkey(self.colorkey)

        #self.rect = self.image.get_rect(center = screen_rect.center)
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)

        self.olist = self.mask.outline()

        if self.olist:
            pygame.draw.lines(self.image, (0, 0, 0), 3, self.olist)

    def draw(self, screen):
        screen.blit(self.original_image, self.rect)
</code>```

Along with my PlayerPaddle class:

```<code>class PlayerPaddle(Image):

    def __init__(self, screen_size, color = (255,0,0)):

        self.centerx = 10
        self.centery = screen_size[1] // 2

        self.height = 100
        self.width = 20

        self.speed = 3
        self.direction = 0

        super().__init__(screen_size, color = (255, 0, 0))

    def update(self):

        super().update()
        self.centery += self.direction*self.speed

        self.rect.center = (self.centerx, self.centery)

        if self.rect.top < 0:
            self.rect.top = 0

        if self.rect.bottom > self.screen_size[1]-1:
            self.rect.bottom = self.screen_size[1]-1
</code>```

I tested my rotation code in another file and it worked perfectly (one key press is one rotation) so I am currently befuddled as to why this is happening right now.

EDIT: SceneBase class

```<code>class SceneBase:
    number_of_players = None
    is_game_over = False
    third_player_mode = None

    def __init__(self):
        self.next = self

    def ProcessInput(self, events, pressed_keys):
        pass

    def Update(self):
        pass

    def Render(self, screen):
        pass

    def SwitchToScene(self, next_scene):
        self.next = next_scene

    def Terminate(self):
        self.SwitchToScene(None)
</code>```

答:
Problem probably is because in update() you have

```<code> self.angle = (self.angle + self.dir) % 360
</code>```

and update() is executed in every loop.

You should change angle only in turnLeft and turnRight, not in update()

BTW: you don't need self.dir and self.angle because both do the same.

You rather need

in turnLeft() "minus 45"

```<code> self.angle = (self.angle - 45) % 360
</code>```

in turnRight() "plus 45"

```<code> self.angle = (self.angle + 45) % 360
</code>```

As I wrote in comment in turnLeft and turnRigth you should only change angle and eventually call update().

But it seems GameScene.Update() calls update() automatically so probably you don't need to call update() in turnLeft and turnRigth.

Title: PlayerPaddle won't stop spinning

Body:
I'm trying to rotate my paddle once at a keypress, but at the moment, my turnLeft() won't stop spinning my paddle, while my turnRight() won't even start.

Here is where I call this in my GameScene.

class GameScreen(SceneBase):

    def __init__(self):
        SceneBase.__init__(self)

        self.player_paddle = classes.PlayerPaddle(screen_size)
        self.my_font = pygame.font.SysFont("Arial", 50)

    def ProcessInput(self, events, pressed_keys):
        for event in events:
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_UP:
                    self.player_paddle.direction = -1
                elif event.key == pygame.K_DOWN:
                    self.player_paddle.direction = 1
                elif event.key == pygame.K_LEFT:
                    self.player_paddle.turnLeft()
                elif event.key == pygame.K_RIGHT:
                    self.player_paddle.turnRight()

            if event.type == pygame.KEYUP:
                if event.key == pygame.K_UP and self.player_paddle.direction == -1:
                    self.player_paddle.direction = 0
                elif event.key == pygame.K_DOWN and self.player_paddle.direction == 1:
                    self.player_paddle.direction = 0

    def Update(self):
        self.player_paddle.update()

And Here is my image class, which PlayerPaddle inherits from.

class Image(pygame.sprite.Sprite):

    def __init__(self, screen_size, color=(255,0,0)):
        super().__init__()
        self.screen_size = screen_size

        self.angle = 0
        #self.dir = 0

        self.original_image = pygame.image.load('naruto.png').convert()
        self.colorkey = self.original_image.get_at((0,0))

        self.original_image = pygame.transform.scale(self.original_image, (20, 100))
        self.rect = self.original_image.get_rect()

        self.update()

    def turnLeft(self):

        self.angle = (self.angle - 45) % 360

    def turnRight(self):
        print("entered")
        self.angle = (self.angle + 30) % 360

    def update(self):

        self.image = pygame.transform.rotate(self.original_image, self.angle).convert()
        self.image.set_colorkey(self.colorkey)

        #self.rect = self.image.get_rect(center = screen_rect.center)
        self.rect = self.image.get_rect()
        self.mask = pygame.mask.from_surface(self.image)

        self.olist = self.mask.outline()

        if self.olist:
            pygame.draw.lines(self.image, (0, 0, 0), 3, self.olist)

    def draw(self, screen):
        screen.blit(self.original_image, self.rect)

Along with my PlayerPaddle class:

class PlayerPaddle(Image):

    def __init__(self, screen_size, color = (255,0,0)):

        self.centerx = 10
        self.centery = screen_size[1] // 2

        self.height = 100
        self.width = 20

        self.speed = 3
        self.direction = 0

        super().__init__(screen_size, color = (255, 0, 0))

    def update(self):

        super().update()
        self.centery += self.direction*self.speed

        self.rect.center = (self.centerx, self.centery)

        if self.rect.top < 0:
            self.rect.top = 0

        if self.rect.bottom > self.screen_size[1]-1:
            self.rect.bottom = self.screen_size[1]-1

I tested my rotation code in another file and it worked perfectly (one key press is one rotation) so I am currently befuddled as to why this is happening right now.

EDIT: SceneBase class

class SceneBase:
    number_of_players = None
    is_game_over = False
    third_player_mode = None

    def __init__(self):
        self.next = self

    def ProcessInput(self, events, pressed_keys):
        pass

    def Update(self):
        pass

    def Render(self, screen):
        pass

    def SwitchToScene(self, next_scene):
        self.next = next_scene

    def Terminate(self):
        self.SwitchToScene(None)

Body:
Problem probably is because in update() you have

 self.angle = (self.angle + self.dir) % 360

and update() is executed in every loop.

You should change angle only in turnLeft and turnRight, not in update()

BTW: you don't need self.dir and self.angle because both do the same.

You rather need

in turnLeft() "minus 45"

 self.angle = (self.angle - 45) % 360

in turnRight() "plus 45"

 self.angle = (self.angle + 45) % 360

As I wrote in comment in turnLeft and turnRigth you should only change angle and eventually call update().

But it seems GameScene.Update() calls update() automatically so probably you don't need to call update() in turnLeft and turnRigth.


问:
How to convert multiple arrays into one array of multiple objects?
Given the following arrays:

```<code>let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];
</code>```

How to generated a new array of objects that look like that:

```<code>let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];
</code>```

This is what I came up so far:

```<code>for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}
</code>```

Thanks!

答:
You can use forEach as following :</p>

```<code>var result = [];
a.forEach((currenValue, index) => {
    result.push({x:x[index], y:b[index], w:c[index]});
});
console.log(result);
</code>```

Body:
Given the following arrays:

let x = [a, b, c, d];
let y = [e, f, g, h];
let w = [i, j, k, l];

How to generated a new array of objects that look like that:

let z = [
    {x: a, y: e, w: i},
    {x: b, y: f, w: j},
    {x: c, y: g, w: k},
    {x: d, y: h, w: l}
];

This is what I came up so far:

for(var i; i < x.length; i++) {

    x = x[i];
    y = y[i];
    w = w[i];

    obj = {
        x: x,
        y: y,
        w: w
    };

    z = [];
    z.push(obj);
}

Thanks!

Body:
You can use forEach as following :

var result = [];
a.forEach((currenValue, index) => {
    result.push({x:x[index], y:b[index], w:c[index]});
});
console.log(result);


问:
Performance impact of writing Azure diagnostic logs to blob storage
Our C# web app, running on Azure, uses System.Diagnostics.Trace to write trace statements for debugging/troubleshooting. Once we enable blob storage for these logs (using the "Application Logging (blob)" option in the Azure portal), the response time for our application slows down considerably. If I turn this option off, the web app speeds up again (though obviously we don't get logs in blob storage anymore).

Does anyone know if this is expected? We certainly write a lot of trace statements on every request (100 or so per request), but I would not think this was unusual for web application. Is there some way to diagnose why enabling blob storage for the logs dramatically slows down the execution of these trace statements? Is writing the trace statement synchronous with the logs being updated in blob storage, for instance?

答:
I was unable to find any information about how logging to blob storage in Azure was implemented. However, this is what I was able to deduce:

I confirmed that disabling the global lock had no effect. Therefore, the performance problem was not directly related to lock contention.

I also confirmed that if I turn AutoFlush off, the performance problem did not occur.

From further cross referencing the source code for the .NET trace API, my conclusion is that it appears that when you enable blob storage for logs, it injects some kind of trace listener into your application (the same way you might add a listener in web.config) and it synchronously writes every trace statement it receives to blob storage.

As such, it seems that there are a few ways to workaround this behavior:

Don't turn on AutoFlush, but manually flush periodically. This will prevent the synchronous blob writes from interrupting every log statement.

Write your own daemon that will periodically copy local log files to blob storage or something like this

Don't use this blob storage feature at all but instead leverage the tracing functionality in Application Insights.

I ended up doing #3 because, as it turns out, we already had Application Insights configured and on, we just didn't realize it could handle trace logging and querying. After disabling sampling for tracing events, we now have a way to easily query for any log statement remotely and get the full set of traces subject to any criteria (keyword match, all traces for a particular request, all traces in a particular time period, etc.)  Moreover, there is no noticeable synchronous overhead to writing log statements with the Application Insights trace listener, so nothing in our application has to change (we can continue using the .NET trace class). As a bonus, since Application Insights tracing is pretty flexible with the tracing source, we can even switch to another higher performance logging API (e.g. ETW or log4net) if needed and Application Insights still works.

Ultimately, you should consider using Application Insights for storing and querying your traces. Depending on why you wanted your logs in blob storage in the first place, it may or may not meet your needs, but it worked for us.


问:
stl vector reserve
I was trying to pre-allocate a vector of integer like this

```<code>vector<int> tmp_color; tmp_color.reserve(node_obj[node].c_max);
    for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
         tmp_color[tmp_color_idx] = tmp_color_idx;
</code>```

where node_obj[node].c_max is > 0 (I checked). size of tmp_color appears to be zero anyways, after the for loop. If there something wrong with the code?

Thanks

答:
reserve does not actually add elements to a vector; that's what resize does.  reserve just reserves space for them.  You either need to add the elements one-by-one in your loop, using:

```<code>tmp_color.push_back(tmp_color_idx);
</code>```

or change your use of reserve to resize.

Title: stl vector reserve

Body:
I was trying to pre-allocate a vector of integer like this

vector<int> tmp_color; tmp_color.reserve(node_obj[node].c_max);
    for(int tmp_color_idx = 0; tmp_color_idx < node_obj[node].c_max; tmp_color_idx++)
         tmp_color[tmp_color_idx] = tmp_color_idx;

where node_obj[node].c_max is > 0 (I checked). size of tmp_color appears to be zero anyways, after the for loop. If there something wrong with the code?

Thanks

Body:
reserve does not actually add elements to a vector; that's what resize does.  reserve just reserves space for them.  You either need to add the elements one-by-one in your loop, using:

tmp_color.push_back(tmp_color_idx);

or change your use of reserve to resize.


问:
Translate the content of a page to other language using Microsoft APIs
We have a requirement to translate the content of a page or rather full page to other language for instance from English to Spanish,

I tried to use the variations available OOTB to translate but it doesn't work and only the OOTB options are translated but not the content on the page.

Is there anyway to accomplish the same using Microsoft APIs?

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
using Microsoft.Office.Client.TranslationServices;
using System.Security;

namespace testTranslate
{
    class Program
    {
        static void Main(string[] args)

        {
            ClientContext clientContext = new ClientContext("https://xyz.sharepoint.com/sites/abc/");
            string username = "abc@xyz.onmicrosoft.com", pssword = "";
            var securePassword = new SecureString();
            foreach (char c in pssword)
            {
                securePassword.AppendChar(c);
            }
            var onlineCredentials = new SharePointOnlineCredentials(username, securePassword);
            clientContext.Credentials = onlineCredentials;
            string jobID;
            string culture = "en";
            string name = "translationJob1";
            string inputFile = "https://xyz.sharepoint.com/sites/abc/SitePages/testTranslate.aspx";
            string outputFile = "https://xyz.sharepoint.com/sites/abc/SitePages/testTranslateEnglish.aspx";
            TranslationJob job = new TranslationJob(clientContext, culture);
            job.AddFile(inputFile, outputFile);
            job.Name = name;
            job.Start();
            clientContext.Load(job);
            clientContext.ExecuteQuery();
            //To retrieve the translation job ID.
            jobID = job.JobId.ToString();

            //IEnumerable<string> supportedLanguages = TranslationJob.EnumerateSupportedLanguages(clientContext);
            //clientContext.ExecuteQuery();
            //foreach (string item in supportedLanguages)
            //{
            //    Console.Write(item + ", ");
            //}
            Console.WriteLine("Script completed,press any key to exit");
            Console.ReadKey();

        }
    }
}
</code>```

Thanks

Paru

答:
Not a SharePoint expert, but you probably need to add code to translate the actual document. Here is a link to a full document translation tool using the Microsoft Translator API:

https://github.com/MicrosoftTranslator/DocumentTranslator

Body:
We have a requirement to translate the content of a page or rather full page to other language for instance from English to Spanish,

I tried to use the variations available OOTB to translate but it doesn't work and only the OOTB options are translated but not the content on the page.

Is there anyway to accomplish the same using Microsoft APIs?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint;
using Microsoft.Office.Client.TranslationServices;
using System.Security;

namespace testTranslate
{
    class Program
    {
        static void Main(string[] args)

        {
            ClientContext clientContext = new ClientContext("https://xyz.sharepoint.com/sites/abc/");
            string username = "abc@xyz.onmicrosoft.com", pssword = "";
            var securePassword = new SecureString();
            foreach (char c in pssword)
            {
                securePassword.AppendChar(c);
            }
            var onlineCredentials = new SharePointOnlineCredentials(username, securePassword);
            clientContext.Credentials = onlineCredentials;
            string jobID;
            string culture = "en";
            string name = "translationJob1";
            string inputFile = "https://xyz.sharepoint.com/sites/abc/SitePages/testTranslate.aspx";
            string outputFile = "https://xyz.sharepoint.com/sites/abc/SitePages/testTranslateEnglish.aspx";
            TranslationJob job = new TranslationJob(clientContext, culture);
            job.AddFile(inputFile, outputFile);
            job.Name = name;
            job.Start();
            clientContext.Load(job);
            clientContext.ExecuteQuery();
            //To retrieve the translation job ID.
            jobID = job.JobId.ToString();

            //IEnumerable<string> supportedLanguages = TranslationJob.EnumerateSupportedLanguages(clientContext);
            //clientContext.ExecuteQuery();
            //foreach (string item in supportedLanguages)
            //{
            //    Console.Write(item + ", ");
            //}
            Console.WriteLine("Script completed,press any key to exit");
            Console.ReadKey();

        }
    }
}

Thanks

Paru


问:
Perform group by average without grouping rows into a single output row in pandas
I'm trying to perform the equivalent of postgreSQL'a WINDOW function in pandas. Basically, I want to average column values in a specific group and create a new column with the results without grouping the rows into a single output row.

Here's an example:

```<code>data = pd.DataFrame(
'name': ['Steve', 'Jim', 'Anna', 'Susie', 'Greg', 'John', 'Sabrina'],
'salary': [100, 200, 300, 100, 250, 90, 260],
'department': ['Finance', 'Finance', 'HR', 'Finance', 'Operations', 'HR',
'Operations']
})
</code>```

I can group by and average the salaries with

```<code>data.groupby('department').agg('mean')
</code>```

and then left merge the results with the original data.

The final result should have all the all the rows and columns 'name', 'department' and 'avg salary by department'.

I'm wondering if there is a quicker and more elegant way of doing this.

答:
Sounds like you need transform

```<code>df['Mean']=df.groupby('department').transform('mean')
df
Out[656]:
   department     name  salary        Mean
0     Finance    Steve     100  133.333333
1     Finance      Jim     200  133.333333
2          HR     Anna     300  195.000000
3     Finance    Susie     100  133.333333
4  Operations     Greg     250  255.000000
5          HR     John      90  195.000000
6  Operations  Sabrina     260  255.000000
</code>```

Body:
I'm trying to perform the equivalent of postgreSQL'a WINDOW function in pandas. Basically, I want to average column values in a specific group and create a new column with the results without grouping the rows into a single output row.

Here's an example:

data = pd.DataFrame(
'name': ['Steve', 'Jim', 'Anna', 'Susie', 'Greg', 'John', 'Sabrina'],
'salary': [100, 200, 300, 100, 250, 90, 260],
'department': ['Finance', 'Finance', 'HR', 'Finance', 'Operations', 'HR',
'Operations']
})

I can group by and average the salaries with

data.groupby('department').agg('mean')

and then left merge the results with the original data.

The final result should have all the all the rows and columns 'name', 'department' and 'avg salary by department'.

I'm wondering if there is a quicker and more elegant way of doing this.

Body:
Sounds like you need transform

df['Mean']=df.groupby('department').transform('mean')
df
Out[656]:
   department     name  salary        Mean
0     Finance    Steve     100  133.333333
1     Finance      Jim     200  133.333333
2          HR     Anna     300  195.000000
3     Finance    Susie     100  133.333333
4  Operations     Greg     250  255.000000
5          HR     John      90  195.000000
6  Operations  Sabrina     260  255.000000


问:
Optimal way to get last posts of user's friends in Firebase
In my DB each user has friends. And I need to get 50 last posts of the user's friends. See below structure of posts of each user in Firebase DB.

So what is optimal way to do that? If a user has for example 150 friends, then my Android app should have as many listeners as friends. Is it ok to have 150 or more DB listeners in the app? Also what is the way to get all friends' posts in single query? Thanks.

```<code>root
- posts
  - {userUid}
    - {postUid}
      - text
      - dateCreated
</code>```

答: What I would do is have a friendsListener, once initialized I would loop through my friends and register their reference in my listener vs 150 listeners. </p>

Body:
In my DB each user has friends. And I need to get 50 last posts of the user's friends. See below structure of posts of each user in Firebase DB.

So what is optimal way to do that? If a user has for example 150 friends, then my Android app should have as many listeners as friends. Is it ok to have 150 or more DB listeners in the app? Also what is the way to get all friends' posts in single query? Thanks.

root
- posts
  - {userUid}
    - {postUid}
      - text
      - dateCreated


问:
How does one add a formatted date to a primeng p-column?
I have an interface for a JSON object that has Date columns in it.  What gets displayed is the number of seconds since the epoch.
I am trying to format the date values, but I am not having much luck.

Can someone point me in the right direction, perhaps with an example?

```<code>   <p-dataTable [value]="observations" [rows]="20" [paginator]="true" [responsive]=true selectionMode="single" [(selection)]="selectedObservation" (onRowSelect)="onRowSelect($event)">
    <p-header>List of Observations</p-header>
    <p-column field="id" header="ID" [sortable]="true" [style]="{'width': '100px'}"></p-column>
    <p-column field="description" header="Description" [sortable]="true"></p-column>
    <p-column field="citation.id" header="CitationID" [sortable]="true" [style]="{'width': '100px'}"></p-column>
    <p-column field="citation.citationShortDescription" header="Citation Short Description" [sortable]="true"></p-column>
    <p-column field="citation.citationDesc" header="Citation Desc" [sortable]="true"></p-column>
    <p-column field="citation.citationObservations" header="Citation Observations" [sortable]="true"></p-column>
    <p-column field="citation.dateCorrectionReceived" header="Date Correction Received" [sortable]="true"></p-column>

    <p-column field="citation.inspectionDate" header="Inspection Date" [sortable]="true">
            <ng-template let-col let-row="rowData" pTemplate="body">
                {{row[col.value]}}
            </ng-template>
    </p-column>

    <p-column field="citation.inspectionDate" header="Inspection Date" [sortable]="true"></p-column>
    <p-column field="citation.inspectionEndDate" header="Inspection End Date" [sortable]="true"></p-column>
    <p-column field="citation.cfrCiteLang" header="Cfr Cite Lang" [sortable]="true"></p-column>
    <p-column field="correctionStatus.status" header="Correction Status" [sortable]="true"></p-column>
    <p-column field="citation.assignment.userId" header="Assigned To" [sortable]="true"></p-column>
    <p-column field="citation.assignment.dateAssigned" header="Date Assigned" [sortable]="true"></p-column>
    <p-column field="citation.assignment.percentInterstate" header="% Interstate" [sortable]="true"></p-column>
    <p-column field="citation.assignment.inspectionalResponsibilty" header="Inspectional Responsibilty" [sortable]="true"></p-column>
</p-dataTable>

    import { Citation } from './citation';
import { CorrectiveAction } from './corrective-action';
import { Operation } from './operation';
import { CorrectionStatus } from './correction-status';

export interface Observation {
    id: number;
    description: string;
    creatdBy: string;
    creatdDt: Date;
    mdfydBy: string;
    mdfydDt: Date;
    citation: Citation;
    correctiveActions: Set<CorrectiveAction>;
    operation: Operation;
    correctionStatus: CorrectionStatus;
}
    import { RefCd } from './refcd';
import { Assignment } from './assignment';
import { Operation } from './operation';

export interface Citation {
    id: number;
    cfrCiteLang: string;
    citationDesc: string;
    issueDate: Date;
    citationShortDescription: string;
    citationObservations: string;
    dateCorrectionReceived: Date;
    inspectionEndDate: Date;
    inspectionDate: Date;
    creatdBy: string;
    creatdDt: Date;
    mdfydBy: string;
    mdfydDt: Date;
    refcd: RefCd;
    assignment: Assignment;
    operation: Operation;
}
</code>```

I also tried this, but it displays nothing.

```<code>        <p-column field="citation.inspectionDate" header="Inspection Date" [sortable]="true">
            <ng-template let-row="rowData" pTemplate="body">
                {{row.inspectionDate | date}}
            </ng-template>
    </p-column>
</code>```

答:
```<code><p-column field="citation.inspectionDate" header="Inspection Date" [sortable]="true">
        <ng-template let-row="rowData" pTemplate="body">
            {{row.inspectionDate | date:'MM/dd/yyyy'}}
        </ng-template>
</p-column>
</code>```

you can also use DatePipe

{{row.inspectionDate | date:'shortDate''}}

For more information please visit this link.

Body:
I have an interface for a JSON object that has Date columns in it.  What gets displayed is the number of seconds since the epoch.
I am trying to format the date values, but I am not having much luck.

Can someone point me in the right direction, perhaps with an example?

List of Observations

            <ng-template let-col let-row="rowData" pTemplate="body">
                {{row[col.value]}}
            </ng-template>

    import { Citation } from './citation';
import { CorrectiveAction } from './corrective-action';
import { Operation } from './operation';
import { CorrectionStatus } from './correction-status';

export interface Observation {
    id: number;
    description: string;
    creatdBy: string;
    creatdDt: Date;
    mdfydBy: string;
    mdfydDt: Date;
    citation: Citation;
    correctiveActions: Set<CorrectiveAction>;
    operation: Operation;
    correctionStatus: CorrectionStatus;
}
    import { RefCd } from './refcd';
import { Assignment } from './assignment';
import { Operation } from './operation';

export interface Citation {
    id: number;
    cfrCiteLang: string;
    citationDesc: string;
    issueDate: Date;
    citationShortDescription: string;
    citationObservations: string;
    dateCorrectionReceived: Date;
    inspectionEndDate: Date;
    inspectionDate: Date;
    creatdBy: string;
    creatdDt: Date;
    mdfydBy: string;
    mdfydDt: Date;
    refcd: RefCd;
    assignment: Assignment;
    operation: Operation;
}

I also tried this, but it displays nothing.

            <ng-template let-row="rowData" pTemplate="body">
                {{row.inspectionDate | date}}
            </ng-template>

Body:
<p-column field="citation.inspectionDate" header="Inspection Date" [sortable]="true">
        <ng-template let-row="rowData" pTemplate="body">
            {{row.inspectionDate | date:'MM/dd/yyyy'}}
        </ng-template>
</p-column>

you can also use DatePipe

{{row.inspectionDate | date:'shortDate''}}

For more information please visit this link.


答:
Try this just use the select and replace #foo with your source of records, and ignore all of the setup unless you just want to run this specific example.

The grouping is based on position, and you can use floor((row_number() over (order by (select 1)) - 1) / 3) to get a group for every three rows.

```<code>create table #foo (
Name varchar(50),
StringValue varchar(50))

insert into #foo values ('Amount', '200')
insert into #foo values ('Target', '66')
insert into #foo values ('Date', '2017-1-1')
insert into #foo values ('Amount', '205')
insert into #foo values ('Target', '67')
insert into #foo values ('Date', '2017-3-1')

select
    max(case when Name = 'Amount' then StringValue else null end) as Amount,
    max(case when Name = 'Target' then StringValue else null end) as Target,
    max(case when Name = 'Date' then StringValue else null end) as Date
from (
    select floor((row_number() over (order by (select 1)) - 1) / 3) as group_on, * from #foo
    ) temp
group by group_on

drop table #foo
</code>```

Title: SQL Server - transpose table and return temporary table with correct format

Body:
I have a non-modifiable SQL transaction that returns the following data:

----------------------
| NAME    |   VALUE  |
----------------------
| Amount   |    ...  |
----------------------
| Target   |    ...  |
----------------------
| Date     |    ...  |
----------------------
| Amount   |    ...  |
----------------------
| Target   |    ...  |
----------------------
| Date     |    ...  |
----------------------

e.g:

I want to format it so it looks like:

-----------------------------------------
|   Amount    |   Target    |   Date    |
-----------------------------------------
|    ...      |    ...      |   ...     |
-----------------------------------------

How would I go on accomplishing this?

The code I have is:

SELECT
NAME, VALUE
FROM
function(@data)
/* AS PIVOT TABLE(...)*/

And I want to return a temporary table with the correct format.

Body:
Try this just use the select and replace #foo with your source of records, and ignore all of the setup unless you just want to run this specific example.

The grouping is based on position, and you can use floor((row_number() over (order by (select 1)) - 1) / 3) to get a group for every three rows.

create table #foo (
Name varchar(50),
StringValue varchar(50))

insert into #foo values ('Amount', '200')
insert into #foo values ('Target', '66')
insert into #foo values ('Date', '2017-1-1')
insert into #foo values ('Amount', '205')
insert into #foo values ('Target', '67')
insert into #foo values ('Date', '2017-3-1')

select
    max(case when Name = 'Amount' then StringValue else null end) as Amount,
    max(case when Name = 'Target' then StringValue else null end) as Target,
    max(case when Name = 'Date' then StringValue else null end) as Date
from (
    select floor((row_number() over (order by (select 1)) - 1) / 3) as group_on, * from #foo
    ) temp
group by group_on

drop table #foo


问:
Bucket Sort implementation in Objective C
I've been implementing different sorting algorithms in Objective-C (quicksort, mergesort, bubblesort). But I haven't found any clear implementation of Bucket Sort algorithm

I'm trying to find a simple and efficient implementation of Bucket Sort algorithm in objective C.

答:
I ended up doing it my self, here's my implementation if anyone needs it:</p>

```<code>- (NSArray*)bucketSort:(NSArray<NSNumber*> *)array buckets:(NSInteger)k {

    // Initialize array of buckets
    NSMutableArray<NSMutableArray*> *buckets = [NSMutableArray arrayWithCapacity:k];
    for (int i=0; i < buckets.count; i++)
        buckets[i] = [NSMutableArray new];

    // Add elements to buckets
    for (int i=0; i < buckets.count; i++) {
        NSInteger index = k * array[i].floatValue; // Asuming "array" has values between 0 and 1
        if (index < buckets.count) [buckets[index] addObject:array[i]];
    }

    NSMutableArray *sortedArray = [NSMutableArray new];

    // Sort individual buckets
    // Concatenate all sorted buckets in order
    for (int i=0; i < buckets.count; i++) {
        buckets[i] = [self quickSort:buckets[i]]; // Sorting algorithm like quicksort/mergesort/insertionsort
        [sortedArray addObjectsFromArray:buckets[i]];
    }

    return sortedArray;
}
</code>```

Body:
I ended up doing it my self, here's my implementation if anyone needs it:

- (NSArray*)bucketSort:(NSArray<NSNumber*> *)array buckets:(NSInteger)k {

    // Initialize array of buckets
    NSMutableArray<NSMutableArray*> *buckets = [NSMutableArray arrayWithCapacity:k];
    for (int i=0; i < buckets.count; i++)
        buckets[i] = [NSMutableArray new];

    // Add elements to buckets
    for (int i=0; i < buckets.count; i++) {
        NSInteger index = k * array[i].floatValue; // Asuming "array" has values between 0 and 1
        if (index < buckets.count) [buckets[index] addObject:array[i]];
    }

    NSMutableArray *sortedArray = [NSMutableArray new];

    // Sort individual buckets
    // Concatenate all sorted buckets in order
    for (int i=0; i < buckets.count; i++) {
        buckets[i] = [self quickSort:buckets[i]]; // Sorting algorithm like quicksort/mergesort/insertionsort
        [sortedArray addObjectsFromArray:buckets[i]];
    }

    return sortedArray;
}


问:
Failed tests when calling feature file from inside a scenario do not show which scenario (in the called feature) failed
I am reusing a feature file by calling it inside a Scenario. The context is that I want to have some common features that all my endpoints need to be tested for in a common.feature file. Then in the feature file (endpoint.feature) for a particular endpoint, I first call the common.feature file in a Scenario and then have other scenarios specific to this endpoint.

My common.feature file looks like this:

```<code>Feature: ...
Scenario: scenario 1
Scenario: scenario 2
</code>```

My endpoint.feature file looks like this:

```<code>Feature: ...
Scenario: test
  * call read('common.feature')
...
</code>```

Everything works as expected. The Scenarios from the common.feature file get executed. The issue is that if Scenario 1 from common.feature fails, I get the following result:

Tests in error:
    * call read('classpath:common/common.feature')(Scenario: test): feature call failed: classpath:common/common.feature(..)
    Scenario: test: feature call failed: classpath:common/common.feature(..)

Karate does not say exactly which Scenario from common.feature failed. If, for example, I have 20 Scenarios in common.feature, it would be great to see exactly which Scenarios failed.

Is there any way for having Karate list exactly which Scenarios in the called feature file failed (the way it shows during normal execution of a feature file)?

答: For anyone stumbling upon this in the future, this now works on v >= 0.6.2

Body:
I am reusing a feature file by calling it inside a Scenario. The context is that I want to have some common features that all my endpoints need to be tested for in a common.feature file. Then in the feature file (endpoint.feature) for a particular endpoint, I first call the common.feature file in a Scenario and then have other scenarios specific to this endpoint.

My common.feature file looks like this:

Feature: ...
Scenario: scenario 1
Scenario: scenario 2

My endpoint.feature file looks like this:

Feature: ...
Scenario: test
  * call read('common.feature')
...

Everything works as expected. The Scenarios from the common.feature file get executed. The issue is that if Scenario 1 from common.feature fails, I get the following result:

Tests in error:
    * call read('classpath:common/common.feature')(Scenario: test): feature call failed: classpath:common/common.feature(..)
    Scenario: test: feature call failed: classpath:common/common.feature(..)

Karate does not say exactly which Scenario from common.feature failed. If, for example, I have 20 Scenarios in common.feature, it would be great to see exactly which Scenarios failed.

Is there any way for having Karate list exactly which Scenarios in the called feature file failed (the way it shows during normal execution of a feature file)?


问:
how to set env variables in my CMD script
I have the following entryfile

```<code>FROM <image-of-nodejs>

COPY docker/node/entry.sh /var/entries/entry.sh
RUN apt-get update
RUN apt-get install ant -y
CMD ["/var/entries/entry.sh"]
</code>```

the image is used by a docker-compose file:

```<code>version: "3.3"

services:
  my_node:
    build:
      context: ./
      dockerfile: docker/node/Dockerfile-build-dev
    volumes:
      - type: bind
        source: ./
        target: /var/proj
</code>```

and the entry.sh file is the following:

```<code>#!/bin/bash
export QNAMAKER_SUB_KEY=b13615t
</code>```

If I then start the image and I enter the docker, I won't find my env variable set:

```<code>docker-compose up --force-recreate -d
docker-compose run my_node bash

root@9c081bedde65:/# echo ${QNAMAKER_SUB_KEY}

<empty>
</code>```

I would prefer to set my variables throug my script in place of the ENV Dockerfile command. What's wrong?

答:
There are a couple of things going on here.

First, docker-compose run doesn't run a command inside the container you started with docker-compose up.  It starts a new container to run a one-off command.  You probably want docker-compose exec.

The reason you don't see the variable when using docker-compose run is that you are overriding your CMD by providing a new command (bash) on the docker-compose run command line.

You could consider:

Using ENV statements in your Dockerfile.

Using the environment key in your docker-compose.yml

The former will embed the information into your image, while the latter would mean that the variable would be unset if you didn't explicitly set it in your docker-compose.yaml file (or using -e on the docker run command line).

You may be able to accomplish your goal using an ENTRYPOINT script and setting the value there, but that won't impact the environment visible to you when using docker exec (or docker-compose exec).

Body:
I have the following entryfile

FROM <image-of-nodejs>

COPY docker/node/entry.sh /var/entries/entry.sh
RUN apt-get update
RUN apt-get install ant -y
CMD ["/var/entries/entry.sh"]

the image is used by a docker-compose file:

version: "3.3"

services:
  my_node:
    build:
      context: ./
      dockerfile: docker/node/Dockerfile-build-dev
    volumes:
      - type: bind
        source: ./
        target: /var/proj

and the entry.sh file is the following:

#!/bin/bash
export QNAMAKER_SUB_KEY=b13615t

If I then start the image and I enter the docker, I won't find my env variable set:

docker-compose up --force-recreate -d
docker-compose run my_node bash

root@9c081bedde65:/# echo ${QNAMAKER_SUB_KEY}

<empty>

I would prefer to set my variables throug my script in place of the ENV Dockerfile command. What's wrong?


问:
Problem in JFileChooser

I want to use JfileChooser to choose a file and writeObject to the selected file or readObject from the selected file. I have serialize my class but I don't know how to serialize this MetalFileChooserUI? Or do I need to do it? Thank you very much.

smiliar error message to mine

Can someone help me to find a solution to it? Thank you.
My Error message:

java.io.NotSerializableException: javax.swing.plaf.metal.MetalFileChooserUI
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at javax.swing.ArrayTable.writeArrayTable(Unknown Source)
      at javax.swing.ActionMap.writeObject(Unknown Source)
      at sun.reflect.GeneratedMethodAccessor11.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
      at javax.swing.JComponent.writeObject(Unknown Source)
      at sun.reflect.GeneratedMethodAccessor10.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
      at javax.swing.JList.writeObject(Unknown Source)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteFields(Unknown Source)
      at java.io.ObjectOutputStream.defaultWriteObject(Unknown Source)
      at java.awt.Window.writeObject(Unknown Source)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at java.awt.Window.writeObject(Unknown Source)
      at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
      at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
      at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
      at java.lang.reflect.Method.invoke(Unknown Source)
      at java.io.ObjectStreamClass.invokeWriteObject(Unknown Source)
      at java.io.ObjectOutputStream.writeSerialData(Unknown Source)
      at java.io.ObjectOutputStream.writeOrdinaryObject(Unknown Source)
      at java.io.ObjectOutputStream.writeObject0(Unknown Source)
      at java.io.ObjectOutputStream.writeObject(Unknown Source)
      at ver_2.sudoku_GUI.actionPerformed(sudoku_GUI.java:90)
      at javax.swing.AbstractButton.fireActionPerformed(Unknown Source)
      at javax.swing.AbstractButton$Handler.actionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.fireActionPerformed(Unknown Source)
      at javax.swing.DefaultButtonModel.setPressed(Unknown Source)
      at javax.swing.AbstractButton.doClick(Unknown Source)
      at javax.swing.plaf.basic.BasicMenuItemUI.doClick(Unknown Source)
      at javax.swing.plaf.basic.BasicMenuItemUI$Handler.mouseReleased(Unknown Source)
      at java.awt.Component.processMouseEvent(Unknown Source)
      at javax.swing.JComponent.processMouseEvent(Unknown Source)
      at java.awt.Component.processEvent(Unknown Source)
      at java.awt.Container.processEvent(Unknown Source)
      at java.awt.Component.dispatchEventImpl(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.LightweightDispatcher.retargetMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.processMouseEvent(Unknown Source)
      at java.awt.LightweightDispatcher.dispatchEvent(Unknown Source)
      at java.awt.Container.dispatchEventImpl(Unknown Source)
      at java.awt.Window.dispatchEventImpl(Unknown Source)
      at java.awt.Component.dispatchEvent(Unknown Source)
      at java.awt.EventQueue.dispatchEvent(Unknown Source)
      at java.awt.EventDispatchThread.pumpOneEventForFilters(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForFilter(Unknown Source)
      at java.awt.EventDispatchThread.pumpEventsForHierarchy(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.pumpEvents(Unknown Source)
      at java.awt.EventDispatchThread.run(Unknown Source)

答: If you do not actually want to serialize the JFileChooser but you simply have a reference to it in some class of yours (that you need to serialize) make that reference transient so the serialisation process will simply ignore it.

Title: Problem in JFileChooser


问:
Converting string into html hyperlinks in Laravel
I'm using this code to hyperlink links from posts in Laravel:

```<code>{!! preg_replace('@(http(s)?)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@', '<a href="http$2://$4" target="_blank" title="$0">$0</a>', nl2br(e($post))) !!}
</code>```

But if I type this:

Hello.

How are you?

I'm getting this weird link "Hello. /> How are you?".

What should I do? I don't know how to work with regex. I want to hyperlink only strings that starts with http://, https://, www., not links like anyword.anydomain.

答:
The best solution I have found is this library: https://github.com/misd-service-development/php-linkify

```<code>$linkify = new \Misd\Linkify\Linkify();
$text = 'This is my text containing a link to www.example.com.';
echo $linkify->process($text);
</code>```

Would output:

This is my text containing a link to www.example.com.

Body:
I'm using this code to hyperlink links from posts in Laravel:

{!! preg_replace('@(http(s)?)?(://)?(([a-zA-Z])([-\w]+\.)+([^\s\.]+[^\s]*)+[^,.\s])@', '$0', nl2br(e($post))) !!}

But if I type this:

Hello.

How are you?

I'm getting this weird link "Hello. /> How are you?".

What should I do? I don't know how to work with regex. I want to hyperlink only strings that starts with http://, https://, www., not links like anyword.anydomain.

Body:
The best solution I have found is this library: https://github.com/misd-service-development/php-linkify

$linkify = new \Misd\Linkify\Linkify();
$text = 'This is my text containing a link to www.example.com.';
echo $linkify->process($text);

Would output:

This is my text containing a link to www.example.com.


问:
How to efficiently alias a float as both a named member and an element of an array?
I am implementing a particle-based fluid simulation. To represent vectors such as velocity, acceleration etc I have defined a class that looks like this

```<code>class Vec3f {
public:
    float x, y, z;

    // ... bunch of constructors, operators and utility functions
}
</code>```

I'm using the library nanoflann for kd-tree searches. To accommodate for arbitrary class designs, nanoflann requires a user-defined adaptor class that the kd-tree class then queries to get info about the particle dataset. One function that the adaptor has to offer, as described in the nanoflann documentation is the following.

```<code>// Must return the dim'th component of the idx'th point in the class:
inline T kdtree_get_pt(const size_t idx, int dim) const { ... }
</code>```

The problem is that this interface does not work seamlessly with the x, y, z representation. Naively, it would need to do something like this

```<code>inline float kdtree_get_pt(const size_t idx, int dim) const {
    switch(dim) {
    case 0:
        return particlearray[idx].x;
    case 1:
        return particlearray[idx].y;
    case 2:
        return particlearray[idx].z;
    }
}
</code>```

Building and querying the kd-tree consumes a significant portion of my app's runtime and kd_tree_get_pt gets queried multiple times in the process so I need it to be optimized. The following solution should be faster.

```<code>class Vec3f {
public:
    float values[3];
    // ...
}

// Then inside the adaptor class
inline float kdtree_get_pt(const size_t idx, int dim) const {
    return particlearrray[idx].values[dim];
}
</code>```

However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z notation for my equations without making kdtree_get_pt suboptimal.

Solutions I have considered:

Vec3f has member float values[3] and getters in the form of float& x(). The function call should be optimized away completely so this almost works but I do not want to have to add the parentheses in my equations if I can avoid it. eg I want to be able to write vec1.x - vec2.x instead of vec1.x() - vec2.x(). As far as I know, C++ does not offer a way to "disguise" a function call as a member variable, excluding preprocessor macros which I do not consider a safe solution.

Vec3f has members float values[3] and float& x, y, z where the latter are initialized to point to the corresponding floats in the array. I thought they would be optimized away as they are known at compile time and obviously cannot change value after initialization, but even with optimizations on, MSVC++ seems to actually store the float&s as can be seen by sizeof(Vec3f) growing by 12 bytes after their addition. This doubles the storage size of my dataset which raises a concern for cache misses when working with arbitrarily large datasets.

kdtree_get_pt uses float& values[3] to point to x, y, z. This might eliminate the branching cost, but I don't believe the extra level of indirection, nor the need to initialize all 3 references can be optimized away so it is presumably slower than the return particlearrray[idx][dim]` version.

kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members. Given a Vec3f object's address, I believe x, y, z are guaranteed to be stored in that order with the first one stored at the same address as the one given by the & operator on the Vec3f object, but even so I'm confused as to whether there exists a well-defined way to observe them.

答:
From a software engineering standpoint, it's best to expose the data through accessor and modifier functions only.

I would suggest:

```<code>class Vec3f
{
   public:

      float& operator[](size_t index) { return values[index]; }
      float operator[](size_t index) const { return values[index]; }

      float& x() { return values[0]; }
      float x() const { return values[0]; }

      float& y() { return values[1]; }
      float y() const { return values[1]; }

      float& z() { return values[2]; }
      float z() const { return values[2]; }

   private:
      float values[3];
}
</code>```

Re: kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members.

That's a bad idea in general. However, I don't see that being a problem with my suggestion.

Body:
I am implementing a particle-based fluid simulation. To represent vectors such as velocity, acceleration etc I have defined a class that looks like this

class Vec3f {
public:
    float x, y, z;

    // ... bunch of constructors, operators and utility functions
}

I'm using the library nanoflann for kd-tree searches. To accommodate for arbitrary class designs, nanoflann requires a user-defined adaptor class that the kd-tree class then queries to get info about the particle dataset. One function that the adaptor has to offer, as described in the nanoflann documentation is the following.

// Must return the dim'th component of the idx'th point in the class:
inline T kdtree_get_pt(const size_t idx, int dim) const { ... }

The problem is that this interface does not work seamlessly with the x, y, z representation. Naively, it would need to do something like this

inline float kdtree_get_pt(const size_t idx, int dim) const {
    switch(dim) {
    case 0:
        return particlearray[idx].x;
    case 1:
        return particlearray[idx].y;
    case 2:
        return particlearray[idx].z;
    }
}

Building and querying the kd-tree consumes a significant portion of my app's runtime and kd_tree_get_pt gets queried multiple times in the process so I need it to be optimized. The following solution should be faster.

class Vec3f {
public:
    float values[3];
    // ...
}

// Then inside the adaptor class
inline float kdtree_get_pt(const size_t idx, int dim) const {
    return particlearrray[idx].values[dim];
}

However, I much prefer the x, y, z interface for my equations. Now that the problem is clear, my question is how can I keep the x, y, z notation for my equations without making kdtree_get_pt suboptimal.

Solutions I have considered:

Vec3f has member float values[3] and getters in the form of float& x(). The function call should be optimized away completely so this almost works but I do not want to have to add the parentheses in my equations if I can avoid it. eg I want to be able to write vec1.x - vec2.x instead of vec1.x() - vec2.x(). As far as I know, C++ does not offer a way to "disguise" a function call as a member variable, excluding preprocessor macros which I do not consider a safe solution.

Vec3f has members float values[3] and float& x, y, z where the latter are initialized to point to the corresponding floats in the array. I thought they would be optimized away as they are known at compile time and obviously cannot change value after initialization, but even with optimizations on, MSVC++ seems to actually store the float&s as can be seen by sizeof(Vec3f) growing by 12 bytes after their addition. This doubles the storage size of my dataset which raises a concern for cache misses when working with arbitrarily large datasets.

kdtree_get_pt uses float& values[3] to point to x, y, z. This might eliminate the branching cost, but I don't believe the extra level of indirection, nor the need to initialize all 3 references can be optimized away so it is presumably slower than the return particlearrray[idx][dim]` version.

kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members. Given a Vec3f object's address, I believe x, y, z are guaranteed to be stored in that order with the first one stored at the same address as the one given by the & operator on the Vec3f object, but even so I'm confused as to whether there exists a well-defined way to observe them.

Body:
From a software engineering standpoint, it's best to expose the data through accessor and modifier functions only.

I would suggest:

class Vec3f
{
   public:

      float& operator[](size_t index) { return values[index]; }
      float operator[](size_t index) const { return values[index]; }

      float& x() { return values[0]; }
      float x() const { return values[0]; }

      float& y() { return values[1]; }
      float y() const { return values[1]; }

      float& z() { return values[2]; }
      float z() const { return values[2]; }

   private:
      float values[3];
}

Re: kdtree_get_pt uses reinterpret_cast or pointer magic to directly point into Vec3f's members.

That's a bad idea in general. However, I don't see that being a problem with my suggestion.


问:
One central XML Schema for multiple XML files?
Currently, we have several configuration XML files in use, which all handle a separate portion of our configuration. One for test sequence, one for timeout, etc. These separate XML files are all defined/validated against a single XML Schema document, which holds all the definitions used in the separate XML files. Is this good practice? Or should each type of XML file have its own, separate XML Schema?</p>

答: This is a perfectly fine practice. This permits you to use some of the same types in multiple document types.</p>


问:
RxJs: request list from server, consume values, re-request when we're almost out of values
I'm fetching a list of items from a REST api. The user interacts with each one via a click, and when there are only, say, a couple left unused, I'd like to repeat the request to get more items. I'm trying to do this using a proper RxJs (5) stream-oriented approach.

So, something like:

```<code>var userClick$ = Observable.fromEvent(button.nativeElement, 'click');

var needToExtend$ = new BehaviorSubject(1);

var list$ = needToExtend$
            .flatMap( () => this.http.get("http://myserver/get-list") )
            .flatMap( x => x['list'] );

var itemsUsed$ = userClick$.zip(list$, (click, item) => item);
itemsUsed$.subscribe( item => use(item) );
</code>```

and then, to trigger a re-load when necessary:

```<code>list$.subscribe(
    if (list$.isEmpty()) {
        needToExtend$.next(1);
    }
)
</code>```

This last bit is wrong, and manually re-triggering doesn't seem very "stream-oriented" even if it did work as intended. Any ideas?

This is similar to Rxjs - Consume API output and re-query when cache is empty but I can't make assumptions about the length of the list returned by the API, and I'd like to re-request before the list is completely consumed. And the solution there feels a bit too clever. There must be a more readable way, right?

答:
How about something like this:

```<code>const LIST_LIMIT = 3;
userClick$ = Observable.fromEvent(button.nativeElement, 'click');
list$ = this.http.get("http://myserver/get-list").map(r => r.list);

clickCounter$ = this.userClick$.scan((acc: number, val) => acc + 1, 0);

getList$ = new BehaviorSubject([]);

this.getList$
    .switchMap(previousList => this.list$)
    .switchMap(list => this.clickCounter$, (list, clickCount) => { return {list, clickCount}; })
    .filter(({list, clickCount}) => clickCount >= list.length - LIST_LIMIT)
    .map(({list, clickCount}) => list)
    .subscribe(this.getList$);
</code>```

The logic here if you define a list getter stream, and a signal to trigger it.

First, the signal causes switchMap to fetch a new list, which is then fed into another switchmap that resubscribes to a click counter.  You combine the result of both streams and feed that to filter, which only emits when the click count is greater than or equal to the list length minus 3 (or whatever you want).  Then the signal is subscribed to this whole stream so that it retriggers itself.

Edit: the biggest weakness of this is that you need to set the list value (for display) in a side effect rather than in subscription or with the async pipe.  You can rearrange it and multicast though:

```<code>const LIST_LIMIT = 3;
userClick$ = Observable.fromEvent(button.nativeElement, 'click');
list$ = this.http.get("http://myserver/get-list").map(r => r.list);

clickCounter$: Observable<number> = this.userClick$.scan((acc: number, val) => acc + 1, 0).startWith(0);

getList$ = new BehaviorSubject([]);

refresh$ = this.getList$
        .switchMap(list => this.clickCounter$
                               .filter(clickCount => list.length <= clickCount + LIST_LIMIT)
                               .first(),
            (list, clickCount) => list)
        .switchMap(previousList => this.list$)
        .multicast(() => this.getList$);

this.refresh$.connect();
this.refresh$.subscribe(e => console.log(e));
</code>```

This way has a few advantages, but may be a little less "readable".  The pieces are mostly the same, but instead you go to the counter first and let that lead into the switch to the list fetch.  and you multicast it to restart the counter.

Body:
I'm fetching a list of items from a REST api. The user interacts with each one via a click, and when there are only, say, a couple left unused, I'd like to repeat the request to get more items. I'm trying to do this using a proper RxJs (5) stream-oriented approach.

So, something like:

var userClick$ = Observable.fromEvent(button.nativeElement, 'click');

var needToExtend$ = new BehaviorSubject(1);

var list$ = needToExtend$
            .flatMap( () => this.http.get("http://myserver/get-list") )
            .flatMap( x => x['list'] );

var itemsUsed$ = userClick$.zip(list$, (click, item) => item);
itemsUsed$.subscribe( item => use(item) );

and then, to trigger a re-load when necessary:

list$.subscribe(
    if (list$.isEmpty()) {
        needToExtend$.next(1);
    }
)

This last bit is wrong, and manually re-triggering doesn't seem very "stream-oriented" even if it did work as intended. Any ideas?

This is similar to Rxjs - Consume API output and re-query when cache is empty but I can't make assumptions about the length of the list returned by the API, and I'd like to re-request before the list is completely consumed. And the solution there feels a bit too clever. There must be a more readable way, right?

Body:
How about something like this:

const LIST_LIMIT = 3;
userClick$ = Observable.fromEvent(button.nativeElement, 'click');
list$ = this.http.get("http://myserver/get-list").map(r => r.list);

clickCounter$ = this.userClick$.scan((acc: number, val) => acc + 1, 0);

getList$ = new BehaviorSubject([]);

this.getList$
    .switchMap(previousList => this.list$)
    .switchMap(list => this.clickCounter$, (list, clickCount) => { return {list, clickCount}; })
    .filter(({list, clickCount}) => clickCount >= list.length - LIST_LIMIT)
    .map(({list, clickCount}) => list)
    .subscribe(this.getList$);

The logic here if you define a list getter stream, and a signal to trigger it.

First, the signal causes switchMap to fetch a new list, which is then fed into another switchmap that resubscribes to a click counter.  You combine the result of both streams and feed that to filter, which only emits when the click count is greater than or equal to the list length minus 3 (or whatever you want).  Then the signal is subscribed to this whole stream so that it retriggers itself.

Edit: the biggest weakness of this is that you need to set the list value (for display) in a side effect rather than in subscription or with the async pipe.  You can rearrange it and multicast though:

const LIST_LIMIT = 3;
userClick$ = Observable.fromEvent(button.nativeElement, 'click');
list$ = this.http.get("http://myserver/get-list").map(r => r.list);

clickCounter$: Observable<number> = this.userClick$.scan((acc: number, val) => acc + 1, 0).startWith(0);

getList$ = new BehaviorSubject([]);

refresh$ = this.getList$
        .switchMap(list => this.clickCounter$
                               .filter(clickCount => list.length <= clickCount + LIST_LIMIT)
                               .first(),
            (list, clickCount) => list)
        .switchMap(previousList => this.list$)
        .multicast(() => this.getList$);

this.refresh$.connect();
this.refresh$.subscribe(e => console.log(e));

This way has a few advantages, but may be a little less "readable".  The pieces are mostly the same, but instead you go to the counter first and let that lead into the switch to the list fetch.  and you multicast it to restart the counter.


问:
Having trouble with $(this) in simple ES6 click handler

```<code>const letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","_"];

$.each(letters, (number, letter) => {
  let b = $('<button>');
   b.addClass('letter-button letter letter-button-color')
    .attr('data-let', letter)
    .text(letter);
   $('#buttons').append(b);
});
</code>```

```<code>$('.letter-button').on('click', () =>  {
    let fridgeMagnet = $('<div>');
    fridgeMagnet.addClass('letter fridge-color')
    .text($(this).data('let'));
    console.log(this);
    $('#display').append(fridgeMagnet);
});
</code>```

<p>This is an old exercise and the solution is with the outdated version of JavaScript.  I am trying to update step 4 and 5 to ES6, but $(this) is not working here. Can anyone explain to me how to fix the click handler and how $(this) changes from ES5 to ES6? We want the newly created buttons to appear on the backround fridge image with the correct letter data.  Also, what is 'data-let'?
</p>

答:
You cant use arrow function with jquery envent handlers because of $(this) ,and  arrow function is not the new function. the function keyword id not outdated ! use function () unstead.

You Can refer to this blog post for more info

Body:
const letters = ["A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z","_"];

$.each(letters, (number, letter) => {
  let b = $('<button>');
   b.addClass('letter-button letter letter-button-color')
    .attr('data-let', letter)
    .text(letter);
   $('#buttons').append(b);
});

$('.letter-button').on('click', () =>  {
    let fridgeMagnet = $('
');
    fridgeMagnet.addClass('letter fridge-color')
    .text($(this).data('let'));
    console.log(this);
    $('#display').append(fridgeMagnet);
});

This is an old exercise and the solution is with the outdated version of JavaScript.  I am trying to update step 4 and 5 to ES6, but $(this) is not working here. Can anyone explain to me how to fix the click handler and how $(this) changes from ES5 to ES6? We want the newly created buttons to appear on the backround fridge image with the correct letter data.  Also, what is 'data-let'?