问:
Swift: Nested type erasure
Using Swift 3.0 (I could use Swift 4.0 if that would help me... But I don't think it will) I would like to Type Erase two levels. I what to type erase a protocol having an associatedtype, which conforms to a protocol that in turn itself has an associatedtype. So one could say that I want to type erase nested associatedtypes.

The code below is an extremely simplified version of my code, but it is more clear that way. So what I really want is something like this:

Original Scenario - Unsolved

```<code>protocol Motor {
    var power: Int { get }
}

protocol Vehicle {
    associatedType Engine: Motor
    var engine: Engine { get }
}

protocol Transportation {
    associatedType Transport: Vehicle
    var transport: Transport { get }
}
</code>```

And then I would like to type erase Transportation and be able to store an array of AnyTransportation which could have any Vehicle which in turn could have any Motor.

So this is a scenario with 3 protocols, where 2 of them have (nested) associatedtypes.

I do not know how to do this. Actually, I do not even know how to solve the even more simple scenario:

Simplified Scenario - Unsolved

We could simplify the original scenario above to a version where we have 2 protocols, where only 1 of them have an associatedtype:

```<code>protocol Vehicle {
    var speed: Int { get }
}

protocol Transportation {
    associatedtype Transport: Vehicle
    var transport: Transport { get }
    var name: String { get }
}
</code>```

Then lets say that we have a Bus conforming to Vehicle:

```<code>struct Bus: Vehicle {
    var speed: Int { return 60 }
}
</code>```

And then we have two different BusLines, RedBusLine and BlueBusLine both conforming to Transportation

```<code>struct RedBusLine: Transportation {
    let transport: Bus
    var name = "Red line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}

struct BlueBusLine: Transportation {
    let transport: Bus
    var name = "Blue line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}
</code>```

We can then type erase Transportation using the base and box pattern and classes, as described by bignerdranch here:

```<code>final class AnyTransportation<_Transport: Vehicle>: Transportation {
    typealias Transport = _Transport
    private let box: _AnyTransportationBase<Transport>
    init<Concrete: Transportation>(_ concrete: Concrete) where Concrete.Transport == Transport {
        box = _AnyTransportationBox(concrete)
    }
    init(transport: Transport) { fatalError("Use type erasing init instead") }
    var transport: Transport { return box.transport }
    var name: String { return box.name }
}

final class _AnyTransportationBox<Concrete: Transportation>: _AnyTransportationBase<Concrete.Transport> {
    private let concrete: Concrete
    init(_ concrete: Concrete) { self.concrete = concrete; super.init() }
    required init(transport: Transport) { fatalError("Use type erasing init instead") }
    override var transport: Transport { return concrete.transport }
    override var name: String {return concrete.name }
}

class _AnyTransportationBase<_Transport: Vehicle> : Transportation {
    typealias Transport = _Transport
    init() { if type(of: self) == _AnyTransportationBase.self { fatalError("Use Box class") } }
    required init(transport: Transport) { fatalError("Use type erasing init instead") }
    var transport: Transport { fatalError("abstract") }
    var name: String { fatalError("abstract") }
}
</code>```

We can then put either RedBusLine or BlueBusLine in

```<code>let busRides: [AnyTransportation<Bus>] = [AnyTransportation(RedBusLine()), AnyTransportation(BlueBusLine())]
busRides.forEach { print($0.name) } // prints "Red line\nBlue line"
</code>```

In the blog post about type erasure linked to above, what I want is actually a workaround for Homogeneous Requirement.

Imagine we have another Vehicle, e.g a Ferry and a FerryLine:

```<code>struct Ferry: Vehicle {
    var speed: Int { return 40 }
}

struct FerryLine: Transportation {
    let transport: Ferry = Ferry()
    var name = "Ferry line"
}
</code>```

I guess we want to type erase Vehicle now? Because we want an array of AnyTransportation<AnyVehicle>, right?

```<code>final class AnyVehicle: Vehicle {
    private let box: _AnyVehicleBase
    init<Concrete: Vehicle>(_ concrete: Concrete) {
        box = _AnyVehicleBox(concrete)
    }
    var speed: Int { return box.speed }
}

final class _AnyVehicleBox<Concrete: Vehicle>: _AnyVehicleBase {
    private let concrete: Concrete
    init(_ concrete: Concrete) { self.concrete = concrete; super.init() }
    override var speed: Int { return concrete.speed }
}

class _AnyVehicleBase: Vehicle {
    init() { if type(of: self) == _AnyVehicleBase.self { fatalError("Use Box class") } }
    var speed: Int { fatalError("abstract") }
}

// THIS DOES NOT WORK
let rides: [AnyTransportation<AnyVehicle>] = [AnyTransportation(AnyVehicle(RedBusLine())), AnyTransportation(AnyVehicle(FerryLine()))] // COMPILE ERROR: error: argument type 'RedBusLine' does not conform to expected type 'Vehicle'
</code>```

Of course this does not work... because AnyTransportation expects passing in a type conforming to Transportation, but AnyVehicle does not conform to it of course.

But I have not been able to figure out a solution for this. Is there any?

Question 1: Is it possible to type erase the Simple Scenario allowing for: [AnyTransportation<AnyVehicle>]?

Question 2: If the Simple Scenario is solvable, is the original scenario also solvable?

Below follows only a more detailed explanation of what I want to achieve with the Original Scenario

Original Scenario - Expanded

My original need is to put any Transportation, having any Vehicle, that in itself has any Motor inside the same array:

```<code>let transportations: [AnyTransportation<AnyVehicle<AnyMotor>>] = [BusLine(), FerryLine()] // want to put `BusLine` and `FerryLine` in same array
</code>```

答:
If you want to express any transportation with any vehicle with any engine, then you want 3 boxes, each talking in terms of the "previous" type-erased wrappers. You don't want generic placeholders on any of these boxes, as you want to talk in terms of fully heterogenous instances (e.g not any transportation with a specific Vehicle type, or any vehicle with a specific Motor type).

Furthermore, rather than using a class hierarchy to perform the type erasing, you can use closures instead, which allows you to capture the base instance rather than storing it directly. This allows you to remove a significant amount of the boilerplate from your original code.

For example:

```<code>protocol Motor {
    var power: Int { get }
}

protocol Vehicle {
    associatedtype Engine : Motor
    var engine: Engine { get }
}

protocol Transportation {
    associatedtype Transport : Vehicle
    var transport: Transport { get }
    var name: String { get set }
}

// we need the concrete AnyMotor wrapper, as Motor is not a type that conforms to Motor
// (as protocols don't conform to themselves).
struct AnyMotor : Motor {

    // we can store base directly, as Motor has no associated types.
    private let base: Motor

    // protocol requirement just forwards onto the base.
    var power: Int { return base.power }

    init(_ base: Motor) {
        self.base = base
    }
}

struct AnyVehicle : Vehicle {

    // we cannot directly store base (as Vehicle has an associated type).
    // however we can *capture* base in a closure that returns the value of the property,
    // wrapped in its type eraser.
    private let _getEngine: () -> AnyMotor

    var engine: AnyMotor { return _getEngine() }

    init<Base : Vehicle>(_ base: Base) {
        self._getEngine = { AnyMotor(base.engine) }
    }
}

struct AnyTransportation : Transportation {

    private let _getTransport: () -> AnyVehicle
    private let _getName: () -> String
    private let _setName: (String) -> Void

    var transport: AnyVehicle { return _getTransport() }
    var name: String {
        get { return _getName() }
        set { _setName(newValue) }
    }

    init<Base : Transportation>(_ base: Base) {
        // similar pattern as above, just multiple stored closures.
        // however in this case, as we have a mutable protocol requirement,
        // we first create a mutable copy of base, then have all closures capture
        // this mutable variable.
        var base = base
        self._getTransport = { AnyVehicle(base.transport) }
        self._getName = { base.name }
        self._setName = { base.name = $0 }
    }
}

struct PetrolEngine : Motor {
    var power: Int
}

struct Ferry: Vehicle {
    var engine = PetrolEngine(power: 100)
}

struct FerryLine: Transportation {
    let transport = Ferry()
    var name = "Ferry line"
}

var anyTransportation = AnyTransportation(FerryLine())

print(anyTransportation.name) // Ferry line
print(anyTransportation.transport.engine.power) // 100

anyTransportation.name = "Foo bar ferries"
print(anyTransportation.name) // Foo bar ferries
</code>```

Note that we still built AnyMotor despite Motor not having any associated types. This is because protocols don't conform to themselves, so we cannot use Motor itself to satisfy the Engine associated type (that requires : Motor) – we currently have to build a concrete wrapper type for it.

Title: Swift: Nested type erasure

Body:
Using Swift 3.0 (I could use Swift 4.0 if that would help me... But I don't think it will) I would like to Type Erase two levels. I what to type erase a protocol having an associatedtype, which conforms to a protocol that in turn itself has an associatedtype. So one could say that I want to type erase nested associatedtypes.

The code below is an extremely simplified version of my code, but it is more clear that way. So what I really want is something like this:

Original Scenario - Unsolved

protocol Motor {
    var power: Int { get }
}

protocol Vehicle {
    associatedType Engine: Motor
    var engine: Engine { get }
}

protocol Transportation {
    associatedType Transport: Vehicle
    var transport: Transport { get }
}

And then I would like to type erase Transportation and be able to store an array of AnyTransportation which could have any Vehicle which in turn could have any Motor.

So this is a scenario with 3 protocols, where 2 of them have (nested) associatedtypes.

I do not know how to do this. Actually, I do not even know how to solve the even more simple scenario:

Simplified Scenario - Unsolved

We could simplify the original scenario above to a version where we have 2 protocols, where only 1 of them have an associatedtype:

protocol Vehicle {
    var speed: Int { get }
}

protocol Transportation {
    associatedtype Transport: Vehicle
    var transport: Transport { get }
    var name: String { get }
}

Then lets say that we have a Bus conforming to Vehicle:

struct Bus: Vehicle {
    var speed: Int { return 60 }
}

And then we have two different BusLines, RedBusLine and BlueBusLine both conforming to Transportation

struct RedBusLine: Transportation {
    let transport: Bus
    var name = "Red line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}

struct BlueBusLine: Transportation {
    let transport: Bus
    var name = "Blue line"
    init(transport: Bus = Bus()) {
        self.transport = transport
    }
}

We can then type erase Transportation using the base and box pattern and classes, as described by bignerdranch here:

final class AnyTransportation<_Transport: Vehicle>: Transportation {
    typealias Transport = _Transport
    private let box: _AnyTransportationBase<Transport>
    init<Concrete: Transportation>(_ concrete: Concrete) where Concrete.Transport == Transport {
        box = _AnyTransportationBox(concrete)
    }
    init(transport: Transport) { fatalError("Use type erasing init instead") }
    var transport: Transport { return box.transport }
    var name: String { return box.name }
}

final class _AnyTransportationBox<Concrete: Transportation>: _AnyTransportationBase<Concrete.Transport> {
    private let concrete: Concrete
    init(_ concrete: Concrete) { self.concrete = concrete; super.init() }
    required init(transport: Transport) { fatalError("Use type erasing init instead") }
    override var transport: Transport { return concrete.transport }
    override var name: String {return concrete.name }
}

class _AnyTransportationBase<_Transport: Vehicle> : Transportation {
    typealias Transport = _Transport
    init() { if type(of: self) == _AnyTransportationBase.self { fatalError("Use Box class") } }
    required init(transport: Transport) { fatalError("Use type erasing init instead") }
    var transport: Transport { fatalError("abstract") }
    var name: String { fatalError("abstract") }
}

We can then put either RedBusLine or BlueBusLine in

let busRides: [AnyTransportation<Bus>] = [AnyTransportation(RedBusLine()), AnyTransportation(BlueBusLine())]
busRides.forEach { print($0.name) } // prints "Red line\nBlue line"

In the blog post about type erasure linked to above, what I want is actually a workaround for Homogeneous Requirement.

Imagine we have another Vehicle, e.g a Ferry and a FerryLine:

struct Ferry: Vehicle {
    var speed: Int { return 40 }
}

struct FerryLine: Transportation {
    let transport: Ferry = Ferry()
    var name = "Ferry line"
}

I guess we want to type erase Vehicle now? Because we want an array of AnyTransportation<AnyVehicle>, right?

final class AnyVehicle: Vehicle {
    private let box: _AnyVehicleBase
    init<Concrete: Vehicle>(_ concrete: Concrete) {
        box = _AnyVehicleBox(concrete)
    }
    var speed: Int { return box.speed }
}

final class _AnyVehicleBox<Concrete: Vehicle>: _AnyVehicleBase {
    private let concrete: Concrete
    init(_ concrete: Concrete) { self.concrete = concrete; super.init() }
    override var speed: Int { return concrete.speed }
}

class _AnyVehicleBase: Vehicle {
    init() { if type(of: self) == _AnyVehicleBase.self { fatalError("Use Box class") } }
    var speed: Int { fatalError("abstract") }
}

// THIS DOES NOT WORK
let rides: [AnyTransportation<AnyVehicle>] = [AnyTransportation(AnyVehicle(RedBusLine())), AnyTransportation(AnyVehicle(FerryLine()))] // COMPILE ERROR: error: argument type 'RedBusLine' does not conform to expected type 'Vehicle'

Of course this does not work... because AnyTransportation expects passing in a type conforming to Transportation, but AnyVehicle does not conform to it of course.

But I have not been able to figure out a solution for this. Is there any?

Question 1: Is it possible to type erase the Simple Scenario allowing for: [AnyTransportation<AnyVehicle>]?

Question 2: If the Simple Scenario is solvable, is the original scenario also solvable?

Below follows only a more detailed explanation of what I want to achieve with the Original Scenario

Original Scenario - Expanded

My original need is to put any Transportation, having any Vehicle, that in itself has any Motor inside the same array:

let transportations: [AnyTransportation<AnyVehicle<AnyMotor>>] = [BusLine(), FerryLine()] // want to put `BusLine` and `FerryLine` in same array

Body:
If you want to express any transportation with any vehicle with any engine, then you want 3 boxes, each talking in terms of the "previous" type-erased wrappers. You don't want generic placeholders on any of these boxes, as you want to talk in terms of fully heterogenous instances (e.g not any transportation with a specific Vehicle type, or any vehicle with a specific Motor type).

Furthermore, rather than using a class hierarchy to perform the type erasing, you can use closures instead, which allows you to capture the base instance rather than storing it directly. This allows you to remove a significant amount of the boilerplate from your original code.

For example:

protocol Motor {
    var power: Int { get }
}

protocol Vehicle {
    associatedtype Engine : Motor
    var engine: Engine { get }
}

protocol Transportation {
    associatedtype Transport : Vehicle
    var transport: Transport { get }
    var name: String { get set }
}

// we need the concrete AnyMotor wrapper, as Motor is not a type that conforms to Motor
// (as protocols don't conform to themselves).
struct AnyMotor : Motor {

    // we can store base directly, as Motor has no associated types.
    private let base: Motor

    // protocol requirement just forwards onto the base.
    var power: Int { return base.power }

    init(_ base: Motor) {
        self.base = base
    }
}

struct AnyVehicle : Vehicle {

    // we cannot directly store base (as Vehicle has an associated type).
    // however we can *capture* base in a closure that returns the value of the property,
    // wrapped in its type eraser.
    private let _getEngine: () -> AnyMotor

    var engine: AnyMotor { return _getEngine() }

    init<Base : Vehicle>(_ base: Base) {
        self._getEngine = { AnyMotor(base.engine) }
    }
}

struct AnyTransportation : Transportation {

    private let _getTransport: () -> AnyVehicle
    private let _getName: () -> String
    private let _setName: (String) -> Void

    var transport: AnyVehicle { return _getTransport() }
    var name: String {
        get { return _getName() }
        set { _setName(newValue) }
    }

    init<Base : Transportation>(_ base: Base) {
        // similar pattern as above, just multiple stored closures.
        // however in this case, as we have a mutable protocol requirement,
        // we first create a mutable copy of base, then have all closures capture
        // this mutable variable.
        var base = base
        self._getTransport = { AnyVehicle(base.transport) }
        self._getName = { base.name }
        self._setName = { base.name = $0 }
    }
}

struct PetrolEngine : Motor {
    var power: Int
}

struct Ferry: Vehicle {
    var engine = PetrolEngine(power: 100)
}

struct FerryLine: Transportation {
    let transport = Ferry()
    var name = "Ferry line"
}

var anyTransportation = AnyTransportation(FerryLine())

print(anyTransportation.name) // Ferry line
print(anyTransportation.transport.engine.power) // 100

anyTransportation.name = "Foo bar ferries"
print(anyTransportation.name) // Foo bar ferries

Note that we still built AnyMotor despite Motor not having any associated types. This is because protocols don't conform to themselves, so we cannot use Motor itself to satisfy the Engine associated type (that requires : Motor) – we currently have to build a concrete wrapper type for it.


来源: stackexchange

问:
Create color histogram of an image using tensorflow
Is there a neat way to compute a color histogram of an image? Maybe by abusing the internal code of tf.histogram_summary? From what I've seen, this code is not very modular and calls directly some C++ code.

Thanks in advance.

答:
```<code>tf.histogram_fixed_width
</code>```

might be what you are looking for...

Full documentation on

https://www.tensorflow.org/api_docs/python/tf/histogram_fixed_width

ContentLicense: CC BY-SA 3.0

Body:
tf.histogram_fixed_width

might be what you are looking for...

Full documentation on

https://www.tensorflow.org/api_docs/python/tf/histogram_fixed_width


问:
Gaps setting font-size in inline elements
I have problems setting font-size styles in inline elements. Some gaps comes up.
There are questions related to this issue but I've not found a solution to my case.

Given this code:

<!doctype html>

Big text

                    Small text

                    Small text

```

How could I remove the extra vertical gaps if the HTML markup can't be modified and new CSS can only be applied to the container div and its children?

I've tried setting vertical-aling:top and line-height:0 but I can't get it to work.

What I need is this:

What I'm getting is:

答:
The font-size on the p elements is still 40px, the small class attributes are only being applied to the spans.  If the order of these elements is static, then you could just apply the font-size of 16px to all p and the font-size of 40px to just the first p.

<!doctype html>

Big text

                    Small text

                    Small text

```

Body:
I have problems setting font-size styles in inline elements. Some gaps comes up.
There are questions related to this issue but I've not found a solution to my case.

Given this code:

<!doctype html>

Big text

                    Small text

                    Small text

How could I remove the extra vertical gaps if the HTML markup can't be modified and new CSS can only be applied to the container div and its children?

I've tried setting vertical-aling:top and line-height:0 but I can't get it to work.

What I need is this:

What I'm getting is:

Body:
The font-size on the p elements is still 40px, the small class attributes are only being applied to the spans.  If the order of these elements is static, then you could just apply the font-size of 16px to all p and the font-size of 40px to just the first p.

<!doctype html>
<html>
    <style>
        .container {
            font-size: 40px;
        }

        p {
            margin: 0;
            font-size: 16px;
        }

        p:first-child {
            font-size: 40px;
        }

        .small {
            font-size: 16px;
        }
    </style>
    <body>
        <div class="container">
            <p>Big text</p>
            <p>
                <span>
                    Small text
                </span>
            </p>
            <p>
                <span class="small">
                    Small text
                </span>
            </p>
        </div>
    </body>
</html>


问:
Websocket sharp log file output
I'm using Websocket sharp (https://github.com/sta/websocket-sharp) for a console program, how do I output all debug/trace information that are displayed on the console to a text file?

For example:

```<code>using (var ws = new WebSocket(WebAddr))
            {

                ws.Log.Level = LogLevel.Debug;
                ws.OnOpen += (ss, ee) =>
                {
                  System.IO.File.WriteAllText(@"C:\log.txt", ws.Log.ToString());

                };
</code>```

But the output for this is "WebSocketSharp.Logger".

I would expecting something like this:

Screenshot

答:
Set the property File:

```<code>using (var ws = new WebSocket(WebAddr))
{
    ws.Log.Level = LogLevel.Debug;

    ws.Log.File = @"C:\log.txt";
}
</code>```

Title: Websocket sharp log file output

Body:
I'm using Websocket sharp (https://github.com/sta/websocket-sharp) for a console program, how do I output all debug/trace information that are displayed on the console to a text file?

For example:

using (var ws = new WebSocket(WebAddr))
            {

                ws.Log.Level = LogLevel.Debug;
                ws.OnOpen += (ss, ee) =>
                {
                  System.IO.File.WriteAllText(@"C:\log.txt", ws.Log.ToString());

                };

But the output for this is "WebSocketSharp.Logger".

I would expecting something like this:

Screenshot

Body:
Set the property File:

using (var ws = new WebSocket(WebAddr))
{
    ws.Log.Level = LogLevel.Debug;

    ws.Log.File = @"C:\log.txt";
}


问:
How to stop ASP.NET MVC view rendering inside cshtml?
What is proper way to stop cshtml view rendering after redirect?
Can I do return inside cshtml?</p>

```<code>@{
 if (someCondition) {
        Response.Redirect("/login");
        return;
    }
 }
}
<!DOCTYPE html>
....
</code>```

答:
I believe this may be a duplicate question, to which the short answer is:

It's perfectly valid to return; from within cshtml; however there is usually a better way.

Sources:

Abort/skip/cancel the rendering of a Razor view

ASP.NET MVC3 Razor - How to conditionally quit or end or return or break a partial view?

Is 'Exit Sub' from within a razor view a concern?

Body:
What is proper way to stop cshtml view rendering after redirect?
Can I do return inside cshtml?

@{
 if (someCondition) {
        Response.Redirect("/login");
        return;
    }
 }
}
<!DOCTYPE html>
....


问:
Django - order by
I need to sort my objects to use it in my template. Now it is something like:

```<code>sites = Site.objects.all().order_by('-date', '-group')[:10]
</code>```

Result is for example:

today group2

today group2

yesterday group2

yesterday group1

three days ago group2

four days ago group2

I need:

today group2

yesterday group2

three days ago group2

four days ago group2

today group1

yesterday group1

I simply need 10 newest sites ordered by group.
I would like to use it in my template (two sites in group2 first and 8 with group 2 or 1 next). Thanks for any advice.

答:
you should order first by group and then by date. Although there are several ways to do this.

On models level, you can achieve this with Meta attribute ordering

On view level, using the query sites = Site.objects.order_by( '-group','-date')[:10]'

Yes, all() is not needed for this.

On template level, regroup template tag. You needed to use nested for your sample.

Title: Django - order by

Body:
I need to sort my objects to use it in my template. Now it is something like:

sites = Site.objects.all().order_by('-date', '-group')[:10]

Result is for example:

today group2

today group2

yesterday group2

yesterday group1

three days ago group2

four days ago group2

I need:

today group2

yesterday group2

three days ago group2

four days ago group2

today group1

yesterday group1

I simply need 10 newest sites ordered by group.
I would like to use it in my template (two sites in group2 first and 8 with group 2 or 1 next). Thanks for any advice.


问:
Using && in if () operator
A friend of mine wrote me some code (and unfortunately he's un accessible right now) and I'm trying to understand it.

```<code>const people = [
  {name: 'morgan', group: 3},
  {name: 'courtney', group: 1},
  {name: 'brian', group: 1},
  {name: 'dog', group: 2}
]

const partitionedPeople = sortedPeople.reduce(
  (parts, person) => {
    const part = parts[0]

    if (part && person.group === part.group) {
      console.log('found part.group')
    } else {
      console.log('did not find part.group')
    }
    return parts;
  },
  []
);
</code>```

What I don't understand is if (part && person.group === part.group) {}

If I change it to if (person.group === part.group) {} I get an error.

Because through the first iteration, part is undefined (first item in an empty list) and I'm asking it to find .group of undefined, which makes sense.

However, when adding in (part && person.group === part.group) it works just fine.

What is part && person.group doing so that the function works?

答:
It fails because part does not have a property called group probably because part is itself not defined.

Using && ensures that the second condition after the && will only be processed/evaluated only if the first condition part is true.

So by putting part first it will evaluate person.group === part.group only if part is true. And as I already said by removing part you are then allowing the code to evaluate the second condition that has part.group and whenever you try to access a property (.group) from an undefined object then an Uncaught TypeError will result.

I would assume your error looks something like this:

Uncaught TypeError: Cannot read property 'group' of undefined

Title: Using && in if () operator

Body:
A friend of mine wrote me some code (and unfortunately he's un accessible right now) and I'm trying to understand it.

const people = [
  {name: 'morgan', group: 3},
  {name: 'courtney', group: 1},
  {name: 'brian', group: 1},
  {name: 'dog', group: 2}
]

const partitionedPeople = sortedPeople.reduce(
  (parts, person) => {
    const part = parts[0]

    if (part && person.group === part.group) {
      console.log('found part.group')
    } else {
      console.log('did not find part.group')
    }
    return parts;
  },
  []
);

What I don't understand is if (part && person.group === part.group) {}

If I change it to if (person.group === part.group) {} I get an error.

Because through the first iteration, part is undefined (first item in an empty list) and I'm asking it to find .group of undefined, which makes sense.

However, when adding in (part && person.group === part.group) it works just fine.

What is part && person.group doing so that the function works?


问:
div animate not working jquery
HTML

```<code><!DOCTYPE html>
<html>

<head>
  <link rel="stylesheet" type="text/css" href="mystyle1.css">
  <title>hd images</title>
</head>

<body>
  <div id="top1">
    <div class="inside1">
      <div class="nested_inside1"> MY HAPPY PLACES </div>
    </div>
    <div class="inside2">
      <div class="nested_inside2"> CLUMSSY BEACHES
      </div>
    </div>
    <div class="inside3">
      <div class="nested_inside3"> REGULAR APPLES </div>
    </div>
    <div class="inside4">
      <div class="nested_inside4"> LUSTY BRUSHES </div>
    </div>
    <div class="inside5">
      <div class="nested_inside5"> ECSTATIC DIMENSIONS </div>
    </div>
    <div class="inside6">
      <div class="nested_inside6"> CURLY HILLS </div>
    </div>
    <div class="inside7">
      <div class="nested_inside7"> SHINY WATER </div>
    </div>
    <div class="inside8">
      <div class="nested_inside8"> COOL BOATS </div>
    </div>
    <div class="inside9">
      <div class="nested_inside9"> CRUNCHY CLUSHTERS </div>
    </div>
    <script type="text/javascript" src="myscript2.js"></script>
</body>

</html>
</code>```

JavaScript

```<code>$(document).ready(function() {
  $("#top1").on("hover", ".nested_inside", function() {
    $(this).animate({
      "top": "-10px"
    });
  });
});
</code>```

答:
```<code>$(".nested_inside").hover( function(){
  $(this).animate({"top": "-10px"});
},function(){
 $(this).animate({"top":"initial"});
})
</code>```

hover() need a callback

Title: div animate not working jquery

Body:
HTML

<!DOCTYPE html>

  <link rel="stylesheet" type="text/css" href="mystyle1.css">
  <title>hd images</title>

 MY HAPPY PLACES

 CLUMSSY BEACHES

 REGULAR APPLES

 LUSTY BRUSHES

 ECSTATIC DIMENSIONS

 CURLY HILLS

 SHINY WATER

 COOL BOATS

 CRUNCHY CLUSHTERS

JavaScript

$(document).ready(function() {
  $("#top1").on("hover", ".nested_inside", function() {
    $(this).animate({
      "top": "-10px"
    });
  });
});

Body:
$(".nested_inside").hover( function(){
  $(this).animate({"top": "-10px"});
},function(){
 $(this).animate({"top":"initial"});
})

hover() need a callback


问:
How can I draw border tightly around 2 controls in WPF?
I have a ToggleButton which control a Popup similar to ComboBox. I want to draw a border like TabItems that flows around the button and popup when popup is visible and just around the button when it is invisible.</p>

答: A PopUp by definition pops up over the existing content, so drawing a border around both a PopUp and the button isn't really an option. What about using an Expander instead?</p>

ContentLicense: CC BY-SA 2.5


问:
Sum together every 3rd Cell in a Row
I would like to sum together every 3rd cell in a row. It would be great to be able to fill down the formula if at all possible. Primarily, I am looking to build this within a VBA script that I have completed other than this one part.

I found the following code, but it doesn't seem to be working:

```<code>=SUMPRODUCT((MOD(COLUMN(6:6),4)=0)*(6:6))
</code>```

While this is a formula, I feel this should be able to be repeated down and and applied accordingly without any issue. The one problem is that in order to activate the above you would need to Press CTRL+SHIFT+ENTER

Any help to get this so that it would calculate every 3rd cell in a row starting at Column 4 that would be awesome.

答:
You can use the following formula to sum every third cell, starting at Column D...

```<code>=SUMPRODUCT(--(MOD(COLUMN(D2:O2)-COLUMN(D2),3)=0),D2:O2)
</code>```

To sum every third cell, starting at the first occurrence of third (ie F2)...

```<code>=SUMPRODUCT(--(MOD(COLUMN(D2:O2)-COLUMN(D2)+1,3)=0),D2:O2)
</code>```

Adjust the range accordingly.  Note that the formula can be filled down, and only needs to be confirmed with ENTER, not CTRL+SHIFT+ENTER.

Title: Sum together every 3rd Cell in a Row

Body:
I would like to sum together every 3rd cell in a row. It would be great to be able to fill down the formula if at all possible. Primarily, I am looking to build this within a VBA script that I have completed other than this one part.

I found the following code, but it doesn't seem to be working:

=SUMPRODUCT((MOD(COLUMN(6:6),4)=0)*(6:6))

While this is a formula, I feel this should be able to be repeated down and and applied accordingly without any issue. The one problem is that in order to activate the above you would need to Press CTRL+SHIFT+ENTER

Any help to get this so that it would calculate every 3rd cell in a row starting at Column 4 that would be awesome.

Body:
You can use the following formula to sum every third cell, starting at Column D...

=SUMPRODUCT(--(MOD(COLUMN(D2:O2)-COLUMN(D2),3)=0),D2:O2)

To sum every third cell, starting at the first occurrence of third (ie F2)...

=SUMPRODUCT(--(MOD(COLUMN(D2:O2)-COLUMN(D2)+1,3)=0),D2:O2)

Adjust the range accordingly.  Note that the formula can be filled down, and only needs to be confirmed with ENTER, not CTRL+SHIFT+ENTER.


问:
How to display list of all staff users in a drop down method?
I want to create a field in a form for superuser. This field should have a list of all the staff users in a drop down manner so that superuser can select one of them to assign him/her a task. How should I create the drop down list?

So far, I can display the users like this:

```<code>from django.contrib.auth.models import User

users = User.objects.all()
</code>```

答:
```<code>class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
         if db_field.name == "cars":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
         return super().formfield_for_manytomany(db_field, request, **kwargs)
</code>```

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey

Body:
I want to create a field in a form for superuser. This field should have a list of all the staff users in a drop down manner so that superuser can select one of them to assign him/her a task. How should I create the drop down list?

So far, I can display the users like this:

from django.contrib.auth.models import User

users = User.objects.all()

Body:
class MyModelAdmin(admin.ModelAdmin):
    def formfield_for_manytomany(self, db_field, request, **kwargs):
         if db_field.name == "cars":
            kwargs["queryset"] = Car.objects.filter(owner=request.user)
         return super().formfield_for_manytomany(db_field, request, **kwargs)

https://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contrib.admin.ModelAdmin.formfield_for_foreignkey


问:
Not able to insert a datetime value in Microsoft SQL Server
I was creating a database and I wanted a column to accept the current date if no date value is inserted. Code worked, but inserting the date didn't.

I used the check constraint and the default along while creating the table

```<code>OrderDate datetime null check (OrderDate <= getdate()) default getdate()
</code>```

This is the code used to create the table:

```<code>create table Transactions.OrderDetails
(
    PurchaseOrderID int identity(1, 1) primary key
  , EmployeeID int not null
  , ItemID int not null
  , OrderDate datetime null check (OrderDate <= getdate()) default getdate()
  , ReceivingDate datetime null --check (ReceivingDate > OrderDate)
  , QO int not null --check (QO > QR)
  , QR int null check (QR > 0)
  , UnitPrice money not null check (UnitPrice > 0)
  , ShippingMethod char(6) not null
  , OrderStatus varchar(50) not null
 )
</code>```

答:
Make the column not null, and add a default constraint of getdate() or getutcdate() for a datetime datatype.

```<code>create table Orders (
    id int
  , OrderDate_notnull datetime not null default getdate()
  , OrderDate_null datetime null default getdate()
);

/* nullable column with default not specified in insert uses default*/
insert into Orders (id) values (1);

/* nullable column with default specified in insert remains null */
insert into Orders (id,OrderDate_null) values (2,null);

/* non-nullable column specified with null value throws an error */
--insert into Orders (id,OrderDate_notnull) values (3,null);

select * from Orders;
</code>```

rextester demo: http://rextester.com/CCNT4591

returns:

```<code>+----+---------------------+---------------------+
| id |  OrderDate_notnull  |   OrderDate_null    |
+----+---------------------+---------------------+
|  1 | 2017-07-08 18:10:50 | 2017-07-08 18:10:50 |
|  2 | 2017-07-08 18:10:50 | NULL                |
+----+---------------------+---------------------+
</code>```

Body:
I was creating a database and I wanted a column to accept the current date if no date value is inserted. Code worked, but inserting the date didn't.

I used the check constraint and the default along while creating the table

OrderDate datetime null check (OrderDate <= getdate()) default getdate()

This is the code used to create the table:

create table Transactions.OrderDetails
(
    PurchaseOrderID int identity(1, 1) primary key
  , EmployeeID int not null
  , ItemID int not null
  , OrderDate datetime null check (OrderDate <= getdate()) default getdate()
  , ReceivingDate datetime null --check (ReceivingDate > OrderDate)
  , QO int not null --check (QO > QR)
  , QR int null check (QR > 0)
  , UnitPrice money not null check (UnitPrice > 0)
  , ShippingMethod char(6) not null
  , OrderStatus varchar(50) not null
 )

Body:
Make the column not null, and add a default constraint of getdate() or getutcdate() for a datetime datatype.

create table Orders (
    id int
  , OrderDate_notnull datetime not null default getdate()
  , OrderDate_null datetime null default getdate()
);

/* nullable column with default not specified in insert uses default*/
insert into Orders (id) values (1);

/* nullable column with default specified in insert remains null */
insert into Orders (id,OrderDate_null) values (2,null);

/* non-nullable column specified with null value throws an error */
--insert into Orders (id,OrderDate_notnull) values (3,null);

select * from Orders;

rextester demo: http://rextester.com/CCNT4591

returns:

+----+---------------------+---------------------+
| id |  OrderDate_notnull  |   OrderDate_null    |
+----+---------------------+---------------------+
|  1 | 2017-07-08 18:10:50 | 2017-07-08 18:10:50 |
|  2 | 2017-07-08 18:10:50 | NULL                |
+----+---------------------+---------------------+


问:
Calculate average using Spark Scala
How do I calculate the Average salary per location in Spark Scala with below two data sets ?

File1.csv(Column 4 is salary)

```<code>Ram, 30, Engineer, 40000
Bala, 27, Doctor, 30000
Hari, 33, Engineer, 50000
Siva, 35, Doctor, 60000
</code>```

File2.csv(Column 2 is location)

```<code>Hari, Bangalore
Ram, Chennai
Bala, Bangalore
Siva, Chennai
</code>```

The above files are not sorted. Need to join these 2 files and find average salary per location. I tried with below code but unable to make it.

```<code>val salary = sc.textFile("File1.csv").map(e => e.split(","))
val location = sc.textFile("File2.csv").map(e.split(","))
val joined = salary.map(e=>(e(0),e(3))).join(location.map(e=>(e(0),e(1)))
val joinedData = joined.sortByKey()
val finalData = joinedData.map(v => (v._1,v._2._1._1,v._2._2))
val aggregatedDF = finalData.map(e=> e.groupby(e(2)).agg(avg(e(1))))
aggregatedDF.repartition(1).saveAsTextFile("output.txt")
</code>```

Please help with code and sample output how it will look.

Many Thanks

答:
You could do something like this:

```<code>val salary = sc.textFile("File1.csv").map(_.split(",").map(_.trim))
val location = sc.textFile("File2.csv").map(_.split(",").map(_.trim))
val joined = salary.map(e=>(e(0),e(3).toInt)).join(location.map(e=>(e(0),e(1))))
val locSalary = joined.map(v => (v._2._2, v._2._1))
val averages = locSalary.aggregateByKey((0,0))((t,e) => (t._1 + 1, t._2 + e),
        (t1,t2) => (t1._1 + t2._1, t1._2 + t2._2)).mapValues(t => t._2/t._1)
</code>```

then averages.take(10) will give:

```<code>res5: Array[(String, Int)] = Array((Chennai,50000), (Bangalore,40000))
</code>```

Title: Calculate average using Spark Scala

Body:
How do I calculate the Average salary per location in Spark Scala with below two data sets ?

File1.csv(Column 4 is salary)

Ram, 30, Engineer, 40000
Bala, 27, Doctor, 30000
Hari, 33, Engineer, 50000
Siva, 35, Doctor, 60000

File2.csv(Column 2 is location)

Hari, Bangalore
Ram, Chennai
Bala, Bangalore
Siva, Chennai

The above files are not sorted. Need to join these 2 files and find average salary per location. I tried with below code but unable to make it.

val salary = sc.textFile("File1.csv").map(e => e.split(","))
val location = sc.textFile("File2.csv").map(e.split(","))
val joined = salary.map(e=>(e(0),e(3))).join(location.map(e=>(e(0),e(1)))
val joinedData = joined.sortByKey()
val finalData = joinedData.map(v => (v._1,v._2._1._1,v._2._2))
val aggregatedDF = finalData.map(e=> e.groupby(e(2)).agg(avg(e(1))))
aggregatedDF.repartition(1).saveAsTextFile("output.txt")

Please help with code and sample output how it will look.

Many Thanks

Body:
You could do something like this:

val salary = sc.textFile("File1.csv").map(_.split(",").map(_.trim))
val location = sc.textFile("File2.csv").map(_.split(",").map(_.trim))
val joined = salary.map(e=>(e(0),e(3).toInt)).join(location.map(e=>(e(0),e(1))))
val locSalary = joined.map(v => (v._2._2, v._2._1))
val averages = locSalary.aggregateByKey((0,0))((t,e) => (t._1 + 1, t._2 + e),
        (t1,t2) => (t1._1 + t2._1, t1._2 + t2._2)).mapValues(t => t._2/t._1)

then averages.take(10) will give:

res5: Array[(String, Int)] = Array((Chennai,50000), (Bangalore,40000))


问:
Define global alias for static classes
I have a static ExceptionHelper that looks like this:

```<code>public static class ExceptionHelper
{
    public static async void ShowDialog(string message)
    {
        // Show message
    }
}
</code>```

Whenever I want to call this method I do it like this at the moment:

```<code>ExceptionHelper.ShowDialog("This is a message.");
</code>```

I now thought of defining an alias for the ExceptionHelper to not having to write the whole word each time I want to use it.

I know I can achieve it with using:

```<code>using Ex = MyNamespaces.ExceptionHelper;
</code>```

But then I'd have to define it in each file I want to use the method. Is there a way I can define the alias globally without changing the name of the class? Or is there any attribute I can set above the class declaration?

答:
This might apply, even though you are using a method. You could use an ENUM type instead that lies outside of any namespace and access globals values that way. Place the enum in a file outside of any namespace. You can access it globally that way, or if you have trouble, using the "global" keyword below if you have any trouble referencing it:</p>

```<code>enum Size
{
SMALL = 1,
MEDIUM = 5,
LARGE = 10
}

class Test {
    int mysize1 = (int)Size.SMALL;
    int mysize2 = (int)global::Size.MEDIUM;
}
</code>```

Title: Define global alias for static classes

Body:
I have a static ExceptionHelper that looks like this:

public static class ExceptionHelper
{
    public static async void ShowDialog(string message)
    {
        // Show message
    }
}

Whenever I want to call this method I do it like this at the moment:

ExceptionHelper.ShowDialog("This is a message.");

I now thought of defining an alias for the ExceptionHelper to not having to write the whole word each time I want to use it.

I know I can achieve it with using:

using Ex = MyNamespaces.ExceptionHelper;

But then I'd have to define it in each file I want to use the method. Is there a way I can define the alias globally without changing the name of the class? Or is there any attribute I can set above the class declaration?

Body:
This might apply, even though you are using a method. You could use an ENUM type instead that lies outside of any namespace and access globals values that way. Place the enum in a file outside of any namespace. You can access it globally that way, or if you have trouble, using the "global" keyword below if you have any trouble referencing it:

enum Size
{
SMALL = 1,
MEDIUM = 5,
LARGE = 10
}

class Test {
    int mysize1 = (int)Size.SMALL;
    int mysize2 = (int)global::Size.MEDIUM;
}


问:
Calculate one lag differences in R
Data:

```<code>d <- data.frame(year= c(1,2,5,6,1,2,7),id=c(1,1,1,1,2,2,2),value=1:7)

year id value
1    1   1
2    1   2
5    1   3
6    1   4
1    2   5
2    2   6
7    2   7
</code>```

Desired output:

```<code>year id value
1    1   NA
2    1   1
5    1   NA
6    1   1
1    2   NA
2    2   1
7    2   NA
</code>```

Basically, I want the one lag differences of value within the same id, if not available then missing. The difficulty is that the available years in each id is basically random, so I am not quite sure the bast way to do this.

答:
We create a grouping variable and then do the one lag</p>

```<code>library(dplyr)
df1 %>%
   group_by(id, grp = as.integer(gl(nrow(df1), 2, nrow(df1)))) %>%
   mutate(diff = lag(value))
</code>```

Title: Calculate one lag differences in R

Body:
Data:

d <- data.frame(year= c(1,2,5,6,1,2,7),id=c(1,1,1,1,2,2,2),value=1:7)

year id value
1    1   1
2    1   2
5    1   3
6    1   4
1    2   5
2    2   6
7    2   7

Desired output:

year id value
1    1   NA
2    1   1
5    1   NA
6    1   1
1    2   NA
2    2   1
7    2   NA

Basically, I want the one lag differences of value within the same id, if not available then missing. The difficulty is that the available years in each id is basically random, so I am not quite sure the bast way to do this.

Body:
We create a grouping variable and then do the one lag

library(dplyr)
df1 %>%
   group_by(id, grp = as.integer(gl(nrow(df1), 2, nrow(df1)))) %>%
   mutate(diff = lag(value))


问:
How to match 2 columns in excel?
I have an excel sheet, sheet1 which has 2 cols, A and B. Col A has some values and has corresponding mapping in col B(not all values in A have a mapping in B, some are empty). The sorting is done from Z-A and w.r.to Col A. I have another excel sheet, sheet2 which has similar Col A and Col B. Now, i want to find out whether any match is there between Col A of sheet1 and Col A of sheet2. If matches are found, those values should be copied onto a new column.</p>

答: It is possible to do a lot with Excel and ADO: Excel VBA to match and line up rows</p>

Title: How to match 2 columns in excel?


答:
To create 9 patches you could set x and y to the vertices of the patches:

```<code>x = [1,3,5,7]
y = [0.55,0.65,0.75,0.85]

x, y = np.meshgrid(x, y)
intensity = np.random.random(size=(3,3))

plt.pcolormesh(x, y, intensity)
plt.colorbar()  # need a colorbar to show the intensity scale
plt.show()
</code>```

Title: Heatmap with matplotlib

Body:
I have a set of 3-tuples, each 3-tuple consists of (var1, var2, result).
Example of a list of 9 3-tuples:

<type 'list'>:
[(4, 0.7, 0.8530612244898, 0.016579670213527985),
 (4, 0.6, 0.8730158730157779, 0.011562402525241757),
 (6, 0.8, 0.8378684807257778, 0.018175985875060037),
 (4, 0.8, 0.8605442176870833, 0.015586992159716321),
 (2, 0.8, 0.8537414965986667, 0.0034013605443334316),
 (2, 0.7, 0.843537414966, 0.006802721088333352),
 (6, 0.6, 0.8480725623582223, 0.01696896774039503),
 (2, 0.6, 0.84693877551025, 0.010204081632749995),
 (6, 0.7, 0.8577097505669444, 0.019873637350220318)]

Now I'd like to create a heatmap out of this.
Var1 can be values [2,4,6] and Var2 can be [0.6, 0.7, 0.8]. There's a total of 9 results.

This is the code I use to plot a heatmap:

    # list of 3-tuples to 3 lists: x, y and weights
    # x (var1) = [2,4,6]
    # y (var2) = [0.6, 0.7, 0.8]
    # weights (res) = [....] (9 values)

    x, y = np.meshgrid(x, y)
    intensity = np.array(weights)

    plt.pcolormesh(x, y, intensity)
    plt.colorbar()  # need a colorbar to show the intensity scale
    plt.show()

Which leads to this graph:

What I find weird is that there's only 4 sections, but I expected there to be 9 (3x3). Can someone shed some light on what I did wrong here?

Body:
To create 9 patches you could set x and y to the vertices of the patches:

x = [1,3,5,7]
y = [0.55,0.65,0.75,0.85]

x, y = np.meshgrid(x, y)
intensity = np.random.random(size=(3,3))

plt.pcolormesh(x, y, intensity)
plt.colorbar()  # need a colorbar to show the intensity scale
plt.show()


答:
You can use ModelChoiceField for this. Just add to form class something like this:

```<code>user = forms.ModelChoiceField(queryset=User.objects.filter(is_staff=True), empty_label=None)
</code>```

Title: How to display list of all staff users in a drop down method?

Body:
You can use ModelChoiceField for this. Just add to form class something like this:

user = forms.ModelChoiceField(queryset=User.objects.filter(is_staff=True), empty_label=None)


问:
How can a memory address (pointer variables) be initialized using constructor?
Notes: 1) Person is the base class of Student
         2) Person contains  name as the only data variable
         3) Student contains  society . The society acts as a pointer to a text string which contains the name of the student's club.

I have difficulty in understanding the fourth line:

```<code>int main (){
Person* p1;
p1=new Student("John", "Drama Society");   //This line
delete p1;
}
</code>```

Isn't p1 a Person pointer pointing to a memory address in the heap? As far as I know, pointer variable is just a 32-bit or 64-bit(system-dependent) location in memory.
How can it be initialized just like objects of type Person?

I know my concept is wrong, please help me find them out :(

答:
You are asking about polymorphism.
You have to distinguish between static and dynamic type. The static type of a pointer is specified at declaration. In this case static type of p1 is Person. The dynamic type can be any descendant of the static type and can be defined at run-time which is Student in your example.

You can find a great explanation here: https://stackoverflow.com/a/7649711/8244162

Body:
Notes: 1) Person is the base class of Student
         2) Person contains  name as the only data variable
         3) Student contains  society . The society acts as a pointer to a text string which contains the name of the student's club.

I have difficulty in understanding the fourth line:

int main (){
Person* p1;
p1=new Student("John", "Drama Society");   //This line
delete p1;
}

Isn't p1 a Person pointer pointing to a memory address in the heap? As far as I know, pointer variable is just a 32-bit or 64-bit(system-dependent) location in memory.
How can it be initialized just like objects of type Person?

I know my concept is wrong, please help me find them out :(


问:
How to list triggers associated with AWS Lambda function using Java SDK
Inside AWS Lambda console if you click on Triggers tab it will show you list of triggers if any triggers are configured for that lambda function.
How to get the list of configured triggered using Java SDK for AWS?

Thanks.

答:
You can get the list of triggers, but it is not a straightforward task. I have managed to reproduce the behavior of the console in code. I code in Node.js, but using these methods in the Java SDK will give you the same results.

1) Use the Lambda getPolicy() method to retrieve the Policy JSON (the same one displayed in the console under Triggers / View Function Policy).

2) Parse the JSON and use the "Statement"/"Condition"/"ArnLike"/"AWS:SourceArn" elements to parse out the S3 bucket names for the triggers.

