问:
How can I best lay out these components in Swing?
What would be the best approach / LayoutManager for a JPanel that needed to display the components shown in the image?
(Note that the fields should resize horizontally when the size of the window is changed, but not the labels).

I'm currently trying (and struggling) to do it with a GridBagLayout.  Is this the correct approach or is there a better way?  Should I be trying to divide + conquer the seperate sections maybe?

Any thoughts or advice would be gratefully appreciated.  :-)

http://img261.imageshack.us/img261/2091/layouthb6.png

PS If you read this and there's no image, please bear with me whilst I fix it!

答: GridBagLayout is definitely the best choice for this. And NetBeans Matisse is probably the fastest way of achieving this. If you are using another IDE, just copy & paste the auto-generated code.</p>

OwnerDisplayName: cagcowboy

LastEditorDisplayName: John Topley

OwnerDisplayName: pek


来源: stackexchange

问:
Can't use quick watch wile debugin in if statement Visual Studio
The problem looks like this:

I have an if statements in my code.

```<code>if (tcd.TrescWartosc != null)
                    {
                        var document = new ISDocument();
                        document.DocContent = tcd.TrescWartosc;
                        int count = 0;
                        int count2 = 0;
                        count = count + 2;
                    }
</code>```

It's just a fragment of the code inside the statement and some variables that I've added to test my errors (count and count2)
The problem is that when i debug the project in this one "if" when i check any variable I'm getting 'don't exist in the current context' error. When I comment out the if fragment everything is ok. I've tried with if(true) and the problem remains so what could be the reason for this?? Pin to source also shows nothing...

答:
The problem was visual studio itself...Above I had another if with code and statement like

```<code> if (!tcd.Wyslano)
                    {
                    ...
                    ...
                    }
</code>```

I wanted to ommit that "if" so I've replaced  if (!tcd.Wyslano) with if(false) and Visual Studio had some problem with that...I've replaced it now with if (!tcd.Wyslano && false) and now it debugs ok so i thinks it was kind of VS bug...

ContentLicense: CC BY-SA 2.5

Body:
The problem looks like this:

I have an if statements in my code.

if (tcd.TrescWartosc != null)
                    {
                        var document = new ISDocument();
                        document.DocContent = tcd.TrescWartosc;
                        int count = 0;
                        int count2 = 0;
                        count = count + 2;
                    }

It's just a fragment of the code inside the statement and some variables that I've added to test my errors (count and count2)
The problem is that when i debug the project in this one "if" when i check any variable I'm getting 'don't exist in the current context' error. When I comment out the if fragment everything is ok. I've tried with if(true) and the problem remains so what could be the reason for this?? Pin to source also shows nothing...

Body:
The problem was visual studio itself...Above I had another if with code and statement like

 if (!tcd.Wyslano)
                    {
                    ...
                    ...
                    }

I wanted to ommit that "if" so I've replaced  if (!tcd.Wyslano) with if(false) and Visual Studio had some problem with that...I've replaced it now with if (!tcd.Wyslano && false) and now it debugs ok so i thinks it was kind of VS bug...


问:
ASP.NET WebApi with angular-cli
I have a pure ASP.NET WebApi project (MVC 5, not .NET Core), and I want to combine it with angular-cli. Angular-cli project is in a separate directory outside of the WebApi project. ng build command puts all scripts into WebApiProject/App.
I want to keep the WebApiProject as a pure WebApi (WebApiControllers only - without MVC controllers). Content, scripts and layout should be only in /App dirctory created by angular-cli.

Question: how to make it working when accessing http://localhost:5000 shows file from /app/index.html and all referenced scripts inside the /app are working.

The simple case:

```<code>WebApiProject(without MVC controllers)
--Controllers
----ValuesController
--web.config
--App
----index.html <script src="main.js" /> //src address cannot be changed, it is generated by angular-cli
----main.js
</code>```

答:
If you are serving the Web API from IIS it make sense that you also serve the Angular app from IIS.
You can add that using a separate MVC app, or add MVC controllers to your Web API app.

See detailed solution here: https://stackoverflow.com/a/43127291/3787891

Assaf

ContentLicense: CC BY-SA 3.0

Title: ASP.NET WebApi with angular-cli

Body:
I have a pure ASP.NET WebApi project (MVC 5, not .NET Core), and I want to combine it with angular-cli. Angular-cli project is in a separate directory outside of the WebApi project. ng build command puts all scripts into WebApiProject/App.
I want to keep the WebApiProject as a pure WebApi (WebApiControllers only - without MVC controllers). Content, scripts and layout should be only in /App dirctory created by angular-cli.

Question: how to make it working when accessing http://localhost:5000 shows file from /app/index.html and all referenced scripts inside the /app are working.

The simple case:

WebApiProject(without MVC controllers)
--Controllers
----ValuesController
--web.config
--App
----index.html


问:
How to find the format of a disk volume
I am updating a backup utility I have written and have on the Mac App store.

In a Macintosh Cocoa application, how do I find how a disk volume is formatted? The only official thing I find, is doing a GetResourceValue: for 'NSURLVolumeLocalizedFormatDescriptionKey', but that is language dependent.

My utility does not support volumes formatted for FAT32. My utility needs to do special handling for XSan drives.

答:
This question has been answered but I'll throw my 2 cents in...

```<code>/sbin/mount | grep acfs | awk '{print $3}'
</code>```

This outputs

```<code>/Volumes/XsanVolumeName1
/Volumes/XsanVolumeName2
</code>```

Title: How to find the format of a disk volume

Body:
This question has been answered but I'll throw my 2 cents in...

/sbin/mount | grep acfs | awk '{print $3}'

This outputs

/Volumes/XsanVolumeName1
/Volumes/XsanVolumeName2


问:
reverse vowels in string in c
I'm a beginner programmer. I was trying out the problem of reversing vowels in a string.

Ex: input: zabedfigu, output: zubidfega

When I run the following code, I get a runtime error. I've tried to change the conditions within incrementing the pointer pc1 upto only upto the middle index etc., but that either gives me a runtime error or doesn't give me the required output. I'd like some help on what to do to make my code work as well as any new way of solving the problem. TIA.

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

char* reverseVowels(char* str)
{
    char *pc1, *pc2;
    int i;
    pc1 = &str[0];
    for(i=0; str[i]!='\0';++i)
        ;
    pc2 = &str[i-1];

    while(pc1!=pc2)
    {
      if((*pc1=='a')||(*pc1=='e')||(*pc1=='i')||(*pc1=='o')||(*pc1=='u'))
      {
        while(pc2!=pc1)
        {
            if((*pc2=='a')||(*pc2=='e')||(*pc2=='i')||(*pc2=='o')||(*pc2=='u'))
            {
              char temp;
              temp = *pc1;
              *pc1 = *pc2;
              *pc2 = temp;
              ++pc2;
              break;
            }
            else
              ++pc2;
        }
        ++pc1;
      }
      else
        ++pc1;
    }
    //return str;
    return NULL;
}
int main()
{
    char string[20], *pstr;
    scanf("%s", string);
    //pstr = reverseVowels(string);
    //printf("%s", pstr);
    reverseVowels(string);
    printf("%s", string);
    return 0;
}
</code>```

答:
You have several answers and comments pointing out the fundamental flaw in your code — that you're incrementing pc2 instead of decrementing it.  However, I think your algorithm is more complicated than need be.  You could:

Subject at all times to pc1 < pc2:

If pc1 is not pointing at a vowel, increment it

If pc2 is not pointing at a vowel, decrement it

If the pointers are different, swap the vowels and adjust the pointers

With test code, and with the addition of an is_vowel() function which detects both upper-case and lower-case vowels, I ended up with:

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

static inline int is_vowel(int c)
{
    c = tolower(c);
    return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

static void reverse_vowels(char *string)
{
    char *p1 = string;
    char *p2 = p1 + strlen(p1);     // '\0' is not a vowel

    while (p1 < p2)
    {
        while (p1 < p2 && !is_vowel((unsigned char)*p1))
            p1++;
        while (p1 < p2 && !is_vowel((unsigned char)*p2))
            p2--;
        if (p1 != p2)
        {
            char c = *p1;
            *p1++ = *p2;
            *p2-- = c;
        }
    }
}

int main(void)
{
#ifdef INTERACTIVE
    char line[1024];
    while (fgets(line, sizeof(line), stdin) != NULL)
    {
        line[strcspn(line, "\n")] = '\0';
        printf("Input:  [%s]\n", line);
        reverse_vowels(line);
        printf("Output: [%s]\n", line);
    }
#else
    char strings[][40] =
    {
        "",
        "a",
        "b",
        "ab",
        "abe",
        "abeci",
        "nnnnummmmmmmmmmmmippppoqq",
        "AbleWasIEreISawElba",
        "A Man, A Plan, A Canal - Panama!"
    };
    enum { NUM_STRINGS = sizeof(strings) / sizeof(strings[0]) };

    for (int i = 0; i < NUM_STRINGS; i++)
    {
        printf("Input:  [%s]\n", strings[i]);
        reverse_vowels(strings[i]);
        printf("Output: [%s]\n", strings[i]);
    }
#endif /* INTERACTIVE */
    return 0;
}
</code>```

You can compile it with -DINTERACTIVE to give you an interactive test, or by default it gives a fixed set of tests.

Default output:

```<code>Input:  []
Output: []
Input:  [a]
Output: [a]
Input:  [b]
Output: [b]
Input:  [ab]
Output: [ab]
Input:  [abe]
Output: [eba]
Input:  [abeci]
Output: [ibeca]
Input:  [nnnnummmmmmmmmmmmippppoqq]
Output: [nnnnommmmmmmmmmmmippppuqq]
Input:  [AbleWasIEreISawElba]
Output: [ablEWasIerEISawelbA]
Input:  [A Man, A Plan, A Canal - Panama!]
Output: [a Man, a Plan, a CAnal - PAnamA!]
</code>```

Sample interactive session (my program was called rv61):

