text:
Q: What Is The Correct Usage of Confluent Kafka Client Within docker-compose Stack On A Cloud CI Server Such As GitLab or Travis? I am new Kafka user and have managed to get a docker-compose stack working locally to successfully run functional tests from an ASP.NET Core 3.1 test service. This exists within the same docker-compose stack as Kafa, Zookeeper and Rest-Proxy services, on the same network.
The SUT and tests use the .NET Core Client to create a topic at startup if it does not already exist.
As soon as I try to run this docker-compose stack on a remote GitLab.com CI server the test hangs while creating the topic. The logs (see below) show that the .NET client is connecting to the correct internal service kafka:19092 within the docker-compose stack.  There is some activity from kafka service starting to create the topic and then it blocks. I should see a message in the log confirming topic creation.
.NET Client Creating Kafka Topic
        /// <summary>Dispatch request to Kafka Broker to create Kafka topic from config</summary>
        /// <param name="client">Kafka admin client</param>
        /// <exception cref="">Thrown for errors except topic already exists</exception>
        private async Task CreateTopicAsync(IAdminClient client)
        {
            try
            {
                _Logger.LogInformation("Admin service trying to create Kafka Topic...");
                _Logger.LogInformation($"Topic::{_Config.Topic.Name}, ReplicationCount::{_Config.Topic.ReplicationCount}, PartitionCount::{_Config.Topic.PartitionCount}");
                _Logger.LogInformation($"Bootstrap Servers::{_Config.Consumer.BootstrapServers}");

                await client.CreateTopicsAsync(new TopicSpecification[] {
                        new TopicSpecification {
                            Name = _Config.Topic.Name,
                            NumPartitions = _Config.Topic.PartitionCount,
                            ReplicationFactor = _Config.Topic.ReplicationCount
                        }
                    }, null);

                _Logger.LogInformation($"Admin service successfully created topic {_Config.Topic.Name}");
            }
            catch (CreateTopicsException e)
            {
                if (e.Results[0].Error.Code != ErrorCode.TopicAlreadyExists)
                {
                    _Logger.LogInformation($"An error occured creating topic {_Config.Topic.Name}: {e.Results[0].Error.Reason}");
                    throw e;
                }
                else
                {
                    _Logger.LogInformation($"Topic {_Config.Topic.Name} already exists");
                }
            }
        }

How do I configure the kafka broker and rest proxy docker-compose services to run on an external CI server? Is this possible?
Details of the docker-compose stack and GitLab CI environment are included below...
create docker network
docker network create --gateway 172.19.0.1 --subnet 172.19.0.0/16 broker

docker-compose stack with zookeeper, kafka, rest-proxy and ASP.NET Core 3.1 for integration test services
---
version: "3.8"

services:
  zookeeper:
    image: confluentinc/cp-zookeeper:6.0.0
    hostname: zookeeper
    container_name: zookeeper
    ports:
      - "2181:2181"
    networks:
      camnet:
        ipv4_address: 172.19.0.11
    environment:
      ZOOKEEPER_CLIENT_PORT: 2181
      ZOOKEEPER_TICK_TIME: 2000

  kafka:
    image: confluentinc/cp-kafka:6.0.0
    hostname: kafka
    container_name: kafka
    depends_on:
      - zookeeper
    ports:
      - "9092:9092"
      - "9101:9101"
    networks:
      camnet:
        ipv4_address: 172.19.0.21
    environment:
      KAFKA_ADVERTISED_LISTENERS: LISTENER_DOCKER_INTERNAL://kafka:19092
      KAFKA_LISTENER_SECURITY_PROTOCOL_MAP: LISTENER_DOCKER_INTERNAL:PLAINTEXT
      KAFKA_INTER_BROKER_LISTENER_NAME: LISTENER_DOCKER_INTERNAL
      KAFKA_ZOOKEEPER_CONNECT: "zookeeper:2181"
      KAFKA_OFFSETS_TOPIC_REPLICATION_FACTOR: 1
      KAFKA_BROKER_ID: 1
      KAFKA_DEFAULT_REPLICATION_FACTOR : 1
      KAFKA_NUM_PARTITIONS: 3

  rest-proxy:
    image: confluentinc/cp-kafka-rest:6.0.0
    hostname: rest-proxy
    container_name: rest-proxy
    depends_on:
      - kafka
    ports:
      - 8082:8082
    networks:
      camnet:
        ipv4_address: 172.19.0.31
    environment:
      KAFKA_REST_HOST_NAME: rest-proxy
      KAFKA_REST_BOOTSTRAP_SERVERS: 'kafka:19092'
      KAFKA_REST_LISTENERS: "http://0.0.0.0:8082"
      KAFKA_REST_SCHEMA_REGISTRY_URL: 'http://schema-registry:8081'

 # ASP.NET Core 3 integration tests
 # uses kafka dotnet client https://docs.confluent.io/current/clients/dotnet.html
 # to create topics from an ASP.NET Core Test Server
  webapp:
    build:
      context: ../
      dockerfile: Docker/Test/Dockerfile
      target: test
    hostname: webapp
    image: dcs3spp/webapp
    container_name: webapp
    depends_on:
      - kafka
      - rest-proxy
    networks:
      camnet:
        ipv4_address: 172.19.0.61
    environment:
      - ASPNETCORE_ENVIRONMENT=Docker

networks:
  camnet:
    external:
      name: broker