3) Use the S3 getBucketNotificationConfiguration() method to retrieve the list of triggers for each bucket found in 2).

4) Parse the result from 3) and search through the LambdaFunctionConfigurations nodes for the matching LambdaFunctionArn of your Lambda. The matching nodes have the details of any triggers from the S3 buckets from 2) to your Lambda.

I would assume that triggers from other AWS sources than S3 buckets can be found similarly, but my use case was only for S3 buckets.

Note: The answer provided by johni on 29-Apr is incorrect. When I attempted it I learned that this method only returns Kinesis events. Triggers from other AWS sources are only visible in the Lambda Function's Policy JSON.


问:
HQL query for entity with max value
I have a Hibernate entity that looks like this (accessors ommitted for brevity):

```<code>@Entity
@Table(name="FeatureList_Version")
@SecondaryTable(name="FeatureList",
    pkJoinColumns=@PrimaryKeyJoinColumn(name="FeatureList_Key"))
public class FeatureList implements Serializable {

    @Id
    @Column(name="FeatureList_Version_Key")
    private String key;

    @Column(name="Name",table="FeatureList")
    private String name;

    @Column(name="VERSION")
    private Integer version;

}
</code>```

I want to craft an HQL query that retrieves the most up to date version of a FeatureList. The following query sort of works:

