问:
Generating all permutations of elements in a single array
I’ve seen several similar questions about how to generate all possible permutations of elements in an array. But I’m having a very hard time figuring out how to write an algorithm that will output values that are not included in each permutations:

Starting with the following array (with N elements):

```<code>var array = ["apple", "banana", "lemon", "mango"];
</code>```

And getting the following result:

```<code>var result = [
   "apple not banana  not lemon  not mango"
   "apple banana not lemon not mango"
   "apple banana lemon not mango"
   "apple banana lemon mango"
   "banana not apple not lemon not mango"
   ...
];
</code>```

答:
Would something like this work (based on Recursively print all permutations of a string (Javascript)):

var this_array = ["apple", "banana", "lemon", "mango"];
function *permute(a, n = a.length) {
  if (n <= 1) yield a.slice();
  else for (let i = 0; i < n; i++) {
    yield *permute(a, n - 1);
    const j = n % 2 ? 0 : i;
    [a[n-1], a[j]] = [a[j], a[n-1]];
  }
}

all_arrays = (Array.from(permute(this_array)));
all_arrays = all_arrays.map(function(element){
 return([element[0]+" not "+element[1]+" not "+element[2]+" not "+element[3], element[0]+" "+element[1]+" not "+element[2]+" not "+element[3], element[0]+" "+element[1]+" "+element[2]+" not "+element[3], element[0]+" "+element[1]+" "+element[2]+" "+element[3]]);

    /*this is the area you need to play around with to get whatever combination of "not"s you want. */

})
joined_arrays = all_arrays.join("\n");

console.dir(all_arrays); // preserving as array
console.dir(joined_arrays); //if you want as a single block of text```

Body:
I’ve seen several similar questions about how to generate all possible permutations of elements in an array. But I’m having a very hard time figuring out how to write an algorithm that will output values that are not included in each permutations:

Starting with the following array (with N elements):

var array = ["apple", "banana", "lemon", "mango"];

And getting the following result:

var result = [
   "apple not banana  not lemon  not mango"
   "apple banana not lemon not mango"
   "apple banana lemon not mango"
   "apple banana lemon mango"
   "banana not apple not lemon not mango"
   ...
];


来源: stackexchange

问:
How to fix an error "FAIL : ValueError: Element locator" in AppiumLibrary with Robotframework?
I am working with AppiumLibrary with Robotframwork and have got an error FAIL : ValueError: Element locator '//*[@text="STG"]' did not match any elements.

```<code>Test Case1
| FAIL |
ValueError: Element locator '//*[@text="STG"]' did not match any elements.
</code>```

This is the test case:

```<code>**Settings**: Library AppiumLibrary

**Test Cases**: Test Case1

    Open Application    http://localhost:4723/wd/hub
    platformName=Android  deviceName=ZY22452GQX
    app=/home/keval/Desktop/extra/app-rheem-qa(1).apk
    appPackage=com.rheem.econetconsumerandroid.qa
    appActivity=com.econet.ui.MainActivity

    Click Element    id=com.rheem.econetconsumerandroid.qa:id/
    activity_login_logo_image_view
    Click Element    id=com.rheem.econetconsumerandroid.qa:id/
    activity_login_logo_image_view
    Click Element    id=com.rheem.econetconsumerandroid.qa:id/
    activity_login_logo_image_view
    Click Text    text=STG    exact_match=False
    Click Element    id=com.rheem.econetconsumerandroid.qa:id/menu_save
    Input Text    id=com.rheem.econetconsumerandroid.qa:id/
    login_email_text    text=deepali.gill@volansystech.com
    Input Password    id=com.rheem.econetconsumerandroid.qa:id/
    login_password_text    text=kalpesh@2017
    Click Element    id=com.rheem.econetconsumerandroid.qa:id/login_button
</code>```

答:
The locator looks to be valid. Looks like you are doing login, so maybe need to wait for element to appear on UI:

```<code>Wait Until Page Contains Element  //*[@text="STG"]
</code>```

More details

ContentLicense: CC BY-SA 4.0

Body:
I am working with AppiumLibrary with Robotframwork and have got an error FAIL : ValueError: Element locator '//*[@text="STG"]' did not match any elements.

Test Case1
| FAIL |
ValueError: Element locator '//*[@text="STG"]' did not match any elements.

This is the test case:

**Settings**: Library AppiumLibrary

**Test Cases**: Test Case1

    Open Application    http://localhost:4723/wd/hub
    platformName=Android  deviceName=ZY22452GQX
    app=/home/keval/Desktop/extra/app-rheem-qa(1).apk
    appPackage=com.rheem.econetconsumerandroid.qa
    appActivity=com.econet.ui.MainActivity

    Click Element    id=com.rheem.econetconsumerandroid.qa:id/
    activity_login_logo_image_view
    Click Element    id=com.rheem.econetconsumerandroid.qa:id/
    activity_login_logo_image_view
    Click Element    id=com.rheem.econetconsumerandroid.qa:id/
    activity_login_logo_image_view
    Click Text    text=STG    exact_match=False
    Click Element    id=com.rheem.econetconsumerandroid.qa:id/menu_save
    Input Text    id=com.rheem.econetconsumerandroid.qa:id/
    login_email_text    text=deepali.gill@volansystech.com
    Input Password    id=com.rheem.econetconsumerandroid.qa:id/
    login_password_text    text=kalpesh@2017
    Click Element    id=com.rheem.econetconsumerandroid.qa:id/login_button

Body:
The locator looks to be valid. Looks like you are doing login, so maybe need to wait for element to appear on UI:

Wait Until Page Contains Element  //*[@text="STG"]

More details

ContentLicense: CC BY-SA 3.0


问:
Is using unnecessary / additional braces in function a good practice in C#?
I'm currently creating a program that write some XML, but due to the library I'm using I have to create many variables like:

```<code>XmlDocument xmlWriter = new XmlDocument();
XmlNode root = xmlWriter.CreateElement("score");
xmlWriter.AppendChild(root);

XmlNode apiKey = xmlWriter.CreateElement("APIkey");
apiKey.InnerText = "placeholder";
root.AppendChild(apiKey);
</code>```

I have many elements to create just as the API Key, resulting in a lot of variables. So i thought of surrounding each element with braces just for readability like so:

```<code>XmlDocument xmlWriter = new XmlDocument();
XmlNode root = xmlWriter.CreateElement("score");
xmlWriter.AppendChild(root);

{
    XmlNode apiKey = xmlWriter.CreateElement("APIkey");
    apiKey.InnerText = "placeholder";
    root.AppendChild(apiKey);
}
apiKey.DoSomething() // Doesn't work because it's out of scope
</code>```

I believe it's saving some memory and helping me later because the variables don't exist anymore (useful for IntelliSense)

You could say "Just use a function" but I only use this code in this particular part (and calling a function with parameters take some nearly negligeable time but anyway...)

What's your opinion about this ?

答:
I don't see the point of this. Using a single function to create an element and append it to another element (perhaps with params attributes) seems like the way to go here. It will produce a much more readable code. Something like this:

```<code>XmlNode CreateAndAppendChild(XmlDocument xmlWriter, XmlNode parent, string name, string innerText, params Tuple<string, string> attributes)
{
    var child = xmlWriter.CreateElement(name);
    foreach(var attribute in attributes)
    {
        child.SetAttribute(attribute.Item1, attribute.Item2);
    }
    child.InnerText = innerText;
    parent.AppendChild(child);
    return child;
}
</code>```

And the usage:

```<code>CreateAndAppendChild(xmlWriter, root, "APIkey", "placeholder");
</code>```

Instead of your current code:

```<code>XmlNode apiKey = xmlWriter.CreateElement("APIkey");
apiKey.InnerText = "placeholder";
root.AppendChild(apiKey);
</code>```

If you want to add a child element to APIKey:

```<code>var apiKey = CreateAndAppendChild(xmlWriter, root, "APIkey", "placeholder");

CreateAndAppendChild(xmlWriter, apiKey , "child", "" Tuple.Create("attributeName", "attributeValue"));
</code>```

Body:
I'm currently creating a program that write some XML, but due to the library I'm using I have to create many variables like:

XmlDocument xmlWriter = new XmlDocument();
XmlNode root = xmlWriter.CreateElement("score");
xmlWriter.AppendChild(root);

XmlNode apiKey = xmlWriter.CreateElement("APIkey");
apiKey.InnerText = "placeholder";
root.AppendChild(apiKey);

I have many elements to create just as the API Key, resulting in a lot of variables. So i thought of surrounding each element with braces just for readability like so:

XmlDocument xmlWriter = new XmlDocument();
XmlNode root = xmlWriter.CreateElement("score");
xmlWriter.AppendChild(root);

{
    XmlNode apiKey = xmlWriter.CreateElement("APIkey");
    apiKey.InnerText = "placeholder";
    root.AppendChild(apiKey);
}
apiKey.DoSomething() // Doesn't work because it's out of scope

I believe it's saving some memory and helping me later because the variables don't exist anymore (useful for IntelliSense)

You could say "Just use a function" but I only use this code in this particular part (and calling a function with parameters take some nearly negligeable time but anyway...)

What's your opinion about this ?

Body:
I don't see the point of this. Using a single function to create an element and append it to another element (perhaps with params attributes) seems like the way to go here. It will produce a much more readable code. Something like this:

XmlNode CreateAndAppendChild(XmlDocument xmlWriter, XmlNode parent, string name, string innerText, params Tuple<string, string> attributes)
{
    var child = xmlWriter.CreateElement(name);
    foreach(var attribute in attributes)
    {
        child.SetAttribute(attribute.Item1, attribute.Item2);
    }
    child.InnerText = innerText;
    parent.AppendChild(child);
    return child;
}

And the usage:

CreateAndAppendChild(xmlWriter, root, "APIkey", "placeholder");

Instead of your current code:

XmlNode apiKey = xmlWriter.CreateElement("APIkey");
apiKey.InnerText = "placeholder";
root.AppendChild(apiKey);

If you want to add a child element to APIKey:

var apiKey = CreateAndAppendChild(xmlWriter, root, "APIkey", "placeholder");

CreateAndAppendChild(xmlWriter, apiKey , "child", "" Tuple.Create("attributeName", "attributeValue"));


