问:
CSS highlight all elements of col in a single row
I have a table with multiple col elements and some of them has a span of 3. If I hover over a cell, which is part of a 3 span col, I'd want all the 3 cells in that row to highlight.

Look at the table below for a better understanding of what I'm refering to by Menu A, etc.
What I want to do is to highlight all the elements of Menu A on that day when I hover over it.
I've tried to achieve it by using siblings, but there's no previous sibling selector, so it only highlights the hovered food, and the foods to its right.

For example, if I hover over MainA1, I'd like to have SoupA1 and GranishA1 highlighted too.

Is there a way to do this in CSS or should I use JavaScript to apply classes to them on hover?

This is what I've tried to do:

```<code>.selector .menu-a:hover, .selector .menu-a:hover~.menu-a {
  background: var(--color_hover);
}
</code>```

This is my table:

:root {
  --color_unselected: #1ba1d6;
  --color_hover: #158ebe;
  --color_selected: #0a688d;
}

.selector {
  border: 1px solid var(--color_unselected);
  width: fit-content;
}

.selector a {
  display: block;
  color: white;
  text-align: center;
  padding: 4px;
  text-decoration: none;
  width: fit-content;
}

.selector {
  border-collapse: collapse;
}

.selector th,
.date-text,
.unselected {
  background: var(--color_unselected);
}

/*My question is about this part*/

.selector .menu-a:hover,
.selector .menu-a:hover~.menu-a {
  background: var(--color_hover);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="selector" class="selector">
  <colgroup>
    <col span="1" class="date-text menu-day">
    <col span="3" class="menu-a">
    <col span="3" class="menu-b">
    <col span="1" class="menu-n">
  </colgroup>
  <tr>
    <th>2020-1</th>
    <th colspan="3"><a>Menu A</a></th>
    <th colspan="3"><a>Menu B</a></th>
    <th><a>Not eating</a></th>
  </tr>
  <!--Generated meals come here-->
  <tr id="line-1" class="line-1">
    <td class="unselected">1</td>
    <td id="1-a-soup" class="menu-a unselected" )><a>SoupA1</a></td>
    <td id="1-a-main" class="menu-a unselected"><a>MainA1</a></td>
    <td id="1-a-garnish" class="menu-a unselected"><a>GarnishA1</a></td>
    <td id="1-b-soup" class="menu-b unselected"><a>SoupB1</a></td>
    <td id="1-b-main" class="menu-b unselected"><a>MainB1</a></td>
    <td id="1-b-garnish" class="menu-b unselected"><a>GarnishB1</a></td>
    <td id="1-n" class="unselected menu-n">
      <a>Not eating</a>
    </td>
  </tr>
  <tr id="line-2" class="line-2">
    <td>2</td>
    <td id="2-a-soup" class="unselected menu-a"><a>SoupA2</a></td>
    <td id="2-a-main" class="unselected menu-a"><a>MainA2</a></td>
    <td id="2-a-garnish" class="unselected menu-a"><a>GarnishA2</a></td>
    <td id="2-b-soup" class="unselected menu-b"><a>SoupB2</a></td>
    <td id="2-b-main" class="unselected menu-b"><a>MainB2</a></td>
    <td id="2-b-garnish" class="unselected menu-b"><a>GarnishB2</a></td>
    <td id="2-n" class="unselected menu-n">
      <a>Not eating</a>
    </td>
  </tr>
</table></code>```

答:
Here is a trick that rely on pseudo element. The idea is to make a pseudo element on the first item of the menu and this element should overflow to cover all the other elements so that you always catch the hover effect on the first element.

:root {
  --color_unselected: #1ba1d6;
  --color_hover: #158ebe;
  --color_selected: #0a688d;
}

.selector {
  border: 1px solid var(--color_unselected);
  width: fit-content;
  overflow:hidden; /* added */
}

.selector a {
  display: block;
  color: white;
  text-align: center;
  padding: 4px;
  text-decoration: none;
  width: fit-content;
}

.selector {
  border-collapse: collapse;
}

.selector th,
.date-text,
.unselected {
  background: var(--color_unselected);
}

/*My question is about this part*/

.selector .menu-a:hover,
.selector .menu-a:hover~.menu-a {
  background: var(--color_hover);
}

.selector .menu-b:hover,
.selector .menu-b:hover~.menu-b {
  background: var(--color_hover);
}

/* The trick start here */
.selector a {
  position:relative;
}
.selector a::before {
  content:"";
  position:absolute;
  z-index:9;
  top:0;
  left:0;
  bottom:0;
  width:100vw;
  height: 100vw;
}
/* Remove the pseudo element on the next elements*/
.selector .menu-a ~ .menu-a a::before,
.selector .menu-b ~ .menu-b a::before{
    content:none;
}
/**/```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table id="selector" class="selector">
  <colgroup>
    <col span="1" class="date-text menu-day">
    <col span="3" class="menu-a">
    <col span="3" class="menu-b">
    <col span="1" class="menu-n">
  </colgroup>
  <tr>
    <th>2020-1</th>
    <th colspan="3"><a>Menu A</a></th>
    <th colspan="3"><a>Menu B</a></th>
    <th><a>Not eating</a></th>
  </tr>
  <!--Generated meals come here-->
  <tr id="line-1" class="line-1">
    <td class="unselected">1</td>
    <td id="1-a-soup" class="menu-a unselected"><a>SoupA1</a></td>
    <td id="1-a-main" class="menu-a unselected"><a>MainA1</a></td>
    <td id="1-a-garnish" class="menu-a unselected"><a>GarnishA1</a></td>
    <td id="1-b-soup" class="menu-b unselected"><a>SoupB1</a></td>
    <td id="1-b-main" class="menu-b unselected"><a>MainB1</a></td>
    <td id="1-b-garnish" class="menu-b unselected"><a>GarnishB1</a></td>
    <td id="1-n" class="unselected menu-n">
      <a>Not eating</a>
    </td>
  </tr>
  <tr id="line-2" class="line-2">
    <td>2</td>
    <td id="2-a-soup" class="unselected menu-a"><a>SoupA2</a></td>
    <td id="2-a-main" class="unselected menu-a"><a>MainA2</a></td>
    <td id="2-a-garnish" class="unselected menu-a"><a>GarnishA2</a></td>
    <td id="2-b-soup" class="unselected menu-b"><a>SoupB2</a></td>
    <td id="2-b-main" class="unselected menu-b"><a>MainB2</a></td>
    <td id="2-b-garnish" class="unselected menu-b"><a>GarnishB2</a></td>
    <td id="2-n" class="unselected menu-n">
      <a>Not eating</a>
    </td>
  </tr>
</table></code>```

Body:
I have a table with multiple col elements and some of them has a span of 3. If I hover over a cell, which is part of a 3 span col, I'd want all the 3 cells in that row to highlight.

Look at the table below for a better understanding of what I'm refering to by Menu A, etc.
What I want to do is to highlight all the elements of Menu A on that day when I hover over it.
I've tried to achieve it by using siblings, but there's no previous sibling selector, so it only highlights the hovered food, and the foods to its right.

For example, if I hover over MainA1, I'd like to have SoupA1 and GranishA1 highlighted too.

Is there a way to do this in CSS or should I use JavaScript to apply classes to them on hover?

This is what I've tried to do:

.selector .menu-a:hover, .selector .menu-a:hover~.menu-a {
  background: var(--color_hover);
}

This is my table:

:root {
  --color_unselected: #1ba1d6;
  --color_hover: #158ebe;
  --color_selected: #0a688d;
}

.selector {
  border: 1px solid var(--color_unselected);
  width: fit-content;
}

.selector a {
  display: block;
  color: white;
  text-align: center;
  padding: 4px;
  text-decoration: none;
  width: fit-content;
}

.selector {
  border-collapse: collapse;
}

.selector th,
.date-text,
.unselected {
  background: var(--color_unselected);
}

/*My question is about this part*/

.selector .menu-a:hover,
.selector .menu-a:hover~.menu-a {
  background: var(--color_hover);
}

  <colgroup>
    <col span="1" class="date-text menu-day">
    <col span="3" class="menu-a">
    <col span="3" class="menu-b">
    <col span="1" class="menu-n">
  </colgroup>

    2020-1
    Menu A
    Menu B
    Not eating

    1
    SoupA1
    MainA1
    GarnishA1
    SoupB1
    MainB1
    GarnishB1

      Not eating

    2
    SoupA2
    MainA2
    GarnishA2
    SoupB2
    MainB2
    GarnishB2

      Not eating

Body:
Here is a trick that rely on pseudo element. The idea is to make a pseudo element on the first item of the menu and this element should overflow to cover all the other elements so that you always catch the hover effect on the first element.

:root {
  --color_unselected: #1ba1d6;
  --color_hover: #158ebe;
  --color_selected: #0a688d;
}

.selector {
  border: 1px solid var(--color_unselected);
  width: fit-content;
  overflow:hidden; /* added */
}

.selector a {
  display: block;
  color: white;
  text-align: center;
  padding: 4px;
  text-decoration: none;
  width: fit-content;
}

.selector {
  border-collapse: collapse;
}

.selector th,
.date-text,
.unselected {
  background: var(--color_unselected);
}

/*My question is about this part*/

.selector .menu-a:hover,
.selector .menu-a:hover~.menu-a {
  background: var(--color_hover);
}

.selector .menu-b:hover,
.selector .menu-b:hover~.menu-b {
  background: var(--color_hover);
}

/* The trick start here */
.selector a {
  position:relative;
}
.selector a::before {
  content:"";
  position:absolute;
  z-index:9;
  top:0;
  left:0;
  bottom:0;
  width:100vw;
  height: 100vw;
}
/* Remove the pseudo element on the next elements*/
.selector .menu-a ~ .menu-a a::before,
.selector .menu-b ~ .menu-b a::before{
    content:none;
}
/**/

<table id="selector" class="selector">
  <colgroup>
    <col span="1" class="date-text menu-day">
    <col span="3" class="menu-a">
    <col span="3" class="menu-b">
    <col span="1" class="menu-n">
  </colgroup>
  <tr>
    <th><a id="currMthText">2020-1</a></th>
    <th colspan="3"><a>Menu A</a></th>
    <th colspan="3"><a>Menu B</a></th>
    <th><a>Not eating</a></th>
  </tr>
  <!--Generated meals come here-->
  <tr id="line-1" class="line-1">
    <td class="unselected"><a id="day-1">1</a></td>
    <td id="1-a-soup" class="menu-a unselected"><a>SoupA1</a></td>
    <td id="1-a-main" class="menu-a unselected"><a>MainA1</a></td>
    <td id="1-a-garnish" class="menu-a unselected"><a>GarnishA1</a></td>
    <td id="1-b-soup" class="menu-b unselected"><a>SoupB1</a></td>
    <td id="1-b-main" class="menu-b unselected"><a>MainB1</a></td>
    <td id="1-b-garnish" class="menu-b unselected"><a>GarnishB1</a></td>
    <td id="1-n" class="unselected menu-n">
      <a>Not eating</a>
    </td>
  </tr>
  <tr id="line-2" class="line-2">
    <td><a id="day-2">2</a></td>
    <td id="2-a-soup" class="unselected menu-a"><a>SoupA2</a></td>
    <td id="2-a-main" class="unselected menu-a"><a>MainA2</a></td>
    <td id="2-a-garnish" class="unselected menu-a"><a>GarnishA2</a></td>
    <td id="2-b-soup" class="unselected menu-b"><a>SoupB2</a></td>
    <td id="2-b-main" class="unselected menu-b"><a>MainB2</a></td>
    <td id="2-b-garnish" class="unselected menu-b"><a>GarnishB2</a></td>
    <td id="2-n" class="unselected menu-n">
      <a>Not eating</a>
    </td>
  </tr>
</table>


来源: stackexchange

问:
Java - Multilevel sort of a 2D array of integers
I'm trying to figure out how to do a multilevel sort of a 2D array of integers in java,
where the first numbers takes priority.

so a dataset like this:-

```<code>{1,2}
{2,9}
{2,7}
{2,8}
{5,6}
{5,8}
{5,2}
{4,1}
{4,4}
</code>```

Should return something like this:-

```<code>{1,2}
{2,7}
{2,8}
{2,9}
{4,1}
{4,4}
{5,2}
{5,6}
{5,8}
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to figure out how to do a multilevel sort of a 2D array of integers in java,
where the first numbers takes priority.