```<code>Select f.name, max(f.version) from FeatureList f group by f.name
</code>```

The trouble is that won't populate the key field, which I need to contain the key of the record with the highest version number for the given FeatureList. If I add f.key in the select it won't work because it's not in the group by or an aggregate and if I put it in the group by the whole thing stops working and it just gives me every version as a separate entity.

So, can anybody help?

答:
I made a scenario here,

Table

```<code>key          name                 version
----------- -------------------- -----------
1           adeel                1
2           adeel                2
3           adeel                3
4           ahmad                1
5           ahmad                2
6           ahmad                3
7           ahmad                4
8           ansari               1
9           ansari               2
10          ansari               3
</code>```

Result using your original query

```<code>>> select f.name, max(f.version) from FeatureList f group by f.name

name                 max(f.version)
-------------------- ------------
adeel                3
ahmad                4
ansari               3
</code>```

Result using your desired query

```<code>>> select fl.* from FeatureList fl
   where (fl.name, fl.version) in (select f.name, max(f.version)
                                           from FeatureList f group by f.name);

key          name                 max(fl.version)
----------- -------------------- -----------
3           adeel                3
7           ahmad                4
10          ansari               3
</code>```

NB: Tried it using MySQL this time. Its working. I am pretty sure MS SQL Server also have IN (...) operator. You just need to use session.createNativeQuery() in Hibernate.