问:
Finding a function definition using a call in C++
I'm trying to understand the source code of a fairly large C++ project.  The source wasn't written with an IDE, so I don't have a "goto" button to go straight to the function definition.

For example:

```<code>srand();
</code>```

I want to find out exactly where the function srand() is defined.

The only method I can come up with is manually checking all the header includes to recursively find the declaration and the corresponding file for the definition.

This is a linux environment and the source is compiled with g++ (using cmake).

答:
If you are using VI you can shift+k that will open it in a man page, if there is one for this word. I believe it automatically is set to search in man(3) but i'm not 100% sure. At least this way you can know wether it's a system function or not.

Another option is to use Doxygen to setup the call graphs and let it generate the source (even if there are no comments). With the call graph you can easily spot from where each function is coming from.

ContentLicense: CC BY-SA 2.5

Body:
I'm trying to understand the source code of a fairly large C++ project.  The source wasn't written with an IDE, so I don't have a "goto" button to go straight to the function definition.

For example:

srand();

I want to find out exactly where the function srand() is defined.

The only method I can come up with is manually checking all the header includes to recursively find the declaration and the corresponding file for the definition.

This is a linux environment and the source is compiled with g++ (using cmake).


问:
how to set column name in DataTable
I am taking Excel data into DataTable but it is taking Excel Column name as first row of data in DataTable. So help me to set Excel's first row as columns in DataTable.
PS: I am using Microsoft.Offfice.Interop.Excel and System.Data.DataTable namespace
This is my code:

```<code>connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
new System.Data.OleDb.OleDbDataAdapter(cmdExcel).Fill(dt);
connExcel.Close();
</code>```

I am getting all the data of specified excel sheet into DataTable dt but it is taking Excel column names as first row of data in Datatable

答:
To change a column name, use ColumnName.

```<code>DataTable table = new DataTable();

table.Columns.Add("A", typeof(int));
table.Columns.Add("B", typeof(string));

table.Columns[0].ColumnName = "Column A";
table.Columns[1].ColumnName = "Column B";

table.Rows.Add(99, "test row");
</code>```

Title: how to set column name in DataTable

Body:
I am taking Excel data into DataTable but it is taking Excel Column name as first row of data in DataTable. So help me to set Excel's first row as columns in DataTable.
PS: I am using Microsoft.Offfice.Interop.Excel and System.Data.DataTable namespace
This is my code:

connExcel.Open();
cmdExcel.CommandText = "SELECT * From [" + SheetName + "]";
oda.SelectCommand = cmdExcel;
new System.Data.OleDb.OleDbDataAdapter(cmdExcel).Fill(dt);
connExcel.Close();

I am getting all the data of specified excel sheet into DataTable dt but it is taking Excel column names as first row of data in Datatable

Body:
To change a column name, use ColumnName.

DataTable table = new DataTable();

table.Columns.Add("A", typeof(int));
table.Columns.Add("B", typeof(string));

table.Columns[0].ColumnName = "Column A";
table.Columns[1].ColumnName = "Column B";

table.Rows.Add(99, "test row");


问:
C# export grid to word using template
I have created a word template with some number and text fields and I export my data from my application like this:

```<code>Object oMissing = System.Reflection.Missing.Value;

        Object oTemplatePath = "C:\\MyTemplate.dotx";

        Application wordApp = new Application();
        Document wordDoc = new Document();

        wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

        foreach (Microsoft.Office.Interop.Word.Field myMergeField in wordDoc.Fields)
        {

            Range rngFieldCode = myMergeField.Code;

            String fieldText = rngFieldCode.Text;

            if (fieldText.StartsWith(" MERGEFIELD"))
            {

                Int32 endMerge = fieldText.IndexOf("\\");

                Int32 fieldNameLength = fieldText.Length - endMerge;

                String fieldName = fieldText.Substring(11, endMerge - 11);

                fieldName = fieldName.Trim();

                if (fieldName == "Name")
                {

                    myMergeField.Select();

                    wordApp.Selection.TypeText(txtSponsorResp.Text.ToString());

                }
                //other fields .....
            }
         }
         wordDoc.SaveAs("myFile.doc");
         wordApp.Documents.Open("myFile.doc");
         wordApp.Application.Quit();
</code>```

And here is my code to export a grid to another word document:

```<code>System.Web.UI.WebControls.GridView GridView1 = new System.Web.UI.WebControls.GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = bud; //where bud contains the datasource
            GridView1.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=Export-Grid.doc");
            Response.Charset = "";
            Response.ContentType = "application/vnd.word";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            GridView1.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.Flush();
            Response.End();
</code>```

How can I use both of them and export all the fields and the grids in one document using a word template?

答:
You will have to iterate over the field of the grid and insert them into the document using the aspose fields:

```<code> Document wordDoc = new Document(myDoc);
 foreach (GridViewRow row in GridView1.Rows)
  {
      foreach (Microsoft.Office.Interop.Word.Field myMergeField in wordDoc.Fields)
      {
          //iterate over fields and save to apose:
           doc.MyField = row.MyRow;
      }
   }
//save To Aspose
</code>```

Aspose must know which of the fields you are going to populate, if any.
Else, it won't export anything.

furthermore, word doesn't act kindly with grids. It won't let you export a table because it cannot create one, unlike excel.
instead of inserting an entire grid, just populate each and every field.

Title: C# export grid to word using template

Body:
I have created a word template with some number and text fields and I export my data from my application like this:

Object oMissing = System.Reflection.Missing.Value;

        Object oTemplatePath = "C:\\MyTemplate.dotx";

        Application wordApp = new Application();
        Document wordDoc = new Document();

        wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

        foreach (Microsoft.Office.Interop.Word.Field myMergeField in wordDoc.Fields)
        {

            Range rngFieldCode = myMergeField.Code;

            String fieldText = rngFieldCode.Text;

            if (fieldText.StartsWith(" MERGEFIELD"))
            {

                Int32 endMerge = fieldText.IndexOf("\\");

                Int32 fieldNameLength = fieldText.Length - endMerge;

                String fieldName = fieldText.Substring(11, endMerge - 11);

                fieldName = fieldName.Trim();

                if (fieldName == "Name")
                {

                    myMergeField.Select();

                    wordApp.Selection.TypeText(txtSponsorResp.Text.ToString());

                }
                //other fields .....
            }
         }
         wordDoc.SaveAs("myFile.doc");
         wordApp.Documents.Open("myFile.doc");
         wordApp.Application.Quit();

And here is my code to export a grid to another word document:

System.Web.UI.WebControls.GridView GridView1 = new System.Web.UI.WebControls.GridView();
            GridView1.AllowPaging = false;
            GridView1.DataSource = bud; //where bud contains the datasource
            GridView1.DataBind();
            Response.ClearContent();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment; filename=Export-Grid.doc");
            Response.Charset = "";
            Response.ContentType = "application/vnd.word";
            StringWriter sw = new StringWriter();
            HtmlTextWriter htw = new HtmlTextWriter(sw);

            GridView1.RenderControl(htw);
            Response.Write(sw.ToString());
            Response.Flush();
            Response.End();

How can I use both of them and export all the fields and the grids in one document using a word template?

Body:
You will have to iterate over the field of the grid and insert them into the document using the aspose fields:

 Document wordDoc = new Document(myDoc);
 foreach (GridViewRow row in GridView1.Rows)
  {
      foreach (Microsoft.Office.Interop.Word.Field myMergeField in wordDoc.Fields)
      {
          //iterate over fields and save to apose:
           doc.MyField = row.MyRow;
      }
   }
//save To Aspose

Aspose must know which of the fields you are going to populate, if any.
Else, it won't export anything.

furthermore, word doesn't act kindly with grids. It won't let you export a table because it cannot create one, unlike excel.
instead of inserting an entire grid, just populate each and every field.


问:
Date manipulation in React js
I am trying like this:

```<code>var db = new Date('2017-12-03T13:32:45.000Z');
console.log(db.getMonth());
</code>```

to get the month from given date but it gives the previous month.

Any suggestion...?

答:
This is the expected behaviour, it's zero-based so January = 0, February = 1 etc. If you want the current month, you need:

```<code>let db = new Date('2017-12-03T13:32:45.000Z');
console.log(db.getMonth() + 1);
</code>```

Reference: MDN

Title: Date manipulation in React js

Body:
I am trying like this:

var db = new Date('2017-12-03T13:32:45.000Z');
console.log(db.getMonth());

to get the month from given date but it gives the previous month.

Any suggestion...?

Body:
This is the expected behaviour, it's zero-based so January = 0, February = 1 etc. If you want the current month, you need:

let db = new Date('2017-12-03T13:32:45.000Z');
console.log(db.getMonth() + 1);

Reference: MDN


问:
C#: Conversion to TimeSpan is not retaining complete value
I get this issue while converting a string value to TimeSpan.

The values are like : "hrs:mm:ss:ms"
eg: "00:00:10:03"

While converting this value to TimeSpan, the leading part gets truncated.

Code :

```<code>TimeSpan span = new TimeSpan();
TimeSpan.TryParse("00:00:10:03" , out span);
</code>```

Output :
00:10:03

How can i retain the entire value in Timespan only

答:
TimeSpan.TryParse doesn`t recognize your format. Instead use

```<code>span = TimeSpan.ParseExact("00:00:10:03", @"hh\:mm\:ss\:ff", System.Globalization.CultureInfo.InvariantCulture);
</code>```

Body:
I get this issue while converting a string value to TimeSpan.

The values are like : "hrs:mm:ss:ms"
eg: "00:00:10:03"

While converting this value to TimeSpan, the leading part gets truncated.

Code :

TimeSpan span = new TimeSpan();
TimeSpan.TryParse("00:00:10:03" , out span);

Output :
00:10:03

How can i retain the entire value in Timespan only

Body:
TimeSpan.TryParse doesn`t recognize your format. Instead use

span = TimeSpan.ParseExact("00:00:10:03", @"hh\:mm\:ss\:ff", System.Globalization.CultureInfo.InvariantCulture);


问:
Visual Studio displaying errors even if projects build
I have a problem with Visual Studio on a C# solution. It displays totally random errors, but the projects build. Right now, I have 33 files with errors, and I can see red squiggly lines in all of them.

