问:
How to represent range in mongoose schema?

Background

Lets say I am doing a schema about fruits that you can buy. In this schema, a fruit has a price range:

```<code>let fruit = {
    name: "banana",
    price: {
        currency: "EUR",
        range: [2, 10]
    }
};
</code>```

To achieve saving the above object, I am trying to use the following schema:

```<code>let fruitSchema = {
    name: {type: String, required: true},
    price: {
        currency: {type: String, required: true},
        range: [{
            type: Number,
            min: 0
        }],
        validate: [arraySize]
    }
};

const arraySize = function arrayLimit(val) {
  return val.length === 2;
};
</code>```

Problem:

My solution to the range part feels clunky, over complicated and doesn't check if the Max range value is bigger than the Min range value, i.e., doesn't check if 10 > 2.

Question:

How would you implement a price range in a schema in mongoose ?

答:
My solution

I decided to have both values in my Schema separately, like in the example bellow:

```<code>income: {
    currency: { type: String },
    range: {
        min: { type: Number, min: 0 },
        max: { type: Number, min: 0 }
    }
}
</code>```

Problem

However, now I am left with a problem. How to check that my MAX >= MIN at all times, and that MIN <= MAX ??

Given that nor MIN nor MAX are mandatory, one can have an object with just an upper range, or just a lower one.

Enter Custom Validators

To fix this validation issue, I used custom validator functions. Validators were the missing piece in the puzzle, and allowed me to enforce max and min restrictions:

validate object for min:

```<code>validate: {
    validator: function(val){
        const currMax = this.target.income.range.max;
        return (currMax !== undefined ? val <= currMax : true);
    },
    message: "The MIN range with value {VALUE} must be <= than the max range!"
}
</code>```

validate object for max:

```<code>validate: {
    validator: function(val) {
        const currMin = this.target.income.range.min;
        return (currMin !== undefined ? val >= currMin : true);
    },
    message: "The MAX range with value {VALUE} must be >= than the min range!"
}
</code>```

Final result

Thus, the final result is as follows:

```<code>income: {
    currency: { type: String },
    range: {
        min: {
            type: Number, min: 0,
            validate: {
                validator: function(val){
                    const currMax = this.target.income.range.max;
                    return (currMax !== undefined ? val <= currMax : true);
                },
                message: "The MIN range with value {VALUE} must be <= than the max range!"
            }
        },
        max: {
            type: Number, min: 0,
            validate: {
                validator: function(val) {
                    const currMin = this.target.income.range.min;
                    return (currMin !== undefined ? val >= currMin : true);
                },
                message: "The MAX range with value {VALUE} must be >= than the min range!"
            }
        }
    }
}
</code>```

Going further

This solution is nice, shows advanced knowledge and does the requirements. In you try to insert an object where MIN > MAX, you will have a nice error message with the VALUE being inserted.

However, I have the following questions / suggestions for improvement, that I didn't add because I don't yet know how to do:

The validator will keep inconsistent objects from being inserted. However, when it does not prevent bad UPDATES, i.e., the following example will work on an object with MIN = 10:

ObjModel.update(
    { _id: "58dd26b5476664e33eec4b93" },
    { $set: {"income.range.max": 1}} );

To do updates on objects using validators, you must use the save method, and follow the convention described at the end of the mongoose docs.

```<code>Model.findOne({ name: 'borne' }, function (err, doc){
  doc.name = 'jason borne';
  doc.visits.$inc();
  doc.save();
});
</code>```

Which will trigger the validator as expected.

In the functions to check MIN and MAX, you can print the value being evaluated using {VALUE}. However, can you use other values of the object? When comparing MIN and MAX, it would be useful to print the value being evaluated as well as the values it is being compared to.

Hope it helps, and inspires!

Body:
Background

Lets say I am doing a schema about fruits that you can buy. In this schema, a fruit has a price range:

let fruit = {
    name: "banana",
    price: {
        currency: "EUR",
        range: [2, 10]
    }
};

To achieve saving the above object, I am trying to use the following schema:

let fruitSchema = {
    name: {type: String, required: true},
    price: {
        currency: {type: String, required: true},
        range: [{
            type: Number,
            min: 0
        }],
        validate: [arraySize]
    }
};

const arraySize = function arrayLimit(val) {
  return val.length === 2;
};

Problem:

My solution to the range part feels clunky, over complicated and doesn't check if the Max range value is bigger than the Min range value, i.e., doesn't check if 10 > 2.

Question:

How would you implement a price range in a schema in mongoose ?

Body:
My solution

I decided to have both values in my Schema separately, like in the example bellow:

income: {
    currency: { type: String },
    range: {
        min: { type: Number, min: 0 },
        max: { type: Number, min: 0 }
    }
}

Problem

However, now I am left with a problem. How to check that my MAX >= MIN at all times, and that MIN <= MAX ??

Given that nor MIN nor MAX are mandatory, one can have an object with just an upper range, or just a lower one.

Enter Custom Validators

To fix this validation issue, I used custom validator functions. Validators were the missing piece in the puzzle, and allowed me to enforce max and min restrictions:

validate object for min:

validate: {
    validator: function(val){
        const currMax = this.target.income.range.max;
        return (currMax !== undefined ? val <= currMax : true);
    },
    message: "The MIN range with value {VALUE} must be <= than the max range!"
}

validate object for max:

validate: {
    validator: function(val) {
        const currMin = this.target.income.range.min;
        return (currMin !== undefined ? val >= currMin : true);
    },
    message: "The MAX range with value {VALUE} must be >= than the min range!"
}

Final result

Thus, the final result is as follows:

income: {
    currency: { type: String },
    range: {
        min: {
            type: Number, min: 0,
            validate: {
                validator: function(val){
                    const currMax = this.target.income.range.max;
                    return (currMax !== undefined ? val <= currMax : true);
                },
                message: "The MIN range with value {VALUE} must be <= than the max range!"
            }
        },
        max: {
            type: Number, min: 0,
            validate: {
                validator: function(val) {
                    const currMin = this.target.income.range.min;
                    return (currMin !== undefined ? val >= currMin : true);
                },
                message: "The MAX range with value {VALUE} must be >= than the min range!"
            }
        }
    }
}

Going further

This solution is nice, shows advanced knowledge and does the requirements. In you try to insert an object where MIN > MAX, you will have a nice error message with the VALUE being inserted.

However, I have the following questions / suggestions for improvement, that I didn't add because I don't yet know how to do:

The validator will keep inconsistent objects from being inserted. However, when it does not prevent bad UPDATES, i.e., the following example will work on an object with MIN = 10:

ObjModel.update(
    { _id: "58dd26b5476664e33eec4b93" },
    { $set: {"income.range.max": 1}} );

To do updates on objects using validators, you must use the save method, and follow the convention described at the end of the mongoose docs.

Model.findOne({ name: 'borne' }, function (err, doc){
  doc.name = 'jason borne';
  doc.visits.$inc();
  doc.save();
});

Which will trigger the validator as expected.

In the functions to check MIN and MAX, you can print the value being evaluated using {VALUE}. However, can you use other values of the object? When comparing MIN and MAX, it would be useful to print the value being evaluated as well as the values it is being compared to.

Hope it helps, and inspires!


来源: stackexchange

问:
Show null values while joining SQL Server tables
Stuck on this assignment and its not displaying null values as it should.

Instructions:

List the number of transactions handled by each department. Include

  departments that have not handled any transactions. Show your results
  in ascending order on department.

This is what I have so far and it displays the total transactions for departments with transaction and skips the null values.

```<code>SELECT
    PC.Department,
    COUNT(TD.TransactionID) AS TotalTransactions
FROM
    TRANSACTION_DETAILS TD
INNER JOIN
    PRODUCTS P ON P.ItemCode = TD.ItemCode
LEFT OUTER JOIN
    PRODUCT_CATEGORIES PC ON P.Category = PC.Category
GROUP BY
    PC.Department
ORDER BY
    PC.Department ASC
</code>```

答:
If you need  also department without value you need  left join  starting PRODUCT_CATEGORIES  ( Department)</p>

```<code>  SELECT PC.Department, COUNT(TD.TransactionID) AS TotalTransactions
  FROM PRODUCT_CATEGORIES PC
  LEFT  JOIN PRODUCTS P ON P.Category = PC.Category
  LEFT  JOIN TRANSACTION_DETAILS TD ON P.ItemCode = TD.ItemCode
  GROUP BY PC.Department
  ORDER BY PC.Department ASC
</code>```

ContentLicense: CC BY-SA 3.0

Body:
Stuck on this assignment and its not displaying null values as it should.

Instructions:

List the number of transactions handled by each department. Include

  departments that have not handled any transactions. Show your results
  in ascending order on department.

This is what I have so far and it displays the total transactions for departments with transaction and skips the null values.

SELECT
    PC.Department,
    COUNT(TD.TransactionID) AS TotalTransactions
FROM
    TRANSACTION_DETAILS TD
INNER JOIN
    PRODUCTS P ON P.ItemCode = TD.ItemCode
LEFT OUTER JOIN
    PRODUCT_CATEGORIES PC ON P.Category = PC.Category
GROUP BY
    PC.Department
ORDER BY
    PC.Department ASC

