问:
Kafka Streams Application died with "StreamsException: Could not create internal topics."
I am evaluating Kafka streams and made a simple application and left it running overnight. I ran it on 2 instances with 1 stream thread per instance. I have a 2 broker Kafka cluster.

The StreamsConfig :

```<code>private Map<String, Object> settings() {

    Map<String, Object> settings = new HashMap<>();
    settings.put(StreamsConfig.APPLICATION_ID_CONFIG, "fare_tracker");
    settings.put(StreamsConfig.APPLICATION_SERVER_CONFIG, serverAddress + ":" + serverPort);
    settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka1:9092,kafka2:9092");
    settings.put(StreamsConfig.STATE_DIR_CONFIG, directoryName);
    settings.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 1);
    settings.put(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, AvroTimeStampExtractor.class);
    settings.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 2);
    settings.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, 2);

    settings.put("schema.registry.url", "http://zookeeper1:8081");

    settings.put(StreamsConfig.consumerPrefix(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG), "earliest");
    settings.put(StreamsConfig.producerPrefix(ProducerConfig.COMPRESSION_TYPE_CONFIG), "snappy");
    settings.put(StreamsConfig.producerPrefix(ProducerConfig.RETRIES_CONFIG), 3);
    settings.put(StreamsConfig.producerPrefix(ProducerConfig.RETRY_BACKOFF_MS_CONFIG), 500);

    return settings;
}
</code>```

It died roughly 12 hours after starting, with below stack-trace :

```<code>Exception in thread "StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Could not create internal topics.
        at org.apache.kafka.streams.processor.internals.InternalTopicManager.makeReady(InternalTopicManager.java:81)
        at org.apache.kafka.streams.processor.internals.StreamPartitionAssignor.prepareTopic(StreamPartitionAssignor.java:628)
        at org.apache.kafka.streams.processor.internals.StreamPartitionAssignor.assign(StreamPartitionAssignor.java:382)
        at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.performAssignment(ConsumerCoordinator.java:343)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.onJoinLeader(AbstractCoordinator.java:501)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.access$1100(AbstractCoordinator.java:89)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$JoinGroupResponseHandler.handle(AbstractCoordinator.java:451)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$JoinGroupResponseHandler.handle(AbstractCoordinator.java:433)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$CoordinatorResponseHandler.onSuccess(AbstractCoordinator.java:784)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$CoordinatorResponseHandler.onSuccess(AbstractCoordinator.java:765)
        at org.apache.kafka.clients.consumer.internals.RequestFuture$1.onSuccess(RequestFuture.java:186)
        at org.apache.kafka.clients.consumer.internals.RequestFuture.fireSuccess(RequestFuture.java:149)
        at org.apache.kafka.clients.consumer.internals.RequestFuture.complete(RequestFuture.java:116)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient$RequestFutureCompletionHandler.fireCompletion(ConsumerNetworkClient.java:493)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.firePendingCompletedRequests(ConsumerNetworkClient.java:322)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:253)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:172)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.joinGroupIfNeeded(AbstractCoordinator.java:347)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureActiveGroup(AbstractCoordinator.java:303)
        at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:290)
        at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:1029)
        at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:995)
        at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:592)
        at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:361)
</code>```

I found some relevant WARN and ERROR logs.

```<code>{
  "@timestamp": "2017-06-07T05:44:26.996+05:30",
  "@version": 1,
  "message": "Got error produce response with correlation id 198191 on topic-partition fare_tracker-small_window-changelog-0, retrying (2 attempts left). Error: NETWORK_EXCEPTION",
  "logger_name": "org.apache.kafka.clients.producer.internals.Sender",
  "thread_name": "kafka-producer-network-thread | fare_tracker-9e0a04f4-c1cc-4b61-8ca5-8bf25f18549f-StreamThread-1-producer",
  "level": "WARN",
  "level_value": 30000
}
</code>```

^This seems like a generic network issue, I have the producer configured with 3 retries.

Application1 died with the following logs:

```<code>{
  "@timestamp": "2017-06-07T06:20:35.122+05:30",
  "@version": 1,
  "message": "stream-thread [StreamThread-1] Failed to commit StreamTask 2_61 state: ",
  "logger_name": "org.apache.kafka.streams.processor.internals.StreamThread",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000,
  "stack_trace": org.apache.kafka.clients.consumer.CommitFailedException: Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured max.poll.interval.ms, which typically implies that the poll loop is spending too much time message processing. You can address this either by increasing the session timeout or by reducing the maximum size of batches returned in poll() with max.poll.records.
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.sendOffsetCommitRequest(ConsumerCoordinator.java:702)
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.commitOffsetsSync(ConsumerCoordinator.java:581)
    at org.apache.kafka.clients.consumer.KafkaConsumer.commitSync(KafkaConsumer.java:1124)
    at org.apache.kafka.streams.processor.internals.StreamTask.commitOffsets(StreamTask.java:296)
    at org.apache.kafka.streams.processor.internals.StreamTask$1.run(StreamTask.java:79)
    at org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:188)
    at org.apache.kafka.streams.processor.internals.StreamTask.commit(StreamTask.java:280)
    at org.apache.kafka.streams.processor.internals.StreamThread.commitOne(StreamThread.java:807)
    at org.apache.kafka.streams.processor.internals.StreamThread.commitAll(StreamThread.java:794)
    at org.apache.kafka.streams.processor.internals.StreamThread.maybeCommit(StreamThread.java:769)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:647)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:361)
}

{
  "@timestamp": "2017-06-07T06:20:35.236+05:30",
  "@version": 1,
  "message": "Bootstrap broker kafka2:9092 disconnected",
  "logger_name": "org.apache.kafka.clients.NetworkClient",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}
{
  "@timestamp": "2017-06-07T06:20:36.100+05:30",
  "@version": 1,
  "message": "Could not create internal topics: Found only 1 brokers,  but replication factor is 2. Decrease replication factor for internal topics via StreamsConfig parameter \"replication.factor\" or add more brokers to your cluster. Retry #4",
  "logger_name": "org.apache.kafka.streams.processor.internals.InternalTopicManager",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}
{
  "@timestamp": "2017-06-07T06:20:36.914+05:30",
  "@version": 1,
  "message": "stream-thread [StreamThread-1] Unexpected state transition from PARTITIONS_REVOKED to NOT_RUNNING.",
  "logger_name": "org.apache.kafka.streams.processor.internals.StreamThread",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}
</code>```

Application 2 died with the following logs:

```<code>{
  "@timestamp": "2017-06-07T06:20:06.254+05:30",
  "@version": 1,
  "message": "Could not create internal topics: Found only 1 brokers,  but replication factor is 2. Decrease replication factor for internal topics via StreamsConfig parameter \"replication.factor\" or add more brokers to your cluster. Retry #4",
  "logger_name": "org.apache.kafka.streams.processor.internals.InternalTopicManager",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}
{
  "@timestamp": "2017-06-07T06:20:07.041+05:30",
  "@version": 1,
  "message": "stream-thread [StreamThread-1] Unexpected state transition from PARTITIONS_REVOKED to NOT_RUNNING.",
  "logger_name": "org.apache.kafka.streams.processor.internals.StreamThread",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}
</code>```

I checked my other applications, and although the are running fine, I saw the following log multiple times at around the same time as above.

```<code>    {
      "@timestamp": "2017-06-07T06:10:34.962+05:30",
      "@version": 1,
      "message": "Publishing to kafka failed ",
      "thread_name": "kafka-producer-network-thread | producer-1",
      "level": "ERROR",
      "level_value": 40000,
      "stack_trace": org.springframework.kafka.core.KafkaProducerException: Failed to send; nested exception is org.apache.kafka.common.errors.TimeoutException: Expiring 30 record(s) for fareAlertDispatch-36 due to 424387 ms has passed since batch creation plus linger time
    at org.springframework.kafka.core.KafkaTemplate$1.onCompletion(KafkaTemplate.java:255)
    at org.apache.kafka.clients.producer.internals.RecordBatch.done(RecordBatch.java:109)
    at org.apache.kafka.clients.producer.internals.RecordBatch.maybeExpire(RecordBatch.java:160)
    at org.apache.kafka.clients.producer.internals.RecordAccumulator.abortExpiredBatches(RecordAccumulator.java:245)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:212)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:135)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.kafka.common.errors.TimeoutException: Expiring 30 record(s) for fareAlertDispatch-36 due to 424387 ms has passed since batch creation plus linger time

org.apache.kafka.common.errors.TimeoutException: Expiring 30 record(s) for fareAlertDispatch-36 due to 424387 ms has passed since batch creation plus linger time
    }
</code>```

答:
You said you have 2 Kafka brokers, but one of the error messages includes the following information:

```<code>Could not create internal topics: Found only 1 brokers, but replication factor is 2.
</code>```

It looks like you have network connectivity issues between your application(s) and the Kafka brokers (and perhaps also between the Kafka brokers themselves). If such a network issue persists for a longer period of time, eventually applications that try to communicate with the Kafka brokers will fail sooner or later (depending on their settings).

Body:
I am evaluating Kafka streams and made a simple application and left it running overnight. I ran it on 2 instances with 1 stream thread per instance. I have a 2 broker Kafka cluster.

The StreamsConfig :

private Map<String, Object> settings() {

    Map<String, Object> settings = new HashMap<>();
    settings.put(StreamsConfig.APPLICATION_ID_CONFIG, "fare_tracker");
    settings.put(StreamsConfig.APPLICATION_SERVER_CONFIG, serverAddress + ":" + serverPort);
    settings.put(StreamsConfig.BOOTSTRAP_SERVERS_CONFIG, "kafka1:9092,kafka2:9092");
    settings.put(StreamsConfig.STATE_DIR_CONFIG, directoryName);
    settings.put(StreamsConfig.NUM_STREAM_THREADS_CONFIG, 1);
    settings.put(StreamsConfig.TIMESTAMP_EXTRACTOR_CLASS_CONFIG, AvroTimeStampExtractor.class);
    settings.put(StreamsConfig.REPLICATION_FACTOR_CONFIG, 2);
    settings.put(StreamsConfig.NUM_STANDBY_REPLICAS_CONFIG, 2);

    settings.put("schema.registry.url", "http://zookeeper1:8081");

    settings.put(StreamsConfig.consumerPrefix(ConsumerConfig.AUTO_OFFSET_RESET_CONFIG), "earliest");
    settings.put(StreamsConfig.producerPrefix(ProducerConfig.COMPRESSION_TYPE_CONFIG), "snappy");
    settings.put(StreamsConfig.producerPrefix(ProducerConfig.RETRIES_CONFIG), 3);
    settings.put(StreamsConfig.producerPrefix(ProducerConfig.RETRY_BACKOFF_MS_CONFIG), 500);

    return settings;
}

