问:
Query data across multiple repositories in DDD
I am using multiple aggregate roots inside a DDD bounded context.

For example

```<code>public class OrderAggregate
{
    public int ID {get;set;}
    public string Order_Name {get;set;}
    public int Created_By_UserID {get;set;}
}

public class UserAggregate
{
    public int ID {get;set;}
    public string Username {get;set;}
    public string First_Name {get;set;}
    public string Last_Name {get;set;}
}
</code>```

I am using SQL relational base to persists domain objects. Each aggregate root matches one repository.

In case I would like to find an order that was created by John Doe (seach accross multiple aggregates) what would be a DDD way to go?

add First_Name and Last_Name into OrderAggregate in order to add FindByUserFirstLastName method in OrderRespository, but that could raise data consistency issue between two aggregate roots

create a raw sql query and access DB directly in order to span search accross "repositories"

use "finders" in order to join entities directly from DB

replicate data necessary for query to be completed to a new aggregate root such as

```<code>public class QueryOrderAggregate
{
    public int ID { get; set; }
    public string Order_Name { get; set; }
    public int Created_By_UserID { get; set; }
    public string First_Name { get; set; }
    public string Last_Name { get; set; }
}
</code>```

答:
In case I would like to find an order that was created by John Doe (seach accross multiple aggregates) what would be a DDD way to go?

Almost the same way that it goes with accessing an aggregate...

You create a Repository that provides a (whatever the name for this view/report is in your domain).  It probably uses the UserId as the key to identify the report.  In the implementation of the repository, the implementation can do whatever makes sense -- a SQL join is a reasonable starting point.

The View/Report is basically a value type; it is immutable, and can provide data, but doesn't not have any methods, or any direct access to the aggregate roots.  For example, the view might include the OrderId, but to actually get at the order aggregate root you would have to invoke a method on that repository.

A view that spans multiple aggregates is perfectly acceptable, because you can't actually modify anything using the view.  Changes to the underlying state still go through the aggregate roots, which provide the consistency guarantees.

The view is a representation of a stale snapshot of your data.  Consumers should not be expecting it to magically update -- if you want something more recent, go back to the repository for a new copy.

Body:
I am using multiple aggregate roots inside a DDD bounded context.

For example

public class OrderAggregate
{
    public int ID {get;set;}
    public string Order_Name {get;set;}
    public int Created_By_UserID {get;set;}
}

public class UserAggregate
{
    public int ID {get;set;}
    public string Username {get;set;}
    public string First_Name {get;set;}
    public string Last_Name {get;set;}
}

I am using SQL relational base to persists domain objects. Each aggregate root matches one repository.

In case I would like to find an order that was created by John Doe (seach accross multiple aggregates) what would be a DDD way to go?

add First_Name and Last_Name into OrderAggregate in order to add FindByUserFirstLastName method in OrderRespository, but that could raise data consistency issue between two aggregate roots

create a raw sql query and access DB directly in order to span search accross "repositories"

use "finders" in order to join entities directly from DB

replicate data necessary for query to be completed to a new aggregate root such as

public class QueryOrderAggregate
{
    public int ID { get; set; }
    public string Order_Name { get; set; }
    public int Created_By_UserID { get; set; }
    public string First_Name { get; set; }
    public string Last_Name { get; set; }
}


来源: stackexchange

问:
Can we have AMP and PWA on same URL/page?
We have already implemented our AMP page on our website - http://m.wishafriend.com/amp/
and we are also planning to implement PWA, so should we need to make a different page for PWA or is it possible to combine AMP and PWA on the same URL?</p>

答: @phpidz It is indeed possible to combine AMP and PWAs. There is a good section in the AMP Project website; it explains the context and the approaches you could follow.</p>

ContentLicense: CC BY-SA 3.0


问:
Can I inherit from one class to another in CSS
What I'm doing is creating multiple classes for different elements one is a hover class and the other is the non hovered version.  Only one or two things change between the two classes and I don't want to have to copy and paste the whole class over and change just one line.

So what I'd like to do is say have

```<code>.hoverOff {
background-color: green;
font-size: 14pt;
border: 2px;
width: 150px;
}
</code>```

And then I have a hover over class

```<code>.hoverOn {
background-color: red;
}
</code>```

I want to inherit everything else from the hoverOff class and only change the background color.  Can I inherit with CSS like that and overide inherited styles in the new class?  As it stands right now I'm simply copying the entire class, renaming it and changing one line.  Seems pretty redundant and archaic to me.

答:
If you want to consider inheritance in the most literal sense, check out CSS variables. Though I wouldn't use this in production code, it's an interesting feature that allows some cool things:

.foo {
  --bg-color: green;
  background-color: var(--bg-color);
  font-size: 14pt;
  border: 2px;
  width: 150px;
}