GitLab.com CI Docker Network Environment
$ docker network ls
NETWORK ID          NAME                DRIVER              SCOPE
2b3286d21fee        bridge              bridge              local
a17bf57d1a86        host                host                local
0252525b2ca4        none                null                local
$ docker network inspect bridge
[
    {
        "Name": "bridge",
        "Id": "2b3286d21fee076047e78188b67c2912dfd388a170de3e3cf2ba8d5238e1c6c7",
        "Created": "2020-11-16T14:53:35.574299006Z",
        "Scope": "local",
        "Driver": "bridge",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": [
                {
                    "Subnet": "172.18.0.0/16"
                }
            ]
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {
            "com.docker.network.bridge.default_bridge": "true",
            "com.docker.network.bridge.enable_icc": "true",
            "com.docker.network.bridge.enable_ip_masquerade": "true",
            "com.docker.network.bridge.host_binding_ipv4": "0.0.0.0",
            "com.docker.network.bridge.name": "docker0",
            "com.docker.network.driver.mtu": "1500"
        },
        "Labels": {}
    }
]
$ docker network inspect host
[
    {
        "Name": "host",
        "Id": "a17bf57d1a865512bebd3f7f73e0fd761d40b1d4f87765edeac6099e86b94339",
        "Created": "2020-11-16T14:53:35.551372286Z",
        "Scope": "local",
        "Driver": "host",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": []
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]
$ docker network inspect none
[
    {
        "Name": "none",
        "Id": "0252525b2ca4b28ddc0f950b472485167cfe18e003c62f3d09ce2a856880362a",
        "Created": "2020-11-16T14:53:35.536741983Z",
        "Scope": "local",
        "Driver": "null",
        "EnableIPv6": false,
        "IPAM": {
            "Driver": "default",
            "Options": null,
            "Config": []
        },
        "Internal": false,
        "Attachable": false,
        "Ingress": false,
        "ConfigFrom": {
            "Network": ""
        },
        "ConfigOnly": false,
        "Containers": {},
        "Options": {},
        "Labels": {}
    }
]
$ docker network create --gateway 172.19.0.1 --subnet 172.19.0.0/16 broker
dbd923b4caacca225f52e8a82dfcad184a1652bde1b5976aa07bbddb2919126c

Gitab.com CI server logs
webapp        | A total of 1 test files matched the specified pattern.
webapp        | warn: Microsoft.AspNetCore.DataProtection.Repositories.FileSystemXmlRepository[60]
webapp        |       Storing keys in a directory '/root/.aspnet/DataProtection-Keys' that may not be persisted outside of the container. Protected data will be unavailable when container is destroyed.
webapp        | info: WebApp.S3.S3Service[0]
webapp        |       Minio client created for endpoint minio:9000
webapp        | info: WebApp.Kafka.ProducerService[0]
webapp        |       ProducerService constructor called
webapp        | info: WebApp.Kafka.SchemaRegistry.Serdes.JsonDeserializer[0]
webapp        |       Constructed
webapp        | info: WebApp.Kafka.ConsumerService[0]
webapp        |       Kafka consumer listening to camera topics =>
webapp        | info: WebApp.Kafka.ConsumerService[0]
webapp        |       Camera Topic :: shinobi/RHSsYfiV6Z/xi5cncrNK6/trigger
webapp        | info: WebApp.Kafka.ConsumerService[0]
webapp        |       Camera Topic :: shinobi/group/monitor/trigger
webapp        | warn: Microsoft.AspNetCore.DataProtection.KeyManagement.XmlKeyManager[35]
webapp        |       No XML encryptor configured. Key {47af6978-c38e-429f-9b34-455ca445c2d8} may be persisted to storage in unencrypted form.
webapp        | info: WebApp.Kafka.Admin.KafkaAdminService[0]
webapp        |       Admin service trying to create Kafka Topic...
webapp        | info: WebApp.Kafka.Admin.KafkaAdminService[0]
webapp        |       Topic::eventbus, ReplicationCount::1, PartitionCount::3
webapp        | info: WebApp.Kafka.Admin.KafkaAdminService[0]
webapp        |       Bootstrap Servers::kafka:19092
kafka         | [2020-11-16 14:59:32,335] INFO Creating topic eventbus with configuration {} and initial partition assignment HashMap(0 -> ArrayBuffer(1), 1 -> ArrayBuffer(1), 2 -> ArrayBuffer(1)) (kafka.zk.AdminZkClient)
kafka         | [2020-11-16 14:59:32,543] INFO [Controller id=1] New topics: [Set(eventbus)], deleted topics: [HashSet()], new partition replica assignment [Map(eventbus-0 -> ReplicaAssignment(replicas=1, addingReplicas=, removingReplicas=), eventbus-1 -> ReplicaAssignment(replicas=1, addingReplicas=, removingReplicas=), eventbus-2 -> ReplicaAssignment(replicas=1, addingReplicas=, removingReplicas=))] (kafka.controller.KafkaController)
kafka         | [2020-11-16 14:59:32,546] INFO [Controller id=1] New partition creation callback for eventbus-0,eventbus-1,eventbus-2 (kafka.controller.KafkaController)
kafka         | [2020-11-16 14:59:32,557] INFO [Controller id=1 epoch=1] Changed partition eventbus-0 state from NonExistentPartition to NewPartition with assigned replicas 1 (state.change.logger)
kafka         | [2020-11-16 14:59:32,558] INFO [Controller id=1 epoch=1] Changed partition eventbus-1 state from NonExistentPartition to NewPartition with assigned replicas 1 (state.change.logger)
kafka         | [2020-11-16 14:59:32,559] INFO [Controller id=1 epoch=1] Changed partition eventbus-2 state from NonExistentPartition to NewPartition with assigned replicas 1 (state.change.logger)
kafka         | [2020-11-16 14:59:32,560] INFO [Controller id=1 epoch=1] Sending UpdateMetadata request to brokers HashSet() for 0 partitions (state.change.logger)
kafka         | [2020-11-16 14:59:32,613] TRACE [Controller id=1 epoch=1] Changed state of replica 1 for partition eventbus-0 from NonExistentReplica to NewReplica (state.change.logger)
kafka         | [2020-11-16 14:59:32,614] TRACE [Controller id=1 epoch=1] Changed state of replica 1 for partition eventbus-1 from NonExistentReplica to NewReplica (state.change.logger)
kafka         | [2020-11-16 14:59:32,615] TRACE [Controller id=1 epoch=1] Changed state of replica 1 for partition eventbus-2 from NonExistentReplica to NewReplica (state.change.logger)
kafka         | [2020-11-16 14:59:32,616] INFO [Controller id=1 epoch=1] Sending UpdateMetadata request to brokers HashSet() for 0 partitions (state.change.logger)
kafka         | [2020-11-16 14:59:32,770] INFO [Controller id=1 epoch=1] Changed partition eventbus-0 from NewPartition to OnlinePartition with state LeaderAndIsr(leader=1, leaderEpoch=0, isr=List(1), zkVersion=0) (state.change.logger)
kafka         | [2020-11-16 14:59:32,772] INFO [Controller id=1 epoch=1] Changed partition eventbus-1 from NewPartition to OnlinePartition with state LeaderAndIsr(leader=1, leaderEpoch=0, isr=List(1), zkVersion=0) (state.change.logger)
kafka         | [2020-11-16 14:59:32,773] INFO [Controller id=1 epoch=1] Changed partition eventbus-2 from NewPartition to OnlinePartition with state LeaderAndIsr(leader=1, leaderEpoch=0, isr=List(1), zkVersion=0) (state.change.logger)
kafka         | [2020-11-16 14:59:32,804] TRACE [Controller id=1 epoch=1] Sending become-leader LeaderAndIsr request LeaderAndIsrPartitionState(topicName='eventbus', partitionIndex=0, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], addingReplicas=[], removingReplicas=[], isNew=true) to broker 1 for partition eventbus-0 (state.change.logger)
kafka         | [2020-11-16 14:59:32,805] TRACE [Controller id=1 epoch=1] Sending become-leader LeaderAndIsr request LeaderAndIsrPartitionState(topicName='eventbus', partitionIndex=1, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], addingReplicas=[], removingReplicas=[], isNew=true) to broker 1 for partition eventbus-1 (state.change.logger)
kafka         | [2020-11-16 14:59:32,806] TRACE [Controller id=1 epoch=1] Sending become-leader LeaderAndIsr request LeaderAndIsrPartitionState(topicName='eventbus', partitionIndex=2, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], addingReplicas=[], removingReplicas=[], isNew=true) to broker 1 for partition eventbus-2 (state.change.logger)
kafka         | [2020-11-16 14:59:32,808] INFO [Controller id=1 epoch=1] Sending LeaderAndIsr request to broker 1 with 3 become-leader and 0 become-follower partitions (state.change.logger)
kafka         | [2020-11-16 14:59:32,818] INFO [Broker id=1] Handling LeaderAndIsr request correlationId 1 from controller 1 for 3 partitions (state.change.logger)
kafka         | [2020-11-16 14:59:32,820] TRACE [Broker id=1] Received LeaderAndIsr request LeaderAndIsrPartitionState(topicName='eventbus', partitionIndex=0, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], addingReplicas=[], removingReplicas=[], isNew=true) correlation id 1 from controller 1 epoch 1 (state.change.logger)
kafka         | [2020-11-16 14:59:32,821] TRACE [Broker id=1] Received LeaderAndIsr request LeaderAndIsrPartitionState(topicName='eventbus', partitionIndex=1, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], addingReplicas=[], removingReplicas=[], isNew=true) correlation id 1 from controller 1 epoch 1 (state.change.logger)
kafka         | [2020-11-16 14:59:32,822] INFO [Controller id=1 epoch=1] Sending UpdateMetadata request to brokers HashSet(1) for 3 partitions (state.change.logger)
kafka         | [2020-11-16 14:59:32,823] TRACE [Broker id=1] Received LeaderAndIsr request LeaderAndIsrPartitionState(topicName='eventbus', partitionIndex=2, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], addingReplicas=[], removingReplicas=[], isNew=true) correlation id 1 from controller 1 epoch 1 (state.change.logger)
kafka         | [2020-11-16 14:59:32,828] TRACE [Controller id=1 epoch=1] Changed state of replica 1 for partition eventbus-0 from NewReplica to OnlineReplica (state.change.logger)
kafka         | [2020-11-16 14:59:32,829] TRACE [Controller id=1 epoch=1] Changed state of replica 1 for partition eventbus-1 from NewReplica to OnlineReplica (state.change.logger)
kafka         | [2020-11-16 14:59:32,830] TRACE [Controller id=1 epoch=1] Changed state of replica 1 for partition eventbus-2 from NewReplica to OnlineReplica (state.change.logger)
kafka         | [2020-11-16 14:59:32,832] INFO [Controller id=1 epoch=1] Sending UpdateMetadata request to brokers HashSet() for 0 partitions (state.change.logger)
kafka         | [2020-11-16 14:59:32,869] TRACE [Broker id=1] Handling LeaderAndIsr request correlationId 1 from controller 1 epoch 1 starting the become-leader transition for partition eventbus-2 (state.change.logger)
kafka         | [2020-11-16 14:59:32,870] TRACE [Broker id=1] Handling LeaderAndIsr request correlationId 1 from controller 1 epoch 1 starting the become-leader transition for partition eventbus-1 (state.change.logger)
kafka         | [2020-11-16 14:59:32,871] TRACE [Broker id=1] Handling LeaderAndIsr request correlationId 1 from controller 1 epoch 1 starting the become-leader transition for partition eventbus-0 (state.change.logger)
kafka         | [2020-11-16 14:59:32,873] INFO [ReplicaFetcherManager on broker 1] Removed fetcher for partitions Set(eventbus-2, eventbus-1, eventbus-0) (kafka.server.ReplicaFetcherManager)
kafka         | [2020-11-16 14:59:32,874] INFO [Broker id=1] Stopped fetchers as part of LeaderAndIsr request correlationId 1 from controller 1 epoch 1 as part of the become-leader transition for 3 partitions (state.change.logger)
kafka         | [2020-11-16 14:59:33,345] INFO [Log partition=eventbus-2, dir=/var/lib/kafka/data] Loading producer state till offset 0 with message format version 2 (kafka.log.Log)
kafka         | [2020-11-16 14:59:33,421] INFO Created log for partition eventbus-2 in /var/lib/kafka/data/eventbus-2 with properties {compression.type -> producer, min.insync.replicas -> 1, message.downconversion.enable -> true, segment.jitter.ms -> 0, cleanup.policy -> [delete], flush.ms -> 9223372036854775807, retention.ms -> 604800000, segment.bytes -> 1073741824, flush.messages -> 9223372036854775807, message.format.version -> 2.6-IV0, max.compaction.lag.ms -> 9223372036854775807, file.delete.delay.ms -> 60000, max.message.bytes -> 1048588, min.compaction.lag.ms -> 0, message.timestamp.type -> CreateTime, preallocate -> false, index.interval.bytes -> 4096, min.cleanable.dirty.ratio -> 0.5, unclean.leader.election.enable -> false, retention.bytes -> -1, delete.retention.ms -> 86400000, segment.ms -> 604800000, message.timestamp.difference.max.ms -> 9223372036854775807, segment.index.bytes -> 10485760}. (kafka.log.LogManager)
kafka         | [2020-11-16 14:59:33,424] INFO [Partition eventbus-2 broker=1] No checkpointed highwatermark is found for partition eventbus-2 (kafka.cluster.Partition)
kafka         | [2020-11-16 14:59:33,425] INFO [Partition eventbus-2 broker=1] Log loaded for partition eventbus-2 with initial high watermark 0 (kafka.cluster.Partition)
kafka         | [2020-11-16 14:59:33,429] INFO [Broker id=1] Leader eventbus-2 starts at leader epoch 0 from offset 0 with high watermark 0 ISR [1] addingReplicas [] removingReplicas []. Previous leader epoch was -1. (state.change.logger)
kafka         | [2020-11-16 14:59:33,462] INFO [Log partition=eventbus-1, dir=/var/lib/kafka/data] Loading producer state till offset 0 with message format version 2 (kafka.log.Log)
kafka         | [2020-11-16 14:59:33,468] INFO Created log for partition eventbus-1 in /var/lib/kafka/data/eventbus-1 with properties {compression.type -> producer, min.insync.replicas -> 1, message.downconversion.enable -> true, segment.jitter.ms -> 0, cleanup.policy -> [delete], flush.ms -> 9223372036854775807, retention.ms -> 604800000, segment.bytes -> 1073741824, flush.messages -> 9223372036854775807, message.format.version -> 2.6-IV0, max.compaction.lag.ms -> 9223372036854775807, file.delete.delay.ms -> 60000, max.message.bytes -> 1048588, min.compaction.lag.ms -> 0, message.timestamp.type -> CreateTime, preallocate -> false, index.interval.bytes -> 4096, min.cleanable.dirty.ratio -> 0.5, unclean.leader.election.enable -> false, retention.bytes -> -1, delete.retention.ms -> 86400000, segment.ms -> 604800000, message.timestamp.difference.max.ms -> 9223372036854775807, segment.index.bytes -> 10485760}. (kafka.log.LogManager)
kafka         | [2020-11-16 14:59:33,469] INFO [Partition eventbus-1 broker=1] No checkpointed highwatermark is found for partition eventbus-1 (kafka.cluster.Partition)
kafka         | [2020-11-16 14:59:33,470] INFO [Partition eventbus-1 broker=1] Log loaded for partition eventbus-1 with initial high watermark 0 (kafka.cluster.Partition)
kafka         | [2020-11-16 14:59:33,470] INFO [Broker id=1] Leader eventbus-1 starts at leader epoch 0 from offset 0 with high watermark 0 ISR [1] addingReplicas [] removingReplicas []. Previous leader epoch was -1. (state.change.logger)
kafka         | [2020-11-16 14:59:33,484] INFO [Log partition=eventbus-0, dir=/var/lib/kafka/data] Loading producer state till offset 0 with message format version 2 (kafka.log.Log)
kafka         | [2020-11-16 14:59:33,488] INFO Created log for partition eventbus-0 in /var/lib/kafka/data/eventbus-0 with properties {compression.type -> producer, min.insync.replicas -> 1, message.downconversion.enable -> true, segment.jitter.ms -> 0, cleanup.policy -> [delete], flush.ms -> 9223372036854775807, retention.ms -> 604800000, segment.bytes -> 1073741824, flush.messages -> 9223372036854775807, message.format.version -> 2.6-IV0, max.compaction.lag.ms -> 9223372036854775807, file.delete.delay.ms -> 60000, max.message.bytes -> 1048588, min.compaction.lag.ms -> 0, message.timestamp.type -> CreateTime, preallocate -> false, index.interval.bytes -> 4096, min.cleanable.dirty.ratio -> 0.5, unclean.leader.election.enable -> false, retention.bytes -> -1, delete.retention.ms -> 86400000, segment.ms -> 604800000, message.timestamp.difference.max.ms -> 9223372036854775807, segment.index.bytes -> 10485760}. (kafka.log.LogManager)
kafka         | [2020-11-16 14:59:33,489] INFO [Partition eventbus-0 broker=1] No checkpointed highwatermark is found for partition eventbus-0 (kafka.cluster.Partition)
kafka         | [2020-11-16 14:59:33,489] INFO [Partition eventbus-0 broker=1] Log loaded for partition eventbus-0 with initial high watermark 0 (kafka.cluster.Partition)
kafka         | [2020-11-16 14:59:33,490] INFO [Broker id=1] Leader eventbus-0 starts at leader epoch 0 from offset 0 with high watermark 0 ISR [1] addingReplicas [] removingReplicas []. Previous leader epoch was -1. (state.change.logger)
kafka         | [2020-11-16 14:59:33,507] TRACE [Broker id=1] Completed LeaderAndIsr request correlationId 1 from controller 1 epoch 1 for the become-leader transition for partition eventbus-2 (state.change.logger)
kafka         | [2020-11-16 14:59:33,508] TRACE [Broker id=1] Completed LeaderAndIsr request correlationId 1 from controller 1 epoch 1 for the become-leader transition for partition eventbus-1 (state.change.logger)
kafka         | [2020-11-16 14:59:33,509] TRACE [Broker id=1] Completed LeaderAndIsr request correlationId 1 from controller 1 epoch 1 for the become-leader transition for partition eventbus-0 (state.change.logger)
kafka         | [2020-11-16 14:59:33,549] TRACE [Controller id=1 epoch=1] Received response {error_code=0,partition_errors=[{topic_name=eventbus,partition_index=0,error_code=0,_tagged_fields={}},{topic_name=eventbus,partition_index=1,error_code=0,_tagged_fields={}},{topic_name=eventbus,partition_index=2,error_code=0,_tagged_fields={}}],_tagged_fields={}} for request LEADER_AND_ISR with correlation id 1 sent to broker kafka:19092 (id: 1 rack: null) (state.change.logger)
kafka         | [2020-11-16 14:59:33,564] TRACE [Broker id=1] Cached leader info UpdateMetadataPartitionState(topicName='eventbus', partitionIndex=0, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], offlineReplicas=[]) for partition eventbus-0 in response to UpdateMetadata request sent by controller 1 epoch 1 with correlation id 2 (state.change.logger)
kafka         | [2020-11-16 14:59:33,569] TRACE [Broker id=1] Cached leader info UpdateMetadataPartitionState(topicName='eventbus', partitionIndex=1, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], offlineReplicas=[]) for partition eventbus-1 in response to UpdateMetadata request sent by controller 1 epoch 1 with correlation id 2 (state.change.logger)
kafka         | [2020-11-16 14:59:33,570] TRACE [Broker id=1] Cached leader info UpdateMetadataPartitionState(topicName='eventbus', partitionIndex=2, controllerEpoch=1, leader=1, leaderEpoch=0, isr=[1], zkVersion=0, replicas=[1], offlineReplicas=[]) for partition eventbus-2 in response to UpdateMetadata request sent by controller 1 epoch 1 with correlation id 2 (state.change.logger)
kafka         | [2020-11-16 14:59:33,574] INFO [Broker id=1] Add 3 partitions and deleted 0 partitions from metadata cache in response to UpdateMetadata request sent by controller 1 epoch 1 with correlation id 2 (state.change.logger)
kafka         | [2020-11-16 14:59:33,576] TRACE [Controller id=1 epoch=1] Received response {error_code=0,_tagged_fields={}} for request UPDATE_METADATA with correlation id 2 sent to broker kafka:19092 (id: 1 rack: null) (state.change.logger)
kafka         | [2020-11-16 15:01:52,665] INFO [Controller id=1] Processing automatic preferred replica leader election (kafka.controller.KafkaController)
kafka         | [2020-11-16 15:01:52,666] TRACE [Controller id=1] Checking need to trigger auto leader balancing (kafka.controller.KafkaController)
kafka         | [2020-11-16 15:01:52,669] DEBUG [Controller id=1] Topics not in preferred replica for broker 1 Map() (kafka.controller.KafkaController)
kafka         | [2020-11-16 15:01:52,675] TRACE [Controller id=1] Leader imbalance ratio for broker 1 is 0.0 (kafka.controller.KafkaController)
kafka         | [2020-11-16 15:06:47,246] INFO [GroupMetadataManager brokerId=1] Removed 0 expired offsets in 0 milliseconds. (kafka.coordinator.group.GroupMetadataManager)
kafka         | [2020-11-16 15:06:52,676] INFO [Controller id=1] Processing automatic preferred replica leader election (kafka.controller.KafkaController)
kafka         | [2020-11-16 15:06:52,677] TRACE [Controller id=1] Checking need to trigger auto leader balancing (kafka.controller.KafkaController)
kafka         | [2020-11-16 15:06:52,678] DEBUG [Controller id=1] Topics not in preferred replica for broker 1 Map() (kafka.controller.KafkaController)
kafka         | [2020-11-16 15:06:52,679] TRACE [Controller id=1] Leader imbalance ratio for broker 1 is 0.0 (kafka.controller.KafkaController)

