问:
MVC Razor build onclick event dynamically to show modal
I am currently trying to attach a click handler to my  tag which will pop up my modal which has a dynamic id. I am having trouble figuring out the syntax to accomplish this- my current attempt can be found below and has a syntax error on onclick="$('#"+ @modalId + "')" (which is the part im struggling a bit with). How can I accomplish this?

```<code>var modalId = string.Format("docusign{0}", doc.Id)
<a href="#" onclick="$('#"+ @modalId + "').modal('toggle')">@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))</a>

<div id="@modalId" class="modal fade" role="dialog">
  <div class="modal-dialog">
    <div class="modal-content">
      <div class="modal-header" style="background-color:#337ab7;color:#ffffff">
         <button type="button" class="close" data-dismiss="modal">×</button>
         <h4 class="modal-title">DocuSign Notice</h4>
      </div>
      <div class="modal-body form-group">
      <h5>Please allow up to 10 minutes for us to receive your e-form after you have completed it. To continue and fill out the necessary e-form, please click the "Fill Form" button below</h5>
    </div>
    <div class="modal-footer">
      <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
      <a class="btn btn-default pull-left" href=@doc.DocuSignPowerFormLink>Fill Form</a>
      </div>
    </div>
  </div>
</div>
</code>```

答:
Try this

@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))

Body:
I am currently trying to attach a click handler to my  tag which will pop up my modal which has a dynamic id. I am having trouble figuring out the syntax to accomplish this- my current attempt can be found below and has a syntax error on onclick="$('#"+ @modalId + "')" (which is the part im struggling a bit with). How can I accomplish this?

var modalId = string.Format("docusign{0}", doc.Id)
@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))

         <button type="button" class="close" data-dismiss="modal">×</button>

DocuSign Notice

Please allow up to 10 minutes for us to receive your e-form after you have completed it. To continue and fill out the necessary e-form, please click the "Fill Form" button below

      <button type="button" class="btn btn-default pull-right" data-dismiss="modal">Close</button>
      Fill Form

Body:
Try this

<a href="#" onclick="$('#@modalId').modal('toggle')">@string.Format("Document {0}", EnumHelper.GetDisplayName(doc.DocumentType))</a>


来源: stackexchange

问:
File handles in Perl
Instead of the typical file handle I am used to:

```<code>open INPUT, $input;
while ($line = <INPUT>) {
    ....
}
close INPUT;
</code>```

How do I retrieve a pointer to the line in a file so that I can advance these pointers at wiil? I'm trying to create two pointers to their corresponding sorted files so that I can advance pointers based on whether the line in one file is "less" or "greater" than the line in the other.

Note: Assume input files are BIG.

答:
Given the answer to my comment, then you need to revise your logic to something like (pseudo-code):

```<code>open Master;
open Transaction;

# Get initial records?
read first Master;
read first Transaction;

BATCH_LOOP:
while (!eof(Master) && !eof(Transaction))
{
     while (Master.ID < Transaction.ID && !eof(Master))
     {
           write Master;
           read next Master;
     }
     if (Master.ID > Transaction.ID)
     {
           report Missing Master for Transaction;
           read next Transaction;
           next BATCH_LOOP;
     }
     # Master.ID == Transaction.ID
     Update Master from Transaction;
     read next Transaction;
}

# At most one of the following two loop bodies is executed
while (!eof(Master))
{
     read next Master;
     write Master;
}

while (!eof(Transaction))
{
     Report Missing Master;
     read next Transaction;
}
</code>```

Double (and triple) check the logic - it was written on the fly around distractions.  But it is close to what you need.

Use lexical file handles:

```<code>open my $master, "<", $master_file or die "Failed to open master file $master_file ($!)";
open my $trans,  "<", $trans_file  or die "Failed to open transaction file $trans_file ($!)";
</code>```

You can read those independently of each other.

ContentLicense: CC BY-SA 2.5

Title: File handles in Perl

Body:
Instead of the typical file handle I am used to:

open INPUT, $input;
while ($line = <INPUT>) {
    ....
}
close INPUT;

How do I retrieve a pointer to the line in a file so that I can advance these pointers at wiil? I'm trying to create two pointers to their corresponding sorted files so that I can advance pointers based on whether the line in one file is "less" or "greater" than the line in the other.

Note: Assume input files are BIG.

Body:
Given the answer to my comment, then you need to revise your logic to something like (pseudo-code):

open Master;
open Transaction;

# Get initial records?
read first Master;
read first Transaction;

BATCH_LOOP:
while (!eof(Master) && !eof(Transaction))
{
     while (Master.ID < Transaction.ID && !eof(Master))
     {
           write Master;
           read next Master;
     }
     if (Master.ID > Transaction.ID)
     {
           report Missing Master for Transaction;
           read next Transaction;
           next BATCH_LOOP;
     }
     # Master.ID == Transaction.ID
     Update Master from Transaction;
     read next Transaction;
}

# At most one of the following two loop bodies is executed
while (!eof(Master))
{
     read next Master;
     write Master;
}

while (!eof(Transaction))
{
     Report Missing Master;
     read next Transaction;
}

Double (and triple) check the logic - it was written on the fly around distractions.  But it is close to what you need.

Use lexical file handles:

open my $master, "<", $master_file or die "Failed to open master file $master_file ($!)";
open my $trans,  "<", $trans_file  or die "Failed to open transaction file $trans_file ($!)";

You can read those independently of each other.


问:
Endless RecyclerView with ProgressBar for pagination
I am using a RecyclerView and fetching objects from an API in batches of ten. For pagination, I use EndlessRecyclerOnScrollListener.

It's all working properly. Now all that's left is to add a progress spinner at the bottom of the list while the next batch of objects is fetched by the API. Here is a screenshot of the Google Play Store app, showing a ProgressBar in what is surely a RecyclerView:

The problem is, neither the RecyclerView nor the EndlessRecyclerOnScrollListener have built-in support for showing a ProgressBar at the bottom while the next batch of objects is being fetched.

I have already seen the following answers:

1. Put an indeterminate ProgressBar as footer in a RecyclerView grid.

2. Adding items to Endless Scroll RecyclerView with ProgressBar at bottom.

I am not satisfied with those answers (both by the same person). This involves shoehorning a null  object into the data-set midway while the user is scrolling and then taking it out after the next batch is delivered. It looks like a hack that sidesteps the main problem which may or may not work properly. And it causes a bit of jarring and distortion in the list

Using SwipeRefreshLayout is not a solution here. SwipeRefreshLayout involves pulling from the top to fetch the newest items, and it does not show a progress view anyway.

Can someone please provide a good solution for this? I am interested in knowing how Google has implemented this for their own apps (the Gmail app has it too). Are there any articles where this is shown in detail? All answers & comments will be appreciated. Thank you.

Some other references:

1. Pagination with RecyclerView. (Superb overview ...)

2. RecyclerView header and footer. (More of the same ...)

3. Endless RecyclerView with ProgressBar at bottom.

答:
HERE IS SIMPLER AND CLEANER APPROACH.

Implement Endless Scrolling from this Codepath Guide and then follow the following steps.

1. Add progress bar under the RecyclerView.

```<code>    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_movie_grid"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:paddingBottom="50dp"
        android:clipToPadding="false"
        android:background="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </android.support.v7.widget.RecyclerView>

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        android:background="@android:color/transparent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />
</code>```

Here android:paddingBottom="50dp" and android:clipToPadding="false" are very important.

2. Get a reference to the progress bar.

```<code>progressBar = findViewById(R.id.progressBar);
</code>```

3. Define methods to show and hide progress bar.

```<code>void showProgressView() {
    progressBar.setVisibility(View.VISIBLE);
}

void hideProgressView() {
    progressBar.setVisibility(View.INVISIBLE);
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
HERE IS SIMPLER AND CLEANER APPROACH.

Implement Endless Scrolling from this Codepath Guide and then follow the following steps.

1. Add progress bar under the RecyclerView.

    <android.support.v7.widget.RecyclerView
        android:id="@+id/rv_movie_grid"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:paddingBottom="50dp"
        android:clipToPadding="false"
        android:background="@android:color/black"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent">

    </android.support.v7.widget.RecyclerView>

    <ProgressBar
        android:id="@+id/progressBar"
        style="?android:attr/progressBarStyle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:visibility="invisible"
        android:background="@android:color/transparent"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent" />

Here android:paddingBottom="50dp" and android:clipToPadding="false" are very important.

2. Get a reference to the progress bar.

progressBar = findViewById(R.id.progressBar);

3. Define methods to show and hide progress bar.

void showProgressView() {
    progressBar.setVisibility(View.VISIBLE);
}

void hideProgressView() {
    progressBar.setVisibility(View.INVISIBLE);
}


问:
How to play audio stream chunks recorded with WebRTC?
I'm trying to create an experimental application that streams audio in real time from client 1 to client 2.

So following some tutorials and questions about the same subject, I used WebRTC and binaryjs. So far this is what I get

1- Client 1 and Client 2 have connected to BinaryJS to send/receive data chunks.

2- Client 1 used WebRTC to record audio and gradually send it to BinaryJS

3- Client 2 receives the chunks and try to play them.

Well I'm getting an error in the last part. This is the error message I get:

Uncaught RangeError: Source is too large

at Float32Array.set (native)

And this is the code:

Client 1

```<code>var WSClient;
var AudioStream;

function load(){
    var session = {
        audio: true,
        video: false
    };

    var recordRTC = null;

    navigator.getUserMedia(session, startRecording, onError);
    WSClient = new BinaryClient('ws://localhost:9001');
    WSClient.on('open',function(){
        console.log('client opened')
        AudioStream = WSClient.createStream();
    })
}

function startRecording(stream){
    var context = new AudioContext();
    var audio_input = context.createMediaStreamSource(stream);
    var buffer_size = 2048;

    var recorder = context.createScriptProcessor(buffer_size, 1, 1);

    recorder.onaudioprocess = function(e){
        console.log('chunk')
        var left = e.inputBuffer.getChannelData(0);
        AudioStream.write(left);
    };

    audio_input.connect(recorder);
    recorder.connect(context.destination);
}
</code>```

Client 2

```<code>var WSClient;
var audioContext;
var sourceNode;