```<code>$ rv61

Input:  []
Output: []
a
Input:  [a]
Output: [a]
b
Input:  [b]
Output: [b]
ab
Input:  [ab]
Output: [ab]
ae
Input:  [ae]
Output: [ea]
abcde
Input:  [abcde]
Output: [ebcda]
ablewasiereisawelba
Input:  [ablewasiereisawelba]
Output: [ablewasiereisawelba]
palindromic nonsense
Input:  [palindromic nonsense]
Output: [pelendromic nonsinsa]
vwlsmssng
Input:  [vwlsmssng]
Output: [vwlsmssng]
AManAPlanACanal-Panama!
Input:  [AManAPlanACanal-Panama!]
Output: [aManaPlanaCAnal-PAnamA!]
  a big and complex sentence with multiple words of a number of lengths and so on
Input:  [  a big and complex sentence with multiple words of a number of lengths and so on  ]
Output: [  o bog and cemplox sentunca woth moltepli wurds if e nember ef longths and si an  ]
$
</code>```

Note that the testing tests a number of degenerate cases — an empty string, a string with no vowels, a string with one vowel, etc.  The palindromic tests benefit from supporting mixed case — it's hard to spot that vowels have been swapped if they're all lower case and the text is a palindrome.

Another test that could be applied is to reverse the vowels twice; the output should be the same as the input.  Conservation tests can be important.  (If you had a sort which didn't preserve all the elements in the array but added random new ones and/or dropped initial ones, you wouldn't be happy.  But that's a topic for another day.)

Having a simple test harness along the lines shown can be helpful for library functions.  Many of my library functions have a #ifdef TEST … #endif at the end to allow them to be tested for sanity.  The best tests verify that the result is what is expected; these ones are lazy and leave it to visual inspection to validate the output.  If it was a library function, there'd be a header to declare the function which would be #included in the source, and the function would not be static.  (My default compilation options require either a declaration of the function before it is defined, or the function must be static.  I make functions static in sample code like this since there's no other file referencing the function, so there's no need for a header to declare the function, and only headers should declare externally visible functions.)

Note too that the is_vowel name is carefully chosen to avoid the reserved names in the C standard:

Function names that begin with either is or to, and a lowercase letter may be added to the declarations in the <ctype.h> header.

Using isVowel() would have been OK too; using isvowel() would be using a reserved name.

Bill Woodger commented:

Why the comment about '\0' not being a vowel? …

With the code as shown, after the initialization of p2, it is true that *p2 == '\0'.  The observation the '\0' is not a vowel matters if the string is non-empty because if it matched the is_vowel() predicate, the null byte could be moved to some point earlier in the string, truncating it.

Suppose the function was reverse_controls() instead of reverse_vowels() and the test used iscntrl() instead of is_vowel(). Then the code would have to handle it differently for a non-zero length string because the null byte would be reported as a control character and that would send things awry — it would be swapped with the first other control character (if there was another) in the string, truncating the string.  That is not what's intended.

Title: reverse vowels in string in c

Body:
I'm a beginner programmer. I was trying out the problem of reversing vowels in a string.

Ex: input: zabedfigu, output: zubidfega

When I run the following code, I get a runtime error. I've tried to change the conditions within incrementing the pointer pc1 upto only upto the middle index etc., but that either gives me a runtime error or doesn't give me the required output. I'd like some help on what to do to make my code work as well as any new way of solving the problem. TIA.

#include<stdio.h>

char* reverseVowels(char* str)
{
    char *pc1, *pc2;
    int i;
    pc1 = &str[0];
    for(i=0; str[i]!='\0';++i)
        ;
    pc2 = &str[i-1];

    while(pc1!=pc2)
    {
      if((*pc1=='a')||(*pc1=='e')||(*pc1=='i')||(*pc1=='o')||(*pc1=='u'))
      {
        while(pc2!=pc1)
        {
            if((*pc2=='a')||(*pc2=='e')||(*pc2=='i')||(*pc2=='o')||(*pc2=='u'))
            {
              char temp;
              temp = *pc1;
              *pc1 = *pc2;
              *pc2 = temp;
              ++pc2;
              break;
            }
            else
              ++pc2;
        }
        ++pc1;
      }
      else
        ++pc1;
    }
    //return str;
    return NULL;
}
int main()
{
    char string[20], *pstr;
    scanf("%s", string);
    //pstr = reverseVowels(string);
    //printf("%s", pstr);
    reverseVowels(string);
    printf("%s", string);
    return 0;
}

Body:
You have several answers and comments pointing out the fundamental flaw in your code — that you're incrementing pc2 instead of decrementing it.  However, I think your algorithm is more complicated than need be.  You could:

Subject at all times to pc1 < pc2:

If pc1 is not pointing at a vowel, increment it

If pc2 is not pointing at a vowel, decrement it

If the pointers are different, swap the vowels and adjust the pointers

With test code, and with the addition of an is_vowel() function which detects both upper-case and lower-case vowels, I ended up with:

#include <ctype.h>
#include <stdio.h>
#include <string.h>

static inline int is_vowel(int c)
{
    c = tolower(c);
    return (c == 'a' || c == 'e' || c == 'i' || c == 'o' || c == 'u');
}

static void reverse_vowels(char *string)
{
    char *p1 = string;
    char *p2 = p1 + strlen(p1);     // '\0' is not a vowel

    while (p1 < p2)
    {
        while (p1 < p2 && !is_vowel((unsigned char)*p1))
            p1++;
        while (p1 < p2 && !is_vowel((unsigned char)*p2))
            p2--;
        if (p1 != p2)
        {
            char c = *p1;
            *p1++ = *p2;
            *p2-- = c;
        }
    }
}

int main(void)
{
#ifdef INTERACTIVE
    char line[1024];
    while (fgets(line, sizeof(line), stdin) != NULL)
    {
        line[strcspn(line, "\n")] = '\0';
        printf("Input:  [%s]\n", line);
        reverse_vowels(line);
        printf("Output: [%s]\n", line);
    }
#else
    char strings[][40] =
    {
        "",
        "a",
        "b",
        "ab",
        "abe",
        "abeci",
        "nnnnummmmmmmmmmmmippppoqq",
        "AbleWasIEreISawElba",
        "A Man, A Plan, A Canal - Panama!"
    };
    enum { NUM_STRINGS = sizeof(strings) / sizeof(strings[0]) };

    for (int i = 0; i < NUM_STRINGS; i++)
    {
        printf("Input:  [%s]\n", strings[i]);
        reverse_vowels(strings[i]);
        printf("Output: [%s]\n", strings[i]);
    }
#endif /* INTERACTIVE */
    return 0;
}

You can compile it with -DINTERACTIVE to give you an interactive test, or by default it gives a fixed set of tests.

Default output:

Input:  []
Output: []
Input:  [a]
Output: [a]
Input:  [b]
Output: [b]
Input:  [ab]
Output: [ab]
Input:  [abe]
Output: [eba]
Input:  [abeci]
Output: [ibeca]
Input:  [nnnnummmmmmmmmmmmippppoqq]
Output: [nnnnommmmmmmmmmmmippppuqq]
Input:  [AbleWasIEreISawElba]
Output: [ablEWasIerEISawelbA]
Input:  [A Man, A Plan, A Canal - Panama!]
Output: [a Man, a Plan, a CAnal - PAnamA!]

Sample interactive session (my program was called rv61):

$ rv61

Input:  []
Output: []
a
Input:  [a]
Output: [a]
b
Input:  [b]
Output: [b]
ab
Input:  [ab]
Output: [ab]
ae
Input:  [ae]
Output: [ea]
abcde
Input:  [abcde]
Output: [ebcda]
ablewasiereisawelba
Input:  [ablewasiereisawelba]
Output: [ablewasiereisawelba]
palindromic nonsense
Input:  [palindromic nonsense]
Output: [pelendromic nonsinsa]
vwlsmssng
Input:  [vwlsmssng]
Output: [vwlsmssng]
AManAPlanACanal-Panama!
Input:  [AManAPlanACanal-Panama!]
Output: [aManaPlanaCAnal-PAnamA!]
  a big and complex sentence with multiple words of a number of lengths and so on
Input:  [  a big and complex sentence with multiple words of a number of lengths and so on  ]
Output: [  o bog and cemplox sentunca woth moltepli wurds if e nember ef longths and si an  ]
$

Note that the testing tests a number of degenerate cases — an empty string, a string with no vowels, a string with one vowel, etc.  The palindromic tests benefit from supporting mixed case — it's hard to spot that vowels have been swapped if they're all lower case and the text is a palindrome.

Another test that could be applied is to reverse the vowels twice; the output should be the same as the input.  Conservation tests can be important.  (If you had a sort which didn't preserve all the elements in the array but added random new ones and/or dropped initial ones, you wouldn't be happy.  But that's a topic for another day.)

Having a simple test harness along the lines shown can be helpful for library functions.  Many of my library functions have a #ifdef TEST … #endif at the end to allow them to be tested for sanity.  The best tests verify that the result is what is expected; these ones are lazy and leave it to visual inspection to validate the output.  If it was a library function, there'd be a header to declare the function which would be #included in the source, and the function would not be static.  (My default compilation options require either a declaration of the function before it is defined, or the function must be static.  I make functions static in sample code like this since there's no other file referencing the function, so there's no need for a header to declare the function, and only headers should declare externally visible functions.)

Note too that the is_vowel name is carefully chosen to avoid the reserved names in the C standard:

Function names that begin with either is or to, and a lowercase letter may be added to the declarations in the <ctype.h> header.

Using isVowel() would have been OK too; using isvowel() would be using a reserved name.

Bill Woodger commented:

Why the comment about '\0' not being a vowel? …

With the code as shown, after the initialization of p2, it is true that *p2 == '\0'.  The observation the '\0' is not a vowel matters if the string is non-empty because if it matched the is_vowel() predicate, the null byte could be moved to some point earlier in the string, truncating it.

Suppose the function was reverse_controls() instead of reverse_vowels() and the test used iscntrl() instead of is_vowel(). Then the code would have to handle it differently for a non-zero length string because the null byte would be reported as a control character and that would send things awry — it would be swapped with the first other control character (if there was another) in the string, truncating the string.  That is not what's intended.


问:
getView() not called even when getCount() has results
Sorry for my english, not my first language.
Im creating an app in Android and I have a issue:

I have a TabBar with 2 fragments (1 - ProductFragment and 2 - CartFragment), in second Fragment (CartFragment) I have a ListView and that ListView is initial null.

CartFragment Layout:

```<code><FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:padding="15dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

               <ListView
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:id="@+id/lancarvenda_carrinho_lvwresultado"
                   android:orientation="vertical" />

    </LinearLayout>
</FrameLayout>
</code>```

In ProductFragment I have a button with onclick, that onclick Intents another activity and in that activity I add values in my public Custom List:

```<code>public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();
</code>```

When I done with adding values that I need, I close that activity and return to TabBar and expects that ListView has been populated.

The method that populate my public list:

```<code>private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();

                    for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
                        PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
                        sCarrinhoAuxiliar.add(sItem);
                    }

                    LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
                            sCarrinhoAuxiliar);
                    fCarrinhoResultado.setAdapter(sAdaptador);
                    sAdaptador.notifyDataSetChanged();

                    Object oi = fCarrinhoResultado.getCount();
                    oi.toString();

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }, new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            byte[] sBytesResposta = error.networkResponse.data;
            String sTexto = new String(sBytesResposta);
            Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
        }
    })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError
        {
            Map<String, String> sHeaders = new HashMap<>();
            sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
            return sHeaders;
        }

        @Override
        public byte[] getBody() throws AuthFailureError
        {
            return new Gson().toJson(sCorpoBusca).getBytes();
        }

        @Override
        public String getBodyContentType()
        {
            return "application/json";
        }
    };

    sQueue.add(sRequest);
}
</code>```

ListView Adapter:

```<code>public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{

private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;

public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
    mContext = context;
    mDataSource = items;
}

@Override
public int getCount() {
    return mDataSource.size();
}

@Override
public Object getItem(int position) {
    return mDataSource.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    try
    {
        LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);

        PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);

        TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
        descricao.setText(sItem.getDescricao());

        TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
        preco.setText(String.valueOf(sItem.getPreco()));

        EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
        quantidade.setText("1");

        return sView;
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
}
</code>```

My layout of row:

```<code><RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/lancarvenda_carrinho_item_imvFoto"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/circulo_foto2"
            app:border_color="#898989"
            app:border_width="2dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="10dp">

            <TextView
                android:id="@+id/lancarvenda_carrinho_item_txtdescricao"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="Relogio"
                android:textSize="20dp"
                android:textStyle="bold"
                android:layout_marginRight="8dp"
                android:lines="2"
                android:minLines="2"
                android:singleLine="false"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">

                    <TextView
                        android:id="@+id/lancarvenda_carrinho_item_txvpreco"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="8dp"
                        android:text="R$ 399,89"
                        android:textColor="#1ba39c"
                        android:textSize="20dp"
                        android:layout_marginRight="70dp"/>

                    <EditText
                        android:id="@+id/lancarvenda_carrinho_item_etquantidade"
                        android:layout_width="50dp"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:backgroundTint="#9a9b9c"
                        android:hint="0"
                        android:textColor="#2a2d2e"
                        android:layout_marginRight="8dp"/>

                </RelativeLayout>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>
</code>```

In debug mode, when code pass in getCount in Adapter, I have size more than 1 and my list still not show! Even if I close TabBar and reopen and set adapter (with values) on onCreate method.
What can I do to my ListView show?

EDIT
I inflate listview on onCreate:

```<code>    super.onCreate(savedInstanceState);

    LayoutInflater sInflater = getActivity().getLayoutInflater();
    View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);

    fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);
</code>```

答:
Try making your list a member of the class instead of a local variable</p>

```<code>private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {

        // Make cart list a private data member so it doesn't loose scope //
        List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;

        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    sCarrinhoAuxiliar = new ArrayList<>();
                    ...
                }
                ...
             }
             ...
         }
         ...
     }
     ...
}
</code>```

Body:
Sorry for my english, not my first language.
Im creating an app in Android and I have a issue:

I have a TabBar with 2 fragments (1 - ProductFragment and 2 - CartFragment), in second Fragment (CartFragment) I have a ListView and that ListView is initial null.

CartFragment Layout:

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:app="http://schemas.android.com/apk/res-auto"
             xmlns:tools="http://schemas.android.com/tools"
             android:layout_width="match_parent"
             android:layout_height="match_parent"
             android:padding="15dp">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical">

               <ListView
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:id="@+id/lancarvenda_carrinho_lvwresultado"
                   android:orientation="vertical" />

    </LinearLayout>
</FrameLayout>

In ProductFragment I have a button with onclick, that onclick Intents another activity and in that activity I add values in my public Custom List:

public static List<PesquisarProdutoResponse> Carrinho = new ArrayList<>();

When I done with adding values that I need, I close that activity and return to TabBar and expects that ListView has been populated.

The method that populate my public list:

private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {
        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar = new ArrayList<>();

                    for (int i = 0; i < Variaveis.Carrinho.size(); i++) {
                        PesquisarProdutoObjetoRetorno sItem = Variaveis.Carrinho.get(i).getDadosProduto();
                        sCarrinhoAuxiliar.add(sItem);
                    }

                    LancarVendaCarrinhoListViewAdapter sAdaptador = new LancarVendaCarrinhoListViewAdapter(getActivity(),
                            sCarrinhoAuxiliar);
                    fCarrinhoResultado.setAdapter(sAdaptador);
                    sAdaptador.notifyDataSetChanged();

                    Object oi = fCarrinhoResultado.getCount();
                    oi.toString();

                }
                catch (Exception e)
                {
                    e.printStackTrace();
                }
            }
        }
    }, new Response.ErrorListener()
    {
        @Override
        public void onErrorResponse(VolleyError error)
        {
            byte[] sBytesResposta = error.networkResponse.data;
            String sTexto = new String(sBytesResposta);
            Mensagem.ExibirAlert(getActivity(), String.valueOf(error.networkResponse.statusCode));
        }
    })
    {
        @Override
        public Map<String, String> getHeaders() throws AuthFailureError
        {
            Map<String, String> sHeaders = new HashMap<>();
            sHeaders.put("Authorization", "Bearer " + Variaveis.ApiToken);
            return sHeaders;
        }

        @Override
        public byte[] getBody() throws AuthFailureError
        {
            return new Gson().toJson(sCorpoBusca).getBytes();
        }

        @Override
        public String getBodyContentType()
        {
            return "application/json";
        }
    };

    sQueue.add(sRequest);
}