A: After reading this aspnetcoreissue discovered that the problem was with the implementation
of my IHostedService implementation that makes the request to Kafka.
The StartAsync method was performing the task, running until the request completed. By design this method is meant to be fire and forget, i.e. start the task and then continue. Updated my KafkaAdmin service to be a BackgroundService, overriding ExecuteAsync method, as listed below.
Subsequently, tests no longer blocks.
using System;
using System.Threading;
using System.Threading.Tasks;

using Confluent.Kafka;
using Confluent.Kafka.Admin;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Options;

using KafkaAdmin.Kafka.Config;

namespace KafkaAdmin.Kafka
{
    public delegate IAdminClient KafkaAdminFactory(KafkaConfig config);

    /// <summary>Background Service to make a request from Kafka to create a topic</summary>
    public class KafkaAdminService : BackgroundService, IDisposable
    {
        private KafkaAdminFactory _Factory { get; set; }
        private ILogger<KafkaAdminService> _Logger { get; set; }
        private KafkaConfig _Config { get; set; }

        /// <summary>
        /// Retrieve KafkaConfig from appsettings
        /// </summary>
        /// <param name="config">Config POCO from appsettings file</param>
        /// <param name="clientFactory"><see cref="KafkaAdminFactory"/></param>
        /// <param name="logger">Logger instance</param>
        public KafkaAdminService(
            IOptions<KafkaConfig> config,
            KafkaAdminFactory clientFactory,
            ILogger<KafkaAdminService> logger)
        {
            if (clientFactory == null)
                throw new ArgumentNullException(nameof(clientFactory));

            if (config == null)
                throw new ArgumentNullException(nameof(config));

            _Config = config.Value ?? throw new ArgumentNullException(nameof(config));
            _Factory = clientFactory ?? throw new ArgumentNullException(nameof(clientFactory));
            _Logger = logger ?? throw new ArgumentNullException(nameof(logger));
        }

        /// <summary>
        /// Create a Kafka topic if it does not already exist
        /// </summary>
        /// <param name="token">Cancellation token required by IHostedService</param>
        /// <exception name="CreateTopicsException">
        /// Thrown for exceptions encountered except duplicate topic
        /// </exception>
        protected override async Task ExecuteAsync(CancellationToken stoppingToken)
        {
            using (var client = _Factory(_Config))
            {
                try
                {
                    _Logger.LogInformation("Admin service trying to create Kafka Topic...");
                    _Logger.LogInformation($"Topic::{_Config.Topic.Name}, ReplicationCount::{_Config.Topic.ReplicationCount}, PartitionCount::{_Config.Topic.PartitionCount}");
                    _Logger.LogInformation($"Bootstrap Servers::{_Config.Consumer.BootstrapServers}");

                    await client.CreateTopicsAsync(new TopicSpecification[] {
                        new TopicSpecification {
                            Name = _Config.Topic.Name,
                            NumPartitions = _Config.Topic.PartitionCount,
                            ReplicationFactor = _Config.Topic.ReplicationCount
                        }
                    }, null);

                    _Logger.LogInformation($"Admin service successfully created topic {_Config.Topic.Name}");
                }
                catch (CreateTopicsException e)
                {
                    if (e.Results[0].Error.Code != ErrorCode.TopicAlreadyExists)
                    {
                        _Logger.LogInformation($"An error occured creating topic {_Config.Topic.Name}: {e.Results[0].Error.Reason}");
                        throw e;
                    }
                    else
                    {
                        _Logger.LogInformation($"Topic {_Config.Topic.Name} already exists");
                    }
                }
            }

            _Logger.LogInformation("Kafka Consumer thread started");

            await Task.CompletedTask;
        }

        /// <summary>
        /// Call base class dispose
        /// </summary>
        public override void Dispose()
        {
            base.Dispose();
        }
    }
}

Still confused as to why the live WebApp starts successfully. Why is this just an issue for the TestServer?
I have created a repository that demonstrates the issue and fix. The master branch contains source code exhibiting the issue. The feat/fix branch contains source code containing the fix.
Hope this helps others who encounter similar issues!


text:
Q: HAProxy MySQL Failover is not starting I am trying to setup HAProxy with MySQL failover with Ubuntu. I used a setup similar to this serverfault question, however I am getting the following error when starting haproxy:
[ALERT] 341/220001 (17405) : parsing [/etc/haproxy/haproxy.cfg:29] : unknown option 'mysql-check'.
[ALERT] 341/220001 (17405) : Error(s) found in configuration file : /etc/haproxy/haproxy.cfg
[ALERT] 341/220001 (17405) : Fatal errors found in configuration.

I even tried installing the lastest version of HAProxy (1.4.22). Does anyone know how to fix this? I have Google'd the heck out of it and can't find any solution.
Thanks for your time!

A: OK, so it was available. I was just running the wrong version. Before I complied HAProxy I installed it from the repo which was at version 1.3. I stopped that versions daemon and started the 1.4 version and everything works! NOOB mistake.

redpajama_set_name: RedPajamaStackExchange


text:
Q: Div height is 0px on a responsive iframe I have a responsive iframe on a page that also requires content to appear beneath the iframe, however the container that's wrapping the iframe has a height of 0px. I've tried clear:both & overflow:auto/hidden at various positions however neither appear to work, nor does adding an additional container around the iframe.

Text That needs to appear beneath the Video

Link to my fiddle here: http://jsfiddle.net/ehcv0bfv/

A: Set .prodYoutube {position: relative;} rather than position:absolute

A: This seems to solve the issue.
.prodYoutube {position: relative;}


text:
Q: IOS9: CoreSpotlight and Siri In my IOS9 app, I am able to add data to spotlight's index using CoreSpotlight library (i.e. what I add to the index shows up when I search using the spotlight search box).
However, Siri doesn't seem to be pulling info from there. Here is my code:
let attributeSet = CSSearchableItemAttributeSet(itemContentType: kUTTypeText as String)
attributeSet.title = "AWS Traffic"
attributeSet.contentDescription = "AWS Server Traffic in MyCompany"
attributeSet.keywords = ["MyApp", "AWS", "Server", "Traffic"]

let item = CSSearchableItem(uniqueIdentifier: "com.mycompany.MyApp", domainIdentifier: "com.company.MyApp.AWS", attributeSet: attributeSet)

