问:
IDisposable Singleton with StructureMap 4 & NestedContainer
I'm looking to register an EasyNetQ's IBus which implements IDisposable as a singleton with StructureMap.

The issue is when using nested container, the instance is disposed with the container, thus leaving me with a singleton instance being disposed for every other containers.

```<code>For<IBus>()
    .Use(c => BusBuilder.CreateMessageBus())
    .Singleton();
</code>```

ContainerScoped is not an option here as I need that is kept alive during all the application lifespan.

How do I prevent StructureMap from disposing this instance with nested containers ? How do I tell it to dispose the instance only with the root container ?

答:
I knew something was odd with my issue. What was the point of defining singletons if they were disposed with each container ?

Indeed, StructureMap does not dispose singleton objects unless a root container is being disposed, see the PipelineGrap.cs source code. :

```<code>if (Role == ContainerRole.Root)
{
    _profiles.AllProfiles().Each(x => x.Dispose());
}
</code>```

It turned out that my IBus instance was being manually disposed by some mysterious legacy code in which it was injected.

Anyway, for anyone facing the same issue : track down your call to Dispose as StructureMap is doing its job as you though it would :)

Body:
I'm looking to register an EasyNetQ's IBus which implements IDisposable as a singleton with StructureMap.

The issue is when using nested container, the instance is disposed with the container, thus leaving me with a singleton instance being disposed for every other containers.

For<IBus>()
    .Use(c => BusBuilder.CreateMessageBus())
    .Singleton();

ContainerScoped is not an option here as I need that is kept alive during all the application lifespan.

How do I prevent StructureMap from disposing this instance with nested containers ? How do I tell it to dispose the instance only with the root container ?

Body:
I knew something was odd with my issue. What was the point of defining singletons if they were disposed with each container ?

Indeed, StructureMap does not dispose singleton objects unless a root container is being disposed, see the PipelineGrap.cs source code. :

if (Role == ContainerRole.Root)
{
    _profiles.AllProfiles().Each(x => x.Dispose());
}

It turned out that my IBus instance was being manually disposed by some mysterious legacy code in which it was injected.

Anyway, for anyone facing the same issue : track down your call to Dispose as StructureMap is doing its job as you though it would :)


来源: stackexchange

问:
Grab object id and insert into session storage Angular
I have a controller that populates a second drop-down box depending on the selection of the first, this works well although WebStorm sees it as a syntax error.
I know want to post the ID of the format fname to my session storage to use else where, however I have tried the code bellow and I see Value as

[object Object]

if I use

```<code>sessionStorage.setItem('format', $scope.formats);
</code>```

and

undefined

if I use

sessionStorage.setItem('format', $scope.formats.id);

I have also tried

```<code>sessionStorage.setItem('format', $scope.formats.formatType.id);
</code>```

I get nothing not even a empty value

how do I correctly add the ID to my format value in my session storage ?

Full code

```<code>FirstModule.controller('dropDown', function ($scope) {

$scope.productsandformats = [
    {
        "name": "staff",
        "format": [
            {"Fname": "bill", "id": "1"},
            {"Fname": "bob", "id": "2"},
            {"Fname": "tom", "id": "3"}
        ]
    },
    {
        "name": "managers",
        "format": [
            {"Fname": "dick", "id": "4"},
            {"Fname": "jhon", "id": "5"}
        ]
    },

    {
        "name": "directors",
        "format": [
            {"Fname": "willy", "id": "6"}
        ]
    },

    {
        "name": "temp",
        "format": [
            {"Fname": "jeff", "id": "18"},
            {"Fname": "billy", "id": "19"}
        ]
    }];

$scope.productTypeChange = function () {
    $scope.formats = $scope.productsandformats.find(ps => ps.name == $scope.formData.ProductType.name)

    sessionStorage.setItem('format', $scope.formats.id);

}
</code>```

});

To further more explain how I get the ID, The code bellow enables the user to select A fname from the name type for example if select staff you get bill, bob and tom then after you select one it,ll print out the selected name and fname including the fname id, the fname id is what i need to send to the session storage

HTML

```<code><div class="radio col-sm-6" style="margin-top: 0 !important;">
    <label>
        <input type="radio" ng-model="formData.type" value="Create" >
        <span class="glyphicon glyphicon-unchecked">
        </span>
        Need to make a poster?
    </label>
</div>

<div class="radio col-sm-6">
    <label>
        <input type="radio" ng-model="formData.type" value="Preview">
        <span class="glyphicon glyphicon-eye-open">
        </span>
        Already have a poster?
    </label>
</div>
</code>```

答:
You cannot store an object, you can only store a string.

To store an object you need to "stringify" it.

```<code>var jsonItem = JSON.stringify($scope.formats);
sessionStorage.setItem('format', jsonItem);
</code>```

Then to retrieve it you need to parse it

```<code>var item = sessionStorage.getItem('format');
item = JSON.parse(item)
</code>```

From MDN Storage/setItem

storage.setItem(keyName, keyValue);

keyName A DOMString containing the name of the key you want to
  create/update.

keyValue A DOMString containing the value you want to
  give the key you are creating/updating.

About finding the ID

When you do

```<code>$scope.formats = $scope.productsandformats.find(ps => ps.name ==
 $scope.formData.ProductType.name)
</code>```

You get an object with this structure

```<code>{
    "name": "staff",
    "format": [
        {"Fname": "bill", "id": "1"},
        {"Fname": "bob", "id": "2"},
        {"Fname": "tom", "id": "3"}
    ]
},
</code>```

So i guess the id is contained inside item.format[0].id for the first item and so on for the subsequent items.

format is an array so you wont be able to directly access id if you don't first select which element of the array you want (eg. format[0]).

ContentLicense: CC BY-SA 3.0

Body:
I have a controller that populates a second drop-down box depending on the selection of the first, this works well although WebStorm sees it as a syntax error.
I know want to post the ID of the format fname to my session storage to use else where, however I have tried the code bellow and I see Value as

[object Object]

if I use

sessionStorage.setItem('format', $scope.formats);

and

undefined

if I use

sessionStorage.setItem('format', $scope.formats.id);

I have also tried

sessionStorage.setItem('format', $scope.formats.formatType.id);

I get nothing not even a empty value

how do I correctly add the ID to my format value in my session storage ?

Full code

FirstModule.controller('dropDown', function ($scope) {

$scope.productsandformats = [
    {
        "name": "staff",
        "format": [
            {"Fname": "bill", "id": "1"},
            {"Fname": "bob", "id": "2"},
            {"Fname": "tom", "id": "3"}
        ]
    },
    {
        "name": "managers",
        "format": [
            {"Fname": "dick", "id": "4"},
            {"Fname": "jhon", "id": "5"}
        ]
    },

    {
        "name": "directors",
        "format": [
            {"Fname": "willy", "id": "6"}
        ]
    },

    {
        "name": "temp",
        "format": [
            {"Fname": "jeff", "id": "18"},
            {"Fname": "billy", "id": "19"}
        ]
    }];

$scope.productTypeChange = function () {
    $scope.formats = $scope.productsandformats.find(ps => ps.name == $scope.formData.ProductType.name)

    sessionStorage.setItem('format', $scope.formats.id);

}

});

To further more explain how I get the ID, The code bellow enables the user to select A fname from the name type for example if select staff you get bill, bob and tom then after you select one it,ll print out the selected name and fname including the fname id, the fname id is what i need to send to the session storage

HTML

        <input type="radio" ng-model="formData.type" value="Create" >

        Need to make a poster?

        <input type="radio" ng-model="formData.type" value="Preview">

        Already have a poster?

Body:
You cannot store an object, you can only store a string.

To store an object you need to "stringify" it.

var jsonItem = JSON.stringify($scope.formats);
sessionStorage.setItem('format', jsonItem);

Then to retrieve it you need to parse it

var item = sessionStorage.getItem('format');
item = JSON.parse(item)

From MDN Storage/setItem

storage.setItem(keyName, keyValue);

keyName A DOMString containing the name of the key you want to
  create/update.

keyValue A DOMString containing the value you want to
  give the key you are creating/updating.

About finding the ID

When you do

$scope.formats = $scope.productsandformats.find(ps => ps.name ==
 $scope.formData.ProductType.name)

You get an object with this structure

{
    "name": "staff",
    "format": [
        {"Fname": "bill", "id": "1"},
        {"Fname": "bob", "id": "2"},
        {"Fname": "tom", "id": "3"}
    ]
},

So i guess the id is contained inside item.format[0].id for the first item and so on for the subsequent items.

format is an array so you wont be able to directly access id if you don't first select which element of the array you want (eg. format[0]).


问:
How to scale aws ec2 cluster based on java application memory
I have a java application which is deployed on aws ec2 cluster. I have auto scaling configured based on cpu usage but the problem is application is not CPU intensive but is IO intensive, CPU usage is 20% on an average, so when traffic increases it is not able to send all the messages in real time causing buffering. This is causing delay in arrival of messages in downstream systems.

How can i auto scale my cluster based on incoming traffic and heap usage of deployed application?

答:
you should use custom metrics for this purposes
CloudWatch does not collect memory consumption by default. To enable this you should use custom metrics script and then you be able to change autoscaling group behavior corresponding to memory consumption chages or any other event which you need to monitor and react</p>


问:
Sequelize options.nest in query() method doesn't work
I have a raw query like

```<code>squelize.query(
   `select "order".id, "orderCustomer".id as "orderCustomer.id", "orderCustomer".forename as "orderCustomer.forename"
    from orders as "order"
    join customers as "orderCustomer" on "orderCustomer".id = "order"."orderCustomerId"
    where "orderCustomer".forename ilike '%petra%';`,
{
    type: Sequelize.QueryTypes.SELECT,
    model: order,
    nest: true,
    mapToModel: true
})
</code>```

When I query this in psql I get a correct result set:

```<code>-[ RECORD 1 ]----------+------
id                     | 383
orderCustomer.id       | 446
orderCustomer.forename | Petra
-[ RECORD 2 ]----------+------
id                     | 419
orderCustomer.id       | 9
orderCustomer.forename | Petra
</code>```

The problem is, that Sequelize is apparently not able to form this into an Array of the kind

```<code>[
 {
   id: 383,
   orderCustomer: {
      id: 446,
      forename: 'Petra'
   }
 },
   ...
]
</code>```

Instead I get something like this:

```<code>[
 {
   id: 383,
   'orderCustomer.id': 446,
   'orderCustomer.forename': 'Petra'
 },
   ...
]
</code>```

Do I need to include the customer-model in the query's option-object?

UPDATE

I logged the result of my query. There is this property _options on all of the returned order-instances:

```<code>_options:{
   isNewRecord: false,
   _schema: null,
   _schemaDelimiter: '',
   raw: true, // <--------- possible cause?
   attributes: undefined
}
</code>```

