问:
Using Spring Cloud Stream to produce Avro Messages using the Confluent Schema Registry
I am new to Spring Cloud Stream and trying to produce Avro messages based on the Confluent Schema Registry.

I can get the very basic example, https://cloud.spring.io/spring-cloud-stream/ working, but when I try to extend it further to use Avro, I am getting exceptions.

As a generic test environment, I am running the Docker image:
https://github.com/Landoop/fast-data-dev/

The test project was generated and slightly modified using Spring Initializr:
https://start.spring.io/

The pom.xml:

```<code><?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.demo.kafka</groupId>
  <artifactId>kafka-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>kafka-demo</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Dalston.SR1</spring-cloud.version>
    <project-avro.version>7.0.0-SNAPSHOT</project-avro.version>
    <apache.avro.version>1.8.2</apache.avro.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-stream</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-stream-kafka</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-stream-schema</artifactId>
      <version>1.2.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.9.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.avro</groupId>
      <artifactId>avro</artifactId>
      <version>${apache.avro.version}</version>
    </dependency>
    <dependency>
      <groupId>project.foundation</groupId>
      <artifactId>maritz-avro</artifactId>
      <version>${project-avro.version}</version>
    </dependency>
  </dependencies>
</project>
</code>```

I have published the following schema to the registry:

```<code>{
  "type": "record",
  "name": "RoutingSlipMsg",
  "fields": [
    {
      "name": "projectNumber",
      "type": "string"
    },
    {
      "name": "clientName",
      "type": "string"
    },
    {
      "name": "programTheme",
      "type": "string"
    },
    {
      "name": "databaseName",
      "type": [
        "null",
        "string"
      ]
    },
    {
      "name": "actionType",
      "type": [
        "null",
        "string"
      ]
    }
  ]
}
</code>```

Original Test application.yml

```<code>spring:
  cloud:
    stream:
      schema:
        avro:
          dynamicSchemaGenerationEnabled: true
      bindings:
        output:
          binder: kafka
          destination: routing_slip_dev
#          contentType: application/avro
#          contentType: application/*+avro
          contentType: application/com.project.RoutingSlipMsg.v1+avro
      schemaRegistryClient:
        endpoint: http://192.168.99.100:8081
      kafka:
        binder:
          defaultBrokerPort: 9092
          defaultZkPort: 2181
          zkNodes: 192.168.99.100
          brokers: 192.168.99.100
</code>```

Test application.yml edits:

```<code>spring:
  cloud:
    stream:
      schema:
        avro:
          dynamicSchemaGenerationEnabled: true
      bindings:
        output:
          binder: kafka
          destination: routing_slip_dev
#          contentType: application/*+avro
#          contentType: application/avro
      schemaRegistryClient:
        endpoint: http://192.168.99.100:8081
      kafka:
        binder:
          defaultBrokerPort: 9092
          defaultZkPort: 2181
          zkNodes: 192.168.99.100
          brokers: 192.168.99.100
</code>```

Configuration class

```<code>@Configuration
public class DemoConfiguration {

  @Bean
  public ConfluentSchemaRegistryClient schemaRegistryClient() {
    ConfluentSchemaRegistryClient registry = new ConfluentSchemaRegistryClient();
    registry.setEndpoint("http://192.168.99.100:8081");
    return registry;
  }

}
</code>```

The auto topic creation seems to be working properly.  I can change the destination: value to something else each time and a new topic will be created.

Test

```<code>package com.project.kafka.kafkademo;

import com.project.avro.RoutingSlipMsg;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class KafkaDemoApplicationTests {

  @Autowired
  private KafkaRoutingSlipSender kafkaRoutingSlipSender;

  @Test
  public void testSend() throws Exception {

    RoutingSlipMsg routingSlip = new RoutingSlipMsg();
    routingSlip.setActionType("FAKE_ACTION");
    routingSlip.setClientName("TEST_CLIENT");
    routingSlip.setDatabaseName("NONE");
    routingSlip.setProgramTheme("THEME");
    routingSlip.setProjectNumber("ABC123");

    kafkaRoutingSlipSender.send(routingSlip);
  }
}
</code>```

**BootApplication class*

```<code>package com.project.kafka.kafkademo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class KafkaDemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(KafkaDemoApplication.class, args);
  }
}
</code>```

Original Sender class

```<code>package com.project.kafka.kafkademo;

import com.project.avro.RoutingSlipMsg;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.cloud.stream.schema.client.EnableSchemaRegistryClient;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.core.MessageSource;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

@Component
@EnableBinding(Source.class)
@EnableSchemaRegistryClient
public class KafkaRoutingSlipSender {

  @InboundChannelAdapter(value = Source.OUTPUT)
  public MessageSource<RoutingSlipMsg> send(RoutingSlipMsg data) {
    System.out.println("**** Hello World ****");
    return () -> {
      return new GenericMessage<>(data);
    };
  }
}
</code>```

Sender Class Edits:

```<code>@Component
@EnableBinding(Source.class)
@EnableSchemaRegistryClient
public class KafkaRoutingSlipSender {

  @Autowired
  private Source source;

  public void send(RoutingSlipMsg data) {
    System.out.println("**** Hello World ****");
    source.output().send(MessageBuilder.withPayload(data).build());
  }
}
</code>```

Original Stacktrace / Exception due to inappropriate use of @InboundChannelAdapter

```<code>2017-07-06 12:20:48.645 ERROR 69011 --- [ask-scheduler-1] o.s.integration.handler.LoggingHandler   : org.springframework.messaging.MessagingException: Failed to invoke method; nested exception is java.lang.IllegalArgumentException: wrong number of arguments
    at org.springframework.integration.endpoint.MethodInvokingMessageSource.doReceive(MethodInvokingMessageSource.java:119)
    at org.springframework.integration.endpoint.AbstractMessageSource.receive(AbstractMessageSource.java:134)
    at org.springframework.integration.endpoint.SourcePollingChannelAdapter.receiveMessage(SourcePollingChannelAdapter.java:224)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:245)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:58)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:190)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:186)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:353)
    at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
    at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:51)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:344)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:201)
    at org.springframework.integration.endpoint.MethodInvokingMessageSource.doReceive(MethodInvokingMessageSource.java:116)
    ... 20 more
</code>```

I have reviewed several different posts on here, but nothing seems to be helping.
What might I be missing?

Update 1:
I have made updates to the KafkaRoutingSlipSender class and the application.yml as shown above.  With the contentType removed, these changes will publish a message like:

```<code>{
  "type": "record",
  "name": "RoutingSlipMsg",
  "fields": [
    {
      "name": "projectNumber",
      "type": "string"
    },
    {
      "name": "clientName",
      "type": "string"
    },
    {
      "name": "programTheme",
      "type": "string"
    },
    {
      "name": "databaseName",
      "type": [
        "null",
        "string"
      ]
    },
    {
      "name": "actionType",
      "type": [
        "null",
        "string"
      ]
    }
  ]
}
</code>```0

to the topic.