I tried cleaning / rebuilding the solution, closing Visual Studio and even restarting my computer. I can modify .cs files and I see the changes in the solution.

Does anyone have an idea about why it does that?

答:
I've just ran into this issue after reverting a git commit that added files back into my project.

Cleaning and rebuilding the project didn't work, even if I closed VS inbetween each step.

What eventually worked, was renaming the file to something else and changing it back again. :facepalm:


问:
I can't use SearchView

I have a problem when I try using SearchView in Android Studio. It's not working when I add SearchView, but when I remove it, my application runs normally. When I rebuild this project. There is a notification:

```<code>"$ adb shell am start -n
"com.example.nguyenkiemhung.myhomework/
com.example.nguyenkiemhung.myhomework.WelcomeActivity" -a
android.intent.action.MAIN -c
android.intent.category.LAUNCHER
Client not ready yet..Connected to process 4038
on device samsung-gt_i8552-cab17026"
</code>```

Can you tell me what problem in here? Thank you!

答:
This might be because you haven't defined your search view in the manifest. You have to declare your activity as searchable; something like this:

```<code><activity android:name=".WelcomeActivity" >
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data android:name="android.app.searchable"
               android:resource="@xml/searchable"/>
</activity>
</code>```

For more info, checkout the documentation here

Title: I can't use SearchView

Body:
I have a problem when I try using SearchView in Android Studio. It's not working when I add SearchView, but when I remove it, my application runs normally. When I rebuild this project. There is a notification:

"$ adb shell am start -n
"com.example.nguyenkiemhung.myhomework/
com.example.nguyenkiemhung.myhomework.WelcomeActivity" -a
android.intent.action.MAIN -c
android.intent.category.LAUNCHER
Client not ready yet..Connected to process 4038
on device samsung-gt_i8552-cab17026"

Can you tell me what problem in here? Thank you!

Body:
This might be because you haven't defined your search view in the manifest. You have to declare your activity as searchable; something like this:

<activity android:name=".WelcomeActivity" >
    <intent-filter>
        <action android:name="android.intent.action.SEARCH" />
    </intent-filter>
    <meta-data android:name="android.app.searchable"
               android:resource="@xml/searchable"/>
</activity>

For more info, checkout the documentation here


问:
How to Invoke Click on this Button in WebBrowser
Here is the HTML Button...

```<code><div class="submitBtnContainer">

<button class="nf-btn nf-btn-primary nf-btn-solid nf-btn-align-undefined nf-btn-oversize" type="button" autocomplete="off" tabindex="0" placeholder="planSelection_button_continue"><!-- react-text: 186 -->CONTINUE<!-- /react-text --></button>

</div>
</code>```

I'm try this code...

```<code>For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("submitBtnContainer") Then
Element.InvokeMember("click")
Return
End If
Next
</code>```

答:
You've got to click the button itself, you cannot click any other elements and expect it to work. Currently you are trying to click an  (anchor) element, also known as a link.

Iterate all <button> tags and check their text instead.

For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
    If Element.InnerText = "CONTINUE" Then
        Element.InvokeMember("click")
        Exit For 'Stop looping.
    End If
Next
```

Body:
Here is the HTML Button...

<button class="nf-btn nf-btn-primary nf-btn-solid nf-btn-align-undefined nf-btn-oversize" type="button" autocomplete="off" tabindex="0" placeholder="planSelection_button_continue">CONTINUE</button>

I'm try this code...

For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("a")
If Element.OuterHtml.Contains("submitBtnContainer") Then
Element.InvokeMember("click")
Return
End If
Next

Body:
You've got to click the button itself, you cannot click any other elements and expect it to work. Currently you are trying to click an <a> (anchor) element, also known as a link.

Iterate all <button> tags and check their text instead.

For Each Element As HtmlElement In WebBrowser1.Document.GetElementsByTagName("button")
    If Element.InnerText = "CONTINUE" Then
        Element.InvokeMember("click")
        Exit For 'Stop looping.
    End If
Next


问:
Largest and smallest number in an array
This works perfectly...but when I use foreach instead of for this doesn't works. I can't understand for and foreach are same.

```<code>namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10];
            Console.WriteLine("enter the array elements to b sorted");
            for(int i=0;i<10;i++)
            {
                array[i] = Convert.ToInt32(Console.ReadLine());
            }
            int smallest = array[0];
            for(int i=0;i<10;i++)

            {
                if(array[i]<smallest)
                {
                    smallest=array[i];

                }
            }
            int largest = array[9];
            for(int i=0;i<10;i++)
            {

                if (array[i] > largest)
                {
                    largest = array[i];

                }
            }
            Console.WriteLine("the smallest no is {0}", smallest);
            Console.WriteLine("the largest no is {0}", largest);
            Console.Read();

        }
    }
}
</code>```

答:
It is a long time. Maybe like this:</p>

```<code>    public int smallestValue(int[] values)
    {
        int smallest = int.MaxValue;

        for (int i = 0; i < values.Length; i++)
        {
            smallest = (values[i] < smallest ? values[i] : smallest);
        }

        return smallest;
    }

    public static int largestvalue(int[] values)
    {
        int largest = int.MinValue;

        for (int i = 0; i < values.Length; i++)
        {
            largest = (values[i] > largest ? values[i] : largest);
        }

        return largest;
    }
</code>```

Title: Largest and smallest number in an array

Body:
This works perfectly...but when I use foreach instead of for this doesn't works. I can't understand for and foreach are same.

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            int[] array = new int[10];
            Console.WriteLine("enter the array elements to b sorted");
            for(int i=0;i<10;i++)
            {
                array[i] = Convert.ToInt32(Console.ReadLine());
            }
            int smallest = array[0];
            for(int i=0;i<10;i++)

            {
                if(array[i]<smallest)
                {
                    smallest=array[i];

                }
            }
            int largest = array[9];
            for(int i=0;i<10;i++)
            {

                if (array[i] > largest)
                {
                    largest = array[i];

                }
            }
            Console.WriteLine("the smallest no is {0}", smallest);
            Console.WriteLine("the largest no is {0}", largest);
            Console.Read();

        }
    }
}

Body:
It is a long time. Maybe like this:

    public int smallestValue(int[] values)
    {
        int smallest = int.MaxValue;

        for (int i = 0; i < values.Length; i++)
        {
            smallest = (values[i] < smallest ? values[i] : smallest);
        }

        return smallest;
    }

    public static int largestvalue(int[] values)
    {
        int largest = int.MinValue;

        for (int i = 0; i < values.Length; i++)
        {
            largest = (values[i] > largest ? values[i] : largest);
        }

        return largest;
    }


问:
When to use generics in Swift
I studied about generics but i still have no understanding, why to use them, when we can use protocols instead?

For example, examine following function:

```<code>public static func delete<T>(entity: T, auth: Auth) -> Observable<Void> where T: MSRequestEntity, T: DictConvertable {

// function do something
    }
</code>```

Ok, we have generic entity T, that is conform to MSRequestEntity and DictConvertable.

But we can simply rewrite this like that:

```<code>public static func delete(entity: MSRequestEntity & DictConvertable, auth: Auth) -> Observable<Void> {

    // function do something
        }
</code>```

So, my question is, in what case should i use generics? All of situations i have imaging could easily be handled with protocols.

答:
In the case you have provided you are correct. It doesn't necessarily add anything by making it generic.

But take the example where you have some protocol MyProtocol and you want to create a function that takes two of these and returns a third. But the function only works if first and second are of the same type...

```<code>func combine(first: MyProtocol, second: MyProtocol) -> MyProtocol {
    // do some combining here.
}
</code>```

Now it's less well defined because first and second can be of different types here. The only thing that is required is that they conform to the protocol. And what is the return type?

Now consider...

```<code>function combine<T: MyProtocol>(first: T, second: T) -> T {
    // do some combining here
}
</code>```

Now the function is generic but what that adds is that still first and second must conform to the protocol. But now they must be of the same type. And the function will return another item of the same type as first and second.

In this case you definitely benefit from using generics rather than just the protocol.

Title: When to use generics in Swift

Body:
I studied about generics but i still have no understanding, why to use them, when we can use protocols instead?

For example, examine following function:

public static func delete<T>(entity: T, auth: Auth) -> Observable<Void> where T: MSRequestEntity, T: DictConvertable {

// function do something
    }

Ok, we have generic entity T, that is conform to MSRequestEntity and DictConvertable.

But we can simply rewrite this like that:

public static func delete(entity: MSRequestEntity & DictConvertable, auth: Auth) -> Observable<Void> {

    // function do something
        }

So, my question is, in what case should i use generics? All of situations i have imaging could easily be handled with protocols.

Body:
In the case you have provided you are correct. It doesn't necessarily add anything by making it generic.

But take the example where you have some protocol MyProtocol and you want to create a function that takes two of these and returns a third. But the function only works if first and second are of the same type...

func combine(first: MyProtocol, second: MyProtocol) -> MyProtocol {
    // do some combining here.
}

Now it's less well defined because first and second can be of different types here. The only thing that is required is that they conform to the protocol. And what is the return type?

Now consider...

function combine<T: MyProtocol>(first: T, second: T) -> T {
    // do some combining here
}

Now the function is generic but what that adds is that still first and second must conform to the protocol. But now they must be of the same type. And the function will return another item of the same type as first and second.

In this case you definitely benefit from using generics rather than just the protocol.


问:
matplotlib error - no module named tkinter
I tried to use the matplotlib package via Pycharm IDE on windows 10.
when I run this code:

```<code>from matplotlib import pyplot
</code>```

I get the following error:

```<code>ImportError: No module named 'tkinter'
</code>```

I know that in python 2.x it was called Tkinter, but that is not the problem - I just installed a brand new python 3.5.1.

EDIT: in addition, I also tried to import 'tkinter' and 'Tkinter' - neither of these worked (both returned the error message I mentioned).

答:
Sometimes (for example in osgeo4w distribution) tkinter is removed.

Try changing matplotlib backend editing matplotlibrc file located in [python install dir]/matplotlib/mpl-data/matplotlibrc changing The backend parameter from backend: TkAgg to something other like backend: Qt4Aggas described here: http://matplotlib.org/faq/usage_faq.html#what-is-a-backend

Body:
I tried to use the matplotlib package via Pycharm IDE on windows 10.
when I run this code:

from matplotlib import pyplot

I get the following error:

ImportError: No module named 'tkinter'

I know that in python 2.x it was called Tkinter, but that is not the problem - I just installed a brand new python 3.5.1.

EDIT: in addition, I also tried to import 'tkinter' and 'Tkinter' - neither of these worked (both returned the error message I mentioned).


问:
Codeigniter: Move one row from one table to another at one time
I'm kinda stuck here! I have to two tables free_members and domstic_members and I need to move selected rows from free_members tables to the domestic_members table. why I'm saying selected rows because of I at the end of every row in free_members tables there is an upgrade option which will move that row to the domestic_members table. I have the code but it's not working the way I want. right now what is happening is when I click on upgrade option it just copies the whole table records and sends it's to the other table. this here is the code

Controller

```<code>function upgradeprofile() {
    //  $this->load->database();
    $this->load->model('freemember_model');

    $this->freemember_model->upgrade();
}
</code>```

model

```<code>function upgrade() {
    $query = $this->db->get('free_members');
    foreach ($query->result() as $row) {
        $this->db->where('id', $member_id);
        $this->db->insert('domestic_members', $row);
    }
}
</code>```

View

```<code><center>  Search Member:
                    <input type="text" name ='search' id='search' placeholder="Search a member"/></center>
                    <input type="hidden" name ='limit_from' id='limit_from'/>
                    </form>