Somehow, I cannot set options.raw to false on my query definition! Maybe that is the reason why …

…sequelize will not try to format the results of the query, or build an instance of a model from the result (see  query() -> options.raw">docs > query() > options.raw)

Any ideas?

答:
Assuming you have the models set up properly,

Why not query it using associations, instead of using a raw query.
Something like this should generate a similar result

```<code>Model.Order.findAll({
  where:{forename:{$iLike:'someString'}},
  attributes:[/*Columns to fetch*/]
  include:[{model:Model.Customer,attributes:[/*Columns to fetch*/]}]
});
</code>```

Also IMO using the nest attributes, wont club across multiple rows returned.

Body:
I have a raw query like

squelize.query(
   `select "order".id, "orderCustomer".id as "orderCustomer.id", "orderCustomer".forename as "orderCustomer.forename"
    from orders as "order"
    join customers as "orderCustomer" on "orderCustomer".id = "order"."orderCustomerId"
    where "orderCustomer".forename ilike '%petra%';`,
{
    type: Sequelize.QueryTypes.SELECT,
    model: order,
    nest: true,
    mapToModel: true
})

When I query this in psql I get a correct result set:

-[ RECORD 1 ]----------+------
id                     | 383
orderCustomer.id       | 446
orderCustomer.forename | Petra
-[ RECORD 2 ]----------+------
id                     | 419
orderCustomer.id       | 9
orderCustomer.forename | Petra

The problem is, that Sequelize is apparently not able to form this into an Array of the kind

[
 {
   id: 383,
   orderCustomer: {
      id: 446,
      forename: 'Petra'
   }
 },
   ...
]

Instead I get something like this:

[
 {
   id: 383,
   'orderCustomer.id': 446,
   'orderCustomer.forename': 'Petra'
 },
   ...
]

Do I need to include the customer-model in the query's option-object?

UPDATE

I logged the result of my query. There is this property _options on all of the returned order-instances:

_options:{
   isNewRecord: false,
   _schema: null,
   _schemaDelimiter: '',
   raw: true, // <--------- possible cause?
   attributes: undefined
}

Somehow, I cannot set options.raw to false on my query definition! Maybe that is the reason why …

…sequelize will not try to format the results of the query, or build an instance of a model from the result (see  query() -> options.raw">docs > query() > options.raw)

Any ideas?

Body:
Assuming you have the models set up properly,

Why not query it using associations, instead of using a raw query.
Something like this should generate a similar result

Model.Order.findAll({
  where:{forename:{$iLike:'someString'}},
  attributes:[/*Columns to fetch*/]
  include:[{model:Model.Customer,attributes:[/*Columns to fetch*/]}]
});

Also IMO using the nest attributes, wont club across multiple rows returned.


问:
How zero-fill-on demand is implemented in Linux kernel, and where I can disable it?
When we malloc memory,  only virtual memory is available, and it actually pointed to zero-page. The real physical memory will be allocated when we try to write to the malloced memory, at this moment, there will be copy-on-wright that copy zeros from zero-page to physical memory which mapped by page-fault. My problem is, how/where zero-fill-on demand is implemented in linux source code, I want to disable this functionality to do some test. I guess it may happened in page-fault procedure, rather than brk() or mmap().

Similar topics related to zero-fill-on-demand. ZFOD and COW.

答:
If you want your userspace process to allocate real memory every *alloc call, I think in the next options:

If it is for performance reasons, you can replace all calloc calls for malloc+memset so processes will always have a real memory page. However, the kernel could still be able to merge some memory pages.

Disable memory overcommit so that every malloc will return the page at the moment. This way, your program will not be able to allocate more memory than available (RAM + swap). See https://www.kernel.org/doc/Documentation/vm/overcommit-accounting


问:
How can we manipulate std class in php?
Is it possible to add elements to stdclasses like we do for arrays?

```<code>Array (
  [0] => item 1
  [1] => item 2
)

Stdclass (
  [0] => item 1
  [1] => item 2
)
</code>```

Is it generally harder to manipulate objects as compared to arrays? Since we have lots of array functions to make use of etc.

答:
It's no harder to manipulate. All I would say is things like count and array_search don't work on an object.

Array and objects both have their benefits it depends on what you are trying to achieve.

http://php.net documentation will state what data types can be passed to what functions.

ContentLicense: CC BY-SA 2.5

Title: How can we manipulate std class in php?

Body:
Is it possible to add elements to stdclasses like we do for arrays?

Array (
  [0] => item 1
  [1] => item 2
)

Stdclass (
  [0] => item 1
  [1] => item 2
)

Is it generally harder to manipulate objects as compared to arrays? Since we have lots of array functions to make use of etc.


问:
Docker swarm mode running Hazelcast cluster
I'm running Hazelcast cluster using docker swarm. Even though nodes establish connection

```<code>Members [1] {
        Member [10.0.0.3]:5701 - b5fae3e3-0727-4bfd-8eb1-82706256ba2d this
}

May 27, 2017 2:38:12 PM com.hazelcast.internal.management.ManagementCenterService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Hazelcast will connect to Hazelcast Management Center on address:
http://10.0.0.3:8080/mancenter
May 27, 2017 2:38:12 PM com.hazelcast.internal.management.ManagementCenterService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Failed to pull tasks from management center
May 27, 2017 2:38:12 PM com.hazelcast.internal.management.ManagementCenterService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Failed to connect to:http://10.0.0.3:8080/mancenter/collector.do
May 27, 2017 2:38:12 PM com.hazelcast.core.LifecycleService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] [10.0.0.3]:5701 is STARTED
May 27, 2017 2:38:12 PM com.hazelcast.internal.partition.impl.PartitionStateManager
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Initializing cluster partition table arrangement...
May 27, 2017 2:38:19 PM com.hazelcast.internal.cluster.ClusterService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8]

Members [2] {
        Member [10.0.0.3]:5701 - b5fae3e3-0727-4bfd-8eb1-82706256ba2d this
        Member [10.0.0.4]:5701 - b3bd51d4-9366-45f0-bb66-78e67b13268c
}

May 27, 2017 2:38:19 PM com.hazelcast.internal.partition.impl.MigrationManager
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Re-partitioning cluster data... Migration queue size: 271
May 27, 2017 2:38:21 PM com.hazelcast.internal.partition.InternalPartitionService
</code>```

after while I keep getting errors:

```<code>WARNING: [10.0.0.3]:5701 [kpts-cluster] [3.8] Wrong bind request from [10.0.0.3]:5701! This node is not requested endpoint: [10.0.0.2]:5701
May 27, 2017 2:45:06 PM com.hazelcast.nio.tcp.TcpIpConnection
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Connection[id=18, /10.0.0.3:5701->/10.0.0.3:49575, endpoint=null, alive=false, type=MEMBER] closed. Reason: Wrong bind request from [10.0.0.3]:5701! This node is not requested endpoint: [10.0.0.2]:5701
May 27, 2017 2:45:06 PM com.hazelcast.nio.tcp.TcpIpConnection
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Connection[id=17, /10.0.0.2:49575->/10.0.0.2:5701, endpoint=[10.0.0.2]:5701, alive=false, type=MEMBER] closed. Reason: Connection closed by the other side
</code>```

I suppose this has to do something with the interface eth0 on every node. There are 2 addresses assigned - one "real" and one "fake" of the cluster manager... for some reason it is advertised as an endpoint...

```<code>1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
82: eth0@if83: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UP group default
    link/ether 02:42:0a:00:00:03 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.3/24 scope global eth0
       valid_lft forever preferred_lft forever
    inet 10.0.0.2/32 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:aff:fe00:3/64 scope link
       valid_lft forever preferred_lft forever
84: eth1@if85: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:12:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.18.0.3/16 scope global eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe12:3/64 scope link
       valid_lft forever preferred_lft forever
86: eth2@if87: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UP group default
    link/ether 02:42:0a:ff:00:07 brd ff:ff:ff:ff:ff:ff
    inet 10.255.0.7/16 scope global eth2
       valid_lft forever preferred_lft forever
    inet 10.255.0.6/32 scope global eth2
       valid_lft forever preferred_lft forever
    inet6 fe80::42:aff:feff:7/64 scope link
       valid_lft forever preferred_lft forever
</code>```

Here is the network config read from one of the nodes:

```<code>[
    {
        "Name": "hazelcast-net",
        "Id": "ly1p50ykwjhf68k88220gxih6",
        "Created": "2017-05-27T16:38:04.638580169+02:00",
        "Scope": "swarm",
        "Driver": "overlay",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "10.0.0.0/24",
                    "Gateway": "10.0.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Containers": {
            "0fa2bd8f8e8e931e1140e2d4bee1b43ff1f7bd5e3049d95e9176c63fa9f47e4f": {
                "Name": "kpts.1zhprrumdjvenkl4cvsc7bt40.2ugiv46ubar8utnxc5hko1hdf",
                "EndpointID": "0c5681aebbacd27672c300742077a460c07a081d113c2238f4c707def735ebec",
                "MacAddress": "02:42:0a:00:00:03",
                "IPv4Address": "10.0.0.3/24",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.driver.overlay.vxlanid_list": "4097"
        },
        "Labels": {},
        "Peers": [
            {
                "Name": "c4-6f6cd87e898f",
                "IP": "10.6.225.34"
            },
            {
                "Name": "c5-77d9f542efe8",
                "IP": "10.6.225.35"
            }
        ]
    }
]
</code>```

答:
Try using the docker swarm discovery SPI. It will provide a custom AddressPicker implementation for swarm that completely gets rid of this constant problem in Hazelcast with interface selection and the "This node is not requested endpoint" error". I really wish they would fix this

https://github.com/bitsofinfo/hazelcast-docker-swarm-discovery-spi

```<code>import org.bitsofinfo.hazelcast.discovery.docker.swarm.SwarmAddressPicker;
...

Config conf =new ClasspathXmlConfig("yourHzConfig.xml");

NodeContext nodeContext = new DefaultNodeContext() {
    @Override
    public AddressPicker createAddressPicker(Node node) {
        return new SwarmAddressPicker(new ILogger() {
            // you provide the impl... or use provided "SystemPrintLogger"
        });
    }
};

HazelcastInstance hazelcastInstance = HazelcastInstanceFactory
        .newHazelcastInstance(conf,"myAppName",nodeContext);
</code>```

Body:
I'm running Hazelcast cluster using docker swarm. Even though nodes establish connection

Members [1] {
        Member [10.0.0.3]:5701 - b5fae3e3-0727-4bfd-8eb1-82706256ba2d this
}

May 27, 2017 2:38:12 PM com.hazelcast.internal.management.ManagementCenterService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Hazelcast will connect to Hazelcast Management Center on address:
http://10.0.0.3:8080/mancenter
May 27, 2017 2:38:12 PM com.hazelcast.internal.management.ManagementCenterService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Failed to pull tasks from management center
May 27, 2017 2:38:12 PM com.hazelcast.internal.management.ManagementCenterService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Failed to connect to:http://10.0.0.3:8080/mancenter/collector.do
May 27, 2017 2:38:12 PM com.hazelcast.core.LifecycleService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] [10.0.0.3]:5701 is STARTED
May 27, 2017 2:38:12 PM com.hazelcast.internal.partition.impl.PartitionStateManager
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Initializing cluster partition table arrangement...
May 27, 2017 2:38:19 PM com.hazelcast.internal.cluster.ClusterService
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8]