However, when I set the contentType to application/*+avro, the @Autowired Source appears to be casuing a NullPointerException.

New Stacktrace / Exception:

```<code>{
  "type": "record",
  "name": "RoutingSlipMsg",
  "fields": [
    {
      "name": "projectNumber",
      "type": "string"
    },
    {
      "name": "clientName",
      "type": "string"
    },
    {
      "name": "programTheme",
      "type": "string"
    },
    {
      "name": "databaseName",
      "type": [
        "null",
        "string"
      ]
    },
    {
      "name": "actionType",
      "type": [
        "null",
        "string"
      ]
    }
  ]
}
</code>```1

Update 2 (07-10-2017):
I have fixed the null Source issue, thanks to this information:

Spring Boot: Configuration Class is simply ignored and not loaded

The ConfluentSchemaRegistryClient is now being used.  I can step into the code when debugging, but it doesn't find the schema.

ConfluentSchemaRegistryClient.register(String subject, String format, String schema)

```<code>{
  "type": "record",
  "name": "RoutingSlipMsg",
  "fields": [
    {
      "name": "projectNumber",
      "type": "string"
    },
    {
      "name": "clientName",
      "type": "string"
    },
    {
      "name": "programTheme",
      "type": "string"
    },
    {
      "name": "databaseName",
      "type": [
        "null",
        "string"
      ]
    },
    {
      "name": "actionType",
      "type": [
        "null",
        "string"
      ]
    }
  ]
}
</code>```2

New Stacktrace / Exception (07-10-2017):

```<code>org.springframework.messaging.MessageDeliveryException: failed to send Message to channel 'output'; nested exception is org.springframework.web.client.HttpClientErrorException: 404 Not Found
, failedMessage=GenericMessage [payload={"projectNumber": "ABC123", "clientName": "TEST_CLIENT", "programTheme": "THEME", "databaseName": "NONE", "actionType": "FAKE_ACTION"}, headers={id=73365130-a91b-ba9c-aaf0-77cfaa26f73d, timestamp=1499700409997}]
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:449)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
    at com.maritz.kafka.kafkademo.KafkaRoutingSlipSender.send(KafkaRoutingSlipSender.java:29)
    at com.maritz.kafka.kafkademo.KafkaDemoApplicationTests.testSend(KafkaDemoApplicationTests.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.web.client.HttpClientErrorException: 404 Not Found
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient.register(ConfluentSchemaRegistryClient.java:73)
    at org.springframework.cloud.stream.schema.avro.AvroSchemaRegistryClientMessageConverter.resolveSchemaForWriting(AvroSchemaRegistryClientMessageConverter.java:242)
    at org.springframework.cloud.stream.schema.avro.AbstractAvroMessageConverter.convertToInternal(AbstractAvroMessageConverter.java:174)
    at org.springframework.messaging.converter.AbstractMessageConverter.toMessage(AbstractMessageConverter.java:193)
    at org.springframework.cloud.stream.binding.MessageConverterConfigurer$ContentTypeConvertingInterceptor.preSend(MessageConverterConfigurer.java:253)
    at org.springframework.integration.channel.AbstractMessageChannel$ChannelInterceptorList.preSend(AbstractMessageChannel.java:538)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:415)
    ... 31 more
</code>```

Is the register() supposed to be creating a new schema if that one doesn't exist, or is the 404 appropriate behavior?  Quite confused.

答:
Caused by: java.lang.IllegalArgumentException: wrong number of arguments

An @InboundChannelAdapter method cannot have any parameters...

```<code>/**
 * Indicates that a method is capable of producing a {@link org.springframework.messaging.Message}
 * or {@link org.springframework.messaging.Message} {@code payload}.
 * <p>
 * A method annotated with {@code @InboundChannelAdapter} can't accept any parameters.
 * <p>
 * Return values from the annotated method may be of any type. If the return
 * value is not a {@link org.springframework.messaging.Message}, a {@link org.springframework.messaging.Message}
 * will be created with that object as its {@code payload}.

...
</code>```

It is polled for a message, or message payload.

Body:
I am new to Spring Cloud Stream and trying to produce Avro messages based on the Confluent Schema Registry.

I can get the very basic example, https://cloud.spring.io/spring-cloud-stream/ working, but when I try to extend it further to use Avro, I am getting exceptions.

As a generic test environment, I am running the Docker image:
https://github.com/Landoop/fast-data-dev/

The test project was generated and slightly modified using Spring Initializr:
https://start.spring.io/

The pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
  <modelVersion>4.0.0</modelVersion>

  <groupId>com.demo.kafka</groupId>
  <artifactId>kafka-demo</artifactId>
  <version>0.0.1-SNAPSHOT</version>
  <packaging>jar</packaging>

  <name>kafka-demo</name>
  <description>Demo project for Spring Boot</description>

  <parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.4.RELEASE</version>
    <relativePath/>
  </parent>

  <properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
    <java.version>1.8</java.version>
    <spring-cloud.version>Dalston.SR1</spring-cloud.version>
    <project-avro.version>7.0.0-SNAPSHOT</project-avro.version>
    <apache.avro.version>1.8.2</apache.avro.version>
  </properties>

  <dependencyManagement>
    <dependencies>
      <dependency>
        <groupId>org.springframework.cloud</groupId>
        <artifactId>spring-cloud-dependencies</artifactId>
        <version>${spring-cloud.version}</version>
        <type>pom</type>
        <scope>import</scope>
      </dependency>
    </dependencies>
  </dependencyManagement>

  <dependencies>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-stream</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-stream-kafka</artifactId>
    </dependency>
    <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-stream-schema</artifactId>
      <version>1.2.2.RELEASE</version>
    </dependency>
    <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
    </dependency>
    <dependency>
      <groupId>joda-time</groupId>
      <artifactId>joda-time</artifactId>
      <version>2.9.9</version>
    </dependency>
    <dependency>
      <groupId>org.apache.avro</groupId>
      <artifactId>avro</artifactId>
      <version>${apache.avro.version}</version>
    </dependency>
    <dependency>
      <groupId>project.foundation</groupId>
      <artifactId>maritz-avro</artifactId>
      <version>${project-avro.version}</version>
    </dependency>
  </dependencies>
</project>

I have published the following schema to the registry:

{
  "type": "record",
  "name": "RoutingSlipMsg",
  "fields": [
    {
      "name": "projectNumber",
      "type": "string"
    },
    {
      "name": "clientName",
      "type": "string"
    },
    {
      "name": "programTheme",
      "type": "string"
    },
    {
      "name": "databaseName",
      "type": [
        "null",
        "string"
      ]
    },
    {
      "name": "actionType",
      "type": [
        "null",
        "string"
      ]
    }
  ]
}

Original Test application.yml

spring:
  cloud:
    stream:
      schema:
        avro:
          dynamicSchemaGenerationEnabled: true
      bindings:
        output:
          binder: kafka
          destination: routing_slip_dev
#          contentType: application/avro
#          contentType: application/*+avro
          contentType: application/com.project.RoutingSlipMsg.v1+avro
      schemaRegistryClient:
        endpoint: http://192.168.99.100:8081
      kafka:
        binder:
          defaultBrokerPort: 9092
          defaultZkPort: 2181
          zkNodes: 192.168.99.100
          brokers: 192.168.99.100

Test application.yml edits:

spring:
  cloud:
    stream:
      schema:
        avro:
          dynamicSchemaGenerationEnabled: true
      bindings:
        output:
          binder: kafka
          destination: routing_slip_dev
#          contentType: application/*+avro
#          contentType: application/avro
      schemaRegistryClient:
        endpoint: http://192.168.99.100:8081
      kafka:
        binder:
          defaultBrokerPort: 9092
          defaultZkPort: 2181
          zkNodes: 192.168.99.100
          brokers: 192.168.99.100

Configuration class

@Configuration
public class DemoConfiguration {

  @Bean
  public ConfluentSchemaRegistryClient schemaRegistryClient() {
    ConfluentSchemaRegistryClient registry = new ConfluentSchemaRegistryClient();
    registry.setEndpoint("http://192.168.99.100:8081");
    return registry;
  }

}

The auto topic creation seems to be working properly.  I can change the destination: value to something else each time and a new topic will be created.

Test

package com.project.kafka.kafkademo;

import com.project.avro.RoutingSlipMsg;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class KafkaDemoApplicationTests {

  @Autowired
  private KafkaRoutingSlipSender kafkaRoutingSlipSender;

  @Test
  public void testSend() throws Exception {

    RoutingSlipMsg routingSlip = new RoutingSlipMsg();
    routingSlip.setActionType("FAKE_ACTION");
    routingSlip.setClientName("TEST_CLIENT");
    routingSlip.setDatabaseName("NONE");
    routingSlip.setProgramTheme("THEME");
    routingSlip.setProjectNumber("ABC123");

    kafkaRoutingSlipSender.send(routingSlip);
  }
}

**BootApplication class*

package com.project.kafka.kafkademo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class KafkaDemoApplication {

  public static void main(String[] args) {
    SpringApplication.run(KafkaDemoApplication.class, args);
  }
}

Original Sender class

package com.project.kafka.kafkademo;

import com.project.avro.RoutingSlipMsg;
import org.springframework.cloud.stream.annotation.EnableBinding;
import org.springframework.cloud.stream.messaging.Source;
import org.springframework.cloud.stream.schema.client.EnableSchemaRegistryClient;
import org.springframework.integration.annotation.InboundChannelAdapter;
import org.springframework.integration.core.MessageSource;
import org.springframework.messaging.support.GenericMessage;
import org.springframework.stereotype.Component;

@Component
@EnableBinding(Source.class)
@EnableSchemaRegistryClient
public class KafkaRoutingSlipSender {

  @InboundChannelAdapter(value = Source.OUTPUT)
  public MessageSource<RoutingSlipMsg> send(RoutingSlipMsg data) {
    System.out.println("**** Hello World ****");
    return () -> {
      return new GenericMessage<>(data);
    };
  }
}

Sender Class Edits:

@Component
@EnableBinding(Source.class)
@EnableSchemaRegistryClient
public class KafkaRoutingSlipSender {

  @Autowired
  private Source source;

  public void send(RoutingSlipMsg data) {
    System.out.println("**** Hello World ****");
    source.output().send(MessageBuilder.withPayload(data).build());
  }
}

Original Stacktrace / Exception due to inappropriate use of @InboundChannelAdapter

2017-07-06 12:20:48.645 ERROR 69011 --- [ask-scheduler-1] o.s.integration.handler.LoggingHandler   : org.springframework.messaging.MessagingException: Failed to invoke method; nested exception is java.lang.IllegalArgumentException: wrong number of arguments
    at org.springframework.integration.endpoint.MethodInvokingMessageSource.doReceive(MethodInvokingMessageSource.java:119)
    at org.springframework.integration.endpoint.AbstractMessageSource.receive(AbstractMessageSource.java:134)
    at org.springframework.integration.endpoint.SourcePollingChannelAdapter.receiveMessage(SourcePollingChannelAdapter.java:224)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.doPoll(AbstractPollingEndpoint.java:245)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint.access$000(AbstractPollingEndpoint.java:58)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:190)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$1.call(AbstractPollingEndpoint.java:186)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller$1.run(AbstractPollingEndpoint.java:353)
    at org.springframework.integration.util.ErrorHandlingTaskExecutor$1.run(ErrorHandlingTaskExecutor.java:55)
    at org.springframework.core.task.SyncTaskExecutor.execute(SyncTaskExecutor.java:50)
    at org.springframework.integration.util.ErrorHandlingTaskExecutor.execute(ErrorHandlingTaskExecutor.java:51)
    at org.springframework.integration.endpoint.AbstractPollingEndpoint$Poller.run(AbstractPollingEndpoint.java:344)
    at org.springframework.scheduling.support.DelegatingErrorHandlingRunnable.run(DelegatingErrorHandlingRunnable.java:54)
    at org.springframework.scheduling.concurrent.ReschedulingRunnable.run(ReschedulingRunnable.java:81)
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511)
    at java.util.concurrent.FutureTask.run(FutureTask.java:266)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.access$201(ScheduledThreadPoolExecutor.java:180)
    at java.util.concurrent.ScheduledThreadPoolExecutor$ScheduledFutureTask.run(ScheduledThreadPoolExecutor.java:293)
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
    at java.lang.Thread.run(Thread.java:745)
Caused by: java.lang.IllegalArgumentException: wrong number of arguments
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:216)
    at org.springframework.util.ReflectionUtils.invokeMethod(ReflectionUtils.java:201)
    at org.springframework.integration.endpoint.MethodInvokingMessageSource.doReceive(MethodInvokingMessageSource.java:116)
    ... 20 more

I have reviewed several different posts on here, but nothing seems to be helping.
What might I be missing?

Update 1:
I have made updates to the KafkaRoutingSlipSender class and the application.yml as shown above.  With the contentType removed, these changes will publish a message like:

ÿcontentType?"application/x-java-object;type=com.maritz.avro.RoutingSlipMsg"FAKE_ACTIOÎTEST_CLIENÔNONÅTHEMÅABC12³

to the topic.

However, when I set the contentType to application/*+avro, the @Autowired Source appears to be casuing a NullPointerException.

New Stacktrace / Exception:

org.springframework.messaging.MessageDeliveryException: failed to send Message to channel 'output'; nested exception is java.lang.NullPointerException
, failedMessage=GenericMessage [payload={"projectNumber": "ABC123", "clientName": "TEST_CLIENT", "programTheme": "THEME", "databaseName": "NONE", "actionType": "FAKE_ACTION"}, headers={id=9a9ebc45-9431-8de5-1cb0-40d191082599, timestamp=1499438830456}]
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:449)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
    at com.maritz.kafka.kafkademo.KafkaRoutingSlipSender.send(KafkaRoutingSlipSender.java:22)
    at com.maritz.kafka.kafkademo.KafkaDemoApplicationTests.testSend(KafkaDemoApplicationTests.java:51)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: java.lang.NullPointerException
    at org.springframework.cloud.stream.schema.client.DefaultSchemaRegistryClient.register(DefaultSchemaRegistryClient.java:57)
    at org.springframework.cloud.stream.schema.avro.AvroSchemaRegistryClientMessageConverter.resolveSchemaForWriting(AvroSchemaRegistryClientMessageConverter.java:242)
    at org.springframework.cloud.stream.schema.avro.AbstractAvroMessageConverter.convertToInternal(AbstractAvroMessageConverter.java:174)
    at org.springframework.messaging.converter.AbstractMessageConverter.toMessage(AbstractMessageConverter.java:193)
    at org.springframework.cloud.stream.binding.MessageConverterConfigurer$ContentTypeConvertingInterceptor.preSend(MessageConverterConfigurer.java:253)
    at org.springframework.integration.channel.AbstractMessageChannel$ChannelInterceptorList.preSend(AbstractMessageChannel.java:538)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:415)
    ... 31 more

Update 2 (07-10-2017):
I have fixed the null Source issue, thanks to this information:

Spring Boot: Configuration Class is simply ignored and not loaded

The ConfluentSchemaRegistryClient is now being used.  I can step into the code when debugging, but it doesn't find the schema.

ConfluentSchemaRegistryClient.register(String subject, String format, String schema)

ResponseEntity<Map> response = this.template.exchange(this.endpoint + path, HttpMethod.POST, request, Map.class, new Object[0]);

New Stacktrace / Exception (07-10-2017):

org.springframework.messaging.MessageDeliveryException: failed to send Message to channel 'output'; nested exception is org.springframework.web.client.HttpClientErrorException: 404 Not Found
, failedMessage=GenericMessage [payload={"projectNumber": "ABC123", "clientName": "TEST_CLIENT", "programTheme": "THEME", "databaseName": "NONE", "actionType": "FAKE_ACTION"}, headers={id=73365130-a91b-ba9c-aaf0-77cfaa26f73d, timestamp=1499700409997}]
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:449)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:373)
    at com.maritz.kafka.kafkademo.KafkaRoutingSlipSender.send(KafkaRoutingSlipSender.java:29)
    at com.maritz.kafka.kafkademo.KafkaDemoApplicationTests.testSend(KafkaDemoApplicationTests.java:52)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
    at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:75)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:86)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:84)
    at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:252)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:94)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:70)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:191)
    at org.junit.runner.JUnitCore.run(JUnitCore.java:137)
    at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
    at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
    at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:242)
    at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
Caused by: org.springframework.web.client.HttpClientErrorException: 404 Not Found
    at org.springframework.web.client.DefaultResponseErrorHandler.handleError(DefaultResponseErrorHandler.java:63)
    at org.springframework.web.client.RestTemplate.handleResponse(RestTemplate.java:700)
    at org.springframework.web.client.RestTemplate.doExecute(RestTemplate.java:653)
    at org.springframework.web.client.RestTemplate.execute(RestTemplate.java:613)
    at org.springframework.web.client.RestTemplate.exchange(RestTemplate.java:531)
    at org.springframework.cloud.stream.schema.client.ConfluentSchemaRegistryClient.register(ConfluentSchemaRegistryClient.java:73)
    at org.springframework.cloud.stream.schema.avro.AvroSchemaRegistryClientMessageConverter.resolveSchemaForWriting(AvroSchemaRegistryClientMessageConverter.java:242)
    at org.springframework.cloud.stream.schema.avro.AbstractAvroMessageConverter.convertToInternal(AbstractAvroMessageConverter.java:174)
    at org.springframework.messaging.converter.AbstractMessageConverter.toMessage(AbstractMessageConverter.java:193)
    at org.springframework.cloud.stream.binding.MessageConverterConfigurer$ContentTypeConvertingInterceptor.preSend(MessageConverterConfigurer.java:253)
    at org.springframework.integration.channel.AbstractMessageChannel$ChannelInterceptorList.preSend(AbstractMessageChannel.java:538)
    at org.springframework.integration.channel.AbstractMessageChannel.send(AbstractMessageChannel.java:415)
    ... 31 more

Is the register() supposed to be creating a new schema if that one doesn't exist, or is the 404 appropriate behavior?  Quite confused.

Body:
Caused by: java.lang.IllegalArgumentException: wrong number of arguments

An @InboundChannelAdapter method cannot have any parameters...

/**
 * Indicates that a method is capable of producing a {@link org.springframework.messaging.Message}
 * or {@link org.springframework.messaging.Message} {@code payload}.
 * <p>
 * A method annotated with {@code @InboundChannelAdapter} can't accept any parameters.
 * <p>
 * Return values from the annotated method may be of any type. If the return
 * value is not a {@link org.springframework.messaging.Message}, a {@link org.springframework.messaging.Message}
 * will be created with that object as its {@code payload}.

...

It is polled for a message, or message payload.


来源: stackexchange

问:
c# Adding Directory.GetFiles to Zip File
I have lots of logs in a folder, I would like to only grab files that have todays date and put them in the zip file.

Here is my code:

```<code>static void Main(string[] args)
{
    //Specify todays date
    DateTime todaysDate = DateTime.Today;

    //Create a zip file with the name logs + todays date
    string zipPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd") + ".zip";
    string myPath = @"C:\Users\Desktop\LOG SEARCH";

    var files = System.IO.Directory.GetFiles(myPath, "*" + todaysDate.ToString("yyyyMMdd") + "*");

    foreach (var file in files)
    {
        Console.WriteLine(file);
    }
}
</code>```

How do I zip files ?

答:
You need to use System.IO.Compression;
and use</p>

```<code> ZipFile.CreateFromDirectory(myPath, zipPath);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have lots of logs in a folder, I would like to only grab files that have todays date and put them in the zip file.

Here is my code:

static void Main(string[] args)
{
    //Specify todays date
    DateTime todaysDate = DateTime.Today;

    //Create a zip file with the name logs + todays date
    string zipPath = @"C:\Users\Desktop\ZIP\logs" + todaysDate.ToString("yyyyMMdd") + ".zip";
    string myPath = @"C:\Users\Desktop\LOG SEARCH";

    var files = System.IO.Directory.GetFiles(myPath, "*" + todaysDate.ToString("yyyyMMdd") + "*");

    foreach (var file in files)
    {
        Console.WriteLine(file);
    }
}

How do I zip files ?

Body:
You need to use System.IO.Compression;
and use

 ZipFile.CreateFromDirectory(myPath, zipPath);


问:
Best Practice for Java UDP Multithreading
First off I'd like to apologize for any dumb questions, I'm still learning network programming.

I never did much network programming, other than out of self interest, and I only used Java's Socket and ServerSocket classes. With these classes, the paradigms I used were to have a single Java thread on the server side which accepted connections from clients, and then passed that accepted Socket onto its own Thread. Thus with 100 concurrent clients, there would be (potentially) 100 threads. Then the client and server could talk to each other on their own threads, separate from the other components of the system.

Now enter the DatagramSocket... I'm just learning about TCP vs UDP, so just discovered this class. It makes sense... you listen for packets on a port, and send packets on a port/address. The body contains a certain number of bytes and is optional (Still learning what the max body sizes are and such). From the information online, I've gathered that the socket listens for ANY packets on that port, and derives the source from the packet headers.

This is all good and fine, and I am comfortable with forwarding those packets to their own runnables in a pool, or their own threads, etc. What is bothering me though is that with TCP sockets, each Thread (One of the 100 in the above example) received only messages from the appropriate source. With Datagram sockets, all packets from every client is going to a single thread... and that thread is responsible for divvying the work.

How would something like that work in an MMO game... say you have a game server supporting 5000 players, and each player sends 15 packets per second... That's 75,000 packets per second, which seems heavy for a single thread to handle. (As opposed to 5000 threads which could each have 15 per second). Obviously that one thread could forward the packets to the proper places based on packet headers and a client hashmap, but I'm just uncomfortable that the listener thread itself is doing that logic.

Now it's possible that TCP is doing something similar (Some packet listener thread that forwards the data to the appropriate Socket), so really I'm losing nothing. I guess the root question boils down to... Is it possible to have multiple Server threads listening to the same port? For example, I'm picturing a load balancer which round robins the packets to different DataGramSocket listeners (One on each thread, maybe 3-4 threads). Then those listeners can do the job of the original single thread, which is sending those unordered packets to the correct locations in the program (Example, this packet came from 123.456.789.123 on port 6750... lets check our clientMap for where this should go... Okay, send to that threads packet queue).

I'm guessing the answer is that as long as the thread handling all the client packets is very lightweight (Just receive packet, delegate, repeat), then there is no problem even for high volume traffic.

Thanks!

EDIT: After some thought and Am_I_Helpful's comment (And now Jamal H), I realized you can abstract this out on a machine or port level. So if you have 3000 players, you could have a load balancer of sorts which directs that player to a particular machine or even a particular port on the machine. So that way you could have X number of server threads each listening for packets on a different port. Player 1 may hit port 7712, player 2 may hit 7713.

答:
First of all, if you don't have access to a large team of people, you wouldn't be writing all the network code from scratch for an MMO. You would use some sort of networking framework that handles load balancing and threading for you (Netty is a good one for Java)

For an MMO you would use Non Blocking IO (NIO), which does not map out each client's request to its own thread, but instead has a set number of threads it wants to use (determined by number of cores), and handles it like that

Regarding loading every request on a single thread, there are a couple of options. This is the reason why MMOs have multiple servers, each for a different area in a game. The central server would give the player the IP and port of the area server that he is currently in. You can also have multiple ports accepting on a single server if the server is powerful, and just send different players different ports to send to if you wanted to balance the load across multiple threads


问:
Restoring Typus plugin after changing DB Schema
I installed Typus plugin (http://intraducibles.com/projects/typus) for my app and I love it. But along the development of the app I frequently do migrations and change the DB Schema and relationships, and then the plugin fails. Is there a way to re-generate the plugin with the new schema? Thanks!</p>

答:
I think simply entering

```<code>rails generate typus
</code>```

again will set things right.

ContentLicense: CC BY-SA 2.5

Body:
I think simply entering

rails generate typus

again will set things right.


问:
Search NetSuite Custom Record Type in PHP
I have a Custom Record Type and I am having trouble searching the barcode from the item value:

I am using the NetSuite PHPToolkit_2015_2 and this stackoverflow answer https://stackoverflow.com/a/13366947/2120512 and http://burnignorance.com/netsuite-tips-and-hacks/working-with-custom-records-in-suitetalk/ to attempt to build this request:

```<code>$service = new NetSuiteService();
// Perform an AdvancedSearch for Items
// https://netsuite.custhelp.com/app/answers/detail/a_id/12203/kw/php%20search%20criteria

$service->setSearchPreferences(false, 1000, false);
$savedSearchId = 'customsearch_barcode_view'; //customsearch## from UI ID field
$searchAdvanced = new CustomRecordSearchAdvanced();
setFields($searchAdvanced, array('savedSearchScriptId'=>$savedSearchId));

$request = new SearchRequest();
$request->searchRecord = $searchAdvanced;

// PHP Toolkit 2012.2: Sample Code to Perform Search that Uses a Custom Field as Filter
// https://netsuite.custhelp.com/app/answers/detail/a_id/25066/kw/php%20custom%20field

$custSearchField = new SearchMultiSelectCustomField();
$custSearchField->value = new ListOrRecordRef();
$custSearchField->value->internalId = "custrecord_barcode_item";
$custSearchField->value->value = "00001 Beer Mug";

$searchAdvanced->customFieldList = $custSearchField;

$results = $service->search($request);
</code>```

I still get all the results for the Custom Record Type and never able to figure out how to search by the item. I have made changes and still receive the entire results.

答:
I'm pretty sure this won't immediately solve your problem, but at the first glance I can see an error in your code.

The customFieldList is of type array, so you need to change this:

```<code>$searchAdvanced->customFieldList = $custSearchField;
</code>```

To this

```<code>$searchAdvanced->customFieldList = [$custSearchField];
</code>```

Body:
I have a Custom Record Type and I am having trouble searching the barcode from the item value:

I am using the NetSuite PHPToolkit_2015_2 and this stackoverflow answer https://stackoverflow.com/a/13366947/2120512 and http://burnignorance.com/netsuite-tips-and-hacks/working-with-custom-records-in-suitetalk/ to attempt to build this request:

$service = new NetSuiteService();
// Perform an AdvancedSearch for Items
// https://netsuite.custhelp.com/app/answers/detail/a_id/12203/kw/php%20search%20criteria

$service->setSearchPreferences(false, 1000, false);
$savedSearchId = 'customsearch_barcode_view'; //customsearch## from UI ID field
$searchAdvanced = new CustomRecordSearchAdvanced();
setFields($searchAdvanced, array('savedSearchScriptId'=>$savedSearchId));

$request = new SearchRequest();
$request->searchRecord = $searchAdvanced;

// PHP Toolkit 2012.2: Sample Code to Perform Search that Uses a Custom Field as Filter
// https://netsuite.custhelp.com/app/answers/detail/a_id/25066/kw/php%20custom%20field

$custSearchField = new SearchMultiSelectCustomField();
$custSearchField->value = new ListOrRecordRef();
$custSearchField->value->internalId = "custrecord_barcode_item";
$custSearchField->value->value = "00001 Beer Mug";

$searchAdvanced->customFieldList = $custSearchField;

$results = $service->search($request);

I still get all the results for the Custom Record Type and never able to figure out how to search by the item. I have made changes and still receive the entire results.

Body:
I'm pretty sure this won't immediately solve your problem, but at the first glance I can see an error in your code.

The customFieldList is of type array, so you need to change this:

$searchAdvanced->customFieldList = $custSearchField;

To this

$searchAdvanced->customFieldList = [$custSearchField];


问:
Force Directed Graph Error, "Cannot Read Property 'Push' of Undefined"
I am new to coding and recently began using d3 to generate a force directed graph. I successfully generated a four node graph when using the links to derive the nodes. However, when I explicitly list the nodes I receive the error "Uncaught TypeError: Cannot read property 'push' of undefined (d3.v3.min.js)". I have studied responses to the following two similar questions but have been unable to resolve this issue using the answers. I attempted to remove as many of the non-relevant features as possible, thanks.

JavaScript error "Uncaught TypeError: Cannot call method 'push' of undefined" D3.js

Uncaught TypeError: Cannot call method 'push' of undefined (d3 force layout)

Force Directed Graph Fails:

```<code><script type="text/javascript" src="d3.v3.min.js"> </script>

<script>

var width = 900,
    height = 590;

var svg = d3.select("body")
        .append("svg")
        .attr("width", width)
        .attr("height", height)

var links = [
    {source: 'H', target: 'I'},
    {source: 'H', target: 'J'},
    {source: 'I', target: 'J'},
    {source: 'J', target: 'K'},
];

var nodes = [
    {name: 'H'},
    {name: 'I'},
    {name: 'J'},
    {name: 'K'},
];

var force = d3.layout.force()
    .size([width, height])
    .nodes(d3.values(nodes))
    .links(links)
    .on('tick', tick)
    .linkDistance(100)
    .gravity(.15)
    .friction(.8)
    .linkStrength(1)
    .charge(-425)
    .chargeDistance(600)
    .start();

var link = svg.selectAll('.link')
    .data(links)
    .enter().append('line')
    .attr('class', 'link');

var node = svg.selectAll('.node')
    .data(force.nodes())
    .enter().append('circle')
    .attr('class', 'node')
    .attr('r', width * 0.01)

function tick(e) {

    node.attr('cx', function(d) { return d.x; })
        .attr('cy', function(d) { return d.y; })
        .call(force.drag);

    link.attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

};

    </script>
</code>```

Force Directed Graph Works:

```<code><script type="text/javascript" src="d3.v3.min.js"> </script>

<script>

var width = 900,
    height = 590;

var svg = d3.select("body")
        .append("svg")
        .attr("width", width)
        .attr("height", height)

var links = [
    {source: 'H', target: 'I'},
    {source: 'H', target: 'J'},
    {source: 'I', target: 'J'},
    {source: 'J', target: 'K'},
];

var nodes = {};
links.forEach(function(link) {
    link.source = nodes[link.source] ||
        (nodes[link.source] = {name: link.source});
    link.target = nodes[link.target] ||
        (nodes[link.target] = {name: link.target});
        });

var force = d3.layout.force()
    .size([width, height])
    .nodes(d3.values(nodes))
    .links(links)
    .on('tick', tick)
    .linkDistance(100)
    .gravity(.15)
    .friction(.8)
    .linkStrength(1)
    .charge(-425)
    .chargeDistance(600)
    .start();

var link = svg.selectAll('.link')
    .data(links)
    .enter().append('line')
    .attr('class', 'link');

var node = svg.selectAll('.node')
    .data(force.nodes())
    .enter().append('circle')
    .attr('class', 'node')
    .attr('r', width * 0.01)

function tick(e) {

    node.attr('cx', function(d) { return d.x; })
        .attr('cy', function(d) { return d.y; })
        .call(force.drag);

    link.attr('x1', function(d) { return d.source.x; })
        .attr('y1', function(d) { return d.source.y; })
        .attr('x2', function(d) { return d.target.x; })
        .attr('y2', function(d) { return d.target.y; });

};

    </script>
</code>```

答: In my case, I had this problem when My source or target value of links which gave the index of nodes was a string. </p>

Body:
I am new to coding and recently began using d3 to generate a force directed graph. I successfully generated a four node graph when using the links to derive the nodes. However, when I explicitly list the nodes I receive the error "Uncaught TypeError: Cannot read property 'push' of undefined (d3.v3.min.js)". I have studied responses to the following two similar questions but have been unable to resolve this issue using the answers. I attempted to remove as many of the non-relevant features as possible, thanks.

JavaScript error "Uncaught TypeError: Cannot call method 'push' of undefined" D3.js

Uncaught TypeError: Cannot call method 'push' of undefined (d3 force layout)

Force Directed Graph Fails:

Force Directed Graph Works:


问:
Regular Expressions: AND behavior
I'm studying regular expressions in Javascript

I've seen many ways to do exclusive matching through the OR operator with [] and | within groups ().

I can't understand how to achieve the AND behavior with regular expressions. I've done some research but I didn't find what I need.

Here an example. I have the following string: kata. I want to compare it with another string: steak.
 The goal is to return true if all the letters in steak is contained in kata. If I use this regular expression [steak] it returns true but actually it should return false because in kata there is no "s".

Example 2. String1 = scriptsjava, string2 = javascript, result = true (because string2 is contained in string1)

Example 3. String1 = jscripts, string2 = javascript, result = false (because string2 is not fully contained in string1)

Example 4. String1 = rkqodlw, string2 = world, result = true (because the string world is in the first string)

I thought that using regular expressions is the best way and I considered string2 as a pattern. My solution to this problem is the following

```<code> var validate=true;
 var counter = 0;
 str2.split("").map(val => {
   counter++;
    var char = new RegExp(val);

    if (char.test(str1) === false) { validate = false;} else
    {
    str1 = str1.slice(0, counter+1) + str1.slice(counter+1,str1.length);
    console.log(str1);
    }

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

I think is not the most efficient though. Do you have a better solution for this?

答:
Well this is my second answer, I might remove the previous answer later on, if I see this seems to be helpful for you.

Although there are some good answer being posted but yet as I can see that you want to have a hold on AND operation in regex, therefore you want a regexAND answer. Thus I am going to give you an answer that works according to your need. But if you want me to be frank, then I would say, for your requirement , regex operation is kind of the last option that I would want to go for.

Now comes the answer:

For each pair , say str1, and str2. You want to see if each character of str2 is present in str1.

thus you can make AND operation in the form of positive lookahead for each character for the entire string of str2 and see if all these exists in str1 or not.
each positie lookahead would look likhe this: (?=.*w)

when written one beside another like the regex mentioned bellow they work as AND.

For example:
str1="rkqodlw"
str2="world"

make a regex by str2 in the following way:

```<code>^(?=.*w)(?=.*o)(?=.*r)(?=.*l)(?=.*d).*$
</code>```

and see if that matches with str1

like this way:

function compare(str1,str2)
{
 var regexAnd=str2.split("").join(")(?=.*");
 var regexStr="^"+"(?=.*"+regexAnd+").*$";
 console.log(regexStr);  // prints the entire and condition

 var re = new RegExp(regexStr,"gm");

 return re.test(str1);

}

console.log(compare("scriptsjava","javascript"));
console.log(compare("jscripts","javascript"));
console.log(compare("rkqodlw","world"));```

Title: Regular Expressions: AND behavior

Body:
I'm studying regular expressions in Javascript

I've seen many ways to do exclusive matching through the OR operator with [] and | within groups ().

I can't understand how to achieve the AND behavior with regular expressions. I've done some research but I didn't find what I need.

Here an example. I have the following string: kata. I want to compare it with another string: steak.
 The goal is to return true if all the letters in steak is contained in kata. If I use this regular expression [steak] it returns true but actually it should return false because in kata there is no "s".

Example 2. String1 = scriptsjava, string2 = javascript, result = true (because string2 is contained in string1)

Example 3. String1 = jscripts, string2 = javascript, result = false (because string2 is not fully contained in string1)

Example 4. String1 = rkqodlw, string2 = world, result = true (because the string world is in the first string)

I thought that using regular expressions is the best way and I considered string2 as a pattern. My solution to this problem is the following

 var validate=true;
 var counter = 0;
 str2.split("").map(val => {
   counter++;
    var char = new RegExp(val);

    if (char.test(str1) === false) { validate = false;} else
    {
    str1 = str1.slice(0, counter+1) + str1.slice(counter+1,str1.length);
    console.log(str1);
    }

 });
 return validate;

I think is not the most efficient though. Do you have a better solution for this?

Body:
Well this is my second answer, I might remove the previous answer later on, if I see this seems to be helpful for you.

Although there are some good answer being posted but yet as I can see that you want to have a hold on AND operation in regex, therefore you want a regexAND answer. Thus I am going to give you an answer that works according to your need. But if you want me to be frank, then I would say, for your requirement , regex operation is kind of the last option that I would want to go for.

Now comes the answer:

For each pair , say str1, and str2. You want to see if each character of str2 is present in str1.

thus you can make AND operation in the form of positive lookahead for each character for the entire string of str2 and see if all these exists in str1 or not.
each positie lookahead would look likhe this: (?=.*w)

when written one beside another like the regex mentioned bellow they work as AND.

For example:
str1="rkqodlw"
str2="world"

make a regex by str2 in the following way:

^(?=.*w)(?=.*o)(?=.*r)(?=.*l)(?=.*d).*$

and see if that matches with str1

like this way:

function compare(str1,str2)
{
 var regexAnd=str2.split("").join(")(?=.*");
 var regexStr="^"+"(?=.*"+regexAnd+").*$";
 console.log(regexStr);  // prints the entire and condition

 var re = new RegExp(regexStr,"gm");

 return re.test(str1);

}

console.log(compare("scriptsjava","javascript"));
console.log(compare("jscripts","javascript"));
console.log(compare("rkqodlw","world"));


问:
Bash script to run Python Tkinter GUI
I am trying to write a Bash script so that I can run my program on a double click. The program uses tkinter and the GUI is the only thing I need to see. My bat file is the following:

```<code>python BudgetGUI.py &
</code>```

This runs the code and successfully prints any print statements I have throughout my code but it never opens up the GUI. It simply runs through and closes immediately.

How can I modify the bash script to run the GUI?

Thanks in advance!

Edit Solutions for both mac and pc would be great, though at the moment I am on PC. I am working in Python3.

答:
You need to add a call to mainloop(). I can't say for sure without seeing your code, but probably you need to add root.mainloop() to the bottom.

You don't need a bash or bat file. For your mac, just add a shebang and make the file executable. For Windows, add a shebang and associate the file with py.exe.

If you want to suppress the command line from popping up along with the GUI, rename your file with a .pyw extension.

Title: Bash script to run Python Tkinter GUI

Body:
I am trying to write a Bash script so that I can run my program on a double click. The program uses tkinter and the GUI is the only thing I need to see. My bat file is the following:

python BudgetGUI.py &

This runs the code and successfully prints any print statements I have throughout my code but it never opens up the GUI. It simply runs through and closes immediately.

How can I modify the bash script to run the GUI?

Thanks in advance!

Edit Solutions for both mac and pc would be great, though at the moment I am on PC. I am working in Python3.


问:
Check if a function was callled
I want to check if a function was called inside a Python script.

My current solution is the following:

```<code>def _print_error(msg):
    print(msg)
    print("Default error message.")
    _print_error.was_called = True

_print_error.was_called = False
</code>```

I can check if _print_error was called by checking _print_error.was_called.

Another possible way to do this is to set a class and define a static variable, that is changed whenever the class is instanced.The __init__ can print the messages and change the was_called variable.

Is there a better way of achieving the same results?

答:
Use a decorator to set the flag:

```<code>from functools import wraps

def flag_when_called(func):
    func.was_called = False

    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        func.was_called = True
        return result

    return wrapper
</code>```

Note that I only set the flag when the call successfully completes (e.g. if an exception is raised the flag is not set). You can swap the order (and directly return func(*args, **kwargs) if you want to set the flag even if an exception was raised.

Just apply that to the function:

```<code>@flag_when_called
def _print_error(msg):
    print(msg)
    print("Default error message.")
</code>```

Title: Check if a function was callled

Body:
I want to check if a function was called inside a Python script.

My current solution is the following:

def _print_error(msg):
    print(msg)
    print("Default error message.")
    _print_error.was_called = True

_print_error.was_called = False

I can check if _print_error was called by checking _print_error.was_called.

Another possible way to do this is to set a class and define a static variable, that is changed whenever the class is instanced.The __init__ can print the messages and change the was_called variable.

Is there a better way of achieving the same results?

Body:
Use a decorator to set the flag:

from functools import wraps

def flag_when_called(func):
    func.was_called = False

    @wraps(func)
    def wrapper(*args, **kwargs):
        result = func(*args, **kwargs)
        func.was_called = True
        return result

    return wrapper

Note that I only set the flag when the call successfully completes (e.g. if an exception is raised the flag is not set). You can swap the order (and directly return func(*args, **kwargs) if you want to set the flag even if an exception was raised.

Just apply that to the function:

@flag_when_called
def _print_error(msg):
    print(msg)
    print("Default error message.")


问:
Base Conversion in c
I found this program to do Base Conversions. What does the following line do in the program listing below?

```<code>printf("%c", base_digits[converted_number[index]]);
</code>```

Program:

```<code>#include <stdio.h>

int main(void)
{
  char base_digits[16] =
   {'0', '1', '2', '3', '4','5', '6', '7','8', '9', 'A', 'B', 'C','D', 'E', 'F'};

  int converted_number[64];
  long int number_to_convert;
  int  base, index=0;

/* get the number and base */
 printf("Enter number and desired base: ");
 scanf("%ld %i", &number_to_convert, &base);