Edited to work on axtavt's answer

As we found out this can be made as simple as,

```<code>select f from FeatureList f
where f.version =
     (select max(ff.version) from FeatureList ff where ff.name = f.name)
</code>```

Now try the same using Hibernate Criteria API,

```<code>DetachedCriteria versions = DetachedCriteria.forClass(FeatureList.class, "f")
    .setProjection( Property.forName("f.version").max())
    .add(Property.forName("f.name").eqProperty("fl.name"));

session.createCriteria(FeatureList.class, "fl")
    .add( Property.forName("fl.version").eq(versions) )
    .list();
</code>```

Title: HQL query for entity with max value

Body:
I have a Hibernate entity that looks like this (accessors ommitted for brevity):

@Entity
@Table(name="FeatureList_Version")
@SecondaryTable(name="FeatureList",
    pkJoinColumns=@PrimaryKeyJoinColumn(name="FeatureList_Key"))
public class FeatureList implements Serializable {

    @Id
    @Column(name="FeatureList_Version_Key")
    private String key;

    @Column(name="Name",table="FeatureList")
    private String name;

    @Column(name="VERSION")
    private Integer version;

}

I want to craft an HQL query that retrieves the most up to date version of a FeatureList. The following query sort of works:

Select f.name, max(f.version) from FeatureList f group by f.name