CSSearchableIndex.defaultSearchableIndex().indexSearchableItems([item]) { (error: NSError?) -> Void in
    if let error = error {
        print("Indexing error: \(error.localizedDescription)")
    } else {
        print("Search item successfully indexed!")
    }
}

Is there any way of getting Siri to show the indexed data from my app? Currently, when I speak to Siri with my keywords, it just does a web search.

A: At this time, in iOS 9, Siri does not interact with the items your app adds to the Spotlight index. This API is only used to get items to appear in Spotlight Search results, not in Siri responses.


text:
Q: ASP.NET MVC Resource not found I am working on an MVC project in Visual Studio 2010 with .NET Framework 4.0 + MVC2 and everything works if I set the target framework to .NET 4.0. However, my host does not offer .NET 4.0 in order to deploy the site I need to get it working on .NET 3.5.
I tried converting it to ASP.NET 3.5 and everything builds just fine except now when I try to load the homepage, I get a 404 Error saying:
The resource cannot be found.

 Description: HTTP 404. The resource you are looking for (or one of its dependencies)      could have been removed, had its name changed, or is temporarily unavailable.  Please      review the following URL and make sure that it is spelled correctly.

 Requested URL: /home

 Version Information: Microsoft .NET Framework Version:2.0.50727.4927; ASP.NET
 Version:2.0.50727.4927

Anyone know why this is?
Thank You for Your help.
TheLorax

A: From my experience with ASP.NET MVC, I've seen that a Default.aspx page is required for IIS to function correctly. I'm using the page that was included in the ASP.NET MVC 1 template. Unfortunately, the ASP.NET MVC 2 does not include this page (to the best of my knowledge), so you should add the following to your project:
Default.aspx:
<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="YourNamespace._Default" %>

<%-- Please do not delete this file. It is used to ensure that ASP.NET MVC is activated by IIS when a user makes a "/" request to the server. --%>

Default.aspx.cs:
using System.Web;
using System.Web.Mvc;
using System.Web.UI;

namespace YourNamespace
{
    public partial class _Default : Page
    {
        public void Page_Load(object sender, System.EventArgs e)
        {
            // Change the current path so that the Routing handler can correctly interpret
            // the request, then restore the original path so that the OutputCache module
            // can correctly process the response (if caching is enabled).

            string originalPath = Request.Path;
            HttpContext.Current.RewritePath(Request.ApplicationPath, false);
            IHttpHandler httpHandler = new MvcHttpHandler();
            httpHandler.ProcessRequest(HttpContext.Current);
            HttpContext.Current.RewritePath(originalPath, false);
        }
    }
}

A: Simple solution: switch to Visual Studio 2008 + SP1 + MVC 1. This is the released/supported combination. If your host doesn't install the MVC assemblies then they can be deployed side by side, you will need to ensure your host has .NET 3.5 SP1.
If I recall correctly VS2010 B2 includes MVC***2*** B2, but not MVC***1***.

A: It may be that the MVC assemblies are not installed on the server you are publishing to.  Try going into your MVC project, then under resources and change the property copy local to true for all MVC specific assemblies (or just highlight everything under references and set this property to true).


text:
Q: What is the format of azure monitor metric alert conditions in Azure CLI? The documentation for az monitor metrics alert create does not explain the format used for --conditon parameter. Seems to me the value ends up being passed as allOf argument to constructor of MetricAlertSingleResourceMultipleMetricCriteria class as seen in the Azure CLI source for metric_alert.py. However this would mean this is a list of MetricCritieria, but the documentation examples are as follows:
--condition "total transactions > 5 where ResponseType includes Success"
--condition "avg SuccessE2ELatency > 250 where ApiName includes GetBlob or PutBlob"

which doesn't look like a valid format for the list[MetricCritieria]

A: The detailed format description is given upon calling with the -h flag:
PS> az monitor metrics alert create -h
Command
    az monitor metrics alert create : Create a metric-based alert rule.

Arguments
    --condition         [Required] : The condition which triggers the rule.
        Usage:  --conditon {avg,min,max,total,count} [NAMESPACE.]METRIC {=,!=,>,>=,<,<=} THRESHOLD
                           [where DIMENSION {includes,excludes} VALUE [or VALUE ...]
                           [and   DIMENSION {includes,excludes} VALUE [or VALUE ...] ...]]

        Dimensions can be queried by adding the 'where' keyword and multiple dimensions can be
        queried by combining them with the 'and' keyword.

        Values for METRIC, DIMENSION and appropriate THRESHOLD values can be obtained from `az
        monitor metrics list-definition` command.

        Multiple conditons can be specified by using more than one `--condition` argument.

A: If you have a custom metrics which contains dot '.' or colon ':' then it is not so easy and I did not find any documentation. Fortunately what I found was a metric condition parser rule where you can read how the condition should look like.
So for example my metric is called Ori.EventHub:DeliveryTime, so the condition switch should look like:
az monitor metrics alert create --condition "avg Azure.ApplicationInsights.'Ori.EventHub:DeliveryTime' > 100" .


text:
Q: Add the camera on current position of the user on the map I added this code in my viewController
import UIKit
import CoreLocation
import GoogleMaps

class CourseClass2: UIViewController, UITableViewDelegate, UITableViewDataSource, UINavigationControllerDelegate {

@IBOutlet weak var mapView: GMSMapView!

}

and this extension
extension CourseClass2:  CLLocationManagerDelegate {

    func determineMyCurrentLocation() {

        guard currentLocation == nil else {
            return
        }

        locationManager = CLLocationManager()
        locationManager?.delegate = self
        locationManager?.desiredAccuracy = kCLLocationAccuracyBest
        locationManager?.requestWhenInUseAuthorization()
    }

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        let userLocation:CLLocation = locations[0] as CLLocation

        manager.stopUpdatingLocation()

        print("user latitude = \(userLocation.coordinate.latitude)")
        print("user longitude = \(userLocation.coordinate.longitude)")

        didReceiveUserLocation(userLocation)
    }

    func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        print("Error \(error)")
        errorGettingCurrentLocation(error.localizedDescription)
    }

    public func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status == .authorizedWhenInUse || status == .authorizedAlways {
            locationManager?.startUpdatingLocation()
            //locationManager.startUpdatingHeading()
        } else if status == .denied || status == .restricted {
            errorGettingCurrentLocation("Location access denied")
        }
    }

    func errorGettingCurrentLocation(_ errorMessage:String) {
        let alert = UIAlertController.init(title: "Error", message: errorMessage, preferredStyle: .alert)
        alert.addAction(UIAlertAction.init(title: "Cancel", style: .cancel, handler: nil))
        present(alert, animated: true, completion: nil)
}
}

to get the user location. Now i would like to add in the viewDidLoad of my controller a camera like  let camera = GMSCameraPosition.camera(withLatitude: , longitude: , zoom: 14) on the user position, but how can i do to use in this line the latitude and longitude of my user current position that i found with my extension?

A: You need to call locationManager.startUpdatingLocation() in viewDidLoad() where locationManager is CLLocationManager object. As soon as your current location is retrieved, didUpdateLocations delegate method is called where you can set the camera position as follows:
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    let userLocation = locations.last

    let location = GMSCameraPosition.camera(withLatitude: userLocation!.coordinate.latitude, longitude: userLocation!.coordinate.longitude, zoom: 16.0)

    mapView.animate(to: location)

}


text:
Q: How can I see session table in Visual Studio? In a ASP.NET Project, is it possible to see all the data in session by visual studio. I mean like the way we can see Variable's values in locals or watch windows when runtime hits a Breakpoint.

A:
It's pretty simple to inspect the session during debug. Just put a breakpoint in your code and just >highlight your Session code (eg. highlight: Session["first_name"]) then right click and select >QuickWatch....
This will setup up a watch on your Session for the value you had defined. You can also inspect other >Session elements by adjusting the Expression field in the QuickWatch window and clicking the Reevaluate >button

How to view Session Variables in Visual Studio 2008 Debugger?
You can also check session data on the client-side


text:
Q: Try to click a togglebutton and make the other togglebutton unchecked. Android Studio-Kotlin So, hello guys,in android-studio, I've got a horizontal-linear-layout and also got two buttons in it side by side which are togglebuttons, lets call them X and Y, what I'm trying to do is, once I click X, X becomes checked then when I try to click Y, Y becomes checked but X becomes unchecked back, so how would I do it? I try to do this but eventually not worked.
    if (beginnerButton.isChecked) {
        balleButton.isChecked = false
    }
    else if (balleButton.isChecked) {
        beginnerButton. = false
    }

A: define OnClick in XML like below
<ToggleButton
        android:id="@+id/beginnerButton"
        android:layout_width="wrap_content"
        android:onClick="clickBeginnerButton"
        android:layout_height="wrap_content"
        />

    <ToggleButton
        android:id="@+id/balleButton"
        android:onClick="clickBalleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        />

and in kotlin:
  public fun clickBeginnerButton(view: View) {
    balleButton.isChecked = false
  }

  public fun clickBalleButton(view: View) {
    beginnerButton.isChecked = false
  }

Its will working as your expected
Hope this helps


text:
Q: How to send tweet to target user? I have some code:
  internal TwitterResponse<TwitterStatus> UpdateTweet(string Tweet)
        {
            TwitterResponse<TwitterStatus> tweetResponse = null;

             OAuthTokens tokens = new OAuthTokens();

             tokens.AccessToken = accessToken;
             tokens.AccessTokenSecret = accessTokenSecret;
             tokens.ConsumerKey = consumerKey;
             tokens.ConsumerSecret = consumerSecret;

             tweetResponse = TwitterStatus.Update(tokens, Tweet);

            return tweetResponse;
        }

This code send tweet to authenticated user but I need send to assigned user.

A: The tweet text should begin with "@<username>" to direct a tweet to a specific person. Keep in mind that this is still a public tweet (provided that the authenticated user is not protected). To send a private message from the authenticated user to another user, you can use the TwitterDirectMessage class or prefix a tweet with "d <username>".
So, to send a public tweet that is directed to a user, do like: @twit_er_izer Just wanted to say hello.
To send a direct message, do like: d twit_er_izer Just wanted to say hello.
(Or use the direct message class.)


text:
Q: How can I bind mutually exclusive MenuItems with Mutually exclusive radio buttons in user control I have a Mainwindow with a mutually exclusive set of menu items. These menu items move a user control over three column positions in a grid. The user control has three mutually exclusive radio buttons that also move the user control over three column positions. Currently, the menu items set the user controls position independently of the radio buttons in the user control and vis-versa. What I want to do is bind each menu item with the respective radio button. For example, if the Left Position radio button is selected, I want to have the left position menu item checked and vis-versa. How can I bind the radio buttons to their respective menu items?
MainWindow.xaml
<Window x:Class="WpfApp1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    xmlns:local="clr-namespace:WpfApp1"
    xmlns:uc="clr-namespace:WpfApp1"
    mc:Ignorable="d"
    Title="MainWindow" Height="450" Width="800">
<Window.DataContext>
    <!-- Declaratively create an instance of MainViewViewModel -->
    <local:MainWindowViewModel />