Members [2] {
        Member [10.0.0.3]:5701 - b5fae3e3-0727-4bfd-8eb1-82706256ba2d this
        Member [10.0.0.4]:5701 - b3bd51d4-9366-45f0-bb66-78e67b13268c
}

May 27, 2017 2:38:19 PM com.hazelcast.internal.partition.impl.MigrationManager
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Re-partitioning cluster data... Migration queue size: 271
May 27, 2017 2:38:21 PM com.hazelcast.internal.partition.InternalPartitionService

after while I keep getting errors:

WARNING: [10.0.0.3]:5701 [kpts-cluster] [3.8] Wrong bind request from [10.0.0.3]:5701! This node is not requested endpoint: [10.0.0.2]:5701
May 27, 2017 2:45:06 PM com.hazelcast.nio.tcp.TcpIpConnection
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Connection[id=18, /10.0.0.3:5701->/10.0.0.3:49575, endpoint=null, alive=false, type=MEMBER] closed. Reason: Wrong bind request from [10.0.0.3]:5701! This node is not requested endpoint: [10.0.0.2]:5701
May 27, 2017 2:45:06 PM com.hazelcast.nio.tcp.TcpIpConnection
INFO: [10.0.0.3]:5701 [kpts-cluster] [3.8] Connection[id=17, /10.0.0.2:49575->/10.0.0.2:5701, endpoint=[10.0.0.2]:5701, alive=false, type=MEMBER] closed. Reason: Connection closed by the other side

I suppose this has to do something with the interface eth0 on every node. There are 2 addresses assigned - one "real" and one "fake" of the cluster manager... for some reason it is advertised as an endpoint...

1: lo: <LOOPBACK,UP,LOWER_UP> mtu 65536 qdisc noqueue state UNKNOWN group default qlen 1
    link/loopback 00:00:00:00:00:00 brd 00:00:00:00:00:00
    inet 127.0.0.1/8 scope host lo
       valid_lft forever preferred_lft forever
    inet6 ::1/128 scope host
       valid_lft forever preferred_lft forever
82: eth0@if83: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UP group default
    link/ether 02:42:0a:00:00:03 brd ff:ff:ff:ff:ff:ff
    inet 10.0.0.3/24 scope global eth0
       valid_lft forever preferred_lft forever
    inet 10.0.0.2/32 scope global eth0
       valid_lft forever preferred_lft forever
    inet6 fe80::42:aff:fe00:3/64 scope link
       valid_lft forever preferred_lft forever
84: eth1@if85: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1500 qdisc noqueue state UP group default
    link/ether 02:42:ac:12:00:03 brd ff:ff:ff:ff:ff:ff
    inet 172.18.0.3/16 scope global eth1
       valid_lft forever preferred_lft forever
    inet6 fe80::42:acff:fe12:3/64 scope link
       valid_lft forever preferred_lft forever
86: eth2@if87: <BROADCAST,MULTICAST,UP,LOWER_UP> mtu 1450 qdisc noqueue state UP group default
    link/ether 02:42:0a:ff:00:07 brd ff:ff:ff:ff:ff:ff
    inet 10.255.0.7/16 scope global eth2
       valid_lft forever preferred_lft forever
    inet 10.255.0.6/32 scope global eth2
       valid_lft forever preferred_lft forever
    inet6 fe80::42:aff:feff:7/64 scope link
       valid_lft forever preferred_lft forever

Here is the network config read from one of the nodes:

[
    {
        "Name": "hazelcast-net",
        "Id": "ly1p50ykwjhf68k88220gxih6",
        "Created": "2017-05-27T16:38:04.638580169+02:00",
        "Scope": "swarm",
        "Driver": "overlay",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "10.0.0.0/24",
                    "Gateway": "10.0.0.1"
                }
            ]
        },
        "Internal": false,
        "Attachable": true,
        "Containers": {
            "0fa2bd8f8e8e931e1140e2d4bee1b43ff1f7bd5e3049d95e9176c63fa9f47e4f": {
                "Name": "kpts.1zhprrumdjvenkl4cvsc7bt40.2ugiv46ubar8utnxc5hko1hdf",
                "EndpointID": "0c5681aebbacd27672c300742077a460c07a081d113c2238f4c707def735ebec",
                "MacAddress": "02:42:0a:00:00:03",
                "IPv4Address": "10.0.0.3/24",
                "IPv6Address": ""
            }
        },
        "Options": {
            "com.docker.network.driver.overlay.vxlanid_list": "4097"
        },
        "Labels": {},
        "Peers": [
            {
                "Name": "c4-6f6cd87e898f",
                "IP": "10.6.225.34"
            },
            {
                "Name": "c5-77d9f542efe8",
                "IP": "10.6.225.35"
            }
        ]
    }
]

Body:
Try using the docker swarm discovery SPI. It will provide a custom AddressPicker implementation for swarm that completely gets rid of this constant problem in Hazelcast with interface selection and the "This node is not requested endpoint" error". I really wish they would fix this

https://github.com/bitsofinfo/hazelcast-docker-swarm-discovery-spi

import org.bitsofinfo.hazelcast.discovery.docker.swarm.SwarmAddressPicker;
...

Config conf =new ClasspathXmlConfig("yourHzConfig.xml");

NodeContext nodeContext = new DefaultNodeContext() {
    @Override
    public AddressPicker createAddressPicker(Node node) {
        return new SwarmAddressPicker(new ILogger() {
            // you provide the impl... or use provided "SystemPrintLogger"
        });
    }
};

HazelcastInstance hazelcastInstance = HazelcastInstanceFactory
        .newHazelcastInstance(conf,"myAppName",nodeContext);


问:
Hide/Show an image drawn with Graphics
I have multiple images drawn with Graphics. How can I make them appear and disappear using a JCheckBox ? </p>

```<code>private void drawImages(int index) {
   Graphics g = mNew.getGraphics();
   int x = index % this.width;
   int y = index / this.width;
   g.drawImage(imageLabelPixel.get(idImage-1), x, y, 100, 100, null);
}
</code>```

答:
I would do it like that:

```<code>JCheckBox cb = new JCheckBox();
ImgPanel p = new ImgPanel();

cb.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent evt){
        if(cb.isSelected){
            p.set(0);
        } else {
            p.set(-1);
        }
    }
});
</code>```

.

```<code>public class ImgPanel extends JPanel {

    private int i = 0;
    private List<BufferedImage> imgs;

    public ImgPanel(){
        //init imgs
    }

    public void set(){
        i = 0;
        repaint();
    }

    @Override
    public void paintComponent (Graphics g){
        super.paintComponent(g);

        if(i >= 0){
            Image img = imgs.get(i-1);
            Image img1 = img.getScaledInstance(100, 100, null);
        }

        g.drawImage(img1, 0, 0, null);
    }

}
</code>```

You can't simply draw on a graphic and then hand it to a compoennt or so (I don't really understand what your given code should have done). Instead you have to overwrite the paintComponent method of a Component and put your custom drawing code in there.

Title: Hide/Show an image drawn with Graphics

Body:
I have multiple images drawn with Graphics. How can I make them appear and disappear using a JCheckBox ?

private void drawImages(int index) {
   Graphics g = mNew.getGraphics();
   int x = index % this.width;
   int y = index / this.width;
   g.drawImage(imageLabelPixel.get(idImage-1), x, y, 100, 100, null);
}

Body:
I would do it like that:

JCheckBox cb = new JCheckBox();
ImgPanel p = new ImgPanel();

cb.addActionListener(new ActionListener(){
    @Override
    public void actionPerformed(ActionEvent evt){
        if(cb.isSelected){
            p.set(0);
        } else {
            p.set(-1);
        }
    }
});

.

public class ImgPanel extends JPanel {

    private int i = 0;
    private List<BufferedImage> imgs;

    public ImgPanel(){
        //init imgs
    }

    public void set(){
        i = 0;
        repaint();
    }

    @Override
    public void paintComponent (Graphics g){
        super.paintComponent(g);

        if(i >= 0){
            Image img = imgs.get(i-1);
            Image img1 = img.getScaledInstance(100, 100, null);
        }

        g.drawImage(img1, 0, 0, null);
    }

}

You can't simply draw on a graphic and then hand it to a compoennt or so (I don't really understand what your given code should have done). Instead you have to overwrite the paintComponent method of a Component and put your custom drawing code in there.


问:
Python: Double KeyboardInterrupt in Windows?
I'm running a console-based app in Python 3.1.2. I want the app to trap a Ctrl-C at the prompt and handle it according to context. I'm getting the KeyboardInterrupt as expected, but unexpectedly, I'm sometimes seeing it again when I go to write a warning message. The tracebacks are below. Any thoughts from you smart people?

```Traceback (most recent call last):
  File "E:\Dropbox\git\vocabulary\v.py", line 58, in main
    command, args = c.getcommand()
  File "E:\Dropbox\git\vocabulary\console.py", line 81, in getcommand
    command, *args = input(prompt).split()
KeyboardInterrupt

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\Dropbox\git\vocabulary\v.py", line 125, in
    main()
  File "E:\Dropbox\git\vocabulary\v.py", line 71, in main
    print("\nUse 'quit' to exit the application.")
  File "E:\Dropbox\git\vocabulary\utilities.py", line 191, in write
    self.stream.write(data)
KeyboardInterrupt```

答:
I can't reproduce this.

```<code>def foo():
    try:
        x = 0
        while True:
            x += 1
    except KeyboardInterrupt:
        print(x)
while True:
    foo()
</code>```

Works just fine and traps CTRL-C as expected.

Body:
I'm running a console-based app in Python 3.1.2. I want the app to trap a Ctrl-C at the prompt and handle it according to context. I'm getting the KeyboardInterrupt as expected, but unexpectedly, I'm sometimes seeing it again when I go to write a warning message. The tracebacks are below. Any thoughts from you smart people?

Traceback (most recent call last):
  File "E:\Dropbox\git\vocabulary\v.py", line 58, in main
    command, args = c.getcommand()
  File "E:\Dropbox\git\vocabulary\console.py", line 81, in getcommand
    command, *args = input(prompt).split()