/* convert to the indicated base */
while (number_to_convert != 0)
{
 converted_number[index] = number_to_convert % base;
 number_to_convert = number_to_convert / base;
 ++index;
}

/* now print the result in reverse order */
--index;  /* back up to last entry in the array */
printf("\n\nConverted Number = ");
for(  ; index>=0; index--) /* go backward through array */
{
 printf("%c", base_digits[converted_number[index]]);
}
printf("\n");
return 0;
}
</code>```

答:
The converted_number array contains the value of each digit in the converted number.

The base_digits array contains the character corresponding to each digit.  So base_digits[converted_number[index]] is getting the proper character for each digit in the specified base.

Title: Base Conversion in c

Body:
I found this program to do Base Conversions. What does the following line do in the program listing below?

printf("%c", base_digits[converted_number[index]]);

Program:

#include <stdio.h>

int main(void)
{
  char base_digits[16] =
   {'0', '1', '2', '3', '4','5', '6', '7','8', '9', 'A', 'B', 'C','D', 'E', 'F'};

  int converted_number[64];
  long int number_to_convert;
  int  base, index=0;

/* get the number and base */
 printf("Enter number and desired base: ");
 scanf("%ld %i", &number_to_convert, &base);

/* convert to the indicated base */
while (number_to_convert != 0)
{
 converted_number[index] = number_to_convert % base;
 number_to_convert = number_to_convert / base;
 ++index;
}

/* now print the result in reverse order */
--index;  /* back up to last entry in the array */
printf("\n\nConverted Number = ");
for(  ; index>=0; index--) /* go backward through array */
{
 printf("%c", base_digits[converted_number[index]]);
}
printf("\n");
return 0;
}


问:
Is it possible to have multiple top level domain in android manifest host declaration?
I am using firebase dynamic link to add deep link to my app, and that website has multiple domains, i.e.

www.foo.com

www.foo.net

www.foo.co.uk

www.foo.kp

and more ...

I saw that in https://developer.android.com/guide/topics/manifest/data-element.html#host it says that astrid must be the first character of the host. Is there any solution to work around this? I would like to see if it is possible to add more domain without the need to update the app.

答:
It is not possible to 'work around' this. This is for security reasons.

Here's why: subdomains are all under the control of the main domain. If you are able to verify example.com, by definition you could also verify example1.example.com. The * wildcard in the Manifest is simply a convenience shortcut, though you still need to handle the server component of the verification separately for each subdomain.

In contrast, example.com and example.co.uk are totally separate domains. There is no guarantee that the owner of one will also be the owner of the other.

Also worth noting: Firebase Dynamic Links does not support white labelled domains. You may also be using Dynamic Links, but you'll need to implement all of this yourself. Branch.io (full disclosure: I'm on the Branch team) does support white labelling, though only of a single domain per app.


问:
Gulp-sourcemaps returning only returning `source` js file
My sourcemaps are only returning the source value no matter what.

Broswerify.js

```<code>// add custom browserify options here
var customOpts = {
    entries: ['./frontend/js/app.js'],
    debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));