It died roughly 12 hours after starting, with below stack-trace :

Exception in thread "StreamThread-1" org.apache.kafka.streams.errors.StreamsException: Could not create internal topics.
        at org.apache.kafka.streams.processor.internals.InternalTopicManager.makeReady(InternalTopicManager.java:81)
        at org.apache.kafka.streams.processor.internals.StreamPartitionAssignor.prepareTopic(StreamPartitionAssignor.java:628)
        at org.apache.kafka.streams.processor.internals.StreamPartitionAssignor.assign(StreamPartitionAssignor.java:382)
        at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.performAssignment(ConsumerCoordinator.java:343)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.onJoinLeader(AbstractCoordinator.java:501)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.access$1100(AbstractCoordinator.java:89)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$JoinGroupResponseHandler.handle(AbstractCoordinator.java:451)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$JoinGroupResponseHandler.handle(AbstractCoordinator.java:433)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$CoordinatorResponseHandler.onSuccess(AbstractCoordinator.java:784)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator$CoordinatorResponseHandler.onSuccess(AbstractCoordinator.java:765)
        at org.apache.kafka.clients.consumer.internals.RequestFuture$1.onSuccess(RequestFuture.java:186)
        at org.apache.kafka.clients.consumer.internals.RequestFuture.fireSuccess(RequestFuture.java:149)
        at org.apache.kafka.clients.consumer.internals.RequestFuture.complete(RequestFuture.java:116)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient$RequestFutureCompletionHandler.fireCompletion(ConsumerNetworkClient.java:493)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.firePendingCompletedRequests(ConsumerNetworkClient.java:322)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:253)
        at org.apache.kafka.clients.consumer.internals.ConsumerNetworkClient.poll(ConsumerNetworkClient.java:172)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.joinGroupIfNeeded(AbstractCoordinator.java:347)
        at org.apache.kafka.clients.consumer.internals.AbstractCoordinator.ensureActiveGroup(AbstractCoordinator.java:303)
        at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.poll(ConsumerCoordinator.java:290)
        at org.apache.kafka.clients.consumer.KafkaConsumer.pollOnce(KafkaConsumer.java:1029)
        at org.apache.kafka.clients.consumer.KafkaConsumer.poll(KafkaConsumer.java:995)
        at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:592)
        at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:361)

I found some relevant WARN and ERROR logs.

{
  "@timestamp": "2017-06-07T05:44:26.996+05:30",
  "@version": 1,
  "message": "Got error produce response with correlation id 198191 on topic-partition fare_tracker-small_window-changelog-0, retrying (2 attempts left). Error: NETWORK_EXCEPTION",
  "logger_name": "org.apache.kafka.clients.producer.internals.Sender",
  "thread_name": "kafka-producer-network-thread | fare_tracker-9e0a04f4-c1cc-4b61-8ca5-8bf25f18549f-StreamThread-1-producer",
  "level": "WARN",
  "level_value": 30000
}

^This seems like a generic network issue, I have the producer configured with 3 retries.

Application1 died with the following logs:

{
  "@timestamp": "2017-06-07T06:20:35.122+05:30",
  "@version": 1,
  "message": "stream-thread [StreamThread-1] Failed to commit StreamTask 2_61 state: ",
  "logger_name": "org.apache.kafka.streams.processor.internals.StreamThread",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000,
  "stack_trace": org.apache.kafka.clients.consumer.CommitFailedException: Commit cannot be completed since the group has already rebalanced and assigned the partitions to another member. This means that the time between subsequent calls to poll() was longer than the configured max.poll.interval.ms, which typically implies that the poll loop is spending too much time message processing. You can address this either by increasing the session timeout or by reducing the maximum size of batches returned in poll() with max.poll.records.
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.sendOffsetCommitRequest(ConsumerCoordinator.java:702)
    at org.apache.kafka.clients.consumer.internals.ConsumerCoordinator.commitOffsetsSync(ConsumerCoordinator.java:581)
    at org.apache.kafka.clients.consumer.KafkaConsumer.commitSync(KafkaConsumer.java:1124)
    at org.apache.kafka.streams.processor.internals.StreamTask.commitOffsets(StreamTask.java:296)
    at org.apache.kafka.streams.processor.internals.StreamTask$1.run(StreamTask.java:79)
    at org.apache.kafka.streams.processor.internals.StreamsMetricsImpl.measureLatencyNs(StreamsMetricsImpl.java:188)
    at org.apache.kafka.streams.processor.internals.StreamTask.commit(StreamTask.java:280)
    at org.apache.kafka.streams.processor.internals.StreamThread.commitOne(StreamThread.java:807)
    at org.apache.kafka.streams.processor.internals.StreamThread.commitAll(StreamThread.java:794)
    at org.apache.kafka.streams.processor.internals.StreamThread.maybeCommit(StreamThread.java:769)
    at org.apache.kafka.streams.processor.internals.StreamThread.runLoop(StreamThread.java:647)
    at org.apache.kafka.streams.processor.internals.StreamThread.run(StreamThread.java:361)
}

{
  "@timestamp": "2017-06-07T06:20:35.236+05:30",
  "@version": 1,
  "message": "Bootstrap broker kafka2:9092 disconnected",
  "logger_name": "org.apache.kafka.clients.NetworkClient",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}
{
  "@timestamp": "2017-06-07T06:20:36.100+05:30",
  "@version": 1,
  "message": "Could not create internal topics: Found only 1 brokers,  but replication factor is 2. Decrease replication factor for internal topics via StreamsConfig parameter \"replication.factor\" or add more brokers to your cluster. Retry #4",
  "logger_name": "org.apache.kafka.streams.processor.internals.InternalTopicManager",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}
{
  "@timestamp": "2017-06-07T06:20:36.914+05:30",
  "@version": 1,
  "message": "stream-thread [StreamThread-1] Unexpected state transition from PARTITIONS_REVOKED to NOT_RUNNING.",
  "logger_name": "org.apache.kafka.streams.processor.internals.StreamThread",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}

Application 2 died with the following logs:

{
  "@timestamp": "2017-06-07T06:20:06.254+05:30",
  "@version": 1,
  "message": "Could not create internal topics: Found only 1 brokers,  but replication factor is 2. Decrease replication factor for internal topics via StreamsConfig parameter \"replication.factor\" or add more brokers to your cluster. Retry #4",
  "logger_name": "org.apache.kafka.streams.processor.internals.InternalTopicManager",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}
{
  "@timestamp": "2017-06-07T06:20:07.041+05:30",
  "@version": 1,
  "message": "stream-thread [StreamThread-1] Unexpected state transition from PARTITIONS_REVOKED to NOT_RUNNING.",
  "logger_name": "org.apache.kafka.streams.processor.internals.StreamThread",
  "thread_name": "StreamThread-1",
  "level": "WARN",
  "level_value": 30000
}

I checked my other applications, and although the are running fine, I saw the following log multiple times at around the same time as above.

    {
      "@timestamp": "2017-06-07T06:10:34.962+05:30",
      "@version": 1,
      "message": "Publishing to kafka failed ",
      "thread_name": "kafka-producer-network-thread | producer-1",
      "level": "ERROR",
      "level_value": 40000,
      "stack_trace": org.springframework.kafka.core.KafkaProducerException: Failed to send; nested exception is org.apache.kafka.common.errors.TimeoutException: Expiring 30 record(s) for fareAlertDispatch-36 due to 424387 ms has passed since batch creation plus linger time
    at org.springframework.kafka.core.KafkaTemplate$1.onCompletion(KafkaTemplate.java:255)
    at org.apache.kafka.clients.producer.internals.RecordBatch.done(RecordBatch.java:109)
    at org.apache.kafka.clients.producer.internals.RecordBatch.maybeExpire(RecordBatch.java:160)
    at org.apache.kafka.clients.producer.internals.RecordAccumulator.abortExpiredBatches(RecordAccumulator.java:245)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:212)
    at org.apache.kafka.clients.producer.internals.Sender.run(Sender.java:135)
    at java.lang.Thread.run(Thread.java:745)
Caused by: org.apache.kafka.common.errors.TimeoutException: Expiring 30 record(s) for fareAlertDispatch-36 due to 424387 ms has passed since batch creation plus linger time

org.apache.kafka.common.errors.TimeoutException: Expiring 30 record(s) for fareAlertDispatch-36 due to 424387 ms has passed since batch creation plus linger time
    }

Body:
You said you have 2 Kafka brokers, but one of the error messages includes the following information:

Could not create internal topics: Found only 1 brokers, but replication factor is 2.

It looks like you have network connectivity issues between your application(s) and the Kafka brokers (and perhaps also between the Kafka brokers themselves). If such a network issue persists for a longer period of time, eventually applications that try to communicate with the Kafka brokers will fail sooner or later (depending on their settings).


来源: stackexchange

问:
How to reload another controller from controller in Angularjs?
Hi i am developing web site in angularjs. I am using ui-routing. I want to reload state after the user login. I have index.html and app.js. Below is my app.js

```<code>var app = angular.module('RoslpApp', ['pascalprecht.translate']);
app.config(function ($stateProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider)
{
    $urlRouterProvider.otherwise('/HomePage');
    $stateProvider
   .state('Login', {
       url: '/Login',
       templateUrl: 'App/Registration/Login.html',
       controller: 'Login'
   });
});

app.controller('RoslpAppController', ['$scope', function ($scope) {
 var cookieloginid = $cookieStore.get('LoginID');
    if (cookieloginid != null) {
        //This will reoload
        var id = document.getElementById('ProfileDropdown');
        id.innerHTML = $scope.ProfileDropdown = ' <ul>' +
            '<li><a href="#/userProfile">User Profile</a></li>' +
            '<li>test1</li>' +
           ' <li onclick="logout(event)">logout</li>' +
        '</ul>';
        $scope.dp == false;
    }
</code>```

Below is my login code.

```<code>  $http.post(url, sub).then(function (response) {
                        setTimeout(function () {
//Trigger or reload RoslpAppController controller
LoginSuccess(response); }, 1000);
                    }, function (error) {
                        setTimeout(function () { HideLoader(); }, 1000);
                        toastr.error($filter('translate')(error.data.msg));
                    });
</code>```

After login success i will get login id and i will store it in cookie. In RoslpAppController controller i want to check if the cookie exists or not on login. May i know how this can be done? Thank you.

答:
You have to transition to a state on getting success response from server after your login POST call.
To transition to a state use - $state.go("<statename>",{params},{reload : true})

If you don't have any state for RoslpAppController then make one.

Edit after OP's comment :

```<code>.state('Roslp', {
    url: '/Roslp',
    templateUrl: 'App/Registration/View.html',
    controller: 'RoslpAppController'
});
</code>```

In the templateUrl give the view that you want to load after login.
Use $state.go("Roslp",{params},{reload : true}) now.