function load(){
    audioContext = new AudioContext();
    sourceNode = audioContext.createBufferSource();
    sourceNode.connect(audioContext.destination);

    sourceNode.start(0);

    WSClient = new BinaryClient('ws://localhost:9001');

    WSClient.on('open',function(){
        console.log('client opened');
    });

    WSClient.on('stream', function(stream, meta){
        // collect stream data
        stream.on('data', function(data){
            console.log('received chunk')
            var integers = new Int16Array(data);
            var audioBuffer = audioContext.createBuffer(1, 2048, 4410);
            audioBuffer.getChannelData(0).set(integers); //appearently this is where the error occurs
            sourceNode.buffer = audioBuffer;
        });
    });
}
</code>```

Server

```<code>var wav = require('wav');
var binaryjs = require('binaryjs');

var binaryjs_server = binaryjs.BinaryServer;

var server = binaryjs_server({port: 9001});

server.on('connection', function(client){
    console.log('server connected');

    var file_writter = null;

    client.on('stream', function(stream, meta){
        console.log('streaming', server.clients)
        //send to other clients
        for(var id in server.clients){
            if(server.clients.hasOwnProperty(id)){
                var otherClient = server.clients[id];
                if(otherClient != client){
                    var send = otherClient.createStream(meta);
                    stream.pipe(send);
                }
            }
        }
    });

    client.on('close', function(stream){
        console.log('client closed')
        if(file_writter != null) file_writter.end();
    });
});
</code>```

The error occurs here:

```<code>audioBuffer.getChannelData(0).set(integers);
</code>```

So I have two questions:

Is it possible to send the chunks I captured in client 1 and then reproduce them in client 2?

What is the deal with the error I'm having?

Thanks guys!

@edit 1

Since i'm getting code snippets from other questions I'm still trying to understand it. I commented the line in client 2 code that creates an Int16Array and I now get a different error (but I don't know which version of the code is more correct):

Uncaught DOMException: Failed to set the 'buffer' property on 'AudioBufferSourceNode': Cannot set buffer after it has been already been set

Probably because I'm setting it everytime I get a new chunk of data.

答:
The DOMException about AudioBufferSourceNode means you need to create a new AudioBufferSourceNode for every new Audiobuffer that you're creating.  So something like

sourceNode = new AudioBufferSourceNode(audioContext, {buffer: audioBuffer})

And an AudioBuffer has Float32Arrays.  You need to convert your
Int16Array to a Float32Array before assigning it to an
AudioBuffer.  Probably good enough to divide everything by 32768.

Body:
I'm trying to create an experimental application that streams audio in real time from client 1 to client 2.

So following some tutorials and questions about the same subject, I used WebRTC and binaryjs. So far this is what I get

1- Client 1 and Client 2 have connected to BinaryJS to send/receive data chunks.

2- Client 1 used WebRTC to record audio and gradually send it to BinaryJS

3- Client 2 receives the chunks and try to play them.

Well I'm getting an error in the last part. This is the error message I get:

Uncaught RangeError: Source is too large

at Float32Array.set (native)

And this is the code:

Client 1

var WSClient;
var AudioStream;

function load(){
    var session = {
        audio: true,
        video: false
    };

    var recordRTC = null;

    navigator.getUserMedia(session, startRecording, onError);
    WSClient = new BinaryClient('ws://localhost:9001');
    WSClient.on('open',function(){
        console.log('client opened')
        AudioStream = WSClient.createStream();
    })
}

function startRecording(stream){
    var context = new AudioContext();
    var audio_input = context.createMediaStreamSource(stream);
    var buffer_size = 2048;

    var recorder = context.createScriptProcessor(buffer_size, 1, 1);

    recorder.onaudioprocess = function(e){
        console.log('chunk')
        var left = e.inputBuffer.getChannelData(0);
        AudioStream.write(left);
    };

    audio_input.connect(recorder);
    recorder.connect(context.destination);
}

Client 2

var WSClient;
var audioContext;
var sourceNode;

function load(){
    audioContext = new AudioContext();
    sourceNode = audioContext.createBufferSource();
    sourceNode.connect(audioContext.destination);

    sourceNode.start(0);

    WSClient = new BinaryClient('ws://localhost:9001');

    WSClient.on('open',function(){
        console.log('client opened');
    });

    WSClient.on('stream', function(stream, meta){
        // collect stream data
        stream.on('data', function(data){
            console.log('received chunk')
            var integers = new Int16Array(data);
            var audioBuffer = audioContext.createBuffer(1, 2048, 4410);
            audioBuffer.getChannelData(0).set(integers); //appearently this is where the error occurs
            sourceNode.buffer = audioBuffer;
        });
    });
}

Server

var wav = require('wav');
var binaryjs = require('binaryjs');

var binaryjs_server = binaryjs.BinaryServer;

var server = binaryjs_server({port: 9001});

server.on('connection', function(client){
    console.log('server connected');

    var file_writter = null;

    client.on('stream', function(stream, meta){
        console.log('streaming', server.clients)
        //send to other clients
        for(var id in server.clients){
            if(server.clients.hasOwnProperty(id)){
                var otherClient = server.clients[id];
                if(otherClient != client){
                    var send = otherClient.createStream(meta);
                    stream.pipe(send);
                }
            }
        }
    });

    client.on('close', function(stream){
        console.log('client closed')
        if(file_writter != null) file_writter.end();
    });
});

The error occurs here:

audioBuffer.getChannelData(0).set(integers);

So I have two questions:

Is it possible to send the chunks I captured in client 1 and then reproduce them in client 2?

What is the deal with the error I'm having?

Thanks guys!

@edit 1

Since i'm getting code snippets from other questions I'm still trying to understand it. I commented the line in client 2 code that creates an Int16Array and I now get a different error (but I don't know which version of the code is more correct):

Uncaught DOMException: Failed to set the 'buffer' property on 'AudioBufferSourceNode': Cannot set buffer after it has been already been set

Probably because I'm setting it everytime I get a new chunk of data.


问:
Drupal 8 select list first as default value
Please, I want to know if there's a simple way in Drupal 8 to make a select list first value always as default value and delete "Select a value" line.
Thank you very much</p>

答:
This can be easily done by adding a List(text) field. After adding the values to your select list choose a default value from that select list as shown in the image below.

Default value for select list

Under Manage Form Display choose select list. This should display the default value set and not 'Select a Value'. Hope this help.


问:
How do I enter values in the database?
I output the necessary WC object values using the class, I make changes to the input field, and I need to rewrite the values. Tell me, how can I do this?</p>

```<code><form>
<!-- Various input fields -->
<?php
$delivery_zones = WC_Shipping_Zones::get_zones();

foreach($delivery_zones[1]['shipping_methods'] as $zone_key=>$zone) { ?>
  <label>
    <?php echo $zone->method_title ?><span>*</span>
    <input type="number" value="<?php echo $zone->cost ?>"> // In this string
  </label>
<?php } ?>
<input type="submit" value="<?php echo $edit_action ? "Save" : "Add"; ?> Product">
</form>
</code>```

答:
```<code><form>
<!-- Various input fields -->
<?php $delivery_zones = WC_Shipping_Zones::get_zones(); ?>

<?php foreach($delivery_zones[1]['shipping_methods'] as $zone_key=>$zone) { ?>
    <?php  $zone_title = mb_strtolower(str_replace(' ', '_', $zone->title));   ?>

    <label>
      <?php echo $zone->title ?><span>*</span>
      <input  id="product_shipping_method_<?php echo $zone_title ?>"
              type="number"
              name="shipping_method_<?php echo $zone_title ?>"
              value="<?php echo $edit_action ? get_post_meta($product_id,'_shipping_method_' . $zone_title, true) : ""; ?>"/>
    </label>
<?php } ?>
  <input type="submit" value="<?php echo $edit_action ? "Save" : "Add"; ?> Product">
</form>
</code>```

In the file with the functional, you need to update_post_meta:

```<code>$delivery_zones = WC_Shipping_Zones::get_zones();
foreach($delivery_zones[2]['shipping_methods'] as $zone_key=>$zone) {
    $zone_title = mb_strtolower(str_replace(' ', '_', $zone->title));
    update_post_meta($product_id, '_ed_shipping_method_' . $zone_title, $_POST['shipping_method_'.$zone_title]);
}
</code>```

Title: How do I enter values in the database?

Body:
I output the necessary WC object values using the class, I make changes to the input field, and I need to rewrite the values. Tell me, how can I do this?

<form>

<?php
$delivery_zones = WC_Shipping_Zones::get_zones();

foreach($delivery_zones[1]['shipping_methods'] as $zone_key=>$zone) { ?>

    <?php echo $zone->method_title ?>*
    <input type="number" value="<?php echo $zone->cost ?>"> // In this string

<?php } ?>
<input type="submit" value="<?php echo $edit_action ? "Save" : "Add"; ?> Product">
</form>

Body:
<form>
<!-- Various input fields -->
<?php $delivery_zones = WC_Shipping_Zones::get_zones(); ?>

<?php foreach($delivery_zones[1]['shipping_methods'] as $zone_key=>$zone) { ?>
    <?php  $zone_title = mb_strtolower(str_replace(' ', '_', $zone->title));   ?>

    <label>
      <?php echo $zone->title ?><span>*</span>
      <input  id="product_shipping_method_<?php echo $zone_title ?>"
              type="number"
              name="shipping_method_<?php echo $zone_title ?>"
              value="<?php echo $edit_action ? get_post_meta($product_id,'_shipping_method_' . $zone_title, true) : ""; ?>"/>
    </label>
<?php } ?>
  <input type="submit" value="<?php echo $edit_action ? "Save" : "Add"; ?> Product">
</form>

In the file with the functional, you need to update_post_meta:

$delivery_zones = WC_Shipping_Zones::get_zones();
foreach($delivery_zones[2]['shipping_methods'] as $zone_key=>$zone) {
    $zone_title = mb_strtolower(str_replace(' ', '_', $zone->title));
    update_post_meta($product_id, '_ed_shipping_method_' . $zone_title, $_POST['shipping_method_'.$zone_title]);
}


问:
(class file version 53.0), Java Runtime versions up to 52.0 Visual studio code
I'm trying to use visual studio code for Java.

Have installed the extensions for Java, and have a 1.8 JDK installed with environment variable pointing to the install.

When starting debugger with a simple hello world program, I get the following:

java.lang.UnsupportedClassVersionError: HelloWorld has been compiled by a more recent version of the Java Runtime (class file version 53.0), this version of the Java Runtime only recognizes class file versions up to 52.0
    at java.lang.ClassLoader.defineClass1(Native Method)
    ......
        ......
        at sun.launcher.LauncherHelper.checkAndLoadMain(LauncherHelper.java:495)

Any help with getting Java debugging in Visual Studio code appreciated.

答:
You are probably compiling (or using dependencies compiled) with java 9, but still using JDK 8.0

Install java 9 and change your OS environment settings to point to the new JDK. This should solve your problem.


问:
Camel JMSComponent not getting registered in JUnit Failed to resolve endpoint
Iam trying to send message to a JMSQueue in Junit test cases and iam getting exception No component found with scheme: hornetq. I have registered the component in the bean declaration.But still it is throwing error.

Junit Test class:

```<code>import java.io.File;

