问:
Unpack dict from list where key is not None
Trying to unpack the dicts which are not None from a list:

```<code>In [4]: unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]
</code>```

Tried a dict comprehension

```<code>In [5]: {key: value for (key, value) in unpack_dict if (key, value) is not None}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-ec0e44b95586> in <module>()
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

<ipython-input-5-ec0e44b95586> in <dictcomp>(.0)
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

ValueError: not enough values to unpack (expected 2, got 1)
</code>```

And a list comprehension:

```<code>In [6]: {**[x for x in [unpack_dict] if x is not None]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ac36898d39a1> in <module>()
----> 1 {**[x for x in [unpack_dict] if x is not None]}

TypeError: 'list' object is not a mapping
</code>```

Expected result:

```<code>{'key': 'a', 'key_2': 'b'}
</code>```

What is the right syntax?

答:
Using the built-in function filter:

Assuming you actually do have a list of dicts or None, as per your example:

```<code>merged_dict = {}
for dict in filter(None, unpack_dict):
    merged_dict.update(dict)
</code>```

Or in one line:

```<code>dict(pair for dict in filter(None, unpack_dict) for pair in dict.items())
</code>```

Or if your input was supposed to be a list of tuples, then it's quite easy, and similar to what you were attempting:

```<code>unpack_dict = [('key': 'a'), ('key_2': 'b'), None]
{key: value for (key, value) in filter(None, unpack_dict)}
</code>```

Body:
Trying to unpack the dicts which are not None from a list:

In [4]: unpack_dict = [{'key': 'a'}, {'key_2': 'b'}, None]

Tried a dict comprehension

In [5]: {key: value for (key, value) in unpack_dict if (key, value) is not None}
---------------------------------------------------------------------------
ValueError                                Traceback (most recent call last)
<ipython-input-5-ec0e44b95586> in <module>()
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

<ipython-input-5-ec0e44b95586> in <dictcomp>(.0)
----> 1 {key: value for (key, value) in unpack_dict if (key, value) is not None}

ValueError: not enough values to unpack (expected 2, got 1)

And a list comprehension:

In [6]: {**[x for x in [unpack_dict] if x is not None]}
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-6-ac36898d39a1> in <module>()
----> 1 {**[x for x in [unpack_dict] if x is not None]}

TypeError: 'list' object is not a mapping

Expected result:

{'key': 'a', 'key_2': 'b'}

What is the right syntax?

Body:
Using the built-in function filter:

Assuming you actually do have a list of dicts or None, as per your example:

merged_dict = {}
for dict in filter(None, unpack_dict):
    merged_dict.update(dict)

Or in one line:

dict(pair for dict in filter(None, unpack_dict) for pair in dict.items())

Or if your input was supposed to be a list of tuples, then it's quite easy, and similar to what you were attempting:

unpack_dict = [('key': 'a'), ('key_2': 'b'), None]
{key: value for (key, value) in filter(None, unpack_dict)}


来源: stackexchange

问:
How to make a save function in Python
So I made a notepad clone in python but I am stuck.
I want to change the doNothing() Function to be a Save function.
I want the user to be able to name the file he wrote in the program and save it where he wants.</p>

```<code>from tkinter import *

# ********** Functions **********
def doNothing():
print("Ok, i won't!")

# ********** TK Initialization **********
root = Tk()
# ********** Main Menu **********
menu = Menu(root)
root.config(menu=menu)

subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New", command=doNothing)
subMenu.add_command(label="Open...", command=doNothing)
subMenu.add_command(label="Save", command=doNothing)
subMenu.add_command(label="Save As...", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Page Setup...", command=doNothing)
subMenu.add_command(label="Print...", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Exit", command=root.quit)

editMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editMenu)
editMenu.add_command(label="Undo", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Cut", command=doNothing)
editMenu.add_command(label="Copy", command=doNothing)
editMenu.add_command(label="Paste", command=doNothing)
editMenu.add_command(label="Delete", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Find...", command=doNothing)
editMenu.add_command(label="Find Next", command=doNothing)
editMenu.add_command(label="Replace...", command=doNothing)
editMenu.add_command(label="Go To...", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Select All", command=doNothing)
editMenu.add_command(label="Time/Date", command=doNothing)

FormatMenu = Menu(menu)
menu.add_cascade(label="Format", menu=FormatMenu)
FormatMenu.add_command(label="Word Wrap", command=doNothing)
FormatMenu.add_command(label="Font...", command=doNothing)

ViewMenu = Menu(menu)
menu.add_cascade(label="View", menu=ViewMenu)
ViewMenu.add_command(label="Status Bar", command=doNothing)

HelpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=HelpMenu)
HelpMenu.add_command(label="View Help", command=doNothing)
HelpMenu.add_separator()
HelpMenu.add_command(label="About Editor", command=doNothing)

AboutMenu = Menu(menu)
menu.add_cascade(label="About", menu=AboutMenu)
AboutMenu.add_command(label="About the Developer", command=doNothing)
AboutMenu.add_separator()
AboutMenu.add_command(label="FK YOALL", command=doNothing)

# ********** Status Bar **********
status = Label(root, text="Preparing to do nothing...", bd=1, relief=SUNKEN,
anchor=W)
status.pack(side=BOTTOM, fill=X)

# ********** Text Area **********
text = Text(root, height=100, width=200)
text.pack()

# ********** Window Properties **********
root.maxsize(width=800, height=680)
root.minsize(width=666, height=666)
root.title('Text Editor')
root.mainloop()
</code>```

答: You can use os.system(command) importing the library os to create, rename or move files like batch. In command you need to put the batch command. To learn batch, see this

ContentLicense: CC BY-SA 3.0

Title: How to make a save function in Python

Body:
So I made a notepad clone in python but I am stuck.
I want to change the doNothing() Function to be a Save function.
I want the user to be able to name the file he wrote in the program and save it where he wants.

from tkinter import *

# ********** Functions **********
def doNothing():
print("Ok, i won't!")

# ********** TK Initialization **********
root = Tk()
# ********** Main Menu **********
menu = Menu(root)
root.config(menu=menu)