KeyboardInterrupt

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "E:\Dropbox\git\vocabulary\v.py", line 125, in
    main()
  File "E:\Dropbox\git\vocabulary\v.py", line 71, in main
    print("\nUse 'quit' to exit the application.")
  File "E:\Dropbox\git\vocabulary\utilities.py", line 191, in write
    self.stream.write(data)
KeyboardInterrupt

Body:
I can't reproduce this.

def foo():
    try:
        x = 0
        while True:
            x += 1
    except KeyboardInterrupt:
        print(x)
while True:
    foo()

Works just fine and traps CTRL-C as expected.


问:
What is the root directory that H2O Flow UI exports to?
For example, I want to export a model (not the POJO) from an h2o flow running on a remote hadoop cluster, so that I can upload it to my local machine h2o session and and view the output metrics without having to train the model again with the same data. However, when I try to export the model from flow (under some name "export_test"), I cannot find it. To start the h2o session, I am doing:

```<code>$cd cd h2o-3.14.0.6-mapr5.2
$hadoop jar h2odriver.jar -nodes 5 -mapperXmx 6g -output hdfsOutputDirName
</code>```

but I don't see any file called "export_test" in the hdfsOutputDirName nor in the h2o-3.14.0.6-mapr5.2 directory (which is where models are stored whenever I export them when using flow on my local machine) so I'm not sure where it could be going. Is there a default base directory that h2o flow may be exporting to somewhere on the node I am remoted into (like baseDir/export_test)? Thanks.

答:
The model will be saved relative to where the particular node you are talking to is running.  So, on the local filesystem on the host where the YARN container that the REST API client (like R, Python, or H2O Flow) is talking to is placed.

This is probably not where you want the model to be saved.

You can explicitly specify an "hdfs://" path to save the model to, and then find it in hdfs.

[ That "-output hdfsOutputDirName" is actually an artifact of inheriting from org.apache.hadoop.util.ToolRunner, and isn't used for anything. ]

ContentLicense: CC BY-SA 4.0

Body:
For example, I want to export a model (not the POJO) from an h2o flow running on a remote hadoop cluster, so that I can upload it to my local machine h2o session and and view the output metrics without having to train the model again with the same data. However, when I try to export the model from flow (under some name "export_test"), I cannot find it. To start the h2o session, I am doing:

$cd cd h2o-3.14.0.6-mapr5.2
$hadoop jar h2odriver.jar -nodes 5 -mapperXmx 6g -output hdfsOutputDirName

but I don't see any file called "export_test" in the hdfsOutputDirName nor in the h2o-3.14.0.6-mapr5.2 directory (which is where models are stored whenever I export them when using flow on my local machine) so I'm not sure where it could be going. Is there a default base directory that h2o flow may be exporting to somewhere on the node I am remoted into (like baseDir/export_test)? Thanks.


问:
How to create a modal instance inside an ajaxLink
I'm using an AjaxLink to open a Modal.
This modal displays first a "Are you sure" panel and then a panel with the result of the operation together with a Close button.
I close the modal and if I open it again I get the second panel and not the first.
I would like everytime the modal is opened to get the sequence of panels from the beginning, i.e., starting with the initial panel.
I tried to instantiate the modal inside the AjaxLink but I have issues with the html markup.

HTML

```<code> <wicket:panel>
    <div wicket:id="modal2"></div>
    <button class="btn btn-primary" wicket:id="link"><span
     wicket:id="buttonLabel"></span></button>
</wicket:panel>
</code>```

Java

```<code>  public class ButtonPayment2 extends Panel{

    private static final long serialVersionUID = 1L;

    private Label label;
    private List<String> current;
    private String party;
    private DetailsModal2 modal;
    private String guid;

    @SpringBean
    private Environment env;

    @SpringBean
    private IService service;

    public ButtonPayment2(String componentId, IModel<PaymentDomain> rowmodel, String invoiceId, String paymentId){

    super(componentId);

    current = service.getPById(rowmodel.getObject());
    guid = rowmodel.getObject().getPaymentGUID();
    initiateButton(current);

    modal = new DetailsModal2("modal2",rowmodel,party){
        @Override
        public void closeAction(AjaxRequestTarget target, boolean toPass) {
            super.closeAction(target, toPass);
        }
    };
    modal.header(Model.of("Transaction process"));
    modal.setHeaderVisible(true);
    modal.setOutputMarkupId(true);
    add(modal);

    add(new AjaxLink("link"){

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {

            modal.show(target);
            target.add(this);

      }//close onclick
   }.add(label));//close ajaxLink

    modal.detach();
 }
</code>```

}

DetailsModal2.java

```<code>public class DetailsModal2 extends Modal<IModel<PaymentDomain>> {

@SpringBean
private IService service;

private String party;
private BootstrapAjaxLink<String> noButton;
private ResponseMessage message;
private String paymentId;
private ProcessingPanel panel2;
private Panel replacedPanel;
private boolean booleanToPass;
private IModel<PaymentDomain> model;

public DetailsModal2(String id, IModel<PaymentDomain> model, String party) {
    super(id);
    this.party = party;
    this.model = model;
    this.paymentId = model.getObject().getGUID();

    replacedPanel = new AreYouSure("replacedPanel");
    replacedPanel.setOutputMarkupId(true);
    add(replacedPanel);

    panel2 = new ProcessingPanel("replacedPanel");

    addButton(new BootstrapAjaxLink<String>("button", null, Buttons.Type.Warning, new ResourceModel("details")) {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {

            addNewPanel(new AjaxLazyLoadPanel("replacedPanel") {
                @Override
                public Component getLazyLoadComponent(String markupId) {
                    if (!condition) {

                        message = service.getPayment(paymentId);

                        if (message == null) {
                            booleanToPass = true;
                            return new VotingResultPanel(markupId, true);
                        } else {
                            return new VotingResultPanel(markupId, false);
                        }
                    } // close if

                    else if (condition)) {

                        message = service.setPayment(paymentId);
                        if (message == null) {
                            booleanToPass = false;
                            return new VotingResultPanel(markupId, true);

                        } else {
                            System.out.println("" + message.getError());
                            return new VotingResultPanel(markupId, false);
                        }
                    }

                    else {
                        System.out.println("It was not possible to access the db");
                    }
                }
            }, target);

            this.setVisible(false);
            target.add(this);
            noButton.setLabel(Model.of("Close"));
            target.add(noButton);

            target.add(this);
        }

    });

    noButton = new BootstrapAjaxLink<String>("button", null, Buttons.Type.Primary) {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target){
            closeAction(target,booleanToPass);
        }
    }.setLabel(Model.of("No"));
    addButton(noButton);

}

public void closeAction(AjaxRequestTarget target, boolean flag){
    close(target);

}

public void addNewPanel(Panel addpanel, AjaxRequestTarget target) {
    Panel newPanel = null;
    newPanel = addpanel;
    newPanel.setOutputMarkupId(true);
    replacedPanel.replaceWith(newPanel);
    target.add(newPanel);
    replacedPanel = newPanel;
 }
}// close class
</code>```

HTML of DetailsModal2

```<code> <wicket:extend>
     <div><span wicket:id="replacedPanel"> </span></div>
 </wicket:extend>
</code>```

New solution for this particular case, DetailsModal2 changed:

```<code> public class DetailsModal2 extends Modal<IModel<PaymentDomain>> {

 @SpringBean
 private IService service;

 private Component noButton;
 private Component yesButton;
 private Component noButton;
 private String paymentId;
 private Panel replacedPanel;
 private IModel<PaymentDomain> model;

 public DetailsModal2(String id, IModel<PaymentDomain> model, String party)
 {
  super(id);
  this.party = party;
  this.model = model;
  this.paymentId = model.getObject().getPaymentGUID();

  replacedPanel = new AreYouSure("replacedPanel");
  replacedPanel = panel1;
  replacedPanel.setOutputMarkupId(true);
  add(replacedPanel);

  addButton(yesButton = new BootstrapAjaxLink<String>("button", null, Buttons.Type.Warning, new ResourceModel("details")) {

    private static final long serialVersionUID = 1L;

    @Override
    public void onClick(AjaxRequestTarget target) {

        addNewPanel(new AjaxLazyLoadPanel("replacedPanel") {
            @Override
            public Component getLazyLoadComponent(String markupId) {
                if (!condition)) {

                    message = service.getPayment(paymentId);

                    if (message == null) {
                        return new VotingResultPanel(markupId, true);
                    } else
                    {
                        return new VotingResultPanel(markupId, false);
                    }
                } // close if

                else if (condition)) {

                    message = service.setPayment(paymentId);
                    if (message == null) {
                        return new VotingResultPanel(markupId, true);

                    } else {
                        System.out.println("" + message.getError());
                        return new VotingResultPanel(markupId, false);
                    }
                }

                else {
                    System.out.println("error");
                }
            }
        }, target);

        this.setOutputMarkupPlaceholderTag(true);
        this.setVisible(false);
        noButton.setOutputMarkupPlaceholderTag(true);
        noButton.setVisible(false);
        closeButton.setVisible(true);
        target.add(this, noButton, closeButton);
    }

  });

  noButton = new BootstrapAjaxLink<String>("button", null, Buttons.Type.Primary) {
    private static final long serialVersionUID = 1L;

    @Override
    public void onClick(AjaxRequestTarget target){
        close(target);
    }
}.setLabel(Model.of("No"));
addButton(noButton);

}

 closeButton = new BootstrapAjaxLink<String>("button", null, Buttons.Type.Primary) {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target){
            addNewPanel(panel1,target);
            yesButton.setOutputMarkupId(true);
            yesButton.setVisible(true);
            noButton.setOutputMarkupId(true);
            noButton.setVisible(true);
            closeButton.setOutputMarkupId(true);
            closeButton.setOutputMarkupPlaceholderTag(true);
            closeButton.setVisible(false);
            target.add(yesButton,noButton,closeButton);
            close(target);

        }
    }.setLabel(Model.of("Close"));
    closeButton.setOutputMarkupPlaceholderTag(true);
    closeButton.setVisible(false);
    addButton(closeButton);
}

 public void addNewPanel(Panel addpanel, AjaxRequestTarget target) {
  Panel newPanel = null;
  newPanel = addpanel;
  newPanel.setOutputMarkupId(true);
  replacedPanel.replaceWith(newPanel);
  target.add(newPanel);
  replacedPanel = newPanel;
 }
}// close class
</code>```

答:
you can try to move the following lines

```<code>replacedPanel = new AreYouSure("replacedPanel");
replacedPanel.setOutputMarkupId(true);
add(replacedPanel);
</code>```

to onConfigure and change add() to addOrReplace()