</Window.DataContext>
<Grid ShowGridLines="True">
    <Grid.RowDefinitions>
        <RowDefinition Height="Auto" />
        <RowDefinition />
    </Grid.RowDefinitions>
    <Grid.ColumnDefinitions>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
        <ColumnDefinition Width="*"/>
    </Grid.ColumnDefinitions>
    <uc:UserControl1 Grid.Row="1" Grid.Column="{Binding Position}"/>
    <Menu>
        <MenuItem Header="Position">
            <MenuItem
                local:MenuItemExtensions.GroupName="groupMenuBarPosition"
                Header="Left Postion"
                x:Name="leftMenuItem"
                IsChecked="{Binding Left, Mode=TwoWay}"
                IsCheckable="True"/>
            <MenuItem
                local:MenuItemExtensions.GroupName="groupMenuBarPosition"
                Header="Middle Postion"
                x:Name="middleMenuItem"
                IsChecked="{Binding Middle, Mode=TwoWay}"
                IsCheckable="True" />
            <MenuItem
                local:MenuItemExtensions.GroupName="groupMenuBarPosition"
                Header="Right Postion"
                x:Name="rightMenuItem"
                IsChecked="{Binding Right, Mode=TwoWay}"
                IsCheckable="True" />
        </MenuItem>
    </Menu>
</Grid>

Extensions.cs
using System.Windows;
using System.Windows.Controls;

namespace WpfApp1
{
public class MenuItemExtensions : DependencyObject
{
    public static MenuItem currentselect;

    public static Dictionary<MenuItem, String> ElementToGroupNames = new Dictionary<MenuItem, String>();

    public static readonly DependencyProperty GroupNameProperty =
        DependencyProperty.RegisterAttached("GroupName",
                                     typeof(String),
                                     typeof(MenuItemExtensions),
                                     new PropertyMetadata(String.Empty, OnGroupNameChanged));

    public static void SetGroupName(MenuItem element, String value)
    {
        element.SetValue(GroupNameProperty, value);
    }

    public static String GetGroupName(MenuItem element)
    {
        return element.GetValue(GroupNameProperty).ToString();
    }

    private static void OnGroupNameChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        //Add an entry to the group name collection
        var menuItem = d as MenuItem;

        if (menuItem != null)
        {
            String newGroupName = e.NewValue.ToString();
            String oldGroupName = e.OldValue.ToString();
            if (String.IsNullOrEmpty(newGroupName))
            {
                //Removing the toggle button from grouping
                RemoveCheckboxFromGrouping(menuItem);
            }
            else
            {
                //Switching to a new group
                if (newGroupName != oldGroupName)
                {
                    if (!String.IsNullOrEmpty(oldGroupName))
                    {
                        //Remove the old group mapping
                        RemoveCheckboxFromGrouping(menuItem);
                    }
                    ElementToGroupNames.Add(menuItem, e.NewValue.ToString());
                    menuItem.Checked += MenuItemChecked;
                    menuItem.Unchecked += MenuItemUnchecked;
                }
            }
        }
    }

    private static void RemoveCheckboxFromGrouping(MenuItem checkBox)
    {
        ElementToGroupNames.Remove(checkBox);
        checkBox.Checked -= MenuItemChecked;
        checkBox.Unchecked -= MenuItemUnchecked;
    }

    private static void MenuItemUnchecked(object sender, RoutedEventArgs e)
    {
        var menuItem = e.OriginalSource as MenuItem;

        if (currentselect != null)
        {
            if (currentselect == menuItem && currentselect.GetValue(GroupNameProperty).ToString() == GetGroupName(menuItem))
            {
                menuItem.IsChecked = true;
            }
        }
    }

    static void MenuItemChecked(object sender, RoutedEventArgs e)
    {
        var menuItem = e.OriginalSource as MenuItem;
        currentselect = menuItem;
        foreach (var item in ElementToGroupNames)
        {
            if (item.Key != menuItem && item.Value == GetGroupName(menuItem))
            {
                item.Key.IsChecked = false;
            }
        }
    }
}
}

MainWindowViewModel.cs
using System;
using System.ComponentModel;
using System.Runtime.CompilerServices;

namespace WpfApp1
{
public class MainWindowViewModel : INotifyPropertyChanged
{
    public MainWindowViewModel()
    {
        _position = 1;
    }

    private int _position;
    private bool _left;
    private bool _middle;
    private bool _right;

    public bool Left
    {
        get
        {
            return _left;
        }
        set
        {
            _left = value;
            if (_left) { Position = 0; }
        }
    }
    public bool Middle
    {
        get
        {
            return _middle;
        }
        set
        {
            _middle = value;
            if (_middle) { Position = 1; }
        }
    }
    public bool Right
    {
        get
        {
            return _right;
        }
        set
        {
            _right = value;
            if (_right) { Position = 2; }
        }
    }

    public int Position
    {
        get
        {
            return _position;
        }
        set
        {
            _position = value;
            RaisePropertyChanged();
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    public void RaisePropertyChanged([CallerMemberName] String propertyName = "")
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}
}

UserControl1.xaml
<UserControl x:Class="WpfApp1.UserControl1"
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
         xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
         xmlns:local="clr-namespace:WpfApp1"
         mc:Ignorable="d"
         x:Name="positionUC"
         Background="Aqua">
<StackPanel Orientation="Vertical" >
    <RadioButton
        GroupName="groupPosition"
        IsChecked="{Binding Left}">
        <TextBlock Text="Left Position"/>
    </RadioButton>
    <RadioButton
        GroupName="groupPosition"
        IsChecked="{Binding Middle}">
        <TextBlock Text="Middle Position"/>
    </RadioButton>
    <RadioButton
        GroupName="groupPosition"
        IsChecked="{Binding Right}">
        <TextBlock Text="Right Position"/>
    </RadioButton>
</StackPanel>

revised MainWindowViemModel.cs
using MvvmFoundation.Wpf;

namespace WpfApp1
{
public class MainWindowViewModel : ObservableObject
{
    public MainWindowViewModel()
    {
        Middle = true;
    }

    private int _position;
    private bool _left;
    private bool _middle;
    private bool _right;

    public bool Left
    {
        get
        {
            return _left;
        }
        set
        {
            _left = value;
            if (_left)
            {
                Position = 0;
                base.RaisePropertyChanged("Left");
            }
        }
    }

    public bool Middle
    {
        get
        {
            return _middle;
        }
        set
        {
            _middle = value;
            if (_middle)
            {
                Position = 1;
                base.RaisePropertyChanged("Middle");
            }
        }
    }

    public bool Right
    {
        get
        {
            return _right;
        }
        set
        {
            _right = value;
            if (_right)
            { Position = 2;
                base.RaisePropertyChanged("Right");
            }
        }
    }

    public int Position
    {
        get
        {
            return _position;
        }
        set
        {
            _position = value;
            base.RaisePropertyChanged("Position");
        }
    }
}
}


text:
Q: Convert decimal <--> binary with T-SQL How can I convert binary (base 2 stored as varchar) into decimal (base 10 stored as int or bigint) and the other way around, using T-SQL?
Example results:

*

*7 (dec) <--> 111 (bin)

*136 (dec) <--> 10001000 (bin)

*2123942362 (dec) <--> 1111110100110001100100111011010 (bin)

A: This answer can handle bigint
Convert to bit(varchar containing 1 and 0)
DECLARE @input BIGINT = 9223372036854775807

;WITH N(N)AS
(
  SELECT top 63
    POWER(cast(2 as bigint),
      ROW_NUMBER()over(ORDER BY (SELECT 1))-1)
  FROM
    (VALUES(1),(1),(1),(1))M(a),
    (VALUES(1),(1),(1),(1))L(a),
    (VALUES(1),(1),(1),(1))K(a)
)
SELECT
  COALESCE
  (
    REVERSE
    (
      (
        SELECT CAST(@input/N%2 as CHAR(1))
        FROM N
        WHERE N <= @input
        for xml path(''), type
      ).value('.', 'varchar(max)')
    )
    , '0'
  )

Result:
111111111111111111111111111111111111111111111111111111111111111

Convert varchar containing bit values to bigint
DECLARE @input varchar(max) =
  '111111111111111111111111111111111111111111111111111111111111111'

;WITH N(V) AS
(
  SELECT
    ROW_NUMBER()over(ORDER BY (SELECT 1))
  FROM
    (VALUES(1),(1),(1),(1))M(a),
    (VALUES(1),(1),(1),(1))L(a),
    (VALUES(1),(1),(1),(1))K(a)
)
SELECT SUM(SUBSTRING(REVERSE(@input),V,1)*POWER(CAST(2 as BIGINT), V-1))
FROM   N
WHERE  V <= LEN(@input)

Result:
9223372036854775807

A: You could get integers from master.dbo.spt_values and use them as the weight for each digit.
use master;

declare @binary     as  varchar(max)    =   '1111110100110001100100111011010';
declare @decimal    as  int             =   2123942362;

--binary --> decimal
select
    @binary                                                     as  binaryValue
,   sum(    substring(@binary,len(@binary)-position.number,1)
        *   power(2,position.number) )                          as  decimalValue
FROM    dbo.spt_values  AS  position
WHERE   position."type" =   'P'     --integers
    and position.number <=  len(@binary)-1
;

--decimal --> binary
select
    @decimal                                                    as  decimalValue
,   (
        SELECT  CAST(sign(@decimal & power(2,position.number)) as varchar(max))
        FROM    dbo.spt_values  AS  position
        WHERE   position."type" =   'P'     --integers
            and position.number <=  isnull(LOG(nullif(@decimal,0),2),0)
        order by    position.number desc
        FOR XML PATH(''),TYPE
    ).value('(./text())[1]','VARCHAR(8000)')                    as  binaryValue

A: You can create two functions as below and then create a wrapper function that would have a bit input to say which format are you trying to convert.
Converting binary to decimal
CREATE FUNCTION [dbo].[BinaryToDecimal]
(
    @Input varchar(255)
)
RETURNS bigint
AS
BEGIN

    DECLARE @Cnt tinyint = 1
    DECLARE @Len tinyint = LEN(@Input)
    DECLARE @Output bigint = CAST(SUBSTRING(@Input, @Len, 1) AS bigint)

    WHILE(@Cnt < @Len) BEGIN
        SET @Output = @Output + POWER(CAST(SUBSTRING(@Input, @Len - @Cnt, 1) * 2 AS bigint), @Cnt)

        SET @Cnt = @Cnt + 1
    END

    RETURN @Output

END

Converting decimal to binary
CREATE FUNCTION [dbo].[DecimalToBinary]
(
    @Input bigint
)
RETURNS varchar(255)
AS
BEGIN

    DECLARE @Output varchar(255) = ''

    WHILE @Input > 0 BEGIN

        SET @Output = @Output + CAST((@Input % 2) AS varchar)
        SET @Input = @Input / 2

    END