.foo:hover {
  --bg-color: red;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="foo">
  Hover over me
</div></code>```

Body:
What I'm doing is creating multiple classes for different elements one is a hover class and the other is the non hovered version.  Only one or two things change between the two classes and I don't want to have to copy and paste the whole class over and change just one line.

So what I'd like to do is say have

.hoverOff {
background-color: green;
font-size: 14pt;
border: 2px;
width: 150px;
}

And then I have a hover over class

.hoverOn {
background-color: red;
}

I want to inherit everything else from the hoverOff class and only change the background color.  Can I inherit with CSS like that and overide inherited styles in the new class?  As it stands right now I'm simply copying the entire class, renaming it and changing one line.  Seems pretty redundant and archaic to me.

Body:
If you want to consider inheritance in the most literal sense, check out CSS variables. Though I wouldn't use this in production code, it's an interesting feature that allows some cool things:

.foo {
  --bg-color: green;
  background-color: var(--bg-color);
  font-size: 14pt;
  border: 2px;
  width: 150px;
}

.foo:hover {
  --bg-color: red;
}

<div class="foo">
  Hover over me
</div>


问:
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.

答:
So what you see as application/x-java-object;type=com.maritz.avro.RoutingSlipMsg is because the default contentType for java objects is to serialize using Kryo, and that's what it set as contentType.

Since you want to use Confluent Schema Registry, that is not the default one, you need to setup a ConfluentSchemaRegistryClient bean, check it here how to enable it: http://docs.spring.io/spring-cloud-stream/docs/Ditmars.BUILD-SNAPSHOT/reference/htmlsingle/#_schema_registry_client

You now have a DefaultSchemaRegistryClient and it's probably having issues since the REST interface between the default server and confluent are not the same.

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.


问:
laravel 5.4 how to write select from multi table query
How am using laravel 5.4,

to write sql query to get data from multiple tables for below query

```<code>select l.party_id,l.container_id,p.party_name from
`tbl_container_lease` l, `tbl_partys` p
where l.`party_id` = p.`id` and l.`user_id` = 5
</code>```

Now am using this

```<code>Containerlease::whereHas('getpartys',function($q){})
->where('user_id','=',$user_id)
->get();
</code>```

but it is getting too confuse to use

is there any better alternative to use this query by using model..

答:
It would be better, since you're in laravel after all, to make use of laravel relationships.

Make sure you have a party model:

```<code>php artisan make:model Party
</code>```

Assuming one lease has one party, In your container lease model add:

```<code>public function party(){
    return $this->hasOne('App\Party', 'id', 'party_id');
}
</code>```

Then access your model

```<code>ContainerLease::with('party')->where('user_id', '=', 5)->get();
</code>```

Body:
How am using laravel 5.4,

to write sql query to get data from multiple tables for below query

select l.party_id,l.container_id,p.party_name from
`tbl_container_lease` l, `tbl_partys` p
where l.`party_id` = p.`id` and l.`user_id` = 5

Now am using this

Containerlease::whereHas('getpartys',function($q){})
->where('user_id','=',$user_id)
->get();

but it is getting too confuse to use

is there any better alternative to use this query by using model..

Body:
It would be better, since you're in laravel after all, to make use of laravel relationships.

Make sure you have a party model:

php artisan make:model Party

Assuming one lease has one party, In your container lease model add:

public function party(){
    return $this->hasOne('App\Party', 'id', 'party_id');
}

Then access your model

ContainerLease::with('party')->where('user_id', '=', 5)->get();


问:
Bootstrap Popover inside of a link in a table cell does not display
I have a link within a table cell that on the hover action, I would like a Bootstrap Popover to appear.  As of now, I cannot get this to work correctly.

Here is the code snippet:

```<code><table style="background: transparent; border: 0; outline: 0; border-collapse: collapse;">
 <tr style="background: transparent; border: 0; outline: 0;">
  <td style="background: transparent; border: 0; outline: 0; text-align:left; width:100px">
   <a href="#" id="lastBACommentCell" tabindex="0" data-toggle="popover" data-trigger="hover" data-placement="bottom" data-template="<div class='mainViewPopover' role='tooltip'><div class='arrow'></div><div class='popover-content' style='color: #FFFFFF;'></div></div>" data-content="Here is my popover">
    Hover here for the popover to appear...
   </a>
  </td>
 </tr>
</table>
...
    <script type="text/javascript" language="javascript">
     $(document).ready(function() {
      $('#lastBACommentCell').popover();
     });
    </script>
</code>```

I have tried putting a  inside the  tag, but it still will not display the popover.

Here is the JSFiddle - https://jsfiddle.net/dzeller44/swnbdjaq/

答:
I duplicated your code and it works for me without the data content.
I included bootstrap css library, jQuery and bootstrap js library (imp for popover to work).

Here is the link:
https://codepen.io/anon/pen/LLJrzJ

code:
 HTML

```<code>        <table style="background: transparent; border: 0; outline: 0; border-collapse: collapse;">
     <tr style="background: transparent; border: 0; outline: 0;">
      <td style="background: transparent; border: 0; outline: 0; text-align:left; width:100px">
       <a href="#" id="lastBACommentCell" tabindex="0" data-toggle="popover"  data-trigger="hover" data-placement="bottom" data-content="Here is my popover">
        Hover here for the popover to appear...
       </a>
  </td>
 </tr>
</table>
</code>```

JS

     $(document).ready(function() {
      $('[data-toggle="popover"]').popover({ trigger: "hover" });
     });

Body:
I have a link within a table cell that on the hover action, I would like a Bootstrap Popover to appear.  As of now, I cannot get this to work correctly.

Here is the code snippet:

    Hover here for the popover to appear...

...

I have tried putting a  inside the  tag, but it still will not display the popover.

Here is the JSFiddle - https://jsfiddle.net/dzeller44/swnbdjaq/

Body:
I duplicated your code and it works for me without the data content.
I included bootstrap css library, jQuery and bootstrap js library (imp for popover to work).

Here is the link:
https://codepen.io/anon/pen/LLJrzJ

code:
 HTML

        <table style="background: transparent; border: 0; outline: 0; border-collapse: collapse;">
     <tr style="background: transparent; border: 0; outline: 0;">
      <td style="background: transparent; border: 0; outline: 0; text-align:left; width:100px">
       <a href="#" id="lastBACommentCell" tabindex="0" data-toggle="popover"  data-trigger="hover" data-placement="bottom" data-content="Here is my popover">
        Hover here for the popover to appear...
       </a>
  </td>
 </tr>
</table>

JS

     $(document).ready(function() {
      $('[data-toggle="popover"]').popover({ trigger: "hover" });
     });


问:
Get month name from date in Oracle
How to fetch month name from a given date in Oracle?

If the given date is '15-11-2010' then I want November from this date.

答: to_char(mydate, 'MONTH') will do the job.

Title: Get month name from date in Oracle

ContentLicense: CC BY-SA 2.5


问:
SQLite database crashing my app
I am trying to make a project with android studio as in the video of :
Source 1 and Source 2
and here is my code in my added java class :

```<code>    package com.example.asus.androidsqlitedatabase_1;
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

    /**
     * Created by ASUS on 7/6/2017.
     */

    public class Databasehelperclass extends SQLiteOpenHelper {
        public static final String DATABASE_NAME = "Student.db";
        public static final String TABLE_NAME = "Student_table";
        public static final String COLUMN1= "ID";
        public static final String COLUMN2 = "NAME";
        public static final String COLUMN3 = "SURNAME";
        public static final String COLUMN4 = "MARKS";

        public Databasehelperclass(Context context) {
            super(context, DATABASE_NAME, null, 1);
            SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL("Create Table" + TABLE_NAME +
   "(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER)");}

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1){
            sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
            onCreate(sqLiteDatabase);
        }
    }