Body:
I'm using an AjaxLink to open a Modal.
This modal displays first a "Are you sure" panel and then a panel with the result of the operation together with a Close button.
I close the modal and if I open it again I get the second panel and not the first.
I would like everytime the modal is opened to get the sequence of panels from the beginning, i.e., starting with the initial panel.
I tried to instantiate the modal inside the AjaxLink but I have issues with the html markup.

HTML

 <wicket:panel>

    <button class="btn btn-primary" wicket:id="link"></button>
</wicket:panel>

Java

  public class ButtonPayment2 extends Panel{

    private static final long serialVersionUID = 1L;

    private Label label;
    private List<String> current;
    private String party;
    private DetailsModal2 modal;
    private String guid;

    @SpringBean
    private Environment env;

    @SpringBean
    private IService service;

    public ButtonPayment2(String componentId, IModel<PaymentDomain> rowmodel, String invoiceId, String paymentId){

    super(componentId);

    current = service.getPById(rowmodel.getObject());
    guid = rowmodel.getObject().getPaymentGUID();
    initiateButton(current);

    modal = new DetailsModal2("modal2",rowmodel,party){
        @Override
        public void closeAction(AjaxRequestTarget target, boolean toPass) {
            super.closeAction(target, toPass);
        }
    };
    modal.header(Model.of("Transaction process"));
    modal.setHeaderVisible(true);
    modal.setOutputMarkupId(true);
    add(modal);

    add(new AjaxLink("link"){

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {

            modal.show(target);
            target.add(this);

      }//close onclick
   }.add(label));//close ajaxLink

    modal.detach();
 }

}

DetailsModal2.java

public class DetailsModal2 extends Modal<IModel<PaymentDomain>> {

@SpringBean
private IService service;

private String party;
private BootstrapAjaxLink<String> noButton;
private ResponseMessage message;
private String paymentId;
private ProcessingPanel panel2;
private Panel replacedPanel;
private boolean booleanToPass;
private IModel<PaymentDomain> model;

public DetailsModal2(String id, IModel<PaymentDomain> model, String party) {
    super(id);
    this.party = party;
    this.model = model;
    this.paymentId = model.getObject().getGUID();

    replacedPanel = new AreYouSure("replacedPanel");
    replacedPanel.setOutputMarkupId(true);
    add(replacedPanel);

    panel2 = new ProcessingPanel("replacedPanel");

    addButton(new BootstrapAjaxLink<String>("button", null, Buttons.Type.Warning, new ResourceModel("details")) {

        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target) {

            addNewPanel(new AjaxLazyLoadPanel("replacedPanel") {
                @Override
                public Component getLazyLoadComponent(String markupId) {
                    if (!condition) {

                        message = service.getPayment(paymentId);

                        if (message == null) {
                            booleanToPass = true;
                            return new VotingResultPanel(markupId, true);
                        } else {
                            return new VotingResultPanel(markupId, false);
                        }
                    } // close if

                    else if (condition)) {

                        message = service.setPayment(paymentId);
                        if (message == null) {
                            booleanToPass = false;
                            return new VotingResultPanel(markupId, true);

                        } else {
                            System.out.println("" + message.getError());
                            return new VotingResultPanel(markupId, false);
                        }
                    }

                    else {
                        System.out.println("It was not possible to access the db");
                    }
                }
            }, target);

            this.setVisible(false);
            target.add(this);
            noButton.setLabel(Model.of("Close"));
            target.add(noButton);

            target.add(this);
        }

    });

    noButton = new BootstrapAjaxLink<String>("button", null, Buttons.Type.Primary) {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target){
            closeAction(target,booleanToPass);
        }
    }.setLabel(Model.of("No"));
    addButton(noButton);

}

public void closeAction(AjaxRequestTarget target, boolean flag){
    close(target);

}

public void addNewPanel(Panel addpanel, AjaxRequestTarget target) {
    Panel newPanel = null;
    newPanel = addpanel;
    newPanel.setOutputMarkupId(true);
    replacedPanel.replaceWith(newPanel);
    target.add(newPanel);
    replacedPanel = newPanel;
 }
}// close class

HTML of DetailsModal2

 <wicket:extend>

 </wicket:extend>

New solution for this particular case, DetailsModal2 changed:

 public class DetailsModal2 extends Modal<IModel<PaymentDomain>> {

 @SpringBean
 private IService service;

 private Component noButton;
 private Component yesButton;
 private Component noButton;
 private String paymentId;
 private Panel replacedPanel;
 private IModel<PaymentDomain> model;

 public DetailsModal2(String id, IModel<PaymentDomain> model, String party)
 {
  super(id);
  this.party = party;
  this.model = model;
  this.paymentId = model.getObject().getPaymentGUID();

  replacedPanel = new AreYouSure("replacedPanel");
  replacedPanel = panel1;
  replacedPanel.setOutputMarkupId(true);
  add(replacedPanel);

  addButton(yesButton = new BootstrapAjaxLink<String>("button", null, Buttons.Type.Warning, new ResourceModel("details")) {

    private static final long serialVersionUID = 1L;

    @Override
    public void onClick(AjaxRequestTarget target) {

        addNewPanel(new AjaxLazyLoadPanel("replacedPanel") {
            @Override
            public Component getLazyLoadComponent(String markupId) {
                if (!condition)) {

                    message = service.getPayment(paymentId);

                    if (message == null) {
                        return new VotingResultPanel(markupId, true);
                    } else
                    {
                        return new VotingResultPanel(markupId, false);
                    }
                } // close if

                else if (condition)) {

                    message = service.setPayment(paymentId);
                    if (message == null) {
                        return new VotingResultPanel(markupId, true);

                    } else {
                        System.out.println("" + message.getError());
                        return new VotingResultPanel(markupId, false);
                    }
                }

                else {
                    System.out.println("error");
                }
            }
        }, target);

        this.setOutputMarkupPlaceholderTag(true);
        this.setVisible(false);
        noButton.setOutputMarkupPlaceholderTag(true);
        noButton.setVisible(false);
        closeButton.setVisible(true);
        target.add(this, noButton, closeButton);
    }

  });

  noButton = new BootstrapAjaxLink<String>("button", null, Buttons.Type.Primary) {
    private static final long serialVersionUID = 1L;

    @Override
    public void onClick(AjaxRequestTarget target){
        close(target);
    }
}.setLabel(Model.of("No"));
addButton(noButton);

}

 closeButton = new BootstrapAjaxLink<String>("button", null, Buttons.Type.Primary) {
        private static final long serialVersionUID = 1L;

        @Override
        public void onClick(AjaxRequestTarget target){
            addNewPanel(panel1,target);
            yesButton.setOutputMarkupId(true);
            yesButton.setVisible(true);
            noButton.setOutputMarkupId(true);
            noButton.setVisible(true);
            closeButton.setOutputMarkupId(true);
            closeButton.setOutputMarkupPlaceholderTag(true);
            closeButton.setVisible(false);
            target.add(yesButton,noButton,closeButton);
            close(target);

        }
    }.setLabel(Model.of("Close"));
    closeButton.setOutputMarkupPlaceholderTag(true);
    closeButton.setVisible(false);
    addButton(closeButton);
}

 public void addNewPanel(Panel addpanel, AjaxRequestTarget target) {
  Panel newPanel = null;
  newPanel = addpanel;
  newPanel.setOutputMarkupId(true);
  replacedPanel.replaceWith(newPanel);
  target.add(newPanel);
  replacedPanel = newPanel;
 }
}// close class

Body:
you can try to move the following lines

replacedPanel = new AreYouSure("replacedPanel");
replacedPanel.setOutputMarkupId(true);
add(replacedPanel);

to onConfigure and change add() to addOrReplace()


问:
$.post is not send data to web form
Function:

```<code>$.post("/SurveyResult.aspx", {
    test: 'testing',
}).done(function (data) {
    alert("Data Updated");
});
</code>```

ServerSide of :

```<code> protected void Page_Load(object sender, EventArgs e)
 {
    var formValue = Request.Form["test"];
 }
</code>```

function is posting well But I'm getting null value of test at server side. Do not know what the issue is.

答:
You will need to mark the method on the aspx code behind as a webmethod and specify the same when you are posting to it.On the client, you will need to make the following change:

```<code>$.post("/SurveyResult.aspx/OnSubmit", {
test: 'testing',
}).done(function (data) {
alert("Data Updated");
});
</code>```

Also, in your code-behind you will need to expose the method you want to be called to handle the post.

```<code>[WebMethod]
public static string OnSubmit(string test)
{
   var value = test;

}
</code>```

Title: $.post is not send data to web form

Body:
Function:

$.post("/SurveyResult.aspx", {
    test: 'testing',
}).done(function (data) {
    alert("Data Updated");
});

ServerSide of :

 protected void Page_Load(object sender, EventArgs e)
 {
    var formValue = Request.Form["test"];
 }

function is posting well But I'm getting null value of test at server side. Do not know what the issue is.

Body:
You will need to mark the method on the aspx code behind as a webmethod and specify the same when you are posting to it.On the client, you will need to make the following change:

$.post("/SurveyResult.aspx/OnSubmit", {
test: 'testing',
}).done(function (data) {
alert("Data Updated");
});

Also, in your code-behind you will need to expose the method you want to be called to handle the post.

[WebMethod]
public static string OnSubmit(string test)
{
   var value = test;

}


问:
Split 2-3 tree into less-than and greater-than given value X
I need to write function, which receives some key x and split 2-3 tree into 2 2-3 trees. In first tree there are all nodes which are bigger than x, and in second which are less. I need to make it with complexity O(logn). thanks in advance for any idea.

edited
I thought about finding key x in the tree. And after split its two sub-trees(bigger or lesser if they exist) into 2 trees, and after begin to go up and every time to check sub-trees which I've not checked yet and to join to one of the trees. My problem is that all leaves must be at the same level.