b.transform(require("jadeify"), { compileDebug: true, pretty: false });

// add transformations here
// i.e. b.transform(coffeeify);

gulp.task('browserify', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
    return b.bundle()
    // log errors if they happen
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source('main.js'))
        // optional, remove if you don't need to buffer file contents
        .pipe(buffer())
        // optional, remove if you dont want sourcemaps
        .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
        // Add transformation tasks to the pipeline here.
        .pipe(sourcemaps.write('./')) // writes .map file
        .pipe(gulp.dest('./public/js'))
        .on('end', function () {
            browserSync.reload();
        });
}
</code>```

main.js.map

```<code>{"version":3,"sources":["/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js"],"names":[],"mappings":"AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;
</code>```

This of course means that all files are referenced as main.js which is less then helpful :(

I am also using browser-sync, but I don't believe this has any effect on sourcemaps.

答:
I was using gulp-sourcemaps v2.3.0

Upgraded to v2.6.0 and now its working. I thank you sir

Body:
My sourcemaps are only returning the source value no matter what.

Broswerify.js

// add custom browserify options here
var customOpts = {
    entries: ['./frontend/js/app.js'],
    debug: true
};
var opts = assign({}, watchify.args, customOpts);
var b = watchify(browserify(opts));
b.transform(require("jadeify"), { compileDebug: true, pretty: false });

// add transformations here
// i.e. b.transform(coffeeify);

gulp.task('browserify', bundle); // so you can run `gulp js` to build the file
b.on('update', bundle); // on any dep update, runs the bundler
b.on('log', gutil.log); // output build logs to terminal

function bundle() {
    return b.bundle()
    // log errors if they happen
        .on('error', gutil.log.bind(gutil, 'Browserify Error'))
        .pipe(source('main.js'))
        // optional, remove if you don't need to buffer file contents
        .pipe(buffer())
        // optional, remove if you dont want sourcemaps
        .pipe(sourcemaps.init({loadMaps: true})) // loads map from browserify file
        // Add transformation tasks to the pipeline here.
        .pipe(sourcemaps.write('./')) // writes .map file
        .pipe(gulp.dest('./public/js'))
        .on('end', function () {
            browserSync.reload();
        });
}

main.js.map

{"version":3,"sources":["/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js","/main.js"],"names":[],"mappings":"AAAA;ACAA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;AACA;

This of course means that all files are referenced as main.js which is less then helpful :(

I am also using browser-sync, but I don't believe this has any effect on sourcemaps.


问:
Navigation bar hidden after initialize ViewController with identifier
I'm ultimating a chat into my app but i still have this issue. As you can see i have a ChatListTableViewController with the list of all the active chats(picture 1, top-left view). When i click on a cell i successfully open che ChatViewController with the NavBar displaying the name of the person whom i chat with ,the back arrow and a trash button to delete the chat. However, in the ChatListTableViewController i have  a "+" button (picture 1, top-left) which opens a PopUpViewController: this one allows you to start a new chat with a user,chosen from a TableView. The issue as you can see from picture 1 ,is that when i click on a cell in the PopUpChatListViewController, i try to initialize a ChatViewController and it opens but the NavigationBar is hidden.This is done by using the function "didSelectRowAt" of the TableView. I post you the code of the PopUpChatListViewController. In the viewDidLoad of the ChatViewController i tryied to put set "navigationBar.isHidden = false " but nothing. Can you explain me what's happening here ?

```<code>import UIKit

class PopUpChatListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return userName.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellPopUp", for: indexPath)
        cell.textLabel?.text = userName[indexPath.row]
        return cell
    }

    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UserDefaults.standard.set(userID[indexPath.row], forKey: "chatID")
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatActivity") as! ChatViewController
        self.present(vc, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}