ContentLicense: CC BY-SA 3.0

Body:
Hi i am developing web site in angularjs. I am using ui-routing. I want to reload state after the user login. I have index.html and app.js. Below is my app.js

var app = angular.module('RoslpApp', ['pascalprecht.translate']);
app.config(function ($stateProvider, $urlRouterProvider, $translateProvider, $translatePartialLoaderProvider)
{
    $urlRouterProvider.otherwise('/HomePage');
    $stateProvider
   .state('Login', {
       url: '/Login',
       templateUrl: 'App/Registration/Login.html',
       controller: 'Login'
   });
});

app.controller('RoslpAppController', ['$scope', function ($scope) {
 var cookieloginid = $cookieStore.get('LoginID');
    if (cookieloginid != null) {
        //This will reoload
        var id = document.getElementById('ProfileDropdown');
        id.innerHTML = $scope.ProfileDropdown = '
' +
            '
User Profile
' +
            '
test1
' +
           '
logout
' +
        '
';
        $scope.dp == false;
    }

Below is my login code.

  $http.post(url, sub).then(function (response) {
                        setTimeout(function () {
//Trigger or reload RoslpAppController controller
LoginSuccess(response); }, 1000);
                    }, function (error) {
                        setTimeout(function () { HideLoader(); }, 1000);
                        toastr.error($filter('translate')(error.data.msg));
                    });

After login success i will get login id and i will store it in cookie. In RoslpAppController controller i want to check if the cookie exists or not on login. May i know how this can be done? Thank you.

Body:
You have to transition to a state on getting success response from server after your login POST call.
To transition to a state use - $state.go("<statename>",{params},{reload : true})

If you don't have any state for RoslpAppController then make one.

Edit after OP's comment :

.state('Roslp', {
    url: '/Roslp',
    templateUrl: 'App/Registration/View.html',
    controller: 'RoslpAppController'
});

In the templateUrl give the view that you want to load after login.
Use $state.go("Roslp",{params},{reload : true}) now.


问:
How might I find the largest number contained in a JavaScript array?
I have a simple JavaScript Array object containing a few numbers.

```<code>[267, 306, 108]
</code>```

Is there a function that would find the largest number in this array?

答:
You can try this,</p>
```<code>var arr = [267, 306, 108];
var largestNum = 0;
for(i=0; i<arr.length; i++) {
   if(arr[i] > largest){
     var largest = arr[i];
   }
}
console.log(largest);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I have a simple JavaScript Array object containing a few numbers.

[267, 306, 108]

Is there a function that would find the largest number in this array?

Body:
You can try this,

var arr = [267, 306, 108];
var largestNum = 0;
for(i=0; i<arr.length; i++) {
   if(arr[i] > largest){
     var largest = arr[i];
   }
}
console.log(largest);

ContentLicense: CC BY-SA 4.0


问:
create a calculated measure in MDX that Filters by Date Range
I am trying to create a calculated member to calculate the nb of employees YTD. By YTD  I mean the number of employees  for any given period of time.My fact table has 2 date dimensions StartDate and EndDate. I would like to calculate YTD employees as follows.

Members with StartDate equal to or before current period
AND
EndDate in the current period  OR EndDate is NULL

答:
I had a similar task and end up with the following solution:

```<code>SUM(
    [EmployeeChanging].[EmployeeChanging].[EmployeeChanging].Members,
    IIF(
        [Measures].[EmployeeFrom] <= [Measures].[MaxDay]
        and
        [Measures].[EmployeeTo] >= [Measures].[MinDay],
        [Measures].[EmployeeChangingCount],
        NULL
    )
)
</code>```

There is the dim/fact table in the following format:

EmployeeID + StartDate + EndDate

Create a new dimension EmployeeChanging where the key is EmployeeID + StartDate and a measure group based on the same table with [Measures].[EmployeeFrom],[Measures].[EmployeeTo],[Measures].[EmployeeChangingCount] measures with max, max, count aggregations. Also you have to provide [Measures].[MaxDay] and [Measures].[MinDay] measures based on your Date dimension with max and min aggregations for the same date field. That's it.
Also you may hide your EmployeeChanging dimension as it required only for MDXing.

Body:
I had a similar task and end up with the following solution:

SUM(
    [EmployeeChanging].[EmployeeChanging].[EmployeeChanging].Members,
    IIF(
        [Measures].[EmployeeFrom] <= [Measures].[MaxDay]
        and
        [Measures].[EmployeeTo] >= [Measures].[MinDay],
        [Measures].[EmployeeChangingCount],
        NULL
    )
)

There is the dim/fact table in the following format:

EmployeeID + StartDate + EndDate

Create a new dimension EmployeeChanging where the key is EmployeeID + StartDate and a measure group based on the same table with [Measures].[EmployeeFrom],[Measures].[EmployeeTo],[Measures].[EmployeeChangingCount] measures with max, max, count aggregations. Also you have to provide [Measures].[MaxDay] and [Measures].[MinDay] measures based on your Date dimension with max and min aggregations for the same date field. That's it.
Also you may hide your EmployeeChanging dimension as it required only for MDXing.


问:
Very weird, Android app crashes when ANY picture of a twenty euro note is inserted
I'm working on an app that allows users to donate money to charity and as of right now the buttons for each amount show a picture of the note/coin. What's really weird is that it crashes whenever the image of a twenty euro note is displayed AND there is a background image. No background image it works fine. I've tried screenshotting the picture and using that in case the file was corrupted, using different pictures, trying different formats. It's always a 20 euro note that causes the problem, I can have 5 buttons of ten euro notes and everything works fine. Also the images I have tried for the twenty euro note have all been the same dimensions and size as the other, working buttons.

```<code><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ie.jc.dare3.temp">

<ImageButton
    android:id="@+id/fiftyCent"
    android:layout_width="94dp"
    android:layout_height="94dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/fifty_cent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="16dp"
    app:layout_constraintLeft_toLeftOf="parent" />
<ImageButton
    android:id="@+id/oneEuro"
    android:layout_width="94dp"
    android:layout_height="94dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/one_euro"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="16dp"
    app:layout_constraintRight_toLeftOf="@+id/twoEuro"
    android:layout_marginRight="8dp"
    app:layout_constraintLeft_toRightOf="@+id/fiftyCent"
    android:layout_marginLeft="8dp"
    app:layout_constraintHorizontal_bias="0.564" />
<ImageButton
    android:id="@+id/twoEuro"
    android:layout_width="94dp"
    android:layout_height="94dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/two_euro"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="16dp"
    android:layout_marginRight="16dp"
    app:layout_constraintRight_toRightOf="parent" />

<ImageButton
    android:id="@+id/twentyEuro"
    android:layout_width="171dp"
    android:layout_height="107dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/twenty"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/tenEuro"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent" />
<ImageButton
    android:id="@+id/tenEuro"
    android:layout_width="171dp"
    android:layout_height="107dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/ten_euro"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/fiveEuro"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent" />
<ImageButton
    android:id="@+id/fiveEuro"
    android:layout_width="171dp"
    android:layout_height="107dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/five_euro"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="28dp"
    app:layout_constraintTop_toBottomOf="@+id/oneEuro"
    app:layout_constraintHorizontal_bias="0.502" />
</code>```

答:
I don't have experience with Android, so I wanted to add this as a comment - but I don't have enough reputation, so...

I may be barking up the completely wrong tree, but I noticed that for one attribute in your xml you have:

```<code>app:srcCompat="@drawable/twenty"
</code>```

which differs from all the other tags where it has an underscore and unit, e.g.

```<code> app:srcCompat="@drawable/five_euro"
</code>```

So maybe you just have a typo and reference something that doesn't exist?

Body:
I'm working on an app that allows users to donate money to charity and as of right now the buttons for each amount show a picture of the note/coin. What's really weird is that it crashes whenever the image of a twenty euro note is displayed AND there is a background image. No background image it works fine. I've tried screenshotting the picture and using that in case the file was corrupted, using different pictures, trying different formats. It's always a 20 euro note that causes the problem, I can have 5 buttons of ten euro notes and everything works fine. Also the images I have tried for the twenty euro note have all been the same dimensions and size as the other, working buttons.

<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="ie.jc.dare3.temp">

<ImageButton
    android:id="@+id/fiftyCent"
    android:layout_width="94dp"
    android:layout_height="94dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/fifty_cent"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="16dp"
    android:layout_marginLeft="16dp"
    app:layout_constraintLeft_toLeftOf="parent" />
<ImageButton
    android:id="@+id/oneEuro"
    android:layout_width="94dp"
    android:layout_height="94dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/one_euro"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="16dp"
    app:layout_constraintRight_toLeftOf="@+id/twoEuro"
    android:layout_marginRight="8dp"
    app:layout_constraintLeft_toRightOf="@+id/fiftyCent"
    android:layout_marginLeft="8dp"
    app:layout_constraintHorizontal_bias="0.564" />
<ImageButton
    android:id="@+id/twoEuro"
    android:layout_width="94dp"
    android:layout_height="94dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/two_euro"
    app:layout_constraintTop_toTopOf="parent"
    android:layout_marginTop="16dp"
    android:layout_marginRight="16dp"
    app:layout_constraintRight_toRightOf="parent" />

<ImageButton
    android:id="@+id/twentyEuro"
    android:layout_width="171dp"
    android:layout_height="107dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/twenty"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/tenEuro"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent" />
<ImageButton
    android:id="@+id/tenEuro"
    android:layout_width="171dp"
    android:layout_height="107dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/ten_euro"
    android:layout_marginTop="8dp"
    app:layout_constraintTop_toBottomOf="@+id/fiveEuro"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent" />
<ImageButton
    android:id="@+id/fiveEuro"
    android:layout_width="171dp"
    android:layout_height="107dp"
    android:backgroundTint="@android:color/transparent"
    android:scaleType="fitXY"
    app:srcCompat="@drawable/five_euro"
    android:layout_marginLeft="8dp"
    app:layout_constraintLeft_toLeftOf="parent"
    android:layout_marginRight="8dp"
    app:layout_constraintRight_toRightOf="parent"
    android:layout_marginTop="28dp"
    app:layout_constraintTop_toBottomOf="@+id/oneEuro"
    app:layout_constraintHorizontal_bias="0.502" />

Body:
I don't have experience with Android, so I wanted to add this as a comment - but I don't have enough reputation, so...

I may be barking up the completely wrong tree, but I noticed that for one attribute in your xml you have:

app:srcCompat="@drawable/twenty"

which differs from all the other tags where it has an underscore and unit, e.g.

 app:srcCompat="@drawable/five_euro"

So maybe you just have a typo and reference something that doesn't exist?


问:
Spring Data error generating query from method name
I'm trying to implement a custom method in my Spring Data JPA repository.

I'm using query generation from method name, and I have something like this:

```<code>List<Person> findByFirstNameOrLastName(String key);
</code>```

I specified a single parameter for the method because I have a single search key that could match firstName or lastName, but on application startup I'm getting this application:

```<code>Caused by: org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'personRepository':
        Invocation of init method failed; nested exception is java.util.NoSuchElementException
</code>```

I suppose this error depends on method signature...

So, is there a way to specify a single param for my method using query creation or should I implement custom logic to achieve this?

答:
```<code>List<Person> findByFirstNameOrLastName(String firstName, String lastName);
</code>```

Yes, it's an issue with the method signature. Spring Data expects 2 parameters when the "or" condition is present in a method name. And you need to pass a key value for both parameters.

Alternatively, you could write a @Query over the method like:

```<code>@Query("SELECT p FROM person p WHERE p.lastName=:key OR p.firstName =:key")
List<AccountInformation> findByFirstNameOrLastName(@Param("key") String key);
</code>```

Body:
I'm trying to implement a custom method in my Spring Data JPA repository.

I'm using query generation from method name, and I have something like this:

List<Person> findByFirstNameOrLastName(String key);

I specified a single parameter for the method because I have a single search key that could match firstName or lastName, but on application startup I'm getting this application:

Caused by: org.springframework.beans.factory.BeanCreationException:
    Error creating bean with name 'personRepository':
        Invocation of init method failed; nested exception is java.util.NoSuchElementException

I suppose this error depends on method signature...

So, is there a way to specify a single param for my method using query creation or should I implement custom logic to achieve this?

Body:
List<Person> findByFirstNameOrLastName(String firstName, String lastName);

Yes, it's an issue with the method signature. Spring Data expects 2 parameters when the "or" condition is present in a method name. And you need to pass a key value for both parameters.

Alternatively, you could write a @Query over the method like:

@Query("SELECT p FROM person p WHERE p.lastName=:key OR p.firstName =:key")
List<AccountInformation> findByFirstNameOrLastName(@Param("key") String key);


问:
Unable To Find Registry Path on Local Disk
I would Like to access the registry path given below I tried to run with Cmd but got System cannot find path Specified error.
Please help me locate this path I have also checked inside Regedit but no luck.

PATH

HKU\S-1-5-21-476251715-2947723853-16432991-1000\Software

答:
That is a registry path so you cannot access it with cmd!

The path component that starts with S- is a SID, it identifies an account on your machine. -1000 means it is probably the first account you created.

These keys under the HKU root are only loaded when that particular user is logged in. You can load the key manually by loading that users ntuser.dat file from their profile directory in Regedit but it is easier to just log in as that user.


问:
PHP nested ternary if condition
```<code><?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ($var > 6) ? "gr than 6" : "not gr than 2 or 6";
?>
</code>```

for the above code, it always returns - gr than 6. Can someone please suggest what did I wrong?

答:
The code will be executed front to back.
So first

```<code><?php
($var > 2) ? "gr than 2" : ($var > 6)
?>
</code>```

will result in "gr than 2".

Then the next questionmark will result in gr than 6, because "gr than 2" is equal to true.

Also because of the above it would be good to notice that > 6 and > 2 are both greater than 2, so the whole line is actually quite pointless the way it is written.

The solution would be something like:

```<code><?php
$var = 4;
echo $current = ($var < 2 ? "not gr than 2 or 6" : ($var > 6 ? "gr than 6" : "gr than 2"));
?>
</code>```

* Edit: *

Thank you for the upvotes. When looking again at this I got lost in my own post, because the logic is so complex. So for others reading this:

The logic the OP posted can be simplified to the following:

```<code><?php
echo true ? "first" : false ? "second" : "third";
</code>```

The OP would expect this to result in first.
However, it does result in second because first the first part is being executed, and because that part is true the outcome is "second".

Title: PHP nested ternary if condition

Body:
<?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ($var > 6) ? "gr than 6" : "not gr than 2 or 6";
?>

for the above code, it always returns - gr than 6. Can someone please suggest what did I wrong?

Body:
The code will be executed front to back.
So first

<?php
($var > 2) ? "gr than 2" : ($var > 6)
?>

will result in "gr than 2".

Then the next questionmark will result in gr than 6, because "gr than 2" is equal to true.

Also because of the above it would be good to notice that > 6 and > 2 are both greater than 2, so the whole line is actually quite pointless the way it is written.

The solution would be something like:

<?php
$var = 4;
echo $current = ($var < 2 ? "not gr than 2 or 6" : ($var > 6 ? "gr than 6" : "gr than 2"));
?>

* Edit: *

Thank you for the upvotes. When looking again at this I got lost in my own post, because the logic is so complex. So for others reading this:

The logic the OP posted can be simplified to the following:

<?php
echo true ? "first" : false ? "second" : "third";

The OP would expect this to result in first.
However, it does result in second because first the first part is being executed, and because that part is true the outcome is "second".


问:
How to display only one text box at a time and click to next display next input field
I have three fields and one next button. I have to display each field one by one after clicking on next button. Means I have to display only one field at a time.
For example. First text box displaying with next button after clicked on next button then display a second text box with next button same on third one but this time no next button. It will display submit button. Would you help me out in this?

.steps{
  max-width:500px;
  height:auto;
  margin:0 auto;
  padding:70px 0;
  background:#ffffff;
  border:1px solid #e1e8f2;
  position:relative;
  text-align:center;
}
label
{
  display: block;
}
.field-set
{
  text-align: left;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="steps">
  <p class="form_title">Please Fill The field Bellow</p>
  <form action="#" method="post" autocomplete="off">

    <div class="field-set">
    <label>name</label>
      <input type="text"  id="name" name="name" placeholder="Enter You Name"/>
    </div>

      <div  class="field-set">
      <label>Email</label>
        <input type="email" id="email" name="email" placeholder="Enter You Email"/>
      </div>

      <div  class="field-set">
      <label>mobile</label>
        <input type="text"  id="mob" name="mob" placeholder="Enter Your mobile no"/>
      </div>

      <div  class="field-set">
        <input type="submit" name="next" value="next" id="click_next">
      </div>

  </form>
</div></code>```

答:
Try something like

```<code>var count = $(".field-set").length - 1;
var countshow = 1;
$("#click_next").click(function(e) {
  e.preventDefault()
  $(".field-set").eq((countshow - 1)).hide();
  if (count > countshow) {
    $(".field-set").eq(countshow).show();
    countshow++;
  } else {
    $("form").unbind("submit").submit();
  }
})
</code>```

I've also changed some of your css.

```<code>.field-set {
  text-align: left;
  display: none;
}

.field-set:first-of-type,
.field-set:last-of-type {
  display: block;
}
</code>```

var count = $(".field-set").length - 1;
var countshow = 1;
$("#click_next").click(function(e) {
  e.preventDefault()
  $(".field-set").eq((countshow - 1)).hide();
  if (count > countshow) {
    $(".field-set").eq(countshow).show();
    if ((count - 1) == countshow) {$(this).val("sumbit")}
  } else {
    $("form").unbind("submit").submit();
  }
  countshow++;

})```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.steps {
  max-width: 500px;
  height: auto;
  margin: 0 auto;
  padding: 70px 0;
  background: #ffffff;
  border: 1px solid #e1e8f2;
  position: relative;
  text-align: center;
}

label {
  display: block;
}

.field-set {
  text-align: left;
  display: none;
}

.field-set:first-of-type,
.field-set:last-of-type {
  display: block;
}</code>```

Please Fill The field Bellow

  <form action="#" method="post" autocomplete="off">

      name
      <input type="text" id="name" name="name" placeholder="Enter You Name" />

      Email
      <input type="email" id="email" name="email" placeholder="Enter You Email" />

      mobile
      <input type="text" id="mob" name="mob" placeholder="Enter Your mobile no" />

      <input type="submit" name="next" value="next" id="click_next">

  </form>

```

Body:
I have three fields and one next button. I have to display each field one by one after clicking on next button. Means I have to display only one field at a time.
For example. First text box displaying with next button after clicked on next button then display a second text box with next button same on third one but this time no next button. It will display submit button. Would you help me out in this?

.steps{
  max-width:500px;
  height:auto;
  margin:0 auto;
  padding:70px 0;
  background:#ffffff;
  border:1px solid #e1e8f2;
  position:relative;
  text-align:center;
}
label
{
  display: block;
}
.field-set
{
  text-align: left;
}

Please Fill The field Bellow

  <form action="#" method="post" autocomplete="off">

    name
      <input type="text"  id="name" name="name" placeholder="Enter You Name"/>

      Email
        <input type="email" id="email" name="email" placeholder="Enter You Email"/>

      mobile
        <input type="text"  id="mob" name="mob" placeholder="Enter Your mobile no"/>

        <input type="submit" name="next" value="next" id="click_next">

  </form>

Body:
Try something like

var count = $(".field-set").length - 1;
var countshow = 1;
$("#click_next").click(function(e) {
  e.preventDefault()
  $(".field-set").eq((countshow - 1)).hide();
  if (count > countshow) {
    $(".field-set").eq(countshow).show();
    countshow++;
  } else {
    $("form").unbind("submit").submit();
  }
})

I've also changed some of your css.

.field-set {
  text-align: left;
  display: none;
}

.field-set:first-of-type,
.field-set:last-of-type {
  display: block;
}

var count = $(".field-set").length - 1;
var countshow = 1;
$("#click_next").click(function(e) {
  e.preventDefault()
  $(".field-set").eq((countshow - 1)).hide();
  if (count > countshow) {
    $(".field-set").eq(countshow).show();
    if ((count - 1) == countshow) {$(this).val("sumbit")}
  } else {
    $("form").unbind("submit").submit();
  }
  countshow++;

})

.steps {
  max-width: 500px;
  height: auto;
  margin: 0 auto;
  padding: 70px 0;
  background: #ffffff;
  border: 1px solid #e1e8f2;
  position: relative;
  text-align: center;
}

label {
  display: block;
}

.field-set {
  text-align: left;
  display: none;
}

.field-set:first-of-type,
.field-set:last-of-type {
  display: block;
}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<!--  start Form Steps  -->
<div class="steps">
  <p class="form_title">Please Fill The field Bellow</p>
  <form action="#" method="post" autocomplete="off">

    <div class="field-set">
      <label>name</label>
      <input type="text" id="name" name="name" placeholder="Enter You Name" />
    </div>

    <div class="field-set">
      <label>Email</label>
      <input type="email" id="email" name="email" placeholder="Enter You Email" />
    </div>

    <div class="field-set">
      <label>mobile</label>
      <input type="text" id="mob" name="mob" placeholder="Enter Your mobile no" />
    </div>

    <div class="field-set">
      <input type="submit" name="next" value="next" id="click_next">
    </div>

  </form>

</div>
<!--  End Form Steps  -->


问:
Job DSL script fails on generating job with allure plugin for reports
I have some groovy script for generating jenkins jobs, which worked great.
But after reinstallation of jenkins this script throws exception.

problem part of script is:

```<code>publishers {
            allure(['path-to/reports'])
        }
</code>```

And error is:

```<code>Processing DSL script seed.groovy
ERROR: (JobBuilder.groovy, line 55) No signature of method:
javaposse.jobdsl.dsl.helpers.publisher.PublisherContext.allure() is
applicable for argument types: (java.util.ArrayList) values:
[[PyUIAutotest/reports]]
Possible solutions: mailer(java.lang.String),
use([Ljava.lang.Object;), asType(java.lang.Class)
Finished: FAILURE
</code>```

It fails on wrong signature of method, but it is correct, and i don't know what is wrong.

example of script available on wiki dock. and javadoc for allure() method

Jenkins ver. 2.46.2; Job DSL ver. 1.63, Allure-Jenkins-Plugin ver. 2.15

weird thing in that, i have another server with same plugin versions, and it works fine

答:
Instead of

```<code>publishers {
        allure(['path-to/reports'])
    }
</code>```

use this syntax (which you can also generate using Jenkins pipeline-syntax generator):

```<code>allure([includeProperties: false, jdk: '', properties: [], reportBuildPolicy: 'ALWAYS', results: [[path: 'path-to/reports']]])
</code>```

Body:
I have some groovy script for generating jenkins jobs, which worked great.
But after reinstallation of jenkins this script throws exception.

problem part of script is:

publishers {
            allure(['path-to/reports'])
        }

And error is:

Processing DSL script seed.groovy
ERROR: (JobBuilder.groovy, line 55) No signature of method:
javaposse.jobdsl.dsl.helpers.publisher.PublisherContext.allure() is
applicable for argument types: (java.util.ArrayList) values:
[[PyUIAutotest/reports]]
Possible solutions: mailer(java.lang.String),
use([Ljava.lang.Object;), asType(java.lang.Class)
Finished: FAILURE

It fails on wrong signature of method, but it is correct, and i don't know what is wrong.

example of script available on wiki dock. and javadoc for allure() method

Jenkins ver. 2.46.2; Job DSL ver. 1.63, Allure-Jenkins-Plugin ver. 2.15

weird thing in that, i have another server with same plugin versions, and it works fine

Body:
Instead of

publishers {
        allure(['path-to/reports'])
    }

use this syntax (which you can also generate using Jenkins pipeline-syntax generator):

allure([includeProperties: false, jdk: '', properties: [], reportBuildPolicy: 'ALWAYS', results: [[path: 'path-to/reports']]])


答:
We need to split the last column by that underscore, lexsort it and then use those indices to sort the input array.

Thus, an implementation would be -

```<code>def numpy_app(arr):
    # Extract out the strings on last column split based on '_'.
    # Thus, for given sample we would have the last column would be
    # split further into 3 columns, the middle one being of '_''s.
    a = np.core.defchararray.partition(arr[:,-1],'_')

    # Lexsort it on the last numeric cols (0,2). We need to flip
    # the order of columns to give precedence to the first string
    sidx = np.lexsort(a[:,2::-2].astype(int).T)

    # Index into input array with lex-sorted indices for final o/p
    return arr[sidx]
</code>```

Based on the edits in the question, it seems we want to cut out the string after the underscore. To do so, here's a modified version -

```<code>def numpy_cut_app(arr):
    a = np.core.defchararray.partition(arr[:,-1],'_')
    sidx = np.lexsort(a[:,2::-2].astype(int).T)
    out = arr[sidx]

    # Replace the last column with the first string off the last column's split one
    out[:,-1] = a[sidx,0]
    return out
</code>```

Based on more edits, it seems we want to include the fourth column into lex-sorting and neglect everything after the underscore in the last column. So, a further modified version would be -

```<code>def numpy_cut_col3_app(arr):
    a = np.core.defchararray.partition(arr[:,-1],'_')

    # Lex-sort using first off the split strings from last col(precedence to it)
    # and col-3 of input array
    sidx = np.lexsort([arr[:,3].astype(float), a[:,0]])
    out = arr[sidx]
    out[:,-1] = a[sidx,0]
    return out
</code>```

Sample runs -

```<code>In [567]: arr
Out[567]:
array([['65.0', '30.0', '20.0', '0.0', '9_49'],
       ['2.0', '29.0', '24.0', '0.0', '1_0'],
       ['0.0', '18.0', '4.0', '0.0', '2_0'],
       ['16.0', '9.0', '0.0', '9990.0', '7_203'],
       ['16.0', '9.0', '0.0', '9990.0', '9_5'],
       ['20.0', '23.0', '31.0', '9990.0', '8_158'],
       ['65.0', '30.0', '20.0', '0.0', '9_50']],
      dtype='|S6')

In [568]: numpy_app(arr)
Out[568]:
array([['2.0', '29.0', '24.0', '0.0', '1_0'],
       ['0.0', '18.0', '4.0', '0.0', '2_0'],
       ['16.0', '9.0', '0.0', '9990.0', '7_203'],
       ['20.0', '23.0', '31.0', '9990.0', '8_158'],
       ['16.0', '9.0', '0.0', '9990.0', '9_5'],
       ['65.0', '30.0', '20.0', '0.0', '9_49'],
       ['65.0', '30.0', '20.0', '0.0', '9_50']],
      dtype='|S6')

In [569]: numpy_cut_app(arr)
Out[569]:
array([['2.0', '29.0', '24.0', '0.0', '1'],
       ['0.0', '18.0', '4.0', '0.0', '2'],
       ['16.0', '9.0', '0.0', '9990.0', '7'],
       ['20.0', '23.0', '31.0', '9990.0', '8'],
       ['16.0', '9.0', '0.0', '9990.0', '9'],
       ['65.0', '30.0', '20.0', '0.0', '9'],
       ['65.0', '30.0', '20.0', '0.0', '9']],
      dtype='|S6')
</code>```

Title: How to sort a NumPy array of strings by the last column

Body:
Is there a way to sort the rows of an array by the last element, in this case the cell ids. The cell id is build as follows : "CellID_NumberOfCell

arr =np.array([['65.0','30.0','20.0','0.0','0_0'],
 ['2.0','29.0','24.0','0.0','1_0'],
 ['0.0','18.0','4.0','0.0','2_0'],
 ['16.0','9.0','0.0','9990.0','7_203'],
 ['16.0','9.0','0.0','9990.0','0_203'],
 ['20.0','23.0','31.0','9990.0','8_158'],
 ['65.0','30.0','20.0','0.0','0_10']])

So after sorting it should look like:

arr =np.array([['65.0','30.0','20.0','0.0','0_0'],
 ['65.0','30.0','20.0','0.0','0_10'],
 ['16.0','9.0','0.0','9990.0','0_203'],
 ['2.0','29.0','24.0','0.0','1_0'],
 ['0.0','18.0','4.0','0.0','2_0'],
 ['16.0','9.0','0.0','9990.0','7_203'],
 ['20.0','23.0','31.0','9990.0','8_158']])

EDIT:

Is it also possible to delete the numbers after the underscore after sorting?. So that i just have the ID. Instead of 0_0 just 0.

EDIT2

After sorting the ID, it should also sort after time, so that every ID with 0 for example should also be sorted after time 0,1...9999 etc.

Body:
We need to split the last column by that underscore, lexsort it and then use those indices to sort the input array.

Thus, an implementation would be -

def numpy_app(arr):
    # Extract out the strings on last column split based on '_'.
    # Thus, for given sample we would have the last column would be
    # split further into 3 columns, the middle one being of '_''s.
    a = np.core.defchararray.partition(arr[:,-1],'_')

    # Lexsort it on the last numeric cols (0,2). We need to flip
    # the order of columns to give precedence to the first string
    sidx = np.lexsort(a[:,2::-2].astype(int).T)

    # Index into input array with lex-sorted indices for final o/p
    return arr[sidx]

Based on the edits in the question, it seems we want to cut out the string after the underscore. To do so, here's a modified version -

def numpy_cut_app(arr):
    a = np.core.defchararray.partition(arr[:,-1],'_')
    sidx = np.lexsort(a[:,2::-2].astype(int).T)
    out = arr[sidx]

    # Replace the last column with the first string off the last column's split one
    out[:,-1] = a[sidx,0]
    return out

Based on more edits, it seems we want to include the fourth column into lex-sorting and neglect everything after the underscore in the last column. So, a further modified version would be -

def numpy_cut_col3_app(arr):
    a = np.core.defchararray.partition(arr[:,-1],'_')

    # Lex-sort using first off the split strings from last col(precedence to it)
    # and col-3 of input array
    sidx = np.lexsort([arr[:,3].astype(float), a[:,0]])
    out = arr[sidx]
    out[:,-1] = a[sidx,0]
    return out

Sample runs -

In [567]: arr
Out[567]:
array([['65.0', '30.0', '20.0', '0.0', '9_49'],
       ['2.0', '29.0', '24.0', '0.0', '1_0'],
       ['0.0', '18.0', '4.0', '0.0', '2_0'],
       ['16.0', '9.0', '0.0', '9990.0', '7_203'],
       ['16.0', '9.0', '0.0', '9990.0', '9_5'],
       ['20.0', '23.0', '31.0', '9990.0', '8_158'],
       ['65.0', '30.0', '20.0', '0.0', '9_50']],
      dtype='|S6')

In [568]: numpy_app(arr)
Out[568]:
array([['2.0', '29.0', '24.0', '0.0', '1_0'],
       ['0.0', '18.0', '4.0', '0.0', '2_0'],
       ['16.0', '9.0', '0.0', '9990.0', '7_203'],
       ['20.0', '23.0', '31.0', '9990.0', '8_158'],
       ['16.0', '9.0', '0.0', '9990.0', '9_5'],
       ['65.0', '30.0', '20.0', '0.0', '9_49'],
       ['65.0', '30.0', '20.0', '0.0', '9_50']],
      dtype='|S6')

In [569]: numpy_cut_app(arr)
Out[569]:
array([['2.0', '29.0', '24.0', '0.0', '1'],
       ['0.0', '18.0', '4.0', '0.0', '2'],
       ['16.0', '9.0', '0.0', '9990.0', '7'],
       ['20.0', '23.0', '31.0', '9990.0', '8'],
       ['16.0', '9.0', '0.0', '9990.0', '9'],
       ['65.0', '30.0', '20.0', '0.0', '9'],
       ['65.0', '30.0', '20.0', '0.0', '9']],
      dtype='|S6')


答:
This.</p>

```<code>echo $current = ($var > 2) ? ($var >6)? "gr than 6":"lower than 6" : "lower than 2 or 6";
</code>```

Title: PHP nested ternary if condition

Body:
This.

echo $current = ($var > 2) ? ($var >6)? "gr than 6":"lower than 6" : "lower than 2 or 6";


问:
How to get only text in Custom Material Spinner with Image and Text
I have a Material Spinner which displays an image and text, but i want to retrieve just the text in OnItemSelected. But it is returning null.

My Adapter Class

```<code>   public class SpinnerCustomAdapter extends BaseAdapter {
    Context context;
    int cat_pics[];
    ArrayList<String> categoryNames;
    LayoutInflater inflter;

    public SpinnerCustomAdapter(Context applicationContext, int[] cat_pics, ArrayList<String> categoryNames) {
        this.context = applicationContext;
        this.cat_pics = cat_pics;
        this.categoryNames = categoryNames;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return cat_pics.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.custom_spinner_items, null);
        ImageView icon = (ImageView) view.findViewById(R.id.imageView);
        TextView names = (TextView) view.findViewById(R.id.textView);
        icon.setImageResource(cat_pics[i]);
        names.setText(categoryNames.get(i));
        return view;
    }
}
</code>```

Setting the Adapter in Main Activity

```<code> customAdapter=newSpinnerCustomAdapter(getApplicationContext(),cat_pics,allCatNames);
    spCategories.setAdapter(customAdapter);
    spCategories.setOnItemSelectedListener(this);
</code>```

onItemSelected

```<code>@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(parent.getContext(), "Selected Item : " + customAdapter.getItem(position) ,
                Toast.LENGTH_LONG).show();
    }
</code>```

答:
Try the following:

```<code>spinner.getSelectedItem().toString()
</code>```

(Or)
Inside OnItemSelectedListener:

```<code>spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Log.d("SeletedItem",adapterView.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });
</code>```

Body:
I have a Material Spinner which displays an image and text, but i want to retrieve just the text in OnItemSelected. But it is returning null.

My Adapter Class

   public class SpinnerCustomAdapter extends BaseAdapter {
    Context context;
    int cat_pics[];
    ArrayList<String> categoryNames;
    LayoutInflater inflter;

    public SpinnerCustomAdapter(Context applicationContext, int[] cat_pics, ArrayList<String> categoryNames) {
        this.context = applicationContext;
        this.cat_pics = cat_pics;
        this.categoryNames = categoryNames;
        inflter = (LayoutInflater.from(applicationContext));
    }

    @Override
    public int getCount() {
        return cat_pics.length;
    }

    @Override
    public Object getItem(int i) {
        return null;
    }

    @Override
    public long getItemId(int i) {
        return 0;
    }

    @Override
    public View getView(int i, View view, ViewGroup viewGroup) {
        view = inflter.inflate(R.layout.custom_spinner_items, null);
        ImageView icon = (ImageView) view.findViewById(R.id.imageView);
        TextView names = (TextView) view.findViewById(R.id.textView);
        icon.setImageResource(cat_pics[i]);
        names.setText(categoryNames.get(i));
        return view;
    }
}

Setting the Adapter in Main Activity

 customAdapter=newSpinnerCustomAdapter(getApplicationContext(),cat_pics,allCatNames);
    spCategories.setAdapter(customAdapter);
    spCategories.setOnItemSelectedListener(this);

onItemSelected

@Override
    public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {

        Toast.makeText(parent.getContext(), "Selected Item : " + customAdapter.getItem(position) ,
                Toast.LENGTH_LONG).show();
    }

Body:
Try the following:

spinner.getSelectedItem().toString()

(Or)
Inside OnItemSelectedListener:

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
                Log.d("SeletedItem",adapterView.getSelectedItem().toString());
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });


问:
How do I access this deserialized data?
I'm trying to parse some json data using Newtonsoft json.NET.

I can deserialize the data but when I try to use the deserialized data I get the error "'Newtonsoft.Json.Linq.JArray' does not contain a definition for 'leagueName'".

Here is the Json data I want to use.

```<code>[
{
    "queueType": "RANKED_SOLO_5x5",
    "hotStreak": false,
    "wins": 6,
    "veteran": false,
    "losses": 10,
    "playerOrTeamId": "39257940",
    "tier": "SILVER",
    "playerOrTeamName": "Kristmas Tree",
    "inactive": false,
    "rank": "V",
    "freshBlood": false,
    "leagueName": "Fizz's Gladiators",
    "leaguePoints": 47
},
{
    "queueType": "RANKED_FLEX_SR",
    "hotStreak": true,
    "wins": 100,
    "veteran": true,
    "losses": 99,
    "playerOrTeamId": "39257940",
    "tier": "SILVER",
    "playerOrTeamName": "Kristmas Tree",
    "inactive": false,
    "rank": "I",
    "freshBlood": false,
    "leagueName": "Xin Zhao's Heralds",
    "leaguePoints": 57
}
]
</code>```

Here is my attempt at printing "hotStreak"

```<code>            var json = GetResponse("https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/39257940?api_key=xxxx-xxxx-xxxx-xxxxxxxx");
            MessageBox.Show(json); // gives me the desired data

            var summonerInfo = JsonConvert.DeserializeObject<dynamic>(json);
            var leagueName = summonerInfo.leagueName;

            MessageBox.Show(leagueName);
</code>```

How do I access the deserialized data?

答:
First, note that this works: but, I don't recommend it:

```<code>var summonerInfo = JsonConvert.DeserializeObject<dynamic>(json);
foreach(var item in summonerInfo)
{
    Console.WriteLine(item.leagueName);
}
</code>```

Instead, what I advise is:

First, define a type that matches the JSON:

```<code>class WhateverThisIs // rename me!
{
    public string QueueType { get; set; }
    public bool HotStreak { get; set; }
    public int Wins { get; set; }
    // ...
    public string LeagueName { get; set; }
    public int LeagueWins { get; set; }
}
</code>```

Now deserialize as that type - in your case, into a list or array (the root object in the JSON is a JSON array ([...]), not a JSON object ({...})):

```<code>var summonerInfo = JsonConvert.DeserializeObject<List<WhateverThisIs>>(json);
foreach(var item in summonerInfo)
{
    Console.WriteLine(item.LeagueName);
}
</code>```

You can do things using dynamic, but it is much more work than simply defining a type.

Title: How do I access this deserialized data?

Body:
I'm trying to parse some json data using Newtonsoft json.NET.

I can deserialize the data but when I try to use the deserialized data I get the error "'Newtonsoft.Json.Linq.JArray' does not contain a definition for 'leagueName'".

Here is the Json data I want to use.

[
{
    "queueType": "RANKED_SOLO_5x5",
    "hotStreak": false,
    "wins": 6,
    "veteran": false,
    "losses": 10,
    "playerOrTeamId": "39257940",
    "tier": "SILVER",
    "playerOrTeamName": "Kristmas Tree",
    "inactive": false,
    "rank": "V",
    "freshBlood": false,
    "leagueName": "Fizz's Gladiators",
    "leaguePoints": 47
},
{
    "queueType": "RANKED_FLEX_SR",
    "hotStreak": true,
    "wins": 100,
    "veteran": true,
    "losses": 99,
    "playerOrTeamId": "39257940",
    "tier": "SILVER",
    "playerOrTeamName": "Kristmas Tree",
    "inactive": false,
    "rank": "I",
    "freshBlood": false,
    "leagueName": "Xin Zhao's Heralds",
    "leaguePoints": 57
}
]

Here is my attempt at printing "hotStreak"

            var json = GetResponse("https://euw1.api.riotgames.com/lol/league/v3/positions/by-summoner/39257940?api_key=xxxx-xxxx-xxxx-xxxxxxxx");
            MessageBox.Show(json); // gives me the desired data

            var summonerInfo = JsonConvert.DeserializeObject<dynamic>(json);
            var leagueName = summonerInfo.leagueName;

            MessageBox.Show(leagueName);

How do I access the deserialized data?

Body:
First, note that this works: but, I don't recommend it:

var summonerInfo = JsonConvert.DeserializeObject<dynamic>(json);
foreach(var item in summonerInfo)
{
    Console.WriteLine(item.leagueName);
}

Instead, what I advise is:

First, define a type that matches the JSON:

class WhateverThisIs // rename me!
{
    public string QueueType { get; set; }
    public bool HotStreak { get; set; }
    public int Wins { get; set; }
    // ...
    public string LeagueName { get; set; }
    public int LeagueWins { get; set; }
}

Now deserialize as that type - in your case, into a list or array (the root object in the JSON is a JSON array ([...]), not a JSON object ({...})):

var summonerInfo = JsonConvert.DeserializeObject<List<WhateverThisIs>>(json);
foreach(var item in summonerInfo)
{
    Console.WriteLine(item.LeagueName);
}

You can do things using dynamic, but it is much more work than simply defining a type.


问:
What's the difference between L1 and L2 caches in web-applications with Hibernate as ORM mechanism?
I just want some general info about standard purpose of using L1 cache and L2 cache.

I'm curious because I'm investigating the system with terracotta as 2nd level cache and I've found that it also has 1st-level cache.

答:
GaryF is not wrong, but is not technically right :-) Anton is more correct on this, but to complement his answer:

First Level Cache: this is a "cache" which stores all the entities known by a specific session. So, if you have 3 transactions inside this session, it'll hold all entities touched by all three transactions. It gets cleared when you close the session or when you perform the "clear" method.

Second Level Cache: this is a "real" cache and is delegated to an external provider, such as Infinispan. In this cache, you have full control over the contents of the cache, meaning that you are able to specify which entries should be evicted, which ones should be retained longer and so on.


问:
Echo only unique values
I've got an XML file that prints out press releases. I want to echo all the years when the press releases have been released, like an archive. Only unique values. The code below prints out all the years. Like "2017,2017,2017,2016,2016,2015,2015,2014" other than "2017,2016,2015,2014,2013".</p>

```<code><?php
$file = "file.xml";
$xml = simplexml_load_file($file);

foreach ($xml->Release as $release) {
   $date = $release['PublishDateUtc']; /* $date is now in format yyyy-mm-ddT06:30:00 */
   $year = substr($date, 0, 4);
   echo $year;
}

?>
</code>```

答:
Make note what dates already printed.</p>

```<code>$printed = [];

foreach ($xml->Releases as $release) {
    $year = date('Y', strtotime($release['PublishDateUtc']));

    if (!isset($printed[$year])) {
        echo $year;
        $printed[$year] = $year;
    }
}
</code>```

Title: Echo only unique values

Body:
I've got an XML file that prints out press releases. I want to echo all the years when the press releases have been released, like an archive. Only unique values. The code below prints out all the years. Like "2017,2017,2017,2016,2016,2015,2015,2014" other than "2017,2016,2015,2014,2013".

<?php
$file = "file.xml";
$xml = simplexml_load_file($file);

foreach ($xml->Release as $release) {
   $date = $release['PublishDateUtc']; /* $date is now in format yyyy-mm-ddT06:30:00 */
   $year = substr($date, 0, 4);
   echo $year;
}

?>

Body:
Make note what dates already printed.

$printed = [];

foreach ($xml->Releases as $release) {
    $year = date('Y', strtotime($release['PublishDateUtc']));

    if (!isset($printed[$year])) {
        echo $year;
        $printed[$year] = $year;
    }
}


问:
Inject data into component in Bootstrap Modal on Angular 4
I'm using the @ng-bootstrap/ng-bootstrap which adds Bootstrap components to Angular. You can inject components into an opened Modal, so the injected component makes up the body/content of the opened modal.

I have a list of Player. When I click a player, I want to open a Modal with the clicked player's data inside of it. I can open a Modal with the injected PlayerComponent like this.

```<code>constructor(
  private modalService: NgbModal
) { }

openPlayerModal() {
  const modalRef = this.modalService.open(PlayerComponent)
}
</code>```

The question is... How do I inject additional data to the component to let it know what player's data to fetch? E.g. I might have an OnInit interface on the PlayerComponent that fetches data from an API based on an ID supplied by the modalService.open() call.

答:
It seems like @ng-angular/ng-angular allow you to touch the component instance after it has been instantiated. So you can then modify the values.

So solution would be:

```<code>constructor(
  private modalService: NgbModal
) { }

openPlayerModal() {
  const modalRef = this.modalService.open(PlayerComponent)
  modalRef.componentInstance.player_id = 1;
}
</code>```

And then make the component use an @Input() decorator on player_id.

```<code>export class PlayerComponent {
  @Input() player_id;
  ...
}
</code>```

Body:
I'm using the @ng-bootstrap/ng-bootstrap which adds Bootstrap components to Angular. You can inject components into an opened Modal, so the injected component makes up the body/content of the opened modal.

I have a list of Player. When I click a player, I want to open a Modal with the clicked player's data inside of it. I can open a Modal with the injected PlayerComponent like this.

constructor(
  private modalService: NgbModal
) { }

openPlayerModal() {
  const modalRef = this.modalService.open(PlayerComponent)
}

The question is... How do I inject additional data to the component to let it know what player's data to fetch? E.g. I might have an OnInit interface on the PlayerComponent that fetches data from an API based on an ID supplied by the modalService.open() call.

Body:
It seems like @ng-angular/ng-angular allow you to touch the component instance after it has been instantiated. So you can then modify the values.

So solution would be:

constructor(
  private modalService: NgbModal
) { }

openPlayerModal() {
  const modalRef = this.modalService.open(PlayerComponent)
  modalRef.componentInstance.player_id = 1;
}

And then make the component use an @Input() decorator on player_id.

export class PlayerComponent {
  @Input() player_id;
  ...
}


问:
SQL - Combine multiple text records to one
I want to combine multiple text records to one.
I have a table with data like this:

```<code>+----+---------+
| id | comment |
+----+---------+
| 1  | Peter   |
| 2  | is      |
| 3  | stupid  |
+----+---------+
</code>```

I want Peter is stupid as output.

Do you have any idea?

I am sorry for my bad SQl knowledge.

答:
Just to be safe, use order by along with group_concat as there is no guarantee that the data will always be returned in same order until you use an order by

Rextester Sample

```<code>select
  group_concat(comment order by id separator ' ')
from table1;
</code>```

Body:
I want to combine multiple text records to one.
I have a table with data like this:

+----+---------+
| id | comment |
+----+---------+
| 1  | Peter   |
| 2  | is      |
| 3  | stupid  |
+----+---------+

I want Peter is stupid as output.

Do you have any idea?

I am sorry for my bad SQl knowledge.

Body:
Just to be safe, use order by along with group_concat as there is no guarantee that the data will always be returned in same order until you use an order by

Rextester Sample

select
  group_concat(comment order by id separator ' ')
from table1;


问:
Highlighting Elasticsearch separates text
I built a auto-completion search with Elasticsearch 5.4 with highlighting the matches.

This is my search query:

```<code>GET statements/_search
    {
      "_source": ["uid","textversions.content"],
      "highlight": {
        "fields": {
          "textversions.content": {}
        }
      },
      "query": {
        "match": {
          "textversions.content": {
            "query": "Informatik",
            "fuzziness": "AUTO"
          }
        }
      }
    }
</code>```

Now, most of the results are highlighted correct. Here is an example:

```<code>  {
    "_index": "statements",
    "_type": "statement",
    "_id": "118",
    "_score": 15.151196,
    "_source": {
      "uid": 118,
      "textversions": [
        {
          "content": "die Nachfrage nach Informatikern auch groß ist"
        }
      ]
    },
    "highlight": {
      "textversions.content": [
        "die Nachfrage nach <em>Informatikern</em> auch groß ist"
      ]
    }
  }
</code>```

But i have some results, where my textversions.content isn't completely in the highlighted version:

```<code>{
    "_index": "statements",
    "_type": "statement",
    "_id": "252",
    "_score": 15.809544,
    "_source": {
      "uid": 252,
      "textversions": [
        {
          "content": "es im Informatikstudium darum geht, sich mit Themen, die für einen Informatiker im späteren Leben absolut notwendig sind, auseinanderzusetzen und nicht mit anderen Fächern"
        }
      ]
    },
    "highlight": {
      "textversions.content": [
        "es im <em>Informatikstudium</em> darum geht, sich mit Themen, die für einen <em>Informatiker</em> im späteren Leben"
      ]
    }
  }
</code>```

or is split into two separate sentences:

```<code>{
    "_index": "statements",
    "_type": "statement",
    "_id": "37",
    "_score": 12.162964,
    "_source": {
      "uid": 37,
      "textversions": [
        {
          "content": "die Abiturzeugnisse über die vorhandenen Informatikkenntnisse sehr wenig aussagen, schließlich haben nur relativ wenige Schulen überhaupt Informatik als ernstzunehmendes Fach"
        }
      ]
    },
    "highlight": {
      "textversions.content": [
        "die Abiturzeugnisse über die vorhandenen <em>Informatikkenntnisse</em> sehr wenig aussagen, schließlich",
        " haben nur relativ wenige Schulen überhaupt <em>Informatik</em> als ernstzunehmendes Fach"
      ]
    }
  }
</code>```

Does anyone know the solution for this misbehavior?

Thanks for your help.

答: I found the answer in the docs: i had to add "number_of_fragments: 0", so highlighting won't break my text into fragments and returns the complete content.</p>

Body:
I built a auto-completion search with Elasticsearch 5.4 with highlighting the matches.

This is my search query:

GET statements/_search
    {
      "_source": ["uid","textversions.content"],
      "highlight": {
        "fields": {
          "textversions.content": {}
        }
      },
      "query": {
        "match": {
          "textversions.content": {
            "query": "Informatik",
            "fuzziness": "AUTO"
          }
        }
      }
    }

Now, most of the results are highlighted correct. Here is an example:

  {
    "_index": "statements",
    "_type": "statement",
    "_id": "118",
    "_score": 15.151196,
    "_source": {
      "uid": 118,
      "textversions": [
        {
          "content": "die Nachfrage nach Informatikern auch groß ist"
        }
      ]
    },
    "highlight": {
      "textversions.content": [
        "die Nachfrage nach Informatikern auch groß ist"
      ]
    }
  }

But i have some results, where my textversions.content isn't completely in the highlighted version:

{
    "_index": "statements",
    "_type": "statement",
    "_id": "252",
    "_score": 15.809544,
    "_source": {
      "uid": 252,
      "textversions": [
        {
          "content": "es im Informatikstudium darum geht, sich mit Themen, die für einen Informatiker im späteren Leben absolut notwendig sind, auseinanderzusetzen und nicht mit anderen Fächern"
        }
      ]
    },
    "highlight": {
      "textversions.content": [
        "es im Informatikstudium darum geht, sich mit Themen, die für einen Informatiker im späteren Leben"
      ]
    }
  }

or is split into two separate sentences:

{
    "_index": "statements",
    "_type": "statement",
    "_id": "37",
    "_score": 12.162964,
    "_source": {
      "uid": 37,
      "textversions": [
        {
          "content": "die Abiturzeugnisse über die vorhandenen Informatikkenntnisse sehr wenig aussagen, schließlich haben nur relativ wenige Schulen überhaupt Informatik als ernstzunehmendes Fach"
        }
      ]
    },
    "highlight": {
      "textversions.content": [
        "die Abiturzeugnisse über die vorhandenen Informatikkenntnisse sehr wenig aussagen, schließlich",
        " haben nur relativ wenige Schulen überhaupt Informatik als ernstzunehmendes Fach"
      ]
    }
  }

Does anyone know the solution for this misbehavior?

Thanks for your help.


问:
How to update localizable.strings from app by code?
I want to be able to update localized strings by code from the app. What I actually want to do is to make changes to the localization on a server and then let the iPhone application fetch updated localization strings from a server and then save them to the localizable.strings file.</p>

答: You won't be able to modify the Localizable.strings file in your app bundle because the app bundle is read-only on iOS devices. To grab localized strings from a strings file in your app's Library directory, you could programmatically create a bundle at that location, put a Localizable.strings file in it and then grab the localized strings with NSLocalizedStringFromTableInBundle(). (I haven't tried this but it should work.)


问:
Windows service is not starting
i used c# to create Windows service but after installing , it doesn't work
and it shows nothing in log so i don't understand the error to solve it
.

this is my on-start event

```<code>     protected override void OnStart(string[] args)
        {
            StartSynchro();
        }
        public void StartSynchro()
        {
            while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
              System.Threading.Thread.Sleep(TimeSpan.FromHours(1));

            }
            GoogleDriveHandler driveHandler = new GoogleDriveHandler();
            List<Google.Apis.Drive.v3.Data.File> onlineFiles = driveHandler.getFiles();
            Google.Apis.Drive.v3.Data.File onlineVerCSVFile = onlineFiles.Where(c => c.Name == GoogleDriveHandler.onlineVerCSV).First();
            onlineFiles.Remove(onlineVerCSVFile);
            List<KeyValuePair<string, string>> result = Helper.ReadFromMemoryStream(driveHandler.downloadfile_GetStream(ref onlineVerCSVFile));
            List<string> corspondingVer = new List<string>();
            foreach (var onlineFile in onlineFiles)
            {
                corspondingVer.Add(result.Find(c => c.Key == onlineFile.Name).Value);
            }

            List<Google.Apis.Drive.v3.Data.File> fileToDownload = LocalClasses.LocalFilesInfo.getFilesToDwonload(onlineFiles, corspondingVer, ref driveHandler);
            driveHandler.StartDownloading(fileToDownload);
            return;
        }