subMenu = Menu(menu)
menu.add_cascade(label="File", menu=subMenu)
subMenu.add_command(label="New", command=doNothing)
subMenu.add_command(label="Open...", command=doNothing)
subMenu.add_command(label="Save", command=doNothing)
subMenu.add_command(label="Save As...", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Page Setup...", command=doNothing)
subMenu.add_command(label="Print...", command=doNothing)
subMenu.add_separator()
subMenu.add_command(label="Exit", command=root.quit)

editMenu = Menu(menu)
menu.add_cascade(label="Edit", menu=editMenu)
editMenu.add_command(label="Undo", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Cut", command=doNothing)
editMenu.add_command(label="Copy", command=doNothing)
editMenu.add_command(label="Paste", command=doNothing)
editMenu.add_command(label="Delete", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Find...", command=doNothing)
editMenu.add_command(label="Find Next", command=doNothing)
editMenu.add_command(label="Replace...", command=doNothing)
editMenu.add_command(label="Go To...", command=doNothing)
editMenu.add_separator()
editMenu.add_command(label="Select All", command=doNothing)
editMenu.add_command(label="Time/Date", command=doNothing)

FormatMenu = Menu(menu)
menu.add_cascade(label="Format", menu=FormatMenu)
FormatMenu.add_command(label="Word Wrap", command=doNothing)
FormatMenu.add_command(label="Font...", command=doNothing)

ViewMenu = Menu(menu)
menu.add_cascade(label="View", menu=ViewMenu)
ViewMenu.add_command(label="Status Bar", command=doNothing)

HelpMenu = Menu(menu)
menu.add_cascade(label="Help", menu=HelpMenu)
HelpMenu.add_command(label="View Help", command=doNothing)
HelpMenu.add_separator()
HelpMenu.add_command(label="About Editor", command=doNothing)

AboutMenu = Menu(menu)
menu.add_cascade(label="About", menu=AboutMenu)
AboutMenu.add_command(label="About the Developer", command=doNothing)
AboutMenu.add_separator()
AboutMenu.add_command(label="FK YOALL", command=doNothing)

# ********** Status Bar **********
status = Label(root, text="Preparing to do nothing...", bd=1, relief=SUNKEN,
anchor=W)
status.pack(side=BOTTOM, fill=X)

# ********** Text Area **********
text = Text(root, height=100, width=200)
text.pack()

# ********** Window Properties **********
root.maxsize(width=800, height=680)
root.minsize(width=666, height=666)
root.title('Text Editor')
root.mainloop()


问:
DuplicateFileException found of Csr305_annotations.gwt.xml in android
Error:Execution failed for task ':app:transformResourcesWithMergeJavaResForDebug'.

com.android.build.api.transform.TransformException: com.android.builder.packaging.DuplicateFileException: Duplicate files copied in APK jsr305_annotations/Jsr305_annotations.gwt.xml
      File1: D:\Workspace\PNB-Copy Birla\app\build\intermediates\exploded-aar\com.google.android.gms\play-services-basement\9.8.0\jars\classes.jar
      File2: D:\Workspace\PNB-Copy Birla\app\build\intermediates\exploded-aar\PNB-Copy Birla\jwplayer-android-sdk\unspecified\jars\classes.jar

Please tell me how to remove this?

答:
You need to add the following in your 'app' build.gradle file:

```<code>android {
    ...
    packagingOptions {
        ...
        exclude 'jsr305_annotations/Jsr305_annotations.gwt.xml'
    }
}
</code>```

Body:
You need to add the following in your 'app' build.gradle file:

android {
    ...
    packagingOptions {
        ...
        exclude 'jsr305_annotations/Jsr305_annotations.gwt.xml'
    }
}


问:
Nesting columns good practice?
I am unable to find any rules as to whether or not this is something that should be done. Bootstrap clearly outlines amongst its rules the following:

Rows must be placed within a .container (fixed-width) or
.container-fluid (full-width) for proper alignment and padding

Use rows to create horizontal groups of columns

Content should be placed within columns, and only columns may be

immediate children of rows

So from this I conclude that each section of the website that I do want self-contained would have a container class. Within this we'd have a row and within that we'd have a column. Like so:

```<code><div class="container">
    <div class="row">
        <div class="col">COL 1 of 2</div>
        <div class="col">COL 2 of 2</div>
    </div>
</div>
</code>```

Now my question is, the rules specify that only columns may be immediate children of rows but it doesn't say what the children of columns should be. If I was to want to "nest" another set of double columns within another column, would I write it like in case one or case two?

```<code><div class="container">
    <div class="row">
        <div class="col">  <!--Columns within columns without a row-->
            <div class="col">
            <div class="col">
        </div>
        <div class="col">  <!--Row nested before nesting columns-->
            <div class="row">
                <div class="col">
                <div class="col">
            </div>
        </div>
    </div>
</div>
</code>```

Both work in terms of actually making the page, but I do not know what is considered "good practice". There are obviously limitations to both ways of writing things. In my case, I'd want the "column" to be filled with a dynamically generated amount of elements, which on different screen resolutions/responsive sizes would be aligned, so a row wrapper is not an option. I do not know how many elements per row I'd have, which would make the following rows break and wrap when it is not needed.

So, is it okay to nest columns within columns without a row to hold the children?

答:
You should put any nested .rows inside of a .container to contain the negative margins, and only nest a .col inside of a .row:

```<code><div class="container">
     <div class="row">
        <div class="col">  <!--Row nested before nesting columns-->
          <div class="container">
            <div class="row">
                <div class="col"> </div>
                <div class="col"> </div>
            </div>
          </div><!-- .container -->
        </div>
    </div>
</div>
</code>```

Title: Nesting columns good practice?

Body:
I am unable to find any rules as to whether or not this is something that should be done. Bootstrap clearly outlines amongst its rules the following:

Rows must be placed within a .container (fixed-width) or
.container-fluid (full-width) for proper alignment and padding

Use rows to create horizontal groups of columns

Content should be placed within columns, and only columns may be

immediate children of rows

So from this I conclude that each section of the website that I do want self-contained would have a container class. Within this we'd have a row and within that we'd have a column. Like so:

COL 1 of 2

COL 2 of 2

Now my question is, the rules specify that only columns may be immediate children of rows but it doesn't say what the children of columns should be. If I was to want to "nest" another set of double columns within another column, would I write it like in case one or case two?

Both work in terms of actually making the page, but I do not know what is considered "good practice". There are obviously limitations to both ways of writing things. In my case, I'd want the "column" to be filled with a dynamically generated amount of elements, which on different screen resolutions/responsive sizes would be aligned, so a row wrapper is not an option. I do not know how many elements per row I'd have, which would make the following rows break and wrap when it is not needed.

So, is it okay to nest columns within columns without a row to hold the children?

Body:
You should put any nested .rows inside of a .container to contain the negative margins, and only nest a .col inside of a .row:

<div class="container">
     <div class="row">
        <div class="col">  <!--Row nested before nesting columns-->
          <div class="container">
            <div class="row">
                <div class="col"> </div>
                <div class="col"> </div>
            </div>
          </div><!-- .container -->
        </div>
    </div>
</div>


问:
Editable cells in dynamic table
I'm trying to make a dynamic table with variable no. of rows and columns. Table is created but when i click on the cells, they are not editable as i assumed they will be.

$(document).ready(function() {
            $("#createit").click(function() {
                var num_rows = document.getElementById('rows').value;
                var num_cols = document.getElementById('cols').value;
                var tbody = '';
                for (var i = 0; i < num_rows; i++) {
                    tbody += '
';
                    for (var j = 0; j < num_cols; j++) {
                        tbody += '';
                        tbody += 'Cell' + i + j;
                        tbody += '	'
                    }
                    tbody += '
';
                }
                //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
                $('.editableTable').append(tbody);
            });
        });
        $(".editableTable td").dblclick(function() {
            console.log('clicked');
            var OriginalContent = $(this).text();
            $(this).addClass("cellEditing");
            $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
            $(this).children().first().focus();
            $(this).bgColor = 'red';

            $(this).children().first().keypress(function(e) {
                if (e.which == 13) {
                    var newContent = OriginalContent;
                    $(this).parent().text(OriginalContent);
                    $(this).parent().removeClass("cellEditing");
                }
            });
            $(this).children().first().blur(function() {
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            });
        });
        $(".editableTable td").bind('keydown', function(event) {
            if (event.keyCode === 9 || event.keyCode === 13) {
                var tabindex = $(this).attr('tabindex');
                tabindex++; //increment tabindex
                $('[tabindex=' + tabindex + ']').focus().dblclick();
                return false;
            }
        });```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }</code>```

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

```

Same thing i have done before but with a static table. JSFIDDLE https://jsfiddle.net/rbrohitbisht/691rx62k/

Now i want to do the same thing with the dynamic table. What i'm doing wrong here?

答:
The operation should be moved into the createit handler definition.

```<code> $(".editableTable td").dblclick(function() {...});
</code>```

Just after the cells are created(of course after a click on Crete Table!).

Otherwise the selector $(".editableTable td") would not return anything before the dynamic table is in place.

Title: Editable cells in dynamic table

Body:
I'm trying to make a dynamic table with variable no. of rows and columns. Table is created but when i click on the cells, they are not editable as i assumed they will be.

$(document).ready(function() {
            $("#createit").click(function() {
                var num_rows = document.getElementById('rows').value;
                var num_cols = document.getElementById('cols').value;
                var tbody = '';
                for (var i = 0; i < num_rows; i++) {
                    tbody += '
';
                    for (var j = 0; j < num_cols; j++) {
                        tbody += '';
                        tbody += 'Cell' + i + j;
                        tbody += '	'
                    }
                    tbody += '
';
                }
                //document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
                $('.editableTable').append(tbody);
            });
        });
        $(".editableTable td").dblclick(function() {
            console.log('clicked');
            var OriginalContent = $(this).text();
            $(this).addClass("cellEditing");
            $(this).html("<select><option>1</option><option>2</option><option >3</option></select>");
            $(this).children().first().focus();
            $(this).bgColor = 'red';

            $(this).children().first().keypress(function(e) {
                if (e.which == 13) {
                    var newContent = OriginalContent;
                    $(this).parent().text(OriginalContent);
                    $(this).parent().removeClass("cellEditing");
                }
            });
            $(this).children().first().blur(function() {
                $(this).parent().text(OriginalContent);
                $(this).parent().removeClass("cellEditing");
            });
        });
        $(".editableTable td").bind('keydown', function(event) {
            if (event.keyCode === 9 || event.keyCode === 13) {
                var tabindex = $(this).attr('tabindex');
                tabindex++; //increment tabindex
                $('[tabindex=' + tabindex + ']').focus().dblclick();
                return false;
            }
        });

.editableTable {
            border: solid 0px;
            width: 100%;
            text-align: center
        }

        .editableTable td {
            border: solid 0.5px;
            border-color: lightblue;
            min-width: 100px;
        }

        .editableTable .cellEditing {
            padding: 0;
        }

        select {
            border: 0px;
            width: 100%;
        }

Rows: <input type="text" name="rows" id="rows"/>

    Cols: <input type="text" name="cols" id="cols"/>

    <input name="generate" type="button" value="Create Table!" id='createit' />

Same thing i have done before but with a static table. JSFIDDLE https://jsfiddle.net/rbrohitbisht/691rx62k/

Now i want to do the same thing with the dynamic table. What i'm doing wrong here?

Body:
The operation should be moved into the createit handler definition.

 $(".editableTable td").dblclick(function() {...});

Just after the cells are created(of course after a click on Crete Table!).

Otherwise the selector $(".editableTable td") would not return anything before the dynamic table is in place.


问:
A better way to build a custom SUM function which takes a list of Expressions
I've defined the following method:

```<code>public static Expression Sum(IList<Expression> expressions)
{
    Expression result = expressions[0];
    foreach (var expression in expressions.Skip(1))
    {
        result = Expression.Add(result, expression);
    }

    return result;
}
</code>```

Which can be used as:

```<code>var number1 = Expression.Constant(42.0);
var number2 = Expression.Constant(10.0);

var resultExpression = Sum(new { number1, number2 });
var value = Expression.Lambda(resultExpression).Compile().DynamicInvoke();
</code>```

However when adding a large number of expressions, I think the performance is not ok.

So I was wondering if a method can be created which used Enumerable.Sum or Queryable.Sum to do the work.

答:
I think you are redifining the Aggregate method, that uses a previous Add expression and current expression of your list of expression. Change your code to this:

```<code>return expressions.Aggregate((previousExpr, currentExpr) => Expression.Add(previousExpr, currentExpr));
</code>```

I'm not sure this is faster, but is cleaner.
previousExpr contains the exression result to sum

Body:
I've defined the following method:

public static Expression Sum(IList<Expression> expressions)
{
    Expression result = expressions[0];
    foreach (var expression in expressions.Skip(1))
    {
        result = Expression.Add(result, expression);
    }

    return result;
}

Which can be used as:

var number1 = Expression.Constant(42.0);
var number2 = Expression.Constant(10.0);

var resultExpression = Sum(new { number1, number2 });
var value = Expression.Lambda(resultExpression).Compile().DynamicInvoke();

However when adding a large number of expressions, I think the performance is not ok.

So I was wondering if a method can be created which used Enumerable.Sum or Queryable.Sum to do the work.

Body:
I think you are redifining the Aggregate method, that uses a previous Add expression and current expression of your list of expression. Change your code to this:

return expressions.Aggregate((previousExpr, currentExpr) => Expression.Add(previousExpr, currentExpr));

I'm not sure this is faster, but is cleaner.
previousExpr contains the exression result to sum


问:
Add a Character Between Strings in C++
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

```<code>void converter(){
    converted = ":regional_indicator_" + character + ":";

}
</code>```

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

```<code>#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}

void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}
</code>```

答:
You can avoid invoking the std::string() constructor and memory allocation by using following. I have tested this before posting and it works:

```<code>void converter(){
    converted = ":regional_indicator_";
    converted.push_back(character);
    converted.push_back(':');
}
</code>```

It's better because "converted" already will have some extra memory reserved, so you will just be filling that extra memory with two more characters and won't be allocating new memory.

Title: Add a Character Between Strings in C++

Body:
So basically I'm trying to add a character in the middle of a string. Normally in something like Python, this would be pretty straightforward, but I'm really not sure how to achieve this in C++. What I'm trying to achieve is something like this:

void converter(){
    converted = ":regional_indicator_" + character + ":";

}

So basically, I'm trying to add the variable character of a type char in a string. Should I be storing character as a string instead?

For reference here's all of my code:

#include <iostream>

using namespace std;

string inputLine;
char character;
string converted;

void input(){
    cout << "Please input the text in which you would like to be converted" << endl;
    cin >> inputLine;
}

void converter(){
    converted = ":regional_indicator_" + character + ":";

}
int main(){
    input();
    for (int i = 0; i < inputLine.length(); i++ ){
        character = tolower(inputLine[i]);
    }
    return 0;
}

Body:
You can avoid invoking the std::string() constructor and memory allocation by using following. I have tested this before posting and it works:

void converter(){
    converted = ":regional_indicator_";
    converted.push_back(character);
    converted.push_back(':');
}

It's better because "converted" already will have some extra memory reserved, so you will just be filling that extra memory with two more characters and won't be allocating new memory.


问:
AWS Custom Authorization lambda to approve Api Gateway service proxy action?
I want to create an Api Gateway route which is connected via service proxy to s3.

Only authenticated and authorized users (from Cognito Userpool) which have a specific permission (which is stored in a DynamoDb table) should be able to upload the file.

Since I'm not using S3 as the service proxy and not lambda, is it ok to put the code checking against the Dynamodb in the Custom Authorizer lambda? (After the token has been verified and before sending the success callback).

The query is simple, based on the Cognito user unique Id, I check in a table that user if user is authorized to upload.

I wouldn't want the upload to be done via a lambda function since some files are big.

Thanks

答:
You can also consider

Setup CloudFront infront of S3 bucket.

Using IAM authorization at API Gateway.

Write a Lambda endpoint which checks Cognito ID in request context against Dynamodb.

Return Signed URL from Lambda for authorized users to directly upload files to S3 from browser client.


问:
PHP url decoding or encoding help needed
Hey I'm trying to pass variables to my variation product page.

For example, im able to pass the keys and part numbers via

http://comugg.com/product/generallisting6/?attribute_pa_keys=yes&attribute_pa_part-number=0-261-204-591

however when i try to pass the engine size using the same format...for example,

http://comugg.com/product/generallisting6/?attribute_pa_engine-size=1.8L

it doesnt work. im assuming its becuase of the "." im wondering what i can do?

P.S. ive already tried using the slug 1-6L. it doesnt work:(

答:
I guess the value and name should be same for this to work.
Try http://comugg.com/product/generallisting6/?attribute_pa_engine-size=1-6L.
Working fine if the value and name are same. try using same for 1.8L.</p>


问:
Angular 4 error when navigating using secondary outlet
I have an issue with navigation using a secondary outlet.

I have a LayoutComponent which is loaded into the primary router-outlet.

The LayoutComponent contains a secondary outlet named content-outlet

So far everything is fine and I am able to navigate to e.g. /accounts/1/overview and have the content-outlet load the correct component (OverviewComponent). But when I click the link in the sidebar to navigate to the /accounts/1/stats route I get an error:

```<code>Error: Cannot activate an already activated outlet
</code>```

The same thing happens if I first navigate to /accounts/1/stats and then try to activate /accounts/1/overview.

The LayoutComponent:

```<code><app-sidebar></app-sidebar>
<div class="topbar-content-wrapper">
  <app-topbar></app-topbar>
  <div class="content-wrapper">
    <router-outlet name="content-outlet"></router-outlet>
  </div>
</div>
</code>```

The sidebar navigation:

```<code><a href="#" [routerLink]="[ '/accounts', accountId, 'overview' ]">Overview</a>
<a href="#" [routerLink]="[ '/accounts', accountId, 'stats' ]">Stats</a>
</code>```

The Routes:

```<code>{
path: 'accounts/:accountid',
component: LayoutComponent,
canActivate: [AuthService],
children: [
  {
    path: 'stats',
    children: [
      {
        path: '',
        component: StatsComponent,
        outlet: 'content-outlet'
      }
    ]
  },
  {
    path: 'overview',
    children: [
      {
        path: '',
        component: OverviewComponent,
        outlet: 'content-outlet'
      }
    ]
  }
]
</code>```

答:
change your routes to the following

```<code>{
   path: 'accounts/:accountid',
   component: LayoutComponent,
   canActivate: [AuthService],
},
{
    path: 'stats',
    component: StatsComponent,
    outlet: 'content-outlet'
 },
{
    path: 'overview',
    component: OverviewComponent,
    outlet: 'content-outlet'
}
</code>```

and your sidebar navigation links too:

```<code><a [routerLink]="[{ outlets: { content-outlet: ['overview'] } }]">Overview</a>
<a [routerLink]="[{ outlets: { content-outlet: ['stats'] } }]">Stats</a>
</code>```

Body:
I have an issue with navigation using a secondary outlet.

I have a LayoutComponent which is loaded into the primary router-outlet.

The LayoutComponent contains a secondary outlet named content-outlet

So far everything is fine and I am able to navigate to e.g. /accounts/1/overview and have the content-outlet load the correct component (OverviewComponent). But when I click the link in the sidebar to navigate to the /accounts/1/stats route I get an error:

Error: Cannot activate an already activated outlet

The same thing happens if I first navigate to /accounts/1/stats and then try to activate /accounts/1/overview.

The LayoutComponent:

<app-sidebar></app-sidebar>

  <app-topbar></app-topbar>

    <router-outlet name="content-outlet"></router-outlet>

The sidebar navigation:

Overview
Stats

The Routes:

{
path: 'accounts/:accountid',
component: LayoutComponent,
canActivate: [AuthService],
children: [
  {
    path: 'stats',
    children: [
      {
        path: '',
        component: StatsComponent,
        outlet: 'content-outlet'
      }
    ]
  },
  {
    path: 'overview',
    children: [
      {
        path: '',
        component: OverviewComponent,
        outlet: 'content-outlet'
      }
    ]
  }
]

Body:
change your routes to the following

{
   path: 'accounts/:accountid',
   component: LayoutComponent,
   canActivate: [AuthService],
},
{
    path: 'stats',
    component: StatsComponent,
    outlet: 'content-outlet'
 },
{
    path: 'overview',
    component: OverviewComponent,
    outlet: 'content-outlet'
}

and your sidebar navigation links too:

<a [routerLink]="[{ outlets: { content-outlet: ['overview'] } }]">Overview</a>
<a [routerLink]="[{ outlets: { content-outlet: ['stats'] } }]">Stats</a>


问:
Filter out entries that appear more than once in a table
I have a table that contains the following data:

```<code>Table t1

A     |   B
12        56
12        56
10        8
10        9
10        11
9         55
9         66
</code>```

I need to write a program that finds all column values which have same value of column A but different values in column B.

Example

My result should be as follows:

```<code>A    |    B
10        8
10        9
10        11
9         55
9         66
</code>```

A is the same and B is different for each value of A.

答:
Please try the following query:

```<code>SELECT
    A
    , B
FROM
(
    SELECT
        A,
        B,
        COUNT(*) AS Total
    FROM
        t1
    GROUP BY
        A,
        B
) AS Results
WHERE
    Results.Total = 1
</code>```

This query will hide any entries that occur more than once in table t1.

Body:
I have a table that contains the following data:

Table t1

A     |   B
12        56
12        56
10        8
10        9
10        11
9         55
9         66

I need to write a program that finds all column values which have same value of column A but different values in column B.

Example

My result should be as follows:

A    |    B
10        8
10        9
10        11
9         55
9         66

A is the same and B is different for each value of A.

Body:
Please try the following query:

SELECT
    A
    , B
FROM
(
    SELECT
        A,
        B,
        COUNT(*) AS Total
    FROM
        t1
    GROUP BY
        A,
        B
) AS Results
WHERE
    Results.Total = 1

This query will hide any entries that occur more than once in table t1.


问:
Classifying PDF Text Documents based on the presence/absence of specific words in R
I would like to be able to import PDF documents into R and classify them as either:

Relevant (contains a specific string, for example, "tacos", within the first 100 words)

Irrelevant (DOES NOT contain "tacos" within the first 100 words)

To be more specific, I would like to address the following questions:

Does a package(s) exist in R to perform this basic classification?

If so, is it possible to generate a dataset that would look something like this in R if I had 2 PDF documents with Paper1 containing at least one instance of the string, "tacos", in the first 100 words and Paper2 that DOES NOT contain at least one instance of the string, "tacos":

Any references to documentation/R packages/sample R code or mock examples related to this type of classification using R would be greatly appreciated! Thanks!

答:
You can use the pdftools library and do something like this:

First, load the library and grab some pdf file names:

```<code>library(pdftools)
fns <- list.files("~/Documents", pattern = "\\.pdf$", full = TRUE)
fns <- sample(fns, 5) # sample of 5 pdf filenames...
</code>```

Then define a function that reads a PDF file in as text and looks up the first n words. (It might be useful to check for errros, like unknown password or things like that - my ex. function returns NA for such cases.)

```<code>isRelevant <- function(fn, needle, n = 100L, ...) {
  res <- try({
    txt <- pdf_text(fn)
    txt <- scan(text = txt, what = "character", quote = "", quiet = TRUE)
    any(grepl(needle, txt[1:n], ...))
  }, silent = TRUE)
  if (inherits(res, "try-error")) NA else res
}
res <- sapply(fns, isRelevant, needle = "mail", ignore.case=TRUE)
</code>```

Finally, wrap it up and put it into a data frame:

```<code>data.frame(
  Document = basename(fns),
  Classification = dplyr::if_else(res, "relevant", "not relevant", "unknown")
)
#   Document  Classification
# 1    a.pdf        relevant
# 2    b.pdf    not relevant
# 3    c.pdf        relevant
# 4    d.pdf    not relevant
# 5    e.pdf        relevant
</code>```

Body:
You can use the pdftools library and do something like this:

First, load the library and grab some pdf file names:

library(pdftools)
fns <- list.files("~/Documents", pattern = "\\.pdf$", full = TRUE)
fns <- sample(fns, 5) # sample of 5 pdf filenames...

Then define a function that reads a PDF file in as text and looks up the first n words. (It might be useful to check for errros, like unknown password or things like that - my ex. function returns NA for such cases.)

isRelevant <- function(fn, needle, n = 100L, ...) {
  res <- try({
    txt <- pdf_text(fn)
    txt <- scan(text = txt, what = "character", quote = "", quiet = TRUE)
    any(grepl(needle, txt[1:n], ...))
  }, silent = TRUE)
  if (inherits(res, "try-error")) NA else res
}
res <- sapply(fns, isRelevant, needle = "mail", ignore.case=TRUE)

Finally, wrap it up and put it into a data frame:

data.frame(
  Document = basename(fns),
  Classification = dplyr::if_else(res, "relevant", "not relevant", "unknown")
)
#   Document  Classification
# 1    a.pdf        relevant
# 2    b.pdf    not relevant
# 3    c.pdf        relevant
# 4    d.pdf    not relevant
# 5    e.pdf        relevant


问:
Swi Prolog, Read file examples
I am new to Prolog but I get the basics. I am having problems reading a file. Here is my file:

```<code>16
78 45 12 32 457 97 12 5 731 2 4 55 44 11 999 7
</code>```

I want to read it so that I get back the characters as numbers. The first line is the amount of numbers on line 2. The problems are:

1) How to split them on SPACE or NEW LINE character

2) They must be numbers:32, not Strings: "32"

I am using SWI-Prolog.

答:
Here is my implementation:

```<code>my_read_file(File,Firt_Number ,List):-
    open(File, read, Stream),
    read_line(Stream, [Firt_Number]),
    read_line(Stream, List),
    close(Stream).

read_line(Stream, List) :-
    read_line_to_codes(Stream, Line),
    atom_codes(A, Line),
    atomic_list_concat(As, ' ', A),
    maplist(atom_number, As, List).
</code>```

Example:

```<code>?- my_read_file("file.txt",N,L).
N = 16,
L = [78, 45, 12, 32, 457, 97, 12, 5, 731, 2, 4, 55, 44, 11, 999, 7] .
</code>```

Title: Swi Prolog, Read file examples

Body:
I am new to Prolog but I get the basics. I am having problems reading a file. Here is my file:

16
78 45 12 32 457 97 12 5 731 2 4 55 44 11 999 7

I want to read it so that I get back the characters as numbers. The first line is the amount of numbers on line 2. The problems are:

1) How to split them on SPACE or NEW LINE character

2) They must be numbers:32, not Strings: "32"

I am using SWI-Prolog.

Body:
Here is my implementation:

my_read_file(File,Firt_Number ,List):-
    open(File, read, Stream),
    read_line(Stream, [Firt_Number]),
    read_line(Stream, List),
    close(Stream).

read_line(Stream, List) :-
    read_line_to_codes(Stream, Line),
    atom_codes(A, Line),
    atomic_list_concat(As, ' ', A),
    maplist(atom_number, As, List).

Example:

?- my_read_file("file.txt",N,L).
N = 16,
L = [78, 45, 12, 32, 457, 97, 12, 5, 731, 2, 4, 55, 44, 11, 999, 7] .


问:
How to write linq query for sample xml
How to get the collection of values of elements from such an xml, using linq
(root/doc/files/file):

```<code><root>

  <doc>
    <files>
      <file>1</file>
      <file>2</file>
      <file>3</file>
    </files>
  </doc>

  <doc>
    <files>
      <file>4</file>
      <file>5</file>
      <file>6</file>
    </files>
  </doc>

</root>
</code>```

From that query I would like to have:

```<code>1
2
3
4
5
6
</code>```

Here is the beginning of the code I have written so far.

```<code>    string xmlIn = "<root> "+
                   "   <doc>"+
                   "     <files>"+
                   "       <file>1</file>"+
                   "       <file>2</file>"+
                   "       <file>3</file>  "+
                   "     </files>   "+
                   "   </doc>"+

                   " <doc>"+
                   "     <files>"+
                   "       <file>4</file>"+
                   "       <file>5</file>"+
                   "       <file>6</file>  "+
                   "     </files>   "+
                   "   </doc>"+

                   " </root>";

    var xml = XDocument.Parse(xmlin);
</code>```

答:
Using Descendants method:

```<code>var result= root.Descendants("file").Select(e=>e.Value);
</code>```

Title: How to write linq query for sample xml

Body:
How to get the collection of values of elements from such an xml, using linq
(root/doc/files/file):

<root>

  <doc>
    <files>
      <file>1</file>
      <file>2</file>
      <file>3</file>
    </files>
  </doc>

  <doc>
    <files>
      <file>4</file>
      <file>5</file>
      <file>6</file>
    </files>
  </doc>

</root>

From that query I would like to have:

1
2
3
4
5
6

Here is the beginning of the code I have written so far.

    string xmlIn = "<root> "+
                   "   <doc>"+
                   "     <files>"+
                   "       <file>1</file>"+
                   "       <file>2</file>"+
                   "       <file>3</file>  "+
                   "     </files>   "+
                   "   </doc>"+

                   " <doc>"+
                   "     <files>"+
                   "       <file>4</file>"+
                   "       <file>5</file>"+
                   "       <file>6</file>  "+
                   "     </files>   "+
                   "   </doc>"+

                   " </root>";

    var xml = XDocument.Parse(xmlin);

Body:
Using Descendants method:

var result= root.Descendants("file").Select(e=>e.Value);


问:
C++ when to use delete[] and properly deallocate memory?
So I see that there's pairings with memory management functions such as malloc/free, new/delete, and new[]/delete[], but sometimes you're not always calling new or new[] and you still have to call delete, delete[], or free. For example, strdup is one such function which encapsulates the allocation of memory and you'd still have to deallocate that memory yourself later on.

So when do you know to free memory, if you're not always writing new or malloc in some sense? I'm particularly curious about deleting arrays of objects. Just simple arrays. Because, that seems to be one of the use cases that delete[] is made for. (I'm looking at cplusplus.)

So, is this valid? Is this necessary? Is anything missing?

```<code>unsigned char bytes[4] = {0xDE, 0xAD, 0xBE, 0xEF};
for(int i = 0; i < 4; i++)
    std::cout << std::hex << +bytes[i];
delete[] bytes;
</code>```

bytes is technically an unsigned char * type, right? I know I technically have a pointer, but because this isn't an array of objects, I'm unsure whether or not it gets automatically destroyed.

答:
No, this is not valid.

Every single call to delete[] should be paired with new[].  If it doesn't pair up (e.g. strdup), it's because some function internally calls malloc/new[].

unsigned char bytes[4] = {0xDE, 0xAD, 0xBE, 0xEF}; declares 4 bytes of memory on the stack.  Stack memory is automatically destroyed at the end of the enclosing scope.  They share the same memory as those needed for function calls.

new/delete allocates and deallocates heap memory.  Heap memory has no specific order of acquisition or destruction (unlike a stack, which is first-in-last-out), so you have to delete it explicitly or the program won't know when to deallocate it.

Body:
So I see that there's pairings with memory management functions such as malloc/free, new/delete, and new[]/delete[], but sometimes you're not always calling new or new[] and you still have to call delete, delete[], or free. For example, strdup is one such function which encapsulates the allocation of memory and you'd still have to deallocate that memory yourself later on.

So when do you know to free memory, if you're not always writing new or malloc in some sense? I'm particularly curious about deleting arrays of objects. Just simple arrays. Because, that seems to be one of the use cases that delete[] is made for. (I'm looking at cplusplus.)

So, is this valid? Is this necessary? Is anything missing?

unsigned char bytes[4] = {0xDE, 0xAD, 0xBE, 0xEF};
for(int i = 0; i < 4; i++)
    std::cout << std::hex << +bytes[i];
delete[] bytes;

bytes is technically an unsigned char * type, right? I know I technically have a pointer, but because this isn't an array of objects, I'm unsure whether or not it gets automatically destroyed.


问:
Error on trying to create HawkConsole Object on TIBCO Hawk JAVA API
When i'm trying to create a HawkConsole Object using Hawk JAVA API, i'm  get bellow error message

Unable to create EMS transport:
  COM.TIBCO.hawk.console.nest.shared.TransportInitializationException:
  COM/TIBCO/hawk/util/security/PasswordObfuscation

I'm using the follow code to try to create the object

```<code>hawkConsole = new TIBHawkConsole("MyDomain",
                  "MyEMSConnectionString",
                  "MyUserTOEMS",
                  "MyPasswortoEMS",
                  1);
</code>```

In according with the official documentation, to the last parameter can be used anyone number ... This will be ignored ...

The object is successfully created but when the below line is executed the error happens

getAgentMonitor().initialize;

答:
Problem is solved.
Its necessary add the security.jar and utils.jar extracted from lib Hawk folder, on the Top of BUildPath to work.</p>

Body:
When i'm trying to create a HawkConsole Object using Hawk JAVA API, i'm  get bellow error message

Unable to create EMS transport:
  COM.TIBCO.hawk.console.nest.shared.TransportInitializationException:
  COM/TIBCO/hawk/util/security/PasswordObfuscation

I'm using the follow code to try to create the object

hawkConsole = new TIBHawkConsole("MyDomain",
                  "MyEMSConnectionString",
                  "MyUserTOEMS",
                  "MyPasswortoEMS",
                  1);

In according with the official documentation, to the last parameter can be used anyone number ... This will be ignored ...

The object is successfully created but when the below line is executed the error happens

getAgentMonitor().initialize;


问:
python3 how to find the largest prefix of a string of bytes that is a substring of another
I need to find largest prefix (string of bytes starting from the beginning) of a bytes object s1 that is a substring of another bytes object s2 and return the start location in s2 and length. In this case s2 happens to be overlapping s1 as well.

The optimal result is the longest prefix that starts closest to the end of s2.

I have tried to implement this using bytes.rfind method as below.

Note: This is trying to find the largest prefix starting at index index in the bytes object  src that is present earlier in src within a maximum of maxOffset bytes before index. Therefore, s1 is src[index:] and s2 is src[index-maxOffset:index+maxLength-1]. maxLength is the maximum length of prefix that I am interested in searching for.

```<code>def crl(index, src, maxOffset, maxLength):
    """
    Returns starting position in source before index from where the max runlength is detected.
    """
    src_size = len(src)
    if index > src_size:
        return (-1, 0)
    if (index+maxLength) > src_size:
        maxLength = src_size - index
    startPos = max(0, index-maxOffset)
    endPos = index+maxLength-1
    l = maxLength

    while l>1:
        if src[index:index+l] in src[startPos:index+l-1]:
            p = src.rfind(src[index:index+l], startPos, index+l-1)
            return (p,l)
        l -= 1
    return (-1, 0)
</code>```

I have also tried to hand-code this as below since the previous implementation was very slow

```<code>def ocrl(index, src, maxOffset, maxLength):
    """
    Returns starting position in source before index from where the max runlength is detected.
    """
    size = len(src)
    if index>=size:
        return (-1, 0)
    startPos = index - 1 # max(0, index-maxOffset)
    stopPos = max(0, index-maxOffset)
    runs = {}
    while(startPos >= stopPos):
        currRun = 0
        pos = startPos
        while src[pos] == src[index+currRun]:
            currRun += 1
            pos += 1
            if currRun == maxLength:
                return (startPos, maxLength) #found best possible run
            if (pos >= size) or ((index+currRun) >= size):
                break
        if (currRun > 0) and (currRun not in runs.keys()):
            runs[currRun] = startPos
        startPos -= 1

    if not runs:
        return (-1, 0)
    else:
        # Return the index from where the longest run was found
        return (runs[max(runs.keys())], max(runs.keys()))
</code>```

While 2nd implementation is faster, it is still very slow and I believe inefficient. How can I make this more efficient and run faster ?

答: Build suffix array for the second string and search for the first string in that array, choosing the last index of the longest common prefix</p>

Body:
I need to find largest prefix (string of bytes starting from the beginning) of a bytes object s1 that is a substring of another bytes object s2 and return the start location in s2 and length. In this case s2 happens to be overlapping s1 as well.

The optimal result is the longest prefix that starts closest to the end of s2.

I have tried to implement this using bytes.rfind method as below.

Note: This is trying to find the largest prefix starting at index index in the bytes object  src that is present earlier in src within a maximum of maxOffset bytes before index. Therefore, s1 is src[index:] and s2 is src[index-maxOffset:index+maxLength-1]. maxLength is the maximum length of prefix that I am interested in searching for.

def crl(index, src, maxOffset, maxLength):
    """
    Returns starting position in source before index from where the max runlength is detected.
    """
    src_size = len(src)
    if index > src_size:
        return (-1, 0)
    if (index+maxLength) > src_size:
        maxLength = src_size - index
    startPos = max(0, index-maxOffset)
    endPos = index+maxLength-1
    l = maxLength

    while l>1:
        if src[index:index+l] in src[startPos:index+l-1]:
            p = src.rfind(src[index:index+l], startPos, index+l-1)
            return (p,l)
        l -= 1
    return (-1, 0)

I have also tried to hand-code this as below since the previous implementation was very slow

def ocrl(index, src, maxOffset, maxLength):
    """
    Returns starting position in source before index from where the max runlength is detected.
    """
    size = len(src)
    if index>=size:
        return (-1, 0)
    startPos = index - 1 # max(0, index-maxOffset)
    stopPos = max(0, index-maxOffset)
    runs = {}
    while(startPos >= stopPos):
        currRun = 0
        pos = startPos
        while src[pos] == src[index+currRun]:
            currRun += 1
            pos += 1
            if currRun == maxLength:
                return (startPos, maxLength) #found best possible run
            if (pos >= size) or ((index+currRun) >= size):
                break
        if (currRun > 0) and (currRun not in runs.keys()):
            runs[currRun] = startPos
        startPos -= 1

    if not runs:
        return (-1, 0)
    else:
        # Return the index from where the longest run was found
        return (runs[max(runs.keys())], max(runs.keys()))

While 2nd implementation is faster, it is still very slow and I believe inefficient. How can I make this more efficient and run faster ?


问:
F# - Turn simple for loop into more functional construct
I have this simple "Investment" type with a "lifetime" property:

```<code>type Investment = {
PurchasePayment: float;
Lifetime: float;
TaxWriteoff: float;
ResidualValue: float;
}

let CoffeMachine = {
    PurchasePayment = 13000.0;
    Lifetime = 4.0;
    TaxWriteoff = 2000.0;
    ResidualValue = 500.0;
}
</code>```

I would like to iterate over the years of investment and perform some calculations for each year:

```<code>for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
    // doSomething
</code>```

Is there a way to avoid using for loop for that and write it in a more functional style?

Cheers,

Wojtek

答:
A different approach from other answers would be to use tail recursion.

What are the benefits of tail recursion over for example?

```<code>[1..int CoffeMachine.Lifetime] |> List.iter (printf "%i")
</code>```

Or:

```<code>for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
</code>```

From a performance and memory perspective List.iter is worse than the for loop because first one create a single linked list (F# immutable lists are single linked list under the hood) and iterate over it. In many situations the increased CPU and memory usage is not relevant but in other situations it is.

Lazy collections like Seq would mitigate this but unfortunate Seq is currently not efficient in F#. Nessos Streams would be a better choice.

The problem with the for loop in F# is that it can't be broken out of prematurely (break or continue doesn't exist in F#).

In addition, the for loop pattern often forces us into a mutable variable pattern when aggregating results.

Tail recursion allows us to aggregate results without relying on mutable variables and supports aborting. In addition, tail recursion loops can return values which for loop can't (the expression result is always unit)

Tail recursion is also efficient in F# as F# detects tail recursive functions and unrolls this to a loop under the hood.

This is how a tail recursive loop the code above could look like:

```<code>let rec loop i l = if i <= l then printf "%i" i; loop (i + 1) l
loop 1 (int CoffeMachine.Lifetime)
</code>```

Using ILSpy one sees this is compiled into a while loop:

```<code>internal static void loop@3(int i, int l)
{
  while (i <= l)
  {
    PrintfFormat<FSharpFunc<int, Unit>, TextWriter, Unit, Unit> format = new PrintfFormat<FSharpFunc<int, Unit>, TextWriter, Unit, Unit, int>("%i");
    PrintfModule.PrintFormatToTextWriter<FSharpFunc<int, Unit>>(Console.Out, format).Invoke(i);
    int arg_28_0 = i + 1;
    l = l;
    i = arg_28_0;
  }
}
</code>```

Body:
I have this simple "Investment" type with a "lifetime" property:

type Investment = {
PurchasePayment: float;
Lifetime: float;
TaxWriteoff: float;
ResidualValue: float;
}

let CoffeMachine = {
    PurchasePayment = 13000.0;
    Lifetime = 4.0;
    TaxWriteoff = 2000.0;
    ResidualValue = 500.0;
}

I would like to iterate over the years of investment and perform some calculations for each year:

for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i
    // doSomething

Is there a way to avoid using for loop for that and write it in a more functional style?

Cheers,

Wojtek

Body:
A different approach from other answers would be to use tail recursion.

What are the benefits of tail recursion over for example?

[1..int CoffeMachine.Lifetime] |> List.iter (printf "%i")

Or:

for i = 1 to int CoffeMachine.Lifetime do
    printf "%i" i

From a performance and memory perspective List.iter is worse than the for loop because first one create a single linked list (F# immutable lists are single linked list under the hood) and iterate over it. In many situations the increased CPU and memory usage is not relevant but in other situations it is.

Lazy collections like Seq would mitigate this but unfortunate Seq is currently not efficient in F#. Nessos Streams would be a better choice.

The problem with the for loop in F# is that it can't be broken out of prematurely (break or continue doesn't exist in F#).

In addition, the for loop pattern often forces us into a mutable variable pattern when aggregating results.

Tail recursion allows us to aggregate results without relying on mutable variables and supports aborting. In addition, tail recursion loops can return values which for loop can't (the expression result is always unit)

Tail recursion is also efficient in F# as F# detects tail recursive functions and unrolls this to a loop under the hood.

This is how a tail recursive loop the code above could look like:

let rec loop i l = if i <= l then printf "%i" i; loop (i + 1) l
loop 1 (int CoffeMachine.Lifetime)

Using ILSpy one sees this is compiled into a while loop:

internal static void loop@3(int i, int l)
{
  while (i <= l)
  {
    PrintfFormat<FSharpFunc<int, Unit>, TextWriter, Unit, Unit> format = new PrintfFormat<FSharpFunc<int, Unit>, TextWriter, Unit, Unit, int>("%i");
    PrintfModule.PrintFormatToTextWriter<FSharpFunc<int, Unit>>(Console.Out, format).Invoke(i);
    int arg_28_0 = i + 1;
    l = l;
    i = arg_28_0;
  }
}


问:
Return type of array access operator overload
I have a class Foo that manages a collection of objects of another class Bar. The managing class has a method Bar *Foo::at( int index ) to access the objects int he collection, so I can do something like myfoo->at(2)->barmethod(), say. Now I was wondering if I can overload Foo::operator[] to return a Bar*, so I could do myfoo[2]->barmethod() instead. The compiler doesn't like that. Does the return type of the operator necessarily need to be a reference to the class it is a member of?

Here is some code. The first works, the second doesn't.

```<code>Foo::Bar *Foo::at( size_t index )
{
    return index < m_count ? m_entry[index] : 0;
}

Foo::Bar *Foo::operator[]( size_t index )
{
    return index < m_count ? m_entry[index] : 0;
}
</code>```

From the header:

```<code>class Foo
{
public:

    class Bar
    {
    ...
    };

    size_t add( UINT8 addr, UINT8 type, UINT8 opt, UINT8 rev );
    Bar    *at( size_t index );
    Bar    *operator[]( size_t index );
    ....

protected:

    Bar             **m_entry;      // array of entry pointers
    size_t          m_size;
    size_t          m_count;

};
</code>```

Here's the code the compiler doesn't like (when using [ ]):

```<code>Foo *myfoo;
...
myfoo[i]->barmethod();
</code>```

and now in writing this I see what the problem is. I'm using [] on a POINTER to a Foo, not on an actual Foo. So if I dereference it, it should work. The compiler error is exactly right:

error: base operand of '->' has non-pointer type 'Foo'

Duh. Okay, sorry for the dumb question. Thanks for your suggestions.

答:
Does the return type of the operator necessarily need to be a reference to the class it is a member of?

You could trivially answer this yourself by thinking about e.g. std::vector, its operator [], and the return type of the latter.

The conclusion is that there is no such restriction. The only restrictions on operator[] are:

It must take exactly one argument.

It must be defined as a member function (it cannot be a namespace-scope function).

Body:
I have a class Foo that manages a collection of objects of another class Bar. The managing class has a method Bar *Foo::at( int index ) to access the objects int he collection, so I can do something like myfoo->at(2)->barmethod(), say. Now I was wondering if I can overload Foo::operator[] to return a Bar*, so I could do myfoo[2]->barmethod() instead. The compiler doesn't like that. Does the return type of the operator necessarily need to be a reference to the class it is a member of?

Here is some code. The first works, the second doesn't.

Foo::Bar *Foo::at( size_t index )
{
    return index < m_count ? m_entry[index] : 0;
}

Foo::Bar *Foo::operator[]( size_t index )
{
    return index < m_count ? m_entry[index] : 0;
}

From the header:

class Foo
{
public:

    class Bar
    {
    ...
    };

    size_t add( UINT8 addr, UINT8 type, UINT8 opt, UINT8 rev );
    Bar    *at( size_t index );
    Bar    *operator[]( size_t index );
    ....

protected:

    Bar             **m_entry;      // array of entry pointers
    size_t          m_size;
    size_t          m_count;

};

Here's the code the compiler doesn't like (when using [ ]):

Foo *myfoo;
...
myfoo[i]->barmethod();

and now in writing this I see what the problem is. I'm using [] on a POINTER to a Foo, not on an actual Foo. So if I dereference it, it should work. The compiler error is exactly right:

error: base operand of '->' has non-pointer type 'Foo'

Duh. Okay, sorry for the dumb question. Thanks for your suggestions.


问:
IF NOT EXIST Recored Select Some Data
I wrote a query that selects highest record from tbl. I want check if there is no record in tbl my query return fake data like (StudentId = 1,HighScore=0)

```<code>var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints
                select new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                }))
    group T by new
    {
        T.StudentId
    } into g
    orderby
      ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending
    select new
    {
        g.Key.StudentId,
        HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0)
    }).Take(1);