</code>```

VIEW OF THE SCREENSHOTS RUNNING APP:

MAIN STORYBOARD SCHEME:

答:
Replace

```<code>self.present(vc, animated: true, completion: nil)
</code>```

to

```<code>self.navigationController?.pushViewController(vc, animated: true)
</code>```

When you use 'present' the view lost de navigationController.

Body:
I'm ultimating a chat into my app but i still have this issue. As you can see i have a ChatListTableViewController with the list of all the active chats(picture 1, top-left view). When i click on a cell i successfully open che ChatViewController with the NavBar displaying the name of the person whom i chat with ,the back arrow and a trash button to delete the chat. However, in the ChatListTableViewController i have  a "+" button (picture 1, top-left) which opens a PopUpViewController: this one allows you to start a new chat with a user,chosen from a TableView. The issue as you can see from picture 1 ,is that when i click on a cell in the PopUpChatListViewController, i try to initialize a ChatViewController and it opens but the NavigationBar is hidden.This is done by using the function "didSelectRowAt" of the TableView. I post you the code of the PopUpChatListViewController. In the viewDidLoad of the ChatViewController i tryied to put set "navigationBar.isHidden = false " but nothing. Can you explain me what's happening here ?

import UIKit

class PopUpChatListViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {

    @IBOutlet var tableView: UITableView!

    public func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int{
        return userName.count
    }

    public func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell{
        let cell = tableView.dequeueReusableCell(withIdentifier: "cellPopUp", for: indexPath)
        cell.textLabel?.text = userName[indexPath.row]
        return cell
    }

    public func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        UserDefaults.standard.set(userID[indexPath.row], forKey: "chatID")
        let vc = self.storyboard?.instantiateViewController(withIdentifier: "ChatActivity") as! ChatViewController
        self.present(vc, animated: true, completion: nil)
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = UIColor.black.withAlphaComponent(0.6)
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

VIEW OF THE SCREENSHOTS RUNNING APP:

MAIN STORYBOARD SCHEME:

Body:
Replace

self.present(vc, animated: true, completion: nil)

to

self.navigationController?.pushViewController(vc, animated: true)

When you use 'present' the view lost de navigationController.


问:
Trying to make a copy of array to then compare it with array to see if it changes
In my Angular program, I have a table where whenever you click on a row, it goes into a different component, row-edit.component, and the row is turned into input boxes so that you can edit the data and passed the number of the row that's selected. I want to be able to make a copy of the array that's displayed in the table so that if someone changes something they didn't mean to, they can just hit a cancel button and it will reset the row to what it originally was. How can I make a copy of the array? - I thought what I had worked, but when it's displayed to the console, I'm just getting undefined

Here's the model of my array:

  public class PTOData
  {
    [Key]
    public int ID { get; set; }
    public int EmpKey { get; set; }
    public string type { get; set; }
    public DateTime date { get; set; }
    public string fullhalf { get; set; }
    public int hours { get; set; }
    public string scheduled { get; set; }
    public string notes { get; set; }
    public bool inPR { get; set; }
    public DateTime? prDate { get; set; }
  }

  }```