The trouble is that won't populate the key field, which I need to contain the key of the record with the highest version number for the given FeatureList. If I add f.key in the select it won't work because it's not in the group by or an aggregate and if I put it in the group by the whole thing stops working and it just gives me every version as a separate entity.

So, can anybody help?

Body:
I made a scenario here,

Table

key          name                 version
----------- -------------------- -----------
1           adeel                1
2           adeel                2
3           adeel                3
4           ahmad                1
5           ahmad                2
6           ahmad                3
7           ahmad                4
8           ansari               1
9           ansari               2
10          ansari               3

Result using your original query

>> select f.name, max(f.version) from FeatureList f group by f.name

name                 max(f.version)
-------------------- ------------
adeel                3
ahmad                4
ansari               3

Result using your desired query

>> select fl.* from FeatureList fl
   where (fl.name, fl.version) in (select f.name, max(f.version)
                                           from FeatureList f group by f.name);

key          name                 max(fl.version)
----------- -------------------- -----------
3           adeel                3
7           ahmad                4
10          ansari               3

NB: Tried it using MySQL this time. Its working. I am pretty sure MS SQL Server also have IN (...) operator. You just need to use session.createNativeQuery() in Hibernate.

Edited to work on axtavt's answer

As we found out this can be made as simple as,

select f from FeatureList f
where f.version =
     (select max(ff.version) from FeatureList ff where ff.name = f.name)

Now try the same using Hibernate Criteria API,

DetachedCriteria versions = DetachedCriteria.forClass(FeatureList.class, "f")
    .setProjection( Property.forName("f.version").max())
    .add(Property.forName("f.name").eqProperty("fl.name"));

session.createCriteria(FeatureList.class, "fl")
    .add( Property.forName("fl.version").eq(versions) )
    .list();