</code>```

and here is my code in MainActivity.java

```<code>    package com.example.asus.androidsqlitedatabase_1;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    public class MainActivity extends AppCompatActivity {
        Databasehelperclass mydb;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mydb = new Databasehelperclass(this);
        }
    }
</code>```

But when I execute the app to the emulator using genymotion, the app stopped working and it cant be executed. Please anyone help me !!

答:
Issue: Wrong spacing in query

Solution: query should be in this format:

```<code>sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + "("
                + COLUMN1 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN2 + " TEXT, "
                + COLUMN3 + " TEXT, "
                + COLUMN4 + " INTEGER, "
                + ")";
</code>```

PS: It is good practice to use Variable name instead of static column names in Query.

Hope it helps :)

Title: SQLite database crashing my app

Body:
I am trying to make a project with android studio as in the video of :
Source 1 and Source 2
and here is my code in my added java class :

    package com.example.asus.androidsqlitedatabase_1;
    import android.content.Context;
    import android.database.sqlite.SQLiteDatabase;
    import android.database.sqlite.SQLiteOpenHelper;

    /**
     * Created by ASUS on 7/6/2017.
     */

    public class Databasehelperclass extends SQLiteOpenHelper {
        public static final String DATABASE_NAME = "Student.db";
        public static final String TABLE_NAME = "Student_table";
        public static final String COLUMN1= "ID";
        public static final String COLUMN2 = "NAME";
        public static final String COLUMN3 = "SURNAME";
        public static final String COLUMN4 = "MARKS";

        public Databasehelperclass(Context context) {
            super(context, DATABASE_NAME, null, 1);
            SQLiteDatabase sqLiteDatabase = this.getWritableDatabase();
        }

        @Override
        public void onCreate(SQLiteDatabase sqLiteDatabase) {
            sqLiteDatabase.execSQL("Create Table" + TABLE_NAME +
   "(ID INTEGER PRIMARY KEY AUTOINCREMENT,NAME TEXT,SURNAME TEXT,MARKS INTEGER)");}

        @Override
        public void onUpgrade(SQLiteDatabase sqLiteDatabase, int i, int i1){
            sqLiteDatabase.execSQL("DROP TABLE IF EXISTS" + TABLE_NAME);
            onCreate(sqLiteDatabase);
        }
    }

and here is my code in MainActivity.java

    package com.example.asus.androidsqlitedatabase_1;

    import android.support.v7.app.AppCompatActivity;
    import android.os.Bundle;

    public class MainActivity extends AppCompatActivity {
        Databasehelperclass mydb;

        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            mydb = new Databasehelperclass(this);
        }
    }

But when I execute the app to the emulator using genymotion, the app stopped working and it cant be executed. Please anyone help me !!

Body:
Issue: Wrong spacing in query

Solution: query should be in this format:

sqLiteDatabase.execSQL("CREATE TABLE " + TABLE_NAME + "("
                + COLUMN1 + " INTEGER PRIMARY KEY AUTOINCREMENT, "
                + COLUMN2 + " TEXT, "
                + COLUMN3 + " TEXT, "
                + COLUMN4 + " INTEGER, "
                + ")";

PS: It is good practice to use Variable name instead of static column names in Query.

Hope it helps :)


问:
How to deal with new line characters in Windows vs Unix in Python Paramiko
Currently I am doing below task.

Create a small file in Windows using Python

Transfer this file to remote Unix environment using Paramiko Python library SFTP module

Problem faced:

Newline created on Windows is not properly converted to Unix new line character during the transfer. I see ^M characters inside the file on my remote host.

Any idea or suggestion how can I get rid of this behaviour.

When I do the transfer of the same file using WinSCP, I do not face this problem. I guess WinSCP has a built-in capability to handle this.

Python version used 3.5.

Step 1:

```<code>with open(myNewFile.txt,'w') as fileToUpload:
    fileToUpload.write('MyOwnTxt'+'\n')
</code>```

Step 2:

```<code>COMP = remoteServerHost
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(COMP, username=user, password=password, allow_agent = False)
src = myNewFile.txt
dst = "/remotePath/myNewFile.txt"
ftp = ssh.open_sftp()
ftp.put(src , dst)
ftp.close()
ssh.close()
</code>```

I am little surprised because no one has specified this problem in SO or any other forum. So it makes me feel is there something wrong on my Windows machine :(

答:
Paramiko does not support converting EOL sequences of transferred files.

You have to convert the contents before uploading it.

See Define transfer mode when trying to SFTP files using Python.

ContentLicense: CC BY-SA 4.0

Body:
Currently I am doing below task.

Create a small file in Windows using Python

Transfer this file to remote Unix environment using Paramiko Python library SFTP module

Problem faced:

Newline created on Windows is not properly converted to Unix new line character during the transfer. I see ^M characters inside the file on my remote host.

Any idea or suggestion how can I get rid of this behaviour.

When I do the transfer of the same file using WinSCP, I do not face this problem. I guess WinSCP has a built-in capability to handle this.

Python version used 3.5.

Step 1:

with open(myNewFile.txt,'w') as fileToUpload:
    fileToUpload.write('MyOwnTxt'+'\n')

Step 2:

COMP = remoteServerHost
ssh = paramiko.SSHClient()
ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
ssh.connect(COMP, username=user, password=password, allow_agent = False)
src = myNewFile.txt
dst = "/remotePath/myNewFile.txt"
ftp = ssh.open_sftp()
ftp.put(src , dst)
ftp.close()
ssh.close()

I am little surprised because no one has specified this problem in SO or any other forum. So it makes me feel is there something wrong on my Windows machine :(


问:
How to access an element of a list using a variable in python
Given that I have a target location for a multi-dimensional list. I.e. an index stored in a variable.

```<code>list = [[1,2,3,4,5],
        [10,20,30,40,50],
        [5,4,3,2,1],
        [50,40,30,20,10]]
target = [3][4]
</code>```

How do I access list[target]?

```<code>  >>> list[target]
    10
</code>```

答:
You can't do this directly because list[variable] will become an entry of the list; the variable must be an index.

So what you need is some way to get list[variable][variable][variable]

This can't be done with a simple variable sadly, even though it would be really cool.

The best way to do it would be to make a recursive function to do it, which takes your list target=[3,4,1] and returns the value, as so.

```<code>def target_value(my_list, place):
    if len(place) == 1:
        return my_list[place[0]]
    return target_value(my_list[place[0]],place[1:])