ListView Adapter:

public class LancarVendaCarrinhoListViewAdapter extends BaseAdapter
{

private Context mContext;
//private LayoutInflater mInflater;
private List<PesquisarProdutoObjetoRetorno> mDataSource;

public LancarVendaCarrinhoListViewAdapter(Context context, List<PesquisarProdutoObjetoRetorno> items)
{
    mContext = context;
    mDataSource = items;
}

@Override
public int getCount() {
    return mDataSource.size();
}

@Override
public Object getItem(int position) {
    return mDataSource.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent)
{
    try
    {
        LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View sView = mInflater.inflate(R.layout.activity_lancarvenda_carrinho_list_view_item, parent, false);

        PesquisarProdutoObjetoRetorno sItem = (PesquisarProdutoObjetoRetorno) getItem(position);

        TextView descricao = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txtdescricao);
        descricao.setText(sItem.getDescricao());

        TextView preco = (TextView)sView.findViewById(R.id.lancarvenda_carrinho_item_txvpreco);
        preco.setText(String.valueOf(sItem.getPreco()));

        EditText quantidade = (EditText)sView.findViewById(R.id.lancarvenda_carrinho_item_etquantidade);
        quantidade.setText("1");

        return sView;
    }
    catch (Exception e)
    {
        e.printStackTrace();
        return null;
    }
}
}

My layout of row:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="horizontal">

        <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
            android:id="@+id/lancarvenda_carrinho_item_imvFoto"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center_horizontal"
            android:background="@drawable/circulo_foto2"
            app:border_color="#898989"
            app:border_width="2dp" />

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:layout_marginLeft="10dp">

            <TextView
                android:id="@+id/lancarvenda_carrinho_item_txtdescricao"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content"
                android:layout_centerHorizontal="true"
                android:text="Relogio"
                android:textSize="20dp"
                android:textStyle="bold"
                android:layout_marginRight="8dp"
                android:lines="2"
                android:minLines="2"
                android:singleLine="false"/>

            <LinearLayout
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="horizontal">

                <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                    android:layout_width="fill_parent"
                    android:layout_height="fill_parent">

                    <TextView
                        android:id="@+id/lancarvenda_carrinho_item_txvpreco"
                        android:layout_width="fill_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentLeft="true"
                        android:layout_centerHorizontal="true"
                        android:layout_marginTop="8dp"
                        android:text="R$ 399,89"
                        android:textColor="#1ba39c"
                        android:textSize="20dp"
                        android:layout_marginRight="70dp"/>

                    <EditText
                        android:id="@+id/lancarvenda_carrinho_item_etquantidade"
                        android:layout_width="50dp"
                        android:layout_height="wrap_content"
                        android:layout_alignParentRight="true"
                        android:backgroundTint="#9a9b9c"
                        android:hint="0"
                        android:textColor="#2a2d2e"
                        android:layout_marginRight="8dp"/>

                </RelativeLayout>

            </LinearLayout>
        </LinearLayout>

    </LinearLayout>

</RelativeLayout>

In debug mode, when code pass in getCount in Adapter, I have size more than 1 and my list still not show! Even if I close TabBar and reopen and set adapter (with values) on onCreate method.
What can I do to my ListView show?

EDIT
I inflate listview on onCreate:

    super.onCreate(savedInstanceState);

    LayoutInflater sInflater = getActivity().getLayoutInflater();
    View sView = sInflater.inflate(R.layout.fragment_lancarvenda_carrinho, null);

    fCarrinhoResultado = (ListView) sView.findViewById(R.id.lancarvenda_carrinho_lvwresultado);

Body:
Try making your list a member of the class instead of a local variable