</code>```

答:
It's better to start the windows service as fast as possible. You could move the initialization code to a separate thread as follows:</p>

```<code>protected override void OnStart(string[] args)
{
   Task.Run(() => StartSynchro());
}
</code>```

Title: Windows service is not starting

Body:
i used c# to create Windows service but after installing , it doesn't work
and it shows nothing in log so i don't understand the error to solve it
.

this is my on-start event

     protected override void OnStart(string[] args)
        {
            StartSynchro();
        }
        public void StartSynchro()
        {
            while (!System.Net.NetworkInformation.NetworkInterface.GetIsNetworkAvailable())
            {
              System.Threading.Thread.Sleep(TimeSpan.FromHours(1));

            }
            GoogleDriveHandler driveHandler = new GoogleDriveHandler();
            List<Google.Apis.Drive.v3.Data.File> onlineFiles = driveHandler.getFiles();
            Google.Apis.Drive.v3.Data.File onlineVerCSVFile = onlineFiles.Where(c => c.Name == GoogleDriveHandler.onlineVerCSV).First();
            onlineFiles.Remove(onlineVerCSVFile);
            List<KeyValuePair<string, string>> result = Helper.ReadFromMemoryStream(driveHandler.downloadfile_GetStream(ref onlineVerCSVFile));
            List<string> corspondingVer = new List<string>();
            foreach (var onlineFile in onlineFiles)
            {
                corspondingVer.Add(result.Find(c => c.Key == onlineFile.Name).Value);
            }

            List<Google.Apis.Drive.v3.Data.File> fileToDownload = LocalClasses.LocalFilesInfo.getFilesToDwonload(onlineFiles, corspondingVer, ref driveHandler);
            driveHandler.StartDownloading(fileToDownload);
            return;
        }

Body:
It's better to start the windows service as fast as possible. You could move the initialization code to a separate thread as follows:

protected override void OnStart(string[] args)
{
   Task.Run(() => StartSynchro());
}


问:
Iterate using Object key and findIndex failed
```<code>{
  "June": [
    {
      "id": "59361b2fa413468484fc41d29d5",
      "is_new": false,
      "name":"John"
      "updated_at": "2017-06-07 10:52:05",
    }
  ]
}
</code>```

I have above object and within it it has array of object, I tried to check within 'June', is there any is_new, but failed?

```<code>const has_any_is_new = Object.keys(arr).map(obj =>
    arr[obj].map(obj2 => obj2.findIndex(o => o.is_new) > -1)
);
</code>```

答:
If you want to test whether any of the items in the June array has is_new==true, you can use .some:

let months = {
  "June" : [
    {
      "id": "59361b2fa413468484fc41d29d5",
      "is_new": false,
      "name":"John",
      "updated_at": "2017-06-07 10:52:05",
    },
     {
      "id": "59361b2fa413468484fc41d29d6",
      "is_new": true,
      "name":"John2",
      "updated_at": "2017-06-07 10:52:05",
    }
  ]
}

const has_any_is_new = Object.keys(months).some( month =>
    months[month].some( obj => obj.is_new )
);

console.log(has_any_is_new)```