</code>```

Then you would call it as a normal function, giving your list and target (target = [3,4,1]) as parameters.

Body:
Given that I have a target location for a multi-dimensional list. I.e. an index stored in a variable.

list = [[1,2,3,4,5],
        [10,20,30,40,50],
        [5,4,3,2,1],
        [50,40,30,20,10]]
target = [3][4]

How do I access list[target]?

  >>> list[target]
    10

Body:
You can't do this directly because list[variable] will become an entry of the list; the variable must be an index.

So what you need is some way to get list[variable][variable][variable]

This can't be done with a simple variable sadly, even though it would be really cool.

The best way to do it would be to make a recursive function to do it, which takes your list target=[3,4,1] and returns the value, as so.

def target_value(my_list, place):
    if len(place) == 1:
        return my_list[place[0]]
    return target_value(my_list[place[0]],place[1:])

Then you would call it as a normal function, giving your list and target (target = [3,4,1]) as parameters.


问:
1004 error for range argument
I have another simple syntax question that I can't quite figure out. I want to change all the cells in a column so they have a bottom border and have a variable to figure out the last night with data on it.

My code is below and I believe the error is how I am trying to define the last cell.

```<code>wsSheet.Range("F11:wsSheet.Cells(LastRowForSig, 6)").Borders(xlEdgeBottom).LineStyle = xlContinuous
</code>```

答:
Try this code below

```<code>Dim r1 as Range, r2 as Range
Set r1 = wsSheet.Range("F11")
Set r2 = wsSheet.Cells(LastRowForSig, 6)

wsSheet.Range(r1 & ":" & r2).Borders(xlEdgeBottom).LineStyle = xlContinuous
</code>```

Edited after request.

Title: 1004 error for range argument

Body:
I have another simple syntax question that I can't quite figure out. I want to change all the cells in a column so they have a bottom border and have a variable to figure out the last night with data on it.

My code is below and I believe the error is how I am trying to define the last cell.

wsSheet.Range("F11:wsSheet.Cells(LastRowForSig, 6)").Borders(xlEdgeBottom).LineStyle = xlContinuous

Body:
Try this code below

Dim r1 as Range, r2 as Range
Set r1 = wsSheet.Range("F11")
Set r2 = wsSheet.Cells(LastRowForSig, 6)

wsSheet.Range(r1 & ":" & r2).Borders(xlEdgeBottom).LineStyle = xlContinuous

Edited after request.


问:
what is the role of ob_start() in here
```<code>session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {
    $hasDB = true;
    mysql_select_db($db);
}
</code>```

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..

答:
Normally php sends all text not included in <?php ... ?>, all echos, all prints to the output. Which is send to the err... output: http server (which sends it to a client), console etc.

After ob_start this output is saved in output buffer, so you can later decide what to do with it.

It doesn't affect db connection. It deals with text (mostly) produced by php.

Title: what is the role of ob_start() in here

Body:
session_start();
ob_start();
$hasDB = false;
$server = 'localhost';
$user = 'user';
$pass = 'pass';
$db = 'acl_test';
$link = mysql_connect($server,$user,$pass);
if (!is_resource($link)) {
    $hasDB = false;
    die("Could not connect to the MySQL server at localhost.");
} else {
    $hasDB = true;
    mysql_select_db($db);
}

a) what does ob_start() exactly do.? i got to understand it will turn output buffering on. with reference to the above code what will be the benefit if i use ob_start() while trying to establish the connection with the database. what output data it will buffer?

thank you..


问:
Rails - Can't install RMagick 2.16.0. Can't find MagickWand.h
I appreciate this question has been asked many times before, however I've tried all available answers to no avail. The error log is as follows:

```<code>have_header: checking for wand/MagickWand.h... -------------------- no

"gcc -E -I/Users/mark/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0/x86_64-darwin16 -I/Users/mark/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0/ruby/backward -I/Users/mark/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0 -I.  -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -I/usr/local/Cellar/imagemagick/7.0.4-8/include/ImageMagick-7  -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -I/usr/local/Cellar/imagemagick/7.0.4-8/include/ImageMagick-7  conftest.c -o conftest.i"
conftest.c:3:10: fatal error: 'wand/MagickWand.h' file not found
#include <wand/MagickWand.h>
     ^
1 error generated.
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: #include <wand/MagickWand.h>
/* end */
</code>```

After running mdfind MagickWand.h I can see the path is:

```<code>/usr/local/Cellar/imagemagick/7.0.4-8/include/ImageMagick-7/MagickWand/MagickWand.h
</code>```

I then run:

```<code>C_INCLUDE_PATH=/usr/local/Cellar/imagemagick/7.0.4-8/include/ImageMagick-7/MagickWand/ gem install rmagick
</code>```

However get the same message as before.

Any help for how to get this solved is greatly appreciated.

答:
Imagemagick 7 seems to not cooperate. Here is what I have found, it works for me:

```<code>brew update
brew rm imagemagick
brew install imagemagick@6
brew link imagemagick@6 --force
bundle
</code>```

If you do not want to force link you can also do the following:

```<code>brew install imagemagick@6
PKG_CONFIG_PATH=/usr/local/opt/imagemagick@6/lib/pkgconfig gem install rmagick
</code>```

per @Leo's comment

Please look at this GitHub Issue for more details.

Body:
I appreciate this question has been asked many times before, however I've tried all available answers to no avail. The error log is as follows:

have_header: checking for wand/MagickWand.h... -------------------- no

"gcc -E -I/Users/mark/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0/x86_64-darwin16 -I/Users/mark/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0/ruby/backward -I/Users/mark/.rvm/rubies/ruby-2.3.3/include/ruby-2.3.0 -I.  -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -I/usr/local/Cellar/imagemagick/7.0.4-8/include/ImageMagick-7  -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -DMAGICKCORE_HDRI_ENABLE=1 -DMAGICKCORE_QUANTUM_DEPTH=16 -I/usr/local/Cellar/imagemagick/7.0.4-8/include/ImageMagick-7  conftest.c -o conftest.i"
conftest.c:3:10: fatal error: 'wand/MagickWand.h' file not found
#include <wand/MagickWand.h>
     ^
1 error generated.
checked program was:
/* begin */
1: #include "ruby.h"
2:
3: #include <wand/MagickWand.h>
/* end */

After running mdfind MagickWand.h I can see the path is:

/usr/local/Cellar/imagemagick/7.0.4-8/include/ImageMagick-7/MagickWand/MagickWand.h

I then run:

C_INCLUDE_PATH=/usr/local/Cellar/imagemagick/7.0.4-8/include/ImageMagick-7/MagickWand/ gem install rmagick

However get the same message as before.

Any help for how to get this solved is greatly appreciated.

Body:
Imagemagick 7 seems to not cooperate. Here is what I have found, it works for me:

brew update
brew rm imagemagick
brew install imagemagick@6
brew link imagemagick@6 --force
bundle

If you do not want to force link you can also do the following:

brew install imagemagick@6
PKG_CONFIG_PATH=/usr/local/opt/imagemagick@6/lib/pkgconfig gem install rmagick

per @Leo's comment

Please look at this GitHub Issue for more details.


问:
Get values of 2 columns as single value separated with '|'
```<code>DECLARE @mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO @mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');

SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
      +ISNULL(NULLIF(Column2,'-'),'')
FROM @mockup
</code>```

Above query result is as below,

```<code>1|2
2
1|2
2|
1|2
</code>```

I want the result as above only except row4, where 2| should be only as 2 .
'|' should not be there at before or end of the values.

答:
Use Replace function

```<code>SELECT replace(replace(replace(Column1 + '|' + Column2,'-|',''),'|-',''),'-','')
FROM @mockup
</code>```

or try using CASE statement

```<code>SELECT CASE
         WHEN column1 LIKE '[0-9]' AND column2 LIKE '[0-9]' THEN column1 + '|' + column1
         WHEN column1 LIKE '[0-9]' AND column2 NOT LIKE '[0-9]' THEN column1
         ELSE column2
       END
FROM   @mockup
</code>```

if you want to check the - instead of numbers then

```<code>SELECT CASE
         WHEN column1 NOT LIKE '-'  AND column2 NOT LIKE '-' THEN column1 + '|' + column1
         WHEN column1 NOT LIKE '-'  AND column2 LIKE '-' THEN column1
         ELSE column2
       END
FROM   @mockup
</code>```

Body:
DECLARE @mockup TABLE(Column1 VARCHAR(1),Column2 VARCHAR(1));
INSERT INTO @mockup VALUES('1','2'),('-','2'),('1','2'),('-','-'),('2','-'),('1','2');

SELECT ISNULL(NULLIF(Column1 + '|','-|'),'')
      +ISNULL(NULLIF(Column2,'-'),'')
FROM @mockup

Above query result is as below,

1|2
2
1|2
2|
1|2

I want the result as above only except row4, where 2| should be only as 2 .
'|' should not be there at before or end of the values.

Body:
Use Replace function

SELECT replace(replace(replace(Column1 + '|' + Column2,'-|',''),'|-',''),'-','')
FROM @mockup

or try using CASE statement

SELECT CASE
         WHEN column1 LIKE '[0-9]' AND column2 LIKE '[0-9]' THEN column1 + '|' + column1
         WHEN column1 LIKE '[0-9]' AND column2 NOT LIKE '[0-9]' THEN column1
         ELSE column2
       END
FROM   @mockup

if you want to check the - instead of numbers then

SELECT CASE
         WHEN column1 NOT LIKE '-'  AND column2 NOT LIKE '-' THEN column1 + '|' + column1
         WHEN column1 NOT LIKE '-'  AND column2 LIKE '-' THEN column1
         ELSE column2
       END
FROM   @mockup


问:
How to pass 2 variables from a method to another method?
I'm currently stuck on a problem that I can't seem to solve.

I need to pass 2 variables from this method:

```<code>public void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    String start = "";
    String ziel = "";

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while (bereich1.contains(""+start) && bereich2.contains(""+ziel)
           || bereich2.contains(""+start) && bereich1.contains(""+ziel) || start.matches(ziel)) {

            System.out.println("Geben Sie einen Startpunkt an: ");
            start = in.next();

            while (!start.matches("\\b[a-oA-O]\\b")) {
                   System.out.println("Geben Sie einen korrekten Startpunkt an: ");
                   start = in.next();
            }

            System.out.println("Geben Sie einen Zielpunkt an: ");
            ziel = in.next();

            while (!start.matches("\\b[a-oA-O]\\b")) {
                   System.out.println("Geben Sie einen korrekten Zielpunkt an: ");
                   start = in.next();

            }
    }

    program(start, ziel);
}
</code>```

At the bottom I call the method program():

```<code>private void program(String start, String ziel) {
    // find connection from 'I' to 'O'
    connection = network.findConnection(start, ziel);

    // print the path
    System.out.println(connection.getPath());
    // print the distance
    System.out.println(connection.getTime());
}
</code>```

And I'm trying to pass through the String variables start and ziel and use them in findConnection()

I get the error (I'm using Eclipse IDE):

```<code>Exception in thread "main" java.lang.IllegalArgumentException: graph must contain the end vertex
</code>```

Note: findConnection() requires String arguments, which start and ziel are. If I were to put for example "a" and "b" as arguments in findConnection() it would work.

Thanks for any help.

答:
Well probably network.findConnection is checking the values and throw an exception if empty.
Check the Strings if blank before call the private method and if in.hasNext() (Scanner)

As for your code these are my observations:
I think your loop should be something like this, you have a mixture of ANDs and ORs

```<code>while ((bereich1.contains(""+start) && bereich2.contains(""+ziel)) || (bereich2.contains(""+start) && bereich1.contains(""+ziel)) || start.matches(ziel)) {
</code>```

Secondly I think

```<code>System.out.println("Geben Sie einen Zielpunkt an: ");

ziel = in.next();
while (!start.matches("\\b[a-oA-O]\\b")) {
System.out.println("Geben Sie einen korrekten Zielpunkt an: ");
ziel = in.next(); //ziel not start
}
</code>```

The thing I don't understand is you have an outer loop and inside loops should the the outer while be an if?!!!

And before call program (string, string) can you check that values are not null or empty.

Body:
I'm currently stuck on a problem that I can't seem to solve.

I need to pass 2 variables from this method:

public void neueRoute() {
    Scanner in = new Scanner(System.in);

    String bereich1 = "aAbBcCdDeEfFgG";
    String bereich2 = "hHiIjJkKlLmMnNoO";
    String start = "";
    String ziel = "";

    System.out.println("Themenbereich 1: Bahn A - G: ");
    System.out.println("\nA\nB\nC\nD\nE\nF\nG\n");
    System.out.println("Themenbereich 2: Bahn H - O: ");
    System.out.println("\nH\nI\nJ\nK\nL\nM\nN\nO");

    while (bereich1.contains(""+start) && bereich2.contains(""+ziel)
           || bereich2.contains(""+start) && bereich1.contains(""+ziel) || start.matches(ziel)) {

            System.out.println("Geben Sie einen Startpunkt an: ");
            start = in.next();

            while (!start.matches("\\b[a-oA-O]\\b")) {
                   System.out.println("Geben Sie einen korrekten Startpunkt an: ");
                   start = in.next();
            }

            System.out.println("Geben Sie einen Zielpunkt an: ");
            ziel = in.next();

            while (!start.matches("\\b[a-oA-O]\\b")) {
                   System.out.println("Geben Sie einen korrekten Zielpunkt an: ");
                   start = in.next();

            }
    }

    program(start, ziel);
}

At the bottom I call the method program():

private void program(String start, String ziel) {
    // find connection from 'I' to 'O'
    connection = network.findConnection(start, ziel);

    // print the path
    System.out.println(connection.getPath());
    // print the distance
    System.out.println(connection.getTime());
}

And I'm trying to pass through the String variables start and ziel and use them in findConnection()

I get the error (I'm using Eclipse IDE):

Exception in thread "main" java.lang.IllegalArgumentException: graph must contain the end vertex

Note: findConnection() requires String arguments, which start and ziel are. If I were to put for example "a" and "b" as arguments in findConnection() it would work.

Thanks for any help.

Body:
Well probably network.findConnection is checking the values and throw an exception if empty.
Check the Strings if blank before call the private method and if in.hasNext() (Scanner)

As for your code these are my observations:
I think your loop should be something like this, you have a mixture of ANDs and ORs

while ((bereich1.contains(""+start) && bereich2.contains(""+ziel)) || (bereich2.contains(""+start) && bereich1.contains(""+ziel)) || start.matches(ziel)) {

Secondly I think

System.out.println("Geben Sie einen Zielpunkt an: ");

ziel = in.next();
while (!start.matches("\\b[a-oA-O]\\b")) {
System.out.println("Geben Sie einen korrekten Zielpunkt an: ");
ziel = in.next(); //ziel not start
}

The thing I don't understand is you have an outer loop and inside loops should the the outer while be an if?!!!

And before call program (string, string) can you check that values are not null or empty.


问:
Write a function called circle that takes a turtle, t, and radius, r, as param
```<code>import turtle
bob = turtle.Turtle()
def polygon(t,length,n):
   for i in range(n):
      t.fd(length)
      t.lt(360/n)
   print(t)

polygon(bob,30,15)

turtle.mainloop()
</code>```

How can I make a circle by calling polygon function?

答:
You already have written the correct code to produce a circle.  In the view of turtle's own circle() method, a circle is just a polygon with 60 sides (fewer if the circle is small.)  I.e. it's about perception and how many sides do you need before you can't tell the difference.

```<code>import turtle

def polygon(t, length, n):
    for _ in range(n):
        t.fd(length)
        t.lt(360 / n)

bob = turtle.Turtle()

bob.penup()
bob.sety(-270)
bob.pendown()

polygon(bob, 30, 60)

turtle.mainloop()
</code>```

Your problem now is to control the drawing of the polygon/circle to produce it with a specific radius.  Your length parameter doesn't map to a radius as the circle is coming out way too large.  Here length represents 1/60 (1/n) of the circumference and we know that:

circumference = 2 * math.pi * radius

We can calculate, in our circle(t, radius) function, what length needs to be given radius (i.e. circumference/n), and call polygon(t, length, n) with these parameters.  Here's a visual comparison drawing a radius 100 circle with turtle's circle() method (red) and drawing it with the solution I just described (blue):

Body:
import turtle
bob = turtle.Turtle()
def polygon(t,length,n):
   for i in range(n):
      t.fd(length)
      t.lt(360/n)
   print(t)

polygon(bob,30,15)

turtle.mainloop()

How can I make a circle by calling polygon function?

Body:
You already have written the correct code to produce a circle.  In the view of turtle's own circle() method, a circle is just a polygon with 60 sides (fewer if the circle is small.)  I.e. it's about perception and how many sides do you need before you can't tell the difference.

import turtle

def polygon(t, length, n):
    for _ in range(n):
        t.fd(length)
        t.lt(360 / n)

bob = turtle.Turtle()

bob.penup()
bob.sety(-270)
bob.pendown()

polygon(bob, 30, 60)

turtle.mainloop()

Your problem now is to control the drawing of the polygon/circle to produce it with a specific radius.  Your length parameter doesn't map to a radius as the circle is coming out way too large.  Here length represents 1/60 (1/n) of the circumference and we know that:

circumference = 2 * math.pi * radius

We can calculate, in our circle(t, radius) function, what length needs to be given radius (i.e. circumference/n), and call polygon(t, length, n) with these parameters.  Here's a visual comparison drawing a radius 100 circle with turtle's circle() method (red) and drawing it with the solution I just described (blue):


问:
Delete an object in Django
I am trying to delete an object. This is the HTML, todo should be deleted when you Click on button (I am trying to call delete_todo) :-

```<code><ul>
          {% for all %}

        </ul>
</code>```

This is the views.py,

答:
You need to change few things in your code.
First of all change urlpattern delete_todo you need to add argument, which allows to determine in view what object you want to delete:

```<code>url(r'^(?P<todo_id>[0-9]+)/$', views.delete_todo, name='delete_todo'),
</code>```

Then you need change delete_todo itself:

```<code>def delete_todo(request, todo_id):
    instance = get_object_or_404(Todo, pk=todo_id)
    instance.delete()
    return redirect('index')
</code>```

Here you can use get_object_or_404 fuction to get object with id.

And finally you need to pass url's argument to view from template:

```<code><form action="{% url 'lists:delete_todo' todo_id=todo.id %}" method=post>
      <input id="submit" type="button" value="Click" />
</form>
</code>```

Title: Delete an object in Django

Body:
I am trying to delete an object. This is the HTML, todo should be deleted when you Click on button (I am trying to call delete_todo) :-

          {% for all %}

This is the views.py,

Body:
You need to change few things in your code.
First of all change urlpattern delete_todo you need to add argument, which allows to determine in view what object you want to delete:

url(r'^(?P<todo_id>[0-9]+)/$', views.delete_todo, name='delete_todo'),

Then you need change delete_todo itself:

def delete_todo(request, todo_id):
    instance = get_object_or_404(Todo, pk=todo_id)
    instance.delete()
    return redirect('index')

Here you can use get_object_or_404 fuction to get object with id.

And finally you need to pass url's argument to view from template:

<form action="{% url 'lists:delete_todo' todo_id=todo.id %}" method=post>
      <input id="submit" type="button" value="Click" />
</form>


问:
Django ManyToMany field get all values from an object without a 'for'
Is it possible to get the values of a ManyToMany from an object without using a 'for'?

models.py

```<code>class Citizenship(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Citizenship"

    def __str__(self):
        return self.name

class Anexa(models.Model):
    name = models.CharField(max_length=150, help_text="3")
    citizenship = models.ManyToManyField(Citizenship, help_text="4")
</code>```

I have an Anexa object with the name Alex and i have 4 citizenships for this object. I'm searching for something equivalent to this:

```<code>for citizenships in x.citizenship.all():
    print(citizenships.name)
</code>```

答:
If you want to abstract away the looping you can create a method on the model:

```<code>class Anexa(models.Model):
    def print_citizens_names(self):
        for name in self.citizenship.values_list('name', flat=True):
            print(name)
</code>```

Then in your codebase you can just do this:

```<code>x.print_citizens_names()
</code>```

Body:
Is it possible to get the values of a ManyToMany from an object without using a 'for'?

models.py

class Citizenship(models.Model):
    name = models.CharField(max_length=100)

    class Meta:
        verbose_name_plural = "Citizenship"

    def __str__(self):
        return self.name

class Anexa(models.Model):
    name = models.CharField(max_length=150, help_text="3")
    citizenship = models.ManyToManyField(Citizenship, help_text="4")

I have an Anexa object with the name Alex and i have 4 citizenships for this object. I'm searching for something equivalent to this:

for citizenships in x.citizenship.all():
    print(citizenships.name)

Body:
If you want to abstract away the looping you can create a method on the model:

class Anexa(models.Model):
    def print_citizens_names(self):
        for name in self.citizenship.values_list('name', flat=True):
            print(name)

Then in your codebase you can just do this:

x.print_citizens_names()


问:
Using COUNTIF, OFFSET, MATCH in Excel
I keep getting an error around this certain part of my COUNTIF function and cannot find out why. I believe it's cause the Offset function won't output a range. It seems to work fine if I manually put a range, but that isn't an option.

How do I get a range as an output using Match?

```<code>=COUNTIFS(OFFSET(Sheet2!$A$1,0,MATCH(I$1,Sheet2!1:1,0)),"*Accountable*")
</code>```

答:
I think you want to count "Accountable" from $A$1 until the found match, so you are trying to "expand" the cell A1 by as many cells. The parameter to enlarge the number of columns in the OFFSET function is parameter 5. Try this:

```<code>=COUNTIFS(OFFSET(Sheet2!$A$1,0,0,1,MATCH(I$1,Sheet2!1:1,0)),"Accountable")
'                              ^^^
</code>```

You could use INDEX to achieve the same. (sometimes preferred for its non-volatility):

```<code>=COUNTIFS(Sheet2!$A$1:INDEX(Sheet2!1:1,MATCH(I$1,Sheet2!1:1,0)),"Accountable")
</code>```

Title: Using COUNTIF, OFFSET, MATCH in Excel

Body:
I keep getting an error around this certain part of my COUNTIF function and cannot find out why. I believe it's cause the Offset function won't output a range. It seems to work fine if I manually put a range, but that isn't an option.

How do I get a range as an output using Match?

=COUNTIFS(OFFSET(Sheet2!$A$1,0,MATCH(I$1,Sheet2!1:1,0)),"*Accountable*")

Body:
I think you want to count "Accountable" from $A$1 until the found match, so you are trying to "expand" the cell A1 by as many cells. The parameter to enlarge the number of columns in the OFFSET function is parameter 5. Try this:

=COUNTIFS(OFFSET(Sheet2!$A$1,0,0,1,MATCH(I$1,Sheet2!1:1,0)),"Accountable")
'                              ^^^

You could use INDEX to achieve the same. (sometimes preferred for its non-volatility):

=COUNTIFS(Sheet2!$A$1:INDEX(Sheet2!1:1,MATCH(I$1,Sheet2!1:1,0)),"Accountable")


问:
How to migrate a file and all its commit history to a new repo in git?
I have a repo (repoA) and a file in that repo has 20-30 commits; I want to move that file to repoB with all of the commit history; how do I do that?</p>

答:
As I understand you want to move changes only from one file and save the history of all repository.

Commits in git aren't about some file. They are about repository.

Maybe you can do something like:

1)get file changes from repoA and copy them in repoB as new commit.

2)after some time push repoB into master for example

3)merge master with repoA. Resolve conflicts if any.


问:
Downloading Attachment from Exchange Server using SSIS package deployed on another Server
I have built an SSIS package which reads CSV from certain folder. But now I need to download same csv from exchange server.Also Outlook is not installed on my machine. Will I be able to download CSV from exchange server and how ? Thanks!</p>

答:
I have used some of the code from the link http://sqlandbilearning.blogspot.com.au/2014/07/download-email-attachment-using-ssis.html but i have added some new code for removing TCP binding error using ServicePointManager as well as added search filter for retrieving specific emails and this code also takes care of multiple attachment from different emails to be saved on file system.</p>

```<code>public void Main()
        {
            string filePath = "";
            string fileName = "";
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            DateTime now = DateTime.Now;
            DateTime beginRecievedTime = new DateTime(now.Year, now.Month, now.Day, 7, 55, 0);
            DateTime finishRecievedTime = new DateTime(now.Year, now.Month, now.Day, 8, 15, 0);
            EmailMessage latestEmail = null;

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.UseDefaultCredentials = true;
                //service.Credentials = new WebCredentials("username", "password");

                service.Url = new Uri("");

                //  10 mails per page in DESC order
                ItemView view = new ItemView(10);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Scheduled search"));
                SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, beginRecievedTime);
                searchFilterCollection.Add(greaterthanfilter);
                SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, finishRecievedTime);
                searchFilterCollection.Add(lessthanfilter);
                SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection);
                //Find mails
                FindItemsResults<Item> fir = service.FindItems(WellKnownFolderName.Inbox, filter, view);
                Dictionary<EmailMessage, string> emailsMap = new Dictionary<EmailMessage, string>();
                foreach (Item item in fir.Items)
                {
                    item.Load(); //Load the entire message with attachment
                    EmailMessage email = item as EmailMessage;
                    if (email != null)
                    {
                        if (email.HasAttachments == true && email.Attachments.Count == 1)
                        {
                            if (email.Subject.StartsWith("Scheduled search") == true)
                            {
                                filePath = Path.Combine(Dts.Variables["User::SourceFolderPath"].Value.ToString()
                                                        , email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                                                        email.Attachments[0].Name);
                                // fileName = email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                                //   email.Attachments[0].Name.ToString();
                                emailsMap.Add(email, filePath);
                            }
                        }
                    }
                }

                if (emailsMap.Count > 0) {
                    foreach (var item in emailsMap) {
                        //Save attachment
                        EmailMessage email = item.Key;
                        filePath = item.Value;
                            FileAttachment fileAttachment = email.Attachments[0] as FileAttachment;
                            fileAttachment.Load(filePath);
                        string extractPath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.Attachments[0].Name;
                        System.IO.Compression.ZipFile.ExtractToDirectory(filePath, extractPath);
                        fileName = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                          email.Attachments[0].Name.ToString();
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                    }
            }

               // Dts.Variables["User::SourceFileName"].Value = fileName;

                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch(System.Runtime.InteropServices.COMException ex)
            {
                if (Dts.Variables.Locked == true)
                {
                    Dts.Variables.Unlock();
                }
                //An error occurred.
                Dts.Events.FireError(0, "Error occured", ex.Message, String.Empty, 0);
                Dts.TaskResult = (int)ScriptResults.Failure;
            }
        }