</code>```

答:
Cleaning up your code a bit:

```<code>var queryWin = (from tbl_ActPoints in dc.tbl_ActPoints
                group new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                } by tbl_ActPoints.StudentId into g
                orderby
                  (g.Sum(p => p.Score) ?? 0) descending
                select new StudentHighScore
                {
                    g.Key.StudentId,
                    HighScore = (g.Sum(p => p.Score) ?? 0)
                }).FirstOrDefault()
                     ?? new StudentHighScore { StudentID = 1, HighScore = 0};
</code>```

The trick, and the reason coolswastik's code didn't work, as that two anonymous objects, even with the same properties, are always different, so you need a named class:

```<code>class StudentHighScore
{
    public int StudentId { get; set; }
    public int HighScore { get; set; }
}
</code>```

Title: IF NOT EXIST Recored Select Some Data

Body:
I wrote a query that selects highest record from tbl. I want check if there is no record in tbl my query return fake data like (StudentId = 1,HighScore=0)

var queryWin = (from T in ((from tbl_ActPoints in dc.tbl_ActPoints
                select new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                }))
    group T by new
    {
        T.StudentId
    } into g
    orderby
      ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0) descending
    select new
    {
        g.Key.StudentId,
        HighScore = ((System.Int32?)g.Sum(p => p.Score) ?? (System.Int32?)0)
    }).Take(1);

Body:
Cleaning up your code a bit:

var queryWin = (from tbl_ActPoints in dc.tbl_ActPoints
                group new
                {
                    tbl_ActPoints.StudentId,
                    tbl_ActPoints.Score
                } by tbl_ActPoints.StudentId into g
                orderby
                  (g.Sum(p => p.Score) ?? 0) descending
                select new StudentHighScore
                {
                    g.Key.StudentId,
                    HighScore = (g.Sum(p => p.Score) ?? 0)
                }).FirstOrDefault()
                     ?? new StudentHighScore { StudentID = 1, HighScore = 0};

The trick, and the reason coolswastik's code didn't work, as that two anonymous objects, even with the same properties, are always different, so you need a named class:

class StudentHighScore
{
    public int StudentId { get; set; }
    public int HighScore { get; set; }
}


问:
How i can shift one row of data frame to first row?
How i can shift one raw of data frame to first raw, i want the id raw be the first raw. in R.</p>

```<code>Sepal.Length Sepal.Width Petal.Length Petal.Width Species