.map just runs a function against each element in an array.

.some returns true if any of the functions it applies returns true.

Body:
{
  "June": [
    {
      "id": "59361b2fa413468484fc41d29d5",
      "is_new": false,
      "name":"John"
      "updated_at": "2017-06-07 10:52:05",
    }
  ]
}

I have above object and within it it has array of object, I tried to check within 'June', is there any is_new, but failed?

const has_any_is_new = Object.keys(arr).map(obj =>
    arr[obj].map(obj2 => obj2.findIndex(o => o.is_new) > -1)
);

Body:
If you want to test whether any of the items in the June array has is_new==true, you can use .some:

let months = {
  "June" : [
    {
      "id": "59361b2fa413468484fc41d29d5",
      "is_new": false,
      "name":"John",
      "updated_at": "2017-06-07 10:52:05",
    },
     {
      "id": "59361b2fa413468484fc41d29d6",
      "is_new": true,
      "name":"John2",
      "updated_at": "2017-06-07 10:52:05",
    }
  ]
}

const has_any_is_new = Object.keys(months).some( month =>
    months[month].some( obj => obj.is_new )
);

console.log(has_any_is_new)

.map just runs a function against each element in an array.

.some returns true if any of the functions it applies returns true.


问:
python csv writing from giant loop
Good day,