so a dataset like this:-

{1,2}
{2,9}
{2,7}
{2,8}
{5,6}
{5,8}
{5,2}
{4,1}
{4,4}

Should return something like this:-

{1,2}
{2,7}
{2,8}
{2,9}
{4,1}
{4,4}
{5,2}
{5,6}
{5,8}

Body:
Here's a solution using Comparator.class

int[][] array = {{1,2},{2,9}, {2,7},{2,8},{5,6},{5,8},{5,2},{4,1},                    {4,4}};

Arrays.sort(array, new Comparator<int[]>() {
            @Override
            public int compare(int[] o1, int[] o2) {
                if(o1[0] == o2[0]){
                    return o1[1]-o2[1];
                }else {
                    return o1[0]-o2[0];
                }
            }
        });
System.out.println(Arrays.deepToString(array));

Prints this : [[1, 2], [2, 7], [2, 8], [2, 9], [4, 1], [4, 4], [5, 2], [5, 6], [5, 8]]


问:
Unable to upload "large" files, both file_exists() and is_uploaded_file() are false
I'm trying to upload a gif file to my server using an upload tool (ShareX)

It works very well with "small" files, but when trying to upload a 8 MB one (takes about 1 minute with my connection), it just doesn't work.

So I did some quick debug, and it seems that the functions file_exists and is_uploaded_file are both set to false, exactly like nothing was uploaded, which isn't the case.