private void PesquisarProduto()
{
    RequestQueue sQueue = Volley.newRequestQueue(getActivity());
    String sEnderecoBase = "http://www.my-url";

    StringRequest sRequest = new StringRequest(Request.Method.POST, sEnderecoBase, new Response.Listener<String>() {

        // Make cart list a private data member so it doesn't loose scope //
        List<PesquisarProdutoObjetoRetorno> sCarrinhoAuxiliar;

        @Override
        public void onResponse(String response)
        {
            PesquisarProdutoResponse sResultado = new Gson().fromJson((String) response, PesquisarProdutoResponse.class);
            if (sResultado.getCodigoRetorno() != 0)
            {
                //lastText = "Produto não encontrado";
                //barcodeView.setStatusText("Produto não encontrado");
            }
            else
            {

                Variaveis.Carrinho.add(sResultado);

                try {
                    sCarrinhoAuxiliar = new ArrayList<>();
                    ...
                }
                ...
             }
             ...
         }
         ...
     }
     ...
}


问:
how to support incognito/private mode in wkwebview/uiwebview
I am working on a incongnito browser.I am using wkwebview when I clear all the cookies I can see that popular search engine like google remembers the searches that has been made.

I tried cleaning all the cookies in NSHTTPCookieStorage and resetcookies using NSURLSession but its still not working.

答:
Set nonpersistentdatastore for wkwebsitedatastore for wkwebviewconfiguration for wkwebview

Set  NSURLrequestreloadcacheignoringlocalandremotecachedata for NSURlrequest in uiwebview

Reference

Creating a non-tracking in-app web browser


问:
SQL Server Convert case for letter that comes after - (hyphen)
I need to convert case for letter that comes after hyphen (-) in all values of a column

like

```<code>Aaa - aaa
Bbbdd - bbbdd
Ccc123 - ccc123
</code>```

to

```<code>Aaa - Aaa
Bbbdd - Bbbdd
Ccc123 - Ccc123
</code>```

Please help!

答:
Using stuff():

```<code>declare @str varchar(64) = 'Aaa - aaa'

select stuff(@str,charindex('-',@str)+2,1,upper(substring(@str,charindex('-',@str)+2,1)))
</code>```

rextester demo: http://rextester.com/CCIZDT37194

Returns: Aaa - Aaa

Body:
I need to convert case for letter that comes after hyphen (-) in all values of a column

like

Aaa - aaa
Bbbdd - bbbdd
Ccc123 - ccc123

to

Aaa - Aaa
Bbbdd - Bbbdd
Ccc123 - Ccc123

Please help!

Body:
Using stuff():

declare @str varchar(64) = 'Aaa - aaa'

select stuff(@str,charindex('-',@str)+2,1,upper(substring(@str,charindex('-',@str)+2,1)))

rextester demo: http://rextester.com/CCIZDT37194

Returns: Aaa - Aaa


问:
Linked Lists Insert
I'm struggling with this example of linked lists, I am not able to change any of the code in the second code block below, however I can freely edit this function. Due to this I believe the use of nodes will not work as I cannot add them anywhere. Any ideas?

```<code>// Insert the given string into the linked-list such that the
// entries in the linked-list are in alphabetical order
bool List::insert(const char *string_p)
{
    // Please write the list insert function
  return SUCCESS;
}
</code>```

Code that cannot be modified is below

```<code>class ListEntry
{
  public:
    explicit     ListEntry();
    explicit     ListEntry(const char *string_p);
                 ~ListEntry();
    string       getData();
    void         setData(const char* string_p);
    void         setData(string string);
    ListEntry   *getNext();
    ListEntry   *getPrevious();
    ListEntry   *prev_p;   // pointer to previous entry in the linked-list
    ListEntry   *next_p;   // pointer to next entry in the linked-list

  private:
    string          data;      // entry's string
};

// Represents the linked-list object
class List
{
  public:
    List();
    ~List();

    bool printForward();
    bool printReverse();
    bool insert(const char *string_p);

  private:
    int        entryCount;  // number of entries present in the linked-list
    ListEntry *head_p;      // pointer to the first entry in the list
    ListEntry *tail_p;      // pointer to the last entry in the list
};

// ListEntry constructor
ListEntry::ListEntry()
{
  this->prev_p = NULL;
  this->next_p = NULL;
  return;
}

// ListEntry constructor
ListEntry::ListEntry(const char *string_p)
{
  this->data   = string_p;
  this->prev_p = NULL;
  this->next_p = NULL;
  return;
}

// List entry destructor
ListEntry::~ListEntry()
{
  return;
}

// Return the stored string object
string ListEntry::getData()
{
  return this->data;
}

// Set the internal string data from a char*
void ListEntry::setData(const char* string_p)
{
  this->data = string_p;
}

// Set the internal string data from a string
void ListEntry::setData(string string)
{
  this->data = string;
}

// Returns reference to the next entry in the list
ListEntry *ListEntry::getNext()
{
  return this->next_p;
}

// Returns reference to the previous entry in the list
ListEntry *ListEntry::getPrevious()
{
  return this->prev_p;
}

// List constructor
List::List()
{
  this->entryCount = 0;
  this->head_p     = NULL;
  this->tail_p     = NULL;
}

// List destructor
List::~List()
{
  // Delete all entries in the list
  ListEntry *entry_p   = this->head_p;
  ListEntry *current_p = this->head_p;

  while (entry_p != NULL)
  {
    current_p = entry_p;
    entry_p = entry_p->getNext();
    delete current_p;
  }
 }

// Output linked list in order from head to tail
// printing out the string data from each list entry
bool List::printForward()
{
  ListEntry *entry_p = this->head_p;
  int count = 0;

  cout << "FORWARD: " << this->entryCount << " entries\n";
  while (entry_p != NULL)
  {
    cout << entry_p->getData() << " ";

    if (++count % 5 == 0 || entry_p == this->tail_p)
    {
      cout << endl;
    }

    entry_p = entry_p->getNext();
  }

  return SUCCESS;
}

// Output linked list in reverse order from tail to head
// printing out the string data from each list entry
bool List::printReverse()
{
  ListEntry *entry_p = this->tail_p;
  int count = 0;

  cout << "REVERSE: " << this->entryCount << " entries\n";
  while (entry_p != NULL)
  {
    cout << entry_p->getData() << " ";

    if (++count % 5 == 0 || entry_p == this->head_p)
    {
      cout << endl;
    }

    entry_p = entry_p->getPrevious();
  }

  return SUCCESS;
}
</code>```

答:
So you have most of the hard stuff out of the way.  What you have to do is complete the insert function witch has 2 special cases.

1) When head_p is null (list is empty)
2) When head_p is not null (list is not empty)

Using this in the insert method you take the const char *string_p you are given and create a ListEntry from it.  From there you insert the created ListEntry into the list.

If head_p is null then you are basically creating the list and will need to set head and end pointers to the new ListEntry.  If the list isn't empty you have to add it to the end.  This requires the update of a the prev_p and next_p pointers in a ListEntry (leaving this as an exercise for you).

Title: Linked Lists Insert

Body:
I'm struggling with this example of linked lists, I am not able to change any of the code in the second code block below, however I can freely edit this function. Due to this I believe the use of nodes will not work as I cannot add them anywhere. Any ideas?

// Insert the given string into the linked-list such that the
// entries in the linked-list are in alphabetical order
bool List::insert(const char *string_p)
{
    // Please write the list insert function
  return SUCCESS;
}

Code that cannot be modified is below

class ListEntry
{
  public:
    explicit     ListEntry();
    explicit     ListEntry(const char *string_p);
                 ~ListEntry();
    string       getData();
    void         setData(const char* string_p);
    void         setData(string string);
    ListEntry   *getNext();
    ListEntry   *getPrevious();
    ListEntry   *prev_p;   // pointer to previous entry in the linked-list
    ListEntry   *next_p;   // pointer to next entry in the linked-list

  private:
    string          data;      // entry's string
};

// Represents the linked-list object
class List
{
  public:
    List();
    ~List();

    bool printForward();
    bool printReverse();
    bool insert(const char *string_p);

  private:
    int        entryCount;  // number of entries present in the linked-list
    ListEntry *head_p;      // pointer to the first entry in the list
    ListEntry *tail_p;      // pointer to the last entry in the list
};

// ListEntry constructor
ListEntry::ListEntry()
{
  this->prev_p = NULL;
  this->next_p = NULL;
  return;
}

// ListEntry constructor
ListEntry::ListEntry(const char *string_p)
{
  this->data   = string_p;
  this->prev_p = NULL;
  this->next_p = NULL;
  return;
}

// List entry destructor
ListEntry::~ListEntry()
{
  return;
}

// Return the stored string object
string ListEntry::getData()
{
  return this->data;
}

// Set the internal string data from a char*
void ListEntry::setData(const char* string_p)
{
  this->data = string_p;
}

// Set the internal string data from a string
void ListEntry::setData(string string)
{
  this->data = string;
}

// Returns reference to the next entry in the list
ListEntry *ListEntry::getNext()
{
  return this->next_p;
}

// Returns reference to the previous entry in the list
ListEntry *ListEntry::getPrevious()
{
  return this->prev_p;
}

// List constructor
List::List()
{
  this->entryCount = 0;
  this->head_p     = NULL;
  this->tail_p     = NULL;
}

// List destructor
List::~List()
{
  // Delete all entries in the list
  ListEntry *entry_p   = this->head_p;
  ListEntry *current_p = this->head_p;

  while (entry_p != NULL)
  {
    current_p = entry_p;
    entry_p = entry_p->getNext();
    delete current_p;
  }
 }

// Output linked list in order from head to tail
// printing out the string data from each list entry
bool List::printForward()
{
  ListEntry *entry_p = this->head_p;
  int count = 0;

  cout << "FORWARD: " << this->entryCount << " entries\n";
  while (entry_p != NULL)
  {
    cout << entry_p->getData() << " ";

    if (++count % 5 == 0 || entry_p == this->tail_p)
    {
      cout << endl;
    }

    entry_p = entry_p->getNext();
  }

  return SUCCESS;
}