</div>
</div>
</p>

<p>here's where the main function is called in my .html:</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-html lang-html prettyprint-override"><code>    <button class="btn btn-default btn-primary btn-sm" (click)="resetRow(pto)"><i class="fa fa-ban" aria-hidden="true"></i></button></code>```

and here's the relevant parts of my .ts file, the console.log(this.origPTO); is just so I can see what's printing out and currently, I'm getting undefined in the console

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

import { PTOData } from './pto-data';
import { PTODataService } from './pto-data.service';
import { EmpInfo } from './emp-info';
import { EmpInfoService } from './emp-info.service';

@Component({
    selector: '[pto-row-edit]',
    templateUrl: `./row-edit.component.html`,
    styleUrls: ['./row-edit.component.css']
})

export class RowEditComponent {

    // Inputs & Outputs to/from grid component
    @Input() pto: PTOData[];
    @Input() rowSelected: number;

    @Output() onDelete = new EventEmitter<number>();
    @Output() onSave = new EventEmitter<number>();

    origPTO: PTOData[] = this.pto;

    constructor(
        private ptodataService: PTODataService,
        private empInfoService: EmpInfoService) { }

    resetRow(pto: PTOData): void {
        console.log(this.origPTO);
        this.rowSelected = null;
        this.onSave.emit(this.rowSelected);
    }
}```

答:
Your assignment statement origPTO: PTOData[] = this.pto; happens before the @Input() occurs. Instead, put the assignment in the OnInit lifecycle hook:

```<code>import { OnInit } from '@angular/core';