问:
Remove [ ' ' ] from a string in Node.js
I know how to remove for example only [, but how can I do for remove multiple things?

I have to remove 3 things, the two ', the [ & ] and the space

The string when I print it's something like this: [ 'Chroma 2 Case' ]

Thank you so much!

答:
You can just use RegEx to remove the braces and quotations.

```<code>var newstring = oldstring.replace(/[\[\]']/gi, '');
</code>```

To remove whitespace, use newstring = newstring.trim();

Title: Remove [ ' ' ] from a string in Node.js

Body:
You can just use RegEx to remove the braces and quotations.

var newstring = oldstring.replace(/[\[\]']/gi, '');

To remove whitespace, use newstring = newstring.trim();


问:
Falsy Freecodecamp algorithm challenge
This code is supposed to remove all falsy values from an array.
Am I close to getting it or should I scrap what I'm doing? I tend to get close only to give up later.</p>

```<code>function bouncer(arr) {

var bouncer = arr.filter(function(bouncer)undefined, null, NaN, 0, "", false); return arr; }

bouncer([7, "ate", "", false, 9]);
</code>```

答:
try to filter by Boolean. That should work. You are overcomplicating the problem in my Opinion. Look at this example. The Boolean Keyword is implemented in JS and simply checks if the given value is a valid Argument. Read more about the Boolean keyword here.

Instead of alert you could also use return or console.log or give the Values into a field on the Site like this.

Title: Falsy Freecodecamp algorithm challenge

Body:
This code is supposed to remove all falsy values from an array.
Am I close to getting it or should I scrap what I'm doing? I tend to get close only to give up later.

function bouncer(arr) {

var bouncer = arr.filter(function(bouncer)undefined, null, NaN, 0, "", false); return arr; }

bouncer([7, "ate", "", false, 9]);


问:
How to copy the hidden field value and pass it on another page using jquery in CodeIgniter?
I am new with CodeIgniter and I want to pass hidden field value to another page using jQuery in CodeIgniter. Can I do this using jQuery?

```<code><input type="hidden" name="grdtot" class="grdtot" />
</code>```

this hidden field on cart.php page

```<code>  <label id="grdtot_c" name="grdtot_c" class="grdtot_c"></label>
</code>```

I want to fetch this hidden field value on checkout.php page. How I can do this using jQuery?

答:
Suppose You have form given below:

```<code><body>
    <div>Upload data to the server without page Refresh</div>
    <input type="hidden" name="hidden_name" id="hidden_name">
    <input type="text" name="name" id="name">
    <input type="text" name="email" id="email">
    <input type="text" name="website" id="website">
    <input type="submit" name="submit" id="save" value="Submit">

    <div id="display"></div>
</body>
</code>```

And Now Your Script to send data to Your Controller.
You must have to use ajax to send data to the controller in CodeIgniter, And It will make your work easy.

```<code><script>
$(document).ready(function(){
    $('#save').click(function(){
        var hidden_name = $('#hidden_name').val();
        var name = $('#name').val();
        var email = $('#email').val();
        var website = $('#website').val();

        $.ajax({
            type:'POST',
            url:'<?php echo base_url();?>index.php/controller_name/function_name',
            async:false,
            data:{
                "done":1,
                "hidden_name":hidden_name,
                "name":name,
                "email":email,
                "website":website
                },
            success:function(data){
                $('#display').html(data);
            }
        });
    });
});
</script>
</code>```

Body:
I am new with CodeIgniter and I want to pass hidden field value to another page using jQuery in CodeIgniter. Can I do this using jQuery?

<input type="hidden" name="grdtot" class="grdtot" />

this hidden field on cart.php page

I want to fetch this hidden field value on checkout.php page. How I can do this using jQuery?

Body:
Suppose You have form given below:

<body>
    <div>Upload data to the server without page Refresh</div>
    <input type="hidden" name="hidden_name" id="hidden_name">
    <input type="text" name="name" id="name">
    <input type="text" name="email" id="email">
    <input type="text" name="website" id="website">
    <input type="submit" name="submit" id="save" value="Submit">

    <div id="display"></div>
</body>

And Now Your Script to send data to Your Controller.
You must have to use ajax to send data to the controller in CodeIgniter, And It will make your work easy.

<script>
$(document).ready(function(){
    $('#save').click(function(){
        var hidden_name = $('#hidden_name').val();
        var name = $('#name').val();
        var email = $('#email').val();
        var website = $('#website').val();

        $.ajax({
            type:'POST',
            url:'<?php echo base_url();?>index.php/controller_name/function_name',
            async:false,
            data:{
                "done":1,
                "hidden_name":hidden_name,
                "name":name,
                "email":email,
                "website":website
                },
            success:function(data){
                $('#display').html(data);
            }
        });
    });
});
</script>


问:
Searching in same element
I have to search a xml based  on two attributes and it's element value. For this I have used cts:near-query with distance zero. But am getting xml that doesn't contain the matching value. I have enabled the position values in settings and done reindexing, too. Please find the below XML
Mismatched XML one:

```<code><cars>
  <car a="subject" b="89">Indian Bank</car>
  <car a="subject" b="79">Central Banks</car>
  <car a="subject" b="90">Coriando banks</car>
</cars>
</code>```

I have query like cts:near-query with two attribute range query with a=subject and b>=89 and with one element word query central banks with distance zero. I don't want this XML to be returned while searching. Please help me in resolving this.

Exact rules:
The XML which contains a=subject and b>=89 and element value of Central banks should be returned while searching. But with the below query in comment am getting the above document.

```<code>cts:and-query((
  cts:near-query((
    cts:element-attribute-range-query(xs:QName("car"), xs:QName("b), ">=", 89),
    cts:element-attribute-range-query(xs:QName("car"), xs:QName("a), "=", "subject"),
    cts:element-word-query(xs:qname("car"), "Central Banks")
  ),0)
))
</code>```

答:
This would work:

```<code>xdmp:document-insert("/cars.xml",
<cars>
  <car a="subject" b="89">Indian Bank</car>
  <car a="subject" b="79">Central Banks</car>
  <car a="subject" b="90">Coriando banks</car>
</cars>)
;
let $car := xs:QName("car")
let $a := xs:QName("a")
let $b := xs:QName("b")
return
cts:search(collection()/cars/car, cts:element-query($car, cts:and-query((
  cts:element-attribute-value-query($car, $a, "subject"),
  cts:element-attribute-value-query($car, $b, "79"),
  cts:word-query("Central Banks")
))))
</code>```

You can use an element-query to constrain sub-queries to a particular element, usually works better than a near-query (which requires position indexes to be enabled too).

Attribute-value-queries where the element name matches that of the parent element-query will include attributes on the element from the element-query. I didn't have range indexes on attributes a and b, but the same applies for attribute-range-queries.

Other element range/value/word queries inside the element-query however, apply to descendants only. So you need to use a word-query to look at the content of element.

The searchable expression pinpointing a specific car will then isolate the exact car that matches the query. Note though that this requires filtering, which usually slows down searching. If you save each car in a separate document, you could do an unfiltered search for better performance. It might also elevate the need for the wrapping element-query.

HTH!

Title: Searching in same element

Body:
I have to search a xml based  on two attributes and it's element value. For this I have used cts:near-query with distance zero. But am getting xml that doesn't contain the matching value. I have enabled the position values in settings and done reindexing, too. Please find the below XML
Mismatched XML one:

<cars>
  <car a="subject" b="89">Indian Bank</car>
  <car a="subject" b="79">Central Banks</car>
  <car a="subject" b="90">Coriando banks</car>
</cars>

I have query like cts:near-query with two attribute range query with a=subject and b>=89 and with one element word query central banks with distance zero. I don't want this XML to be returned while searching. Please help me in resolving this.

Exact rules:
The XML which contains a=subject and b>=89 and element value of Central banks should be returned while searching. But with the below query in comment am getting the above document.

cts:and-query((
  cts:near-query((
    cts:element-attribute-range-query(xs:QName("car"), xs:QName("b), ">=", 89),
    cts:element-attribute-range-query(xs:QName("car"), xs:QName("a), "=", "subject"),
    cts:element-word-query(xs:qname("car"), "Central Banks")
  ),0)
))

Body:
This would work:

xdmp:document-insert("/cars.xml",
<cars>
  <car a="subject" b="89">Indian Bank</car>
  <car a="subject" b="79">Central Banks</car>
  <car a="subject" b="90">Coriando banks</car>
</cars>)
;
let $car := xs:QName("car")
let $a := xs:QName("a")
let $b := xs:QName("b")
return
cts:search(collection()/cars/car, cts:element-query($car, cts:and-query((
  cts:element-attribute-value-query($car, $a, "subject"),
  cts:element-attribute-value-query($car, $b, "79"),
  cts:word-query("Central Banks")
))))

You can use an element-query to constrain sub-queries to a particular element, usually works better than a near-query (which requires position indexes to be enabled too).

Attribute-value-queries where the element name matches that of the parent element-query will include attributes on the element from the element-query. I didn't have range indexes on attributes a and b, but the same applies for attribute-range-queries.

Other element range/value/word queries inside the element-query however, apply to descendants only. So you need to use a word-query to look at the content of element.

The searchable expression pinpointing a specific car will then isolate the exact car that matches the query. Note though that this requires filtering, which usually slows down searching. If you save each car in a separate document, you could do an unfiltered search for better performance. It might also elevate the need for the wrapping element-query.

HTH!


问:
@OnDelete Hibernate annotation does not generate ON DELETE CASCADE for MySql
I have two entities parent and child with a unidirectional relationship

```<code>class Parent {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
}
</code>```

and

```<code>class Child {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "parent_id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Parent parent;
}
</code>```

In the application.properties file I have configured

```<code>spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.database-platform = org.hibernate.dialect.MySQL5InnoDBDialect
</code>```

But when I run the application the following statement is created

```<code>...
alter table child add constraint FKi62eg01ijyk2kya7eil2gafmx foreign key (parent_id) references parent (id)
...
</code>```

So there is no ON CASCADE DELETE as there should be. The tables are created each time I run the application and I checked if the method

```<code>org.hibernate.dialect.MySQL5InnoDBDialect#supportsCascadeDelete()
</code>```

is really called (it is). I am using spring-boot-parent version 1.4.3, which uses Hibernate 5.11. Any ideas? I do not want to use a bi-directional relationship by the way.

Edit
Thanks to @AlanHay I discovered that I omitted an important part. There actually is a third class involved

```<code>class Kindergarten {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy = "kindergarten", fetch = FetchType.EAGER)
    @MapKeyJoinColumn(name = "parent_id") // parent_id causes the problem!
    private Map<Parent, Child> children;
}
</code>```

and Child with Kindergarten looks actually like this

```<code>class Child {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "parent_id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Parent parent;

    @ManyToOne
    @JoinColumn(name = "kindergarten_id")
    private Kindergarten kindergarten;
}
</code>```

and that is why the problem occurs. If you change "parent_id" in the MapKeyJoinColumn annotation to something not existing in Child as a column e.g. "map_id" the ON DELETE CASCADE is added to the foreign key parent_id in Child. If the parameter is the Child's column "parent_id" the ON DELETE CASCADE part will not be appended. Unfortunately the reason for this is not yet clear to me. Changing the parameter is no option because I want to use the existing link to parent of the child object.

答:
Maybe a little late, but since it is one of the top posts when searching for 'hibernate ondelete generate cascade':

For some reason putting @OnDelete on the ManyToOne side in Mysql did not work for me, but it worked on the OneToMany side. So if you are unlucky, try it on the other side.

Body:
I have two entities parent and child with a unidirectional relationship

class Parent {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;
}

and

class Child {
    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "parent_id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Parent parent;
}

In the application.properties file I have configured

spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.database-platform = org.hibernate.dialect.MySQL5InnoDBDialect

But when I run the application the following statement is created

...
alter table child add constraint FKi62eg01ijyk2kya7eil2gafmx foreign key (parent_id) references parent (id)
...

So there is no ON CASCADE DELETE as there should be. The tables are created each time I run the application and I checked if the method

org.hibernate.dialect.MySQL5InnoDBDialect#supportsCascadeDelete()

is really called (it is). I am using spring-boot-parent version 1.4.3, which uses Hibernate 5.11. Any ideas? I do not want to use a bi-directional relationship by the way.

Edit
Thanks to @AlanHay I discovered that I omitted an important part. There actually is a third class involved

class Kindergarten {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @OneToMany(mappedBy = "kindergarten", fetch = FetchType.EAGER)
    @MapKeyJoinColumn(name = "parent_id") // parent_id causes the problem!
    private Map<Parent, Child> children;
}

and Child with Kindergarten looks actually like this

class Child {

    @Id
    @GeneratedValue(strategy= GenerationType.AUTO)
    private Long id;

    @ManyToOne(optional = false)
    @JoinColumn(name = "parent_id")
    @OnDelete(action = OnDeleteAction.CASCADE)
    private Parent parent;

    @ManyToOne
    @JoinColumn(name = "kindergarten_id")
    private Kindergarten kindergarten;
}

and that is why the problem occurs. If you change "parent_id" in the MapKeyJoinColumn annotation to something not existing in Child as a column e.g. "map_id" the ON DELETE CASCADE is added to the foreign key parent_id in Child. If the parameter is the Child's column "parent_id" the ON DELETE CASCADE part will not be appended. Unfortunately the reason for this is not yet clear to me. Changing the parameter is no option because I want to use the existing link to parent of the child object.


答:
you can use a regular expression and use the first capture group (the insides of first round parentheses) as $1 in string.replace function, e.g.:

```<code>"[ 'Chroma 2 Case' ]".replace(/^\[\s*'(.*)'\s*\]$/, '$1')
</code>```

explanation: https://regex101.com/r/TGWCVn/1

P.S.: also works for strings with escaped apostrophes like [ 'Chroma 2\' Case' ]

edit: if needed to support various quotes:

```<code>'["StatTrak™ R8 Revolver | Crimson Web (Battle-Scarred)"]'.replace(
  /^\[\s*['"](.*)['"]\s*\]$/,
  '$1'
)
</code>```

edit2: if you have an array and not a string, to get the 1st item:

```<code>["StatTrak™ R8 Revolver | Crimson Web (Battle-Scarred)"][0]
</code>```

Title: Remove [ ' ' ] from a string in Node.js

Body:
I know how to remove for example only [, but how can I do for remove multiple things?

I have to remove 3 things, the two ', the [ & ] and the space

The string when I print it's something like this: [ 'Chroma 2 Case' ]

Thank you so much!

Body:
you can use a regular expression and use the first capture group (the insides of first round parentheses) as $1 in string.replace function, e.g.:

"[ 'Chroma 2 Case' ]".replace(/^\[\s*'(.*)'\s*\]$/, '$1')

explanation: https://regex101.com/r/TGWCVn/1

P.S.: also works for strings with escaped apostrophes like [ 'Chroma 2\' Case' ]

edit: if needed to support various quotes:

'["StatTrak™ R8 Revolver | Crimson Web (Battle-Scarred)"]'.replace(
  /^\[\s*['"](.*)['"]\s*\]$/,
  '$1'
)

edit2: if you have an array and not a string, to get the 1st item:

["StatTrak™ R8 Revolver | Crimson Web (Battle-Scarred)"][0]


答:
I would use dataframes:
First read the dataframes such as:

```<code>val salary = spark.read.option("header", "true").csv("File1.csv")
val location = spark.read.option("header", "true").csv("File2.csv")
</code>```

if you don't have headers you would need to set the option to "false" and use withColumnRenamed to change the default names.

```<code>val salary = spark.read.option("header", "false").csv("File1.csv").toDF("name", "age", "job", "salary")
val location = spark.read.option("header", "false").csv("File2.csv").toDF("name", "location")
</code>```

now do the join:

```<code>val joined = salary.join(location, "name")
</code>```

lastly do the average calculation:

```<code>val avg = joined.groupby("location").agg(avg($"salary"))
</code>```

to save do:

```<code>avg.repartition(1).write.csv("output.csv")
</code>```

Title: Calculate average using Spark Scala

Body:
How do I calculate the Average salary per location in Spark Scala with below two data sets ?

File1.csv(Column 4 is salary)

Ram, 30, Engineer, 40000
Bala, 27, Doctor, 30000
Hari, 33, Engineer, 50000
Siva, 35, Doctor, 60000

File2.csv(Column 2 is location)

Hari, Bangalore
Ram, Chennai
Bala, Bangalore
Siva, Chennai

The above files are not sorted. Need to join these 2 files and find average salary per location. I tried with below code but unable to make it.

val salary = sc.textFile("File1.csv").map(e => e.split(","))
val location = sc.textFile("File2.csv").map(e.split(","))
val joined = salary.map(e=>(e(0),e(3))).join(location.map(e=>(e(0),e(1)))
val joinedData = joined.sortByKey()
val finalData = joinedData.map(v => (v._1,v._2._1._1,v._2._2))
val aggregatedDF = finalData.map(e=> e.groupby(e(2)).agg(avg(e(1))))
aggregatedDF.repartition(1).saveAsTextFile("output.txt")

Please help with code and sample output how it will look.

Many Thanks

Body:
I would use dataframes:
First read the dataframes such as:

val salary = spark.read.option("header", "true").csv("File1.csv")
val location = spark.read.option("header", "true").csv("File2.csv")

if you don't have headers you would need to set the option to "false" and use withColumnRenamed to change the default names.

val salary = spark.read.option("header", "false").csv("File1.csv").toDF("name", "age", "job", "salary")
val location = spark.read.option("header", "false").csv("File2.csv").toDF("name", "location")

now do the join:

val joined = salary.join(location, "name")

lastly do the average calculation:

val avg = joined.groupby("location").agg(avg($"salary"))

to save do:

avg.repartition(1).write.csv("output.csv")


问:
C++ virtual functions implementation outside the class
I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.

Following code gives error:

```<code>class B
{
public:
    virtual void f();
};

void B::f() {
    std::cout<<"B::f";
}

class D : public B
{
public:
    void f2() {int b;}
};

// error: no "void D::f()" member function declared in class "D"
void D::f() {
    std::cout<<"D::F";
}
</code>```

It works if I declare f() inside D. I was wondering why do I need to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?

Thanks in advance..

答:
Even though D derives from B and therefore you can call f() on an instance of D, it does not mean you do not need to put the declaration into the header.

Any function you implement must be explicitly declared in the header.

You do not need, however, to put its implementation in there. Just

```<code>class D : public B
{
public:
   /*virtual*/ void f();
};
</code>```

and you can optionally choose whether to include the word "virtual" here

Body:
I am new to C++. While trying sample polymorphism code, I found that base class virtual function definition in derived class is possible only when defined within the derived class or outside with declaration in derived class.

Following code gives error:

class B
{
public:
    virtual void f();
};

void B::f() {
    std::cout<<"B::f";
}

class D : public B
{
public:
    void f2() {int b;}
};

// error: no "void D::f()" member function declared in class "D"
void D::f() {
    std::cout<<"D::F";
}

It works if I declare f() inside D. I was wondering why do I need to explicitly declare the function again when it is already declared in Base class. The compiler can get the signature from Base class right?

Thanks in advance..

Body:
Even though D derives from B and therefore you can call f() on an instance of D, it does not mean you do not need to put the declaration into the header.

Any function you implement must be explicitly declared in the header.

You do not need, however, to put its implementation in there. Just

class D : public B
{
public:
   /*virtual*/ void f();
};

and you can optionally choose whether to include the word "virtual" here


问:
How to fill a dropdownlist with arraylist that I get from a web service
I am consuming a java web service in asp.net, the method is an arraylist that devuleve the code and name, and I do not know how to load it to a dropdonwlist in which it shows the name and value is the code.

I tried the following way:

```<code>WebReferences.agencia datos = new WebReferences.agencia();

listAgencia.DataSource = datos;
listAgencia.DataTextField = datos.nombre;
listAgencia.DataValueField = Convert.ToString(datos.ida);
listAgencia.DataBind();
</code>```

It gives me error in the datasource.

答:
As you access properties nombre and ida from datos, it seems that datos isn't a collection but a single object.

In this case this would be enough:

```<code>listaAgencia.Items.Add(new ListItem(datos.nombre, datos.ida.ToString()));
</code>```

Should datos be a collection, instead, I would do like this:

```<code>foreach (var singleData in datos)
   listaAgencia.Items.Add(new ListItem(singleData.nombre, singleData.ida.ToString()));
</code>```

Body:
I am consuming a java web service in asp.net, the method is an arraylist that devuleve the code and name, and I do not know how to load it to a dropdonwlist in which it shows the name and value is the code.

I tried the following way:

WebReferences.agencia datos = new WebReferences.agencia();

listAgencia.DataSource = datos;
listAgencia.DataTextField = datos.nombre;
listAgencia.DataValueField = Convert.ToString(datos.ida);
listAgencia.DataBind();

It gives me error in the datasource.

Body:
As you access properties nombre and ida from datos, it seems that datos isn't a collection but a single object.

In this case this would be enough:

listaAgencia.Items.Add(new ListItem(datos.nombre, datos.ida.ToString()));

Should datos be a collection, instead, I would do like this:

foreach (var singleData in datos)
   listaAgencia.Items.Add(new ListItem(singleData.nombre, singleData.ida.ToString()));


问:
Getting computer serial number with python and .bat file
I have been studying for exams recently and the textbook I was reading told me that the command (in CMD) for getting a computers serial number is as follows - (as one method of lowering piracy).

```<code>wmic bios get serialnumber
</code>```

I decided to try this for myself using python, where I wanted to get the serial number of my own computer, I created a batch file (.bat) and recorded the serial number to a txt file which I thought I could then read off in python, this created more questions if anything... here is the code I currently have:

SerialNumber.bat (new to bat files by the way)

```<code>SET num=wmic bios get serialnumber

%num% > serial.txt
</code>```

What serial.txt looks like (modified slightly to not give away my serial number)

Readtxt.py

```<code># Trying to read in two different ways
with open("serial.txt", "r") as file:
    print(file.read())

lines = []
for line in open("serial.txt"):
    lines.append(line)
print(lines)
</code>```

which outputs: (not showing full image again)

the questions are:

How would I store the serial number as some string?

Why does each different method I use to read provide different outputs?

Thanks for any answers :)

答:
When redirecting to a file wmic writes UTF-16-LE with a BOM</p>

```<code>> wmic bios get serialnumber >serial.txt

> hex.exe serial.txt
HEX:       +00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f  0123456789abcdef
0000000000: FF FE 53 00 65 00 72 00  69 00 61 00 6C 00 4E 00  .■S.e.r.i.a.l.N.
0000000010: 75 00 6D 00 62 00 65 00  72 00 20 00 20 00 0D 00  u.m.b.e.r. . ...

> type readtext.py
with open("serial.txt", 'rb') as file:
    print(file.read().decode('utf-16'))

> py readtext.py
SerialNumber
5xxxxyyyy
</code>```

Body:
I have been studying for exams recently and the textbook I was reading told me that the command (in CMD) for getting a computers serial number is as follows - (as one method of lowering piracy).

wmic bios get serialnumber

I decided to try this for myself using python, where I wanted to get the serial number of my own computer, I created a batch file (.bat) and recorded the serial number to a txt file which I thought I could then read off in python, this created more questions if anything... here is the code I currently have:

SerialNumber.bat (new to bat files by the way)

SET num=wmic bios get serialnumber

%num% > serial.txt

What serial.txt looks like (modified slightly to not give away my serial number)

Readtxt.py

# Trying to read in two different ways
with open("serial.txt", "r") as file:
    print(file.read())

lines = []
for line in open("serial.txt"):
    lines.append(line)
print(lines)

which outputs: (not showing full image again)

the questions are:

How would I store the serial number as some string?

Why does each different method I use to read provide different outputs?

Thanks for any answers :)

Body:
When redirecting to a file wmic writes UTF-16-LE with a BOM

> wmic bios get serialnumber >serial.txt

> hex.exe serial.txt
HEX:       +00 01 02 03 04 05 06 07  08 09 0a 0b 0c 0d 0e 0f  0123456789abcdef
0000000000: FF FE 53 00 65 00 72 00  69 00 61 00 6C 00 4E 00  .■S.e.r.i.a.l.N.
0000000010: 75 00 6D 00 62 00 65 00  72 00 20 00 20 00 0D 00  u.m.b.e.r. . ...

> type readtext.py
with open("serial.txt", 'rb') as file:
    print(file.read().decode('utf-16'))

> py readtext.py
SerialNumber
5xxxxyyyy


答:
You can split on the quotes, providing that you aren't expecting any more in the string

```<code> const test = "[ \'Chroma 2 Case\' ]"
 test.split('\'')[1]
</code>```

Demo at: https://repl.it/JTIx/1

Title: Remove [ ' ' ] from a string in Node.js

Body:
You can split on the quotes, providing that you aren't expecting any more in the string

 const test = "[ \'Chroma 2 Case\' ]"
 test.split('\'')[1]

Demo at: https://repl.it/JTIx/1


问:
Cannot add keys from keys.gnupg.net
I am trying to run this command:

```<code>sudo apt-key adv --keyserver keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A
</code>```

But I get an error:

```<code>Executing: /tmp/apt-key-gpghome.jrw4s0ijoc/gpg.1.sh --keyserver keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A
gpg: keyserver receive failed: Connection refused
</code>```

Could you help me? I am running on Debian 9, GPG version is 2.1.18 and libgcrypt version is 1.7.6-beta.

答:
keys.gnupg.net is an alias for the SKS keyserver pool, a number of PGP keyservers run by organisations and volunteers (like me):

```<code>$ host keys.gnupg.net
keys.gnupg.net is an alias for pool.sks-keyservers.net.
pool.sks-keyservers.net has address 78.157.209.9
pool.sks-keyservers.net has address 45.33.82.183
pool.sks-keyservers.net has address 176.9.31.215
pool.sks-keyservers.net has address 217.92.13.131
...
</code>```

Your request will have gone to one of the servers from the pool (possibly randomly).

My guess is that you got unlucky and hit a server which was down (or blocking your IP, or whatever) and hadn't yet been removed from the pool.

My first suggestion is to just try again - that command succeeded for me just now.

Title: Cannot add keys from keys.gnupg.net

Body:
I am trying to run this command:

sudo apt-key adv --keyserver keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A

But I get an error:

Executing: /tmp/apt-key-gpghome.jrw4s0ijoc/gpg.1.sh --keyserver keys.gnupg.net --recv-keys 1C4CBDCDCD2EFD2A
gpg: keyserver receive failed: Connection refused

Could you help me? I am running on Debian 9, GPG version is 2.1.18 and libgcrypt version is 1.7.6-beta.

Body:
keys.gnupg.net is an alias for the SKS keyserver pool, a number of PGP keyservers run by organisations and volunteers (like me):

$ host keys.gnupg.net
keys.gnupg.net is an alias for pool.sks-keyservers.net.
pool.sks-keyservers.net has address 78.157.209.9
pool.sks-keyservers.net has address 45.33.82.183
pool.sks-keyservers.net has address 176.9.31.215
pool.sks-keyservers.net has address 217.92.13.131
...

Your request will have gone to one of the servers from the pool (possibly randomly).

My guess is that you got unlucky and hit a server which was down (or blocking your IP, or whatever) and hadn't yet been removed from the pool.

My first suggestion is to just try again - that command succeeded for me just now.


问:
Which Javascript Library To Use?
I am new to Android development with Phonegap and just got through these two tutorials:

http://news.softpedia.com/news/How-to-Run-Android-Applications-on-Ubuntu-115152.shtml

http://wiki.phonegap.com/w/page/30862722/phonegap-android-eclipse-quickstart

Now I want to make the index.html do more spectacular things. Do you recommend I use jQuery, Zepto.js, Sencha Touch, jQTouch, or a mix of these, to do what I want? I'm confused. I know jQuery very well, but if it's bloated compared to Zepto.js (which I have only read about), then perhaps I need Zepto.js if it's not too limiting? And then there's Sencha Touch and jQTouch, and I see these provide a framework for controls, but I don't know if they also provide their own Javascript API, or require jQuery, or whatever. I just want to set up the best environment for doing general purpose apps.

My app needs so far are fairly simple and are only two kinds:

Loads a single page and then
loads a Flash SWF component. This
component may or may not interact
over AJAX with a backend web server.
(I'm not a fan of Flash, but my
client requests it. She runs a lot
of games for her business.)

A tabbed interface with 4 static
pages and images, but then on the
5th tab, it connects to a website in
an IFRAME (or perhaps uses AJAX)

答:
I vote none.

I would recommend keeping the application as small as possible.

If you want a framework, then i would prefer sencha above jQTouch. It is more mature as we speak (don't know for sure as i personally do not use a framework).

But if you go commercial, then watch out for the licence.

Title: Which Javascript Library To Use?


问:
Calculate average using Spark Scala
How do I calculate the Average salary per location in Spark Scala with below two data sets ?

File1.csv(Column 4 is salary)

```<code>Ram, 30, Engineer, 40000
Bala, 27, Doctor, 30000
Hari, 33, Engineer, 50000
Siva, 35, Doctor, 60000
</code>```

File2.csv(Column 2 is location)

```<code>Hari, Bangalore
Ram, Chennai
Bala, Bangalore
Siva, Chennai
</code>```

The above files are not sorted. Need to join these 2 files and find average salary per location. I tried with below code but unable to make it.

```<code>val salary = sc.textFile("File1.csv").map(e => e.split(","))
val location = sc.textFile("File2.csv").map(e.split(","))
val joined = salary.map(e=>(e(0),e(3))).join(location.map(e=>(e(0),e(1)))
val joinedData = joined.sortByKey()
val finalData = joinedData.map(v => (v._1,v._2._1._1,v._2._2))
val aggregatedDF = finalData.map(e=> e.groupby(e(2)).agg(avg(e(1))))
aggregatedDF.repartition(1).saveAsTextFile("output.txt")
</code>```

Please help with code and sample output how it will look.

Many Thanks

答:
I would use DataFrame API, this should work:</p>

```<code>val salary = sc.textFile("File1.csv")
               .map(e => e.split(","))
               .map{case Seq(name,_,_,salary) => (name,salary)}
               .toDF("name","salary")

val location = sc.textFile("File2.csv")
                 .map(e => e.split(","))
                 .map{case Seq(name,location) => (name,location)}
                 .toDF("name","location")

import org.apache.spark.sql.functions._

salary
  .join(location,Seq("name"))
  .groupBy($"location")
  .agg(
    avg($"salary").as("avg_salary")
  )
  .repartition(1)
  .write.csv("output.csv")
</code>```

Title: Calculate average using Spark Scala

Body:
I would use DataFrame API, this should work:

val salary = sc.textFile("File1.csv")
               .map(e => e.split(","))
               .map{case Seq(name,_,_,salary) => (name,salary)}
               .toDF("name","salary")

val location = sc.textFile("File2.csv")
                 .map(e => e.split(","))
                 .map{case Seq(name,location) => (name,location)}
                 .toDF("name","location")

import org.apache.spark.sql.functions._

salary
  .join(location,Seq("name"))
  .groupBy($"location")
  .agg(
    avg($"salary").as("avg_salary")
  )
  .repartition(1)
  .write.csv("output.csv")


问:
Whenever I run my android application it stopped as it is i clicked the login button
53rd line is this:

```<code>HttpsURLConnection httpsURLConnection=(HttpsURLConnection)url.openConnection();
</code>```

24th line is this:

public class BackGroundWork extends AsyncTask]

The image i attached is the error which is found in error list .

答:
```<code>  try this codes below:

 URL url = new URL(Link);
  URLConnection connect = url.openConnection();

@Override
protected Object doInBackground(Object[] objects) {
    try {
        String data = URLEncoder.encode("tableName", "UTF8") + "=" + URLEncoder.encode(TableName, "UTF8") + "&" + "record" + "=" + RecordNo;
        //data
        URL url = new URL(Link);
        URLConnection connect = url.openConnection();
        connect.setDoOutput(true);
        OutputStreamWriter wr = new OutputStreamWriter(connect.getOutputStream());
        wr.write(data);
        wr.flush();
        String S = convetInputStreamToString(connect.getInputStream());

        assert S != null;
        if (!S.equals("no")) {
            GetUpdates.access = true;
            GetUpdates.res = S;
        } else {
            GetUpdates.access = false;
            GetUpdates.err = S;
        }
    } catch (IOException e) {
        e.printStackTrace();
    }
    return "";
}
</code>```

Body:
53rd line is this:

HttpsURLConnection httpsURLConnection=(HttpsURLConnection)url.openConnection();

24th line is this:

public class BackGroundWork extends AsyncTask]

The image i attached is the error which is found in error list .