5.1         3.5          1.4         0.2         setosa
4.9         3.0          1.4         0.2         setosa
4.7         3.2          1.3         0.2         setosa
4.6         3.1          1.5         0.2         setosa
5.0         3.6          1.4         0.2         setosa
id           A            B           C            D
</code>```

答:
You could do the following (assuming your ID is the Nth row):

```<code>df <- iris # Example of data.frame
myIdrow <- 5 # as an example id row
df2 <- df[c(myIdrow, (1:nrow(df))[-myIdrow]), ]
</code>```

Although I would recommend to have the ID as column name.

Body:
How i can shift one raw of data frame to first raw, i want the id raw be the first raw. in R.

Sepal.Length Sepal.Width Petal.Length Petal.Width Species

5.1         3.5          1.4         0.2         setosa
4.9         3.0          1.4         0.2         setosa
4.7         3.2          1.3         0.2         setosa
4.6         3.1          1.5         0.2         setosa
5.0         3.6          1.4         0.2         setosa
id           A            B           C            D

Body:
You could do the following (assuming your ID is the Nth row):

df <- iris # Example of data.frame
myIdrow <- 5 # as an example id row
df2 <- df[c(myIdrow, (1:nrow(df))[-myIdrow]), ]

Although I would recommend to have the ID as column name.


答:
C++ when to use delete[] and properly deallocate memory?

When the memory was allocated memory with new[] and that memory has not yet been deallocated, and won't be deallocated by anyone else.

So, is this valid?

Not valid. What you've shown has undefined behaviour. You may not deallocate automatic variables. You may not call delete[] on anything that wasn't allocated with new[].

Is this necessary?

Not necessary. Automatic variables are destroyed... automatically, when they go out of scope.

bytes is technically an unsigned char * type, right?

I know I technically have a pointer

Not right. bytes is in all regards, an array. Not a pointer.

So is C++ different from C in that regard about pointers to arrays?

Not different. Arrays are arrays in C as well.

You may be confused with array decaying. When used in a value context, array name will decay into a pointer to first element. The pointer that the array decays into is a pointer, but the array is not. Example:

```<code>int  arr[4] = {1, 2, 3, 4}; // an array
int* ptr  = arr;            // a pointer; arr decays and is assignable to a pointer
int* ptr2 = &arr[0]         // decaying is syntactic sugar for this
int size1 = sizeof arr;     // size of the array == sizeof(int)*4
int size2 = sizeof ptr;     // size of the pointer == sizeof(int*)
</code>```

Also, in a function argument list, array declaration is the same as a pointer declaration. Which is highly confusing. You just have to remember that arrays can not be passed by value, so an array as function argument must mean something else.

```<code>void foo(int[4]); // confusing
void foo(int*);   // actually means this
</code>```

Body:
C++ when to use delete[] and properly deallocate memory?

When the memory was allocated memory with new[] and that memory has not yet been deallocated, and won't be deallocated by anyone else.

So, is this valid?

Not valid. What you've shown has undefined behaviour. You may not deallocate automatic variables. You may not call delete[] on anything that wasn't allocated with new[].

Is this necessary?

Not necessary. Automatic variables are destroyed... automatically, when they go out of scope.

bytes is technically an unsigned char * type, right?

I know I technically have a pointer

Not right. bytes is in all regards, an array. Not a pointer.

So is C++ different from C in that regard about pointers to arrays?

Not different. Arrays are arrays in C as well.

You may be confused with array decaying. When used in a value context, array name will decay into a pointer to first element. The pointer that the array decays into is a pointer, but the array is not. Example:

int  arr[4] = {1, 2, 3, 4}; // an array
int* ptr  = arr;            // a pointer; arr decays and is assignable to a pointer
int* ptr2 = &arr[0]         // decaying is syntactic sugar for this
int size1 = sizeof arr;     // size of the array == sizeof(int)*4
int size2 = sizeof ptr;     // size of the pointer == sizeof(int*)

Also, in a function argument list, array declaration is the same as a pointer declaration. Which is highly confusing. You just have to remember that arrays can not be passed by value, so an array as function argument must mean something else.

void foo(int[4]); // confusing
void foo(int*);   // actually means this


问:
How to keep flex element's width after removing contents?
I have this flexible layout and some JS https://jsfiddle.net/7k8t3xgc/3/

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

    <div class="left">
         <div class="optional">optional content</div>
    </div>

    <div class="right">
        <div class="wordpool"></div>
        <div class="category"></div>
    </div>

</div>
</code>```