答: If you move from the root to your key and split each node so one points at the nodes larger than the key and the other at the rest and then make the larger node be a part of your larger tree, say by having the leftmost node at one level higher point at it, (don't fix the tree yet, do it at the end) until you reach the key you will get your trees. Then you just need to fix both trees on the path you used (note that the same path exists on both trees).</p>


问:
WebForms redirect page request for same page
Webforms using VB.NET.  I have a page a.aspx that exists within a web app.  I want to replace that page (with my own modified version) and call a new page b.aspx, but still call a.aspx if I need to.  By design I cannot rename or change existing links in the application to a.aspx (out of my control).

Can I, using some sort of re-writing IIS module (or something more practical), create a new a.aspx that checks some server variable, if that is true then redirect to b.aspx, otherwise redirect to the original a.aspx, bypassing my code.

Thanks,

答:
I think I understand your question, and you can solve it by using a Session variable. Something like:

```<code>If Session("YourVariableHere") = Nothing Then
    Server.Transfer("b.aspx", True)
End If
</code>```

Use this on your page A load.

Body:
I think I understand your question, and you can solve it by using a Session variable. Something like:

If Session("YourVariableHere") = Nothing Then
    Server.Transfer("b.aspx", True)
End If

Use this on your page A load.


问:
rjava dependent package installation Segmentation fault (core dumped)
I am trying to reinstall a package that I was previously able to install and use. I was building a package of my own after my computer unexpectedly restarted and then I started to have problems loading the rpgraph package. So I decided to uninstall it and to reinstall it. When I did so I got the following error:

```<code>library(devtools)

library(rJava)
install_github("Albluca/rpgraph")

Downloading GitHub repo Albluca/rpgraph@master
from URL https://api.github.com/repos/Albluca/rpgraph/zipball/master
Installing rpgraph
Running command /usr/lib/R/bin/R
Arguments:
CMD
INSTALL
/tmp/Rtmp5OrtLL/devtools505a703b3ccd/Albluca-rpgraph-de04f96
--library=/home/gonzalo/R/x86_64-pc-linux-gnu-library/3.4
--install-tests

installing source package ‘rpgraph’ ...
** R
** data
*** moving datasets to lazyload DB
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
Segmentation fault (core dumped)
ERROR: loading failed
removing ‘/home/gonzalo/R/x86_64-pc-linux-gnu-library/3.4/rpgraph’
Installation failed: run(bin, args = real_cmdargs,         stdout_line_callback = real_callback(stdout), stderr_line_callback =     real_callback(stderr), stdout_callback = real_block_callback,     stderr_callback = real_block_callback, echo_cmd = echo, echo = show,     spinner = spinner, error_on_status = fail_on_status, timeout = timeout) :     System command error`
</code>```

I tried reinstalling JAva and cran from zero but somehow there is     something that remains in my system that avoids the package to be installed. Also, since the error is not very informative, I have no idea on how to narrow where the problem is.

Thanks for any help you can provide.

答:
This seems to be a bug in recent kernel versions, the same problem happens with other R libraries that involve Java, and also other software.

See https://lists.ubuntu.com/archives/ubuntu-devel-discuss/2017-June/017507.html and https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1698919.

This workaround does the trick for me:

```<code>export _JAVA_OPTIONS="-Xss2560k -Xmx2g"
</code>```

Body:
I am trying to reinstall a package that I was previously able to install and use. I was building a package of my own after my computer unexpectedly restarted and then I started to have problems loading the rpgraph package. So I decided to uninstall it and to reinstall it. When I did so I got the following error:

library(devtools)

library(rJava)
install_github("Albluca/rpgraph")

Downloading GitHub repo Albluca/rpgraph@master
from URL https://api.github.com/repos/Albluca/rpgraph/zipball/master
Installing rpgraph
Running command /usr/lib/R/bin/R
Arguments:
CMD
INSTALL
/tmp/Rtmp5OrtLL/devtools505a703b3ccd/Albluca-rpgraph-de04f96
--library=/home/gonzalo/R/x86_64-pc-linux-gnu-library/3.4
--install-tests

installing source package ‘rpgraph’ ...
** R
** data
*** moving datasets to lazyload DB
** inst
** preparing package for lazy loading
** help
*** installing help indices
** building package indices
** installing vignettes
** testing if installed package can be loaded
Segmentation fault (core dumped)
ERROR: loading failed
removing ‘/home/gonzalo/R/x86_64-pc-linux-gnu-library/3.4/rpgraph’
Installation failed: run(bin, args = real_cmdargs,         stdout_line_callback = real_callback(stdout), stderr_line_callback =     real_callback(stderr), stdout_callback = real_block_callback,     stderr_callback = real_block_callback, echo_cmd = echo, echo = show,     spinner = spinner, error_on_status = fail_on_status, timeout = timeout) :     System command error`

I tried reinstalling JAva and cran from zero but somehow there is     something that remains in my system that avoids the package to be installed. Also, since the error is not very informative, I have no idea on how to narrow where the problem is.

Thanks for any help you can provide.

Body:
This seems to be a bug in recent kernel versions, the same problem happens with other R libraries that involve Java, and also other software.

See https://lists.ubuntu.com/archives/ubuntu-devel-discuss/2017-June/017507.html and https://bugs.launchpad.net/ubuntu/+source/linux/+bug/1698919.

This workaround does the trick for me:

export _JAVA_OPTIONS="-Xss2560k -Xmx2g"


问:
How to build an Eclipse plugin with maven?
How do you build an Eclipse plugin with Maven?  What dependencies or plugins do I need?  I am looking to develop for Eclipse 3.7.</p>

答:
You can use Maven 3.3 (at least) and Maven Tycho 0.24.0. Add this to your project's .mvn/extensions.xml:

```<code><extensions>
  <extension>
    <groupId>org.eclipse.tycho.extras</groupId>
    <artifactId>tycho-pomless</artifactId>
    <version>0.26.0</version>
  </extension>
</extensions>
</code>```

Then you must define your pom.xml according to the structure of your project.
I recommend this article: Eclipse Tycho for building Eclipse Plug-ins, OSGi bundles and RCP applications - Tutorial

You can follow the example on this page to have a general idea of using maven plugin Tycho.

Body:
You can use Maven 3.3 (at least) and Maven Tycho 0.24.0. Add this to your project's .mvn/extensions.xml:

<extensions>
  <extension>
    <groupId>org.eclipse.tycho.extras</groupId>
    <artifactId>tycho-pomless</artifactId>
    <version>0.26.0</version>
  </extension>
</extensions>

Then you must define your pom.xml according to the structure of your project.
I recommend this article: Eclipse Tycho for building Eclipse Plug-ins, OSGi bundles and RCP applications - Tutorial

You can follow the example on this page to have a general idea of using maven plugin Tycho.


问:
Return both string and integer from a template function in C++
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

```<code>template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}
</code>```

and I would like to be able to call it like:

```<code>bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");
</code>```

as an alternative for the char*, a string would be also fine:

```<code>string sBrokerUrl = getEntry<string>(node, "BrokerUrl");
</code>```

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

答:
Since C++17 you can use constexpr if; whose condition part will be evaluated at the compile time, and if the result is true then the statement-false part (otherwise the statement-true part) will be discarded. (Thus won't cause the error.) e.g.

```<code>if constexpr (is_same<entryType, bool>::value) {
     return boolvalue; //returning a boolean
}
else if constexpr (is_same<entryType, int>::value) {
     return a; //this is an integer
}
else if constexpr (is_same<entryType, char*>::value) {
     return result; //this is a char*
}
</code>```

LIVE

Body:
I am trying to write a generic function, using template, that is able to return bool, integer or char* or string.

template<typename entryType>
entryType getEntry(xml_node node, const char* entryKey)
{
    ...

    if (is_same<entryType, bool>::value) {
         return boolvalue; //returning a boolean
    }
    else if(is_same<entryType, int>::value) {
         return a; //this is an integer
    }
    else if (is_same<entryType, char*>::value) {
         return result; //this is a char*
    }
}

and I would like to be able to call it like:

bool bPublisher = getEntry<bool>(node, "Publisher");
int QoS = getEntry<int>(node, "QualityOfService");
char* sBrokerUrl = getEntry<char*>(node, "BrokerUrl");

as an alternative for the char*, a string would be also fine:

string sBrokerUrl = getEntry<string>(node, "BrokerUrl");

I get errors like: "cannot convert from 'bool' to 'char*'. I understand the problem, the compiler is not able to detect that the code execution branch depends on the type I give. I just can't find a solution for that. Could anyone help me? Thanks.

Body:
Since C++17 you can use constexpr if; whose condition part will be evaluated at the compile time, and if the result is true then the statement-false part (otherwise the statement-true part) will be discarded. (Thus won't cause the error.) e.g.

if constexpr (is_same<entryType, bool>::value) {
     return boolvalue; //returning a boolean
}
else if constexpr (is_same<entryType, int>::value) {
     return a; //this is an integer
}
else if constexpr (is_same<entryType, char*>::value) {
     return result; //this is a char*
}

LIVE


问:
C# LINQ OrderBy several clauses
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

```<code>public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}
</code>```

My project status enum:

```<code>public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}
</code>```

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

```<code>projects = projects.OrderBy(x => x.StatusId).ToList();
</code>```

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

答:
Not really pretty, but should work:

```<code>projects.OrderBy(x => x.StatusId).ThenBy(c => c.StatusId == Status.Validated ? 1 : 0).ToList();
</code>```

Otherwise you need to provide your own Comparer:

```<code>class StatusComparer : IComparer<Status>
        {
            public int Compare(Status x, Status y)
            {
                if (x.Equals(y)) return 0;
                return (x > y || x.Equals(Status.Validated)) ? 1 : -1;
            }
        }
</code>```

And then call:

```<code>projects.OrderBy(x => x.StatusId, new StatusComparer()).ToList();
</code>```

Or do something like the other people here proposed ;)

Title: C# LINQ OrderBy several clauses

Body:
I'm currently working on an application in ASP.NET MVC 4.5. I need to write a LINQ query to order a list of Projects by different StatusIds.

Given is a list of Projects with this ViewModel:

public class ProjectVm
{
   public int ProjectId { get; set; }
   public string Title { get; set; }
   public Status StatusId { get; set; }
}

My project status enum:

public enum Status : byte
{
    Draft = 1,
    Pending = 2,
    Validated = 3,
    Refused = 4
}

The idea is to bring the List<ProjectVm> in a certain order, thus first ordered by 1 Draft, second by 2 Pending, third by 4 Refused and fourth by 3 Validated.

My current query looks like this:

projects = projects.OrderBy(x => x.StatusId).ToList();

Unfortunately this query doesn't respect the desired order (4 comes before 3).

Do you know how to apply a condition on this query to bring the projects into the right order (1, 2, 4, 3) ?

Thanks!

Body:
Not really pretty, but should work:

projects.OrderBy(x => x.StatusId).ThenBy(c => c.StatusId == Status.Validated ? 1 : 0).ToList();

Otherwise you need to provide your own Comparer:

class StatusComparer : IComparer<Status>
        {
            public int Compare(Status x, Status y)
            {
                if (x.Equals(y)) return 0;
                return (x > y || x.Equals(Status.Validated)) ? 1 : -1;
            }
        }

And then call:

projects.OrderBy(x => x.StatusId, new StatusComparer()).ToList();

Or do something like the other people here proposed ;)


问:
Basic Python looping and appending
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.

Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.

So the above is what I am trying to accomplish. And I am extremely new to all this so sorry if I don't make sense at times. Right now I am just trying to set up running through my list and appending any str to string list, and any int to my num list. Ive tried tons of ways and read documentation, and tried to search for help but I am either misreading stuff or just searching the wrong stuff. any help would be greatly appreciated.

```<code>stuff = ['magical unicorns',19,'hello',98.98,'world']

string = []
num = []

for i in range(len(stuff)):
    if isinstance(i,str):
        string.append(value,i)
    if isinstance(i,int):
        num.append(i)

print (string)
print (num)
</code>```

答:
You can use list comprehension for a quick, concise solution:

```<code>stuff = ['magical unicorns',19,'hello',98.98,'world']

s = ''.join(i for i in stuff if isinstance(i, str))

a = sum(i for i in stuff if isinstance(i, int) or isinstance(i, float))

print(s)

print(a)

if len(s) > 0 and a > 0:
   print("mixed")

elif len(s) > 0 and a == 0:
   print("string")

elif len(s) == 0 and a > 0:
   print("integer")
</code>```

Output:

```<code>magical unicornshelloworld
19
mixed
</code>```

Title: Basic Python looping and appending

Body:
Write a program that takes a list and prints a message for each element in the list, based on that element's data type.

Your program input will always be a list. For each item in the list, test its data type. If the item is a string, concatenate it onto a new string. If it is a number, add it to a running sum. At the end of your program print the string, the number and an analysis of what the array contains. If it contains only one type, print that type, otherwise, print 'mixed'.

So the above is what I am trying to accomplish. And I am extremely new to all this so sorry if I don't make sense at times. Right now I am just trying to set up running through my list and appending any str to string list, and any int to my num list. Ive tried tons of ways and read documentation, and tried to search for help but I am either misreading stuff or just searching the wrong stuff. any help would be greatly appreciated.

stuff = ['magical unicorns',19,'hello',98.98,'world']

string = []
num = []

for i in range(len(stuff)):
    if isinstance(i,str):
        string.append(value,i)
    if isinstance(i,int):
        num.append(i)

print (string)
print (num)

Body:
You can use list comprehension for a quick, concise solution:

stuff = ['magical unicorns',19,'hello',98.98,'world']

s = ''.join(i for i in stuff if isinstance(i, str))

a = sum(i for i in stuff if isinstance(i, int) or isinstance(i, float))

print(s)

print(a)

if len(s) > 0 and a > 0:
   print("mixed")

elif len(s) > 0 and a == 0:
   print("string")

elif len(s) == 0 and a > 0:
   print("integer")

Output:

magical unicornshelloworld
19
mixed


问:
How to hide loader when there is no more page to be loaded
In this website that I am building https://vase.ai/blog/ , I am using a script of infinite scrolling to make several pages into one page for scrolling.

I would like to hide the loader(the spinning one) when there is no more page to be loaded. I figured that the following code might be able to help me to detect the error (Failed to load resource: the server responded with a status of 404 (Not Found)) and execute the hiding. However, it does not work. Am I missing something out?

```<code>window.addEventListener('error', function(e) {
  $('loading').fadeOut()
}, true);
</code>```

Code that I use to to load more :

```<code>//implementing infinite scrolling
$grid.infinitescroll({
  // Pagination element that will be hidden
  navSelector: '.pagination',

  // Next page link
  nextSelector: '.pagination a',

  // Selector of items to retrieve
  itemSelector: '.grid-blog',
},

// Function called once the elements are retrieved
function(new_elts) {
  var elts = $(new_elts).css('opacity', 0);

  elts.animate({opacity: 1});
  $grid.packery('appended', elts);

  $('.target-resize').textfill({
    maxFontPixels: 36,
    changeLineHeight:false
  })

  $grid.packery({
    itemSelector: '.grid-blog',
    gutter: 20,

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

答:
It's difficult to answer your question without the code that make the http calls in order to load your content. But,

1) you may have an error, and still have contents to be loaded, in that case your loader will disappear even if contents are still loading.

2) You should have something that tel your site what you have to load.
an array of url, or anything, you can maybe use this to hide your loader when all contents has been loaded.

3) You should have somewhere a function that make httpcalls to get your content. This function should have a callback. In this callback, you should be able to catch an error, and then hide your loader.

I cannot give you more informations with the amount of code you show in your exemple.

edit : after looking at your code, you may try to do :

```<code>// Function called once the elements are retrieved
function(new_elts) {
    if(!new_elts) {
        $('loading').fadeOut();
        return;
    }
...
}
</code>```

I don't think this is the right solution, your plugin should have a built-in function to stop calling new pages, but since I don't see the function that make the http call, or any array/iterator of URLs, it's difficult top help you.

you should check this demo to : https://codepen.io/desandro/pen/rwwoGe

Body:
In this website that I am building https://vase.ai/blog/ , I am using a script of infinite scrolling to make several pages into one page for scrolling.

I would like to hide the loader(the spinning one) when there is no more page to be loaded. I figured that the following code might be able to help me to detect the error (Failed to load resource: the server responded with a status of 404 (Not Found)) and execute the hiding. However, it does not work. Am I missing something out?

window.addEventListener('error', function(e) {
  $('loading').fadeOut()
}, true);

Code that I use to to load more :

//implementing infinite scrolling
$grid.infinitescroll({
  // Pagination element that will be hidden
  navSelector: '.pagination',

  // Next page link
  nextSelector: '.pagination a',

  // Selector of items to retrieve
  itemSelector: '.grid-blog',
},

// Function called once the elements are retrieved
function(new_elts) {
  var elts = $(new_elts).css('opacity', 0);

  elts.animate({opacity: 1});
  $grid.packery('appended', elts);

  $('.target-resize').textfill({
    maxFontPixels: 36,
    changeLineHeight:false
  })

  $grid.packery({
    itemSelector: '.grid-blog',
    gutter: 20,

  })
});

Body:
It's difficult to answer your question without the code that make the http calls in order to load your content. But,

1) you may have an error, and still have contents to be loaded, in that case your loader will disappear even if contents are still loading.

2) You should have something that tel your site what you have to load.
an array of url, or anything, you can maybe use this to hide your loader when all contents has been loaded.

3) You should have somewhere a function that make httpcalls to get your content. This function should have a callback. In this callback, you should be able to catch an error, and then hide your loader.

I cannot give you more informations with the amount of code you show in your exemple.

edit : after looking at your code, you may try to do :

// Function called once the elements are retrieved
function(new_elts) {
    if(!new_elts) {
        $('loading').fadeOut();
        return;
    }
...
}

I don't think this is the right solution, your plugin should have a built-in function to stop calling new pages, but since I don't see the function that make the http call, or any array/iterator of URLs, it's difficult top help you.

you should check this demo to : https://codepen.io/desandro/pen/rwwoGe


问:
delete table view cell from Firebase
I have a chat app. A user can choose another user in the app to chat with. Once a user sends a message to another user, their appended messages is displayed in a table view controller and when you click on the table view cell you are segued into a detailed controller.

```<code>  override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
        let convoRef = FIRDatabase.database().reference().child("messages").child(convoId!)
        let itemRef = rootRef.child("messages").child(convoId!).childByAutoId() // 1
        let messageItem = [ // 2
            "senderId": senderId!,
            "ReceiverId": senderDisplayName!,
            "text": text!,
            "timestamp": NSDate().timeIntervalSince1970,
            "convoId": convoId!
            ] as [String : Any]

        itemRef.setValue(messageItem) // 3

        JSQSystemSoundPlayer.jsq_playMessageSentSound() // 4

        finishSendingMessage() // 5
        isTyping = false
    }