<br><center><button type="button" onclick="CallPrint1('background12')">Print</button>
                <div id="background12" class="box-body">
                  <table id="example1" class="table table-bordered table-striped">
                    <thead>
                      <tr>
                        <th>Sr#</th>
                        <th><center>Full Name</th>

                        <th><center>Mobile Number</th>
                         <th><center>Membership# / CNIC</th>
                        <th><center>Email Address</th>

                        <th><center>Province</th>
                        <th><center>District</th>
                        <th><center>Tehsil</th>
                        <th><center>Union Council</th>
<?php /*?>  <?php if($sessiondata['deletemembers']):?><?php */?>
     <?php if($sessiondata['username'] != 'bilal.sabir'):?>
                        <th><center>Delete</th>
  <?php endif;?>

    <?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
         <?php if($sessiondata['username'] != 'bilal.sabir'):?>
                        <th><center>Print</th>
                        <th><center>Edit</th>
                        <th><center>Change Pwd</th>
                        <th><center>Upgrade</th>
    <?php endif;?>

                      </tr>
                    </thead>
                    <tbody>
                    <?php $sr=0;?>
                      <?php foreach ($freemembers as $member): ?>
<tr><td><center><?php echo $sr+=1; ?></td><td><center><?php echo $member->first_name; ?></td>
<td><center><?php echo $member->mobile; ?></td><td><center><?php echo $member->cnic; ?></td>
<td><center><?php echo $member->email; ?></td>
<td><center><?php echo $member->province; ?></td><td><center><?php echo $member->district; ?></td><td><center><?php echo $member->tehsil; ?></td><td><center><?php echo $member->uc; ?></td>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
     <?php if($sessiondata['username'] != 'bilal.sabir'):?>

<td><center><a href="<?php echo base_url() . "index.php/admin/deletefreemember/" . $member->id; ?>">delete</a></td>
<?php endif;?>
  <?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
       <?php if($sessiondata['username'] != 'bilal.sabir'):?>
<td><center><a href="<?php echo base_url() . "index.php/admin/printcardfree/" . $member->id; ?>">print</a></td>

<td><center><a href="<?php echo base_url() . "index.php/admin/editprofilefree/" . $member->id; ?>">edit</a></td>
<td><center><a href="<?php echo base_url() . "index.php/admin/changepasswordfree/" . $member->id; ?>">change pwd</a></td>
<td><center><a href="<?php echo base_url() . "index.php/admin/upgradeprofile/" . $member->id; ?>">Upgrade</a></td>
<?php endif;?>
</tr>
<?php endforeach; ?>
                    </tbody>
                  </table>
</code>```

this is the view of my table free_members

答:
Based upon your View, you have this...

```<code>index.php/admin/upgradeprofile/" . $member->id
</code>```

So if $member->id = 100 the url will be

```<code>index.php/admin/upgradeprofile/100
</code>```

So you are passing a member_id as mentioned in your model code BUT you are not getting it nor are you using the where correctly.

So you need to get a handle on the member_id...

This is ONE Solution/idea...This relies on you providing a correctly validated integer... You need to always Check/validate your inputs...

Controller

```<code>function upgradeprofile($member_id) {
    // Need to check that $member_id is an integer
    // To be added by the OP

    $this->load->model('freemember_model');

    // $member_id is passed in via the URL.
    $this->freemember_model->upgrade($member_id);
}
</code>```

Model

```<code>function upgrade() {
    // Which member do we want to get from the free_members Table?
    $this->db->where('id', $member_id);
    $query = $this->db->get('free_members');
    // Did we get a result? i.e was a valid member id passed in?
    if($query !== false) {
        $row = $query->row();
        $this->db->insert('domestic_members', $row);
    } else {
       // Do nothing or handle the case where an illegal number was used...
    }
}
</code>```

Note: This code is not tested and is only to be used as a guide.
It can be refactored a number of ways but I am trying to keep it simple for now.

So please, do not just copy and paste this without at least "thinking" about what you are trying to do and how the code might be written to achieve it.

The main points here are...
1. You have to use a member id of some kind so you can retrieve the record for the free member so you can insert it into the other table.
2. You are providing this "member id" in the url so you need to extract it.
3. You can do that by either setting it as a parameter in the method being called... Or you can use segments ( look it up ).

So once you have the member id you can fetch the free member entry and insert it into the other table BUT What do you want to happen to the entry in the free members table because that is still going to be there and now you have two copies of the same information... Delete it?

If you need further explanation - ask.

One last point.
You should be making sure you fully understand what is you are doing and not just doing it because someone said to or you thought it was a good idea... Have a Good Reason and think of the implications...

Body:
I'm kinda stuck here! I have to two tables free_members and domstic_members and I need to move selected rows from free_members tables to the domestic_members table. why I'm saying selected rows because of I at the end of every row in free_members tables there is an upgrade option which will move that row to the domestic_members table. I have the code but it's not working the way I want. right now what is happening is when I click on upgrade option it just copies the whole table records and sends it's to the other table. this here is the code

Controller

function upgradeprofile() {
    //  $this->load->database();
    $this->load->model('freemember_model');

    $this->freemember_model->upgrade();
}

model

function upgrade() {
    $query = $this->db->get('free_members');
    foreach ($query->result() as $row) {
        $this->db->where('id', $member_id);
        $this->db->insert('domestic_members', $row);
    }
}

View

  Search Member:
                    <input type="text" name ='search' id='search' placeholder="Search a member"/>
                    <input type="hidden" name ='limit_from' id='limit_from'/>
                    </form>

<button type="button" onclick="CallPrint1('background12')">Print</button>

                        Sr#
                        Full Name

                        Mobile Number
                         Membership# / CNIC
                        Email Address

                        Province
                        District
                        Tehsil
                        Union Council
<?php /*?>  <?php if($sessiondata['deletemembers']):?><?php */?>
     <?php if($sessiondata['username'] != 'bilal.sabir'):?>
                        Delete
  <?php endif;?>

    <?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
         <?php if($sessiondata['username'] != 'bilal.sabir'):?>
                        Print
                        Edit
                        Change Pwd
                        Upgrade
    <?php endif;?>

                    <?php $sr=0;?>
                      <?php foreach ($freemembers as $member): ?>

<?php echo $sr+=1; ?>	<?php echo $member->first_name; ?>
<?php echo $member->mobile; ?>	<?php echo $member->cnic; ?>
<?php echo $member->email; ?>
<?php echo $member->province; ?>	<?php echo $member->district; ?>	<?php echo $member->tehsil; ?>	<?php echo $member->uc; ?>
<?php /*?> <?php if($sessiondata['deletemembers']):?><?php */?>
     <?php if($sessiondata['username'] != 'bilal.sabir'):?>

<a href="<?php echo base_url() . "index.php/admin/deletefreemember/" . $member->id; ?>">delete
<?php endif;?>
  <?php /*?><?php if($sessiondata['data_modification'] && $sessiondata['username'] != 'bilal.sabir' ):?><?php */?>
       <?php if($sessiondata['username'] != 'bilal.sabir'):?>
<a href="<?php echo base_url() . "index.php/admin/printcardfree/" . $member->id; ?>">print

<a href="<?php echo base_url() . "index.php/admin/editprofilefree/" . $member->id; ?>">edit
<a href="<?php echo base_url() . "index.php/admin/changepasswordfree/" . $member->id; ?>">change pwd
<a href="<?php echo base_url() . "index.php/admin/upgradeprofile/" . $member->id; ?>">Upgrade
<?php endif;?>

<?php endforeach; ?>

this is the view of my table free_members

Body:
Based upon your View, you have this...

index.php/admin/upgradeprofile/" . $member->id

So if $member->id = 100 the url will be

index.php/admin/upgradeprofile/100

So you are passing a member_id as mentioned in your model code BUT you are not getting it nor are you using the where correctly.

So you need to get a handle on the member_id...

This is ONE Solution/idea...This relies on you providing a correctly validated integer... You need to always Check/validate your inputs...

Controller

function upgradeprofile($member_id) {
    // Need to check that $member_id is an integer
    // To be added by the OP

    $this->load->model('freemember_model');

    // $member_id is passed in via the URL.
    $this->freemember_model->upgrade($member_id);
}

Model

function upgrade() {
    // Which member do we want to get from the free_members Table?
    $this->db->where('id', $member_id);
    $query = $this->db->get('free_members');
    // Did we get a result? i.e was a valid member id passed in?
    if($query !== false) {
        $row = $query->row();
        $this->db->insert('domestic_members', $row);
    } else {
       // Do nothing or handle the case where an illegal number was used...
    }
}

Note: This code is not tested and is only to be used as a guide.
It can be refactored a number of ways but I am trying to keep it simple for now.

So please, do not just copy and paste this without at least "thinking" about what you are trying to do and how the code might be written to achieve it.

The main points here are...
1. You have to use a member id of some kind so you can retrieve the record for the free member so you can insert it into the other table.
2. You are providing this "member id" in the url so you need to extract it.
3. You can do that by either setting it as a parameter in the method being called... Or you can use segments ( look it up ).

So once you have the member id you can fetch the free member entry and insert it into the other table BUT What do you want to happen to the entry in the free members table because that is still going to be there and now you have two copies of the same information... Delete it?

If you need further explanation - ask.

One last point.
You should be making sure you fully understand what is you are doing and not just doing it because someone said to or you thought it was a good idea... Have a Good Reason and think of the implications...


问:
listview in dialougbox shows nothing
i have this code to show listview in dialogbox frame of listview is shown but without any text in it(i have background colored listview)

```<code> public void shw(View view)
    {

        Dialog dialog=new Dialog(MainActivity.this);
        dialog.setTitle("Dialog Title");
        dialog.setContentView(R.layout.custadd);
        LayoutInflater inflater = getLayoutInflater();
        View convertView = (View) inflater.inflate(R.layout.custadd,null);
        ListView lv=(ListView) convertView.findViewById(R.id.listv);
        String s1[]={"sunday","monday","tuesday"};
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                R.layout.simple_list_item, s1 );
        lv.setAdapter(arrayAdapter);
        dialog.show();

    }