import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.test.spring.CamelSpringJUnit4ClassRunner;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(CamelSpringJUnit4ClassRunner.class)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:/META-INF/spring/camel-context.xml",
        "classpath:/META-INF/spring/policyHolderRoutepolicyHolderRoute.xml", "classpath:/META-INF/spring/policyRoute.xml" })
public class OnlineComponentTest extends CamelTestSupport {
    private static final Logger LOGGER = LoggerFactory.getLogger(OnlineComponentTest.class);
    @Autowired
    private CamelContext context;

    @Produce(uri = "hornetq://queue:EVENT.API.IN.ONLINE")
    protected ProducerTemplate template;

    @EndpointInject(uri = "mock:cxfrs://bean://importPolicyHolderRestEndpoint")
    protected MockEndpoint mockImportpolicyHolderEndpoint;

    @EndpointInject(uri = "mock:cxfrs://bean://importPolicyRestEndpoint")
    protected MockEndpoint mockImportpolicyEndpoint;

    @Test
    public void testOnlineRouteSuccess() throws Exception {
        template.sendBody("hornetq://queue:EVENT.API.IN.ONLINE", FileUtils.readFileToString(new File(
                "src/test/resources/componenttest/success/input/onlineinqueue-request.json")));
    }
}
</code>```

Defined component with HornetQ in test resources:

```<code><bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="vm://broker?broker.persistent=false" />
    </bean>

    <!-- setup spring jms TX manager -->
    <bean id="jmsTransactionManager"
        class="org.springframework.jms.connection.JmsTransactionManager">
        <property name="connectionFactory" ref="jmsConnectionFactory" />
    </bean>

    <bean id="hornetq" class="org.apache.camel.component.jms.JmsComponent">
        <property name="connectionFactory" ref="jmsConnectionFactory" />
        <!-- define the jms consumer/producer as transacted -->
        <property name="transacted" value="true" />
        <!-- setup the transaction manager to use -->
        <!-- if not provided then Camel will automatic use a JmsTransactionManager,
            however if you for instance use a JTA transaction manager then you must configure
            it -->
        <property name="transactionManager" ref="jmsTransactionManager" />
    </bean>
</code>```

Junit Logs:

```<code>2017-11-14 09:57:42,559 [main           ]  INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [META-INF/spring/camel-context.xml]
2017-11-14 09:57:43,186 [main           ]  INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [META-INF/spring/bean-declarations.xml]
2017-11-14 09:57:45,984 [main           ]  INFO  DefaultListableBeanFactory     - Overriding bean definition for bean 'OnlineInEndpoint': replacing [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-11-14 09:57:45,985 [main           ]  INFO  DefaultListableBeanFactory     - Overriding bean definition for bean '_to2': replacing [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-11-14 09:57:45,986 [main           ]  INFO  DefaultListableBeanFactory     - Overriding bean definition for bean '_to1': replacing [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-11-14 09:57:45,990 [main           ]  INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [META-INF/spring/policyHolderRoute.xml]
2017-11-14 09:57:46,099 [main           ]  INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [META-INF/spring/policyRoute.xml]
2017-11-14 09:57:46,202 [main           ]  INFO  CamelSpringTestContextLoader   - Disabling Camel JMX globally for tests by default.  Use the DisableJMX annotation to override the default setting.
2017-11-14 09:57:46,257 [main           ]  INFO  GenericApplicationContext      - Refreshing org.springframework.context.support.GenericApplicationContext@71318ec4: startup date [Tue Nov 14 09:57:46 GMT 2017]; root of context hierarchy
2017-11-14 09:57:46,711 [main           ]  INFO  ePropertyPlaceholderConfigurer - Loading properties file from class path resource [com/company/esb/environment/properties/common.properties]
2017-11-14 09:57:46,712 [main           ]  INFO  ePropertyPlaceholderConfigurer - Loading properties file from class path resource [com/company/esb/environment/properties/online.properties]
2017-11-14 09:57:46,726 [main           ]  INFO  redAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-11-14 09:57:46,780 [main           ]  INFO  DefaultListableBeanFactory     - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@41dd05a: defining beans [eventLogger,bridgePropertyPlaceholder,jmsConnectionFactory,jmsTransactionManager,hornetq,importPolicyRestEndpoint,importPolicyHolderRestEndpoint,*.http-conduit,OnlineInEndpoint,_to2,_to1,template,consumerTemplate,OnlineContext:beanPostProcessor,OnlineContext,policyHolderRouteContext,policyRouteContext,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
2017-11-14 09:57:47,913 [main           ]  INFO  CamelContextFactoryBean        - Bridging Camel and Spring property placeholder configurer with id: bridgePropertyPlaceholder
2017-11-14 09:57:48,777 [main           ]  INFO  DefaultTypeConverter           - Loaded 201 type converters
2017-11-14 09:57:48,799 [main           ]  INFO  CamelSpringTestContextLoader   - Setting shutdown timeout to [10 SECONDS] on CamelContext with name [OnlineContext].
2017-11-14 09:57:48,811 [main           ]  INFO  CamelSpringTestContextLoader   - Enabling lazy loading of type converters on CamelContext with name [OnlineContext].
2017-11-14 09:57:48,813 [main           ]  INFO  CamelSpringTestContextLoader   - Starting CamelContext with name [OnlineContext].
2017-11-14 09:57:48,815 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) is starting
2017-11-14 09:57:48,821 [main           ]  INFO  DefaultManagementStrategy      - JMX is disabled
2017-11-14 09:57:50,991 [main           ]  INFO  SpringCamelContext             - AllowUseOriginalMessage is enabled. If access to the original message is not needed, then its recommended to turn this option off as it may improve performance.
2017-11-14 09:57:51,147 [main           ]  INFO  DefaultStreamCachingStrategy   - StreamCaching in use with spool directory: C:\Users\jmjl29k\AppData\Local\Temp\camel\camel-tmp-8dce384f-0ca4-4e09-9560-53a30d7b089f and rules: [Spool > 128K body size]
2017-11-14 09:57:51,222 [main           ]  INFO  SpringCamelContext             - Route: policyRoute started and consuming from: Endpoint[direct://policyLoad]
2017-11-14 09:57:51,223 [main           ]  INFO  SpringCamelContext             - Route: policyHolderRoute started and consuming from: Endpoint[direct://policyHolderLoad]
2017-11-14 09:57:51,237 [main           ]  INFO  SpringCamelContext             - Route: OnlineInWriteConsumerRoute started and consuming from: Endpoint[hornetq://queue:EVENT.API.IN.ONLINE]
2017-11-14 09:57:51,237 [main           ]  INFO  SpringCamelContext             - Total 3 routes, of which 3 are started.
2017-11-14 09:57:51,240 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) started in 2.424 seconds
2017-11-14 09:57:51,450 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,450 [main           ]  INFO  OnlineComponentTest            - Testing: testOnlineRouteSuccess(com.company.esb.online.OnlineComponentTest)
2017-11-14 09:57:51,450 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,605 [.API.IN.ONLINE]]  INFO  BrokerService                  - Using Persistence Adapter: MemoryPersistenceAdapter
2017-11-14 09:57:51,610 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,622 [main           ]  INFO  OnlineComponentTest            - Testing done: testOnlineRouteSuccess(com.company.esb.online.OnlineComponentTest)
2017-11-14 09:57:51,622 [main           ]  INFO  OnlineComponentTest            - Took: 9.366 seconds (9366 millis)
2017-11-14 09:57:51,622 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,645 [main           ]  INFO  DefaultCamelContext            - Apache Camel 2.17.0.redhat-630262 (CamelContext: camel-2) is shutting down
2017-11-14 09:57:51,646 [main           ]  INFO  DefaultCamelContext            - Apache Camel 2.17.0.redhat-630262 (CamelContext: camel-2) uptime
2017-11-14 09:57:51,646 [main           ]  INFO  DefaultCamelContext            - Apache Camel 2.17.0.redhat-630262 (CamelContext: camel-2) is shutdown in 0.023 seconds
2017-11-14 09:57:51,647 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,647 [main           ]  INFO  OnlineComponentTest            - Testing done: testOnlineRouteSuccess(com.company.esb.online.OnlineComponentTest)
2017-11-14 09:57:51,647 [main           ]  INFO  OnlineComponentTest            - Took: 0.197 seconds (197 millis)
2017-11-14 09:57:51,647 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,647 [main           ]  INFO  GenericApplicationContext      - Closing org.springframework.context.support.GenericApplicationContext@71318ec4: startup date [Tue Nov 14 09:57:46 GMT 2017]; root of context hierarchy
2017-11-14 09:57:51,649 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) is shutting down
2017-11-14 09:57:51,651 [main           ]  INFO  DefaultShutdownStrategy        - Starting to graceful shutdown 3 routes (timeout 10 seconds)
2017-11-14 09:57:51,889 [JMX connector  ]  INFO  ManagementContext              - JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
2017-11-14 09:57:52,063 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) is starting
2017-11-14 09:57:52,084 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) started
2017-11-14 09:57:52,084 [.API.IN.ONLINE]]  INFO  BrokerService                  - For help or more information please see: http://activemq.apache.org
2017-11-14 09:57:52,105 [.API.IN.ONLINE]]  WARN  BrokerService                  - Temporary Store limit is 51200 mb (current store usage is 0 mb). The data directory: C:\Temp\GITRepo\esb\routes\Online only has 26504 mb of usable space. - resetting to maximum available disk space: 26504 mb
2017-11-14 09:57:52,195 [.API.IN.ONLINE]]  INFO  TransportConnector             - Connector vm://broker started
2017-11-14 09:57:53,612 [.API.IN.ONLINE]]  INFO  TransportConnector             - Connector vm://broker stopped
2017-11-14 09:57:53,613 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) is shutting down
2017-11-14 09:57:53,634 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) uptime 2.167 seconds
2017-11-14 09:57:53,634 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) is shutdown
2017-11-14 09:57:53,634 [ - ShutdownTask]  INFO  DefaultShutdownStrategy        - Route: OnlineInWriteConsumerRoute shutdown complete, was consuming from: Endpoint[hornetq://queue:EVENT.API.IN.ONLINE]
2017-11-14 09:57:53,635 [ - ShutdownTask]  INFO  DefaultShutdownStrategy        - Route: policyHolderRoute shutdown complete, was consuming from: Endpoint[direct://policyHolderLoad]
2017-11-14 09:57:53,635 [ - ShutdownTask]  INFO  DefaultShutdownStrategy        - Route: policyRoute shutdown complete, was consuming from: Endpoint[direct://policyLoad]
2017-11-14 09:57:53,635 [main           ]  INFO  DefaultShutdownStrategy        - Graceful shutdown of 3 routes completed in 1 seconds
2017-11-14 09:57:53,640 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) uptime 4.827 seconds
2017-11-14 09:57:53,640 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) is shutdown in 1.991 seconds
2017-11-14 09:57:53,643 [main           ]  INFO  DefaultListableBeanFactory     - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@41dd05a: defining beans [eventLogger,bridgePropertyPlaceholder,jmsConnectionFactory,jmsTransactionManager,hornetq,importPolicyRestEndpoint,importPolicyHolderRestEndpoint,*.http-conduit,OnlineInEndpoint,_to2,_to1,template,consumerTemplate,OnlineContext:beanPostProcessor,OnlineContext,policyHolderRouteContext,policyRouteContext,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
</code>```

Exception:

```<code>org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: hornetq://queue:EVENT.API.IN.ONLINE due to: No component found with scheme: hornetq
    at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:595)
    at org.apache.camel.util.CamelContextHelper.getEndpointInjection(CamelContextHelper.java:174)
    at org.apache.camel.impl.CamelPostProcessorHelper.doGetEndpointInjection(CamelPostProcessorHelper.java:157)
    at org.apache.camel.impl.CamelPostProcessorHelper.getEndpointInjection(CamelPostProcessorHelper.java:152)
    at org.apache.camel.impl.CamelPostProcessorHelper.createInjectionProducerTemplate(CamelPostProcessorHelper.java:289)
    at org.apache.camel.impl.CamelPostProcessorHelper.getInjectionValue(CamelPostProcessorHelper.java:205)
    at org.apache.camel.impl.DefaultCamelBeanPostProcessor.injectField(DefaultCamelBeanPostProcessor.java:195)
    at org.apache.camel.impl.DefaultCamelBeanPostProcessor$1.doWith(DefaultCamelBeanPostProcessor.java:187)
    at org.apache.camel.util.ReflectionHelper.doWithFields(ReflectionHelper.java:73)
    at org.apache.camel.impl.DefaultCamelBeanPostProcessor.injectFields(DefaultCamelBeanPostProcessor.java:168)
    at org.apache.camel.impl.DefaultCamelBeanPostProcessor.postProcessBeforeInitialization(DefaultCamelBeanPostProcessor.java:82)
    at org.apache.camel.test.junit4.CamelTestSupport.applyCamelPostProcessor(CamelTestSupport.java:499)
    at org.apache.camel.test.junit4.CamelTestSupport.postProcessTest(CamelTestSupport.java:487)
    at org.apache.camel.test.junit4.CamelTestSupport.doSetUp(CamelTestSupport.java:320)
    at org.apache.camel.test.junit4.CamelTestSupport.setUp(CamelTestSupport.java:239)
    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:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)