I'm gathering data from an api, and trying to save it as a csv. The format that I'm receiving it is:

```<code>for title in titles:
   print(title.name)
   for data in title.data:
      print(data)

Title1
data1
data2
data3
Title2
data4
data5
data6
</code>```

etc., (top first, bottom last, from a giant loop)

I'd like to make a csv so that it looks like

```<code>Title1 Title2
data1 data4
data2 data5
data3 data6
</code>```

There is a lot of data, so I can't save it as a list and zip it. Seems like it should be a simple task but I can't find a solution.

答:
Following Maarten Fabré's suggestion, you can make your data receiving function as data generator:

```<code>import pyexce as p

...

def data_gen():
    for title in titles: # put your data recicving api code here
       yield [title.name] +  title.data

p.save_as(array=data_gen(), dest_file_name='result.csv')
</code>```

Then you will have the data in result.csv as:

```<code>Title1,data1,data2,data3
Title2,data4,data5,data6
</code>```

Then you can transpose it later:

```<code>>>> s=p.get_sheet(file_name='result.csv')
>>> s
result.csv:
+--------+-------+-------+-------+
| Title1 | data1 | data2 | data3 |
+--------+-------+-------+-------+
| Title2 | data4 | data5 | data6 |
+--------+-------+-------+-------+
>>> s.transpose()
>>> s
result.csv:
+--------+--------+
| Title1 | Title2 |
+--------+--------+
| data1  | data4  |
+--------+--------+
| data2  | data5  |
+--------+--------+
| data3  | data6  |
+--------+--------+
>>> s.save_as('perferct_result.csv')
</code>```