</code>```

Body:
I have used some of the code from the link http://sqlandbilearning.blogspot.com.au/2014/07/download-email-attachment-using-ssis.html but i have added some new code for removing TCP binding error using ServicePointManager as well as added search filter for retrieving specific emails and this code also takes care of multiple attachment from different emails to be saved on file system.

public void Main()
        {
            string filePath = "";
            string fileName = "";
            List<SearchFilter> searchFilterCollection = new List<SearchFilter>();
            DateTime now = DateTime.Now;
            DateTime beginRecievedTime = new DateTime(now.Year, now.Month, now.Day, 7, 55, 0);
            DateTime finishRecievedTime = new DateTime(now.Year, now.Month, now.Day, 8, 15, 0);
            EmailMessage latestEmail = null;

            try
            {
                ServicePointManager.ServerCertificateValidationCallback = (sender, certificate, chain, sslPolicyErrors) => true;

                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2010);
                service.UseDefaultCredentials = true;
                //service.Credentials = new WebCredentials("username", "password");

                service.Url = new Uri("");

                //  10 mails per page in DESC order
                ItemView view = new ItemView(10);
                view.OrderBy.Add(ItemSchema.DateTimeReceived, SortDirection.Descending);
                searchFilterCollection.Add(new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Scheduled search"));
                SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.DateTimeReceived, beginRecievedTime);
                searchFilterCollection.Add(greaterthanfilter);
                SearchFilter lessthanfilter = new SearchFilter.IsLessThan(ItemSchema.DateTimeReceived, finishRecievedTime);
                searchFilterCollection.Add(lessthanfilter);
                SearchFilter filter = new SearchFilter.SearchFilterCollection(LogicalOperator.And, searchFilterCollection);
                //Find mails
                FindItemsResults<Item> fir = service.FindItems(WellKnownFolderName.Inbox, filter, view);
                Dictionary<EmailMessage, string> emailsMap = new Dictionary<EmailMessage, string>();
                foreach (Item item in fir.Items)
                {
                    item.Load(); //Load the entire message with attachment
                    EmailMessage email = item as EmailMessage;
                    if (email != null)
                    {
                        if (email.HasAttachments == true && email.Attachments.Count == 1)
                        {
                            if (email.Subject.StartsWith("Scheduled search") == true)
                            {
                                filePath = Path.Combine(Dts.Variables["User::SourceFolderPath"].Value.ToString()
                                                        , email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                                                        email.Attachments[0].Name);
                                // fileName = email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                                //   email.Attachments[0].Name.ToString();
                                emailsMap.Add(email, filePath);
                            }
                        }
                    }
                }

                if (emailsMap.Count > 0) {
                    foreach (var item in emailsMap) {
                        //Save attachment
                        EmailMessage email = item.Key;
                        filePath = item.Value;
                            FileAttachment fileAttachment = email.Attachments[0] as FileAttachment;
                            fileAttachment.Load(filePath);
                        string extractPath = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.Attachments[0].Name;
                        System.IO.Compression.ZipFile.ExtractToDirectory(filePath, extractPath);
                        fileName = Dts.Variables["User::SourceFolderPath"].Value.ToString() + "\\" + email.DateTimeReceived.Date.ToString("MM.dd.yyyy") + "_" +
                          email.Attachments[0].Name.ToString();
                        if (File.Exists(fileName))
                        {
                            File.Delete(fileName);
                        }
                    }
            }

               // Dts.Variables["User::SourceFileName"].Value = fileName;

                Dts.TaskResult = (int)ScriptResults.Success;
            }
            catch(System.Runtime.InteropServices.COMException ex)
            {
                if (Dts.Variables.Locked == true)
                {
                    Dts.Variables.Unlock();
                }
                //An error occurred.
                Dts.Events.FireError(0, "Error occured", ex.Message, String.Empty, 0);
                Dts.TaskResult = (int)ScriptResults.Failure;
            }
        }