// Output linked list in reverse order from tail to head
// printing out the string data from each list entry
bool List::printReverse()
{
  ListEntry *entry_p = this->tail_p;
  int count = 0;

  cout << "REVERSE: " << this->entryCount << " entries\n";
  while (entry_p != NULL)
  {
    cout << entry_p->getData() << " ";

    if (++count % 5 == 0 || entry_p == this->head_p)
    {
      cout << endl;
    }

    entry_p = entry_p->getPrevious();
  }

  return SUCCESS;
}


问:
VBA code for comparing first column of multiple spreadsheet with mastersheet
I have VBA code for comparing first column and highlight the cell in first column of sheet2 which is not there in sheet1.

I am new to VBA and not good in coding part and need this to work in a excel sheet which has multiple spreadsheet(This may vary from 5 to 10).
sheet1 is the master sheet and other sheet should be compared with the master sheet and highlight the cell which is not present in master sheet.

```<code>    Public Sub CompareSheets()

    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim cell As Range, rng As Range

    Set ws1 = Worksheets("Sheet1")
    Set ws2 = Worksheets("Sheet2")
    Set rng = ws1.Range("A1:A20")
    For Each cell In rng
        Celladdress = cell.Address
        If cell <> ws2.Range(Celladdress) Then
           cell.Interior.Color = vbYellow
           ws2.Range(Celladdress).Interior.Color = vbYellow
        End If
     Next cell
   End Sub
</code>```

答:
This code avoids a row-by-row comparison (per your comments) and looks for each value in column A of Sheet2, Sheet3, Sheet4, etc to be found somewhere in column A of Sheet1. It also locates rows that are greater than the total number of rows with values in Sheet1.

This does not force the cells to vbYellow. Instead, it uses conditional formatting to show vbYellow on non-matching cells. These can be filtered for just as forced vbYellow cells can. The benefit here is that once a value has been corrected (a match to Sheet1!A:A is made), the highlight will be auto-magically removed.

```<code>Option Explicit

Sub CompareSheets()
    Dim lrw1 As Long, lrwn As Long, w As Long

    'get the last row of values in master sheet
    With Worksheets(1)
        lrw1 = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    'the first worksheet (e.g. worksheets(1) ) is the 'master sheet' so we start at 2
    For w = 2 To Worksheets.Count
        With Worksheets(w)
            lrwn = .Cells(.Rows.Count, "A").End(xlUp).Row
            With .Range(.Cells(1, "A"), .Cells(Application.Max(lrwn, lrwn), "A"))
                .FormatConditions.Delete
                With .FormatConditions.Add(Type:=xlExpression, _
                        Formula1:="=OR(ROW()>" & lrw1 & ", ISNA(MATCH($A1, " & Worksheets(1).Columns("A").Address(external:=True) & ", 0)))")
                    With .Interior
                        .PatternColorIndex = xlAutomatic
                        .Color = vbYellow
                    End With
                    .StopIfTrue = True
                End With
            End With
        End With
    Next w

End Sub
</code>```

FWIW, I found your narrative a bit confusing. It either contradicted the supplied code or contradicted itself. The logic behind this proposed solution comes largely from your comments.

Body:
I have VBA code for comparing first column and highlight the cell in first column of sheet2 which is not there in sheet1.

I am new to VBA and not good in coding part and need this to work in a excel sheet which has multiple spreadsheet(This may vary from 5 to 10).
sheet1 is the master sheet and other sheet should be compared with the master sheet and highlight the cell which is not present in master sheet.

    Public Sub CompareSheets()

    Dim ws1 As Worksheet, ws2 As Worksheet
    Dim cell As Range, rng As Range

    Set ws1 = Worksheets("Sheet1")
    Set ws2 = Worksheets("Sheet2")
    Set rng = ws1.Range("A1:A20")
    For Each cell In rng
        Celladdress = cell.Address
        If cell <> ws2.Range(Celladdress) Then
           cell.Interior.Color = vbYellow
           ws2.Range(Celladdress).Interior.Color = vbYellow
        End If
     Next cell
   End Sub

Body:
This code avoids a row-by-row comparison (per your comments) and looks for each value in column A of Sheet2, Sheet3, Sheet4, etc to be found somewhere in column A of Sheet1. It also locates rows that are greater than the total number of rows with values in Sheet1.

This does not force the cells to vbYellow. Instead, it uses conditional formatting to show vbYellow on non-matching cells. These can be filtered for just as forced vbYellow cells can. The benefit here is that once a value has been corrected (a match to Sheet1!A:A is made), the highlight will be auto-magically removed.

Option Explicit

Sub CompareSheets()
    Dim lrw1 As Long, lrwn As Long, w As Long

    'get the last row of values in master sheet
    With Worksheets(1)
        lrw1 = .Cells(.Rows.Count, "A").End(xlUp).Row
    End With

    'the first worksheet (e.g. worksheets(1) ) is the 'master sheet' so we start at 2
    For w = 2 To Worksheets.Count
        With Worksheets(w)
            lrwn = .Cells(.Rows.Count, "A").End(xlUp).Row
            With .Range(.Cells(1, "A"), .Cells(Application.Max(lrwn, lrwn), "A"))
                .FormatConditions.Delete
                With .FormatConditions.Add(Type:=xlExpression, _
                        Formula1:="=OR(ROW()>" & lrw1 & ", ISNA(MATCH($A1, " & Worksheets(1).Columns("A").Address(external:=True) & ", 0)))")
                    With .Interior
                        .PatternColorIndex = xlAutomatic
                        .Color = vbYellow
                    End With
                    .StopIfTrue = True
                End With
            End With
        End With
    Next w

End Sub

FWIW, I found your narrative a bit confusing. It either contradicted the supplied code or contradicted itself. The logic behind this proposed solution comes largely from your comments.


问:
ARB Pleace holders not working
I'm making a localization using  ARB google's API but actually the place holder is not working i spent 5 hours to solve this issue with no luck

```<code>arb.register(
"login",
{
"title": "Login",
"subtitle": "to your account",
"MSG_BODY_TEST": "This is a test.",
"email": "Email {0}",
"@email": {
 "placeholders": {
   "0": {
      "example": "$123.45",
      "description": "cost presented with currency symbol"
   }
   }
},
"MSG_CURR_LOCALE": "...and the selected language is \"{currentLocale}\"."

}
</code>```

);

```<code>    arb.register(
"login:ar",
{
"title": "الدخول",
"subtitle": "الى حسابك",
"email": "البريد الاكتروني {0}",
"@email": {
 "placeholders": {
   "0": {
      "example": "$123.45",
      "description": "cost presented with currency symbol"
         }
         }
            },
    "MSG_CURR_LOCALE": "...and the selected language is \"          {currentLocale}\"."
    }

 );
</code>```

could someone tell me what the problem is please ?

答:
Well, try to replace "email": "Email {0}" with "email@placeholder": "Email"

check this : reference

also remove the place holder bracket you don't need it

Title: ARB Pleace holders not working

Body:
I'm making a localization using  ARB google's API but actually the place holder is not working i spent 5 hours to solve this issue with no luck

arb.register(
"login",
{
"title": "Login",
"subtitle": "to your account",
"MSG_BODY_TEST": "This is a test.",
"email": "Email {0}",
"@email": {
 "placeholders": {
   "0": {
      "example": "$123.45",
      "description": "cost presented with currency symbol"
   }
   }
},
"MSG_CURR_LOCALE": "...and the selected language is \"{currentLocale}\"."

}

);

    arb.register(
"login:ar",
{
"title": "الدخول",
"subtitle": "الى حسابك",
"email": "البريد الاكتروني {0}",
"@email": {
 "placeholders": {
   "0": {
      "example": "$123.45",
      "description": "cost presented with currency symbol"
         }
         }
            },
    "MSG_CURR_LOCALE": "...and the selected language is \"          {currentLocale}\"."
    }

 );

could someone tell me what the problem is please ?


问:
How to use hdfk library into qt?
How can I use HKDF library in my qt project?  I found this library seems appropriate in qt (I checked with my source), but I couldn't include this header to project.</p>

答:
Adding a library to a Qt project is actually quite simple. In your qmake .pro file you need the following:

```<code># This is the search location for the compiler to look for headers that accompany your library.
# For system libraries that typically resides under **/usr/include** or **/usr/local/include** if you used `make install`.
INCLUDEPATH+="/path/of/headers/for/library"

# This is the search location for the compiler/linker to look for the library itself.
# For system libraries this is usually somewhere under **/usr/lib** or **/usr/local/lib**
LIBS+= -L/path/of/library/itself

# This is the name of the library to include at link time
# without the **lib** prefix and the **.so** / **.a** / **.lib** / **.dll** extension.
LIBS+= -lMyLibraryName

# This is the full path of the library file itself
# *including* the aforementioned  **lib** prefix and the **.so** / **.a** / **.lib** / **.dll** extension.
# This is used by qmake to look for changes to the library at build time,
# to make sure it is re-linked on change and other dependency related stuff
PRE_TARGETDEPS += /path/and/filename/of/library/itself/libMyLibraryName.lib
</code>```

TIP: All the paths, unless they are specified as absolute paths (starting with '/') will be relative to the build directory. This might be the project directory, but in the case of shadow builds, it will be the shadow build directory. As a tip, simply prepend the following to your relative paths to make them relative to project directory: $$_PRO_FILE_PWD_/ so if for example your lib resides in /my/qt/project/libs/mylib you could make your project resilient to moving by using $$_PRO_FILE_PWD_/libs/mylib instead. Please note that the "project dir" is the location of the qmake .pro file.

Title: How to use hdfk library into qt?

Body:
Adding a library to a Qt project is actually quite simple. In your qmake .pro file you need the following:

# This is the search location for the compiler to look for headers that accompany your library.
# For system libraries that typically resides under **/usr/include** or **/usr/local/include** if you used `make install`.
INCLUDEPATH+="/path/of/headers/for/library"

# This is the search location for the compiler/linker to look for the library itself.
# For system libraries this is usually somewhere under **/usr/lib** or **/usr/local/lib**
LIBS+= -L/path/of/library/itself

# This is the name of the library to include at link time
# without the **lib** prefix and the **.so** / **.a** / **.lib** / **.dll** extension.
LIBS+= -lMyLibraryName