</code>```

答: Remove dialog.setContentView(R.layout.custadd); and set view for dialog when it get's inflated dialog.setContentView(convertView); and the issue will be resolved.

Title: listview in dialougbox shows nothing

Body:
i have this code to show listview in dialogbox frame of listview is shown but without any text in it(i have background colored listview)

 public void shw(View view)
    {

        Dialog dialog=new Dialog(MainActivity.this);
        dialog.setTitle("Dialog Title");
        dialog.setContentView(R.layout.custadd);
        LayoutInflater inflater = getLayoutInflater();
        View convertView = (View) inflater.inflate(R.layout.custadd,null);
        ListView lv=(ListView) convertView.findViewById(R.id.listv);
        String s1[]={"sunday","monday","tuesday"};
        ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                this,
                R.layout.simple_list_item, s1 );
        lv.setAdapter(arrayAdapter);
        dialog.show();

    }


问:
Radio button styles not getting changed
I'm trying to implement custom styles for radio buttons.

I've almost achieved it but issue is when i try to click on other radio button it is not getting highlighted.

I'm struck here please help.

.radio-radio-wrapper {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-radio-wrapper input[type='radio'] {
  display: none;
}

.radio-radio-wrapper label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
  cursor: pointer;
}

.radio-radio-wrapper input[type=radio]:checked+span>label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 4px;
  left: 4px;
  content: " ";
  display: block;
  background: #004c97;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div _ngcontent-c9="" class="col-lg-12 radioBlock">
  <span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Capacity" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio1">Capacity & Partial Service</label></span>
  </span><span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Prod" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio1">Full Network Service (No Capacity)</label></span>
  </span>
</div></code>```

答:
Here is the perfectly working code for your quick reference

.radio-radio-wrapper {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-radio-wrapper input[type='radio'] {
  display: none;
}

.radio-radio-wrapper label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
  cursor: pointer;
}

.radio-radio-wrapper input[type=radio]:checked+span>label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 11px;
  left: 12px;
  content: " ";
  display: block;
  background: #004c97;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div _ngcontent-c9="" class="col-lg-12 radioBlock">
  <span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Capacity" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio1">Capacity & Partial Service</label></span>
  </span><span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio2" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Prod" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio2">Full Network Service (No Capacity)</label></span>
  </span>
</div></code>```

Title: Radio button styles not getting changed

Body:
I'm trying to implement custom styles for radio buttons.

I've almost achieved it but issue is when i try to click on other radio button it is not getting highlighted.

I'm struck here please help.

.radio-radio-wrapper {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-radio-wrapper input[type='radio'] {
  display: none;
}

.radio-radio-wrapper label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
  cursor: pointer;
}

.radio-radio-wrapper input[type=radio]:checked+span>label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 4px;
  left: 4px;
  content: " ";
  display: block;
  background: #004c97;
}

            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Capacity" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            Capacity & Partial Service

            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Prod" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            Full Network Service (No Capacity)

Body:
Here is the perfectly working code for your quick reference

.radio-radio-wrapper {
  display: inline-block;
  position: relative;
  padding: 0 6px;
  margin: 10px 0 0;
}

.radio-radio-wrapper input[type='radio'] {
  display: none;
}

.radio-radio-wrapper label:before {
  content: " ";
  display: inline-block;
  position: relative;
  top: 5px;
  margin: 0 5px 0 0;
  width: 20px;
  height: 20px;
  border-radius: 11px;
  border: 2px solid #004c97;
  background-color: transparent;
  cursor: pointer;
}

.radio-radio-wrapper input[type=radio]:checked+span>label:after {
  border-radius: 11px;
  width: 12px;
  height: 12px;
  position: absolute;
  top: 11px;
  left: 12px;
  content: " ";
  display: block;
  background: #004c97;
}

<div _ngcontent-c9="" class="col-lg-12 radioBlock">
  <span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio1" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Capacity" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio1">Capacity &amp; Partial Service</label></span>
  </span><span _ngcontent-c9="" class="radio-radio-wrapper padding-radio">
            <input _ngcontent-c9="" id="radio2" name="radio" type="radio" ng-reflect-name="radio" ng-reflect-value="Prod" ng-reflect-model="Capacity" class="ng-untouched ng-pristine ng-valid">
            <span _ngcontent-c9="" class="radioLabel"><label _ngcontent-c9="" class="custom-control-description" for="radio2">Full Network Service (No Capacity)</label></span>
  </span>
</div>


问:
How I can group containers in docker-compose?
I'm using this docker-compose.yml.
And I wanna make simpler and inherrit configuration, if its possible.

```<code>version: '2'

services:
    nginx-proxy:
        image: jwilder/nginx-proxy
        container_name: nginx-proxy
        ports:
            - "80:80"
        volumes:
            - /var/run/docker.sock:/tmp/docker.sock:ro

    web_one:
        container_name: "web_one"
        build:
            context: ./
            dockerfile: web.docker
        volumes:
            - ./../one:/var/www

        environment:
            - VIRTUAL_HOST=whoami_one.local
        links:
            - app_one
    app_one:
        container_name: "app_one"
        build:
            context: ./
            dockerfile: app.docker
        volumes:
            - ./../one:/var/www
        links:
            - db

    web_two:
        container_name: "web_two"
        build:
            context: ./
            dockerfile: web.docker
        volumes:
            - ./../two:/var/www

        environment:
            - VIRTUAL_HOST=whoami_two.local
        links:
            - app_two
    app_two:
        container_name: "app_two"
        build:
            context: ./
            dockerfile: app.docker
        volumes:
            - ./../two:/var/www
        links:
            - db
</code>```

I have 15 sites with same configuration.
Can I make config simpler? Like this:

```<code>version: '2'

services:
    nginx-proxy:
        image: jwilder/nginx-proxy
        container_name: nginx-proxy
        ports:
            - "80:80"
        volumes:
            - /var/run/docker.sock:/tmp/docker.sock:ro

    one:
        extends:
            file: common-services.yml
        volumes:
            - ./../one:/var/www

        environment:
            - VIRTUAL_HOST=whoami_one.local

    two:
        extends:
            file: common-services.yml
        volumes:
            - ./../two:/var/www

        environment:
            - VIRTUAL_HOST=whoami_two.local
</code>```

Or better?

Thank you!

答:
UPDATE 31 Aug 2021 In the latest docker compose there's support for profiles https://docs.docker.com/compose/profiles/ so this problem would be perfectly solved by that new feature.

Another way is to create no-op services that depend on other services.
For example, in the following docker-compose.yml I have two namespaces, dev for services needed when developing the app, and metrics for services related to visualizing app metrics (since I'm not interested instarting those when developing).

```<code>version: "3"
services:
  dev:
    image: tianon/true
    depends_on: ["postgres", "keycloak"]
  metrics:
    image: monroe/noop
    depends_on: ["grafana"]
  postgres: ...
  keycloak: ...
  grafana: ...