if (!file_exists($_FILES[$fileFormName]["tmp_name"]) || !is_uploaded_file($_FILES[$fileFormName]["tmp_name"]))
{
    error([
        "error" => "No file uploaded",
        "file_exists" => file_exists($_FILES[$fileFormName]["tmp_name"]),
        "is_uploaded_file" => is_uploaded_file($_FILES[$fileFormName]["tmp_name"])
    ], "400 Bad Request");
}
```

Why would that happen?

My apache2 php.ini upload_max_filesize is set to 128M so it shouldn't be a file size issue.

My apache2 php.ini max_execution_time is set to 0 so it shouldn't be a timeout issue.

I wasn't able to find anything similar to my problem using Google.

答: Fixed, I also had to adjust post_max_size in my php.ini file.

Body:
I'm trying to upload a gif file to my server using an upload tool (ShareX)

It works very well with "small" files, but when trying to upload a 8 MB one (takes about 1 minute with my connection), it just doesn't work.

So I did some quick debug, and it seems that the functions file_exists and is_uploaded_file are both set to false, exactly like nothing was uploaded, which isn't the case.

if (!file_exists($_FILES[$fileFormName]["tmp_name"]) || !is_uploaded_file($_FILES[$fileFormName]["tmp_name"]))
{
    error([
        "error" => "No file uploaded",
        "file_exists" => file_exists($_FILES[$fileFormName]["tmp_name"]),
        "is_uploaded_file" => is_uploaded_file($_FILES[$fileFormName]["tmp_name"])
    ], "400 Bad Request");
}

Why would that happen?

My apache2 php.ini upload_max_filesize is set to 128M so it shouldn't be a file size issue.

My apache2 php.ini max_execution_time is set to 0 so it shouldn't be a timeout issue.

I wasn't able to find anything similar to my problem using Google.


问:
Array of Strings to an Array of Objects
Maybe there is a method that does this that I don't know about - I doubt it though - but I'm trying to convert an array of strings to an array of Objects. Here is the problem: I'm reading a file in from the command line. The file represents several classes of the following types each with their own data fields. Vehicle is the parent class of all who follow: Vehicle,Car,American Car, Foreign car, Truck, Bicycle.

I have no problem reading the file into a string array. However I need to create objects of all these types and store them in an array of type Vehicle[]. For example a portion of the file looks like this:

Vehicle

Kim Stanley Robinson

2344 court drive

(221)885-7777

stackoverflow@overflow.com

American Car

John Bunyon

1010 binary lane

(221)885-55643

bgt.com

convertable

made in detroit

 union plant

Where Class type is the first line followed by, Owner's Name, address, phone number, email address...Each type has fields particular to it. So a foreign car is not made in Detroit. Each of these fields appear on a separate line in the file. So what I've done is read the  entire file into a string array. However, I need to find my types in the array of strings,create objects of those types, and store them in a Vehicle array. My main problem is that each data field is on a separate line. How should I approach this problem?
This is java code by the way.

答:
Initially reading the data into a String array is fine. Then you need to loop through that array, and based on the "first line" of each loop ("Vehicle", "American car" etc) you will know how many subsequent elements of the array belong to the same.

Something like this (i'll let you fill in the blanks yourself):

```<code>int i = 0;
ArrayList<vehicle> vehicles = new ArrayList();
while (i < data.length)
{
  if (data[i].equalsIgnoreCase("vehicle"))
  {
    Vehicle vehicle = new Vehicle();
    vehicle.setOwner(data[++i]);
    ...
    vehicles.add(vehicle);
  }
  else if (data[i].equalsIgnoreCase("american car"))
  {
    ...
  }
  i++;
}
</code>```

OwnerDisplayName: BloodParrot

ContentLicense: CC BY-SA 2.5

Title: Array of Strings to an Array of Objects

Body:
Initially reading the data into a String array is fine. Then you need to loop through that array, and based on the "first line" of each loop ("Vehicle", "American car" etc) you will know how many subsequent elements of the array belong to the same.

Something like this (i'll let you fill in the blanks yourself):

int i = 0;
ArrayList<vehicle> vehicles = new ArrayList();
while (i < data.length)
{
  if (data[i].equalsIgnoreCase("vehicle"))
  {
    Vehicle vehicle = new Vehicle();
    vehicle.setOwner(data[++i]);
    ...
    vehicles.add(vehicle);
  }
  else if (data[i].equalsIgnoreCase("american car"))
  {
    ...
  }
  i++;
}

OwnerDisplayName: tehvan


问:
mjsip cant send message
I have implemented an android program that can receive simple messages using the MJSIP, the problem is that I would like to be able to send messages too, my class is:

```<code>package org.sipdroid.sipua.ui;
import java.util.Iterator;
import java.util.Locale;
import java.util.Vector;
import org.sipdroid.sipua.SipdroidEngine;
import org.zoolu.sip.address.NameAddress;
import org.zoolu.sip.address.SipURL;
import org.zoolu.sip.call.CallListenerAdapter;
import org.zoolu.sip.dialog.Dialog;
import org.zoolu.sip.dialog.InviteDialog;
import org.zoolu.sip.header.FromHeader;
import org.zoolu.sip.header.Header;
import org.zoolu.sip.header.RecordRouteHeader;
import org.zoolu.sip.header.ToHeader;
import org.zoolu.sip.message.Message;
import org.zoolu.sip.message.MessageFactory;
import org.zoolu.sip.message.SipMethods;
import org.zoolu.sip.message.SipResponses;
import org.zoolu.sip.provider.ConnectionIdentifier;
import org.zoolu.sip.provider.DialogIdentifier;
import org.zoolu.sip.provider.SipProvider;
import org.zoolu.sip.provider.SipProviderListener;
import org.zoolu.sip.provider.TransactionIdentifier;
import org.zoolu.sip.transaction.AckTransactionServer;
import org.zoolu.sip.transaction.AckTransactionServerListener;
import org.zoolu.sip.transaction.InviteTransactionServer;
import org.zoolu.sip.transaction.InviteTransactionServerListener;
import org.zoolu.sip.transaction.TransactionClient;
import org.zoolu.sip.transaction.TransactionClientListener;
import org.zoolu.sip.transaction.TransactionServer;
import org.zoolu.sip.transaction.TransactionServerListener;
import org.zoolu.tools.LogLevel;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.Reader;
import java.io.StringReader;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
public class IMHandler extends TransactionServer implements TransactionClientListener,SipProviderListener,TransactionServerListener,
                            InviteTransactionServerListener, AckTransactionServerListener,
                                                        TextToSpeech.OnInitListener{

private SipProvider sip_provider;
private Message message;
private TransactionServer ts;
private AckTransactionServer ack_ts;
private String callee;
private TextToSpeech mTts;
private String contact_url;

private boolean firstTime = true;

/** constructor */
public IMHandler(SipProvider sip_provider) {
    super(sip_provider);
    this.sip_provider = sip_provider;
    listen();
    Log.e("IMHandler"," <Constructor> IMHandler");

        mTts = new TextToSpeech(Receiver.mContext, this);
}

public void setMessage( Message message){
    this.message = message;
}

/** Starts a new InviteTransactionServer. */
public void listen() {
    ts = new TransactionServer(sip_provider,"MESSAGE", this);
    ts.listen();
    Log.e("IMHandler","<listen> LISTENING FOR INCOMING IM MSGS ....");
}

public void sendMessage(String callee, String caller, String contact,String session_descriptor, String icsi){
    this.callee = callee;
    this.contact_url = contact;
    Log.e("IMHandler","********** callee::"+callee+" caller::"+caller+" contact::"+contact+" *************");
    NameAddress to_url = new NameAddress(callee);
    NameAddress from_url = new NameAddress(caller);
    SipURL request_uri = to_url.getAddress();

    NameAddress contact_url = null;
    if (contact != null) {
        if (contact.indexOf("sip:") >= 0)
            contact_url = new NameAddress(contact);
        else
            contact_url = new NameAddress(new SipURL(contact,sip_provider. getViaAddress(),sip_provider.getPort()));
    } else
        contact_url = from_url;

    Message messageIM = MessageFactory.createMessageRequest(sip_provider, to_url,  from_url, "HELLO", "text/plain", "HELLO WORLD");
    message = messageIM;
    sendIM(messageIM);
}

/**
 * Starts a new InviteTransactionClient and initializes the dialog state
 * information
 *
 * @param invite
 *            the INVITE message
 */
public void sendIM(Message messageIM) {
    TransactionClient invite_tc = new TransactionClient(sip_provider, message, this);
    invite_tc.request();
}

@Override
public void onTransProvisionalResponse(
        org.zoolu.sip.transaction.TransactionClient tc, Message resp) {
    Log.e("IMHandler"," <onTransProvisionalResponse>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onTransSuccessResponse(
        org.zoolu.sip.transaction.TransactionClient tc, Message resp) {
    Log.e("IMHandler"," <onTransSuccessResponse>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onTransFailureResponse(
        org.zoolu.sip.transaction.TransactionClient tc, Message resp) {
    Log.e("IMHandler"," <onTransFailureResponse>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onTransTimeout(org.zoolu.sip.transaction.TransactionClient tc) {
    Log.e("IMHandler"," <onTransTimeout>  ##################");
    // TODO Auto-generated method stub

}

public Message sendResponce(String callee, String caller, String contact,Message req,NameAddress contact_address){
    this.callee = callee;

    Log.e("IMHandler","********** callee::"+callee+" caller::"+caller+" contact::"+contact+" *************");
    NameAddress to_url = new NameAddress(callee);
    NameAddress from_url = new NameAddress(caller);
    SipURL request_uri = to_url.getAddress();

    NameAddress contact_url = null;
    if (contact != null) {
        if (contact.indexOf("sip:") >= 0)
            contact_url = new NameAddress(contact);
        else
            contact_url = new NameAddress(new SipURL(contact,sip_provider. getViaAddress(),sip_provider.getPort()));
    } else
        contact_url = from_url;
    Message resp = MessageFactory.createResponse(req, 200,SipResponses.reasonOf(200), contact_address);
}

@Override
public void onTransRequest(TransactionServer ts, Message req)  {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder;
    try {
            builder = domFactory.newDocumentBuilder();
            Log.e("IMHandler","<onTransRequest> parsing body:: "+ req.getBody());
            InputStream is = new ByteArrayInputStream(req.getBody().getBytes());
            final Document doc = builder.parse(is );

            NamespaceContext NMC = new NamespaceContext() {
                public String getNamespaceURI(String s) {
                    if (s.equals(XMLConstants.DEFAULT_NS_PREFIX))
                        return doc.lookupNamespaceURI(null);
                    else
                        return doc.lookupNamespaceURI(s);
                }

                public String getPrefix(String s) {
                    return doc.lookupPrefix(s);
                }

                public Iterator getPrefixes(String s) {
                    return null;
                }
            };

            NodeList nodes =doc.getChildNodes();// (NodeList) result;
            Log.e("IMHandler"," <PARSING>  *************** result ***********"+nodes.getLength());
            for (int i = 0; i < nodes.getLength(); i++) {
                Log.e("IMHandler"," <PARSING>  *************** PARSING ***********");
                Log.e("IMHandler"," <PARSING>  NodeValue"+nodes.item(i).getNodeName());
                Log.e("IMHandler"," <PARSING>  *************** /PARSING ***********");
            }

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String msg = req.getBody().replaceAll("<(.|\n)*?>","");
    if(firstTime ){
        Receiver.showIM();
        firstTime = false;
    }else{
        Receiver.getMessageListener().setFrom(req.getFromHeader().getValue());
        Receiver.getMessageListener().messageReceived(msg);
    }
    mTts.speak(msg,TextToSpeech.QUEUE_FLUSH,  null);

    NameAddress contact_address = new NameAddress("win@192.168.1.10");
    ConnectionIdentifier conn_id = ts.getConnectionId();

    Message resp = sendResponce(contact_address.toString(),"maxsap@192.168.1.9","maxsap@192.168.1.9",req,contact_address);
    ts.respondWith(resp);

    listen();
}

/**
 * Responds with <i>resp</i>. This method can be called when the
 * InviteDialog is in D_INVITED or D_BYED states.
 * <p>
 * If the CSeq method is INVITE and the response is 2xx, it moves to state
 * D_ACCEPTED, adds a new listener to the SipProviderListener, and creates
 * new AckTransactionServer
 * <p>
 * If the CSeq method is INVITE and the response is not 2xx, it moves to
 * state D_REFUSED, and sends the response.
 */
public void respond(Message resp)
{
    Log.d("IMHandler","<respond> inside respond(resp)");
    String method = resp.getCSeqHeader().getMethod();
    int code = resp.getStatusLine().getCode();

        if (code >= 200 && code < 300) {
            ts.terminate();
            ConnectionIdentifier conn_id = ts.getConnectionId();
            ack_ts = new AckTransactionServer(sip_provider, conn_id, resp,this);
            ack_ts.respond();
            return;
        }
}

/**
 * Responds with <i>code</i> and <i>reason</i>. This method can be called
 * when the InviteDialog is in D_INVITED, D_ReINVITED states
 */
public void respond(int code, String reason, String contact,  Message req) {
    Log.d("InviteDialog","<respond> inside respond(" + code + "," + reason + ")");

        NameAddress contact_address = null;
        if (contact != null)
            contact_address = new NameAddress(contact);
        Message resp = MessageFactory.createResponse(req, code,
                reason, contact_address);
        respond(resp);
}

@Override
public void onTransAckTimeout(AckTransactionServer transaction) {
    Log.e("IMHandler"," <onTransAckTimeout>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onTransFailureAck(InviteTransactionServer ts, Message ack) {
    Log.e("IMHandler"," <onTransFailureAck>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onReceivedMessage(SipProvider sip_provider, Message message) {
    Log.e("IMHandler"," <onReceivedMessage>  ##################");

    //NameAddress contact_address = new NameAddress("win@192.168.1.10");
//  Message resp = MessageFactory.createResponse(req, 200,SipResponses.reasonOf(200), contact_address);
//  ts.respondWith(resp);

    // TODO Auto-generated method stub

}

// Implements TextToSpeech.OnInitListener.
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        int result = mTts.setLanguage(Locale.US);
        if (result == TextToSpeech.LANG_MISSING_DATA ||
             result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("IMHandler", "Language is not available.");
        } else {
             Log.i("IMHandler", "Language found and TTS is initiated.");
        }
    } else {
        Log.e("IMHandler", "Could not initialize TextToSpeech.");
    }
}
</code>```

}

This class is able to receive a message send from a sip client and respond back. But I would like to initiate an im session using the send message method. I am initializing a transaction client and then call on the request method but nothing happens, no error no exception and no message is send.Can someone tell me what I am doing wrong?

答:
found out that the correct way to send the message is:</p>

```<code> /** Sends a new message. */
 public void send(String recipient, String subject, String content_type, String content)                                                                                {
 //    Receiver.engine(Receiver.mContext).ua.
  NameAddress to_url = new NameAddress("Win@192.168.1.37");//recipient);
  NameAddress from_url=new NameAddress(user_profile.from_url);
  Log.e("IMHANDLER","$$$$$$$$$$$$$ to_url"+to_url+" from_url"+from_url+" recipient"+recipient);
  Message req=MessageFactory.createMessageRequest(sip_provider,to_url,from_url,subject,content_type,content);
  TransactionClient t=new TransactionClient(sip_provider,req,this);
  t.request();
 }
</code>```

ContentLicense: CC BY-SA 3.0

Title: mjsip cant send message

Body:
I have implemented an android program that can receive simple messages using the MJSIP, the problem is that I would like to be able to send messages too, my class is:

package org.sipdroid.sipua.ui;
import java.util.Iterator;
import java.util.Locale;
import java.util.Vector;
import org.sipdroid.sipua.SipdroidEngine;
import org.zoolu.sip.address.NameAddress;
import org.zoolu.sip.address.SipURL;
import org.zoolu.sip.call.CallListenerAdapter;
import org.zoolu.sip.dialog.Dialog;
import org.zoolu.sip.dialog.InviteDialog;
import org.zoolu.sip.header.FromHeader;
import org.zoolu.sip.header.Header;
import org.zoolu.sip.header.RecordRouteHeader;
import org.zoolu.sip.header.ToHeader;
import org.zoolu.sip.message.Message;
import org.zoolu.sip.message.MessageFactory;
import org.zoolu.sip.message.SipMethods;
import org.zoolu.sip.message.SipResponses;
import org.zoolu.sip.provider.ConnectionIdentifier;
import org.zoolu.sip.provider.DialogIdentifier;
import org.zoolu.sip.provider.SipProvider;
import org.zoolu.sip.provider.SipProviderListener;
import org.zoolu.sip.provider.TransactionIdentifier;
import org.zoolu.sip.transaction.AckTransactionServer;
import org.zoolu.sip.transaction.AckTransactionServerListener;
import org.zoolu.sip.transaction.InviteTransactionServer;
import org.zoolu.sip.transaction.InviteTransactionServerListener;
import org.zoolu.sip.transaction.TransactionClient;
import org.zoolu.sip.transaction.TransactionClientListener;
import org.zoolu.sip.transaction.TransactionServer;
import org.zoolu.sip.transaction.TransactionServerListener;
import org.zoolu.tools.LogLevel;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.CharArrayReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.PipedInputStream;
import java.io.Reader;
import java.io.StringReader;
import org.w3c.dom.*;
import org.xml.sax.SAXException;
import javax.xml.XMLConstants;
import javax.xml.namespace.NamespaceContext;
import javax.xml.parsers.*;
import javax.xml.xpath.*;
import android.content.Intent;
import android.speech.tts.TextToSpeech;
import android.util.Log;
public class IMHandler extends TransactionServer implements TransactionClientListener,SipProviderListener,TransactionServerListener,
                            InviteTransactionServerListener, AckTransactionServerListener,
                                                        TextToSpeech.OnInitListener{

private SipProvider sip_provider;
private Message message;
private TransactionServer ts;
private AckTransactionServer ack_ts;
private String callee;
private TextToSpeech mTts;
private String contact_url;

private boolean firstTime = true;

/** constructor */
public IMHandler(SipProvider sip_provider) {
    super(sip_provider);
    this.sip_provider = sip_provider;
    listen();
    Log.e("IMHandler"," <Constructor> IMHandler");

        mTts = new TextToSpeech(Receiver.mContext, this);
}

public void setMessage( Message message){
    this.message = message;
}

/** Starts a new InviteTransactionServer. */
public void listen() {
    ts = new TransactionServer(sip_provider,"MESSAGE", this);
    ts.listen();
    Log.e("IMHandler","<listen> LISTENING FOR INCOMING IM MSGS ....");
}

public void sendMessage(String callee, String caller, String contact,String session_descriptor, String icsi){
    this.callee = callee;
    this.contact_url = contact;
    Log.e("IMHandler","********** callee::"+callee+" caller::"+caller+" contact::"+contact+" *************");
    NameAddress to_url = new NameAddress(callee);
    NameAddress from_url = new NameAddress(caller);
    SipURL request_uri = to_url.getAddress();

    NameAddress contact_url = null;
    if (contact != null) {
        if (contact.indexOf("sip:") >= 0)
            contact_url = new NameAddress(contact);
        else
            contact_url = new NameAddress(new SipURL(contact,sip_provider. getViaAddress(),sip_provider.getPort()));
    } else
        contact_url = from_url;

    Message messageIM = MessageFactory.createMessageRequest(sip_provider, to_url,  from_url, "HELLO", "text/plain", "HELLO WORLD");
    message = messageIM;
    sendIM(messageIM);
}

/**
 * Starts a new InviteTransactionClient and initializes the dialog state
 * information
 *
 * @param invite
 *            the INVITE message
 */
public void sendIM(Message messageIM) {
    TransactionClient invite_tc = new TransactionClient(sip_provider, message, this);
    invite_tc.request();
}

@Override
public void onTransProvisionalResponse(
        org.zoolu.sip.transaction.TransactionClient tc, Message resp) {
    Log.e("IMHandler"," <onTransProvisionalResponse>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onTransSuccessResponse(
        org.zoolu.sip.transaction.TransactionClient tc, Message resp) {
    Log.e("IMHandler"," <onTransSuccessResponse>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onTransFailureResponse(
        org.zoolu.sip.transaction.TransactionClient tc, Message resp) {
    Log.e("IMHandler"," <onTransFailureResponse>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onTransTimeout(org.zoolu.sip.transaction.TransactionClient tc) {
    Log.e("IMHandler"," <onTransTimeout>  ##################");
    // TODO Auto-generated method stub

}

public Message sendResponce(String callee, String caller, String contact,Message req,NameAddress contact_address){
    this.callee = callee;

    Log.e("IMHandler","********** callee::"+callee+" caller::"+caller+" contact::"+contact+" *************");
    NameAddress to_url = new NameAddress(callee);
    NameAddress from_url = new NameAddress(caller);
    SipURL request_uri = to_url.getAddress();

    NameAddress contact_url = null;
    if (contact != null) {
        if (contact.indexOf("sip:") >= 0)
            contact_url = new NameAddress(contact);
        else
            contact_url = new NameAddress(new SipURL(contact,sip_provider. getViaAddress(),sip_provider.getPort()));
    } else
        contact_url = from_url;
    Message resp = MessageFactory.createResponse(req, 200,SipResponses.reasonOf(200), contact_address);
}

@Override
public void onTransRequest(TransactionServer ts, Message req)  {
    DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
    domFactory.setNamespaceAware(true); // never forget this!
    DocumentBuilder builder;
    try {
            builder = domFactory.newDocumentBuilder();
            Log.e("IMHandler","<onTransRequest> parsing body:: "+ req.getBody());
            InputStream is = new ByteArrayInputStream(req.getBody().getBytes());
            final Document doc = builder.parse(is );

            NamespaceContext NMC = new NamespaceContext() {
                public String getNamespaceURI(String s) {
                    if (s.equals(XMLConstants.DEFAULT_NS_PREFIX))
                        return doc.lookupNamespaceURI(null);
                    else
                        return doc.lookupNamespaceURI(s);
                }

                public String getPrefix(String s) {
                    return doc.lookupPrefix(s);
                }

                public Iterator getPrefixes(String s) {
                    return null;
                }
            };

            NodeList nodes =doc.getChildNodes();// (NodeList) result;
            Log.e("IMHandler"," <PARSING>  *************** result ***********"+nodes.getLength());
            for (int i = 0; i < nodes.getLength(); i++) {
                Log.e("IMHandler"," <PARSING>  *************** PARSING ***********");
                Log.e("IMHandler"," <PARSING>  NodeValue"+nodes.item(i).getNodeName());
                Log.e("IMHandler"," <PARSING>  *************** /PARSING ***********");
            }

    } catch (ParserConfigurationException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (SAXException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

    String msg = req.getBody().replaceAll("<(.|\n)*?>","");
    if(firstTime ){
        Receiver.showIM();
        firstTime = false;
    }else{
        Receiver.getMessageListener().setFrom(req.getFromHeader().getValue());
        Receiver.getMessageListener().messageReceived(msg);
    }
    mTts.speak(msg,TextToSpeech.QUEUE_FLUSH,  null);

    NameAddress contact_address = new NameAddress("win@192.168.1.10");
    ConnectionIdentifier conn_id = ts.getConnectionId();

    Message resp = sendResponce(contact_address.toString(),"maxsap@192.168.1.9","maxsap@192.168.1.9",req,contact_address);
    ts.respondWith(resp);

    listen();
}

/**
 * Responds with resp. This method can be called when the
 * InviteDialog is in D_INVITED or D_BYED states.
 *

 * If the CSeq method is INVITE and the response is 2xx, it moves to state
 * D_ACCEPTED, adds a new listener to the SipProviderListener, and creates
 * new AckTransactionServer
 *

 * If the CSeq method is INVITE and the response is not 2xx, it moves to
 * state D_REFUSED, and sends the response.
 */
public void respond(Message resp)
{
    Log.d("IMHandler","<respond> inside respond(resp)");
    String method = resp.getCSeqHeader().getMethod();
    int code = resp.getStatusLine().getCode();

        if (code >= 200 && code < 300) {
            ts.terminate();
            ConnectionIdentifier conn_id = ts.getConnectionId();
            ack_ts = new AckTransactionServer(sip_provider, conn_id, resp,this);
            ack_ts.respond();
            return;
        }
}

/**
 * Responds with code and reason. This method can be called
 * when the InviteDialog is in D_INVITED, D_ReINVITED states
 */
public void respond(int code, String reason, String contact,  Message req) {
    Log.d("InviteDialog","<respond> inside respond(" + code + "," + reason + ")");

        NameAddress contact_address = null;
        if (contact != null)
            contact_address = new NameAddress(contact);
        Message resp = MessageFactory.createResponse(req, code,
                reason, contact_address);
        respond(resp);
}

@Override
public void onTransAckTimeout(AckTransactionServer transaction) {
    Log.e("IMHandler"," <onTransAckTimeout>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onTransFailureAck(InviteTransactionServer ts, Message ack) {
    Log.e("IMHandler"," <onTransFailureAck>  ##################");
    // TODO Auto-generated method stub

}

@Override
public void onReceivedMessage(SipProvider sip_provider, Message message) {
    Log.e("IMHandler"," <onReceivedMessage>  ##################");

    //NameAddress contact_address = new NameAddress("win@192.168.1.10");
//  Message resp = MessageFactory.createResponse(req, 200,SipResponses.reasonOf(200), contact_address);
//  ts.respondWith(resp);

    // TODO Auto-generated method stub

}

// Implements TextToSpeech.OnInitListener.
public void onInit(int status) {
    if (status == TextToSpeech.SUCCESS) {
        int result = mTts.setLanguage(Locale.US);
        if (result == TextToSpeech.LANG_MISSING_DATA ||
             result == TextToSpeech.LANG_NOT_SUPPORTED) {
            Log.e("IMHandler", "Language is not available.");
        } else {
             Log.i("IMHandler", "Language found and TTS is initiated.");
        }
    } else {
        Log.e("IMHandler", "Could not initialize TextToSpeech.");
    }
}

}

This class is able to receive a message send from a sip client and respond back. But I would like to initiate an im session using the send message method. I am initializing a transaction client and then call on the request method but nothing happens, no error no exception and no message is send.Can someone tell me what I am doing wrong?

Body:
found out that the correct way to send the message is:

 /** Sends a new message. */
 public void send(String recipient, String subject, String content_type, String content)                                                                                {
 //    Receiver.engine(Receiver.mContext).ua.
  NameAddress to_url = new NameAddress("Win@192.168.1.37");//recipient);
  NameAddress from_url=new NameAddress(user_profile.from_url);
  Log.e("IMHANDLER","$$$$$$$$$$$$$ to_url"+to_url+" from_url"+from_url+" recipient"+recipient);
  Message req=MessageFactory.createMessageRequest(sip_provider,to_url,from_url,subject,content_type,content);
  TransactionClient t=new TransactionClient(sip_provider,req,this);
  t.request();
 }


问:
Accessing Docker container from outside/browser
My Docker Compose config:

```<code>
version: "3"
services:
  django1:
    build: .
    command: "python ./test1/manage.py runserver"
    ports:
      - "8006:8000"
    expose:
      - "8006"
    networks:
      main_network:
        ipv4_address: 20.20.0.3
  django2:
    build: .
    command: "python ./test2/manage.py runserver"
    ports:
      - "8007:8000"
    expose:
      - "8007"
    networks:
      main_network:
        ipv4_address: 20.20.0.2

networks:
  main_network:
    driver: bridge
    ipam:
      config:
        - subnet: 20.20.0.0/24

</code>```

and this is my command for accessing Docker from outside

```<code>docker run --name testname -p 8077:8007 my_image_name
</code>```

But still when I visit from browser 20.20.0.2:8077 but it does not work

What am I doing wrong?

答:
The Docker-internal IP addresses only work on one very specific host/OS configuration; you shouldn’t try to access them directly and there’s almost never a need to specify them in configuration.  (You can in fact delete all of the networks: blocks, Compose provides reasonable defaults for you.)

Since you publish ports: you can use your host’s IP address and the published (first) port number.  If your browser and Docker are on the same host then localhost will work here too (http://localhost:8077), unless you’re using Docker Toolbox, in which case you need the docker-machine ip address (often 192.168.99.100).

If you can access the container-private IP addresses at all (your browser and Docker are on the same native-Linux host and you’re not running a more complex Docker-in-Docker or VM-based setup) then you need the port number inside the container, the second number in ports:.  This also applies to container-to-container communication, where the Compose service names should be used as host names (django1 can call http://django2:8000).

Body:
My Docker Compose config:

version: "3"
services:
  django1:
    build: .
    command: "python ./test1/manage.py runserver"
    ports:
      - "8006:8000"
    expose:
      - "8006"
    networks:
      main_network:
        ipv4_address: 20.20.0.3
  django2:
    build: .
    command: "python ./test2/manage.py runserver"
    ports:
      - "8007:8000"
    expose:
      - "8007"
    networks:
      main_network:
        ipv4_address: 20.20.0.2

networks:
  main_network:
    driver: bridge
    ipam:
      config:
        - subnet: 20.20.0.0/24

and this is my command for accessing Docker from outside

docker run --name testname -p 8077:8007 my_image_name

But still when I visit from browser 20.20.0.2:8077 but it does not work

What am I doing wrong?


问:
Using a Python Dictionary as a Key (Non-nested)
Python doesn't allow dictionaries to be used as keys in other dictionaries. Is there a workaround for using non-nested dictionaries as keys?

The general problem with more complicated non-hashable objects and my specific use case has been moved here. My original description of my use case was incorrect.

答:
I'll sum up the options and add one of my own,
you can :

make a subclass to dict and provide a hash function

flatten the dict into a tuple

pickle the dict

convert the Dict into a string using the json module (as shown below)

```<code>import json
Dict = {'key' :'value123'}
stringifiedDict = json.dumps(Dict)
print(stringifiedDict)
# {"key": "value123"}
newDict = {stringifiedDict: 12345}
print(newDict[stringifiedDict])
# 12345
for key, val in newDict.items():
    print(json.loads(key))
    # {'key': 'value123'}
    print(json.loads(key)['key'])
    # value123
</code>```

Body:
I'll sum up the options and add one of my own,
you can :

make a subclass to dict and provide a hash function

flatten the dict into a tuple

pickle the dict

convert the Dict into a string using the json module (as shown below)

import json
Dict = {'key' :'value123'}
stringifiedDict = json.dumps(Dict)
print(stringifiedDict)
# {"key": "value123"}
newDict = {stringifiedDict: 12345}
print(newDict[stringifiedDict])
# 12345
for key, val in newDict.items():
    print(json.loads(key))
    # {'key': 'value123'}
    print(json.loads(key)['key'])
    # value123


问:
Load balancer does not have available server for client
I'm trying to use Feign client. Below is my feing client:

```<code>import com.eprogrammerz.examples.domain.Movie;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by Yogen on 12/26/2016.
 */
@FeignClient(name = "movie-api")
public interface MovieApi {
    @RequestMapping(method = RequestMethod.GET, value = "/movies/{id}")
    Movie getMovie(@PathVariable("id") Long id);
}
</code>```

I'm calling it from simple service as below:

```<code>@Service
public class MovieService {

    @Autowired
    MovieApi movieApi;

    public Movie findMovie(Long id){
        Movie movieOfTheDay = movieApi.getMovie(id);
        return movieOfTheDay;
    }
}
</code>```

My spring boot app is as below:

```<code>import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@EnableFeignClients(basePackages = {"com.eprogrammerz.examples"})
@EnableCircuitBreaker
@SpringBootApplication
public class ClientAppApplication {

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

build.gradle

```<code>buildscript {
    ext {
        springBootVersion = '1.4.3.RELEASE'
    }
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'client-app'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    jcenter()
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}

dependencies {
    compile('org.springframework.cloud:spring-cloud-starter-feign')
    // https://mvnrepository.com/artifact/com.netflix.hystrix/hystrix-core
    compile('org.springframework.cloud:spring-cloud-starter-hystrix')
    compile("org.springframework.boot:spring-boot-starter-web"){
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
    compileOnly('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:Camden.BUILD-SNAPSHOT"
        mavenBom "org.springframework.boot:spring-boot-starter-parent:${springBootVersion}"
    }
}
</code>```

I'm getting error as below:

```<code>2016-12-30 13:07:16.894  INFO 6748 --- [nio-8082-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 39 ms
2016-12-30 13:07:16.939  INFO 6748 --- [nio-8082-exec-1] c.e.e.controllers.RequestController      : Calling findMovie(1203)
2016-12-30 13:07:17.240  INFO 6748 --- [rix-movie-api-1] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@547496c2: startup date [Fri Dec 30 13:07:17 EST 2016]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@542e560f
2016-12-30 13:07:17.318  INFO 6748 --- [rix-movie-api-1] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-12-30 13:07:17.619  INFO 6748 --- [rix-movie-api-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: movie-api.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2016-12-30 13:07:17.670  INFO 6748 --- [rix-movie-api-1] c.n.u.concurrent.ShutdownEnabledTimer    : Shutdown hook installed for: NFLoadBalancer-PingTimer-movie-api
2016-12-30 13:07:17.727  INFO 6748 --- [rix-movie-api-1] c.netflix.loadbalancer.BaseLoadBalancer  : Client:movie-api instantiated a LoadBalancer:DynamicServerListLoadBalancer:{NFLoadBalancer:name=movie-api,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2016-12-30 13:07:17.739  INFO 6748 --- [rix-movie-api-1] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2016-12-30 13:07:17.746  INFO 6748 --- [rix-movie-api-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client movie-api initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=movie-api,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:com.netflix.loadbalancer.ConfigurationBasedServerList@45bcfd5
2016-12-30 13:07:18.191 ERROR 6748 --- [nio-8082-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.netflix.hystrix.exception.HystrixRuntimeException: MovieApi#getMovie(Long) failed and no fallback available.] with root cause

com.netflix.client.ClientException: Load balancer does not have available server for client: movie-api
    at com.netflix.loadbalancer.LoadBalancerContext.getServerFromLoadBalancer(LoadBalancerContext.java:468) ~[ribbon-loadbalancer-2.2.0.jar:2.2.0]
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:184) ~[ribbon-loadbalancer-2.2.0.jar:2.2.0]
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:180) ~[ribbon-loadbalancer-2.2.0.jar:2.2.0]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:94) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:42) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber$1.call(OperatorRetryWithPredicate.java:127) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue(TrampolineScheduler.java:73) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule(TrampolineScheduler.java:52) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:79) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:45) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.util.ScalarSynchronousObservable$WeakSingleProducer.request(ScalarSynchronousObservable.java:276) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Subscriber.setProducer(Subscriber.java:209) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:138) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:129) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.subscribe(Observable.java:10307) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.subscribe(Observable.java:10274) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.observables.BlockingObservable.blockForSingle(BlockingObservable.java:445) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.observables.BlockingObservable.single(BlockingObservable.java:342) ~[rxjava-1.1.10.jar:1.1.10]
    at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:102) ~[ribbon-loadbalancer-2.2.0.jar:2.2.0]
    at org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:63) ~[spring-cloud-netflix-core-1.2.4.BUILD-SNAPSHOT.jar:1.2.4.BUILD-SNAPSHOT]
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:97) ~[feign-core-9.3.1.jar:na]
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76) ~[feign-core-9.3.1.jar:na]
    at feign.hystrix.HystrixInvocationHandler$1.run(HystrixInvocationHandler.java:108) ~[feign-hystrix-9.3.1.jar:na]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:301) ~[hystrix-core-1.5.6.jar:1.5.6]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:297) ~[hystrix-core-1.5.6.jar:1.5.6]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94) ~[rxjava-1.1.10.jar:1.1.10]
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:56) ~[hystrix-core-1.5.6.jar:1.5.6]
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:47) ~[hystrix-core-1.5.6.jar:1.5.6]
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction.call(HystrixContexSchedulerAction.java:69) ~[hystrix-core-1.5.6.jar:1.5.6]
    at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55) ~[rxjava-1.1.10.jar:1.1.10]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_51]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_51]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_51]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_51]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_51]
</code>```

I tried different way. But couldn't figure out the solution. I couldn't find any information about this on Spring Cloud Netflix too. I couldn't find any information on discussion thread on StackOverflow too.

What I'm missing here? TIA.

Further Details:

application.yml for movie-api microservice is as below:

```<code>server:
  port: 8090
logging:
  config: classpath:log4j2.yml
spring:
  application:
    name: movie-api
</code>```

Spring boot app on movie-api module:

```<code>@SpringBootApplication
public class MovieApiApplication {

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

And controller is as below:

```<code>@RestController
@Slf4j
public class MovieController {
    @Autowired
    private MovieRepository movieRepository;

    @RequestMapping("/movies/{id}")
    public ResponseEntity<Movie> getBook(@PathVariable("id") Long id){
        log.trace("getBook({})",id);
        Optional<Movie> movie = Optional.of(movieRepository.findOneById(id));
        if(movie.isPresent())
            return new ResponseEntity(movie.get(), HttpStatus.OK);
        return new ResponseEntity<Movie>(HttpStatus.NOT_FOUND);
    }
}
</code>```

答:
The problem is that your service doesn't know the host of the requested service. If you are using Eureka and zuul, put this line on your zuul .properties or .yml file :

eureka.client.fetch-registry=true

Body:
I'm trying to use Feign client. Below is my feing client:

import com.eprogrammerz.examples.domain.Movie;
import org.springframework.cloud.netflix.feign.FeignClient;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

/**
 * Created by Yogen on 12/26/2016.
 */
@FeignClient(name = "movie-api")
public interface MovieApi {
    @RequestMapping(method = RequestMethod.GET, value = "/movies/{id}")
    Movie getMovie(@PathVariable("id") Long id);
}

I'm calling it from simple service as below:

@Service
public class MovieService {

    @Autowired
    MovieApi movieApi;

    public Movie findMovie(Long id){
        Movie movieOfTheDay = movieApi.getMovie(id);
        return movieOfTheDay;
    }
}

My spring boot app is as below:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.circuitbreaker.EnableCircuitBreaker;
import org.springframework.cloud.netflix.feign.EnableFeignClients;

@EnableFeignClients(basePackages = {"com.eprogrammerz.examples"})
@EnableCircuitBreaker
@SpringBootApplication
public class ClientAppApplication {

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

build.gradle

buildscript {
    ext {
        springBootVersion = '1.4.3.RELEASE'
    }
    repositories {
        jcenter()
        mavenCentral()
    }
    dependencies {
        classpath("org.springframework.boot:spring-boot-gradle-plugin:${springBootVersion}")
    }
}

apply plugin: 'java'
apply plugin: 'eclipse'
apply plugin: 'org.springframework.boot'

jar {
    baseName = 'client-app'
    version = '0.0.1-SNAPSHOT'
}
sourceCompatibility = 1.8
targetCompatibility = 1.8

repositories {
    jcenter()
    mavenCentral()
    maven { url "https://repo.spring.io/snapshot" }
    maven { url "https://repo.spring.io/milestone" }
}

dependencies {
    compile('org.springframework.cloud:spring-cloud-starter-feign')
    // https://mvnrepository.com/artifact/com.netflix.hystrix/hystrix-core
    compile('org.springframework.cloud:spring-cloud-starter-hystrix')
    compile("org.springframework.boot:spring-boot-starter-web"){
        exclude group: 'org.springframework.boot', module: 'spring-boot-starter-logging'
    }
    compileOnly('org.projectlombok:lombok')
    testCompile('org.springframework.boot:spring-boot-starter-test')
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:Camden.BUILD-SNAPSHOT"
        mavenBom "org.springframework.boot:spring-boot-starter-parent:${springBootVersion}"
    }
}

I'm getting error as below:

2016-12-30 13:07:16.894  INFO 6748 --- [nio-8082-exec-1] o.s.web.servlet.DispatcherServlet        : FrameworkServlet 'dispatcherServlet': initialization completed in 39 ms
2016-12-30 13:07:16.939  INFO 6748 --- [nio-8082-exec-1] c.e.e.controllers.RequestController      : Calling findMovie(1203)
2016-12-30 13:07:17.240  INFO 6748 --- [rix-movie-api-1] s.c.a.AnnotationConfigApplicationContext : Refreshing org.springframework.context.annotation.AnnotationConfigApplicationContext@547496c2: startup date [Fri Dec 30 13:07:17 EST 2016]; parent: org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext@542e560f
2016-12-30 13:07:17.318  INFO 6748 --- [rix-movie-api-1] f.a.AutowiredAnnotationBeanPostProcessor : JSR-330 'javax.inject.Inject' annotation found and supported for autowiring
2016-12-30 13:07:17.619  INFO 6748 --- [rix-movie-api-1] c.netflix.config.ChainedDynamicProperty  : Flipping property: movie-api.ribbon.ActiveConnectionsLimit to use NEXT property: niws.loadbalancer.availabilityFilteringRule.activeConnectionsLimit = 2147483647
2016-12-30 13:07:17.670  INFO 6748 --- [rix-movie-api-1] c.n.u.concurrent.ShutdownEnabledTimer    : Shutdown hook installed for: NFLoadBalancer-PingTimer-movie-api
2016-12-30 13:07:17.727  INFO 6748 --- [rix-movie-api-1] c.netflix.loadbalancer.BaseLoadBalancer  : Client:movie-api instantiated a LoadBalancer:DynamicServerListLoadBalancer:{NFLoadBalancer:name=movie-api,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:null
2016-12-30 13:07:17.739  INFO 6748 --- [rix-movie-api-1] c.n.l.DynamicServerListLoadBalancer      : Using serverListUpdater PollingServerListUpdater
2016-12-30 13:07:17.746  INFO 6748 --- [rix-movie-api-1] c.n.l.DynamicServerListLoadBalancer      : DynamicServerListLoadBalancer for client movie-api initialized: DynamicServerListLoadBalancer:{NFLoadBalancer:name=movie-api,current list of Servers=[],Load balancer stats=Zone stats: {},Server stats: []}ServerList:com.netflix.loadbalancer.ConfigurationBasedServerList@45bcfd5
2016-12-30 13:07:18.191 ERROR 6748 --- [nio-8082-exec-1] o.a.c.c.C.[.[.[/].[dispatcherServlet]    : Servlet.service() for servlet [dispatcherServlet] in context with path [] threw exception [Request processing failed; nested exception is com.netflix.hystrix.exception.HystrixRuntimeException: MovieApi#getMovie(Long) failed and no fallback available.] with root cause

com.netflix.client.ClientException: Load balancer does not have available server for client: movie-api
    at com.netflix.loadbalancer.LoadBalancerContext.getServerFromLoadBalancer(LoadBalancerContext.java:468) ~[ribbon-loadbalancer-2.2.0.jar:2.2.0]
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:184) ~[ribbon-loadbalancer-2.2.0.jar:2.2.0]
    at com.netflix.loadbalancer.reactive.LoadBalancerCommand$1.call(LoadBalancerCommand.java:180) ~[ribbon-loadbalancer-2.2.0.jar:2.2.0]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:94) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeConcatMap.call(OnSubscribeConcatMap.java:42) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber$1.call(OperatorRetryWithPredicate.java:127) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.enqueue(TrampolineScheduler.java:73) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.schedulers.TrampolineScheduler$InnerCurrentThreadScheduler.schedule(TrampolineScheduler.java:52) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:79) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorRetryWithPredicate$SourceSubscriber.onNext(OperatorRetryWithPredicate.java:45) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.util.ScalarSynchronousObservable$WeakSingleProducer.request(ScalarSynchronousObservable.java:276) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Subscriber.setProducer(Subscriber.java:209) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:138) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.util.ScalarSynchronousObservable$JustOnSubscribe.call(ScalarSynchronousObservable.java:129) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.subscribe(Observable.java:10307) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.subscribe(Observable.java:10274) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.observables.BlockingObservable.blockForSingle(BlockingObservable.java:445) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.observables.BlockingObservable.single(BlockingObservable.java:342) ~[rxjava-1.1.10.jar:1.1.10]
    at com.netflix.client.AbstractLoadBalancerAwareClient.executeWithLoadBalancer(AbstractLoadBalancerAwareClient.java:102) ~[ribbon-loadbalancer-2.2.0.jar:2.2.0]
    at org.springframework.cloud.netflix.feign.ribbon.LoadBalancerFeignClient.execute(LoadBalancerFeignClient.java:63) ~[spring-cloud-netflix-core-1.2.4.BUILD-SNAPSHOT.jar:1.2.4.BUILD-SNAPSHOT]
    at feign.SynchronousMethodHandler.executeAndDecode(SynchronousMethodHandler.java:97) ~[feign-core-9.3.1.jar:na]
    at feign.SynchronousMethodHandler.invoke(SynchronousMethodHandler.java:76) ~[feign-core-9.3.1.jar:na]
    at feign.hystrix.HystrixInvocationHandler$1.run(HystrixInvocationHandler.java:108) ~[feign-hystrix-9.3.1.jar:na]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:301) ~[hystrix-core-1.5.6.jar:1.5.6]
    at com.netflix.hystrix.HystrixCommand$2.call(HystrixCommand.java:297) ~[hystrix-core-1.5.6.jar:1.5.6]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:46) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:51) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDefer.call(OnSubscribeDefer.java:35) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:41) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeDoOnEach.call(OnSubscribeDoOnEach.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:48) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OnSubscribeLift.call(OnSubscribeLift.java:30) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.Observable.unsafeSubscribe(Observable.java:10211) ~[rxjava-1.1.10.jar:1.1.10]
    at rx.internal.operators.OperatorSubscribeOn$1.call(OperatorSubscribeOn.java:94) ~[rxjava-1.1.10.jar:1.1.10]
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:56) ~[hystrix-core-1.5.6.jar:1.5.6]
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction$1.call(HystrixContexSchedulerAction.java:47) ~[hystrix-core-1.5.6.jar:1.5.6]
    at com.netflix.hystrix.strategy.concurrency.HystrixContexSchedulerAction.call(HystrixContexSchedulerAction.java:69) ~[hystrix-core-1.5.6.jar:1.5.6]
    at rx.internal.schedulers.ScheduledAction.run(ScheduledAction.java:55) ~[rxjava-1.1.10.jar:1.1.10]
    at java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:511) ~[na:1.8.0_51]
    at java.util.concurrent.FutureTask.run(FutureTask.java:266) ~[na:1.8.0_51]
    at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1142) ~[na:1.8.0_51]
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617) ~[na:1.8.0_51]
    at java.lang.Thread.run(Thread.java:745) [na:1.8.0_51]

I tried different way. But couldn't figure out the solution. I couldn't find any information about this on Spring Cloud Netflix too. I couldn't find any information on discussion thread on StackOverflow too.

What I'm missing here? TIA.

Further Details:

application.yml for movie-api microservice is as below:

server:
  port: 8090
logging:
  config: classpath:log4j2.yml
spring:
  application:
    name: movie-api

Spring boot app on movie-api module:

@SpringBootApplication
public class MovieApiApplication {

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

And controller is as below:

@RestController
@Slf4j
public class MovieController {
    @Autowired
    private MovieRepository movieRepository;

    @RequestMapping("/movies/{id}")
    public ResponseEntity<Movie> getBook(@PathVariable("id") Long id){
        log.trace("getBook({})",id);
        Optional<Movie> movie = Optional.of(movieRepository.findOneById(id));
        if(movie.isPresent())
            return new ResponseEntity(movie.get(), HttpStatus.OK);
        return new ResponseEntity<Movie>(HttpStatus.NOT_FOUND);
    }
}


问:
Variable shadowing in Java, multiple cases static/non static
I have been taking a course in Java lately and we are dealing with programm outputs, compile errors etc.
I have tried different codes myself, and one thing from my experiments really confused me:
Firstly, the main method looks like this:

```<code>public static void main(String[] args){
     A a = new A();
     B b = new B();
     A ab = new B();

     System.out.println(a.a + " " + b.a + " " + ab.a);

}
</code>```

Now I tried these different versions:

```<code>//1
public class A {
  public static int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
  public static int a = 2;
   public B(){ a = 22;}
}
//------------
//2
public class A {
  public int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
  public static int a = 2;
   public B(){ a = 22;}
}
//--------------
//3
public class A {
  public static int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
   public B(){ a = 22;}
}
//-----------
//4
public class A {
  public int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
   public B(){ a = 22;}
}
</code>```

The outputs are the following:

11  22  11

11  22  11

3: 11  22  22

22  22  22

While I can understand outputs 1 and 2, 3 and 4 are really confusing to me.

For 3: The a = 22 in B, changes the value of a for the A object ab, because int a is not declared again in B?

And for 4: If int a in A is not static, and a is an object of the type A, why does a.a have the value of b.a? What is happening in 4, when I set the int a as not static?

Thanks in advance!

答:
Important note: The answer for case 4 is 11 22 22

In case 3: when A ab = B() executed constructor of B set the static variable a in A so it has the value of 22.

in case 4: both classes A and B has instance field (a) (actually class B inherit this attribute from class A) and at construction time first the constructor of Class A executed and then the constructor of class B so when we have A a = B() first constructor of class A set the variable a to 11 then the constructor of class B set it to 22
static field in child class don't override static fields in parent class they just hide the static fields in parent class if you access the static the result is not depend on the type of object itself but it depend on the type of reference you use to access that object so when you write A a = B(), if A and B both has static field a, the result of a.a is a in class A not a in class B because the type of reference you use to access the object here is A, while the object type itself is B.

Body:
I have been taking a course in Java lately and we are dealing with programm outputs, compile errors etc.
I have tried different codes myself, and one thing from my experiments really confused me:
Firstly, the main method looks like this:

public static void main(String[] args){
     A a = new A();
     B b = new B();
     A ab = new B();

     System.out.println(a.a + " " + b.a + " " + ab.a);

}

Now I tried these different versions:

//1
public class A {
  public static int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
  public static int a = 2;
   public B(){ a = 22;}
}
//------------
//2
public class A {
  public int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
  public static int a = 2;
   public B(){ a = 22;}
}
//--------------
//3
public class A {
  public static int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
   public B(){ a = 22;}
}
//-----------
//4
public class A {
  public int a = 1;
   public A() {
    a = 11;
   }
}
public class B extends A {
   public B(){ a = 22;}
}

The outputs are the following:

11  22  11

11  22  11

3: 11  22  22

22  22  22

While I can understand outputs 1 and 2, 3 and 4 are really confusing to me.

For 3: The a = 22 in B, changes the value of a for the A object ab, because int a is not declared again in B?

And for 4: If int a in A is not static, and a is an object of the type A, why does a.a have the value of b.a? What is happening in 4, when I set the int a as not static?

Thanks in advance!


问:
Autocomplete in PyCharm for Python compiled extensions
When writing Python code using compiled extensions (the OpenCV Python bindings, for example), PyCharm doesn't seem to be aware of their availability. The imports are marked with a grey underline, saying "unresolved reference" as a tooltip, and autocomplete doesn't work, either. (Except for the function names already used in the code.)

This isn't caused by wrong module paths, the code runs without error when started. Also, after I import the modules in a Python shell, autocomplete starts working as expected.

Is there a solution for that or is this an architectural limitation for compiled extensions? Are there any other IDEs that manage to cope with this problem?

答:
I had to hardlink the binary into the folder lib-dynload of my interpreter.

```<code>$ cd /usr/lib/python3.7/lib-dynload
$ sudo ln /usr/local/lib/python3.7/dist-packages/cv2/python-3.7/cv2.cpython-37m-x86_64-linux-gnu.so cv2.cpython-37m-x86_64-linux-gnu.so
</code>```

The paths may vary in your environment. I didn't test it on OSX or Windows, but it may work there too. The lib-dynload folder is here:

Body:
I had to hardlink the binary into the folder lib-dynload of my interpreter.

$ cd /usr/lib/python3.7/lib-dynload
$ sudo ln /usr/local/lib/python3.7/dist-packages/cv2/python-3.7/cv2.cpython-37m-x86_64-linux-gnu.so cv2.cpython-37m-x86_64-linux-gnu.so

The paths may vary in your environment. I didn't test it on OSX or Windows, but it may work there too. The lib-dynload folder is here:


问:
Python_Cookbook_3rd_Edition 6.12 a Question
Python_Cookbook_3rd_Edition

6.12. Reading Nested and Variable-Sized Binary
Structures

```<code>import struct
import itertools

def write_polys(filename, polys):
    # Determine bounding box
    flattened = list(itertools.chain(*polys))
    min_x = min(x for x, y in flattened)
    max_x = max(x for x, y in flattened)
    min_y = min(y for x, y in flattened)
    max_y = max(y for x, y in flattened)
    with open(filename, 'wb') as f:
        f.write(struct.pack('<iddddi', 0x1234,
                            min_x, min_y,
                            max_x, max_y,
                            len(polys)))
        for poly in polys:
            size = len(poly) * struct.calcsize('<dd')
            f.write(struct.pack('<i', size + 4))
            for pt in poly:
                f.write(struct.pack('<dd', *pt))
</code>```

Why use f.write(struct.pack('<i', size + 4)) size+4？

I think just f.write(struct.pack('<i', size))is ok

答: In the book in the figure right before the code, it shows how polygon records are encoded. The first field is an int whose value is "Record length including length (N bytes)". Since this record length is written as a 4-byte i integer, 4 is being added to size of all the points (pairs of X,Y coordinates) comprising the polygon.

Body:
Python_Cookbook_3rd_Edition

6.12. Reading Nested and Variable-Sized Binary
Structures

import struct
import itertools

def write_polys(filename, polys):
    # Determine bounding box
    flattened = list(itertools.chain(*polys))
    min_x = min(x for x, y in flattened)
    max_x = max(x for x, y in flattened)
    min_y = min(y for x, y in flattened)
    max_y = max(y for x, y in flattened)
    with open(filename, 'wb') as f:
        f.write(struct.pack('<iddddi', 0x1234,
                            min_x, min_y,
                            max_x, max_y,
                            len(polys)))
        for poly in polys:
            size = len(poly) * struct.calcsize('<dd')
            f.write(struct.pack('<i', size + 4))
            for pt in poly:
                f.write(struct.pack('<dd', *pt))

Why use f.write(struct.pack('<i', size + 4)) size+4？

I think just f.write(struct.pack('<i', size))is ok


问:
How to make a circular histogram in which both the axes and the range of values are modified in R
I have a dataframe df which has a column called Roll with values of angles that ranges between -180 to 180. As an example:

```<code>set.seed(123)
Roll<-sample(seq(from = -180, to = 180, by = 10), size = 200, replace = TRUE)
df<- data.frame(Roll)
head(df$Roll)

[1]  120  -40  -50 -160  180  -50
</code>```

I want to create a circular histogram with the next aesthetic:

Does anyone know how to create a plot like this? I don't know how to transform axes to get this.

答:
You can use coord_polar to transform a histogram into polar coordinates, and adjust the start value in radians (here we want 90 degrees in radians to match your drawing).

library(ggplot2)

ggplot(df) +
  geom_histogram(aes(x = Roll)) +
  scale_x_continuous(breaks = c(-180, -90, 0, 90, 180)) +
  coord_polar(start = pi/2)
```

Body:
I have a dataframe df which has a column called Roll with values of angles that ranges between -180 to 180. As an example:

set.seed(123)
Roll<-sample(seq(from = -180, to = 180, by = 10), size = 200, replace = TRUE)
df<- data.frame(Roll)
head(df$Roll)

[1]  120  -40  -50 -160  180  -50

I want to create a circular histogram with the next aesthetic:

Does anyone know how to create a plot like this? I don't know how to transform axes to get this.


问:
Extracting values
If I have an array,I want to extract each values in each line (values after (:) )

```<code>Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}
</code>```

Imagine I have several key : value then I want to extract Just value like bellow:

```<code>Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

</code>```

I have the result like this :

```<code>var result = ["value","value1",value3","value5","value6","value7"];
</code>```

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start

答:
You will need create a function like "findWithAttr".

Try this step by step below after create the "findWithAttr" function.

function findWithAttr(array, attr, value) {
  for(var i = 0; i < array.length; i += 1) {
    if(array[i][attr] === value) {
      return i;
    }
  }
  return -1;
}

const allLines = [
  {id: "29605581.57644a", type: "tab", label: "Flow 1"},
  {id: "f17a4a1e.6513f8", type: "tab", label: "Flow 2"},
  {id: "6730d437.0698dc", type: "tab", label: "Flow 3"},
  {id: "89b04ddc.4d32e", type: "input-distributer", z: "29605581.57644a"},
  {id: "74d8cc97.780304", type: "video-switcher", z: "29605581.57644a"},
  {id: "5555183d.d59408", type: "output-distributer", z: "29605581.57644a"},
  {id: "29605581.57644a", type: "output-distributer", z: "29605581.57644a"}
]

// Get clicked line
const clickedLine = {id: "29605581.57644a", type: "tab", label: "Flow 1"}

// Use a "findWithAttr" function to get clicked line's index
const clickedLineIndex = findWithAttr(allLines, clickedLine.id)

// Then filter other lines
const otherLines = allLines.filter((line, index) => index !== clickedLineIndex)

// Finally get lines with equal IDs
const linesWithEqualId = otherLines.filter((line, i) => line.id === clickedLine.id)

// And log the result
console.log(linesWithEqualId)```

Title: Extracting values

Body:
If I have an array,I want to extract each values in each line (values after (:) )

Array =
0:Object {node-input-audio_services1: "79388", audio_ip: "127.0.0.1", audio_port_1: "7654"}
1:Object {node-input-video_services1: "80788", video_ip: "127.0.0.1", video_port_1: "7654"}
2:Object {node-input-audio_services1: "4fe10"}
3:Object {node-input-video_services1: "4fe10"}

Imagine I have several key : value then I want to extract Just value like bellow:

Array =
0:Object {key1 : "value" , Key2 : "value2" , key3: "value3"}
1:Object {key1 : "value5" , Key2 : "value6" , key3: "value7"}

I have the result like this :

var result = ["value","value1",value3","value5","value6","value7"];

The problem is, I can't use (key1.array) because each time in my program have one key's name.I really new in JavaScript and don't know how I can start


问:
navigate function in Gatsby simple-auth example leads to build error
the simple-auth example in Gatsby works fine in development mode but when I try to build it, it will throw following error

WebpackError: TypeError: window.___navigate is not a function

index.js:233 navigate node_modules/gatsby-link/index.js:233:1

PrivateRoute.js:11 PrivateRoute src/components/PrivateRoute.js:11:14

It seems the error lies in the navigate function which leads to the build error. I googled and find that a fix is to use navigate inside useEffect however, there is no example online which I can refer. I'm trying to solve this. Can anyone who has successfully resolve this build error share how they resolve this build error? Thanks

Below is the PrivateRoute.js component

import React, { Component } from "react"
import { navigate } from "gatsby"
import { isLoggedIn } from "../utils/auth"

const PrivateRoute = ({ component: Component, location, ...rest }) => {
  if (!isLoggedIn() && location.pathname !== /admin) {
    navigate("/admin")
    return null
  }
  return <Component {...rest} />
}

export default PrivateRoute
```

答:
It seems below work. Anyone thinks my code can be improved are welcome to comment. Hope it helps someone. Thanks

import React, { useEffect, Component } from "react"
import { navigate } from "gatsby"

import { isLoggedIn } from "../utils/auth"

const PrivateRoute = ({ component: Component, location, ...rest }) => {
  useEffect(() => {
    checkLoginStatus()
    // return () => {
    //   cleanup
    // };
  }, [])

  const checkLoginStatus = () => {
    if (!isLoggedIn() && location.pathname !== `/admin`) {
      navigate("/admin")
      return null
    }
  }

return <Component {...rest} />
}

export default PrivateRoute
```


问:
Define window and use it in several analytic columns
I have an oracle query in which I need use several analytic functions within the same window. How can I define a window once and then use it for each of these calls?

I.e. I wanna to write it like in PostGRESql:

SELECT
    sum(salary) OVER w,
    avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);
```

Forgot to mention, the goal is to avoid code duplication, not to speed up the query.

答:
Starting from version 20c Oracle supports window clause syntax.

Enhanced Analytic Functions

The query_block clause of a SELECT statement now supports the window_clause, which implements the window clause of the SQL standard table expression as defined in the SQL:2011 standard.

SELECT

So your query will work perfectly fine without changes:

```<code>SELECT
    sum(salary) OVER w,
    avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);
</code>```

Body:
I have an oracle query in which I need use several analytic functions within the same window. How can I define a window once and then use it for each of these calls?

I.e. I wanna to write it like in PostGRESql:

SELECT
    sum(salary) OVER w,
    avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);

Forgot to mention, the goal is to avoid code duplication, not to speed up the query.

Body:
Starting from version 20c Oracle supports window clause syntax.

Enhanced Analytic Functions

The query_block clause of a SELECT statement now supports the window_clause, which implements the window clause of the SQL standard table expression as defined in the SQL:2011 standard.

SELECT

So your query will work perfectly fine without changes:

SELECT
    sum(salary) OVER w,
    avg(salary) OVER w
FROM empsalary
WINDOW w AS (PARTITION BY depname ORDER BY salary DESC);


问:
How can I dynamically replace portions of text with TextBoxes?

TL;DR:

I need to insert a TextBox into a PlaceHolder wherever I see a token like @token@, and splitting on @ won't cut it. How can I do this?

Setup:

I have a database-driven ASP.NET page with merge fields in several places. On one of the admin pages, I want to make the text in the merge fields editable by showing TextBoxes where the merge fields are. The rest of the text needs to stay non-editable.

The input looks like this:

"the quick brown fox @foo@ jumps over @bar@ the lazy @baz@ dog."

The merge fields here would be foo, bar, and baz. I have a Dictionary<string, string> with the value of the merge fields:

```<code>var Tokens = new Dictionary<string, string>
{
    { "foo", "john" },
    { "bar", "george" },
    //...etc...
};
</code>```

Goal:

For each of these text blocks, I have a PlaceHolder. What I'd like to do is dynamically insert a Label for each block of uneditable text, and a TextBox for each editable block. So the results of the above would be as if I had hard-coded something like this:

```<code><asp:Label   Text="the quick brown fox" />
<asp:TextBox ID="foo" Text="john" />
<asp:Label   Text="jumps over" />
<asp:TextBox ID="bar" Text="george" />
<asp:Label   Text="the lazy" />
...etc...
</code>```

Problem:

Matching the @token@ pattern is easy. The trick is adding the Labels and TextBoxes in the right places. There might be more than one token in a given input, so I have to separate it out into editable and non-editable text, while still keeping track of which merge variable each TextBox corresponds to. As it turns out, this is not as easy as it sounds. I could use regular expressions to convert the input string into HTML, replacing the @token@ pattern with <input> tags. However, that has a couple of problems:

I already have a ton of code for the dynamic-server-controls approach.

I only want to match specific tokens, so /@[a-zA-Z\d]+@/ isn't strict enough.

Previous Strategy:

Until now, I simply split the input string on @, then inserted a Label for each odd-numbered substring and a TextBox for each even substring. That worked fine, but the requirements are changing. @ symbols will now be allowed outside of a variable name, so the input string might look like:

blah blah@blah.com @foo@ blah

...in which case only foo would be a merge field.

Current Strategy:

I feel like I need to iterate through Tokens and build some sort of array of Labels and TextBoxes. The problem is that any number of tokens might be in the input, so once I split out TextBoxes for @foo@, I need to go through the text again for instances of @bar@. I think I need some sort of recursion for this, but I can't quite put my finger on it.

答:
you can do it with Regular expressions.
The Expression would look something like:

```<code>@([a-zA-Z0-9])+@
</code>```

this would mean that it matches for all patterns which start with @, contain at least one character a-z or A-Z or 0-9 and end with @

Regex.Match

Body:
TL;DR:

I need to insert a TextBox into a PlaceHolder wherever I see a token like @token@, and splitting on @ won't cut it. How can I do this?

Setup:

I have a database-driven ASP.NET page with merge fields in several places. On one of the admin pages, I want to make the text in the merge fields editable by showing TextBoxes where the merge fields are. The rest of the text needs to stay non-editable.

The input looks like this:

"the quick brown fox @foo@ jumps over @bar@ the lazy @baz@ dog."

The merge fields here would be foo, bar, and baz. I have a Dictionary<string, string> with the value of the merge fields:

var Tokens = new Dictionary<string, string>
{
    { "foo", "john" },
    { "bar", "george" },
    //...etc...
};

Goal:

For each of these text blocks, I have a PlaceHolder. What I'd like to do is dynamically insert a Label for each block of uneditable text, and a TextBox for each editable block. So the results of the above would be as if I had hard-coded something like this:

<asp:Label   Text="the quick brown fox" />
<asp:TextBox ID="foo" Text="john" />
<asp:Label   Text="jumps over" />
<asp:TextBox ID="bar" Text="george" />
<asp:Label   Text="the lazy" />
...etc...

Problem:

Matching the @token@ pattern is easy. The trick is adding the Labels and TextBoxes in the right places. There might be more than one token in a given input, so I have to separate it out into editable and non-editable text, while still keeping track of which merge variable each TextBox corresponds to. As it turns out, this is not as easy as it sounds. I could use regular expressions to convert the input string into HTML, replacing the @token@ pattern with <input> tags. However, that has a couple of problems:

I already have a ton of code for the dynamic-server-controls approach.

I only want to match specific tokens, so /@[a-zA-Z\d]+@/ isn't strict enough.

Previous Strategy:

Until now, I simply split the input string on @, then inserted a Label for each odd-numbered substring and a TextBox for each even substring. That worked fine, but the requirements are changing. @ symbols will now be allowed outside of a variable name, so the input string might look like:

blah blah@blah.com @foo@ blah

...in which case only foo would be a merge field.

Current Strategy:

I feel like I need to iterate through Tokens and build some sort of array of Labels and TextBoxes. The problem is that any number of tokens might be in the input, so once I split out TextBoxes for @foo@, I need to go through the text again for instances of @bar@. I think I need some sort of recursion for this, but I can't quite put my finger on it.

Body:
you can do it with Regular expressions.
The Expression would look something like:

@([a-zA-Z0-9])+@

this would mean that it matches for all patterns which start with @, contain at least one character a-z or A-Z or 0-9 and end with @

Regex.Match