# This is the full path of the library file itself
# *including* the aforementioned  **lib** prefix and the **.so** / **.a** / **.lib** / **.dll** extension.
# This is used by qmake to look for changes to the library at build time,
# to make sure it is re-linked on change and other dependency related stuff
PRE_TARGETDEPS += /path/and/filename/of/library/itself/libMyLibraryName.lib

TIP: All the paths, unless they are specified as absolute paths (starting with '/') will be relative to the build directory. This might be the project directory, but in the case of shadow builds, it will be the shadow build directory. As a tip, simply prepend the following to your relative paths to make them relative to project directory: $$_PRO_FILE_PWD_/ so if for example your lib resides in /my/qt/project/libs/mylib you could make your project resilient to moving by using $$_PRO_FILE_PWD_/libs/mylib instead. Please note that the "project dir" is the location of the qmake .pro file.


问:
Typecast to a type from just the string representation of the type name
```<code>sTypeName = ... //do some string stuff here to get the name of the type

/*
The Assembly.CreateInstance function returns a type
of System.object. I want to type cast it to
the type whose name is sTypeName.

assembly.CreateInstance(sTypeName)

So, in effect I want to do something like:

*/

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);
</code>```

How do I do that? And, what do I take on the left side of the assignment expression, assuming this is C# 2.0. I don't have the var keyword.

答:
.

Define a generic method in your class, and then you can cast like this:

```<code> public T Cast<T>(object obj)
 {
      return (T) obj;
 }

 string sTypename = "SomeClassName";
 MethodInfo cast = this.GetType().GetMethod("Cast");
 MethodInfo genericCast = cast.MakeGenericMethod(new Type[] { Type.GetType(sTypename) });
 Object castedValue = genericCast.Invoke(this, new object[] { instanceToBeCasted });
</code>```

But then I think, what is the point of such casting if you cannot store the casted value in a variable of the actual type, precisely because you don't know the actual type at the time of writing the code?

Body:
sTypeName = ... //do some string stuff here to get the name of the type

/*
The Assembly.CreateInstance function returns a type
of System.object. I want to type cast it to
the type whose name is sTypeName.

assembly.CreateInstance(sTypeName)

So, in effect I want to do something like:

*/

assembly.CreateInstance(sTypeName) as Type.GetType(sTypeName);

How do I do that? And, what do I take on the left side of the assignment expression, assuming this is C# 2.0. I don't have the var keyword.

Body:
.

Define a generic method in your class, and then you can cast like this:

 public T Cast<T>(object obj)
 {
      return (T) obj;
 }

 string sTypename = "SomeClassName";
 MethodInfo cast = this.GetType().GetMethod("Cast");
 MethodInfo genericCast = cast.MakeGenericMethod(new Type[] { Type.GetType(sTypename) });
 Object castedValue = genericCast.Invoke(this, new object[] { instanceToBeCasted });

But then I think, what is the point of such casting if you cannot store the casted value in a variable of the actual type, precisely because you don't know the actual type at the time of writing the code?


问:
Reading MS Word document in C#, dollar sign, special characters are ignored
I am reading a word document (Word 97) word by word, returning text ignores dollar sign and any special characters. I have set encoding to
 (var wordEncode = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;)
at document open time but it doesn't seem to work.

Here is my code:

```<code>var wordEncode = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
Document document = app.Documents.Open(@"C:\Transcript.doc", ReadOnly: true, Encoding: wordEncode);

for (int i = 1; i < document.Words.Count; i++)
{
    textOftheWord = document.Words[i].Text.ToString().Trim().ToLower();
}
</code>```

Example: document contains $587 but after reading it in a program, variable "textOftheWord" has 587, $ sign doesn't come through.Similarly, any special characters and numbers with decimals, all ignored.

Your help is greatly appreciated,Thanks!

答:
Hopefully this will help:

```<code>Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
object path = @"C:\Transcript.doc";
object readOnly = true;
Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
string totaltext = "";
for (int i = 0; i < docs.Paragraphs.Count; i++)
{
     totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
}
Console.WriteLine(totaltext);
docs.Close();
word.Quit();
</code>```

I was able to get $578 in the variable using that.

Similar question is asked here: Read from word document line by line

Original answer here: http://mantascode.com/c-how-to-parse-the-text-content-from-microsoft-word-document/

Body:
I am reading a word document (Word 97) word by word, returning text ignores dollar sign and any special characters. I have set encoding to
 (var wordEncode = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;)
at document open time but it doesn't seem to work.

Here is my code:

var wordEncode = Microsoft.Office.Core.MsoEncoding.msoEncodingUTF8;
Document document = app.Documents.Open(@"C:\Transcript.doc", ReadOnly: true, Encoding: wordEncode);

for (int i = 1; i < document.Words.Count; i++)
{
    textOftheWord = document.Words[i].Text.ToString().Trim().ToLower();
}

Example: document contains $587 but after reading it in a program, variable "textOftheWord" has 587, $ sign doesn't come through.Similarly, any special characters and numbers with decimals, all ignored.

Your help is greatly appreciated,Thanks!

Body:
Hopefully this will help:

Microsoft.Office.Interop.Word.Application word = new Microsoft.Office.Interop.Word.Application();
object miss = System.Reflection.Missing.Value;
object path = @"C:\Transcript.doc";
object readOnly = true;
Microsoft.Office.Interop.Word.Document docs = word.Documents.Open(ref path, ref miss, ref readOnly, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss, ref miss);
string totaltext = "";
for (int i = 0; i < docs.Paragraphs.Count; i++)
{
     totaltext += " \r\n " + docs.Paragraphs[i + 1].Range.Text.ToString();
}
Console.WriteLine(totaltext);
docs.Close();
word.Quit();

I was able to get $578 in the variable using that.

Similar question is asked here: Read from word document line by line

Original answer here: http://mantascode.com/c-how-to-parse-the-text-content-from-microsoft-word-document/


问:
Azure Webjobs timing out, not receiving response from webapi
I have a Azure Webjob which hits a WebApi. The WebApi sends back an acknowledgement in 4 - 5mins. So, I have declared the TimeOut for the HttpClient to be at 10 mins.

Now, if the WebApi is returning the response in less than 4 mins, it works fine. But if the WebApi is returning the response for a request in 4 min 30 sec, the azure  webjob is not getting this acknowledgement. Instead, the HttpClient on the WebJob is waiting for 10 mins, and then timing out. Is there some kind of a time out on the Webjob that I'm missing?

答:
If you are executing a long running task or function in the context of BrokeredMessages, they have a timeout hard coded to 5 minutes.

Utilizing Task I place my long running function inside one and passing it to this function to run and "relock" the BrokeredMessage:

```<code>/// <summary>
/// Maximum time lockout for a BrokeredMessage is 5 minutes. This allows the
/// timer to relock every 4 minutes while waiting on Task parameter to complete.
/// </summary>
/// <param name="task"></param>
/// <param name="message"></param>
private void WaitAndRelockMessage( Task task, BrokeredMessage message )
{
    var myTimer = new Timer( new TimerCallback( RelockMessage ), message, 240000, 240000 );

    task.Wait();

    myTimer.Dispose();
}

private void RelockMessage( object message )
{
    try { ((BrokeredMessage)message).RenewLock(); }
    catch( OperationCanceledException ) { }
}
</code>```

Sample Usage:

```<code>var task = Task.Run( async () => { await m_service.doWork(); } );

WaitAndRelockMessage(task, message);
</code>```

Body:
If you are executing a long running task or function in the context of BrokeredMessages, they have a timeout hard coded to 5 minutes.

Utilizing Task I place my long running function inside one and passing it to this function to run and "relock" the BrokeredMessage:

/// <summary>
/// Maximum time lockout for a BrokeredMessage is 5 minutes. This allows the
/// timer to relock every 4 minutes while waiting on Task parameter to complete.
/// </summary>
/// <param name="task"></param>
/// <param name="message"></param>
private void WaitAndRelockMessage( Task task, BrokeredMessage message )
{
    var myTimer = new Timer( new TimerCallback( RelockMessage ), message, 240000, 240000 );

    task.Wait();

    myTimer.Dispose();
}

private void RelockMessage( object message )
{
    try { ((BrokeredMessage)message).RenewLock(); }
    catch( OperationCanceledException ) { }
}

Sample Usage:

var task = Task.Run( async () => { await m_service.doWork(); } );

WaitAndRelockMessage(task, message);


问:
How to add button in row of table
I have table which populated from database. How can i add a single button in last column?

Here is the code for jtable,

```<code>private void getData(){
        try{
            con = DatabaseConnection.ConnectDB();
            java.sql.Statement st = con.createStatement();
            String sql  = "SELECT * FROM mainTable WHERE status = 0";
            rs = st.executeQuery(sql);
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        } catch(Exception e){
            JOptionPane.showMessageDialog(null,e);
        }
    }
</code>```

答:
I suggest you to start with simple example that would add the button into JTable cell. Later you can setModel() with resultset from database.

An example would demonstrate how to add JButton into JTable Cell.

```<code>public class JButtonTableExample {

public JButtonTableExample() {
    JFrame frame = new JFrame("JButtonTable Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][] {
        {
            "button 1",
            "foo"
        }, {
            "button 2",
            "bar"
        }
    }, new Object[] {
        "Button",
        "String"
    });

    JTable table = new JTable(dm);
    table.getColumn("Button").setCellRenderer(new ButtonRenderer());
    table.getColumn("Button").setCellEditor(new ButtonEditor(new JCheckBox()));

    JScrollPane scroll = new JScrollPane(table);

    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    table.getColumnModel().getColumn(0).setPreferredWidth(100);
    frame.add(scroll);

    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new JButtonTableExample();
        }
    });

 }
}

class ButtonRenderer extends JButton implements TableCellRenderer {

public ButtonRenderer() {
    setOpaque(true);
}

@Override
public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
        setForeground(table.getSelectionForeground());
        setBackground(table.getSelectionBackground());
    } else {
        setForeground(table.getForeground());
        setBackground(UIManager.getColor("Button.background"));
    }
    setText((value == null) ? "" : value.toString());
    return this;
  }
 }

class ButtonEditor extends DefaultCellEditor {

protected JButton button;
private String label;
private boolean isPushed;

public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            fireEditingStopped();
        }
    });
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column) {
    if (isSelected) {
        button.setForeground(table.getSelectionForeground());
        button.setBackground(table.getSelectionBackground());
    } else {
        button.setForeground(table.getForeground());
        button.setBackground(table.getBackground());
    }
    label = (value == null) ? "" : value.toString();
    button.setText(label);
    isPushed = true;
    return button;
}

@Override
public Object getCellEditorValue() {
    if (isPushed) {
        JOptionPane.showMessageDialog(button, label + ": Ouch!");
    }
    isPushed = false;
    return label;
}

@Override
public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
 }
}
</code>```