The .wordpool element is filled with some words that need to be moved to the .category element by clicking on them.

What is happening now, is that the .window element is shrinking in width when you click the words. Is there a way to prevent this behaviour? Only way I can think of is to calculate wordpools width on render and set it into a style attribute, but it has its drawbacks with responsiveness.

I can't remove the flex functionality, because both left (optional) and right panels need to be same width and centered.

I can't use static width as it needs to be responsive.

It can't be something like .window { width: 90%; } because of short content looking silly on wide screens.

Both left and right content changes between pages in my app (think of a quiz or Google Forms - can be text, can be images, checkboxes, radiobuttons etc.) but the HTML template is the same.

答:
As you want it to be dynamic, based on the actual text width on load, add this line to your script

```<code>$(".window").css('min-width', $(".window").width() + 'px');
</code>```

Updated fiddle

Instead of monitoring the resize event for smaller screens, you can do like this instead

Note, the width: 100% needs to be set using the script, if set in CSS, the calculation will be wrong

```<code>$(".window").css({'max-width':$(".window").width() + 'px','width':'100%'});
</code>```

Updated fiddle 2

Body:
I have this flexible layout and some JS https://jsfiddle.net/7k8t3xgc/3/

optional content

The .wordpool element is filled with some words that need to be moved to the .category element by clicking on them.