Alternatively, you can consume it right away without transposing it:

```<code>>>> s=p.get_sheet(file_name='result.csv')
>>> s.name_rows_by_column(0)
>>> s
result.csv:
+--------+-------+-------+-------+
| Title1 | data1 | data2 | data3 |
+--------+-------+-------+-------+
| Title2 | data4 | data5 | data6 |
+--------+-------+-------+-------+
>>> s.to_dict()
OrderedDict([(u'Title1', [u'data1', u'data2', u'data3']), (u'Title2', [u'data4', u'data5', u'data6'])])
</code>```

Title: python csv writing from giant loop

Body:
Good day,

I'm gathering data from an api, and trying to save it as a csv. The format that I'm receiving it is:

for title in titles:
   print(title.name)
   for data in title.data:
      print(data)

Title1
data1
data2
data3
Title2
data4
data5
data6

etc., (top first, bottom last, from a giant loop)

I'd like to make a csv so that it looks like

Title1 Title2
data1 data4
data2 data5
data3 data6

There is a lot of data, so I can't save it as a list and zip it. Seems like it should be a simple task but I can't find a solution.

Body:
Following Maarten Fabré's suggestion, you can make your data receiving function as data generator:

import pyexce as p

...

def data_gen():
    for title in titles: # put your data recicving api code here
       yield [title.name] +  title.data