</code>```

So only the two users chatting can view the messages. But I want one user to be able to delete the table view cell in their app (the messages) but when they do that it deletes in Firebase and that means it deletes in the other user's app too but I want it to only delete in the user that deleted the message. Here is how the messages are appended to be displayed in the tableview controller

```<code>  func loadData()
    {

        FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

            if let postsDictionary = snapshot .value as? [String: AnyObject] {

                for post in postsDictionary {
                    let messages = post.value as! [String: AnyObject]
                    for (id, value) in messages {
                        let info = value as! [String: AnyObject]

                        let convoId = info["convoId"]
                        let toId = info["ReceiverId"] as! String!
                        let fromId = info["senderId"] as! String!

                        if (toId == self.loggedInUserUid  || fromId == self.loggedInUserUid) {

        let ref = FIRDatabase.database().reference().child("messages").child(convoId as! String)
        ref.observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let message = Message(dictionary: dictionary)

                if let receiver = message.convoId {
                    self.messagesDictionary[receiver] = message

                    self.messages = Array(self.messagesDictionary.values)
                    print(self.messages)
                    self.messages.sort(by: { (message1, message2) -> Bool in

                        return (message1.timestamp?.int32Value)! > (message2.timestamp?.int32Value)!

                    })
                }

                //this will crash because of background thread, so lets call this on dispatch_async main thread
                DispatchQueue.main.async(execute: {
                    self.MessageTableView.reloadData()
                })
            }

        }, withCancel: nil)}
                    }

                }}})

    }