Body:
If you need  also department without value you need  left join  starting PRODUCT_CATEGORIES  ( Department)

  SELECT PC.Department, COUNT(TD.TransactionID) AS TotalTransactions
  FROM PRODUCT_CATEGORIES PC
  LEFT  JOIN PRODUCTS P ON P.Category = PC.Category
  LEFT  JOIN TRANSACTION_DETAILS TD ON P.ItemCode = TD.ItemCode
  GROUP BY PC.Department
  ORDER BY PC.Department ASC


问:
MS SQL Server: Treat Column As Json
I want a function (MS SQL Server 2016) that can recursively call itself to traverse a tree and to return that traversal as a single Json value.  I have a working chunk of code, shown below, but I'd like to do something other than the clunky JSON_MODIFY I've used.  Unfortunately, I can't find a way to make it work without it.  If you comment out the line of code with the JSON_MODIFY and uncomment the next line, you'll see what I mean.

Is there a better solution?

```<code>DROP TABLE dbo.Node;
GO

DROP FUNCTION dbo.NodeList;
GO

CREATE TABLE dbo.Node (
    NodeId INT NOT NULL ,
    ParentNodeId INT NULL ,
    NodeName NVARCHAR(MAX)
);
GO

INSERT  dbo.Node(NodeId, ParentNodeId, NodeName)
VALUES  (1, NULL, 'A'), (2, 1, 'B'), (3, 1, 'C'), (4, 3, 'D'), (5, 3, 'E');
GO

CREATE FUNCTION dbo.NodeList(@ParentNodeId INT) RETURNS NVARCHAR(MAX)
AS BEGIN
    DECLARE @JsonOut NVARCHAR(MAX) = (
        SELECT  n.NodeId ,
                n.NodeName ,
                JSON_MODIFY(dbo.NodeList(n.NodeId), '$.x', '') AS Children
                -- dbo.NodeList(n.NodeId) AS Children
        FROM    dbo.Node n
        WHERE   ISNULL(n.ParentNodeId, -1) = ISNULL(@ParentNodeId, -1)
        FOR JSON AUTO
        ) ;
    RETURN @JsonOut;
END;
GO

PRINT dbo.NodeList(NULL);
GO
</code>```

The output with the JSON_MODIFY is exactly what I want...

```<code>[{"NodeId":1,"NodeName":"A","Children":[{"NodeId":2,"NodeName":"B"},
{"NodeId":3,"NodeName":"C","Children":[{"NodeId":4,"NodeName":"D"},
{"NodeId":5,"NodeName":"E"}]}]}]
</code>```

... but without it, it all goes wrong ...

```<code>[{"NodeId":1,"NodeName":"A","Children":"[{\"NodeId\":2,\"NodeName\":\"B\"},
{\"NodeId\":3,\"NodeName\":\"C\",\"Children\":\"
[{\\\"NodeId\\\":4,\\\"NodeName\\\":\\\"D\\\"},
{\\\"NodeId\\\":5,\\\"NodeName\\\":\\\"E\\\"}]\"}]"}]
</code>```

Thanks in advance for any ideas.

答:
Two things:

1) The JSON_MODIFY() doesn't actually generate exactly what I want.  Using the original code, the JSON_MODIFY adds an element with the name 'x' and the value '' to the value.