</code>```

Any help appreciated.

答:
Try with 2.20.x as it has improved startup of Camel and Spring. But you can also on current version avoid using the custom component name, in the @Produce annotation

And then just refer to a uri that exists in camel-core

```<code> @Produce(uri = "log:foo")
</code>```

And in your test method you send to hornetq which at this point in time should work, as then Spring has been fully started up and loaded the XML files with the custom <bean>.

Body:
Iam trying to send message to a JMSQueue in Junit test cases and iam getting exception No component found with scheme: hornetq. I have registered the component in the bean declaration.But still it is throwing error.

Junit Test class:

import java.io.File;

import org.apache.camel.CamelContext;
import org.apache.camel.EndpointInject;
import org.apache.camel.Exchange;
import org.apache.camel.Expression;
import org.apache.camel.Produce;
import org.apache.camel.ProducerTemplate;
import org.apache.camel.builder.AdviceWithRouteBuilder;
import org.apache.camel.component.mock.MockEndpoint;
import org.apache.camel.model.ModelCamelContext;
import org.apache.camel.test.junit4.CamelTestSupport;
import org.apache.camel.test.spring.CamelSpringJUnit4ClassRunner;
import org.apache.commons.io.FileUtils;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;
import org.springframework.test.annotation.DirtiesContext.ClassMode;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.web.WebAppConfiguration;

@RunWith(CamelSpringJUnit4ClassRunner.class)
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@WebAppConfiguration
@ContextConfiguration(locations = { "classpath:/META-INF/spring/camel-context.xml",
        "classpath:/META-INF/spring/policyHolderRoutepolicyHolderRoute.xml", "classpath:/META-INF/spring/policyRoute.xml" })
public class OnlineComponentTest extends CamelTestSupport {
    private static final Logger LOGGER = LoggerFactory.getLogger(OnlineComponentTest.class);
    @Autowired
    private CamelContext context;

    @Produce(uri = "hornetq://queue:EVENT.API.IN.ONLINE")
    protected ProducerTemplate template;

    @EndpointInject(uri = "mock:cxfrs://bean://importPolicyHolderRestEndpoint")
    protected MockEndpoint mockImportpolicyHolderEndpoint;

    @EndpointInject(uri = "mock:cxfrs://bean://importPolicyRestEndpoint")
    protected MockEndpoint mockImportpolicyEndpoint;

    @Test
    public void testOnlineRouteSuccess() throws Exception {
        template.sendBody("hornetq://queue:EVENT.API.IN.ONLINE", FileUtils.readFileToString(new File(
                "src/test/resources/componenttest/success/input/onlineinqueue-request.json")));
    }
}

Defined component with HornetQ in test resources:

<bean id="jmsConnectionFactory" class="org.apache.activemq.ActiveMQConnectionFactory">
        <property name="brokerURL" value="vm://broker?broker.persistent=false" />
    </bean>

    <bean id="jmsTransactionManager"
        class="org.springframework.jms.connection.JmsTransactionManager">
        <property name="connectionFactory" ref="jmsConnectionFactory" />
    </bean>

    <bean id="hornetq" class="org.apache.camel.component.jms.JmsComponent">
        <property name="connectionFactory" ref="jmsConnectionFactory" />

        <property name="transacted" value="true" />

        <property name="transactionManager" ref="jmsTransactionManager" />
    </bean>

Junit Logs:

2017-11-14 09:57:42,559 [main           ]  INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [META-INF/spring/camel-context.xml]
2017-11-14 09:57:43,186 [main           ]  INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [META-INF/spring/bean-declarations.xml]
2017-11-14 09:57:45,984 [main           ]  INFO  DefaultListableBeanFactory     - Overriding bean definition for bean 'OnlineInEndpoint': replacing [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-11-14 09:57:45,985 [main           ]  INFO  DefaultListableBeanFactory     - Overriding bean definition for bean '_to2': replacing [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-11-14 09:57:45,986 [main           ]  INFO  DefaultListableBeanFactory     - Overriding bean definition for bean '_to1': replacing [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null] with [Generic bean: class [org.apache.camel.spring.CamelEndpointFactoryBean]; scope=; abstract=false; lazyInit=false; autowireMode=0; dependencyCheck=0; autowireCandidate=true; primary=false; factoryBeanName=null; factoryMethodName=null; initMethodName=null; destroyMethodName=null]
2017-11-14 09:57:45,990 [main           ]  INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [META-INF/spring/policyHolderRoute.xml]
2017-11-14 09:57:46,099 [main           ]  INFO  XmlBeanDefinitionReader        - Loading XML bean definitions from class path resource [META-INF/spring/policyRoute.xml]
2017-11-14 09:57:46,202 [main           ]  INFO  CamelSpringTestContextLoader   - Disabling Camel JMX globally for tests by default.  Use the DisableJMX annotation to override the default setting.
2017-11-14 09:57:46,257 [main           ]  INFO  GenericApplicationContext      - Refreshing org.springframework.context.support.GenericApplicationContext@71318ec4: startup date [Tue Nov 14 09:57:46 GMT 2017]; root of context hierarchy
2017-11-14 09:57:46,711 [main           ]  INFO  ePropertyPlaceholderConfigurer - Loading properties file from class path resource [com/company/esb/environment/properties/common.properties]
2017-11-14 09:57:46,712 [main           ]  INFO  ePropertyPlaceholderConfigurer - Loading properties file from class path resource [com/company/esb/environment/properties/online.properties]
2017-11-14 09:57:46,726 [main           ]  INFO  redAnnotationBeanPostProcessor - JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2017-11-14 09:57:46,780 [main           ]  INFO  DefaultListableBeanFactory     - Pre-instantiating singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@41dd05a: defining beans [eventLogger,bridgePropertyPlaceholder,jmsConnectionFactory,jmsTransactionManager,hornetq,importPolicyRestEndpoint,importPolicyHolderRestEndpoint,*.http-conduit,OnlineInEndpoint,_to2,_to1,template,consumerTemplate,OnlineContext:beanPostProcessor,OnlineContext,policyHolderRouteContext,policyRouteContext,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy
2017-11-14 09:57:47,913 [main           ]  INFO  CamelContextFactoryBean        - Bridging Camel and Spring property placeholder configurer with id: bridgePropertyPlaceholder
2017-11-14 09:57:48,777 [main           ]  INFO  DefaultTypeConverter           - Loaded 201 type converters
2017-11-14 09:57:48,799 [main           ]  INFO  CamelSpringTestContextLoader   - Setting shutdown timeout to [10 SECONDS] on CamelContext with name [OnlineContext].
2017-11-14 09:57:48,811 [main           ]  INFO  CamelSpringTestContextLoader   - Enabling lazy loading of type converters on CamelContext with name [OnlineContext].
2017-11-14 09:57:48,813 [main           ]  INFO  CamelSpringTestContextLoader   - Starting CamelContext with name [OnlineContext].
2017-11-14 09:57:48,815 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) is starting
2017-11-14 09:57:48,821 [main           ]  INFO  DefaultManagementStrategy      - JMX is disabled
2017-11-14 09:57:50,991 [main           ]  INFO  SpringCamelContext             - AllowUseOriginalMessage is enabled. If access to the original message is not needed, then its recommended to turn this option off as it may improve performance.
2017-11-14 09:57:51,147 [main           ]  INFO  DefaultStreamCachingStrategy   - StreamCaching in use with spool directory: C:\Users\jmjl29k\AppData\Local\Temp\camel\camel-tmp-8dce384f-0ca4-4e09-9560-53a30d7b089f and rules: [Spool > 128K body size]
2017-11-14 09:57:51,222 [main           ]  INFO  SpringCamelContext             - Route: policyRoute started and consuming from: Endpoint[direct://policyLoad]
2017-11-14 09:57:51,223 [main           ]  INFO  SpringCamelContext             - Route: policyHolderRoute started and consuming from: Endpoint[direct://policyHolderLoad]
2017-11-14 09:57:51,237 [main           ]  INFO  SpringCamelContext             - Route: OnlineInWriteConsumerRoute started and consuming from: Endpoint[hornetq://queue:EVENT.API.IN.ONLINE]
2017-11-14 09:57:51,237 [main           ]  INFO  SpringCamelContext             - Total 3 routes, of which 3 are started.
2017-11-14 09:57:51,240 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) started in 2.424 seconds
2017-11-14 09:57:51,450 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,450 [main           ]  INFO  OnlineComponentTest            - Testing: testOnlineRouteSuccess(com.company.esb.online.OnlineComponentTest)
2017-11-14 09:57:51,450 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,605 [.API.IN.ONLINE]]  INFO  BrokerService                  - Using Persistence Adapter: MemoryPersistenceAdapter
2017-11-14 09:57:51,610 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,622 [main           ]  INFO  OnlineComponentTest            - Testing done: testOnlineRouteSuccess(com.company.esb.online.OnlineComponentTest)
2017-11-14 09:57:51,622 [main           ]  INFO  OnlineComponentTest            - Took: 9.366 seconds (9366 millis)
2017-11-14 09:57:51,622 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,645 [main           ]  INFO  DefaultCamelContext            - Apache Camel 2.17.0.redhat-630262 (CamelContext: camel-2) is shutting down
2017-11-14 09:57:51,646 [main           ]  INFO  DefaultCamelContext            - Apache Camel 2.17.0.redhat-630262 (CamelContext: camel-2) uptime
2017-11-14 09:57:51,646 [main           ]  INFO  DefaultCamelContext            - Apache Camel 2.17.0.redhat-630262 (CamelContext: camel-2) is shutdown in 0.023 seconds
2017-11-14 09:57:51,647 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,647 [main           ]  INFO  OnlineComponentTest            - Testing done: testOnlineRouteSuccess(com.company.esb.online.OnlineComponentTest)
2017-11-14 09:57:51,647 [main           ]  INFO  OnlineComponentTest            - Took: 0.197 seconds (197 millis)
2017-11-14 09:57:51,647 [main           ]  INFO  OnlineComponentTest            - ********************************************************************************
2017-11-14 09:57:51,647 [main           ]  INFO  GenericApplicationContext      - Closing org.springframework.context.support.GenericApplicationContext@71318ec4: startup date [Tue Nov 14 09:57:46 GMT 2017]; root of context hierarchy
2017-11-14 09:57:51,649 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) is shutting down
2017-11-14 09:57:51,651 [main           ]  INFO  DefaultShutdownStrategy        - Starting to graceful shutdown 3 routes (timeout 10 seconds)
2017-11-14 09:57:51,889 [JMX connector  ]  INFO  ManagementContext              - JMX consoles can connect to service:jmx:rmi:///jndi/rmi://localhost:1099/jmxrmi
2017-11-14 09:57:52,063 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) is starting
2017-11-14 09:57:52,084 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) started
2017-11-14 09:57:52,084 [.API.IN.ONLINE]]  INFO  BrokerService                  - For help or more information please see: http://activemq.apache.org
2017-11-14 09:57:52,105 [.API.IN.ONLINE]]  WARN  BrokerService                  - Temporary Store limit is 51200 mb (current store usage is 0 mb). The data directory: C:\Temp\GITRepo\esb\routes\Online only has 26504 mb of usable space. - resetting to maximum available disk space: 26504 mb
2017-11-14 09:57:52,195 [.API.IN.ONLINE]]  INFO  TransportConnector             - Connector vm://broker started
2017-11-14 09:57:53,612 [.API.IN.ONLINE]]  INFO  TransportConnector             - Connector vm://broker stopped
2017-11-14 09:57:53,613 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) is shutting down
2017-11-14 09:57:53,634 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) uptime 2.167 seconds
2017-11-14 09:57:53,634 [.API.IN.ONLINE]]  INFO  BrokerService                  - Apache ActiveMQ 5.11.0.redhat-630262 (broker, ID:VPE1-D01307-58386-1510653471708-0:1) is shutdown
2017-11-14 09:57:53,634 [ - ShutdownTask]  INFO  DefaultShutdownStrategy        - Route: OnlineInWriteConsumerRoute shutdown complete, was consuming from: Endpoint[hornetq://queue:EVENT.API.IN.ONLINE]
2017-11-14 09:57:53,635 [ - ShutdownTask]  INFO  DefaultShutdownStrategy        - Route: policyHolderRoute shutdown complete, was consuming from: Endpoint[direct://policyHolderLoad]
2017-11-14 09:57:53,635 [ - ShutdownTask]  INFO  DefaultShutdownStrategy        - Route: policyRoute shutdown complete, was consuming from: Endpoint[direct://policyLoad]
2017-11-14 09:57:53,635 [main           ]  INFO  DefaultShutdownStrategy        - Graceful shutdown of 3 routes completed in 1 seconds
2017-11-14 09:57:53,640 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) uptime 4.827 seconds
2017-11-14 09:57:53,640 [main           ]  INFO  SpringCamelContext             - Apache Camel 2.17.0.redhat-630262 (CamelContext: OnlineContext) is shutdown in 1.991 seconds
2017-11-14 09:57:53,643 [main           ]  INFO  DefaultListableBeanFactory     - Destroying singletons in org.springframework.beans.factory.support.DefaultListableBeanFactory@41dd05a: defining beans [eventLogger,bridgePropertyPlaceholder,jmsConnectionFactory,jmsTransactionManager,hornetq,importPolicyRestEndpoint,importPolicyHolderRestEndpoint,*.http-conduit,OnlineInEndpoint,_to2,_to1,template,consumerTemplate,OnlineContext:beanPostProcessor,OnlineContext,policyHolderRouteContext,policyRouteContext,org.springframework.context.annotation.internalConfigurationAnnotationProcessor,org.springframework.context.annotation.internalAutowiredAnnotationProcessor,org.springframework.context.annotation.internalRequiredAnnotationProcessor,org.springframework.context.annotation.internalCommonAnnotationProcessor,org.springframework.context.annotation.ConfigurationClassPostProcessor.importAwareProcessor]; root of factory hierarchy

Exception:

org.apache.camel.ResolveEndpointFailedException: Failed to resolve endpoint: hornetq://queue:EVENT.API.IN.ONLINE due to: No component found with scheme: hornetq
    at org.apache.camel.impl.DefaultCamelContext.getEndpoint(DefaultCamelContext.java:595)
    at org.apache.camel.util.CamelContextHelper.getEndpointInjection(CamelContextHelper.java:174)
    at org.apache.camel.impl.CamelPostProcessorHelper.doGetEndpointInjection(CamelPostProcessorHelper.java:157)
    at org.apache.camel.impl.CamelPostProcessorHelper.getEndpointInjection(CamelPostProcessorHelper.java:152)
    at org.apache.camel.impl.CamelPostProcessorHelper.createInjectionProducerTemplate(CamelPostProcessorHelper.java:289)
    at org.apache.camel.impl.CamelPostProcessorHelper.getInjectionValue(CamelPostProcessorHelper.java:205)
    at org.apache.camel.impl.DefaultCamelBeanPostProcessor.injectField(DefaultCamelBeanPostProcessor.java:195)
    at org.apache.camel.impl.DefaultCamelBeanPostProcessor$1.doWith(DefaultCamelBeanPostProcessor.java:187)
    at org.apache.camel.util.ReflectionHelper.doWithFields(ReflectionHelper.java:73)
    at org.apache.camel.impl.DefaultCamelBeanPostProcessor.injectFields(DefaultCamelBeanPostProcessor.java:168)
    at org.apache.camel.impl.DefaultCamelBeanPostProcessor.postProcessBeforeInitialization(DefaultCamelBeanPostProcessor.java:82)
    at org.apache.camel.test.junit4.CamelTestSupport.applyCamelPostProcessor(CamelTestSupport.java:499)
    at org.apache.camel.test.junit4.CamelTestSupport.postProcessTest(CamelTestSupport.java:487)
    at org.apache.camel.test.junit4.CamelTestSupport.doSetUp(CamelTestSupport.java:320)
    at org.apache.camel.test.junit4.CamelTestSupport.setUp(CamelTestSupport.java:239)
    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:47)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:44)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:24)
    at org.springframework.test.context.junit4.statements.RunBeforeTestMethodCallbacks.evaluate(RunBeforeTestMethodCallbacks.java:74)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestMethodCallbacks.evaluate(RunAfterTestMethodCallbacks.java:83)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
    at org.junit.rules.TestWatcher$1.evaluate(TestWatcher.java:55)
    at org.junit.rules.RunRules.evaluate(RunRules.java:20)
    at org.springframework.test.context.junit4.statements.SpringRepeat.evaluate(SpringRepeat.java:72)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:231)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.runChild(SpringJUnit4ClassRunner.java:88)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:238)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:63)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:236)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:53)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:229)
    at org.springframework.test.context.junit4.statements.RunBeforeTestClassCallbacks.evaluate(RunBeforeTestClassCallbacks.java:61)
    at org.junit.internal.runners.statements.RunAfters.evaluate(RunAfters.java:27)
    at org.springframework.test.context.junit4.statements.RunAfterTestClassCallbacks.evaluate(RunAfterTestClassCallbacks.java:71)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:309)
    at org.springframework.test.context.junit4.SpringJUnit4ClassRunner.run(SpringJUnit4ClassRunner.java:174)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:86)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:459)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:678)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:382)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:192)

Any help appreciated.

Body:
Try with 2.20.x as it has improved startup of Camel and Spring. But you can also on current version avoid using the custom component name, in the @Produce annotation

And then just refer to a uri that exists in camel-core

 @Produce(uri = "log:foo")

And in your test method you send to hornetq which at this point in time should work, as then Spring has been fully started up and loaded the XML files with the custom <bean>.


问:
How to add button to top left corner in UICollectionViewCell in iOS?
I want to add the Button to the top left corner of the cell.I have tried but i always added inside the collection view cell but not on the cell so please tell me how can i o this?

I have tried this.

```<code>    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BlogAlbumCell  *cell;
    static NSString *identifier = @"UserBlogAlbum";
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    UserAlbum *user_allbum=[arr_userAlbums objectAtIndex:indexPath.row];
    cell.label_blog_name.text=user_allbum.album_name;
    [cell.image_blog_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_allbum.album_image]] placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];
    if([[[NSUserDefaults standardUserDefaults]valueForKey:@"longPressed"] isEqualToString:@"yes"])
    {
        NSLog(@"Inside the long press section");
        CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        [anim setToValue:[NSNumber numberWithFloat:0.0f]];
        [anim setFromValue:[NSNumber numberWithDouble:M_PI/50]];
        [anim setDuration:0.1];
        [anim setRepeatCount:NSUIntegerMax];
        [anim setAutoreverses:YES];
        cell.layer.shouldRasterize = YES;
        [cell.layer addAnimation:anim forKey:@"SpringboardShake"];
        CGFloat delButtonSize = 30;
        UIButton *delButton = [[UIButton alloc] initWithFrame:CGRectMake(-5,-5, delButtonSize, delButtonSize)];
        delButton.backgroundColor = [UIColor clearColor];
        [delButton setImage: [UIImage imageNamed:@"cross_30.png"] forState:UIControlStateNormal];
       [delButton setBackgroundColor:[UIColor blueColor]];
        [cell addSubview:delButton];
        delButton.tag=indexPath.row;
        [delButton addTarget:self action:@selector(deleteAlbum:) forControlEvents:UIControlEventTouchUpInside];
    }
    else if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"singleTap"] isEqualToString:@"yes"])
    {
        if(indexPath.row==([arr_userAlbums count]-1))
        {
            [[NSUserDefaults standardUserDefaults]setValue:@"no" forKey:@"singleTap"];
        }
        for(UIView *subview in [cell subviews])
        {
            if([subview isKindOfClass:[UIButton class]])
            {
                [subview removeFromSuperview];
            }

        }
        [cell.layer removeAllAnimations];
        // _deleteButton.hidden = YES;
         [_deleteButton removeFromSuperview];
    }
        return cell;
}
</code>```

But it does not add the button to the top left.

I want like this

EDIT:

This is what i am getting as of now

答:
I have found a simple hack for doing this. .

1.Take the image you have to show in cell smaller then the cell size and align it to right - bottom.

Now just add your button to the left-top at the remaining space of cell.

If you are beginner and don't know how to play with constraint then I let me explain what I actually did.

I made my cell 100X100 pts and imageView 70X70 pts.

then align given imageView right and bottom constraint to its superview with constant value "0" or ZERO.

Give left and top constraint constant 30 pts.

Add button with cross image icon.

left align button with imageView by giving -10 left align constraint points

similarly top align button with imageView -10 top align constraint points.

It will give the same user experience as required!. I have attached an image as well.

Body:
I want to add the Button to the top left corner of the cell.I have tried but i always added inside the collection view cell but not on the cell so please tell me how can i o this?

I have tried this.

    - (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    BlogAlbumCell  *cell;
    static NSString *identifier = @"UserBlogAlbum";
    cell = [collectionView dequeueReusableCellWithReuseIdentifier:identifier forIndexPath:indexPath];
    UserAlbum *user_allbum=[arr_userAlbums objectAtIndex:indexPath.row];
    cell.label_blog_name.text=user_allbum.album_name;
    [cell.image_blog_image setImageWithURL:[NSURL URLWithString:[IMAGE_BASE_URL stringByAppendingString:user_allbum.album_image]] placeholderImage:[UIImage imageNamed:@"post_placeholder.png"]];
    if([[[NSUserDefaults standardUserDefaults]valueForKey:@"longPressed"] isEqualToString:@"yes"])
    {
        NSLog(@"Inside the long press section");
        CABasicAnimation* anim = [CABasicAnimation animationWithKeyPath:@"transform.rotation"];
        [anim setToValue:[NSNumber numberWithFloat:0.0f]];
        [anim setFromValue:[NSNumber numberWithDouble:M_PI/50]];
        [anim setDuration:0.1];
        [anim setRepeatCount:NSUIntegerMax];
        [anim setAutoreverses:YES];
        cell.layer.shouldRasterize = YES;
        [cell.layer addAnimation:anim forKey:@"SpringboardShake"];
        CGFloat delButtonSize = 30;
        UIButton *delButton = [[UIButton alloc] initWithFrame:CGRectMake(-5,-5, delButtonSize, delButtonSize)];
        delButton.backgroundColor = [UIColor clearColor];
        [delButton setImage: [UIImage imageNamed:@"cross_30.png"] forState:UIControlStateNormal];
       [delButton setBackgroundColor:[UIColor blueColor]];
        [cell addSubview:delButton];
        delButton.tag=indexPath.row;
        [delButton addTarget:self action:@selector(deleteAlbum:) forControlEvents:UIControlEventTouchUpInside];
    }
    else if ([[[NSUserDefaults standardUserDefaults]valueForKey:@"singleTap"] isEqualToString:@"yes"])
    {
        if(indexPath.row==([arr_userAlbums count]-1))
        {
            [[NSUserDefaults standardUserDefaults]setValue:@"no" forKey:@"singleTap"];
        }
        for(UIView *subview in [cell subviews])
        {
            if([subview isKindOfClass:[UIButton class]])
            {
                [subview removeFromSuperview];
            }

        }
        [cell.layer removeAllAnimations];
        // _deleteButton.hidden = YES;
         [_deleteButton removeFromSuperview];
    }
        return cell;
}

But it does not add the button to the top left.

I want like this

EDIT:

This is what i am getting as of now


问:
Twitter - The URI requested is invalid or the resource requested, such as a user, does not exists.
Desired Behavior: Get Tweets of users from their userID's listed in a TXT file

Work/Research done beforehand:
Note: I have attempted looking up this error message, and any associated with the classes used in my code before posting this.

Note: Additionally I have MANUALLY checked the users by going to twitter and looking up their username, and they DO come up. For example, this is one of the users, and they do come up: https://twitter.com/rendrarh
I have done this with MANY of the users in the list.

Note: This works when just manually entering a user (using this Get tweets of a public twitter profile ) , but not when pulling it from the file

I am using Twitter4j to get tweets of users and getting the following error:

```<code>TwitterException{exceptionCode=[7defbde2-0dc3a547], statusCode=404, message=Sorry, that page does not exist., code=34, retryAfter=-1, rateLimitStatus=RateLimitStatusJSONImpl{remaining=899, limit=900, resetTimeInSeconds=1510626518, secondsUntilReset=899}, version=4.0.4}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.get(HttpClientBase.java:75)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1786)
at twitter4j.TwitterImpl.getUserTimeline(TwitterImpl.java:131)
at twitter4j.TwitterImpl.getUserTimeline(TwitterImpl.java:152)
at UserTweets.main(UserTweets.java:42)
</code>```

Line 42 is : statuses.addAll(twitter.getUserTimeline(user));

Here is my code:

```<code>import java.io.File;
import java.util.*;
    import twitter4j.*;
    import twitter4j.conf.*;