    RETURN REVERSE(@Output)

END

Hope this helps


text:
Q: Enable user access to all DBs and tables in MS SQL server managment I create a new user in MS SQL via MS SQL server managment in / SECURITY / LOGINS part.
User is set and can connect , however dispite the fact he see all databases he can get data just from one of them and from rest he can get just structure.
Is there some special settings to enable full access to specifc user to all DBs?
Thanks

A: Unless the user is given the system adminstrator (sa) role, you will need to add a user to each database which is mapped to the login and which gives the correct permissions just for that database.
Be very careful creating users with global access to databases, it is the start of a slippery slope to a major hack!

A: As mentioned by Lukos you will need to give them access to each database individually under the "User Mapping" tab in Logins. I would do it this way and give them the least permissions that they require rather than just blanket giving them sysadmin.
One extra thing to note is if you give them the required access (datareader or owner etc...) to the model database any new databases that you create the user will automatically have the same permissions applied to the new databases.


text:
Q: Orthonormal basis of linear subspace For a rectangular matrix $M_{i\mu}$ where $i=1,...,m$ and $\mu=1,...,n$ and $n>m$, consider the following $n-m$ dimensional linear subspace of $\mathbf{R}^n$:
$$V=\{\vec x\in \mathbf{R}^n:M\vec x=0\}.$$
Clearly $V$ is spanned by $n-m$ orthonormal vectors $\{\vec e_1,...,\vec e_{n-m}\}$. How can one find an explicit set of such vectors given $M_{i\mu}$?


text:
Q: Cannot set CssClass property in inherited Label / TextBox WebControl I have created a very simple custom control:
     [assembly: System.Web.UI.TagPrefix("CustomMultiLineTextBox", "evo")]
        public class CustomMultiLineTextBox :
            System.Web.UI.WebControls.TextBox
        {

            public override int Rows
            {
                get
                {
                    return 5;
                }
            }

            public override System.Web.UI.WebControls.TextBoxMode TextMode
            {
                get
                {
                    return System.Web.UI.WebControls.TextBoxMode.MultiLine;
                }
            }
    public override string CssClass
            {
                get
                {
                    return "textboxStyle";
                }
                set
                {
//base.CssClass = "textboxStyle";
                    base.CssClass = value;
                }
            }
        }
        }

However, when I drop this control onto my aspx page the CssClass does not seem to be applied. The TextMode and Rows property are set correctly.
    <evo:CustomMultiLineTextBox ID="txtTrainingNeeds" runat="server">
</evo:CustomMultiLineTextBox>

Only if I add CssClass="textboxStyle" to markup will the CssClass be applied.
Any suggestions?
Thanks in advance

A: Since it doesn't look like you're modifying behavior, only data, I would set the properties to the values you want in the constructor instead of overriding the properties themselves.
public CustomMultiLineTextBox()
{
    Rows = 5;
    TextBoxMode = System.Web.UI.WebControls.TextBoxMode.MultiLine;
    CssClass = "textboxStyle";
}


text:
Q: Smooth same screen scrolling I want to make it so I can click the link on my page and have it smoothly transition to the target, if anyone can help I would be very grateful.
Here is my button link,

Read More

And below is the target,

My Work

How are trends in colour usage formulated in contemporary culture?

I want it so I can click the button and have it scroll down smoothly.
Thanks.


text:
Q: Creating YouTube playlist in real time Is there any possibility to create a YouTube playlist that will work in a real time.
All viewers will watch the same content at the same time as the traditional television.
https://viloud.tv offers this feature, but I wonder is there some script or way of embedding to achive the same thing.

A: You will probably have to start a live stream.


text:
Q: "To live" vs "for living in" I was wondering which is the correct form for expressing this simple concept in a formal way: " my hometown is a good place FOR LIVING IN / TO LIVE ".
Grammatically I would say that "my hometown is a good place for living in" is correct, but I see a lot of people that write "my hometown is a good place to live".

A:
"My hometown is a good place for living in."
"My hometown is a good place to live".

They are both grammatically correct and it could be argued that the meaning is the same.
For me there is a difference.
"My hometown is a good place for living in."  This means that my hometown has good facilities: cinemas, music venues, sports arenas, restaurants etc.  The town supports the everyday activities of living.
"My hometown is a good place to live". This could mean the same but to me it means that it is good because it is in a good location or is situated somewhere important. For example:
"My hometown is a good place to live because it is near the university that I want to attend. I'll be able to visit my parents and friends regularly".


text:
Q: Java Clip (Clip.Stop not working) I make a video games on eclipse and i will make a menu song and stop the song but clip.stop(); not work i don't know why please help me. The menu song Clip.play();and Clip.loop(Clip.LOOP_CONTINUOUSLY); work but i can stop the song only if i close my game.
package Audio;

import java.io.File;

import javax.sound.sampled.AudioInputStream;
import javax.sound.sampled.AudioSystem;
import javax.sound.sampled.Clip;

import sun.audio.AudioPlayer;

public class MenuAudio {

public static boolean stopped = false;

public static void Start(){
System.out.println(stopped);
try{
File f = new File("C:\\Games\\Test\\Assets\\sound\\menu\\menuLoop.wav");
Clip clip = AudioSystem.getClip();
AudioInputStream ais = AudioSystem.getAudioInputStream(f);
clip.open(ais);
clip.start();
clip.loop(Clip.LOOP_CONTINUOUSLY);
AudioPlayer.player.stop(ais);
if(stopped == true) // work
{
    clip.stop(); //not work
    clip.close(); //not work
    stopped = false; //work
    System.out.println(stopped);//work
}

}catch(Exception exception){System.out.println("WAV FILES NOT FOUND!! ");}

}

}

boolean stopped return to true in another class whit this code
    int test = 0;
 //code useless
    ........
 //code useless
    MenuAudio.Start(); // play the sound
 //code useless
    ........
 //code useless

if(Keyboard.isKeyDown(Keyboard.KEY_LEFT)){  //work
            test = 0;
        }

        if(test == 0 && Keyboard.isKeyDown(Keyboard.KEY_RIGHT)){ //work
            MenuAudio.stopped = true;
            MenuAudio.Start();
            test = 1;
        }

this code is work
the console return that :
true
false
if i press the key Left after Right.
I don't know why Clip.stop(); not work.
(Sorry for the bad english)

A: There are a number of confusing things in your code. For one, I think sun.audio.AudioPlayer is deprecated. I don't see it listed in the Java 7 API. I'm pretty sure it has no role to play in controlling a javax.audio.Clip in the code you have written.
There is more info on sun.audio.AudioPlayer at this
past StackOverflow question link.
Another source of confusion is your naming convention. If the first letter is a capital letter, we expect this to be a Class, not a variable or method. Fixing the indentations would also make it a little easier to read.
I don't understand why you are setting a variable to false and then calling a routine to both load and start and stop the playback in quick succession.
Clip's were designed to be opened separately from when they are played. As written, your code has to load the entire clip into RAM before the start command will execute. If you load the Clip beforehand, perhaps in a constructor for MenuAudio, then you could consider a plan such as passing the clip variable to any method responsible for starting or stopping it.


text:
Q: c++ Parameters not passed into operator overload< When creating an operator overload for a class "State", the operator that i've overloaded does not have any member variables initialized.
    bool operator<(const State m)const
    {
       return (mDist < m.mDist);
    }

When adding a state into a priority queue which calls this operator, the value for mDist is not initialized
This is the code that begins the process
int row=0;
int col=0;
current.getBlank(row, col); // gets position of 0 in 3x3 int array

if (row > 0)
{
    //creates a new state with current 3x3 array and postion of 0 as member variables
    State u(current, row, col);
    u.swapUp();           // swaps 0 with position above it
    //n.findMDist(goal);  //calculates Manhattan distance from goal state
    nextMoves.push(u);    //push into queue
}

Any advice on what i should check that may cause the values to mot be passed to the operator overload?
Edit :
This is my state class.
#pragma once
#ifndef STATE_H_
#define STATE_H_
#include<iostream>
#include <vector>

using namespace std;

const int SIZE = 3;

class State
{
private:
    int board[SIZE][SIZE];
    int blankRow;
    int blankCol;
    State *parent;
    State *goal;

public:
    State()
    {
        int counter = 0;
        for (int i = 0; i < SIZE; i++)
            for (int j = 0; j < SIZE; j++)
            {
                setValue(i, j, counter);
                counter++;
            }
        int mDist = 0;
    }

    State(const State& s)
    {
        for (int i = 0; i < SIZE; i++)
            for (int j = 0; j < SIZE; j++)
                board[i][j] = s.getValue(i, j);
    }
    State(const State& s, int r, int c, State *g)
    {
        for (int i = 0; i < SIZE; i++)
            for (int j = 0; j < SIZE; j++)
                board[i][j] = s.getValue(i, j);
        blankRow = r;
        blankCol = c;
        goal = g;
        findMDist(*goal);
    }

    //get
    int mDist;

    //find
    void findMDist(State Goal);

    bool operator<( State m)const
    {
        return (mDist < m.mDist);
    }

};

#endif

This is where mDist is implemented
void Game::next() {

int row=0;
int col=0;
current.getBlank(row, col);

if (row > 0)
{
    State u(current, row, col);
    u.swapUp();
    n.findMDist(goal);
    nextMoves.push(u);
}
if (row < 2)
{
    State d(current, row, col);
    d.swapDown();
    n.findMDist(goal);
    nextMoves.push(d);
}
if (col < 2)
{
    State n(current, row, col);
    n.swapRight();
    n.findMDist(goal);
    nextMoves.push(n);
}
if (col > 0)
{
    State n(current, row, col);
    n.swapLeft();
    n.findMDist(goal);
    nextMoves.push(n);
}
}

A: bool operator<( State m)const

This passes by value and hence invokes the copy constructor. Here that is:
State(const State& s)
{
    for (int i = 0; i < SIZE; i++)
        for (int j = 0; j < SIZE; j++)
            board[i][j] = s.getValue(i, j);
}

This only copies the board. It completely omits to do its job properly by copying all the other member variables, including the offending mDist.
So, operator< ends up working on an incomplete copy, in which multiple member variables are uninitialised, so you invoke undefined behaviour by reading them subsequently.
The fixes are:

*

*Implement a proper copy constructor that does its job, i.e. copies all member variables and results in all externally visible state being the same after it's done.

*Don't pass by value to the copy constructor, though, because that's a waste of resources and bad semantics. Pass by const& instead.

A:
Any advice on what i should check that may cause the values to mot be
  passed to the operator overload?

When you pass a copy of State to you operator<, the mDist is not copied. You can add mDist = s.mDist; to your copy constructor (actually you might want to add it anyway), but it would be better to pass State by const ref to the comparator:
bool operator<(State const &m) const
{
    return (mDist < m.mDist);
}

Also in your constructor you have local variable initialisation int mDist = 0; which makes no sense as it goes out of scope almost immediately. I think you meant mDist = 0; this will take care of your currently uninitialised member mDist.


text:
Q: ¿Sumatorio de enlaces en bipartite? Dado el siguiente código de una red bipartita con enlaces pesados:
prueba<-read.csv("matriz_prueba.csv",header=TRUE,sep=";")
head(prueba)