2) Although not a perfect answer, it is much cleaner to replace JSON_MODIFY() with JSON_QUERY() (specifically with JSON_QUERY(dbo.NodeList(...), '$').  Not only does it make more sense, this way but it gets rid of the extra 'x' artifact.

SQL obviously know that whatever comes back from JSON_MODIFY isn't really just an NVARCHAR (despite its signature), but I can't find any other way to make SQL think that an NVARCHAR is JSON.

Title: MS SQL Server: Treat Column As Json

Body:
I want a function (MS SQL Server 2016) that can recursively call itself to traverse a tree and to return that traversal as a single Json value.  I have a working chunk of code, shown below, but I'd like to do something other than the clunky JSON_MODIFY I've used.  Unfortunately, I can't find a way to make it work without it.  If you comment out the line of code with the JSON_MODIFY and uncomment the next line, you'll see what I mean.

Is there a better solution?

DROP TABLE dbo.Node;
GO

DROP FUNCTION dbo.NodeList;
GO

CREATE TABLE dbo.Node (
    NodeId INT NOT NULL ,
    ParentNodeId INT NULL ,
    NodeName NVARCHAR(MAX)
);
GO

INSERT  dbo.Node(NodeId, ParentNodeId, NodeName)
VALUES  (1, NULL, 'A'), (2, 1, 'B'), (3, 1, 'C'), (4, 3, 'D'), (5, 3, 'E');
GO

CREATE FUNCTION dbo.NodeList(@ParentNodeId INT) RETURNS NVARCHAR(MAX)
AS BEGIN
    DECLARE @JsonOut NVARCHAR(MAX) = (
        SELECT  n.NodeId ,
                n.NodeName ,
                JSON_MODIFY(dbo.NodeList(n.NodeId), '$.x', '') AS Children
                -- dbo.NodeList(n.NodeId) AS Children
        FROM    dbo.Node n
        WHERE   ISNULL(n.ParentNodeId, -1) = ISNULL(@ParentNodeId, -1)
        FOR JSON AUTO
        ) ;
    RETURN @JsonOut;
END;
GO

PRINT dbo.NodeList(NULL);
GO

The output with the JSON_MODIFY is exactly what I want...

[{"NodeId":1,"NodeName":"A","Children":[{"NodeId":2,"NodeName":"B"},
{"NodeId":3,"NodeName":"C","Children":[{"NodeId":4,"NodeName":"D"},
{"NodeId":5,"NodeName":"E"}]}]}]

... but without it, it all goes wrong ...

[{"NodeId":1,"NodeName":"A","Children":"[{\"NodeId\":2,\"NodeName\":\"B\"},
{\"NodeId\":3,\"NodeName\":\"C\",\"Children\":\"
[{\\\"NodeId\\\":4,\\\"NodeName\\\":\\\"D\\\"},
{\\\"NodeId\\\":5,\\\"NodeName\\\":\\\"E\\\"}]\"}]"}]

Thanks in advance for any ideas.


问:
else is not working when called by function
```<code> public static void main(String[] args) {
    //For String
    Scanner input = new Scanner(System.in);
    //For Letter
    Scanner word = new Scanner(System.in);
    String name;
     //Input For a String
    System.out.println("Enter A String");
        name = input.nextLine();

    //Input For a Char
    char letter[] = new char[3];
    System.out.println("Enter a Letter You Want to Search ");
    for(char c : letter)
        letter = word.nextLine().toCharArray();

    elfish(letter, name);

}

public static void elfish(char letter[], String name) {
     if(name.toLowerCase().contains(name.valueOf(letter).toLowerCase())) {
        System.out.println("Yes The Letter Contains Elfish");
     } else {
        System.out.println("You're Word is not in this String");
        }
}
</code>```

i m making the program which is near to completion. It actually searches the desired letter in the string and if condition is true is prints the "if block" and if condition is false "else block" should run but actually its not working now. only "if block" is working. "else block" was also working fine until it was directly placed in main function. please tell me where what is wrong.

答:
You're trying to iterate through letter before putting anything in the array.  If you take out the for loop, (leaving the assignment of letter) the code should run properly in many cases.  I do not know how you want to validate input.

I'm guessing you are new.  Learning to use a debugger can be overwhelming, but it is a powerful tool.  It'll be slightly different for every debugger and IDE but the process is the same.

A little more info here: Breakpoints and step by step debug in Java?

However, in this instance finding a guide for your IDE on Google might be the best option.

Body:
 public static void main(String[] args) {
    //For String
    Scanner input = new Scanner(System.in);
    //For Letter
    Scanner word = new Scanner(System.in);
    String name;
     //Input For a String
    System.out.println("Enter A String");
        name = input.nextLine();

    //Input For a Char
    char letter[] = new char[3];
    System.out.println("Enter a Letter You Want to Search ");
    for(char c : letter)
        letter = word.nextLine().toCharArray();

    elfish(letter, name);

}

public static void elfish(char letter[], String name) {
     if(name.toLowerCase().contains(name.valueOf(letter).toLowerCase())) {
        System.out.println("Yes The Letter Contains Elfish");
     } else {
        System.out.println("You're Word is not in this String");
        }
}

i m making the program which is near to completion. It actually searches the desired letter in the string and if condition is true is prints the "if block" and if condition is false "else block" should run but actually its not working now. only "if block" is working. "else block" was also working fine until it was directly placed in main function. please tell me where what is wrong.


问:
Concatenate Multiple Columns
I have a sheet that lists multiple values starting in C12 where the first six numbers are the same and the last three are different and are separated by spaces (e.g. 123456 111 222 333 444). I would like to use VBA to combine the values using the first six digits in the cell with however many three digit values there are in that cell (e.g. 123456111, 123456222, 123456333, 123456444). These combined values should each be in their own cell. The number of three digit values varies in each cell. I was thinking that maybe the easiest way would be to split them into columns and then combine them, but I cannot figure this out.

Here is an example:

```<code>#DATA#
1. 541259 139 285
2. 452679 245
3. 894623 455 654

#DESIRED RESULT#
1. 541259139
2. 541259285
3. 452679245
4. 894623455
5. 894623654
</code>```

I was able to separate the values onto a second sheet using the following code:

```<code>Sub Split()
Dim totalRows As Long, i As Long, sColNames As String
totalRows = LastRowWithData(Sheet1, "C")
For i = 1 To totalRows
    sColNames = Sheet1.Range("C" & i).value
    Call SplitToColumns(sColNames, " ", Sheet2.Range("A" & i))
Next i
End Sub
</code>```

I am not sure if this is the best way to do this and I cannot figure out how to join them.

Thank you for your time!

答:
Here is how I would do it:</p>

```<code>Sub SplitMyNum()
    Dim i&, j&
    Dim splt() As String
    Dim rngArr() As Variant
    Dim oWs As Worksheet
    Dim tWs As Worksheet

    Set oWs = Worksheets("Sheet1") 'change to your input
    Set tWs = Worksheets("Sheet2") 'change to your output sheet, may be the same as above

    With oWs
        rngArr = .Range(.Cells(1, 3), .Cells(.Rows.Count, 3).End(xlUp)).Value 'loads all the numbers into an array
    End With
    With tWs
        For i = LBound(rngArr, 1) To UBound(rngArr, 1) 'iterate through the numbers
            splt = Split(rngArr(i, 1), " ") 'Split the numbers on spaces
            For j = LBound(splt) + 1 To UBound(splt) 'iterates through the split values
                'Next line concatenates the first with each set after and puts it in the next available cell in column A.
                .Cells(.Rows.Count, 1).End(xlUp).Offset(1).Value = splt(LBound(splt)) & splt(j)
            Next j
        Next i
    End With
End Sub
</code>```

Title: Concatenate Multiple Columns

Body:
I have a sheet that lists multiple values starting in C12 where the first six numbers are the same and the last three are different and are separated by spaces (e.g. 123456 111 222 333 444). I would like to use VBA to combine the values using the first six digits in the cell with however many three digit values there are in that cell (e.g. 123456111, 123456222, 123456333, 123456444). These combined values should each be in their own cell. The number of three digit values varies in each cell. I was thinking that maybe the easiest way would be to split them into columns and then combine them, but I cannot figure this out.

Here is an example:

#DATA#
1. 541259 139 285
2. 452679 245
3. 894623 455 654

#DESIRED RESULT#
1. 541259139
2. 541259285
3. 452679245
4. 894623455
5. 894623654

I was able to separate the values onto a second sheet using the following code:

Sub Split()
Dim totalRows As Long, i As Long, sColNames As String
totalRows = LastRowWithData(Sheet1, "C")
For i = 1 To totalRows
    sColNames = Sheet1.Range("C" & i).value
    Call SplitToColumns(sColNames, " ", Sheet2.Range("A" & i))
Next i
End Sub

I am not sure if this is the best way to do this and I cannot figure out how to join them.

Thank you for your time!

Body:
Here is how I would do it:

Sub SplitMyNum()
    Dim i&, j&
    Dim splt() As String
    Dim rngArr() As Variant
    Dim oWs As Worksheet
    Dim tWs As Worksheet

    Set oWs = Worksheets("Sheet1") 'change to your input
    Set tWs = Worksheets("Sheet2") 'change to your output sheet, may be the same as above

    With oWs
        rngArr = .Range(.Cells(1, 3), .Cells(.Rows.Count, 3).End(xlUp)).Value 'loads all the numbers into an array
    End With
    With tWs
        For i = LBound(rngArr, 1) To UBound(rngArr, 1) 'iterate through the numbers
            splt = Split(rngArr(i, 1), " ") 'Split the numbers on spaces
            For j = LBound(splt) + 1 To UBound(splt) 'iterates through the split values
                'Next line concatenates the first with each set after and puts it in the next available cell in column A.
                .Cells(.Rows.Count, 1).End(xlUp).Offset(1).Value = splt(LBound(splt)) & splt(j)
            Next j
        Next i
    End With
End Sub


问:
How to downsize my scss code?
I started writing classes such as:

```<code>.small-bottom-margin { margin-bottom: $margin; }
.small-top-margin { margin-top: $margin; }
.medium-bottom-margin { margin-bottom: $margin *2; }
.medium-top-margin { margin-top: $margin *2; }
.large-bottom-margin { margin-bottom: $margin *4; }
.large-top-margin { margin-top: $margin *4; }
</code>```

Soon I wanted to be able to specify what happened on different screens, such as (for the small bottom margin example):

```<code>@media #{$small-only} { .small-bottom-margin-sm { margin-bottom: $margin; }}
@media #{$medium-only} { .small-bottom-margin-md { margin-bottom: $margin; }}
@media #{$large-only} { .small-bottom-margin-lg { margin-bottom: $margin; }}
@media #{$small-up} { .small-bottom-margin-sm-up { margin-bottom: $margin; }}
@media #{$medium-up} { .small-bottom-margin-md-up { margin-bottom: $margin; }}
@media #{$large-up} { .small-bottom-margin-lg-up { margin-bottom: $margin; }}
@media #{$medium-down} { .small-bottom-margin-sm-mp { margin-bottom: $margin; }}
</code>```

... etc for all the margin sizes (medium and large), and for the top margin too.

I find this extremely practical in terms of readability of my html + speed to add margins through my app, which is often a pain when you have a complicated layout, but it seems awfully long to write in my css.

Is it bad practice to do this?
  If not, is there some kind of css function that would allow me to automatically generate all this code?

答:
You have way too many classes. You are basically just replicating all the css properties only for the sake of not using inline styles, which is indeed suboptimal but definitely better than doing something like this.

When you apply a CSS class to an element, it should primarily tell what that specific element is a class of, not describe what type of visual style it should have applied.

According to the Google HTML/CSS Style guide, under ID and Class Naming they say that

```<code>/* Not recommended: presentational */
.button-green {}
.clear {}
</code>```

and should rather have something that would implicitly mean more properties at once, like

```<code>/* Recommended: specific */
.contact-image {}
.btn-primary {}
.video {}
</code>```

In this way, you avoid having extreme amounts of classes on an element (I guess you have to apply like a minimum of 4-5 of those to get an element look the way you want), and you also add meaning to an element. In HTML, meaning is always good.

Also, assuming that you have cases where your element is not satisfied fully by a class, but is more rather a variation of an existing one, you can either add the differences inline or create variation classes (like .disabled, .big, .full-width) if you think they can appear again in the future.

Title: How to downsize my scss code?

Body:
I started writing classes such as:

.small-bottom-margin { margin-bottom: $margin; }
.small-top-margin { margin-top: $margin; }
.medium-bottom-margin { margin-bottom: $margin *2; }
.medium-top-margin { margin-top: $margin *2; }
.large-bottom-margin { margin-bottom: $margin *4; }
.large-top-margin { margin-top: $margin *4; }

Soon I wanted to be able to specify what happened on different screens, such as (for the small bottom margin example):

@media #{$small-only} { .small-bottom-margin-sm { margin-bottom: $margin; }}
@media #{$medium-only} { .small-bottom-margin-md { margin-bottom: $margin; }}
@media #{$large-only} { .small-bottom-margin-lg { margin-bottom: $margin; }}
@media #{$small-up} { .small-bottom-margin-sm-up { margin-bottom: $margin; }}
@media #{$medium-up} { .small-bottom-margin-md-up { margin-bottom: $margin; }}
@media #{$large-up} { .small-bottom-margin-lg-up { margin-bottom: $margin; }}
@media #{$medium-down} { .small-bottom-margin-sm-mp { margin-bottom: $margin; }}

... etc for all the margin sizes (medium and large), and for the top margin too.

I find this extremely practical in terms of readability of my html + speed to add margins through my app, which is often a pain when you have a complicated layout, but it seems awfully long to write in my css.

Is it bad practice to do this?
  If not, is there some kind of css function that would allow me to automatically generate all this code?

Body:
You have way too many classes. You are basically just replicating all the css properties only for the sake of not using inline styles, which is indeed suboptimal but definitely better than doing something like this.

When you apply a CSS class to an element, it should primarily tell what that specific element is a class of, not describe what type of visual style it should have applied.

According to the Google HTML/CSS Style guide, under ID and Class Naming they say that

/* Not recommended: presentational */
.button-green {}
.clear {}

and should rather have something that would implicitly mean more properties at once, like

/* Recommended: specific */
.contact-image {}
.btn-primary {}
.video {}

In this way, you avoid having extreme amounts of classes on an element (I guess you have to apply like a minimum of 4-5 of those to get an element look the way you want), and you also add meaning to an element. In HTML, meaning is always good.

Also, assuming that you have cases where your element is not satisfied fully by a class, but is more rather a variation of an existing one, you can either add the differences inline or create variation classes (like .disabled, .big, .full-width) if you think they can appear again in the future.


答:
```<code>SELECT      PC.Department, COUNT(TD.TransactionID) AS TotalTransactions
FROM        PRODUCT_CATEGORIES  PC
LEFT JOIN   PRODUCTS            P   ON P.Category = PC.Category
LEFT JOIN   TRANSACTION_DETAILS TD  ON P.ItemCode = TD.ItemCode
GROUP BY    PC.Department
ORDER BY    PC.Department ASC
</code>```

Title: Show null values while joining SQL Server tables


问:
Can't get my maze wall collisions to work c#
Im trying to get the main mechanics for a maze game working but i cant figure this out.

I want it to jump the character back if they hit the rectangle but it doesn't seem to do so and you just end up stuck.

here is my code:

```<code>Texture2D txr;
    Rectangle rect;
    Vector2 position;
    Vector2 velocity;

    public player(Texture2D texture)
    {
        txr = texture;
        position = new Vector2(100, 100);
        rect = new Rectangle(100, 100, txr.Width, txr.Height);
    }

    public void update(Rectangle wall, GameTime gt)
    {
        MoveIfPossible(gt, wall);

        KeyboardState keys = Keyboard.GetState();

        if (keys.IsKeyDown(Keys.Up))
            velocity = new Vector2(0, -1);
        else if (keys.IsKeyDown(Keys.Down))
            velocity = new Vector2(0, 1);
        else if (keys.IsKeyDown(Keys.Left))
            velocity = new Vector2(-1, 0);
        else if (keys.IsKeyDown(Keys.Right))
            velocity = new Vector2(1, 0);
        else
            velocity = new Vector2(0, 0);

        rect.X = (int)position.X;
        rect.Y = (int)position.Y;

    }

    private void UpdatePositionBasedOnMovement(GameTime gameTime)
    {
        position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
    }

    private void MoveIfPossible(GameTime gameTime, Rectangle wall)
    {
        Vector2 oldPosition = position;

        UpdatePositionBasedOnMovement(gameTime);
        if (rect.Intersects(wall))
        {
            position = oldPosition;
        }
    }
</code>```

If anyone knows why it doesnt work please let me know!!

Im sorry to say that these changes have not fixed the fact that the player gets stuck on the wall. Here is the rest of my code if it helps
Game1

```<code> KeyboardState curr_keys;
    Rectangle wall_rect;
    Texture2D wall;
    player player;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        // wall
        wall_rect = new Rectangle(200, 100, 100, 100);
        player = new player(Content.Load<Texture2D>("maze_rect_border"));
        wall = Content.Load<Texture2D>("maze_rect_border");
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
    }

    protected override void UnloadContent()
    {
    }

    protected override void Update(GameTime gameTime)
    {
        curr_keys = Keyboard.GetState();
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();
        if (curr_keys.IsKeyDown(Keys.Escape))
            Exit();

        player.update(wall_rect, gameTime);

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.White);

        spriteBatch.Begin();
        spriteBatch.Draw(wall, wall_rect, Color.White);
        player.draw(spriteBatch);
        spriteBatch.End();

        base.Draw(gameTime);
    }
</code>```

player

```<code>Texture2D txr;
    Rectangle rect;
    Vector2 position;

    public player(Texture2D texture)
    {
        txr = texture;
        position = new Vector2(100, 100);
        rect = new Rectangle(100, 100, txr.Width, txr.Height);
    }

    public void update(Rectangle wall, GameTime gt)
    {
        KeyboardState keys = Keyboard.GetState();

        Vector2 velocity;
        if (keys.IsKeyDown(Keys.Up))
            velocity = new Vector2(0, -1);
        else if (keys.IsKeyDown(Keys.Down))
            velocity = new Vector2(0, 1);
        else if (keys.IsKeyDown(Keys.Left))
            velocity = new Vector2(-1, 0);
        else if (keys.IsKeyDown(Keys.Right))
            velocity = new Vector2(1, 0);
        else
            velocity = new Vector2(0, 0);

        Move(gt, wall, velocity);

        rect.X = (int)position.X;
        rect.Y = (int)position.Y;
    }

    private void Move(GameTime gameTime, Rectangle wall, Vector2 velocity)
    {
        Vector2 oldPosition = position;

        position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
        if (rect.Intersects(wall))
        {
            position = oldPosition;
        }
    }

    public void draw(SpriteBatch sb)
    {
        sb.Draw(txr, position, Color.White);
    }
</code>```

Thank you for your help so far, any other ideas?

答:
I think the issue is that you are utilizing the velocity vector before it has been initialized. I'm not sure what result that would produce. I think the root cause is that you have velocity as a class variable, when it really should be local instead.

I would change MoveIfPossible to be after velocity is initialized. I would also change velocity to be a local variable. Here's a summary of the changes with comments to track what I did.

I would also get rid of the UpdatePositionBasedOnMovement method. I'm not sure it adds anything in this case other than obfuscating what you are trying to do in this case.

```<code>Texture2D txr;
Rectangle rect;
Vector2 position;
//Vector2 velocity;

public player(Texture2D texture)
{
    txr = texture;
    position = new Vector2(100, 100);
    rect = new Rectangle(100, 100, txr.Width, txr.Height);
}

public void update(Rectangle wall, GameTime gt)
{
    //MoveIfPossible(gt, wall);     // the velocity vector was not set when this was being called

    KeyboardState keys = Keyboard.GetState();

    Vector2 velocity;  // Change this to local
    if (keys.IsKeyDown(Keys.Up))
        velocity = new Vector2(0, -1);
    else if (keys.IsKeyDown(Keys.Down))
        velocity = new Vector2(0, 1);
    else if (keys.IsKeyDown(Keys.Left))
        velocity = new Vector2(-1, 0);
    else if (keys.IsKeyDown(Keys.Right))
        velocity = new Vector2(1, 0);
    else
        velocity = new Vector2(0, 0);

    MoveIfPossible(gt, wall, velocity); // Pass vector as a parameter, if it's not needed elsewhere, keep it local

    rect.X = (int)position.X;
    rect.Y = (int)position.Y;

}

// private void UpdatePositionBasedOnMovement(GameTime gameTime)
// {
    // position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
// }

private void MoveIfPossible(GameTime gameTime, Rectangle wall, Vector2 velocity)
{
    Vector2 oldPosition = position;

    //UpdatePositionBasedOnMovement(gameTime);          // Don't think this is adding anything with just one line of code
    position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
    if (rect.Intersects(wall))
    {
        position = oldPosition;
    }
}
</code>```

Cleaning up and removing all comments, I would personally write/name it this way:

```<code>Texture2D txr;
Rectangle rect;
Vector2 position;

public player(Texture2D texture)
{
    txr = texture;
    position = new Vector2(100, 100);
    rect = new Rectangle(100, 100, txr.Width, txr.Height);
}

public void update(Rectangle wall, GameTime gt)
{
    KeyboardState keys = Keyboard.GetState();

    Vector2 velocity;
    if (keys.IsKeyDown(Keys.Up))
        velocity = new Vector2(0, -1);
    else if (keys.IsKeyDown(Keys.Down))
        velocity = new Vector2(0, 1);
    else if (keys.IsKeyDown(Keys.Left))
        velocity = new Vector2(-1, 0);
    else if (keys.IsKeyDown(Keys.Right))
        velocity = new Vector2(1, 0);
    else
        velocity = new Vector2(0, 0);

    Move(gt, wall, velocity);

    rect.X = (int)position.X;
    rect.Y = (int)position.Y;
}

private void Move(GameTime gameTime, Rectangle wall, Vector2 velocity)
{
    Vector2 oldPosition = position;

    position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
    if (rect.Intersects(wall))
    {
        position = oldPosition;
    }
}
</code>```

I'm guessing this wasn't all of the code. My gut tells me it would be better to move the Vector2 position into a local as well, although without insight into the rect.Intersects() method I don't have enough information to say for sure. Or more likely it seems like it should be a property of the rectangle class itself.

In general I would default to not using class variables. Start off by not making something a class variable. You can always go back and change that if you find a reason, but local variables simplify code. Simple code has less bugs.

Body:
Im trying to get the main mechanics for a maze game working but i cant figure this out.

I want it to jump the character back if they hit the rectangle but it doesn't seem to do so and you just end up stuck.

here is my code:

Texture2D txr;
    Rectangle rect;
    Vector2 position;
    Vector2 velocity;

    public player(Texture2D texture)
    {
        txr = texture;
        position = new Vector2(100, 100);
        rect = new Rectangle(100, 100, txr.Width, txr.Height);
    }

    public void update(Rectangle wall, GameTime gt)
    {
        MoveIfPossible(gt, wall);

        KeyboardState keys = Keyboard.GetState();

        if (keys.IsKeyDown(Keys.Up))
            velocity = new Vector2(0, -1);
        else if (keys.IsKeyDown(Keys.Down))
            velocity = new Vector2(0, 1);
        else if (keys.IsKeyDown(Keys.Left))
            velocity = new Vector2(-1, 0);
        else if (keys.IsKeyDown(Keys.Right))
            velocity = new Vector2(1, 0);
        else
            velocity = new Vector2(0, 0);

        rect.X = (int)position.X;
        rect.Y = (int)position.Y;

    }

    private void UpdatePositionBasedOnMovement(GameTime gameTime)
    {
        position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
    }

    private void MoveIfPossible(GameTime gameTime, Rectangle wall)
    {
        Vector2 oldPosition = position;

        UpdatePositionBasedOnMovement(gameTime);
        if (rect.Intersects(wall))
        {
            position = oldPosition;
        }
    }

If anyone knows why it doesnt work please let me know!!

Im sorry to say that these changes have not fixed the fact that the player gets stuck on the wall. Here is the rest of my code if it helps
Game1

 KeyboardState curr_keys;
    Rectangle wall_rect;
    Texture2D wall;
    player player;

    public Game1()
    {
        graphics = new GraphicsDeviceManager(this);
        Content.RootDirectory = "Content";
    }

    protected override void Initialize()
    {
        // wall
        wall_rect = new Rectangle(200, 100, 100, 100);
        player = new player(Content.Load<Texture2D>("maze_rect_border"));
        wall = Content.Load<Texture2D>("maze_rect_border");
        base.Initialize();
    }

    protected override void LoadContent()
    {
        spriteBatch = new SpriteBatch(GraphicsDevice);
    }

    protected override void UnloadContent()
    {
    }

    protected override void Update(GameTime gameTime)
    {
        curr_keys = Keyboard.GetState();
        // Allows the game to exit
        if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed)
            this.Exit();
        if (curr_keys.IsKeyDown(Keys.Escape))
            Exit();

        player.update(wall_rect, gameTime);

        base.Update(gameTime);
    }

    protected override void Draw(GameTime gameTime)
    {
        GraphicsDevice.Clear(Color.White);

        spriteBatch.Begin();
        spriteBatch.Draw(wall, wall_rect, Color.White);
        player.draw(spriteBatch);
        spriteBatch.End();

        base.Draw(gameTime);
    }

player

Texture2D txr;
    Rectangle rect;
    Vector2 position;

    public player(Texture2D texture)
    {
        txr = texture;
        position = new Vector2(100, 100);
        rect = new Rectangle(100, 100, txr.Width, txr.Height);
    }

    public void update(Rectangle wall, GameTime gt)
    {
        KeyboardState keys = Keyboard.GetState();

        Vector2 velocity;
        if (keys.IsKeyDown(Keys.Up))
            velocity = new Vector2(0, -1);
        else if (keys.IsKeyDown(Keys.Down))
            velocity = new Vector2(0, 1);
        else if (keys.IsKeyDown(Keys.Left))
            velocity = new Vector2(-1, 0);
        else if (keys.IsKeyDown(Keys.Right))
            velocity = new Vector2(1, 0);
        else
            velocity = new Vector2(0, 0);

        Move(gt, wall, velocity);

        rect.X = (int)position.X;
        rect.Y = (int)position.Y;
    }

    private void Move(GameTime gameTime, Rectangle wall, Vector2 velocity)
    {
        Vector2 oldPosition = position;

        position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
        if (rect.Intersects(wall))
        {
            position = oldPosition;
        }
    }

    public void draw(SpriteBatch sb)
    {
        sb.Draw(txr, position, Color.White);
    }

Thank you for your help so far, any other ideas?

Body:
I think the issue is that you are utilizing the velocity vector before it has been initialized. I'm not sure what result that would produce. I think the root cause is that you have velocity as a class variable, when it really should be local instead.

I would change MoveIfPossible to be after velocity is initialized. I would also change velocity to be a local variable. Here's a summary of the changes with comments to track what I did.

I would also get rid of the UpdatePositionBasedOnMovement method. I'm not sure it adds anything in this case other than obfuscating what you are trying to do in this case.

Texture2D txr;
Rectangle rect;
Vector2 position;
//Vector2 velocity;

public player(Texture2D texture)
{
    txr = texture;
    position = new Vector2(100, 100);
    rect = new Rectangle(100, 100, txr.Width, txr.Height);
}

public void update(Rectangle wall, GameTime gt)
{
    //MoveIfPossible(gt, wall);     // the velocity vector was not set when this was being called

    KeyboardState keys = Keyboard.GetState();

    Vector2 velocity;  // Change this to local
    if (keys.IsKeyDown(Keys.Up))
        velocity = new Vector2(0, -1);
    else if (keys.IsKeyDown(Keys.Down))
        velocity = new Vector2(0, 1);
    else if (keys.IsKeyDown(Keys.Left))
        velocity = new Vector2(-1, 0);
    else if (keys.IsKeyDown(Keys.Right))
        velocity = new Vector2(1, 0);
    else
        velocity = new Vector2(0, 0);

    MoveIfPossible(gt, wall, velocity); // Pass vector as a parameter, if it's not needed elsewhere, keep it local

    rect.X = (int)position.X;
    rect.Y = (int)position.Y;

}

// private void UpdatePositionBasedOnMovement(GameTime gameTime)
// {
    // position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
// }

private void MoveIfPossible(GameTime gameTime, Rectangle wall, Vector2 velocity)
{
    Vector2 oldPosition = position;

    //UpdatePositionBasedOnMovement(gameTime);          // Don't think this is adding anything with just one line of code
    position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
    if (rect.Intersects(wall))
    {
        position = oldPosition;
    }
}

Cleaning up and removing all comments, I would personally write/name it this way:

Texture2D txr;
Rectangle rect;
Vector2 position;

public player(Texture2D texture)
{
    txr = texture;
    position = new Vector2(100, 100);
    rect = new Rectangle(100, 100, txr.Width, txr.Height);
}

public void update(Rectangle wall, GameTime gt)
{
    KeyboardState keys = Keyboard.GetState();

    Vector2 velocity;
    if (keys.IsKeyDown(Keys.Up))
        velocity = new Vector2(0, -1);
    else if (keys.IsKeyDown(Keys.Down))
        velocity = new Vector2(0, 1);
    else if (keys.IsKeyDown(Keys.Left))
        velocity = new Vector2(-1, 0);
    else if (keys.IsKeyDown(Keys.Right))
        velocity = new Vector2(1, 0);
    else
        velocity = new Vector2(0, 0);

    Move(gt, wall, velocity);

    rect.X = (int)position.X;
    rect.Y = (int)position.Y;
}

private void Move(GameTime gameTime, Rectangle wall, Vector2 velocity)
{
    Vector2 oldPosition = position;

    position += velocity * (float)gameTime.ElapsedGameTime.TotalMilliseconds / 4;
    if (rect.Intersects(wall))
    {
        position = oldPosition;
    }
}

I'm guessing this wasn't all of the code. My gut tells me it would be better to move the Vector2 position into a local as well, although without insight into the rect.Intersects() method I don't have enough information to say for sure. Or more likely it seems like it should be a property of the rectangle class itself.

In general I would default to not using class variables. Start off by not making something a class variable. You can always go back and change that if you find a reason, but local variables simplify code. Simple code has less bugs.


问:
Preventing JavaScript Injections in a PHP Web Application
What are the measures needed to prevent or to stop JavaScript injections from happening in a PHP Web application so that sensitive information is not given out (best-practices in PHP, HTML/XHTML and JavaScript)?</p>

答:
I do not agree fully with the other answers provided so I will post my recommendations.

Recommended reading
XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

Html Injection:
Whenever displaying any user submitted content, it should be appropriately cleaned up with htmlspecialchars or htmlentities when specifying ENT_QUOTES if used inside of single quotes. I would recommend never encapsulating in single quotes and always encapsulating your attributes in double quotes (do not omit them). This applies to things such as:

```<code><input value="<?php echo htmlspecialchars($var); ?>" />
<textarea><?php echo htmlspecialchars($var); ?></textarea>
<p><?php echo htmlspecialchars($var); ?></p>
<img width="<?php echo htmlspecialchars($var); ?>" />
</code>```

Javascript Injection:
It is best practice (but not always practical) to never echo user content into events and javascript. However, if you do there are some things that can be done to reduce the risk. Only pass integer id's. If you require something such as a type specifier, then use a whitelist and/or conditional check ahead of time before outputting. Possibly force user content to alphanumeric only when appropriate; preg_replace("/[^A-Za-z0-9]/", '', $string); but be very careful what you allow here. Only include content when it is encapsulated in quotes and note that htmlspecialchars/htmlentities does not protect you here. It will be interpreted at runtime even if it has been translated into html entities.
This applies to things such as:

```<code><a href="www.stackoverlow.com/?id=<?php echo (int)$id; ?>">Click</a>
href, src, style, onClick, etc.
</code>```

Do not echo any user content into other areas such as the body of script tags etc unless it has been forced to an int or some other very very limited character set (if you know what you are doing).

SQL Injection:
Use Prepared statements, bind user content to them, and never directly insert user content into the query. I would recommend creating a class for prepared statements with helper functions for your different basic statement types (and while on the subject, functionalize all of your database statements). If you choose not to use prepared statements then use mysql_real_escape_string() or similar (not addslashes()). Validate content when possible before storing into the database such as forcing/checking for integer data type, conditional checks on types, etc. Use proper database column types and lengths. Remember the main goal here is to prevent sql injection but you can optionally do html/javascript injection protection here as well.

Other Resources
I have done some research online in hopes to find a simple solution already publicly available. I found OWASP ESAPI but it appears quite dated. The links to the php version are broken in several places. I believe I found it here; ESAPI PHP but again it is quite dated and not as simple as I was hoping for. You may find it useful however.

All in all, don't ever just assume you're protected such as using htmlentities in an onClick attribute. You must use the right tool in the right location and avoid doing things in the wrong location.

ContentLicense: CC BY-SA 2.5

Body:
I do not agree fully with the other answers provided so I will post my recommendations.

Recommended reading
XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet

Html Injection:
Whenever displaying any user submitted content, it should be appropriately cleaned up with htmlspecialchars or htmlentities when specifying ENT_QUOTES if used inside of single quotes. I would recommend never encapsulating in single quotes and always encapsulating your attributes in double quotes (do not omit them). This applies to things such as:

<input value="<?php echo htmlspecialchars($var); ?>" />
<textarea><?php echo htmlspecialchars($var); ?></textarea>
<p><?php echo htmlspecialchars($var); ?></p>
<img width="<?php echo htmlspecialchars($var); ?>" />

Javascript Injection:
It is best practice (but not always practical) to never echo user content into events and javascript. However, if you do there are some things that can be done to reduce the risk. Only pass integer id's. If you require something such as a type specifier, then use a whitelist and/or conditional check ahead of time before outputting. Possibly force user content to alphanumeric only when appropriate; preg_replace("/[^A-Za-z0-9]/", '', $string); but be very careful what you allow here. Only include content when it is encapsulated in quotes and note that htmlspecialchars/htmlentities does not protect you here. It will be interpreted at runtime even if it has been translated into html entities.
This applies to things such as:

<a href="www.stackoverlow.com/?id=<?php echo (int)$id; ?>">Click</a>
href, src, style, onClick, etc.

Do not echo any user content into other areas such as the body of script tags etc unless it has been forced to an int or some other very very limited character set (if you know what you are doing).

SQL Injection:
Use Prepared statements, bind user content to them, and never directly insert user content into the query. I would recommend creating a class for prepared statements with helper functions for your different basic statement types (and while on the subject, functionalize all of your database statements). If you choose not to use prepared statements then use mysql_real_escape_string() or similar (not addslashes()). Validate content when possible before storing into the database such as forcing/checking for integer data type, conditional checks on types, etc. Use proper database column types and lengths. Remember the main goal here is to prevent sql injection but you can optionally do html/javascript injection protection here as well.

Other Resources
I have done some research online in hopes to find a simple solution already publicly available. I found OWASP ESAPI but it appears quite dated. The links to the php version are broken in several places. I believe I found it here; ESAPI PHP but again it is quite dated and not as simple as I was hoping for. You may find it useful however.

All in all, don't ever just assume you're protected such as using htmlentities in an onClick attribute. You must use the right tool in the right location and avoid doing things in the wrong location.


问:
Generating new columns as a full-combination of other columns
Could not find similar cases here.
Suppose, i have a DataFrame

```<code>df = pd.DataFrame({'A':[2,2,1,2],
                   'B':[2,2,3,3],
                   'C':[3,3,3,4],
                   'I':[1,0,0,1],
                   'II':[0,1,0,1]})
</code>```

So it is:

```<code>    A   B   C   I   II
0   2   2   3   1   0
1   2   2   3   0   1
2   1   3   3   0   0
3   2   3   4   1   1
</code>```

I want to make a full pairwise combination between {A,B,C} and {I,II}, so i get {I-A,I-B,I-C,II-A,II-B,II-C}:

Each of a new column is just an elementwise multiplication of corresponding base columns

```<code>    I-A I-B I-C II-A  II-B  II-C
 0   2   2   3    0    0      0
 1   0   0   0    2    2      3
 2   0   0   0    0    0      0
 3   2   3   4    2    3      4
</code>```

ATM i dont have any working solution. I'am trying to use loops(not succeding in this), but i hope there's more sufficient way.

答:
Using loops, you can use this code. It's definitely not the most elegant solution but should work for your purpose. It only requires that you specify the columns that you'd like to use for the pairwise multiplication. It seems to be quite readable though, which is something you may want.

```<code>def element_wise_mult(first, second):

    element_wise_mult = []
    for i, el in enumerate(first):
        element_wise_mult.append(el * second[i])

    return element_wise_mult

if __name__ == '__main__':

    import pandas as pd

    df = pd.DataFrame({'A':[2,2,1,2],
                       'B':[2,2,3,3],
                       'C':[3,3,3,4],
                       'I':[1,0,0,1],
                      'II':[0,1,0,1]})

    fs = ['I', 'II']
    sc = ['A', 'B', 'C']

    series = []
    names = []

    for i in fs:
        for j in sc:
            names.append(i + '-' + j)
            series.append(pd.Series(element_wise(df[i], df[j])))  # append array creates as a pandas series

   print(pd.DataFrame(series, index=names).T)    # reconstruct dataframe from the series and names stored
</code>```

Returns:

```<code>   I-A  I-B  I-C  II-A  II-B  II-C
0    2    2    3     0     0     0
1    0    0    0     2     2     3
2    0    0    0     0     0     0
3    2    3    4     2     3     4
</code>```

Body:
Could not find similar cases here.
Suppose, i have a DataFrame

df = pd.DataFrame({'A':[2,2,1,2],
                   'B':[2,2,3,3],
                   'C':[3,3,3,4],
                   'I':[1,0,0,1],
                   'II':[0,1,0,1]})

So it is:

    A   B   C   I   II
0   2   2   3   1   0
1   2   2   3   0   1
2   1   3   3   0   0
3   2   3   4   1   1

I want to make a full pairwise combination between {A,B,C} and {I,II}, so i get {I-A,I-B,I-C,II-A,II-B,II-C}:

Each of a new column is just an elementwise multiplication of corresponding base columns

    I-A I-B I-C II-A  II-B  II-C
 0   2   2   3    0    0      0
 1   0   0   0    2    2      3
 2   0   0   0    0    0      0
 3   2   3   4    2    3      4

ATM i dont have any working solution. I'am trying to use loops(not succeding in this), but i hope there's more sufficient way.

Body:
Using loops, you can use this code. It's definitely not the most elegant solution but should work for your purpose. It only requires that you specify the columns that you'd like to use for the pairwise multiplication. It seems to be quite readable though, which is something you may want.

def element_wise_mult(first, second):

    element_wise_mult = []
    for i, el in enumerate(first):
        element_wise_mult.append(el * second[i])

    return element_wise_mult

if __name__ == '__main__':

    import pandas as pd

    df = pd.DataFrame({'A':[2,2,1,2],
                       'B':[2,2,3,3],
                       'C':[3,3,3,4],
                       'I':[1,0,0,1],
                      'II':[0,1,0,1]})

    fs = ['I', 'II']
    sc = ['A', 'B', 'C']

    series = []
    names = []

    for i in fs:
        for j in sc:
            names.append(i + '-' + j)
            series.append(pd.Series(element_wise(df[i], df[j])))  # append array creates as a pandas series

   print(pd.DataFrame(series, index=names).T)    # reconstruct dataframe from the series and names stored

Returns:

   I-A  I-B  I-C  II-A  II-B  II-C
0    2    2    3     0     0     0
1    0    0    0     2     2     3
2    0    0    0     0     0     0
3    2    3    4     2     3     4


问:
how to calculate tow numbers in textbox instantly and the result chaged when i delete numbers?
how to calculate tow numbers in textbox instantly  and the result chaged when i delete numbers from any textbox??
this is my code

```<code>        private void expenses_KeyDown(object sender, KeyEventArgs e)
    {
        if (expenses.Text != string.Empty)
        {
            decimal Pprice = Convert.ToDecimal(buyTotal.Text);
            decimal expens = Convert.ToDecimal(expenses.Text);
            decimal final = Pprice + expens;
            buyTotal.Text = final.ToString();
        }
    }
</code>```

but when i use backspace and delete number from any text box and write another number i receive wrong result , i think now it's clear i want when typing number in expenses.Text it add to buyTotal.Text and when i delete number when i typing it calculate the result

答:
Below code should be enough to calculate two numbers sum :</p>

```<code>private void expenses_KeyDown(object sender, KeyEventArgs e)
{
    try
    {
        if (expenses.Text != string.Empty)
        {
            double Pprice = Convert.ToDouble(buyTotal.Text);
            double expens = Convert.ToDouble(expenses.Text);
            double final = Pprice + expens;
            buyTotal.Text = final.ToString("0.00");
        }
        else
        {
            buyTotal.Text="0.00";
        }
    }
    catch(Exception exc)
    {
        buyTotal.Text="0.00";
    }
}
</code>```

Body:
how to calculate tow numbers in textbox instantly  and the result chaged when i delete numbers from any textbox??
this is my code

        private void expenses_KeyDown(object sender, KeyEventArgs e)
    {
        if (expenses.Text != string.Empty)
        {
            decimal Pprice = Convert.ToDecimal(buyTotal.Text);
            decimal expens = Convert.ToDecimal(expenses.Text);
            decimal final = Pprice + expens;
            buyTotal.Text = final.ToString();
        }
    }

but when i use backspace and delete number from any text box and write another number i receive wrong result , i think now it's clear i want when typing number in expenses.Text it add to buyTotal.Text and when i delete number when i typing it calculate the result

Body:
Below code should be enough to calculate two numbers sum :

private void expenses_KeyDown(object sender, KeyEventArgs e)
{
    try
    {
        if (expenses.Text != string.Empty)
        {
            double Pprice = Convert.ToDouble(buyTotal.Text);
            double expens = Convert.ToDouble(expenses.Text);
            double final = Pprice + expens;
            buyTotal.Text = final.ToString("0.00");
        }
        else
        {
            buyTotal.Text="0.00";
        }
    }
    catch(Exception exc)
    {
        buyTotal.Text="0.00";
    }
}


问:
data.table subsetting in i with column number
Is it possible to subset a data.table in i, referencing the column not by its name (e.g. by number/position)?

Example:

```<code>library(data.table)
dt <- data.table(A=1:18, Name=c('A','B','C'))
dt2 <- data.table(A=2:20, Username=c('A','B','C'))

#stuff happens and eventually I end up with either dt or dt2 copied to a final dt

#depending on which is there, I want to get only "A"s
final[Name=='A']
final[Username=='A']
</code>```

But I want a way that I can subset both data.tables with the same call despite the different column names. One potential solution is to set the key for each dt as Name and Username, then subset like this: final['A'] but I am wondering if there is another way.

I can't change the column names because they are going into a table in a shiny app.

答:
If this is based on position, then we extract the column with numeric column index using [[ and do the comparison to get the logical vector and subset the rows based on it

```<code>final[final[[2]]=="A"]
</code>```

Body:
Is it possible to subset a data.table in i, referencing the column not by its name (e.g. by number/position)?

Example:

library(data.table)
dt <- data.table(A=1:18, Name=c('A','B','C'))
dt2 <- data.table(A=2:20, Username=c('A','B','C'))

#stuff happens and eventually I end up with either dt or dt2 copied to a final dt

#depending on which is there, I want to get only "A"s
final[Name=='A']
final[Username=='A']

But I want a way that I can subset both data.tables with the same call despite the different column names. One potential solution is to set the key for each dt as Name and Username, then subset like this: final['A'] but I am wondering if there is another way.

I can't change the column names because they are going into a table in a shiny app.

Body:
If this is based on position, then we extract the column with numeric column index using [[ and do the comparison to get the logical vector and subset the rows based on it

final[final[[2]]=="A"]


问:
Printing odd numbers
I would like help to find a short and small program in C++ to print out all odd number from 1 to 100 using a loop. Is that possible?</p>

答:
Bruteforce, stupid algorithm:

```<code>for(int i = 1; i < 100; ++i) if(i%2) std::cout << i << std::endl;
</code>```

More intelligent algorithm:

```<code>for(short i = 1; i != 101; i+=2) std::cout << i << std::endl;
</code>```

OwnerDisplayName: BE Student

Title: Printing odd numbers

Body:
Bruteforce, stupid algorithm:

for(int i = 1; i < 100; ++i) if(i%2) std::cout << i << std::endl;

More intelligent algorithm:

for(short i = 1; i != 101; i+=2) std::cout << i << std::endl;


答:
Please KeyUp instead of KeyDown, because your input value write in textbox after KeyDown event.

Please check this:

```<code>private void expenses_KeyUp(object sender, KeyEventArgs e)
{
    if (expenses.Text != string.Empty)
    {
        decimal Pprice = Convert.ToDecimal(buyTotal.Text);
        decimal expens = Convert.ToDecimal(expenses.Text);
        decimal final = Pprice + expens;
        buyTotal.Text = final.ToString();
    }
    if (e.KeyCode == Keys.Back)
    {
        buyTotal.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[6].FormattedValue.ToString() != string.Empty select Convert.ToDecimal(row.Cells[6].FormattedValue)).Sum().ToString();
    }
}
</code>```

Title: how to calculate tow numbers in textbox instantly and the result chaged when i delete numbers?

Body:
Please KeyUp instead of KeyDown, because your input value write in textbox after KeyDown event.

Please check this:

private void expenses_KeyUp(object sender, KeyEventArgs e)
{
    if (expenses.Text != string.Empty)
    {
        decimal Pprice = Convert.ToDecimal(buyTotal.Text);
        decimal expens = Convert.ToDecimal(expenses.Text);
        decimal final = Pprice + expens;
        buyTotal.Text = final.ToString();
    }
    if (e.KeyCode == Keys.Back)
    {
        buyTotal.Text = (from DataGridViewRow row in dataGridView1.Rows where row.Cells[6].FormattedValue.ToString() != string.Empty select Convert.ToDecimal(row.Cells[6].FormattedValue)).Sum().ToString();
    }
}


问:
HTML / CSS - Custom made image border
First of all, I would like to point out that I'm somewhat new to CSS :)

I'm trying to make a custom image border around an image, but I just can't figure out where did it all went wrong.

Basically, I need to make this happen:

Pic of the final result

, and this is the code that I came up with:

```<code><div class="AboutMeImage">
<a href="https://s22.postimg.org/ma6wrg5r5/girl-in-winter.jpg">
<img class="test-img img-responsive" src="https://s22.postimg.org/ma6wrg5r5/girl-in-winter.jpg" alt="test photo" />
 </a>
</div>

.AboutMeImage {
clear: both;
margin-left:auto;
margin-right: auto;
height: auto;
width: 40%;
}

.test_img {
border: 10px solid transparent;
border-image: url(https://s24.postimg.org/tpxcnhk51/image_holder1.png) 602 774 0 0 stretch;
</code>```

}

```<code>.img-responsive {
display: block;
height: auto;
max-width: 100%;
}
</code>```

https://jsfiddle.net/KC87/956purro/6/

Please help!

答:
Check the below modified code..You can customize the border more according to your need.Click to view the code</p>

```<code>img {
  outline: 1px solid black;
  outline-offset: -4px;
}
</code>```

Title: HTML / CSS - Custom made image border

Body:
First of all, I would like to point out that I'm somewhat new to CSS :)

I'm trying to make a custom image border around an image, but I just can't figure out where did it all went wrong.

Basically, I need to make this happen:

Pic of the final result

, and this is the code that I came up with:

.AboutMeImage {
clear: both;
margin-left:auto;
margin-right: auto;
height: auto;
width: 40%;
}

.test_img {
border: 10px solid transparent;
border-image: url(https://s24.postimg.org/tpxcnhk51/image_holder1.png) 602 774 0 0 stretch;

}

.img-responsive {
display: block;
height: auto;
max-width: 100%;
}

https://jsfiddle.net/KC87/956purro/6/

Please help!

Body:
Check the below modified code..You can customize the border more according to your need.Click to view the code

img {
  outline: 1px solid black;
  outline-offset: -4px;
}


问:
Excel VBA Only Allow Administrator to Modify Workbook
I am having some issues with VBA to allow only Administrators to modify an excel workbook. Can anyone help me with the code to make this happen? Thanks!</p>

答:
Getting the username is fairly straightfoward:

```<code> username = Environ("UserName")
</code>```

It is also possible through API calls, which is detailed here

You can then check that username against your list of administrators. If they are in the list, you can then unprotect the workbook.

```<code> ThisWorkbook.Unprotect
</code>```

Body:
Getting the username is fairly straightfoward:

 username = Environ("UserName")

It is also possible through API calls, which is detailed here

You can then check that username against your list of administrators. If they are in the list, you can then unprotect the workbook.

 ThisWorkbook.Unprotect


问:
c# array not working initializing without MessageBox
I've encountered a strange problem with a c# program. The purpose of the program is to roll dice and display their outputs. The Logic for the program is fine and only works for reason when I output to a message box. Here's teh code:

```<code>private void btnRoll_Click(object sender, EventArgs e)
    {
        lbDice.Items.Clear();
        int[] rolls = new int[13];
        for (int i = 1; i < numTxt.Value; i++) {
            int index = new Random().Next(1, 7) + new Random().Next(1, 7);
            //MessageBox.Show(index + ""); THIS LINE IS REQUIRED
            rolls[index] += 1;
        }
        updateList(rolls);
    }

    public void updateList(int[] rolls)
    {
        for (int i = 1; i < rolls.Length; i++)
        {
            lbDice.Items.Add("" + i + "  " + rolls[i]);
        }
    }
</code>```

If it's not there, the program will only add 1 to each index.

答:
No need to create a Random instance every time. Keep it and reuse it.
If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

This code (below) may help you.

```<code>using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please provide a number and press 'Enter'");
            var input = Console.ReadLine();

            int lenght;
            if (!int.TryParse(input, out lenght))
            {
                lenght = 10;
            }
            int l = 13;
            int[] rolls = new int[l];

            var rnd = new Random();

            for (int i = 1; i < lenght; i++)
            {
                int index = rnd.Next(1, 7) + rnd.Next(1, 7);
                //MessageBox.Show(index + ""); THIS LINE IS REQUIRED
                rolls[index] += 1;
            }

            for (int i = 0; i < l; i++)
            {
                Console.WriteLine($"rolls[{i}] = {rolls[i]}");
            }

            Console.WriteLine("Done. Prss any key to exit");
            Console.ReadKey();
        }
    }
}
</code>```

Overall I think this is related to this question

Good luck!

Body:
I've encountered a strange problem with a c# program. The purpose of the program is to roll dice and display their outputs. The Logic for the program is fine and only works for reason when I output to a message box. Here's teh code:

private void btnRoll_Click(object sender, EventArgs e)
    {
        lbDice.Items.Clear();
        int[] rolls = new int[13];
        for (int i = 1; i < numTxt.Value; i++) {
            int index = new Random().Next(1, 7) + new Random().Next(1, 7);
            //MessageBox.Show(index + ""); THIS LINE IS REQUIRED
            rolls[index] += 1;
        }
        updateList(rolls);
    }

    public void updateList(int[] rolls)
    {
        for (int i = 1; i < rolls.Length; i++)
        {
            lbDice.Items.Add("" + i + "  " + rolls[i]);
        }
    }

If it's not there, the program will only add 1 to each index.

Body:
No need to create a Random instance every time. Keep it and reuse it.
If you create new instances too close in time, they will produce the same series of random numbers as the random generator is seeded from the system clock.

This code (below) may help you.

using System;

namespace ConsoleApplication2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Please provide a number and press 'Enter'");
            var input = Console.ReadLine();

            int lenght;
            if (!int.TryParse(input, out lenght))
            {
                lenght = 10;
            }
            int l = 13;
            int[] rolls = new int[l];

            var rnd = new Random();

            for (int i = 1; i < lenght; i++)
            {
                int index = rnd.Next(1, 7) + rnd.Next(1, 7);
                //MessageBox.Show(index + ""); THIS LINE IS REQUIRED
                rolls[index] += 1;
            }

            for (int i = 0; i < l; i++)
            {
                Console.WriteLine($"rolls[{i}] = {rolls[i]}");
            }

            Console.WriteLine("Done. Prss any key to exit");
            Console.ReadKey();
        }
    }
}

Overall I think this is related to this question

Good luck!


问:
Display OpenCover results in TFS 2015 build Summary
I have generated my xml coverage file as part of CI build on the TFS server using vNext 2015 build definition.  How would one display the results in the TFS 2015 summary ?  Either using the xml report or the html generated using the ReportGenerator.</p>

答:
You need to convert the results produced by OpenCover to a format which can be parsed by TFS.

One way to do this would be to use the OpenCoverToCoberturaConverter NuGet package.

Once you have that, you can use the Publish Code Coverage Results build step.

I have described the whole process on my blog.


问:
Change date text (string) to date format Javascript
I am working on a small webapp for calculating the count of days.

What i've figured out is:

```<code>function cost() {

var oneDay = 24*60*60*1000; //hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12); //Would like to input it myself
var secondDate = new Date(2008,01,22); //Would like to input it myself

var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));

var priceInDays = diffDays * 250;

alert(priceInDays);

}
</code>```

What I would like instead is to set the dates dynamically. I am using the Chrome date picker what will return the date as: 2017-03-30. I've tried something like this:

```<code>var firstDate =  document.getElementById('dateRent').value;
var secondDate = document.getElementById('dateEnd').value;
</code>```

But that didn't work out. So now, the dates are set the hard coded way. It will give me 10 * 250 = 2500 in the alert box.

I've created a jsfiddle (one problem, it doesn't handle my function, can't find the problem. https://jsfiddle.net/w93c571x/3/

答:
You're very close. Try this instead:

```<code>var firstDate =  new Date(document.getElementById('dateRent').value);
var secondDate = new Date(document.getElementById('dateEnd').value);
</code>```

Also to fix your fiddle, add an id attribute to the calculate button, and call the cost() function in an event listener, like so:

HTML

```<code><a href="#" id="calculate">Calculate!</a>
</code>```

JS

```<code>document.getElementById('calculate').addEventListener('click', cost);
</code>```

Here's a working fiddle.

Body:
I am working on a small webapp for calculating the count of days.

What i've figured out is:

function cost() {

var oneDay = 24*60*60*1000; //hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12); //Would like to input it myself
var secondDate = new Date(2008,01,22); //Would like to input it myself

var diffDays = Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay));

var priceInDays = diffDays * 250;

alert(priceInDays);

}

What I would like instead is to set the dates dynamically. I am using the Chrome date picker what will return the date as: 2017-03-30. I've tried something like this:

var firstDate =  document.getElementById('dateRent').value;
var secondDate = document.getElementById('dateEnd').value;

But that didn't work out. So now, the dates are set the hard coded way. It will give me 10 * 250 = 2500 in the alert box.

I've created a jsfiddle (one problem, it doesn't handle my function, can't find the problem. https://jsfiddle.net/w93c571x/3/

Body:
You're very close. Try this instead:

var firstDate =  new Date(document.getElementById('dateRent').value);
var secondDate = new Date(document.getElementById('dateEnd').value);

Also to fix your fiddle, add an id attribute to the calculate button, and call the cost() function in an event listener, like so:

HTML

<a href="#" id="calculate">Calculate!</a>

JS

document.getElementById('calculate').addEventListener('click', cost);

Here's a working fiddle.


问:
Change a value from 0->1 or 1->0 with only mathematic operations
I have a variable on javascrit, initialized at 0. What I'd like to do is this :

if the value is 0, change it to 1;

if the value is 1, change it to 0;

and I'll avoid conditional statement (like if/else) to check what the value is.

I think I just do it with some matematic operation; I thought to a NOT operation, but I don't know how to do that operation without

答:
Short XOR syntax:

```<code>x ^= 1
</code>```

Swaps 0 to 1 and 1 to 0.

Body:
Short XOR syntax:

x ^= 1

Swaps 0 to 1 and 1 to 0.


问:
SPARQL DBpedia filter out specific results
I am working on a small part where I receive all types of a resource. The thing is: I don't want to have all types, only the "http://dbpedia.org/ontology"-types. How do I filter them within a SPARQL query? I don't really care as long I receive only the ontologies.

In this query I need only the dbpedia-Ontologies "Country", "Location" "PopulatedPlace" and "Place".

SPARQL endpoint: http://de.dbpedia.org/sparql

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?type WHERE {
?i rdfs:label "Deutschland"@de ; a ?type .
}
```

<p>I set up a <code>FILTER</code> which filters out the Ontologies. But that's not the solution as it is static and only works for this example. It also duplicates. But that's a minor problem.</p>

<pre class="lang-sql prettyprint-override"><code>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?type WHERE {
?i rdfs:label "Deutschland"@de ; a ?type .
FILTER (?type = <http://dbpedia.org/ontology/Country> ||
?type = <http://dbpedia.org/ontology/PopulatedPlace> ||
?type = <http://dbpedia.org/ontology/Place> ||
?type = <http://dbpedia.org/ontology/Location>)
}
</code>```

Need some suggestions or help. Thx in advance.

答:
Okay i thought i shouldn't have asked, but this took me some time to realize... There is a function to filter when a string starts with the same letters...

```<code> strstarts
</code>```

Solution. Hope i could at least help someone.

```<code>PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?type WHERE {
?i rdfs:label "Deutschland"@de ; a ?type .
FILTER (strstarts(str(?type), "http://dbpedia.org/ontology/"))
}
</code>```

Body:
I am working on a small part where I receive all types of a resource. The thing is: I don't want to have all types, only the "http://dbpedia.org/ontology"-types. How do I filter them within a SPARQL query? I don't really care as long I receive only the ontologies.

In this query I need only the dbpedia-Ontologies "Country", "Location" "PopulatedPlace" and "Place".

SPARQL endpoint: http://de.dbpedia.org/sparql

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?type WHERE {
?i rdfs:label "Deutschland"@de ; a ?type .
}

I set up a FILTER which filters out the Ontologies. But that's not the solution as it is static and only works for this example. It also duplicates. But that's a minor problem.

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT ?type WHERE {
?i rdfs:label "Deutschland"@de ; a ?type .
FILTER (?type = <http://dbpedia.org/ontology/Country> ||
?type = <http://dbpedia.org/ontology/PopulatedPlace> ||
?type = <http://dbpedia.org/ontology/Place> ||
?type = <http://dbpedia.org/ontology/Location>)
}

Need some suggestions or help. Thx in advance.

Body:
Okay i thought i shouldn't have asked, but this took me some time to realize... There is a function to filter when a string starts with the same letters...

 strstarts

Solution. Hope i could at least help someone.

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
SELECT DISTINCT ?type WHERE {
?i rdfs:label "Deutschland"@de ; a ?type .
FILTER (strstarts(str(?type), "http://dbpedia.org/ontology/"))
}


答:
From my experience, this is related to how the Random class generates random numbers. Doing new Random() more than once could create the same value for each case.

trying creating the Random class instance only once:

```<code>Random rand = new Random();
for (int i = 1; i < numTxt.Value; i++) {
    int index = rand.Next(1, 7) + rand.Next(1, 7);
    rolls[index] += 1;
}
</code>```

As an experiment, you could replace the MessageBox line with a Sleep and see if that also works

Title: c# array not working initializing without MessageBox

Body:
From my experience, this is related to how the Random class generates random numbers. Doing new Random() more than once could create the same value for each case.

trying creating the Random class instance only once:

Random rand = new Random();
for (int i = 1; i < numTxt.Value; i++) {
    int index = rand.Next(1, 7) + rand.Next(1, 7);
    rolls[index] += 1;
}

As an experiment, you could replace the MessageBox line with a Sleep and see if that also works


问:
How to let my web-user-control determine automatically the url of the page where it's placed
```<code>        <asp:HyperLink
        ID="hyper1"
        runat="server"
        NavigateUrl='<%#string.Format("~/PLayer.aspx?ID={0}&Type={1}",Eval("arrange_by_id"),Eval("value"))%>'><%# Eval("value")%></asp:HyperLink>
</code>```

I've implemented this string format in my NavigateUrl to pass a dynamic querystring depending on the clicked item!

but you see the first part in the string format where it says "~/PLayer.aspx" i want the user control to automatically change this part according to where it's placed!

答:
You don't need to move the user control from place to place. You can only get the name of the current page from either Request.Url, Request.RawUrl or Request.ServerVariables["SCRIPT_NAME"].

You can dynamically register user control to change the path when you want it like that. For a reference on dynamically registering user control see this

Body:
        <asp:HyperLink
        ID="hyper1"
        runat="server"
        NavigateUrl='<%#string.Format("~/PLayer.aspx?ID={0}&Type={1}",Eval("arrange_by_id"),Eval("value"))%>'><%# Eval("value")%></asp:HyperLink>

I've implemented this string format in my NavigateUrl to pass a dynamic querystring depending on the clicked item!

but you see the first part in the string format where it says "~/PLayer.aspx" i want the user control to automatically change this part according to where it's placed!