What is happening now, is that the .window element is shrinking in width when you click the words. Is there a way to prevent this behaviour? Only way I can think of is to calculate wordpools width on render and set it into a style attribute, but it has its drawbacks with responsiveness.

I can't remove the flex functionality, because both left (optional) and right panels need to be same width and centered.

I can't use static width as it needs to be responsive.

It can't be something like .window { width: 90%; } because of short content looking silly on wide screens.

Both left and right content changes between pages in my app (think of a quiz or Google Forms - can be text, can be images, checkboxes, radiobuttons etc.) but the HTML template is the same.

Body:
As you want it to be dynamic, based on the actual text width on load, add this line to your script

$(".window").css('min-width', $(".window").width() + 'px');

Updated fiddle

Instead of monitoring the resize event for smaller screens, you can do like this instead

Note, the width: 100% needs to be set using the script, if set in CSS, the calculation will be wrong

$(".window").css({'max-width':$(".window").width() + 'px','width':'100%'});

Updated fiddle 2


问:
Too many arguments to 'Public Function MsgBox...'
I have an error like this:

Too many arguments to 'Public Function MsgBox(Prompt As Object, [Buttons As Microsoft.VisualBasic.MsgBoxStyle = MsgBoxStyle.OkOnly], [Title As Object = Nothing]) As Microsoft.VisualBasic.MsgBoxResult'.