</code>```

Body:
I'm using this docker-compose.yml.
And I wanna make simpler and inherrit configuration, if its possible.

version: '2'

services:
    nginx-proxy:
        image: jwilder/nginx-proxy
        container_name: nginx-proxy
        ports:
            - "80:80"
        volumes:
            - /var/run/docker.sock:/tmp/docker.sock:ro

    web_one:
        container_name: "web_one"
        build:
            context: ./
            dockerfile: web.docker
        volumes:
            - ./../one:/var/www

        environment:
            - VIRTUAL_HOST=whoami_one.local
        links:
            - app_one
    app_one:
        container_name: "app_one"
        build:
            context: ./
            dockerfile: app.docker
        volumes:
            - ./../one:/var/www
        links:
            - db

    web_two:
        container_name: "web_two"
        build:
            context: ./
            dockerfile: web.docker
        volumes:
            - ./../two:/var/www

        environment:
            - VIRTUAL_HOST=whoami_two.local
        links:
            - app_two
    app_two:
        container_name: "app_two"
        build:
            context: ./
            dockerfile: app.docker
        volumes:
            - ./../two:/var/www
        links:
            - db

I have 15 sites with same configuration.
Can I make config simpler? Like this:

version: '2'

services:
    nginx-proxy:
        image: jwilder/nginx-proxy
        container_name: nginx-proxy
        ports:
            - "80:80"
        volumes:
            - /var/run/docker.sock:/tmp/docker.sock:ro

    one:
        extends:
            file: common-services.yml
        volumes:
            - ./../one:/var/www

        environment:
            - VIRTUAL_HOST=whoami_one.local

    two:
        extends:
            file: common-services.yml
        volumes:
            - ./../two:/var/www

        environment:
            - VIRTUAL_HOST=whoami_two.local

Or better?

Thank you!

Body:
UPDATE 31 Aug 2021 In the latest docker compose there's support for profiles https://docs.docker.com/compose/profiles/ so this problem would be perfectly solved by that new feature.

Another way is to create no-op services that depend on other services.
For example, in the following docker-compose.yml I have two namespaces, dev for services needed when developing the app, and metrics for services related to visualizing app metrics (since I'm not interested instarting those when developing).

version: "3"
services:
  dev:
    image: tianon/true
    depends_on: ["postgres", "keycloak"]
  metrics:
    image: monroe/noop
    depends_on: ["grafana"]
  postgres: ...
  keycloak: ...
  grafana: ...


问:
How to concat a string to a windows batch command variable in Jenkins?
I'm getting our application version value via curl command and set it into a app_version variable:

```<code>for /f "tokens=*" %%a in (
  'curl myApp-installer:8080/info/version'
) do (
  set app_version=%%a
)
</code>```

This works for me and I'm getting the value as expected.
Later on, I'm using this value as a parameter to build our application installer for overriding the application version.

My application version syntax should be: Beta - version %app_version%.
How can I concat the app_version variable to the "Beta - version" String?

Whatever I tried I got 2 strings like that: "Beta - version" "10.1.2"

答:
The quotes are actually literals within your variable values. You simply need to define the variables without the quotes in the value.

This is easily done when the value is coming from a FOR variable - you can use the ~ modifier. Enter for /? or help for, and then look at the bottom of the help output for a brief description of all available modifiers.

```<code>for /f "tokens=*" %%a in (
  'curl myApp-installer:8080/info/version'
) do (
  set "app_version=%%~a"
)
</code>```

Note that the quotes in my code above surround the entire assignment - structured like this, they do not get included in the value. This construct generally protects against poison characters, (not an issue when expanding FOR variables), and also prevents accidental trailing white-space characters from being included in the value - all characters after the last quote are ignored by the SET command.

Body:
I'm getting our application version value via curl command and set it into a app_version variable:

for /f "tokens=*" %%a in (
  'curl myApp-installer:8080/info/version'
) do (
  set app_version=%%a
)

This works for me and I'm getting the value as expected.
Later on, I'm using this value as a parameter to build our application installer for overriding the application version.

My application version syntax should be: Beta - version %app_version%.
How can I concat the app_version variable to the "Beta - version" String?

Whatever I tried I got 2 strings like that: "Beta - version" "10.1.2"

Body:
The quotes are actually literals within your variable values. You simply need to define the variables without the quotes in the value.

This is easily done when the value is coming from a FOR variable - you can use the ~ modifier. Enter for /? or help for, and then look at the bottom of the help output for a brief description of all available modifiers.

for /f "tokens=*" %%a in (
  'curl myApp-installer:8080/info/version'
) do (
  set "app_version=%%~a"
)

Note that the quotes in my code above surround the entire assignment - structured like this, they do not get included in the value. This construct generally protects against poison characters, (not an issue when expanding FOR variables), and also prevents accidental trailing white-space characters from being included in the value - all characters after the last quote are ignored by the SET command.


问:
plist.info in flash cs5
Is there any way I can create/edit a plist.info file in flash cs5 while developing for the iPhone?  Where can I find the available plist tags?</p>

答:
You should be able to use the ActionScript editor in CS5 to write your XML code.  Just save the file as plist.as, and change the file name to plist.info when it is finished.

As for the available tags: Check out Apple's DTD for PropertyList files.

(btw I can't help but wonder why Adobe never thought of including a "real" XML editor into Flash CS5... But then again, the IDE is completely horrible to code in, anyway - there has to be some incentive for people to buy Flash/Flex Builder, right?

Title: plist.info in flash cs5


问:
PHP Laravel 5 elseif not behaving as expected
I have 2 variables that can either be filled with a value, be 'all' or be 'null'

Variable 1 is $type and variable 2 is $brand.

So if the user selects a type and a brand I want to query the cars accordingly. If the users selects nothing then the value is 'null' if the user selects 'all' then the value is 'all' obviously.

I've wrote the 4 scenario's out in commented code as follows:

```<code>//brand                 and type                -> get cars of brand and type
//brand = all or null   and type = all or null  -> get all cars
//brand                 and type = all or null  -> get cars of all types and brand
//brand = all or null   and type                -> get cars of all brands and type
</code>```

this is my if structure:

```<code>if ($brand && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
                ['type', '=', $type]
            ])->get();
} elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {
            $cars = Cars::where('cost', '<=', $budget)
                ->get();
} elseif($brand && $type == 'all' || $type === null) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
            ])->get();
} elseif ($brand == 'all' || $brand === null && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['type', '=', $type]
            ])->get();
}
</code>```

Now when I check the value of $brand it's filled with Audi and $type is null.

Can someone please explain to me why I get the result of the first elseif?
So my code thinks this is the case:

elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {

Which is weird because $brand is neither 'all' or 'null' since it's 'Audi'

Hope it's clear.

答:
You are really making your life harder. You have 2 independent variables affecting two independent conditions, there's no reason you should mix them in the same conditional.</p>

```<code>$wheres = [  ['cost', '<=', $budget] ];
if ($brand !== "all" && $brand !== null) {
   $wheres[] = [ "brand", "=", $brand ];
}
if ($type !== "all" && $type !== null) {
   $wheres[] = [ "type", "=", $type ];
}
$cars = Cars::where($wheres);
</code>```

Body:
I have 2 variables that can either be filled with a value, be 'all' or be 'null'

Variable 1 is $type and variable 2 is $brand.

So if the user selects a type and a brand I want to query the cars accordingly. If the users selects nothing then the value is 'null' if the user selects 'all' then the value is 'all' obviously.

I've wrote the 4 scenario's out in commented code as follows:

//brand                 and type                -> get cars of brand and type
//brand = all or null   and type = all or null  -> get all cars
//brand                 and type = all or null  -> get cars of all types and brand
//brand = all or null   and type                -> get cars of all brands and type

this is my if structure:

if ($brand && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
                ['type', '=', $type]
            ])->get();
} elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {
            $cars = Cars::where('cost', '<=', $budget)
                ->get();
} elseif($brand && $type == 'all' || $type === null) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['brand', '=', $brand],
            ])->get();
} elseif ($brand == 'all' || $brand === null && $type) {
            $cars = Cars::where([
                ['cost', '<=', $budget],
                ['type', '=', $type]
            ])->get();
}

Now when I check the value of $brand it's filled with Audi and $type is null.

Can someone please explain to me why I get the result of the first elseif?
So my code thinks this is the case:

elseif($brand == 'all' || $brand === null && $type == 'all' || $type === null) {

Which is weird because $brand is neither 'all' or 'null' since it's 'Audi'

Hope it's clear.

Body:
You are really making your life harder. You have 2 independent variables affecting two independent conditions, there's no reason you should mix them in the same conditional.

$wheres = [  ['cost', '<=', $budget] ];
if ($brand !== "all" && $brand !== null) {
   $wheres[] = [ "brand", "=", $brand ];
}
if ($type !== "all" && $type !== null) {
   $wheres[] = [ "type", "=", $type ];
}
$cars = Cars::where($wheres);


问:
Webservice works on Android but not on IOS
I have written the below service in Angular 4. When I try to consume it
on Android it works, but on IOS I get error status: 0  for URL: null
Need to know if something is wrong in web-service code? </p>

```<code>getConversationData(userText : string){

    let userName = 'XYZ'
    let meetingType = 'ABC'
    let url = 'serverURL' + '/Conversation'

    return this.http.post(
      url,
      {
        headers : {'Content-Type': 'application/json charset=UTF-8',
                        'Accept': 'application/json'},
        "message" : userText,
        "username" : userName,
        "MeetingType" : meetingType
      },

    ).map(response => response.json())
  }