export class RowEditComponent implements OnInit {

    @Input() pto: PTOData[];
    origPTO: PTOData[];

    ngOnInit(): void {
        this.origPTO = this.pto;
    }
}
</code>```

This still is not what you want, since it is not making a deep copy. Any changes to pto will also be made to origPTO. You should loop through the original array to make a deep copy:

```<code>this.origPTO = [];
this.pto.forEach(x => this.origPTO.push(x));
</code>```

Body:
In my Angular program, I have a table where whenever you click on a row, it goes into a different component, row-edit.component, and the row is turned into input boxes so that you can edit the data and passed the number of the row that's selected. I want to be able to make a copy of the array that's displayed in the table so that if someone changes something they didn't mean to, they can just hit a cancel button and it will reset the row to what it originally was. How can I make a copy of the array? - I thought what I had worked, but when it's displayed to the console, I'm just getting undefined

Here's the model of my array:

  public class PTOData
  {
    [Key]
    public int ID { get; set; }
    public int EmpKey { get; set; }
    public string type { get; set; }
    public DateTime date { get; set; }
    public string fullhalf { get; set; }
    public int hours { get; set; }
    public string scheduled { get; set; }
    public string notes { get; set; }
    public bool inPR { get; set; }
    public DateTime? prDate { get; set; }
  }

  }

here's where the main function is called in my .html:

    <button class="btn btn-default btn-primary btn-sm" (click)="resetRow(pto)"></button>

and here's the relevant parts of my .ts file, the console.log(this.origPTO); is just so I can see what's printing out and currently, I'm getting undefined in the console

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

import { PTOData } from './pto-data';
import { PTODataService } from './pto-data.service';
import { EmpInfo } from './emp-info';
import { EmpInfoService } from './emp-info.service';

@Component({
    selector: '[pto-row-edit]',
    templateUrl: `./row-edit.component.html`,
    styleUrls: ['./row-edit.component.css']
})

export class RowEditComponent {

    // Inputs & Outputs to/from grid component
    @Input() pto: PTOData[];
    @Input() rowSelected: number;

    @Output() onDelete = new EventEmitter<number>();
    @Output() onSave = new EventEmitter<number>();

    origPTO: PTOData[] = this.pto;

    constructor(
        private ptodataService: PTODataService,
        private empInfoService: EmpInfoService) { }

    resetRow(pto: PTOData): void {
        console.log(this.origPTO);
        this.rowSelected = null;
        this.onSave.emit(this.rowSelected);
    }
}

Body:
Your assignment statement origPTO: PTOData[] = this.pto; happens before the @Input() occurs. Instead, put the assignment in the OnInit lifecycle hook:

import { OnInit } from '@angular/core';

export class RowEditComponent implements OnInit {

    @Input() pto: PTOData[];
    origPTO: PTOData[];

    ngOnInit(): void {
        this.origPTO = this.pto;
    }
}

This still is not what you want, since it is not making a deep copy. Any changes to pto will also be made to origPTO. You should loop through the original array to make a deep copy:

this.origPTO = [];
this.pto.forEach(x => this.origPTO.push(x));


问:
Process DOM elements with PhantomJS
I'd like to load the full DOM of a website and process each element later. The example code / testcase is going to log all tags of a website.

This works perfect inside a normal browser:

```<code>var dom = document.getElementsByTagName('*'),
    i;

for (i in dom)
{
    console.log(dom[i] && dom[i].tagName ? dom[i].tagName : 'invalid');
}
</code>```

This testcase logs:

```<code>HTML
BODY
DIV
...etc...
</code>```

This doesn't work inside PHANTOMJS:

```<code>var page = require('webpage').create();

page.open('https://google.com', function ()
{
    var dom = page.evaluate(function ()
        {
            return document.getElementsByTagName('*');
        }),
        i;

    for (i in dom)
    {
        console.log(dom[i] && dom[i].tagName ? dom[i].tagName : 'invalid');
    }
    phantom.exit();
});
</code>```

For some reason, only the very first object contains values. Therefore this testcase logs:

```<code>HTML
invalid
invalid
...
</code>```

Help is wanted! Thank you

答:
From the docs:

Note: The arguments and the return value to the evaluate function must
  be a simple primitive object. The rule of thumb: if it can be
  serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

Finally, I found the answer... just prepare and return a simple object inside the evaluate method.

```<code>var page = require('webpage').create();