p.save_as(array=data_gen(), dest_file_name='result.csv')

Then you will have the data in result.csv as:

Title1,data1,data2,data3
Title2,data4,data5,data6

Then you can transpose it later:

>>> s=p.get_sheet(file_name='result.csv')
>>> s
result.csv:
+--------+-------+-------+-------+
| Title1 | data1 | data2 | data3 |
+--------+-------+-------+-------+
| Title2 | data4 | data5 | data6 |
+--------+-------+-------+-------+
>>> s.transpose()
>>> s
result.csv:
+--------+--------+
| Title1 | Title2 |
+--------+--------+
| data1  | data4  |
+--------+--------+
| data2  | data5  |
+--------+--------+
| data3  | data6  |
+--------+--------+
>>> s.save_as('perferct_result.csv')

Alternatively, you can consume it right away without transposing it:

>>> s=p.get_sheet(file_name='result.csv')
>>> s.name_rows_by_column(0)
>>> s
result.csv:
+--------+-------+-------+-------+
| Title1 | data1 | data2 | data3 |
+--------+-------+-------+-------+
| Title2 | data4 | data5 | data6 |
+--------+-------+-------+-------+
>>> s.to_dict()
OrderedDict([(u'Title1', [u'data1', u'data2', u'data3']), (u'Title2', [u'data4', u'data5', u'data6'])])


问:
Azure AD B2C authentication hybrid
I created a B2C AD in my developer account on Azure.
In this environment I have users created in my personal AD, and users in AD B2C (where the user can log in with: twitter and facebook).

I found an ASP.NET project that logs in to these two ADs, but with two types of logins, one for normal AD and one for AD B2C. And from what I've researched, the only way to log in to these two different ADs is this way.

Does anyone know of a way to make a single login in these two ADs?

答:
Thanks for the quick response.
I tried to do this but could not find the settings needed to put Twitter, Google and Microsoft. For Facebook and other AD worked.
I found a post, that Microsoft will soon make available an "Identity Provider" to validate the user in another AD.
For now, I'll put two Sign-in in my application, one for the company's AD and another for the B2C AD.

I am now looking for a way to get the user's profile in AD (Name, First Name, Last Name, Job Title, Departament, ....).

Once this is done, I'm going to make a DEMO and publish it to github, I think this will help a lot of people.

Title: Azure AD B2C authentication hybrid


答:
You can use () for each conditions..try it..

echo $current = (($var > 2) ? "gr than 2" : (($var > 6) ? "gr than 6" : "not gr than 2 or 6"));

Title: PHP nested ternary if condition

Body:
<?php
$var = 4;
echo $current = ($var > 2) ? "gr than 2" : ($var > 6) ? "gr than 6" : "not gr than 2 or 6";
?>

for the above code, it always returns - gr than 6. Can someone please suggest what did I wrong?


问:
Check time in stored procedure
I have a stored procedure that takes a lot of time to execute. We want it to execute during the night, but it has to check for the current time every now and then, and at a given time it has to stop executing. How do I do that? Please provide me with the code I can use in my stored procedure. We are using Microsoft SQL Server 2005.</p>

答:
You can get the current date:

```<code>SELECT GETDATE()
</code>```

Stop executing:

```<code>If @date > GETDATE()
    RETURN --Exits procedure
</code>```

Where @date is the date/time when you want to stop executing

Title: Check time in stored procedure

Body:
You can get the current date:

SELECT GETDATE()

Stop executing:

If @date > GETDATE()
    RETURN --Exits procedure

Where @date is the date/time when you want to stop executing