public class UserTweets {

    public static void main(String[] a) {

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true)
        .setOAuthConsumerKey("key")
        .setOAuthConsumerSecret("key")
        .setOAuthAccessToken("key")
        .setOAuthAccessTokenSecret("key");

        Twitter twitter = new TwitterFactory(cb.build()).getInstance();

        String user;

        List statuses = new ArrayList();
        int userCount = 1;

        String fileName = "C:-----/spam-twitter-accounts.txt";
        File file = new File(fileName);
        Scanner input = new Scanner(file);
        List<String> list = new ArrayList<String>();

        while (userCount < 20 && input.hasNextLine()) {
          try {

            user =  list.add(input.nextLine());

            statuses.addAll(twitter.getUserTimeline(user));

            System.out.println(statuses.toString());
            if (statuses.size() == 20)
              break;
          }
          catch(TwitterException e) {

            e.printStackTrace();
          }
        }
    }

}
</code>```

答:
Needed to change it to Long since the txt file had numbers:</p>

```<code>while (userCount < 20 && input.hasNextLong()) {
      try {

        user =  input.nextLong();
</code>```

Body:
Desired Behavior: Get Tweets of users from their userID's listed in a TXT file

Work/Research done beforehand:
Note: I have attempted looking up this error message, and any associated with the classes used in my code before posting this.

Note: Additionally I have MANUALLY checked the users by going to twitter and looking up their username, and they DO come up. For example, this is one of the users, and they do come up: https://twitter.com/rendrarh
I have done this with MANY of the users in the list.

Note: This works when just manually entering a user (using this Get tweets of a public twitter profile ) , but not when pulling it from the file

I am using Twitter4j to get tweets of users and getting the following error:

TwitterException{exceptionCode=[7defbde2-0dc3a547], statusCode=404, message=Sorry, that page does not exist., code=34, retryAfter=-1, rateLimitStatus=RateLimitStatusJSONImpl{remaining=899, limit=900, resetTimeInSeconds=1510626518, secondsUntilReset=899}, version=4.0.4}
at twitter4j.HttpClientImpl.handleRequest(HttpClientImpl.java:164)
at twitter4j.HttpClientBase.request(HttpClientBase.java:57)
at twitter4j.HttpClientBase.get(HttpClientBase.java:75)
at twitter4j.TwitterImpl.get(TwitterImpl.java:1786)
at twitter4j.TwitterImpl.getUserTimeline(TwitterImpl.java:131)
at twitter4j.TwitterImpl.getUserTimeline(TwitterImpl.java:152)
at UserTweets.main(UserTweets.java:42)

Line 42 is : statuses.addAll(twitter.getUserTimeline(user));

Here is my code:

import java.io.File;
import java.util.*;
    import twitter4j.*;
    import twitter4j.conf.*;

public class UserTweets {

    public static void main(String[] a) {

        ConfigurationBuilder cb = new ConfigurationBuilder();
        cb.setDebugEnabled(true)
        .setOAuthConsumerKey("key")
        .setOAuthConsumerSecret("key")
        .setOAuthAccessToken("key")
        .setOAuthAccessTokenSecret("key");

        Twitter twitter = new TwitterFactory(cb.build()).getInstance();

        String user;

        List statuses = new ArrayList();
        int userCount = 1;

        String fileName = "C:-----/spam-twitter-accounts.txt";
        File file = new File(fileName);
        Scanner input = new Scanner(file);
        List<String> list = new ArrayList<String>();

        while (userCount < 20 && input.hasNextLine()) {
          try {

            user =  list.add(input.nextLine());

            statuses.addAll(twitter.getUserTimeline(user));

            System.out.println(statuses.toString());
            if (statuses.size() == 20)
              break;
          }
          catch(TwitterException e) {

            e.printStackTrace();
          }
        }
    }

}

Body:
Needed to change it to Long since the txt file had numbers:

while (userCount < 20 && input.hasNextLong()) {
      try {

        user =  input.nextLong();


问:
#2002 getaddrinfo failed - phpmyadmin using docker container
i'm trying to connect phpmyadmin with mysql database through docker containers

I have the following docker-compose.yml file

```<code>version: "3"
services:
database:
image: mysql:latest
container_name: locations-service-mysql
environment:
  MYSQL_ROOT_PASSWORD: root
  MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

volumes:
  - ./mysql-init:/var/lib/mysql:rw
  - ./mysql-init/locations_schema.sql:/docker-entrypoint-
    initdb.d/locations_schema.sql:ro

 phpmyadmin:
   image: phpmyadmin/phpmyadmin:latest
   ports:
  - 8181:80
environment:
  MYSQL_USERNAME: root
  MYSQL_ROOT_PASSWORD: examplepass
  PMA_HOST: database

dropwizard:
build: ../locations-service/
ports:
      - 8080:8080
      - 8081:8081
      - 5005:5005
depends_on:
      - database
container_name: locations-service
</code>```

I tried to log in to PMA using root account and the given password: blabla.
I receive the following error:

2002 - php_network_getaddresses: getaddrinfo failed: Name does not resolve — The server is not responding (or the local server's socket is not correctly configured).

答:
Seems "database" is not in phpmyadmin's container /etc/hosts (it's not linked)

Try links:

```<code>version: "3"
  services:
  database:
    image: mysql:latest
    container_name: locations-service-mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
  volumes:
    - ./mysql-init:/var/lib/mysql:rw
    - ./mysql-init/locations_schema.sql:/docker-entrypoint-initdb.d/locations_schema.sql:ro

 phpmyadmin:
   image: phpmyadmin/phpmyadmin:latest
   links:
     - database
   ports:
    - 8181:80
  environment:
    MYSQL_USERNAME: root
    MYSQL_ROOT_PASSWORD: examplepass
    PMA_HOST: database
</code>```

Body:
i'm trying to connect phpmyadmin with mysql database through docker containers

I have the following docker-compose.yml file

version: "3"
services:
database:
image: mysql:latest
container_name: locations-service-mysql
environment:
  MYSQL_ROOT_PASSWORD: root
  MYSQL_ALLOW_EMPTY_PASSWORD: "yes"

volumes:
  - ./mysql-init:/var/lib/mysql:rw
  - ./mysql-init/locations_schema.sql:/docker-entrypoint-
    initdb.d/locations_schema.sql:ro

 phpmyadmin:
   image: phpmyadmin/phpmyadmin:latest
   ports:
  - 8181:80
environment:
  MYSQL_USERNAME: root
  MYSQL_ROOT_PASSWORD: examplepass
  PMA_HOST: database

dropwizard:
build: ../locations-service/
ports:
      - 8080:8080
      - 8081:8081
      - 5005:5005
depends_on:
      - database
container_name: locations-service

I tried to log in to PMA using root account and the given password: blabla.
I receive the following error:

2002 - php_network_getaddresses: getaddrinfo failed: Name does not resolve — The server is not responding (or the local server's socket is not correctly configured).

Body:
Seems "database" is not in phpmyadmin's container /etc/hosts (it's not linked)

Try links:

version: "3"
  services:
  database:
    image: mysql:latest
    container_name: locations-service-mysql
    environment:
      MYSQL_ROOT_PASSWORD: root
      MYSQL_ALLOW_EMPTY_PASSWORD: "yes"
  volumes:
    - ./mysql-init:/var/lib/mysql:rw
    - ./mysql-init/locations_schema.sql:/docker-entrypoint-initdb.d/locations_schema.sql:ro

 phpmyadmin:
   image: phpmyadmin/phpmyadmin:latest
   links:
     - database
   ports:
    - 8181:80
  environment:
    MYSQL_USERNAME: root
    MYSQL_ROOT_PASSWORD: examplepass
    PMA_HOST: database


问:
Model class doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS
I am using sphinx and was trying to generate documentation for my Django project. I decided to first try to document the models so in my .rst file I did this

```<code>wdland\.models
==============

.. automodule:: wdland.models
    :members:
    :undoc-members:
    :show-inheritance:
</code>```

But the get the following errors

```<code>WARNING: /home/fabou/wdlandenvpy3/source/docs/wdland.rst:9: (WARNING/2) autodoc: failed to import module 'wdland.models'; the following exception was raised:
Traceback (most recent call last):
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 657, in import_object
    __import__(self.modname)
  File "/home/fabou/wdlandenvpy3/source/wdland/models.py", line 35, in <module>
    class Device(models.Model):
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/db/models/base.py", line 118, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class wdland.models.Device doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
</code>```

After some google search I found a solution here Django 1.9 deprecation warnings app_label see comment from Роман Арсеньев on “Jan 11 '16 at 14:54”

I went in my models.py and added “class Meta: app_label”  as per above post to every single class I had in models.py. This fixed the problem and I was able to generate the documentation for my models using the sphinx-build script.

Now I wanted to do the same for views.py and did this in my .rst file

```<code>wdland\.views
=============

.. automodule:: wdland.views
    :members:
    :undoc-members:
    :show-inheritance:
</code>```

But on compile I get this new similar error and I have been unable to find a solution for it nor did understand the previous fix for models.

```<code>WARNING: /home/fabou/wdlandenvpy3/source/docs/wdland.rst:19: (WARNING/2) autodoc: failed to import module 'wdland.views'; the following exception was raised:
Traceback (most recent call last):
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 657, in import_object
    __import__(self.modname)
  File "/home/fabou/wdlandenvpy3/source/wdland/views.py", line 2, in <module>
    from . import views
  File "/home/fabou/wdlandenvpy3/source/wdland/views.py", line 19, in <module>
    from .forms import TicketForm, TicketAmendForm
  File "/home/fabou/wdlandenvpy3/source/wdland/forms.py", line 1, in <module>
    from django.contrib.auth.forms import AuthenticationForm
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/contrib/auth/forms.py", line 12, in <module>
    from django.contrib.auth.models import User
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/contrib/auth/models.py", line 6, in <module>
    from django.contrib.contenttypes.models import ContentType
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 139, in <module>
    class ContentType(models.Model):
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/db/models/base.py", line 118, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.
</code>```

Here the relevant sphinx configuration

```<code>#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import django
import os
import sphinx_rtd_theme
import sys

from django.conf import settings

sys.path.insert(0, os.path.abspath('../'))
settings.configure()
django.setup()
</code>```

wdland is a Django app an is listed in my INSTALLED_APPS tuple in the settings file. The sphinx docs folder is at the same level as the wdland folder.

Reading similar threads on the topic seem to point to modules that are not yet loaded when being called. I have no clue how to fix as not experienced in either sphinx and Django. Any idea on how I can fix this?

Trying to document urls.py would yield similar errors.

EDIT:
Here the begining of my view.py

```<code>import datetime

from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import Http404, HttpResponse
from django.template.loader import render_to_string
from django.shortcuts import render, HttpResponseRedirect
from django.views import generic
from random import randint
from script.serversnmp import get_ubuntu_snmp, get_esxi_snmp
from script.wdlandtools import get_monthly_sess_hour_stats,\
                                get_monthly_sess_nb_stats,\
                                get_monthly_ticket_stats,\
                                get_ticket_category_stats,\
                                clean_usersession_tbl, update_usertotals_tbl,\
                                send_email_notification, get_adsl_usage
from wdland.models import Device, UserSession, SupportTicket, News, UserTotals,\
                            SavedUsrSess
from .forms import TicketForm, TicketAmendForm

from jchart import Chart
from jchart.config import Axes, DataSet, rgba
</code>```

答:
My solution was to create a BaseModel abstract class on your models.py within your app, on your error this may be:

```<code>class BaseModel(models.Model):

    class Meta:
        abstract = True  # specify this model as an Abstract Model
        app_label = 'wdland'
</code>```

And made all models inherit from this instead of the usual models.Model.

To solve it, I went to the basics of trying to figure out the error message, which states:

Model class wdland.models.Device doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

I also had the same error with a different app. Adding the requested "app_label" solved the issue.

Body:
I am using sphinx and was trying to generate documentation for my Django project. I decided to first try to document the models so in my .rst file I did this

wdland\.models
==============

.. automodule:: wdland.models
    :members:
    :undoc-members:
    :show-inheritance:

But the get the following errors

WARNING: /home/fabou/wdlandenvpy3/source/docs/wdland.rst:9: (WARNING/2) autodoc: failed to import module 'wdland.models'; the following exception was raised:
Traceback (most recent call last):
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 657, in import_object
    __import__(self.modname)
  File "/home/fabou/wdlandenvpy3/source/wdland/models.py", line 35, in <module>
    class Device(models.Model):
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/db/models/base.py", line 118, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class wdland.models.Device doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

After some google search I found a solution here Django 1.9 deprecation warnings app_label see comment from Роман Арсеньев on “Jan 11 '16 at 14:54”

I went in my models.py and added “class Meta: app_label”  as per above post to every single class I had in models.py. This fixed the problem and I was able to generate the documentation for my models using the sphinx-build script.

Now I wanted to do the same for views.py and did this in my .rst file

wdland\.views
=============

.. automodule:: wdland.views
    :members:
    :undoc-members:
    :show-inheritance:

But on compile I get this new similar error and I have been unable to find a solution for it nor did understand the previous fix for models.

WARNING: /home/fabou/wdlandenvpy3/source/docs/wdland.rst:19: (WARNING/2) autodoc: failed to import module 'wdland.views'; the following exception was raised:
Traceback (most recent call last):
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/sphinx/ext/autodoc.py", line 657, in import_object
    __import__(self.modname)
  File "/home/fabou/wdlandenvpy3/source/wdland/views.py", line 2, in <module>
    from . import views
  File "/home/fabou/wdlandenvpy3/source/wdland/views.py", line 19, in <module>
    from .forms import TicketForm, TicketAmendForm
  File "/home/fabou/wdlandenvpy3/source/wdland/forms.py", line 1, in <module>
    from django.contrib.auth.forms import AuthenticationForm
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/contrib/auth/forms.py", line 12, in <module>
    from django.contrib.auth.models import User
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/contrib/auth/models.py", line 6, in <module>
    from django.contrib.contenttypes.models import ContentType
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/contrib/contenttypes/models.py", line 139, in <module>
    class ContentType(models.Model):
  File "/home/fabou/wdlandenvpy3/lib/python3.5/site-packages/django/db/models/base.py", line 118, in __new__
    "INSTALLED_APPS." % (module, name)
RuntimeError: Model class django.contrib.contenttypes.models.ContentType doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

Here the relevant sphinx configuration

#!/usr/bin/env python3
# -*- coding: utf-8 -*-

import django
import os
import sphinx_rtd_theme
import sys

from django.conf import settings

sys.path.insert(0, os.path.abspath('../'))
settings.configure()
django.setup()

wdland is a Django app an is listed in my INSTALLED_APPS tuple in the settings file. The sphinx docs folder is at the same level as the wdland folder.

Reading similar threads on the topic seem to point to modules that are not yet loaded when being called. I have no clue how to fix as not experienced in either sphinx and Django. Any idea on how I can fix this?

Trying to document urls.py would yield similar errors.

EDIT:
Here the begining of my view.py

import datetime

from django.core.urlresolvers import reverse
from django.db.models import Q
from django.http import Http404, HttpResponse
from django.template.loader import render_to_string
from django.shortcuts import render, HttpResponseRedirect
from django.views import generic
from random import randint
from script.serversnmp import get_ubuntu_snmp, get_esxi_snmp
from script.wdlandtools import get_monthly_sess_hour_stats,\
                                get_monthly_sess_nb_stats,\
                                get_monthly_ticket_stats,\
                                get_ticket_category_stats,\
                                clean_usersession_tbl, update_usertotals_tbl,\
                                send_email_notification, get_adsl_usage
from wdland.models import Device, UserSession, SupportTicket, News, UserTotals,\
                            SavedUsrSess
from .forms import TicketForm, TicketAmendForm

from jchart import Chart
from jchart.config import Axes, DataSet, rgba

Body:
My solution was to create a BaseModel abstract class on your models.py within your app, on your error this may be:

class BaseModel(models.Model):

    class Meta:
        abstract = True  # specify this model as an Abstract Model
        app_label = 'wdland'

And made all models inherit from this instead of the usual models.Model.

To solve it, I went to the basics of trying to figure out the error message, which states:

Model class wdland.models.Device doesn't declare an explicit app_label and isn't in an application in INSTALLED_APPS.

I also had the same error with a different app. Adding the requested "app_label" solved the issue.


问:
Simplest way to use JPA with my GWT application
I'd like to create a simple Google Web Toolkit application which makes uses RPCs.  For persistence, I'd like to use something like the Java Persistence API.

Does this mean I have to use an application server like Glassfish? or can I stick with a simple web container?

In terms of concrete libraries, how should I proceed?  TopLink? Hibernate? ...

答:
You can user any container you like, i mean servlet and jpa containers.

The key point is that GWT doesn't suport jpa, so you have to use DTO design parten.
This will keep everything organized and you will not have problems with lazy loading.

OwnerDisplayName: carrier

OwnerDisplayName: Thiago Diniz


问:
jQuery validate single input in similar forms
I have two forms on a page that are identical, but I'm trying to validate the one field (which is email in this case), but I can't seem to get it to just validate the one input field as it just shows the error for both forms.

HTML:

```<code><div class="general-form">
  <div class="email-error" style="display:none;">
    <p>You need valid email</p>
  </div>
  <div class="form-wrap">
    <div class="form-row">
      <input id="from-email" type="email" name="email" placeholder="Your Email" />
    </div>
    <div class="btn-row">
      <button class="submit-btn">Submit</button>
    </div>
  </div>
</div>

<div class="general-form">
  <div class="email-error" style="display:none;">
    <p>You need valid email</p>
  </div>
  <div class="form-wrap">
    <div class="form-row">
      <input id="from-email" type="email" name="email" placeholder="Your Email" />
    </div>
    <div class="btn-row">
      <button class="submit-btn">Submit</button>
    </div>
  </div>
</div>
</code>```

JS:

```<code>$(".submit-btn").on("click", function() {
  var $this = $(this);
  var valid_email = $this.find("#from-email").val();
  if (/(.+)@(.+){2,}\.(.+){2,}/.test(valid_email)) {
    return true;
  } else {
    $this.parents().find(".email-error").show();
    return false;
  }
});
</code>```

Overall, I can get it to pass through the validation, but the error message shows for both forms and I'm not sure how to get it so it only shows the error message for that particular form. I'm guessing that I'm pushing too far up the chain and it's testing for both of the forms, but I can't remember which one to target specifically if that makes any sense.

答:
Just add required> attribute and add this js     </p>

```<code>$("#formid").validate();
</code>```

Body:
I have two forms on a page that are identical, but I'm trying to validate the one field (which is email in this case), but I can't seem to get it to just validate the one input field as it just shows the error for both forms.

HTML:

You need valid email

      <input id="from-email" type="email" name="email" placeholder="Your Email" />

      <button class="submit-btn">Submit</button>

You need valid email

      <input id="from-email" type="email" name="email" placeholder="Your Email" />

      <button class="submit-btn">Submit</button>

JS:

$(".submit-btn").on("click", function() {
  var $this = $(this);
  var valid_email = $this.find("#from-email").val();
  if (/(.+)@(.+){2,}\.(.+){2,}/.test(valid_email)) {
    return true;
  } else {
    $this.parents().find(".email-error").show();
    return false;
  }
});

Overall, I can get it to pass through the validation, but the error message shows for both forms and I'm not sure how to get it so it only shows the error message for that particular form. I'm guessing that I'm pushing too far up the chain and it's testing for both of the forms, but I can't remember which one to target specifically if that makes any sense.

Body:
Just add required> attribute and add this js

$("#formid").validate();