page.open('https://google.com', function ()
{
    var dom = page.evaluate(function ()
        {
            var temp =  document.getElementsByTagName('*'),
                tempArray = [],
                j;

            for (j in temp)
            {
                tempArray.push(
                {
                    tagName: temp[j].tagName,
                    className: temp[j].className
                });
            }
            return tempArray;
        }),
        i;

    for (i in dom)
    {
        console.log(dom[i] && dom[i].tagName ? dom[i].tagName : 'invalid');
        console.log(dom[i] && dom[i].className ? dom[i].className : 'invalid');
    }
    phantom.exit();
});
</code>```

Title: Process DOM elements with PhantomJS

Body:
I'd like to load the full DOM of a website and process each element later. The example code / testcase is going to log all tags of a website.

This works perfect inside a normal browser:

var dom = document.getElementsByTagName('*'),
    i;

for (i in dom)
{
    console.log(dom[i] && dom[i].tagName ? dom[i].tagName : 'invalid');
}

This testcase logs:

HTML
BODY
DIV
...etc...

This doesn't work inside PHANTOMJS:

var page = require('webpage').create();

page.open('https://google.com', function ()
{
    var dom = page.evaluate(function ()
        {
            return document.getElementsByTagName('*');
        }),
        i;

    for (i in dom)
    {
        console.log(dom[i] && dom[i].tagName ? dom[i].tagName : 'invalid');
    }
    phantom.exit();
});

For some reason, only the very first object contains values. Therefore this testcase logs:

HTML
invalid
invalid
...

Help is wanted! Thank you

Body:
From the docs:

Note: The arguments and the return value to the evaluate function must
  be a simple primitive object. The rule of thumb: if it can be
  serialized via JSON, then it is fine.

Closures, functions, DOM nodes, etc. will not work!

Finally, I found the answer... just prepare and return a simple object inside the evaluate method.

var page = require('webpage').create();

page.open('https://google.com', function ()
{
    var dom = page.evaluate(function ()
        {
            var temp =  document.getElementsByTagName('*'),
                tempArray = [],
                j;

            for (j in temp)
            {
                tempArray.push(
                {
                    tagName: temp[j].tagName,
                    className: temp[j].className
                });
            }
            return tempArray;
        }),
        i;

    for (i in dom)
    {
        console.log(dom[i] && dom[i].tagName ? dom[i].tagName : 'invalid');
        console.log(dom[i] && dom[i].className ? dom[i].className : 'invalid');
    }
    phantom.exit();
});


问:
Using HTML Divs to Make Navigation Bar
I'm just starting web development, and I'm trying to construct a page-navigation bar with a bunch of 'Div' elements, but I cant seem to get my second button ("AboutButton") to appear on the screen. Here is my HTML body code:

```<code><body>

    <div id="navbar" id="top">
        <div id="pageselection">
            <div id="HomeButton"> <a href="#top"> HOME </a> </div>
            <div id="AboutButton"> <a href="#About> ABOUT </a> </div>
        </div>
    </div>

</body>
</code>```

and here is my CSS for the page:

```<code>#navbar{
Position: fixed;
Width: 100%;
Height: 10%;
}

#pageselection{
Position: absolute;
Width: 40%;
Height: 100%;
Right: 30%;
}

#HomeButton{
Position: absolute;
Width: 33%;
Height: 100%;
Left: 0%;
text-align: center;
}

#AboutButton{
Position: absolute;
Width: 33%;
Height: 100%;
Left: 33%;
text-align: center;
}
</code>```

Essentially, I'm trying to build a 'div' that runs across the top of the page, then mark off the central 40% of that 'div' as a space for a second 'div' to sit, which will in turn hold the three links that users can use to navigate the page.

Thanks in advance, hopefully its a stupid error, and I hope my description was clear enough :)

答:
You missed an quote mark in

```<code><a href="#About>
</code>```

If you are only starting, i recommend you to use some free editors like Atom or Sublime that will alert you about this kind of errors.

Also, it is not allowed to use "id" two times on an element. A better practice would be to use classes where you will be able to stack them like:

```<code><div class="navbar top"></div>
</code>```

Title: Using HTML Divs to Make Navigation Bar

Body:
I'm just starting web development, and I'm trying to construct a page-navigation bar with a bunch of 'Div' elements, but I cant seem to get my second button ("AboutButton") to appear on the screen. Here is my HTML body code:

  HOME

  ABOUT

and here is my CSS for the page:

#navbar{
Position: fixed;
Width: 100%;
Height: 10%;
}

#pageselection{
Position: absolute;
Width: 40%;
Height: 100%;
Right: 30%;
}

#HomeButton{
Position: absolute;
Width: 33%;
Height: 100%;
Left: 0%;
text-align: center;
}

#AboutButton{
Position: absolute;
Width: 33%;
Height: 100%;
Left: 33%;
text-align: center;
}

Essentially, I'm trying to build a 'div' that runs across the top of the page, then mark off the central 40% of that 'div' as a space for a second 'div' to sit, which will in turn hold the three links that users can use to navigate the page.

Thanks in advance, hopefully its a stupid error, and I hope my description was clear enough :)

Body:
You missed an quote mark in

<a href="#About>

If you are only starting, i recommend you to use some free editors like Atom or Sublime that will alert you about this kind of errors.

Also, it is not allowed to use "id" two times on an element. A better practice would be to use classes where you will be able to stack them like:

<div class="navbar top"></div>


问:
Rollback a set of actions in Azure Logic Apps
I have a workflow like this as a Azure Logic App:

Read from Azure Table -> Process it in a Function -> Send Data to SQL Server -> Send an email

Currently we can check if the previous action ended with an error and based on that we do not execute any further steps.

Is it possible in Logic Apps to perform a Rollback of actions when one of the steps goes wrong? Meaning can we undo all the steps to the beginning when something in step 3 goes wrong, for example.

Thanks in advance.

Regards.

答:
Currently there is no support for rollback in Logic Apps (as they are not transnational).

Note that Logic Apps provide out-of-the-box resiliency against intermittent errors (retry strategies), which should minimize execution failures.

You can add custom handling of errors (e.g. following your example, if something goes in step 3, you can explicitly handle the failure and add rollback steps). Take a look at https://learn.microsoft.com/en-us/azure/logic-apps/logic-apps-exception-handling for details. You

Depending on whether steps in your logic app are idempotent you can also make use of the resubmit feature. It allows you to re-trigger the run with same trigger contents with which the original run instance was invoked. Take a look at https://www.codit.eu/blog/2017/02/logic-apps-resubmit-considerations/ for a good overview of this feature.


问:
nth word in a text
how can I find the nth word in a text.

example:

```<code>my_txt("hello to you all" , 3)

all
</code>```

I don't wanna use any built in function ...and this is not a homework :D

答:
OK you asked for this. You need a "split into words" function. Here it is. Assumes that "words" are delimited by whitespace.

No built-in functions, no imported anythings, no methods of built-in types, not even any panty-waist stuff like +=. And it's tested.

```<code>C:\junk>\python15\python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> def mysplit(s):
...     words = []
...     inword = 0
...     for c in s:
...         if c in " \r\n\t": # whitespace
...             inword = 0
...         elif not inword:
...             words = words + [c]
...             inword = 1
...         else:
...             words[-1] = words[-1] + c
...     return words
...
>>> mysplit('')
[]
>>> mysplit('x')
['x']
>>> mysplit('foo')
['foo']
>>> mysplit('  foo')
['foo']
>>> mysplit('  foo    ')
['foo']
>>> mysplit('\nfoo\tbar\rzot ugh\n\n   ')
['foo', 'bar', 'zot', 'ugh']
>>>
</code>```

Title: nth word in a text

Body:
how can I find the nth word in a text.

example:

my_txt("hello to you all" , 3)

all

I don't wanna use any built in function ...and this is not a homework :D

Body:
OK you asked for this. You need a "split into words" function. Here it is. Assumes that "words" are delimited by whitespace.

No built-in functions, no imported anythings, no methods of built-in types, not even any panty-waist stuff like +=. And it's tested.

C:\junk>\python15\python
Python 1.5.2 (#0, Apr 13 1999, 10:51:12) [MSC 32 bit (Intel)] on win32
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> def mysplit(s):
...     words = []
...     inword = 0
...     for c in s:
...         if c in " \r\n\t": # whitespace
...             inword = 0
...         elif not inword:
...             words = words + [c]
...             inword = 1
...         else:
...             words[-1] = words[-1] + c
...     return words
...
>>> mysplit('')
[]
>>> mysplit('x')
['x']
>>> mysplit('foo')
['foo']
>>> mysplit('  foo')
['foo']
>>> mysplit('  foo    ')
['foo']
>>> mysplit('\nfoo\tbar\rzot ugh\n\n   ')
['foo', 'bar', 'zot', 'ugh']
>>>


答:
It's okay to do what you do. If you do it often you can write a decorator for this:</p>

```<code>import functools

def trackcalls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.was_called = True
        return func(*args, **kwargs)
    wrapper.was_called = False
    return wrapper

@trackcalls
def _print_error(msg):
    print(msg)
    print("Default error message.")

_print_error()

# and then check it:
if _print_error.was_called:
   print("Alarm!")
</code>```

Title: Check if a function was callled

Body:
It's okay to do what you do. If you do it often you can write a decorator for this:

import functools

def trackcalls(func):
    @functools.wraps(func)
    def wrapper(*args, **kwargs):
        wrapper.was_called = True
        return func(*args, **kwargs)
    wrapper.was_called = False
    return wrapper

@trackcalls
def _print_error(msg):
    print(msg)
    print("Default error message.")

_print_error()

# and then check it:
if _print_error.was_called:
   print("Alarm!")