</code>```

答:
WkWebView enforces CORS unlike the older UIWebView in IOS. Ionic is switching to this as a part of IOS 11 changes.

You will need to ensure your server-side API returns Origin: http:localhost:8080 in the response header.(depends on the technology you are using to implement API).

Or use ionic-native/http plugin to get around it.

Check docs WKWebView Documentation here.

Body:
I have written the below service in Angular 4. When I try to consume it
on Android it works, but on IOS I get error status: 0  for URL: null
Need to know if something is wrong in web-service code?

getConversationData(userText : string){

    let userName = 'XYZ'
    let meetingType = 'ABC'
    let url = 'serverURL' + '/Conversation'

    return this.http.post(
      url,
      {
        headers : {'Content-Type': 'application/json charset=UTF-8',
                        'Accept': 'application/json'},
        "message" : userText,
        "username" : userName,
        "MeetingType" : meetingType
      },

    ).map(response => response.json())
  }


问:
Field shouldn't be populated in HTTP Request
How can I specify in ASP.NET model object that certain field should not be populated when the user makes an Post request?
The other fields should be populated.

The solution i came up with it is to override the value, but i'm looking for more "clean" solution.

答:
It sounds like you are using that model for more than just one thing.
If that is the case, I suggest you create a separate model for POST, one that only includes the fields you want to see.

If you use most of the model properties somewhere else then you can have a base class where you share whatever is common and keep the differences in classes which extend the base one.

The main idea here is to make sure that your models only include the properties you want to see and nothing else.


问:
Generate a simple table with javascript
I dont understand why but I'm getting the wrong body structure. You can see on the image that I get a

 and I dont have that on javascript.

I just want a table with 3 columns and up to 10 rows.

What's happening?

My generated html

JavaScript

```<code>  $('#selectMRPC').change(function () {
    //fetch data
    var mrpc = $(this).find('option:selected').data('mrpc');

    $('#paramBody').empty();
    for (var i = 1; i <= 10; i++) {
        var field = mrpc["field" + i];
        if (field !== undefined) {
            var parsedField = field.split('_');
            var value = parsedField[0];
            var type = parsedField[1];

            switch (type) {
                case  "S":
                    type = "text";
                    if (value === '""')
                        value = null;
                    break;
                case "B":
                    type = "checkbox";
                    break;
                case "N":
                    type = "number";
                    value = parseInt(value);
                    break;
                case "D":
                    type = "number";
                    value = parseInt(value);
                    if (value === '""')
                        value = null;
                    break;
            }
            $('#paramBody').append('<tr>');
            $('#paramBody').append('<td>' + i + '</td>');
            $('#paramBody').append('<td>' + type + '</td>');
            $('#paramBody').append('<td><input name="Fields" type="' + type + '">').val(value);
            $('#paramBody').append('</tr>');

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

答:
store everything in a var then add it to dom : </p>

```<code>var html = "";

html += '<tr>';
html += '<td>' + i + '</td>';
html += '<td>' + type + '</td>';
html += '<td><input name="Fields" type="' + type + '" value="' + value +'">';
html += '</tr>';

$('#paramBody').append(html);
</code>```

Title: Generate a simple table with javascript

Body:
I dont understand why but I'm getting the wrong body structure. You can see on the image that I get a

 and I dont have that on javascript.

I just want a table with 3 columns and up to 10 rows.

What's happening?

My generated html

JavaScript

  $('#selectMRPC').change(function () {
    //fetch data
    var mrpc = $(this).find('option:selected').data('mrpc');

    $('#paramBody').empty();
    for (var i = 1; i <= 10; i++) {
        var field = mrpc["field" + i];
        if (field !== undefined) {
            var parsedField = field.split('_');
            var value = parsedField[0];
            var type = parsedField[1];

            switch (type) {
                case  "S":
                    type = "text";
                    if (value === '""')
                        value = null;
                    break;
                case "B":
                    type = "checkbox";
                    break;
                case "N":
                    type = "number";
                    value = parseInt(value);
                    break;
                case "D":
                    type = "number";
                    value = parseInt(value);
                    if (value === '""')
                        value = null;
                    break;
            }
            $('#paramBody').append('
');
            $('#paramBody').append('' + i + '	');
            $('#paramBody').append('' + type + '	');
            $('#paramBody').append('<input name="Fields" type="' + type + '">').val(value);
            $('#paramBody').append('
');

        }
    }
});

Body:
store everything in a var then add it to dom :

var html = "";

html += '<tr>';
html += '<td>' + i + '</td>';
html += '<td>' + type + '</td>';
html += '<td><input name="Fields" type="' + type + '" value="' + value +'">';
html += '</tr>';

$('#paramBody').append(html);


问:
why "abc" + null results abcnull
why "abc" + null  results abcnull

```<code>String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);
</code>```

Result: abcnull

答:
```<code>String s = "a" + null;
</code>```

compiler understands it as

```<code>String s = "a" + String.valueOf(null)
</code>```

so

```<code>String s = "a" + String.valueOf(null)/* null*/  = "anull";
</code>```

In your example

```<code>String s3 = String.valueOf(s1) + String.valueOf(s2);
s3 = "abc" + "null" // absnull
</code>```

Title: why "abc" + null results abcnull

Body:
why "abc" + null  results abcnull

String s1 = "abc";
String s2 = null;
String s3 = s1+ s2;

System.out.println(s3);

Result: abcnull

Body:
String s = "a" + null;

compiler understands it as

String s = "a" + String.valueOf(null)

so

String s = "a" + String.valueOf(null)/* null*/  = "anull";

In your example

String s3 = String.valueOf(s1) + String.valueOf(s2);
s3 = "abc" + "null" // absnull


问:
Mac OSX: LoadModule wsgi_module not working as mentioned in docs
I upgraded apache from 2.4.25 to 2.4.29 due to security reasons in Mac OSX.
Also installed mod_wsgi via pip.

Now facing difficulty while restarting the apache server!

I ran this command as per the mod_wsgi docs,

```<code>> mod_wsgi-express module-config
LoadModule wsgi_module "/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so"
WSGIPythonHome "/System/Library/Frameworks/Python.framework/Versions/2.7"
</code>```

Copied the above two lines in apache.conf file and tried to start the apache server but getting the following error:

```<code>> sudo apachectl start
/usr/local/apache/bin/apachectl: line 79: 51863 Illegal instruction: 4  $HTTPD -k $ARGV
</code>```

Any help would be appreciated. Thanks!

EDIT as per Graham answer:

```<code># I upgraded the mod_wsgi
> sudo pip install --upgrade --no-cache-dir mod_wsgi
Collecting mod_wsgi
  Downloading mod_wsgi-4.5.21.tar.gz (2.5MB)
    100% |████████████████████████████████| 2.5MB 2.1MB/s
Installing collected packages: mod-wsgi
  Found existing installation: mod-wsgi 4.5.20
    Uninstalling mod-wsgi-4.5.20:
      Successfully uninstalled mod-wsgi-4.5.20
  Running setup.py install for mod-wsgi ... done
Successfully installed mod-wsgi-4.5.21
</code>```

But when i tried:

```<code>> mod_wsgi-express start-server
Traceback (most recent call last):
  File "/Library/WebServer/Documents/DSFENV/bin/mod_wsgi-express", line 11, in <module>
    load_entry_point('mod-wsgi==4.5.21', 'console_scripts', 'mod_wsgi-express')()
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/site-packages/mod_wsgi/server/__init__.py", line 3484, in main
    cmd_start_server(args)
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/site-packages/mod_wsgi/server/__init__.py", line 3332, in cmd_start_server
    config = _cmd_setup_server('start-server', args, vars(options))
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/site-packages/mod_wsgi/server/__init__.py", line 2999, in _cmd_setup_server
    language, encoding = locale.getdefaultlocale()
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/locale.py", line 543, in getdefaultlocale
    return _parse_localename(localename)
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/locale.py", line 475, in _parse_localename
    raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8
</code>```

getting the above error.
Also I have installed apache 2.4.29 following this blog:

2nd Edit
I have resolved ValueError: unknown locale: UTF-8, now the output of mod_wsgi-express start-server shows:

```<code>> mod_wsgi-express start-server
Server URL         : http://localhost:8000/
Server Root        : /tmp/mod_wsgi-localhost:8000:501
Server Conf        : /tmp/mod_wsgi-localhost:8000:501/httpd.conf
Error Log File     : /tmp/mod_wsgi-localhost:8000:501/error_log (warn)
Request Capacity   : 5 (1 process * 5 threads)
Request Timeout    : 60 (seconds)
Startup Timeout    : 15 (seconds)
Queue Backlog      : 100 (connections)
Queue Timeout      : 45 (seconds)
Server Capacity    : 20 (event/worker), 20 (prefork)
Server Backlog     : 500 (connections)
Locale Setting     : en_US.UTF-8
</code>```

But when I try to do config test, still showing the same error:

```<code>> sudo apachectl configtest
/usr/local/apache/bin/apachectl: line 79: 53944 Illegal instruction: 4  $HTTPD -t
</code>```

xcode version:

```<code>> xcodebuild -version
Xcode 8.3.2
Build version 8E2002
</code>```

3rd EDIT as per comments:

```<code>> /usr/local/apache/bin/httpd
Illegal instruction: 4

> /Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so
-bash: /Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so: cannot execute binary file

> sys.prefix
'/System/Library/Frameworks/Python.framework/Versions/2.7'

> sys.version
'2.7.10 (default, Feb  7 2017, 00:08:15) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]'
</code>```

I followed this blog to install Apache 2.4.29:
http://mac-dev-env.patrickbougie.com/apache/

--with-ssl option as we need to https for the website.

4th EDIT:

```<code>> file /usr/local/apache/bin/httpd
/usr/local/apache/bin/httpd: Mach-O 64-bit executable x86_64

> file /Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so
/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so: Mach-O universal binary with 2 architectures: [x86_64: Mach-O 64-bit bundle x86_64] [i386: Mach-O bundle i386]
/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so (for architecture x86_64):   Mach-O 64-bit bundle x86_64
/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so (for architecture i386): Mach-O bundle i386
</code>```

Please let me know how to proceed forward.

答:
If you have updated your Apache installation in some way, usually the mod_wsgi.so binary from an older release should still work as Apache maintains ABI compatibility across patch level updates.

If it isn't working, then you may need to re-build mod_wsgi. If there is no newer version of mod_wsgi, you will need to force a full re-build to ensure cached binaries from pip cache are not used.

```<code>pip install --upgrade --no-cache-dir mod_wsgi
</code>```

Next problem though is if you have upgraded to Xcode 9.1, Apple have further broken things by completely removing apxs, meaning that my prior workaround for Apple brokeness no longer works. In this case you need to ensure you are installing mod_wsgi 4.5.21 or later. That version only just got released with fixes to accomodate for Xcode 9.1

So try that pip command above and make sure mod_wsgi-express still works by running:

```<code>mod_wsgi-express start-server
</code>```

Then validate configuration snippet to use in Apache config by running again:

```<code>mod_wsgi-express module-config
</code>```

If still issues with main Apache, then ensure you do a complete stop of Apache and then a start, and not just restart. Let me know how that all goes.

UPDATE 1

Above presumes you were using Apple supplied Apache in respect of Xcode 9.1 comments. You seem to be using your own Apache, maybe form Homebrew. Still try the same thing.

Body:
I upgraded apache from 2.4.25 to 2.4.29 due to security reasons in Mac OSX.
Also installed mod_wsgi via pip.

Now facing difficulty while restarting the apache server!

I ran this command as per the mod_wsgi docs,

> mod_wsgi-express module-config
LoadModule wsgi_module "/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so"
WSGIPythonHome "/System/Library/Frameworks/Python.framework/Versions/2.7"

Copied the above two lines in apache.conf file and tried to start the apache server but getting the following error:

> sudo apachectl start
/usr/local/apache/bin/apachectl: line 79: 51863 Illegal instruction: 4  $HTTPD -k $ARGV

Any help would be appreciated. Thanks!

EDIT as per Graham answer:

# I upgraded the mod_wsgi
> sudo pip install --upgrade --no-cache-dir mod_wsgi
Collecting mod_wsgi
  Downloading mod_wsgi-4.5.21.tar.gz (2.5MB)
    100% |████████████████████████████████| 2.5MB 2.1MB/s
Installing collected packages: mod-wsgi
  Found existing installation: mod-wsgi 4.5.20
    Uninstalling mod-wsgi-4.5.20:
      Successfully uninstalled mod-wsgi-4.5.20
  Running setup.py install for mod-wsgi ... done
Successfully installed mod-wsgi-4.5.21

But when i tried:

> mod_wsgi-express start-server
Traceback (most recent call last):
  File "/Library/WebServer/Documents/DSFENV/bin/mod_wsgi-express", line 11, in <module>
    load_entry_point('mod-wsgi==4.5.21', 'console_scripts', 'mod_wsgi-express')()
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/site-packages/mod_wsgi/server/__init__.py", line 3484, in main
    cmd_start_server(args)
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/site-packages/mod_wsgi/server/__init__.py", line 3332, in cmd_start_server
    config = _cmd_setup_server('start-server', args, vars(options))
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/site-packages/mod_wsgi/server/__init__.py", line 2999, in _cmd_setup_server
    language, encoding = locale.getdefaultlocale()
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/locale.py", line 543, in getdefaultlocale
    return _parse_localename(localename)
  File "/Library/WebServer/Documents/DSFENV/lib/python2.7/locale.py", line 475, in _parse_localename
    raise ValueError, 'unknown locale: %s' % localename
ValueError: unknown locale: UTF-8

getting the above error.
Also I have installed apache 2.4.29 following this blog:

2nd Edit
I have resolved ValueError: unknown locale: UTF-8, now the output of mod_wsgi-express start-server shows:

> mod_wsgi-express start-server
Server URL         : http://localhost:8000/
Server Root        : /tmp/mod_wsgi-localhost:8000:501
Server Conf        : /tmp/mod_wsgi-localhost:8000:501/httpd.conf
Error Log File     : /tmp/mod_wsgi-localhost:8000:501/error_log (warn)
Request Capacity   : 5 (1 process * 5 threads)
Request Timeout    : 60 (seconds)
Startup Timeout    : 15 (seconds)
Queue Backlog      : 100 (connections)
Queue Timeout      : 45 (seconds)
Server Capacity    : 20 (event/worker), 20 (prefork)
Server Backlog     : 500 (connections)
Locale Setting     : en_US.UTF-8

But when I try to do config test, still showing the same error:

> sudo apachectl configtest
/usr/local/apache/bin/apachectl: line 79: 53944 Illegal instruction: 4  $HTTPD -t

xcode version:

> xcodebuild -version
Xcode 8.3.2
Build version 8E2002

3rd EDIT as per comments:

> /usr/local/apache/bin/httpd
Illegal instruction: 4

> /Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so
-bash: /Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so: cannot execute binary file

> sys.prefix
'/System/Library/Frameworks/Python.framework/Versions/2.7'

> sys.version
'2.7.10 (default, Feb  7 2017, 00:08:15) \n[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.34)]'

I followed this blog to install Apache 2.4.29:
http://mac-dev-env.patrickbougie.com/apache/

--with-ssl option as we need to https for the website.

4th EDIT:

> file /usr/local/apache/bin/httpd
/usr/local/apache/bin/httpd: Mach-O 64-bit executable x86_64

> file /Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so
/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so: Mach-O universal binary with 2 architectures: [x86_64: Mach-O 64-bit bundle x86_64] [i386: Mach-O bundle i386]
/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so (for architecture x86_64):   Mach-O 64-bit bundle x86_64
/Library/Python/2.7/site-packages/mod_wsgi/server/mod_wsgi-py27.so (for architecture i386): Mach-O bundle i386

Please let me know how to proceed forward.

Body:
If you have updated your Apache installation in some way, usually the mod_wsgi.so binary from an older release should still work as Apache maintains ABI compatibility across patch level updates.

If it isn't working, then you may need to re-build mod_wsgi. If there is no newer version of mod_wsgi, you will need to force a full re-build to ensure cached binaries from pip cache are not used.

pip install --upgrade --no-cache-dir mod_wsgi

Next problem though is if you have upgraded to Xcode 9.1, Apple have further broken things by completely removing apxs, meaning that my prior workaround for Apple brokeness no longer works. In this case you need to ensure you are installing mod_wsgi 4.5.21 or later. That version only just got released with fixes to accomodate for Xcode 9.1

So try that pip command above and make sure mod_wsgi-express still works by running:

mod_wsgi-express start-server

Then validate configuration snippet to use in Apache config by running again:

mod_wsgi-express module-config

If still issues with main Apache, then ensure you do a complete stop of Apache and then a start, and not just restart. Let me know how that all goes.

UPDATE 1

Above presumes you were using Apple supplied Apache in respect of Xcode 9.1 comments. You seem to be using your own Apache, maybe form Homebrew. Still try the same thing.


问:
what does this bash script line of code mean
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

```<code>Path=`echo $line | awk -F '|' '{print $1}'`
</code>```

答:
```<code>echo $line | awk -F '|' '{print $1}'
</code>```

Explanation:

```<code>echo -> display a line of text
$line -> parameter expansion read the line
| -> A  pipeline is a sequence of one or more commands separated by one of the control operators |
awk -> Invoke awk program
-F '|' -> Field separator as | for the data feed
'{print $1}' -> Print the first field
</code>```

Example

```<code>echo 'a|b|c' | awk -F '|' '{print $1}'
</code>```

will print a

Body:
I am new to shell scripting and I found following line of code in a given script.

Could someone explain me with an example what the following line of code means

Path=`echo $line | awk -F '|' '{print $1}'`

Body:
echo $line | awk -F '|' '{print $1}'

Explanation:

echo -> display a line of text
$line -> parameter expansion read the line
| -> A  pipeline is a sequence of one or more commands separated by one of the control operators |
awk -> Invoke awk program
-F '|' -> Field separator as | for the data feed
'{print $1}' -> Print the first field

Example

echo 'a|b|c' | awk -F '|' '{print $1}'

will print a


问:
C++ how to infer the Callable's type (arguments list & return value) in a template
Basically what I want to do, is to make a function template, that takes any Callable (function type / lambda / Functor) and returns a lambda-taking-the-similar-args-list and returning the type of original's return type</p>

```<code>#include <iostream>

int func(int a,float b) {
    return a+b;
}

struct callable {
    int operator() (int a, float b) {
        return a+b;
    }
};

template <typename RV, typename... Args>
auto getLambdaFromCallable(RV(&func)(Args...)) {
    auto l = [&](Args... args) -> RV {
        return func(args...);
    };

    return l;
}

int main() {
    auto f = getLambdaFromCallable(func);
    std::cout << f(1,2.f);
    std::cout << " " << typeid(f).name();

    auto f2 = getLambdaFromCallable(callable{}); // doesn't work
    callable{}(1,2); // works

    auto lambdaTest = [](int a, float b) -> int {
        return a+b;
    };
    auto f3 = getLambdaFromCallable(lambdaTest);
}
</code>```

答:
You can change getLambdaFromCallable to:

```<code>template <typename F>
auto getLambdaFromFunction(const F& func) {
  auto l = [&](auto&&... args)
    -> decltype(func(std::forward<decltype(args)>(args)...)) {
    return func(std::forward<decltype(args)>(args)...);
  };

  return l;
}
</code>```

The reasoning behind this is that since you cannot get an exhaustive list of argument you can call a function object with (there might be multiple overloads in the first place), you might as well use a generic lambda which accepts everything and forward it to the callable.

To elaborate more about how this works:

The auto&&... part gets converted to a template argument list on the lambda's call operator.

F is deduced to whatever you called the getLambdaFromFunction with (without the const and reference but that can be changed if needed).

decltype(args) is just there to use std::forward which in turn is there to correctly forward both lvalue and rvalue references, see std::forward for more details.

The generated lambda object will look like this:

```<code>template <typename F>
class generatedLambda
{
public:
  template <typename... Args>
  auto operator()(Args&&... args) -> decltype(func(std::forward<decltype(args)>(args)...))
  {
    return func(std::forward<decltype(args)>(args)...);
  }

private:
  F     func;
};
</code>```

Body:
Basically what I want to do, is to make a function template, that takes any Callable (function type / lambda / Functor) and returns a lambda-taking-the-similar-args-list and returning the type of original's return type

#include <iostream>

int func(int a,float b) {
    return a+b;
}

struct callable {
    int operator() (int a, float b) {
        return a+b;
    }
};

template <typename RV, typename... Args>
auto getLambdaFromCallable(RV(&func)(Args...)) {
    auto l = [&](Args... args) -> RV {
        return func(args...);
    };

    return l;
}

int main() {
    auto f = getLambdaFromCallable(func);
    std::cout << f(1,2.f);
    std::cout << " " << typeid(f).name();

    auto f2 = getLambdaFromCallable(callable{}); // doesn't work
    callable{}(1,2); // works

    auto lambdaTest = [](int a, float b) -> int {
        return a+b;
    };
    auto f3 = getLambdaFromCallable(lambdaTest);
}

Body:
You can change getLambdaFromCallable to:

template <typename F>
auto getLambdaFromFunction(const F& func) {
  auto l = [&](auto&&... args)
    -> decltype(func(std::forward<decltype(args)>(args)...)) {
    return func(std::forward<decltype(args)>(args)...);
  };

  return l;
}

The reasoning behind this is that since you cannot get an exhaustive list of argument you can call a function object with (there might be multiple overloads in the first place), you might as well use a generic lambda which accepts everything and forward it to the callable.

To elaborate more about how this works:

The auto&&... part gets converted to a template argument list on the lambda's call operator.

F is deduced to whatever you called the getLambdaFromFunction with (without the const and reference but that can be changed if needed).

decltype(args) is just there to use std::forward which in turn is there to correctly forward both lvalue and rvalue references, see std::forward for more details.

The generated lambda object will look like this:

template <typename F>
class generatedLambda
{
public:
  template <typename... Args>
  auto operator()(Args&&... args) -> decltype(func(std::forward<decltype(args)>(args)...))
  {
    return func(std::forward<decltype(args)>(args)...);
  }

private:
  F     func;
};


问:
Shiny using the selectizeInput load(query, callback) configuration
I am looking to use the selectizeInput() input control to allow a user to search for an address using the google API, so when a user starts typing an address into the control, the selectizeInput() function will then return a list of addresses, very similar to the Google Maps address search box.

I have found notes on the selectize.js GitHub, possibly using the load(query, callback) option to call the Google API using Javascript. However, I am a complete novice with Javascript so unsure how to go about this, and even whether its possible using the Shiny implementation of selectize.

Any feedback is much appreciated.

答:
Figured this out eventually.

Using the documentation here, built a custom input object through Javascript, which I was then able to take advantage of the Google Maps Javascript API.