Title: How to add button in row of table

Body:
I have table which populated from database. How can i add a single button in last column?

Here is the code for jtable,

private void getData(){
        try{
            con = DatabaseConnection.ConnectDB();
            java.sql.Statement st = con.createStatement();
            String sql  = "SELECT * FROM mainTable WHERE status = 0";
            rs = st.executeQuery(sql);
            jTable1.setModel(DbUtils.resultSetToTableModel(rs));
        } catch(Exception e){
            JOptionPane.showMessageDialog(null,e);
        }
    }

Body:
I suggest you to start with simple example that would add the button into JTable cell. Later you can setModel() with resultset from database.

An example would demonstrate how to add JButton into JTable Cell.

public class JButtonTableExample {

public JButtonTableExample() {
    JFrame frame = new JFrame("JButtonTable Example");
    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

    DefaultTableModel dm = new DefaultTableModel();
    dm.setDataVector(new Object[][] {
        {
            "button 1",
            "foo"
        }, {
            "button 2",
            "bar"
        }
    }, new Object[] {
        "Button",
        "String"
    });

    JTable table = new JTable(dm);
    table.getColumn("Button").setCellRenderer(new ButtonRenderer());
    table.getColumn("Button").setCellEditor(new ButtonEditor(new JCheckBox()));

    JScrollPane scroll = new JScrollPane(table);

    table.setPreferredScrollableViewportSize(table.getPreferredSize());
    table.getColumnModel().getColumn(0).setPreferredWidth(100);
    frame.add(scroll);

    frame.pack();
    frame.setVisible(true);
}

public static void main(String[] args) {
    SwingUtilities.invokeLater(new Runnable() {
        @Override
        public void run() {
            new JButtonTableExample();
        }
    });

 }
}

class ButtonRenderer extends JButton implements TableCellRenderer {

public ButtonRenderer() {
    setOpaque(true);
}

@Override
public Component getTableCellRendererComponent(JTable table, Object value,
    boolean isSelected, boolean hasFocus, int row, int column) {
    if (isSelected) {
        setForeground(table.getSelectionForeground());
        setBackground(table.getSelectionBackground());
    } else {
        setForeground(table.getForeground());
        setBackground(UIManager.getColor("Button.background"));
    }
    setText((value == null) ? "" : value.toString());
    return this;
  }
 }

class ButtonEditor extends DefaultCellEditor {

protected JButton button;
private String label;
private boolean isPushed;

public ButtonEditor(JCheckBox checkBox) {
    super(checkBox);
    button = new JButton();
    button.setOpaque(true);
    button.addActionListener(new ActionListener() {
        @Override
        public void actionPerformed(ActionEvent e) {
            fireEditingStopped();
        }
    });
}

@Override
public Component getTableCellEditorComponent(JTable table, Object value,
    boolean isSelected, int row, int column) {
    if (isSelected) {
        button.setForeground(table.getSelectionForeground());
        button.setBackground(table.getSelectionBackground());
    } else {
        button.setForeground(table.getForeground());
        button.setBackground(table.getBackground());
    }
    label = (value == null) ? "" : value.toString();
    button.setText(label);
    isPushed = true;
    return button;
}

@Override
public Object getCellEditorValue() {
    if (isPushed) {
        JOptionPane.showMessageDialog(button, label + ": Ouch!");
    }
    isPushed = false;
    return label;
}

@Override
public boolean stopCellEditing() {
    isPushed = false;
    return super.stopCellEditing();
 }
}


问:
How to run a Mininet CLI command from inside python module
I wrote a python module to generate a random topology using Mininet and connected OpenDayLight as the remote controller.

I would like to pass a command to the mininet CLI, but from inside the python module. After generating the hosts and switches as well as connecting them to the remote controller, the module randomly chooses 2 hosts to act as Server and Client.
I am having trouble doing something similar to this, but from in-line inside the python module:

```<code>mininet> h<random_number> sudo python HTTPTraffic.py <SrcIP> <DstIP>
</code>```

HTTPTraffic.py is another module that takes arguments SrcIP and DstIP

This is the part of the main module that elects 2 random hosts and gets their IPs. I would like the HTTPTraffic.py to run in the host corresponding to SrcIP

```<code>Nodes = list(range(1,h))
Src = random.choice(Nodes)         # randomly chooses 1 host
Nodes.remove(Src)
Dst = random.choice(Nodes)         # randomly chooses another host

SrcName = 'h%s' %(Src)
DstName = 'h%s' %(Dst)
SrcNode=net.get(SrcName)
DstNode=net.get(DstName)

SrcIP = SrcNode.IP()               # IP retrieval of chosen hosts
DstIP = DstNode.IP()
print ('The Souce/Client is: '+ SrcName)
print (SrcIP)
print ('The Destination/Server is: '+ DstName)
print (DstIP)

SrcName +".cmd('sudo python HTTPTraffic.py "+SrcIP+" " +DstIP+"')"    # this is where I am having trouble
</code>```

From the mininet API documentation (See section 'Customizing a Network'), something like that is possible but I am having so much trouble doing it. Also, I would like for this command to run in the background while the main program runs. Any feedback is appreciated.

答:
I recommend you take a look at the documentation for the Python module subprocess, which acts as an platform-agnostic API for running other programs from your program.

For example, you can call ls by adding the following line to your code:

```<code>subprocess.run(["ls", "-l"])
</code>```

The first argument of run takes an array of strings where each string is a part of the command you are executing.

Body:
I wrote a python module to generate a random topology using Mininet and connected OpenDayLight as the remote controller.

I would like to pass a command to the mininet CLI, but from inside the python module. After generating the hosts and switches as well as connecting them to the remote controller, the module randomly chooses 2 hosts to act as Server and Client.
I am having trouble doing something similar to this, but from in-line inside the python module:

mininet> h<random_number> sudo python HTTPTraffic.py <SrcIP> <DstIP>

HTTPTraffic.py is another module that takes arguments SrcIP and DstIP

This is the part of the main module that elects 2 random hosts and gets their IPs. I would like the HTTPTraffic.py to run in the host corresponding to SrcIP

Nodes = list(range(1,h))
Src = random.choice(Nodes)         # randomly chooses 1 host
Nodes.remove(Src)
Dst = random.choice(Nodes)         # randomly chooses another host

SrcName = 'h%s' %(Src)
DstName = 'h%s' %(Dst)
SrcNode=net.get(SrcName)
DstNode=net.get(DstName)

SrcIP = SrcNode.IP()               # IP retrieval of chosen hosts
DstIP = DstNode.IP()
print ('The Souce/Client is: '+ SrcName)
print (SrcIP)
print ('The Destination/Server is: '+ DstName)
print (DstIP)

SrcName +".cmd('sudo python HTTPTraffic.py "+SrcIP+" " +DstIP+"')"    # this is where I am having trouble

From the mininet API documentation (See section 'Customizing a Network'), something like that is possible but I am having so much trouble doing it. Also, I would like for this command to run in the background while the main program runs. Any feedback is appreciated.

Body:
I recommend you take a look at the documentation for the Python module subprocess, which acts as an platform-agnostic API for running other programs from your program.

For example, you can call ls by adding the following line to your code:

subprocess.run(["ls", "-l"])

The first argument of run takes an array of strings where each string is a part of the command you are executing.


问:
Plotting lda-object in R
I am trying to plot a lda-object created with the lda-function of the MASS package.

The data I am using is here:
https://pastebin.com/yjfmsE3F

My current code is:

```<code>types <- c('GO', 'GO', 'GO', 'GO', 'GO', 'OO', 'OR', 'OO', 'OO', 'GO', 'GR', 'OO', 'OO', 'GO')
bacDummy <- t(bacCountData)
bacDummy2 <- decostand(bacDummy, "freq")
bacDummy3 <- cbind(types, bacDummy2)
colnames(bacDummy3)[1] <- "Site"
bacDummy4 <- as.data.frame(bacDummy3)
</code>```

with decostand being form the vegan package.

I then went ahead and tried to use the lda-function:

```<code>bac.lda <- lda(bacDummy4[,2:170], grouping=types)
</code>```

which gives me the following error:

```<code>Error in lda.default(x, grouping, ...) :
  variables   4  53 114 138 appear to be constant within groups
</code>```

I then deleted the troubling columns (even though I know it the dirty work around):

```<code>bacDummy4 <- bacDummy4[,-139]
bacDummy4 <- bacDummy4[,-115]
bacDummy4 <- bacDummy4[,-54]
bacDummy4 <- bacDummy4[,-5]
</code>```

This let me do the LDA, however with the warning: In lda.default(x, grouping, ...) : variables are collinear

When I try to plot the groups in a scatter plot I get the following error:

```<code>plot(bac.lda)
Error in FUN(x, aperm(array(STATS, dims[perm]), order(perm)), ...) :
  non-numeric argument to binary operator
</code>```

What am I doing wrong? If I do str(bac.lda) I get this output:

```<code>List of 8
 $ prior  : Named num [1:4] 0.5 0.0714 0.3571 0.0714
  ..- attr(*, "names")= chr [1:4] "GO" "GR" "OO" "OR"
 $ counts : Named int [1:4] 7 1 5 1
  ..- attr(*, "names")= chr [1:4] "GO" "GR" "OO" "OR"
 $ means  : num [1:4, 1:165] 6.14 1 2.2 5 2.14 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:4] "GO" "GR" "OO" "OR"
  .. ..$ : chr [1:165] "ReferenceOTU1484" "ReferenceOTU893" "ReferenceOTU1445" "ReferenceOTU623" ...
 $ scaling: num [1:165, 1:3] -0.01649 -0.03767 -0.00607 0.04141 -0.03966 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:165] "ReferenceOTU1484" "ReferenceOTU893" "ReferenceOTU1445" "ReferenceOTU623" ...
  .. ..$ : chr [1:3] "LD1" "LD2" "LD3"
 $ lev    : chr [1:4] "GO" "GR" "OO" "OR"
 $ svd    : num [1:3] 4.54 3.06 2.03
 $ N      : int 14
 $ call   : language lda(x = bacDummy4[, -1], grouping = bacDummy4$Site)
 - attr(*, "class")= chr "lda"
</code>```

All help is much appreciated!

答:
You should take care to carefully track the datatypes of your variables during each transformation. I ran into a few problems with the code you provided. This seems to work

```<code>bacCountData <- read.csv("https://pastebin.com/raw/yjfmsE3F", header=T, row.names=1)
types <- c('GO', 'GO', 'GO', 'GO', 'GO', 'OO',
    'OR', 'OO', 'OO', 'GO', 'GR', 'OO', 'OO', 'GO')

bacDummy <- t(bacCountData)
bacDummy2 <- vegan::decostand(bacDummy, "freq")
bacDummy3 <- data.frame(types=types, bacDummy2)
colnames(bacDummy3)[1] <- "Site"

bac.lda <- MASS::lda(bacDummy3[,-c(1, 5, 54, 115, 139)], grouping=types)
plot(bac.lda)
</code>```

And produces the following plot

Title: Plotting lda-object in R

Body:
I am trying to plot a lda-object created with the lda-function of the MASS package.

The data I am using is here:
https://pastebin.com/yjfmsE3F

My current code is:

types <- c('GO', 'GO', 'GO', 'GO', 'GO', 'OO', 'OR', 'OO', 'OO', 'GO', 'GR', 'OO', 'OO', 'GO')
bacDummy <- t(bacCountData)
bacDummy2 <- decostand(bacDummy, "freq")
bacDummy3 <- cbind(types, bacDummy2)
colnames(bacDummy3)[1] <- "Site"
bacDummy4 <- as.data.frame(bacDummy3)

with decostand being form the vegan package.

I then went ahead and tried to use the lda-function:

bac.lda <- lda(bacDummy4[,2:170], grouping=types)

which gives me the following error:

Error in lda.default(x, grouping, ...) :
  variables   4  53 114 138 appear to be constant within groups

I then deleted the troubling columns (even though I know it the dirty work around):

bacDummy4 <- bacDummy4[,-139]
bacDummy4 <- bacDummy4[,-115]
bacDummy4 <- bacDummy4[,-54]
bacDummy4 <- bacDummy4[,-5]

This let me do the LDA, however with the warning: In lda.default(x, grouping, ...) : variables are collinear

When I try to plot the groups in a scatter plot I get the following error:

plot(bac.lda)
Error in FUN(x, aperm(array(STATS, dims[perm]), order(perm)), ...) :
  non-numeric argument to binary operator

What am I doing wrong? If I do str(bac.lda) I get this output:

List of 8
 $ prior  : Named num [1:4] 0.5 0.0714 0.3571 0.0714
  ..- attr(*, "names")= chr [1:4] "GO" "GR" "OO" "OR"
 $ counts : Named int [1:4] 7 1 5 1
  ..- attr(*, "names")= chr [1:4] "GO" "GR" "OO" "OR"
 $ means  : num [1:4, 1:165] 6.14 1 2.2 5 2.14 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:4] "GO" "GR" "OO" "OR"
  .. ..$ : chr [1:165] "ReferenceOTU1484" "ReferenceOTU893" "ReferenceOTU1445" "ReferenceOTU623" ...
 $ scaling: num [1:165, 1:3] -0.01649 -0.03767 -0.00607 0.04141 -0.03966 ...
  ..- attr(*, "dimnames")=List of 2
  .. ..$ : chr [1:165] "ReferenceOTU1484" "ReferenceOTU893" "ReferenceOTU1445" "ReferenceOTU623" ...
  .. ..$ : chr [1:3] "LD1" "LD2" "LD3"
 $ lev    : chr [1:4] "GO" "GR" "OO" "OR"
 $ svd    : num [1:3] 4.54 3.06 2.03
 $ N      : int 14
 $ call   : language lda(x = bacDummy4[, -1], grouping = bacDummy4$Site)
 - attr(*, "class")= chr "lda"

All help is much appreciated!

Body:
You should take care to carefully track the datatypes of your variables during each transformation. I ran into a few problems with the code you provided. This seems to work

bacCountData <- read.csv("https://pastebin.com/raw/yjfmsE3F", header=T, row.names=1)
types <- c('GO', 'GO', 'GO', 'GO', 'GO', 'OO',
    'OR', 'OO', 'OO', 'GO', 'GR', 'OO', 'OO', 'GO')

bacDummy <- t(bacCountData)
bacDummy2 <- vegan::decostand(bacDummy, "freq")
bacDummy3 <- data.frame(types=types, bacDummy2)
colnames(bacDummy3)[1] <- "Site"

bac.lda <- MASS::lda(bacDummy3[,-c(1, 5, 54, 115, 139)], grouping=types)
plot(bac.lda)

And produces the following plot


问:
ConstraintLayout in Cardview adding white space
I am trying to create a CardView that has a ConstraintLayout to organize some TextView.

Sometimes it'll display as intended, but sometimes, it'll add extra white space such as when a keyboard is closed and ruin the layout. I have a GIF below showing the CardView working and not working in the same span of time.

A code snippet for the relevant CardView is below. I use wrap_content to try to keep the CardView at the size I want, but it still expands.

```<code>    <android.support.v7.widget.CardView
    android:id="@+id/cardView_game_cash"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_margin="6dp"
    app:cardCornerRadius="4dp"
    app:contentPadding="6dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/textView_game_cashLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Total Cash"
            app:layout_constraintLeft_toLeftOf="@+id/textView_game_cash"
            app:layout_constraintRight_toRightOf="@+id/textView_game_cash"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView_game_totalProfitLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Total Profit"
            app:layout_constraintLeft_toLeftOf="@+id/textView_game_totalProfit"
            app:layout_constraintRight_toRightOf="@+id/textView_game_totalProfit"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView_game_profitLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Win Profit"
            app:layout_constraintLeft_toLeftOf="@+id/textView_game_profit"
            app:layout_constraintRight_toRightOf="@+id/textView_game_profit"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView_game_cash"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:gravity="center"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@+id/textView_game_totalProfit"
            app:layout_constraintTop_toBottomOf="@+id/textView_game_cashLabel"
            tools:text="TextView" />

        <TextView
            android:id="@+id/textView_game_totalProfit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:gravity="center"
            app:layout_constraintLeft_toRightOf="@+id/textView_game_cash"
            app:layout_constraintRight_toLeftOf="@+id/textView_game_profit"
            app:layout_constraintTop_toTopOf="@+id/textView_game_cash"
            tools:text="TextView" />

        <TextView
            android:id="@+id/textView_game_profit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:gravity="center"
            app:layout_constraintLeft_toRightOf="@+id/textView_game_totalProfit"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="@+id/textView_game_cash"
            tools:text="TextView" />
    </android.support.constraint.ConstraintLayout>

</android.support.v7.widget.CardView>
</code>```

答:
I found a solution to my problem. In the TextView within the ConstraintLayout, I replaced android:layout_height="wrap_content"

with:

android:layout_height="0dp"
app:layout_constraintHeight_default="wrap"

The layout worked as intended with that change to all the TextView within.

Body:
I am trying to create a CardView that has a ConstraintLayout to organize some TextView.

Sometimes it'll display as intended, but sometimes, it'll add extra white space such as when a keyboard is closed and ruin the layout. I have a GIF below showing the CardView working and not working in the same span of time.

A code snippet for the relevant CardView is below. I use wrap_content to try to keep the CardView at the size I want, but it still expands.

    <android.support.v7.widget.CardView
    android:id="@+id/cardView_game_cash"
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_margin="6dp"
    app:cardCornerRadius="4dp"
    app:contentPadding="6dp"
    app:layout_constraintLeft_toLeftOf="parent"
    app:layout_constraintRight_toRightOf="parent"
    app:layout_constraintTop_toTopOf="parent">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content">

        <TextView
            android:id="@+id/textView_game_cashLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Total Cash"
            app:layout_constraintLeft_toLeftOf="@+id/textView_game_cash"
            app:layout_constraintRight_toRightOf="@+id/textView_game_cash"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView_game_totalProfitLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Total Profit"
            app:layout_constraintLeft_toLeftOf="@+id/textView_game_totalProfit"
            app:layout_constraintRight_toRightOf="@+id/textView_game_totalProfit"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView_game_profitLabel"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:text="Win Profit"
            app:layout_constraintLeft_toLeftOf="@+id/textView_game_profit"
            app:layout_constraintRight_toRightOf="@+id/textView_game_profit"
            app:layout_constraintTop_toTopOf="parent" />

        <TextView
            android:id="@+id/textView_game_cash"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:gravity="center"
            app:layout_constraintLeft_toLeftOf="parent"
            app:layout_constraintRight_toLeftOf="@+id/textView_game_totalProfit"
            app:layout_constraintTop_toBottomOf="@+id/textView_game_cashLabel"
            tools:text="TextView" />

        <TextView
            android:id="@+id/textView_game_totalProfit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/colorPrimary"
            android:gravity="center"
            app:layout_constraintLeft_toRightOf="@+id/textView_game_cash"
            app:layout_constraintRight_toLeftOf="@+id/textView_game_profit"
            app:layout_constraintTop_toTopOf="@+id/textView_game_cash"
            tools:text="TextView" />

        <TextView
            android:id="@+id/textView_game_profit"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:background="@color/colorAccent"
            android:gravity="center"
            app:layout_constraintLeft_toRightOf="@+id/textView_game_totalProfit"
            app:layout_constraintRight_toRightOf="parent"
            app:layout_constraintTop_toTopOf="@+id/textView_game_cash"
            tools:text="TextView" />
    </android.support.constraint.ConstraintLayout>

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