  PAIS_ORIGEN     AFG     ETH     TZA     PAK     VNM
1         USA 6686.77 1726.46  834.16 2044.88  192.19
2          EU  609.50  396.27  298.63  244.11   84.17
3         IDA  424.68 1637.79 1461.09 1150.64 1939.73
4         FRA   95.65   45.01   26.00   20.54  341.29
5         JPN  867.20  154.99  182.21  272.97 1622.79
6         DEU  754.42  164.52  207.36  233.14  194.22

Me gustaría saber si hay alguna función en la librería bipartite que me sume el peso de todos los enlaces de un nodo y me devuelva el sumatorio de esos pesos para cada nodo, tanto en fila como en columna.
Ejemplo: (USA-AFG)+(USA-ETH)+...+(USA-VNM) => USA: 11.484,46
Gracias!

A: Lo más simple es usar rowSums(), solo hay que descartar las columna PAIS_ORIGEN  de la suma:
prueba$Total <- rowSums(prueba[,-1])
prueba

  PAIS_ORIGEN     AFG     ETH     TZA     PAK     VNM    Total
1         USA 6686.77 1726.46  834.16 2044.88  192.19 11484.46
2          EU  609.50  396.27  298.63  244.11   84.17  1632.68
3         IDA  424.68 1637.79 1461.09 1150.64 1939.73  6613.93
4         FRA   95.65   45.01   26.00   20.54  341.29   528.49
5         JPN  867.20  154.99  182.21  272.97 1622.79  3100.16
6         DEU  754.42  164.52  207.36  233.14  194.22  1553.66

Por cierto, esto no es algo particular de bipartite, sino una  solución más general que aplica a cualquier estructura tabular tipo matriz o data.frame


text:
Q: Does JCR (java content repository) store videos? Does JCR (java content repository) store videos ?
The reason I am asking, I saw one of the open source cms called Hippo and they embed videos from vimeo in their website rather than having stored it on content repository.
I appreciate any input.
Thanks,
Sri

A: Yes this is possible to do. In fact JCR can store binary data including videos,images, documents etc...Then,you will need just to read the content of the binary and stream it in a video reader.
You can watch a simple usage on eXo Platform they are using JCR as their storage and they are providing a video player on their Social streams and their JCR browser (Content Explorer)

A: Embedding videos from online services can be useful to avoid the bandwidth and infrastructure costs of streaming videos yourself. That being said, as Ali says JCR can store any binary, but you'll need to check the performance of a given JCR implementation against your use cases to make an informed decision.


text:
Q: Download a file from NestJS (without saving it ) I want to make client download a pdf file generated from my back-end. I am using the pdfkit-lib to generate my pdf file. From the NestJs documentation, I decided to use StreamableFile from a DuplexStream (pdfkit-lib works with a WritableStream and StreamableFile with a ReadableStream) :
@Get('/generate-file')
generateFile(): StreamableFile {
  const fileStream = new stream.Duplex();
  const doc = new pdfkit()
  doc.pipe(fileStream);
  // do stuff
  doc.end();
  return new StreamableFile(fileStream);
}

But I end up with this error :
Error: The _write() method is not implemented
    at new NodeError (node:internal/errors:371:5)
    at Duplex.Writable._write (node:internal/streams/writable:588:11)
    at writeOrBuffer (node:internal/streams/writable:389:12)
    at _write (node:internal/streams/writable:330:10)
    at Duplex.Writable.write (node:internal/streams/writable:334:10)
    at PDFDocument.ondata (node:internal/streams/readable:754:22)
    at PDFDocument.emit (node:events:390:28)
    at PDFDocument.Readable.read (node:internal/streams/readable:527:10)
    at flow (node:internal/streams/readable:1012:34)
    at resume_ (node:internal/streams/readable:993:3)

It can make it works with fs.createWriteStream and fs.createReadStream but I don't want to create the file on my server (and there is no callback on StreamableFile to delete). Any idea ?

A: It should be possible to do this without the overhead of writing to a temporary file. You can try streaming directly into the res stream, something like:
@Get('/generate-file')
generateFile(@Res() res: Response): void {
   const filename = 'SomeFileName.pdf';
   const doc = new PDFDocument({ bufferPages: true });
   const stream = res.writeHead(200, {
    'Content-Type': 'application/pdf',
    'Content-disposition': `attachment;filename=${filename}.pdf`,
   });
   doc.on('data', (chunk) => stream.write(chunk));
   doc.on('end', () => stream.end());

   doc
     .font('Times-Roman')
     .fontSize(12)
     .text(`just a test`);
   doc.end();
 }

A: I end up using fs.createWriteStream and fs.createReadStream by deleting the created file :
@Get('/generate-file')
generateFile(@Res({ passthrough: true }) res: Response): StreamableFile {
  const fileName = '';
  const filePath = '';

  const doc = new pdfkit()
  doc.pipe(fs.createWriteStream(filePath));
  // do stuff
  doc.end();

  const fileStream = fs.createReadStream(filePath);

  fileStream.on('end', () => {
    try {
      fs.unlinkSync(filePath);
    } catch (error) {
      throw new BadRequestException('An error occurred while removing the file.');
    }
  });

  res.set({
    'Content-Type': 'application/pdf',
    'Content-Disposition': `attachment; filename="${fileName}"`,
  });
  return new StreamableFile(fileStream);
}


text:
Q: Missing Xcode dependency: Python module "six" I've installed Python module "six" and it prints the same error:
I've installed and i get the same error
How can I fix this?

A: Please run this 2 line of commend
brew reinstall python@2
pip install six

Then
pip install six

Make sure you have downloaded brew


text:
Q: WP_Query to display posts by category in Wordpress (in custom post types) Hej, I'll keep it short. I want to output this in a WP loop:
Support
    Category1
      -Post1
      -Post2
    Category2
      -PostA
      -PostB
      -PostC

So I want to order posts by category that are located in a custom post type - support (created thanks to Types plugin, link: ujeb.se/A4zqZ ).
I have this:
<?php
$args = array('post_type' => 'support');
$query = new WP_Query($args);

while($query -> have_posts()) : $query -> the_post(); ?>

<?php the_category(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php the_content(); ?>

<?php endwhile; ?>

My $query stores all the necessary posts from my custom post type (support) but I have a problem with displaying them by category. I believe I need some sort of foreach but I can't really figure it out. Any suggestions?
/edit/
The current display looks like this:
Support, Category1
Post1
---
Support, Category2
PostA
---
Support, Category1
Post2

etc.

A: Here is how you do it. You needed a foreach loop to cycle through the categories.
<?php
$cats = get_categories();

foreach ($cats as $cat) {
$args = array(
'post_type' => 'support',
'tax_query' => array(
    array(
        'taxonomy' => 'category',
        'field'    => 'term_id',
        'terms'    => $cat->cat_ID,
        ),
    ),
);
$query = new WP_Query($args);

if ( $query->have_posts() ): ?>

<?php echo $cat->cat_name ; ?>
 <?

   while($query -> have_posts()) : $query -> the_post(); ?>

<a href="<?php the_permalink(); ?>"><?php the_title(); ?>

<?php the_content(); ?>
 <?php
   endwhile;
endif;

// Added this now
wp_reset_query() ;
}

A: this work for me:
   $posts = new WP_Query(array(
        'category_name' => 'news,
        'post_status' => 'publish',
        'post_type' => 'post',
        'posts_per_page' => 6,
        ));


text:
Q: Closing value grouping by last week's data I'm working on the base below, and I need to group the close variable, grouping the last day of each week, by month and year, the base I'm working on has data from 2005 to 2017, below I'm just leaving a sample.
date        close   year   month  day    quarter      week
2016-12-23   961    2016    12    23      4        51
2016-12-22   928    2016    12    22      4        51
2016-12-21   926    2016    12    21      4        51
2016-12-20   914    2016    12    20      4        51
2016-12-19   927    2016    12    19      4        51
2016-12-16   946    2016    12    16      4        50
2016-12-15   966    2016    12    15      4        50
2016-12-14   1003   2016    12    14      4        50
2016-12-13   1052   2016    12    13      4        50
2016-12-12   1069   2016    12    12      4        50
2016-12-23   934    2017    12    23      4        51
2016-12-22   928    2017    12    22      4        51
2016-12-21   926    2017    12    21      4        51
2016-12-20   914    2017    12    20      4        51
2016-12-19   927    2017    12    19      4        51
2016-12-16   933    2017    12    16      4        50
2016-12-15   966    2017    12    15      4        50
2016-12-14   1003   2017    12    14      4        50
2016-12-13   1052   2017    12    13      4        50
2016-12-12   1069   2017    12    12      4        50

Grouping should look like this.
date       close    year    month     day     quarter   week
2016-12-23  961     2016      12      23       4         51
2016-12-16  946     2016      12      16       4         50
2017-12-23  934     2017      12      23       4         51
2017-12-16  933     2017      12      16       4         50

Can anyone help me with this?

A: You can use groupby with idxmax
df.set_index('date').groupby(['week', 'year']).idxmax().reset_index()

   week  year      close      month        day    quarter
0    50  2016 2016-12-12 2016-12-16 2016-12-16 2016-12-16
1    50  2017 2016-12-12 2016-12-16 2016-12-16 2016-12-16
2    51  2016 2016-12-23 2016-12-23 2016-12-23 2016-12-23
3    51  2017 2016-12-23 2016-12-23 2016-12-23 2016-12-23

A: IIUC, you can so this without using groupby:
df = df.sort_values(['year', 'month','quarter', 'week' , 'day']).drop_duplicates(['year', 'month','quarter', 'week'] , keep ='last')

OUTPUT:
          date  close  year  month  day  quarter  week
5   2016-12-16    946  2016     12   16        4    50
0   2016-12-23    961  2016     12   23        4    51
15  2016-12-16    933  2017     12   16        4    50
10  2016-12-23    934  2017     12   23        4    51


text:
Q: Fragment shader in LibGDX for tiled water texture Using LibGDX, I am trying to figure out how to write a simple fragment shader that is able to render a tiled water texture using a simple sine effect in both the X and Y directions, but making sure adjacent tiles are still connected on the texture edge (see picture). I'm having a hard time figuring this simple thing out - my maths might be a little bit rusty. Can you help me?

Of course, the shader cannot "guess" what's on the negative part of the texture when the texture coordinates are offset inwards, but the texture is a self-connecting mosaic, so I guess something can be done here.
The fragment shader is:
#ifdef GL_ES
precision mediump float;
#endif

uniform sampler2D u_texture;    // 0
uniform float time;             // elapsed time
uniform float xFactor;          // controls effect amplitude in the X and Y directions
uniform float yFactor;
uniform float xWobble;          // de-synchronize X and Y 'wobling' effect between layers
uniform float yWobble;

const float M_PI = 3.1415926538;

varying vec2 v_texCoords;

void main()
{
    vec2 l_texCoords = v_texCoords;
    l_texCoords = v_texCoords + vec2(xFactor * sin((1. - v_texCoords.x) * 2. * M_PI + time * xWobble), yFactor * cos((1. - v_texCoords.y) * 2. * M_PI + time * yWobble));
    gl_FragColor = texture2D(u_texture, l_texCoords);

}

Then, in the Java side, I do:
batch.setShader(waterShader);
batch.setProjectionMatrix(backgroundCamera1.combined); //Background 1
batch.begin();
batch.getShader().setUniformf("time", deltaAcc);
batch.getShader().setUniformf("xFactor", 0.05f);
batch.getShader().setUniformf("yFactor", 0.07f);
batch.getShader().setUniformf("xWobble", 0.12f);
batch.getShader().setUniformf("yWobble", 0.22f);
batchTileMapRenderer.setView(backgroundCamera1);
bTileMapRenderer.renderTileLayer(tilesBg1Layer); // The water layer, with 128x128 tiles
batch.end();
batch.setShader(null);

I hope you can shed some light on this apparently simple problem...


text:
Q: How to: Make a button shake every X seconds? I'm trying to make a button shake every couple of seconds when a certain bool is true ..
I've found a "ShakeWidget" that I've wrapped my button in, but struggling to figure out how to make it shake every couple of seconds...
Here's a little example of the code:
This is the widget I'm wrapping my button with
class ShakeWidget extends StatelessWidget {
  final Duration duration;
  final double deltaX;
  final Widget child;
  final Curve curve;

  const ShakeWidget({
    Key key,
    this.duration = const Duration(milliseconds: 500),
    this.deltaX = 20,
    this.curve = Curves.bounceOut,
    this.child,
  }) : super(key: key);

  /// convert 0-1 to 0-1-0
  double shake(double animation) =>
      2 * (0.5 - (0.5 - curve.transform(animation)).abs());

  @override
  Widget build(BuildContext context) {
    return TweenAnimationBuilder<double>(
      key: key,
      tween: Tween(begin: 0.0, end: 1.0),
      duration: duration,
      builder: (context, animation, child) => Transform.translate(
        offset: Offset(deltaX * shake(animation), 0),
        child: child,
      ),
      child: child,
    );
  }
}

Here's an example of what I've tried
It's definitely not shaking every 2 seconds like I thought it would.. I've got a second bool/condition that's there to allow the button to start shaking if it's true
  bool _shakeButton = false;
  bool _canStartShaking = false;

  void _startShakeTimer() {
    _shakeTimer = Timer.periodic(Duration(seconds: 1), (timer) {
     if(_canStartShaking)
      setState(() {
        _shakeButton = !_shakeButton;
      });
    });
  }

  @override
  void initState() {
    super.initState();
    _startShakeTimer();
  }

  Widget _myShakingButton() {
    return _shakeButton
        ? ShakeWidget(
            child: CustomButton(
              buttonType: ButtonType.Primary,
              onPressedHandler: (){},
            ),
          )
        : CustomButton(
            buttonType: ButtonType.Primary,
            onPressedHandler: (){},
          );
  }

A: The variable _canStartShaking is set to false, so there is no way for _shakeButton to be set to true since that code only runs when _canStartShaking is true.
So the solution is to set _canStartShaking to true instead of false
bool _canStartShaking = true;


text:
Q: How does a maximum power point charge controller regulate the charging current, when it always draws the maximum current from the panel? I want to understand exactly how an MPPT charge controller works and all I could find is this:

An MPPT charger is a DC-DC transformer, that when it lowers the input voltage, it raises the output current as well, therefore, except for a small loss, the input and output power is the same.

But I also know that a battery bank needs to be charged in different steps having different voltages and currents (bulk, floating, ..etc)
So my question is that, if the MPPT charger always tries to get the most current out of the panel, how does it achieve those different charging steps?
Also, most references say that the output voltage is constant, so the control is done on the current, i.e. the output current is constantly compared to the maximum value and it alternates around a maximum reference value. How is the voltage constant - doesn't the battery voltage also change when the bank is charged and discharged?

A: Good question. You are right that there is a contradiction there. How can you do maximum power point tracking if the load is not able to accept the maximum power? For a grid tie inverter, it is no problem because the grid can accept all the power that the solar array can produce.
But what about a battery? What if the battery is charged already, or if the maximum power would result in too high of a charge current? The way this contradiction is resolved is that the MPPT charge controller for an off-grid system will do MPPT only when the battery can accept the maximum power. At other times, it will abandon the MPPT protocol and function as a normal charge controller.
In a typical off-grid system, the battery will be large enough to accept the solar array's maximum power output during bulk-charging, but once the charge controller transitions to constant voltage, the maximum power will not be used.

A: MPPT stands for Maximum Power Point Tracker.
It tries to draw the Maximum Power from the panel at all times, and Tracks the panel's operating point as the amount of sun arriving changes.
In order to stay operating at Maximum Power, the MPPT needs to have a load connected to it that can absorb safely all the power it produces. This means a sufficiently big, uncharged battery, or a good grid connection. If the load cannot absorb the power, perhaps the battery is not big enough or is nearing full charge, then the MPPT has to drop back from maximum, and must only draw what is permitted to charge the battery safely.
An MPPT works by drawing a certain amount of current from the panel, converting to a the voltage/current the load needs at that moment, and measuring the power that represents. For a load like a battery, it can simply measure the charging current as a proxy for the power. It then varies the amount of current it's drawing from the panel by a small amount, and does the sums again. It keeps this, or the last, current setting, whichever produced more power, and varies again. Rinse and repeat.

A: MPPT controllers vary the current draw in order to maintain the optimum voltage.  This is done by varying the effective resistance of the load typically by varying the output current of a switching power converter (by varying the switch duty cycle) charging a battery.  Loads where the current cannot be controlled usually cannot be used with MPPT schemes, it would be possible to use a mosfet/bjt or other programmable series resistance to reduce the current, but the losses associated with these schemes offset any optimization associated with MPPT.


text:
Q: Select specific table cell in JavaScript I have a HTML like this:

        <input type="text" name="start"/>
        <input type="text" name="end"/>
        <textarea name="desc"></textarea>
        <button type="button" onclick="saveValues(this);createRow('laboral')"> + </button>

What I want is to save the values in the three cells (2 inputs and 1 textarea).
The button creates another row just like the first, with the same inputs and names. The problem is that I don't know how to access THIS row, I mean, the row who owns the button.
I tried with this.parentNode.parentNode but didn't work.

A: You're passing a reference to the button into saveValues, so within saveValues the first argument will refer to the button. Let's call that argument btn. btn.parentNode will be the td containing the button, and `btn.parentNode.parentNode will be the tr containing that td. So:
function saveValues(btn) {
    var tr = btn.parentNode.parentNode;
    // Work with `childNodes` and the `childNodes` of those children to get the values
}

A: Try this

        <input type="text" name="start"/>
        <input type="text" name="end"/>
        <textarea name="desc"></textarea>
        <button type="button" onclick="saveValues(this)"> + </button>

var inputVals = [];

function saveValues(elm) {
    //         button   td         tr        tbody     table
    var table = elm.parentNode.parentNode.parentNode.parentNode;

    //  iterating through the first row cells
    for (var i = 0; i<table.rows[0].cells.length-1; i++) {
        //  the current cell
        var cell = table.rows[0].cells[i];
        //  pushing the input elm's value into the array
        inputVals.push(cell.childNodes[0].value);
        //  retrieving the pushed value
        alert(inputVals[i]);
    }
}

Fiddle example
You can modify the code.


text:
Q: Most efficient way to direct my studies for a career in Data Science/ML? First, I don't know if this question is suitable for this site. I tried posting to Quora, but the length was too long. If it's not an acceptable question, would someone please suggest a more appropriate place?
I'm a student currently finishing up an MS in electrical engineering. In the past few months I've gotten really interested in data science and machine learning, and I've decided that I'd like to try and pursue this field as a career. There's a tremendous amount of resources available for learning these topics, which is a great thing, but to the beginner it is slightly overwhelming to try and figure out which resources I should focus on first and what's the best way to make use of my time. My goal is to be prepared to interview for junior data science/entry level machine learning engineer positions in about 6-8 months time. I know that this is a small timeframe and I'll need to work very hard for this to be possible. I'm currently taking an introductory course in machine learning that's supposed to loosely follow the book Machine Learning: a Probabilistic Perspective by Kevin P. Murphy, along with a course in image processing which I hope will be useful later on for feature extraction and other topics. I went a bit (a lot?) overboard in the past few weeks and purchased several textbooks related to data science and machine learning. I also started the Kaggle-Udacity machine learning engineer nanodegree program.
Would someone who has some experience in the field mind suggesting a rough order of how I should direct my studies with respect to the resources I've compiled? The books/resources I currently have at my disposal are:
Online services:

*

*Dataquest.io data scientist path (25% completed)

*Kaggle-Udacity
machine learning engineer nanodegree program
Books:

*

*Make Your Own Neural Network (100% completed)

*An Introduction to Statistical Learning with R (50% completed)

*Deep Learning (25% completed)

*Python Machine Learning (25% completed)

*The Elements of Statistical Learning

*Machine Learning: A Probabilistic Perspective

*Doing Bayesian Data Analysis

*Practical Data Science with R

*Data Science for Business

*OpenIntro Statistics

*Probability Theory The Logic of Science
At this point I've read the introductory chapters to all of these books, but am beginning to feel a bit haphazard in my approach. I know that it will be difficult to complete all of these in 6-8 months, so which would be the most important to focus on in order to appear competent to hiring managers?

A: I think someone will close this question, but I'll give you some help anyway.

*

*The nanodegree is expensive and in my view not very useful

*You should familiar yourself regression. Don't bother deep learning if you can't do linear regression

*Learn the practical tools (e.g. tensorflow). Try to train MINST digits, can you do it? Then, then try to train something harder. Kaggle is your best friend.

*Practice your skills in Kaggle competitions and look at other people's submission. Read, study, fork and ask their solutions.

*Learn basic about feature engineering, look at how Kaggle people do it.

*You have too many books to read. Deep learning is probably not expected for a graduate position, so skip it. You need to spend more time on the foundation.

*None of your book is about visualization. Data visualization is actually the most important skill set for a data scientist. Again, drop your deep learning book and your Bayesian analysis. Study PCA plot, scatterplot, histogram, normal distribution smoothing, ROC curve etc

*You should be familiar with the most common R packages such as ggplot and car.

*You should also learn scikit-learn, numpy and pandas Python packages. They are very popular in the industry.

*Train your programming in R and Python

*Visit Kaggle everyday, bookmark it

Typically, some of the advanced stuffs you read such as Bayesian analysis and probability theory is done by people with a PHD degree. You don't have time to read it, focus on what people in Kaggle talk about.
EDIT:

*

*Study classification metrics, such as confusion matrix. Read up what you should do if your data set is imbalanced. You need to understand when to use accuracy and when to use precision.

*Study how to work with different data formats - CSV, REST API, SQL etc.


text:
Q: MVC Response.Redirect not working with question mark I am trying to redirect to another page from a controller, the code is:
Response.Redirect("http://server1:8080/amj/servlet/inv/template/print.html?txt=ABC");

But the redirect is done to this url:
http://server1:8080/amj/servlet/inv/txt/ABC/template/print.html

As you can see, it puts the txt=ABC in the middle of string...
If I try with the url without question mark, it works fine.
Thanks in advance for your help.
Regards
Carlos.

A: The query string parameters are matching one of the routes in your routing setup.
You can get around this for a specific page/route by using routes.IgnoreRoute inside your RegisterRoutes method.
Another option would be to not use Response.Redirect and instead use the Controller/Action route model. This would be the preferred approach and you can read more about why in this article.

A: You can try the below. The controller's ActionResult can return Content type which contains the link for your redirect.
public ActionResult RedirectPage(long param)
{
     string url = "http://server1:8080/amj/servlet/inv/template/print.html?id=" + param;
     return Content("<html><script>window.location.href = '" + url + "';</script></html>");
}