And my code is like this:

```<code>Private Sub LogoutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LogoutToolStripMenuItem.Click
    If MsgBox("Are You Sure?", vbYesNo, MsgBoxStyle.Question, "Logout") = MsgBoxResult.Yes Then
        Form6.ShowDialog()
        Me.Close()
    End If
End Sub
</code>```

And I don't know why this error is occurring. Am I missing something?

答:
Using the proper MessageBox.Show overload (instead of the legacy MsgBox function), it should look like this:

```<code>If MessageBox.Show("Are you sure?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
    Form6.ShowDialog()
    Me.Close()
End If
</code>```

Body:
I have an error like this:

Too many arguments to 'Public Function MsgBox(Prompt As Object, [Buttons As Microsoft.VisualBasic.MsgBoxStyle = MsgBoxStyle.OkOnly], [Title As Object = Nothing]) As Microsoft.VisualBasic.MsgBoxResult'.

And my code is like this:

Private Sub LogoutToolStripMenuItem_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles LogoutToolStripMenuItem.Click
    If MsgBox("Are You Sure?", vbYesNo, MsgBoxStyle.Question, "Logout") = MsgBoxResult.Yes Then
        Form6.ShowDialog()
        Me.Close()
    End If
End Sub

And I don't know why this error is occurring. Am I missing something?

Body:
Using the proper MessageBox.Show overload (instead of the legacy MsgBox function), it should look like this:

If MessageBox.Show("Are you sure?", "Logout", MessageBoxButtons.YesNo, MessageBoxIcon.Question) = DialogResult.Yes Then
    Form6.ShowDialog()
    Me.Close()
End If


问:
Unable to access "_ngcontent-c1" elements using protractor
Unable to access the below element

```<code>< input _ngcontent-c1="" name="field1" value="" type="text" >
</code>```

I declared and access the element as below, But unable to access the element.

```<code>Format1: this.loginTextBox = $("input[name='field1']");
                   (or)
Format2: loginTextBox  : element(by.name('field1')),
</code>```

And in step definition I called it as:

```<code>  expect((login.loginTextBox).isPresent()).to.eventually.be.false;
</code>```

While executing the above condition got pass. can anyone help me on this....

答:
I assume that ** means commented line.
If so, everything looks correct. You are expecting that element is not present and due the commented input the assertion returns true.

Body:
Unable to access the below element

< input _ngcontent-c1="" name="field1" value="" type="text" >

I declared and access the element as below, But unable to access the element.

Format1: this.loginTextBox = $("input[name='field1']");
                   (or)
Format2: loginTextBox  : element(by.name('field1')),

And in step definition I called it as:

  expect((login.loginTextBox).isPresent()).to.eventually.be.false;

While executing the above condition got pass. can anyone help me on this....


问:
Where does the space from the top-margin came from?
I started to learn CSS, and I got to that example in the internet:
https://www.w3schools.com/css/tryit.asp?filename=trycss_margin_shorthand

But I tried to play with it, and changed some things. Now the code looks like:

 div#my {
        border: 8px solid black;
        margin-left: 0%;
        margin-right: 0%;

        height: 500px;

        background-color: red;
    }

    div {
        border: 5px solid black;
        margin: inherit;
        background-color: lightblue;
    }

    ```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="my">
   <div>This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.</div>
</div></code>```

What I see is a big blue block inside a big red block. The blue block collapse with his left and right sides to the red block's border, but from the top I have margin for some reason.

I think its because I chose inherit in the css element. But that says that I have a default margin to the page. Please, help here to understand.

答:
There's default margin to body tag of 8px which gets attached to your child divs because of explicitly written rule margin: inherit. You have to change the margin form inherit to 0 or remove it, in order to child elements don't have weird (default) margins.

div#my {
        border: 8px solid black;
        margin-left: 0%;
        margin-right: 0%;

        height: 500px;

        background-color: red;
    }

    div {
        border: 5px solid black;
        margin: 0;
        background-color: lightblue;
    }```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="my">
  <div>This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.</div>
</div></code>```