</code>```

答:
If an update is made to a Firebase Realtime Database node, then any user reading on that node would see the same value ( if the security rules allow the user to read that node ). So, to answer your question - you can't really make user specific updates to a database path.

Having said that, in your case, you can do one of the following :-

You can delete what you're trying to delete on the client side, so that it won't be visible any longer. However, that won't delete the data in the database, and you would see it again the next time you download from the same path.

You can have separate conversation paths for both the users, and store the same messages in both these locations instead of a common one. In this method, you'd be duplicating data. But if you want to make user-specific changes, then this would more than do it for you.

Title: delete table view cell from Firebase

Body:
I have a chat app. A user can choose another user in the app to chat with. Once a user sends a message to another user, their appended messages is displayed in a table view controller and when you click on the table view cell you are segued into a detailed controller.

  override func didPressSend(_ button: UIButton!, withMessageText text: String!, senderId: String!, senderDisplayName: String!, date: Date!) {
        let convoRef = FIRDatabase.database().reference().child("messages").child(convoId!)
        let itemRef = rootRef.child("messages").child(convoId!).childByAutoId() // 1
        let messageItem = [ // 2
            "senderId": senderId!,
            "ReceiverId": senderDisplayName!,
            "text": text!,
            "timestamp": NSDate().timeIntervalSince1970,
            "convoId": convoId!
            ] as [String : Any]

        itemRef.setValue(messageItem) // 3

        JSQSystemSoundPlayer.jsq_playMessageSentSound() // 4

        finishSendingMessage() // 5
        isTyping = false
    }

So only the two users chatting can view the messages. But I want one user to be able to delete the table view cell in their app (the messages) but when they do that it deletes in Firebase and that means it deletes in the other user's app too but I want it to only delete in the user that deleted the message. Here is how the messages are appended to be displayed in the tableview controller

  func loadData()
    {

        FIRDatabase.database().reference().child("messages").observeSingleEvent(of: .value, with: { (snapshot:FIRDataSnapshot) in

            if let postsDictionary = snapshot .value as? [String: AnyObject] {

                for post in postsDictionary {
                    let messages = post.value as! [String: AnyObject]
                    for (id, value) in messages {
                        let info = value as! [String: AnyObject]

                        let convoId = info["convoId"]
                        let toId = info["ReceiverId"] as! String!
                        let fromId = info["senderId"] as! String!

                        if (toId == self.loggedInUserUid  || fromId == self.loggedInUserUid) {

        let ref = FIRDatabase.database().reference().child("messages").child(convoId as! String)
        ref.observe(.childAdded, with: { (snapshot) in

            if let dictionary = snapshot.value as? [String: AnyObject] {
                let message = Message(dictionary: dictionary)

                if let receiver = message.convoId {
                    self.messagesDictionary[receiver] = message

                    self.messages = Array(self.messagesDictionary.values)
                    print(self.messages)
                    self.messages.sort(by: { (message1, message2) -> Bool in

                        return (message1.timestamp?.int32Value)! > (message2.timestamp?.int32Value)!

                    })
                }

                //this will crash because of background thread, so lets call this on dispatch_async main thread
                DispatchQueue.main.async(execute: {
                    self.MessageTableView.reloadData()
                })
            }

        }, withCancel: nil)}
                    }

                }}})

    }


问:
What is the difference between the predict and predict_on_batch methods of a Keras model?
According to the keras documentation:

```<code>predict_on_batch(self, x)
Returns predictions for a single batch of samples.
</code>```

However, there does not seem to be any difference with the standard predict method when called on a batch, whether it being with one or multiple elements.

```<code>model.predict_on_batch(np.zeros((n, d_in)))
</code>```

is the same as

```<code>model.predict(np.zeros((n, d_in)))
</code>```

(a numpy.ndarray of shape (n, d_out)

答:
The difference lies in when you pass as x data that is larger than one batch.

predict will go through all the data, batch by batch, predicting labels.
It thus internally does the splitting in batches and feeding one batch at a time.

predict_on_batch, on the other hand, assumes that the data you pass in is exactly one batch and thus feeds it to the network. It won't try to split it (which, depending on your setup, might prove problematic for your GPU memory if the array is very big)

Body:
According to the keras documentation:

predict_on_batch(self, x)
Returns predictions for a single batch of samples.

However, there does not seem to be any difference with the standard predict method when called on a batch, whether it being with one or multiple elements.

model.predict_on_batch(np.zeros((n, d_in)))

is the same as

model.predict(np.zeros((n, d_in)))

(a numpy.ndarray of shape (n, d_out)


问:
VS 2008, deploying application with resource folder
I am using Visual Studio 2008 on a C# project. My programs requires around 300 data files (txt, dbf and csv mostly). I use a post build command line to copy those files into the output directory (so far so good).

```<code>MKDIR $(ProjectDir)$(OutputPath)system
XCOPY $(ProjectDir)system $(ProjectDir)$(OutputPath)system /S /Y
</code>```

I also have a deployment project to facilitate the program installation on my users' computers. My problem is that I cannot find a way to make the installer copy the "system" directory from my project output directory into the installation directory.

I have tryed the following:

to script (postbuild event) the directory copy from the program project to the deployment output like this (working):

```<code>MKDIR "$(ProjectDir)$(Configuration)\system"
XCOPY "$(ProjectDir)..\Track\bin\x64\$(Configuration)\system" "$(ProjectDir)$(Configuration)\system" /S /Y
</code>```

to script the directory copy from the deployment programm execution folder to the installation directory. Something like this:

```<code>MKDIR "$(InstallationDir))\system" XCOPY "$(DeploymentAppDirectory)\system" "$(IstallationDir)\system" /S /Y
</code>```

But I cannot figure how to make the second point.

I am really stuck now, an hint would much appreciated.

答: Try move your "system" dir to solution level instead project level and use $(SolutionDir)system in both post build events.

Body:
I am using Visual Studio 2008 on a C# project. My programs requires around 300 data files (txt, dbf and csv mostly). I use a post build command line to copy those files into the output directory (so far so good).

MKDIR $(ProjectDir)$(OutputPath)system
XCOPY $(ProjectDir)system $(ProjectDir)$(OutputPath)system /S /Y

I also have a deployment project to facilitate the program installation on my users' computers. My problem is that I cannot find a way to make the installer copy the "system" directory from my project output directory into the installation directory.

I have tryed the following:

to script (postbuild event) the directory copy from the program project to the deployment output like this (working):

MKDIR "$(ProjectDir)$(Configuration)\system"
XCOPY "$(ProjectDir)..\Track\bin\x64\$(Configuration)\system" "$(ProjectDir)$(Configuration)\system" /S /Y

to script the directory copy from the deployment programm execution folder to the installation directory. Something like this:

MKDIR "$(InstallationDir))\system" XCOPY "$(DeploymentAppDirectory)\system" "$(IstallationDir)\system" /S /Y

But I cannot figure how to make the second point.

I am really stuck now, an hint would much appreciated.


问:
Search-friendly way to store checkbox values in MySQL?
What is a search-friendly way to store checkbox values in the database?

Currently, checkboxes are processed as an array and values are separated by a ";"

As such:

```<code><input type="checkbox" name="frequency[]" value="Daily"/> Daily
<input type="checkbox" name="frequency[]" value="Weekly"/> Weekly
<input type="checkbox" name="frequency[]" value="Monthly"/> Monthly
</code>```

The PHP backend runs implode(';', $frequency) and adds the string to the database.

This works fine but it's a nightmare when it comes to searching.

Is there a better way to approach this?

答:
It seems to me that if stire attribute powers of 2 to each value, and store their sum when seaching for example to see if one of several options are set doens't allow to use index.
If we apply function to the field, indexes won't be able to be used.</p>

Body:
What is a search-friendly way to store checkbox values in the database?

Currently, checkboxes are processed as an array and values are separated by a ";"

As such:

<input type="checkbox" name="frequency[]" value="Daily"/> Daily
<input type="checkbox" name="frequency[]" value="Weekly"/> Weekly
<input type="checkbox" name="frequency[]" value="Monthly"/> Monthly

The PHP backend runs implode(';', $frequency) and adds the string to the database.

This works fine but it's a nightmare when it comes to searching.

Is there a better way to approach this?


问:
Change Map language dynamically in angular2
I am using AgmCoreModule to load google map.
Is it possible to change map language dynamically when language is selected?

I am able to set default language on load of map using code below

```<code>@NgModule({
  imports: [
    AgmCoreModule.forRoot({
      libraries: ["places"],
      language: 'de'
    }),
    ...
    ]
})
</code>```

But what I actually needed is to change language of map on language selected from dropdown.
OR
How do I set language in MapsAPILoader?

```<code>this._mapsAPILoader.load().then(() => {
...
});
</code>```

Thanks.

答:
Try This:

```<code>imports: [
      BrowserModule,
      AgmCoreModule.forRoot({
          apiKey: 'yourmapapikey',
          language: 'iw',
      })
  ],
</code>```

iw - For Hebrew,
check here for your language.

Body:
I am using AgmCoreModule to load google map.
Is it possible to change map language dynamically when language is selected?

I am able to set default language on load of map using code below

@NgModule({
  imports: [
    AgmCoreModule.forRoot({
      libraries: ["places"],
      language: 'de'
    }),
    ...
    ]
})

But what I actually needed is to change language of map on language selected from dropdown.
OR
How do I set language in MapsAPILoader?

this._mapsAPILoader.load().then(() => {
...
});

Thanks.

Body:
Try This:

imports: [
      BrowserModule,
      AgmCoreModule.forRoot({
          apiKey: 'yourmapapikey',
          language: 'iw',
      })
  ],

iw - For Hebrew,
check here for your language.


答:
```<code>stuff = ['magical unicorns',19,'hello',98.98,'world']

string = []
num = []

for i in stuff:
    if isinstance(i,str):
       string.append(i)
    if isinstance(i,int):
       num.append(i)

print (string)
print (num)
</code>```

Title: Basic Python looping and appending


问:
Inline if-else with conditional operator not working React
I've been struggeling with this basic stuff for a while now, but I cant seem to get it to work.

I'm getting data from our backend and if there're any deliveries objects it will be displayed with this:

```<code><Expandable>
  <ObjectDisplay
    key={id}
    parentDocumentId={id}
    schema={schema[this.props.schema.collectionName]}
    value={this.props.collection.documents[id]}
  />
</Expandable>
</code>```

But if there is no deliveries I'd like to display a message like there's no deliveries. I can use .length and !deliveries (I get that), but it seems like my conditional isn't working:

```<code>render() {
  console.log(this.props.collection.ids.length) //Getting how many deliveries there are with their id
  return (
    <div>//Struggling with this:

      {!this.props.collection.ids && this.props.collection.ids.length < 1
        ? <p>No deliviers</p>
        : <div className="box">
            {this.props.collection.ids
              .filter(
                id =>
                  // note: this is only passed when in top level of document
                  this.props.collection.documents[id][
                    this.props.schema.foreignKey
                  ] === this.props.parentDocumentId
              )
              .map(id => {
                return (
                  <Expandable>
                    <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                    />
                  </Expandable>
                )
              })}
          </div>}
    </div>
  )
}
</code>```

I bet my problem is super basic, but I just can't get it to work.. Help is much appreciated!!

答: Change your && to ||. You want to render "no delivers" if you have no ids (first test) OR if your ids.length is < 1</p>

Body:
I've been struggeling with this basic stuff for a while now, but I cant seem to get it to work.

I'm getting data from our backend and if there're any deliveries objects it will be displayed with this:

<Expandable>
  <ObjectDisplay
    key={id}
    parentDocumentId={id}
    schema={schema[this.props.schema.collectionName]}
    value={this.props.collection.documents[id]}
  />
</Expandable>

But if there is no deliveries I'd like to display a message like there's no deliveries. I can use .length and !deliveries (I get that), but it seems like my conditional isn't working:

render() {
  console.log(this.props.collection.ids.length) //Getting how many deliveries there are with their id
  return (

//Struggling with this:

      {!this.props.collection.ids && this.props.collection.ids.length < 1
        ?
No deliviers

        :

            {this.props.collection.ids
              .filter(
                id =>
                  // note: this is only passed when in top level of document
                  this.props.collection.documents[id][
                    this.props.schema.foreignKey
                  ] === this.props.parentDocumentId
              )
              .map(id => {
                return (
                  <Expandable>
                    <ObjectDisplay
                      key={id}
                      parentDocumentId={id}
                      schema={schema[this.props.schema.collectionName]}
                      value={this.props.collection.documents[id]}
                    />
                  </Expandable>
                )
              })}

}

  )
}

I bet my problem is super basic, but I just can't get it to work.. Help is much appreciated!!