Body:
I started to learn CSS, and I got to that example in the internet:
https://www.w3schools.com/css/tryit.asp?filename=trycss_margin_shorthand

But I tried to play with it, and changed some things. Now the code looks like:

 div#my {
        border: 8px solid black;
        margin-left: 0%;
        margin-right: 0%;

        height: 500px;

        background-color: red;
    }

    div {
        border: 5px solid black;
        margin: inherit;
        background-color: lightblue;
    }

This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.

What I see is a big blue block inside a big red block. The blue block collapse with his left and right sides to the red block's border, but from the top I have margin for some reason.

I think its because I chose inherit in the css element. But that says that I have a default margin to the page. Please, help here to understand.

Body:
There's default margin to body tag of 8px which gets attached to your child divs because of explicitly written rule margin: inherit. You have to change the margin form inherit to 0 or remove it, in order to child elements don't have weird (default) margins.

div#my {
        border: 8px solid black;
        margin-left: 0%;
        margin-right: 0%;

        height: 500px;

        background-color: red;
    }

    div {
        border: 5px solid black;
        margin: 0;
        background-color: lightblue;
    }

<div id="my">
  <div>This div element has a top margin of 100px, a right margin of 150px, a bottom margin of 100px, and a left margin of 80px.</div>
</div>


问:
Android,Problems with Fragment hierarchy
I currently have a fragment with a view pager inside, one of its three childern has a recycler view with selectable items, when an item is selected, another fragment,with a recycler view, is showed (it is an indipendent fragment and not showed in the same view pager).

What i'm trying to do, is to replace F1 with F2 from F1,1. When F2.onCreateView() is invoked i obtain this error:

"java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."

In order to provide a FragmentManager to the FragmentPagerAdapter, F1.getChildFragmentManger() is invoked when F1 starts.

The steps I'm following "when an item is selected from F1,1" are:

1) get the parent fragment

2) get the FragmentManager from parent fragment

3) replace parent fragment (F1) with F2.

I suspect the problem is the way i'm trying to change fragments, i also tried, always from F1,1, to get the FragmentManager directly from the activity. I know, maybe it is a very bad idea but i had to try something...

this is the F1,1 method that is invoked when you select an item from the recycler view.

```<code>@Override
public void navigateToProductListView(Vendor vendor, Category category) {
    Bundle argument = new Bundle();
    argument.putParcelable(Vendor.TAG, vendor);
    argument.putParcelable(Category.TAG, category);

    FragmentManager fragmentManager = getParentFragment().getFragmentManager();

    ProductListFragment productListFragment = (ProductListFragment) fragmentManager.findFragmentByTag(ProductListFragment.TAG);

    if (productListFragment == null) {
        productListFragment = new ProductListFragment();
        Log.i("ProductListFragment", "was null");
    }

    productListFragment.setArguments(argument);
    Transitions.replaceFragment(fragmentManager, productListFragment, ProductListFragment.TAG, true);
}
</code>```

and onCreateView() of F2 that throws the exception

```<code>@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_product_list, container, false);

    mUnbinder = ButterKnife.bind(this, root);

    ListHelper.init(getActivity(), mRecyclerView);

    Log.i("ProductListFragment","onCreateView()");

    return root;
}
</code>```

this is the code of my Transitions class, i use only one activity so the FrameLayout used to hold fragments is always the same

```<code>public static void replaceFragment(FragmentManager fragmentManager, Fragment fragment, String tag, boolean addToBackStack) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        Slide enterTransition = new Slide(Gravity.BOTTOM);
        enterTransition.setDuration(500);
        fragment.setEnterTransition(enterTransition);
        fragment.setAllowEnterTransitionOverlap(false);
    }

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment, tag);
    if (addToBackStack) {
        fragmentTransaction.addToBackStack(null);
    }
    fragmentTransaction.commit();
}
</code>```

答:
FragmentManager fragmentManager = getParentFragment().getFragmentManager(); this statement gives you the parent private FragmentManager for placing and managing Fragments inside of this Fragment.
Try this FragmentManager fragmentManager = getParentFragment().getActivity().getFragmentManager();

Body:
I currently have a fragment with a view pager inside, one of its three childern has a recycler view with selectable items, when an item is selected, another fragment,with a recycler view, is showed (it is an indipendent fragment and not showed in the same view pager).

What i'm trying to do, is to replace F1 with F2 from F1,1. When F2.onCreateView() is invoked i obtain this error:

"java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first."

In order to provide a FragmentManager to the FragmentPagerAdapter, F1.getChildFragmentManger() is invoked when F1 starts.

The steps I'm following "when an item is selected from F1,1" are:

1) get the parent fragment

2) get the FragmentManager from parent fragment

3) replace parent fragment (F1) with F2.

I suspect the problem is the way i'm trying to change fragments, i also tried, always from F1,1, to get the FragmentManager directly from the activity. I know, maybe it is a very bad idea but i had to try something...

this is the F1,1 method that is invoked when you select an item from the recycler view.

@Override
public void navigateToProductListView(Vendor vendor, Category category) {
    Bundle argument = new Bundle();
    argument.putParcelable(Vendor.TAG, vendor);
    argument.putParcelable(Category.TAG, category);

    FragmentManager fragmentManager = getParentFragment().getFragmentManager();

    ProductListFragment productListFragment = (ProductListFragment) fragmentManager.findFragmentByTag(ProductListFragment.TAG);

    if (productListFragment == null) {
        productListFragment = new ProductListFragment();
        Log.i("ProductListFragment", "was null");
    }

    productListFragment.setArguments(argument);
    Transitions.replaceFragment(fragmentManager, productListFragment, ProductListFragment.TAG, true);
}

and onCreateView() of F2 that throws the exception

@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
    View root = inflater.inflate(R.layout.fragment_product_list, container, false);

    mUnbinder = ButterKnife.bind(this, root);

    ListHelper.init(getActivity(), mRecyclerView);

    Log.i("ProductListFragment","onCreateView()");

    return root;
}

this is the code of my Transitions class, i use only one activity so the FrameLayout used to hold fragments is always the same

public static void replaceFragment(FragmentManager fragmentManager, Fragment fragment, String tag, boolean addToBackStack) {
    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
        Slide enterTransition = new Slide(Gravity.BOTTOM);
        enterTransition.setDuration(500);
        fragment.setEnterTransition(enterTransition);
        fragment.setAllowEnterTransitionOverlap(false);
    }

    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();
    fragmentTransaction.replace(R.id.fragment_container, fragment, tag);
    if (addToBackStack) {
        fragmentTransaction.addToBackStack(null);
    }
    fragmentTransaction.commit();
}


问:
Unexpected virtual host behavior of Drupal sites on Apache
I'm running an Apache server on a CentOS 7 machine.

A month ago I created a new Drupal site (let's call it site1) under /var/www/html/site1.
Visiting http://<server-ip>/site1 yielded site1 correctly.

Today, in order to provide a test environment for a new customer, I had to create a virtual host for a new Drupal site (let's call it site2).

So I created the following vhost rule:

```<code><VirtualHost *:80>
        ServerAdmin test@email.com
        ServerName site2.dev
        DocumentRoot /var/www/html/site2
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>
</code>```

After that I created the site's folder /var/www/html/site2 and installed Drupal. Visiting http://site2.dev yields site2 correctly.

The problem is, if I now visit http://<server-ip>/site1, site2 is shown.

I can't figure out what might be the problem. The two sites are on completely different paths and different databases, so one shouldn't affect the other in my opinion.

Since I literally defined my first vhost today, I was wondering if someone might help me explain the issue. Thanks in advance!

答:
Based on Laurent's answer, this is the configuration I ended up using:</p>

```<code># So all IP only paths continue to work
<VirtualHost *:80>
        DocumentRoot /var/www/html/
        ServerName 10.10.10.10          # Server's IP
        <Directory /var/www/html/>
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>

# So site2.dev points to its folder
<VirtualHost *:80>
        DocumentRoot /var/www/html/site2
        ServerName site2.dev
        <Directory /var/www/html/site2>
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>
</code>```

Body:
I'm running an Apache server on a CentOS 7 machine.

A month ago I created a new Drupal site (let's call it site1) under /var/www/html/site1.
Visiting http://<server-ip>/site1 yielded site1 correctly.

Today, in order to provide a test environment for a new customer, I had to create a virtual host for a new Drupal site (let's call it site2).

So I created the following vhost rule:

<VirtualHost *:80>
        ServerAdmin test@email.com
        ServerName site2.dev
        DocumentRoot /var/www/html/site2
        <Directory />
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>

After that I created the site's folder /var/www/html/site2 and installed Drupal. Visiting http://site2.dev yields site2 correctly.

The problem is, if I now visit http://<server-ip>/site1, site2 is shown.

I can't figure out what might be the problem. The two sites are on completely different paths and different databases, so one shouldn't affect the other in my opinion.

Since I literally defined my first vhost today, I was wondering if someone might help me explain the issue. Thanks in advance!

Body:
Based on Laurent's answer, this is the configuration I ended up using:

# So all IP only paths continue to work
<VirtualHost *:80>
        DocumentRoot /var/www/html/
        ServerName 10.10.10.10          # Server's IP
        <Directory /var/www/html/>
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>

# So site2.dev points to its folder
<VirtualHost *:80>
        DocumentRoot /var/www/html/site2
        ServerName site2.dev
        <Directory /var/www/html/site2>
                Options FollowSymLinks
                AllowOverride All
        </Directory>
</VirtualHost>