问:
Lambda expression question
```<code>string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/
</code>```

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

答:
That's just how that particular overload of Select works: "the second parameter of the function represents the index of the source element".

If you want the entire string then you can do something like this:

```<code>var query = fruits.Select((fruit, index) => new { index, str = fruit });
</code>```

Title: Lambda expression question

Body:
string[] fruits = { "apple", "banana", "mango", "orange",
                      "passionfruit", "grape" };

var query =
    fruits.Select((fruit, index) =>
                      new { index, str = fruit.Substring(0, index) });

foreach (var obj in query)
{
    Console.WriteLine("{0}", obj);
}

/*
 This code produces the following output:

 {index=0, str=}
 {index=1, str=b}
 {index=2, str=ma}
 {index=3, str=ora}
 {index=4, str=pass}
 {index=5, str=grape}
*/

Could somebody explain, how "index" is associated here as array index of the elements?

Say, I need a query that instead of first letter returns me the whole object (string in this case) + associated index.

Body:
That's just how that particular overload of Select works: "the second parameter of the function represents the index of the source element".

If you want the entire string then you can do something like this:

var query = fruits.Select((fruit, index) => new { index, str = fruit });


来源: stackexchange

问:
JQuery hide/show from textbox
I'm trying to get a password field to be shown/hidden depending on value that of a different input element.

For example if the username is "admin" it should hide the password field.

If you they type in anything else then the password field appears or remains.

function togglePassword() {
  if ($("#j_username").val() == "admin")
    $("#j_password").hide();
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><label>User Name</label>
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1' onkeypress='javascript:return loginIdKeyPress(event);' />

<label>Password</label>
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2' onkeypress='javascript:return passwordKeyPress(event);' />
<br/></code>```

Currently this code doesn't work for me, what should I change?

答:
Try following code where ensure the case sensitivity :)</p>

```<code>$(document).ready(function(){
  $('#j_username').on('input',function(){
    if($(this).val().toLowerCase().trim() === 'admin'){
      $("#j_password").hide();
    }
    else {
      $("#j_password").show();
    }
  });
});
</code>```

ContentLicense: CC BY-SA 3.0

Title: JQuery hide/show from textbox

Body:
I'm trying to get a password field to be shown/hidden depending on value that of a different input element.

For example if the username is "admin" it should hide the password field.

If you they type in anything else then the password field appears or remains.

function togglePassword() {
  if ($("#j_username").val() == "admin")
    $("#j_password").hide();
}

User Name
<input type='text' id="j_username" name='j_username' style='text-align: Left;' MaxLength='100' size='20' tabindex='1' onkeypress='javascript:return loginIdKeyPress(event);' />

Password
<input type='password' id="j_password" name='j_password' value='' Align='Left' size='20' tabindex='2' onkeypress='javascript:return passwordKeyPress(event);' />

Currently this code doesn't work for me, what should I change?

Body:
Try following code where ensure the case sensitivity :)

$(document).ready(function(){
  $('#j_username').on('input',function(){
    if($(this).val().toLowerCase().trim() === 'admin'){
      $("#j_password").hide();
    }
    else {
      $("#j_password").show();
    }
  });
});


问:
Multiple nested loops equivalent replacement in python
I have a simple dictionary of the form D = {2: 4, 3: 2, 5: 1, 7: 1}. There are 4 keys which are the primes and  4 values which represent the maximum power. Based on that I want to generate all combinations of the form :

p1^range1 * p2^range2 * p3^range3 * p4^range4

where range1 to range4 are the ranges corresponding to the values of the dictionary of each prime. For p1 = 2 the range will be range(0, 4+1)

The most simplistic way would be a nested for loop with four levels :

```<code>for i1 in range(0, 4+1):
   for i2 in range(0, 2+1):
      for i3 in range(0, 1+1):
         for i4 in range(0, 1+1):
            n = 2**i1 * 3**i2 * 5**i3 * 7**i4
</code>```

which is what I intend and it is correct but this is a non-elegant and mechanical way.

Another way is to use the  itertools.product which works if all the ranges are the same. Basically it is as follows  :

```<code>for x in itertools.product(range(0, 4+1), repeat=4):
    print(x, end='   ')
</code>```

However this will generate all the possible combinations including (2, 2, 3, 4),
(4, 4, 2, 3) or (2, 3, 4, 4) which are not valid in my case as the power of 5 (which is the third element in the tuple) will never be 3 and the power of 7 will never be 4. I want to limit somehow if possible the range of elements . So in this case the maximum tuple will be (4, 2, 1, 1) corresponding to the powers (values in dictionary D). So basically I need ONLY the range of tuples from (0,0,0,0) to (4,2,1,1).

Is there a way to achieve this without using for loops and do it in a similar approach as with itertools.product?

Many thanks in advance.

答:
Actually,

As miradulo wrote the solution is very simple :
either use :

```<code>for x in itertools.product(*map(range, (5, 3, 2, 2))) :
    print(x, end='   ')
</code>```

or :

```<code>for x in itertools.product(range(5), range(3), range(2), range(2)) :
    print(x, end='   ')
</code>```

Both ways solve the problem.

Body:
I have a simple dictionary of the form D = {2: 4, 3: 2, 5: 1, 7: 1}. There are 4 keys which are the primes and  4 values which represent the maximum power. Based on that I want to generate all combinations of the form :

p1^range1 * p2^range2 * p3^range3 * p4^range4

where range1 to range4 are the ranges corresponding to the values of the dictionary of each prime. For p1 = 2 the range will be range(0, 4+1)

The most simplistic way would be a nested for loop with four levels :

for i1 in range(0, 4+1):
   for i2 in range(0, 2+1):
      for i3 in range(0, 1+1):
         for i4 in range(0, 1+1):
            n = 2**i1 * 3**i2 * 5**i3 * 7**i4

which is what I intend and it is correct but this is a non-elegant and mechanical way.

Another way is to use the  itertools.product which works if all the ranges are the same. Basically it is as follows  :

for x in itertools.product(range(0, 4+1), repeat=4):
    print(x, end='   ')

However this will generate all the possible combinations including (2, 2, 3, 4),
(4, 4, 2, 3) or (2, 3, 4, 4) which are not valid in my case as the power of 5 (which is the third element in the tuple) will never be 3 and the power of 7 will never be 4. I want to limit somehow if possible the range of elements . So in this case the maximum tuple will be (4, 2, 1, 1) corresponding to the powers (values in dictionary D). So basically I need ONLY the range of tuples from (0,0,0,0) to (4,2,1,1).

Is there a way to achieve this without using for loops and do it in a similar approach as with itertools.product?

Many thanks in advance.

Body:
Actually,

As miradulo wrote the solution is very simple :
either use :

for x in itertools.product(*map(range, (5, 3, 2, 2))) :
    print(x, end='   ')

or :

for x in itertools.product(range(5), range(3), range(2), range(2)) :
    print(x, end='   ')

Both ways solve the problem.


问:
Display data from array to multiple elements in HTML Angular 4
I'm trying to show a list of informations from an XML to a list using Angular 4 and Angular Material.
I have already converted the XML to JSON and the JSON I retrieve is like this:

```<code>{
    "json": {

        "0": [{
                "Name": "John",
                "Address": "5th street",
                "Phone": "555-123-456"
            }

        ],
        "1": [{
                "Name": "Mary",
                "Address": "4th street",
                "Phone": "555-654-321"
            }

        ],
        "2": [{
                "Name": "Harry",
                "Address": "3th street",
                "Phone": "555-124-231"
            }

        ]

    }
}
</code>```

this is my ts file: [i] is the id and id has dozens of entries.

```<code>for (let i = 0; i< json.length; i++){
              this.name = json[i]['Name'];
              this.address = json[i]['Address'];
              this.phone = json[i]['Phone'];
 }
</code>```

this is my html file:

```<code><mat-list>
  <h3 mat-subheader>Your info</h3>
  <mat-list-item>
    <h2 mat-line>Your name is: <b>{{name}}</b></h2>
    <p mat-line> Your address is: <b> {{address}} </b></p>
    <p mat-line> Your phone is: <b> {{phone}} </b></p>
  </mat-list-item>
  <mat-divider></mat-divider>
</mat-list>
</code>```

The thing is, the list has dozens of rows but it is showing the first only.
My intention was to have all the items loaded on page.
Already tried using *ngFor but it didn't work.

I know I might have missed something stupid but I've tried a lot and searched a lot but couldn't find a solution.

Thanks in advance

答:
```<code> <mat-list-item *ngFor="let posicao of jsonPosicao ">
    <mat-icon mat-list-icon>directions_car</mat-icon>
    <h2 mat-line>Your name is: <b>{{posicao.name}}</b></h2>
    <p mat-line> Your address is: <b> {{posicao.address}} </b></p>
    <p mat-line> Your phone is: <b> {{posicao.phone}} </b></p>
 </mat-list-item>
</code>```

I'm confused by your quest and your desired results but from what you are trying to do in the javascript seems like you could use the ngFor like this.

```<code>{
   "json": [
            {
                    "Id":"1",
                    "Name": "John",
                    "Address": "5th street",
                    "Phone": "555-123-456"
                }
            ,
            {
                    "Id":"2",
                    "Name": "Mary",
                    "Address": "4th street",
                    "Phone": "555-654-321"
                }
            ,
            {
                    "Id":"3",
                    "Name": "Harry",
                    "Address": "3th street",
                    "Phone": "555-124-231"
                }
        ]
    }
</code>```

If you want to keep the data structure of the JSON, change html to this

```<code><mat-list-item *ngFor="let posicao of jsonPosicao ">
    <mat-icon mat-list-icon>directions_car</mat-icon>
    <h2 mat-line>Your name is: <b>{{posicao[0].name}}</b></h2>
    <p mat-line> Your address is: <b> {{posicao[0].address}} </b></p>
    <p mat-line> Your phone is: <b> {{posicao[0].phone}} </b></p>
</mat-list-item>
</code>```

Body:
I'm trying to show a list of informations from an XML to a list using Angular 4 and Angular Material.
I have already converted the XML to JSON and the JSON I retrieve is like this:

{
    "json": {

        "0": [{
                "Name": "John",
                "Address": "5th street",
                "Phone": "555-123-456"
            }

        ],
        "1": [{
                "Name": "Mary",
                "Address": "4th street",
                "Phone": "555-654-321"
            }

        ],
        "2": [{
                "Name": "Harry",
                "Address": "3th street",
                "Phone": "555-124-231"
            }

        ]

    }
}

this is my ts file: [i] is the id and id has dozens of entries.

for (let i = 0; i< json.length; i++){
              this.name = json[i]['Name'];
              this.address = json[i]['Address'];
              this.phone = json[i]['Phone'];
 }

this is my html file:

<mat-list>

Your info

  <mat-list-item>

Your name is: {{name}}

 Your address is:  {{address}}

 Your phone is:  {{phone}}

  </mat-list-item>
  <mat-divider></mat-divider>
</mat-list>

The thing is, the list has dozens of rows but it is showing the first only.
My intention was to have all the items loaded on page.
Already tried using *ngFor but it didn't work.

I know I might have missed something stupid but I've tried a lot and searched a lot but couldn't find a solution.

Thanks in advance

Body:
 <mat-list-item *ngFor="let posicao of jsonPosicao ">
    <mat-icon mat-list-icon>directions_car</mat-icon>
    <h2 mat-line>Your name is: <b>{{posicao.name}}</b></h2>
    <p mat-line> Your address is: <b> {{posicao.address}} </b></p>
    <p mat-line> Your phone is: <b> {{posicao.phone}} </b></p>
 </mat-list-item>

I'm confused by your quest and your desired results but from what you are trying to do in the javascript seems like you could use the ngFor like this.

{
   "json": [
            {
                    "Id":"1",
                    "Name": "John",
                    "Address": "5th street",
                    "Phone": "555-123-456"
                }
            ,
            {
                    "Id":"2",
                    "Name": "Mary",
                    "Address": "4th street",
                    "Phone": "555-654-321"
                }
            ,
            {
                    "Id":"3",
                    "Name": "Harry",
                    "Address": "3th street",
                    "Phone": "555-124-231"
                }
        ]
    }

If you want to keep the data structure of the JSON, change html to this

<mat-list-item *ngFor="let posicao of jsonPosicao ">
    <mat-icon mat-list-icon>directions_car</mat-icon>
    <h2 mat-line>Your name is: <b>{{posicao[0].name}}</b></h2>
    <p mat-line> Your address is: <b> {{posicao[0].address}} </b></p>
    <p mat-line> Your phone is: <b> {{posicao[0].phone}} </b></p>
</mat-list-item>


问:
Razor template to javascript string
Ok, I got this one working, but I'm not sure about how much of a terrible hack this is. Can anyone tell me if what I did is ok or not, and why?

I needed to share a template between my Razor and JavaScript, so one could use it server-side and the other client-side. So, here is what I did:

```<code>Func<dynamic, HelperResult> sampleTemplate =
    @<span>Sample markup @item.Something</span>;
</code>```

Then, I used my template in my View like this:

```<code>for(int idxSample = 0; idxSample < Model.Number; idxSample++) {
    @sampleTemplate(new { Something = "" })
}
</code>```

And for the javascript I did this:

```<code><script type="text/javascript">
    var someJsTemplate = "" +
        <r><[!CDATA[@sampleTemplate(new { Something = "" })]]></r>;
</script>
</code>```

So I could later append someJsTemplate whenever I needed it. So, what is the verdict? Does anyone see a better way to do it? Or is this alright?

Edit:

Now I can't use this. Although it works fine in FireFox, Chrome does not allow my hack. Any help?

答:
Storing HTML in server side code looks like a bad idea to me. Personally I would write a controller:

```<code>public class TemplatesController: Controller
{
    [ChildActionOnly]
    public ActionResult Index(Item item)
    {
        return View("~/Views/Shared/EditorTemplates/Item.cshtml", item);
    }
}
</code>```

and a partial (~/Views/Shared/EditorTemplates/Item.cshtml) containing the markup:

```<code>@model AppName.Models.Item
@{
    Layout = null;
}
<span>Sample markup @Model.Something</span>
</code>```

Then if I need to use it in a strongly typed view I would simply use an editor template:

```<code>@Html.EditorFor(x => x.Items)
</code>```

and in javascript:

```<code><script type="text/javascript">
    var someJsTemplate = '@HttpUtility.JavaScriptStringEncode(Html.Action("index", "templates", new { something = "abc" }).ToHtmlString())';
</script>
</code>```

And to simplify a little bit this javascript call you could write a helper:

```<code>public static class HtmlExtensions
{
    public static MvcHtmlString Template(this HtmlHelper htmlHelper, object item)
    {
        return MvcHtmlString.Create(
            HttpUtility.JavaScriptStringEncode(
                htmlHelper.Action("index", "templates", item).ToHtmlString()
            )
        );
    }
}
</code>```

and then:

```<code><script type="text/javascript">
    var someJsTemplate = '@Html.Template(new { something = "abc" })';
</script>
</code>```

ContentLicense: CC BY-SA 2.5

Title: Razor template to javascript string

Body:
Ok, I got this one working, but I'm not sure about how much of a terrible hack this is. Can anyone tell me if what I did is ok or not, and why?

I needed to share a template between my Razor and JavaScript, so one could use it server-side and the other client-side. So, here is what I did:

Func<dynamic, HelperResult> sampleTemplate =
    @Sample markup @item.Something;

Then, I used my template in my View like this:

for(int idxSample = 0; idxSample < Model.Number; idxSample++) {
    @sampleTemplate(new { Something = "" })
}

And for the javascript I did this:

So I could later append someJsTemplate whenever I needed it. So, what is the verdict? Does anyone see a better way to do it? Or is this alright?

Edit:

Now I can't use this. Although it works fine in FireFox, Chrome does not allow my hack. Any help?

Body:
Storing HTML in server side code looks like a bad idea to me. Personally I would write a controller:

public class TemplatesController: Controller
{
    [ChildActionOnly]
    public ActionResult Index(Item item)
    {
        return View("~/Views/Shared/EditorTemplates/Item.cshtml", item);
    }
}

and a partial (~/Views/Shared/EditorTemplates/Item.cshtml) containing the markup:

@model AppName.Models.Item
@{
    Layout = null;
}
<span>Sample markup @Model.Something</span>

Then if I need to use it in a strongly typed view I would simply use an editor template:

@Html.EditorFor(x => x.Items)

and in javascript:

<script type="text/javascript">
    var someJsTemplate = '@HttpUtility.JavaScriptStringEncode(Html.Action("index", "templates", new { something = "abc" }).ToHtmlString())';
</script>

And to simplify a little bit this javascript call you could write a helper:

public static class HtmlExtensions
{
    public static MvcHtmlString Template(this HtmlHelper htmlHelper, object item)
    {
        return MvcHtmlString.Create(
            HttpUtility.JavaScriptStringEncode(
                htmlHelper.Action("index", "templates", item).ToHtmlString()
            )
        );
    }
}

and then:

<script type="text/javascript">
    var someJsTemplate = '@Html.Template(new { something = "abc" })';
</script>


问:
Counting rows with NaN
I have the following DataFrame:

```<code>dur  wage1  wage2  wage3  cola  hours     pension  stby_pay  shift_diff
6   3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
8   1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
9   1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
13  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
17  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
31  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
43  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
44  1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
47  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
</code>```

What I have to do is count the rows that are exactly the same, including the NaN values.

The problem is the following, I use groupby, but it is a function that ignores the NaN values, that is, it does not have them in mind when doing the counting, that is the reason why I am not returning a correct output counting the number of exact repetitions between those rows.

My code is the following one:

```<code>def detect_duplicates(data):
    x = DataFrame(columns=data.columns.tolist() + ["num_reps"])

    aux = data[data.duplicated(keep=False)]
    x = data[data.duplicated(keep=False)].drop_duplicates()
    #This line should count my repeated rows
    s = aux.groupby(data.columns.tolist(),as_index=False).transform('size')

    return x
</code>```

If I print "x" var, I get this result, it shows all the repeated rows:

```<code>dur  wage1  wage2  wage3  cola  hours     pension  stby_pay  shift_diff
6   3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
8   1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
9   1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
13  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
17  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
31  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
43  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
44  1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
47  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
51  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
53  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
</code>```

Now I have to count those rows from my x result that are exactly the same.

This should be my correct output:

```<code> dur    wage1   wage2   wage3   cola    hours   pension stby_pay    shift_diff  num_reps
6   3.0 2.0 3.0 NaN tcf NaN empl_contr  NaN NaN                4
8   1.0 2.8 NaN NaN none    38.0    empl_contr  2.0 3.0        2
9   1.0 5.7 NaN NaN none    40.0    empl_contr  NaN 4.0        3
43  2.0 2.5 3.0 NaN NaN 40.0    none    NaN NaN                2
</code>```

Here is my problem and it's that groupby ignores NaN values, and that's why other similar posts about this problem can't help me.

Thanks

答:
If your dataframe's name is df, you can count the number of duplicates using just one line of code:

```<code>sum(df.duplicated(keep = False))
</code>```

If you want to drop duplicate rows, use the drop_duplicates method. documentation

Example:

```<code>#data.csv
col1,col2,col3
a,3,NaN #duplicate
b,9,4   #duplicate
c,12,5
a,3,NaN #duplicate
b,9,4   #duplicate
d,19,20
a,3,NaN #duplicate - 5 duplicate rows
</code>```

Importing data.csv and dropping duplicate rows (by default the first instance of a duplicated row is kept)

```<code>import pandas as pd
df = pd.read_csv("data.csv")
print(df.drop_duplicates())
#Output
   c1   c2   c3
0   a   3   NaN
1   b   9   4.0
2   c   12  5.0
5   d   19  20.0
</code>```

To count the number of duplicates rows, use the dataframe's duplicated method. Set "keep" to False (documentation). As mentioned above, you can simply do this using sum(df.duplicated(keep = False)). Here's a messier way to do it that demonstrates what the "duplicated" method does:

```<code>duplicate_rows = df.duplicated(keep = False)
print(duplicate_rows)

#count the number of duplicates (i.e. count the number of 'True' values in
#the duplicate_rows boolean series.

number_of_duplicates = sum(duplicate_rows)

print("Number of duplicate rows:")

print(number_of_duplicates)

#Output

#The duplicate_rows pandas series from df.duplicated(keep = False)
0     True
1     True
2    False
3     True
4     True
5    False
6     True
dtype: bool

#The number of rows from sum(df.duplicated(keep = False))
Number of duplicate rows:
5
</code>```

Title: Counting rows with NaN

Body:
I have the following DataFrame:

dur  wage1  wage2  wage3  cola  hours     pension  stby_pay  shift_diff
6   3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
8   1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
9   1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
13  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
17  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
31  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
43  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
44  1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
47  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN

What I have to do is count the rows that are exactly the same, including the NaN values.

The problem is the following, I use groupby, but it is a function that ignores the NaN values, that is, it does not have them in mind when doing the counting, that is the reason why I am not returning a correct output counting the number of exact repetitions between those rows.

My code is the following one:

def detect_duplicates(data):
    x = DataFrame(columns=data.columns.tolist() + ["num_reps"])

    aux = data[data.duplicated(keep=False)]
    x = data[data.duplicated(keep=False)].drop_duplicates()
    #This line should count my repeated rows
    s = aux.groupby(data.columns.tolist(),as_index=False).transform('size')

    return x

If I print "x" var, I get this result, it shows all the repeated rows:

dur  wage1  wage2  wage3  cola  hours     pension  stby_pay  shift_diff
6   3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
8   1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
9   1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
13  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
17  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
31  1.0    5.7    NaN    NaN  none   40.0  empl_contr       NaN         4.0
43  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN
44  1.0    2.8    NaN    NaN  none   38.0  empl_contr       2.0         3.0
47  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
51  3.0    2.0    3.0    NaN   tcf    NaN  empl_contr       NaN         NaN
53  2.0    2.5    3.0    NaN   NaN   40.0        none       NaN         NaN

Now I have to count those rows from my x result that are exactly the same.

This should be my correct output:

 dur    wage1   wage2   wage3   cola    hours   pension stby_pay    shift_diff  num_reps
6   3.0 2.0 3.0 NaN tcf NaN empl_contr  NaN NaN                4
8   1.0 2.8 NaN NaN none    38.0    empl_contr  2.0 3.0        2
9   1.0 5.7 NaN NaN none    40.0    empl_contr  NaN 4.0        3
43  2.0 2.5 3.0 NaN NaN 40.0    none    NaN NaN                2

Here is my problem and it's that groupby ignores NaN values, and that's why other similar posts about this problem can't help me.

Thanks

Body:
If your dataframe's name is df, you can count the number of duplicates using just one line of code:

sum(df.duplicated(keep = False))

If you want to drop duplicate rows, use the drop_duplicates method. documentation

Example:

#data.csv
col1,col2,col3
a,3,NaN #duplicate
b,9,4   #duplicate
c,12,5
a,3,NaN #duplicate
b,9,4   #duplicate
d,19,20
a,3,NaN #duplicate - 5 duplicate rows

Importing data.csv and dropping duplicate rows (by default the first instance of a duplicated row is kept)

import pandas as pd
df = pd.read_csv("data.csv")
print(df.drop_duplicates())
#Output
   c1   c2   c3
0   a   3   NaN
1   b   9   4.0
2   c   12  5.0
5   d   19  20.0

To count the number of duplicates rows, use the dataframe's duplicated method. Set "keep" to False (documentation). As mentioned above, you can simply do this using sum(df.duplicated(keep = False)). Here's a messier way to do it that demonstrates what the "duplicated" method does:

duplicate_rows = df.duplicated(keep = False)
print(duplicate_rows)

#count the number of duplicates (i.e. count the number of 'True' values in
#the duplicate_rows boolean series.

number_of_duplicates = sum(duplicate_rows)

print("Number of duplicate rows:")

print(number_of_duplicates)

#Output

#The duplicate_rows pandas series from df.duplicated(keep = False)
0     True
1     True
2    False
3     True
4     True
5    False
6     True
dtype: bool

#The number of rows from sum(df.duplicated(keep = False))
Number of duplicate rows:
5


问:
Fatal Error :1:1: Content is not allowed in prolog. org.xml.sax.SAXParseException
I am trying to read an XML file in Java and then compare it against its XML Schema but I can't get past this error :

[Fatal Error] :1:1: Content is not allowed in prolog.
      org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

This is the start of the file reading

```<code>try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml"))); // ERROR OCCURS HERE
</code>```

I scanned my XML through HEX Editors but I did not find any weird characters inside, so I dont know where the problem is

myfile.xml

```<code><?xml version="1.0" encoding="UTF-8" standalone="no"?>

<Schedule xmlns ="schedule"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="schedule.xsd">
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture Classroom="BA">
            <Day>Wednesday</Day>
            <Time>09-11</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Constraint Satisfaction Problems</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Knowledge Representation in Web</Title>
        <Lecture Classroom="P200">
            <Day>Friday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture>
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>AI Programming</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>11-13</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Introduction to Procedural Programming</Title>
        <Lecture Classroom="P200">
            <Day>Wednesday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Papadopoulos</Professor>
    </Lesson>
</Schedule>
</code>```

答: You probably have an UTF-8 file with a byte-order marker (BOM). It’ll be invisible to most editors, but might mess with the parser. Try converting to UTF-8 without BOM.</p>

Body:
I am trying to read an XML file in Java and then compare it against its XML Schema but I can't get past this error :

[Fatal Error] :1:1: Content is not allowed in prolog.
      org.xml.sax.SAXParseException; lineNumber: 1; columnNumber: 1; Content is not allowed in prolog.

This is the start of the file reading

try {
        DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
        DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
        Document doc = dBuilder.parse(new InputSource(new StringReader("myfile.xml"))); // ERROR OCCURS HERE

I scanned my XML through HEX Editors but I did not find any weird characters inside, so I dont know where the problem is

myfile.xml

<?xml version="1.0" encoding="UTF-8" standalone="no"?>

<Schedule xmlns ="schedule"
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
          xsi:noNamespaceSchemaLocation="schedule.xsd">
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture Classroom="BA">
            <Day>Wednesday</Day>
            <Time>09-11</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Constraint Satisfaction Problems</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Knowledge Representation in Web</Title>
        <Lecture Classroom="P200">
            <Day>Friday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Hatzilygeroudis</Professor>
    </Lesson>
    <Lesson>
        <Title>Artificial Intelligence</Title>
        <Lecture>
            <Day>Monday</Day>
            <Time>19-21</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>AI Programming</Title>
        <Lecture Classroom="B3">
            <Day>Monday</Day>
            <Time>11-13</Time>
        </Lecture>
    </Lesson>
    <Lesson>
        <Title>Introduction to Procedural Programming</Title>
        <Lecture Classroom="P200">
            <Day>Wednesday</Day>
            <Time>15-17</Time>
        </Lecture>
        <Professor>Papadopoulos</Professor>
    </Lesson>
</Schedule>


问:
Maintain data in R package with scheduled sql pulls
I have a personal, non-CRAN, R package. Its purpose is reduce the amount of repeated wrangling I need to do. The data must be pulled from sql server. This pull from SQL is done weekly. Where should I put my sql file and where should I put the R code that does a scheduled weekly sql pull?</p>

答: You will need to make a chron task which will load the package, pull the data (see here) and recompile the package.</p>


问:
__FILE__ macro shows full path
The standard predefined macro __FILE__ available in C shows the full path to the file. Is there any way to short the path? I mean instead of

```<code>/full/path/to/file.c
</code>```

I see

```<code>to/file.c
</code>```

or

```<code>file.c
</code>```

答:
Here's a solution that works for environments that don't have the string library (Linux kernel, embedded systems, etc):

```<code>#define FILENAME ({ \
    const char* filename_start = __FILE__; \
    const char* filename = filename_start; \
    while(*filename != '\0') \
        filename++; \
    while((filename != filename_start) && (*(filename - 1) != '/')) \
        filename--; \
    filename; })
</code>```

Now just use FILENAME instead of __FILENAME__. Yes, it's still a runtime thing but it works.

ContentLicense: CC BY-SA 4.0

Title: __FILE__ macro shows full path

Body:
The standard predefined macro __FILE__ available in C shows the full path to the file. Is there any way to short the path? I mean instead of

/full/path/to/file.c

I see

to/file.c

or

file.c

Body:
Here's a solution that works for environments that don't have the string library (Linux kernel, embedded systems, etc):

#define FILENAME ({ \
    const char* filename_start = __FILE__; \
    const char* filename = filename_start; \
    while(*filename != '\0') \
        filename++; \
    while((filename != filename_start) && (*(filename - 1) != '/')) \
        filename--; \
    filename; })

Now just use FILENAME instead of __FILENAME__. Yes, it's still a runtime thing but it works.


问:
How to construct a query that shows all procedures inside a procedure? SQL server
I need to be able to write a query that tells me all the procedures that are executed within a procedure, even if there are procedures being executed in multiple levels.

e.g.

I have procedure 1.

Procedure 1 runs procedure 2 and 3.

Procedure 2 runs procedure 4.

Is there a way I can get a query for this? I tried to look for it online but I can't really find what I'm looking for.

In Management Studio, if you right click an object and click on View Dependencies, there's 2 options, "Objects that depend on " and "Objects on which  depends"

I need a query for the second one.

EDIT:

I got a query going and this is working mostly. I just need to filter the data out by procedures ONLY. What table should I join on so that I can view only procedures?

```<code>select  object_name(referencing_id) as referencing_entity_name,
        o.type_desc as referencing_desciption,
        coalesce(col_name(referencing_id, referencing_minor_id), '(n/a)') as referencing_minor_id,
        referencing_class_desc,
        referenced_class_desc,
        referenced_server_name,
        referenced_database_name,
        referenced_schema_name,
        referenced_entity_name,
        coalesce(col_name(referenced_id, referenced_minor_id), '(n/a)') as referenced_column_name,
        is_caller_dependent,
        is_ambiguous
from    sys.sql_expression_dependencies as sed
inner join sys.objects as o
on      sed.referencing_id = o.object_id
where   referencing_id = object_id(N'dbo.npc_sp_par_calc_MinMax')
</code>```

答:
You need a recursive CTE.

Something like the below (demo)

```<code>WITH R
     AS (SELECT referenced_id                                          AS referencing_id,
                referenced_id                                          AS referenced_id,
                CAST(CONCAT('/', referenced_id, '/') AS VARCHAR(8000)) AS referenced_id_path,
                OBJECT_SCHEMA_NAME(referenced_id)                      AS referenced_schema_name,
                OBJECT_NAME(referenced_id)                             AS referenced_entity_name
         FROM   (VALUES (OBJECT_ID('P1'))) V(referenced_id) /*Anchor element*/
         UNION ALL
         SELECT sed.referencing_id,
                CA.referenced_id,
                CAST(CONCAT(R.referenced_id_path, CA.referenced_id, '/')AS VARCHAR(8000)),
                sed.referenced_schema_name,
                sed.referenced_entity_name
         FROM   sys.sql_expression_dependencies AS sed
                INNER JOIN sys.objects AS o
                  ON sed.referencing_id = o.object_id
                INNER JOIN R
                  ON sed.referencing_id = OBJECT_ID(CONCAT(R.referenced_schema_name + '.', R.referenced_entity_name))
                CROSS APPLY (SELECT OBJECT_ID(CONCAT(sed.referenced_schema_name + '.', sed.referenced_entity_name))) CA(referenced_id)
         WHERE  o.type_desc = 'SQL_STORED_PROCEDURE'
                AND R.referenced_id_path NOT LIKE CONCAT('%/', CA.referenced_id, '/%'))
SELECT OBJECT_SCHEMA_NAME(referenced_id),
       OBJECT_NAME(referenced_id),
       referenced_id,
       referenced_id_path
FROM   R
</code>```

Body:
I need to be able to write a query that tells me all the procedures that are executed within a procedure, even if there are procedures being executed in multiple levels.

e.g.

I have procedure 1.

Procedure 1 runs procedure 2 and 3.

Procedure 2 runs procedure 4.

Is there a way I can get a query for this? I tried to look for it online but I can't really find what I'm looking for.

In Management Studio, if you right click an object and click on View Dependencies, there's 2 options, "Objects that depend on " and "Objects on which  depends"

I need a query for the second one.

EDIT:

I got a query going and this is working mostly. I just need to filter the data out by procedures ONLY. What table should I join on so that I can view only procedures?

select  object_name(referencing_id) as referencing_entity_name,
        o.type_desc as referencing_desciption,
        coalesce(col_name(referencing_id, referencing_minor_id), '(n/a)') as referencing_minor_id,
        referencing_class_desc,
        referenced_class_desc,
        referenced_server_name,
        referenced_database_name,
        referenced_schema_name,
        referenced_entity_name,
        coalesce(col_name(referenced_id, referenced_minor_id), '(n/a)') as referenced_column_name,
        is_caller_dependent,
        is_ambiguous
from    sys.sql_expression_dependencies as sed
inner join sys.objects as o
on      sed.referencing_id = o.object_id
where   referencing_id = object_id(N'dbo.npc_sp_par_calc_MinMax')

Body:
You need a recursive CTE.

Something like the below (demo)

WITH R
     AS (SELECT referenced_id                                          AS referencing_id,
                referenced_id                                          AS referenced_id,
                CAST(CONCAT('/', referenced_id, '/') AS VARCHAR(8000)) AS referenced_id_path,
                OBJECT_SCHEMA_NAME(referenced_id)                      AS referenced_schema_name,
                OBJECT_NAME(referenced_id)                             AS referenced_entity_name
         FROM   (VALUES (OBJECT_ID('P1'))) V(referenced_id) /*Anchor element*/
         UNION ALL
         SELECT sed.referencing_id,
                CA.referenced_id,
                CAST(CONCAT(R.referenced_id_path, CA.referenced_id, '/')AS VARCHAR(8000)),
                sed.referenced_schema_name,
                sed.referenced_entity_name
         FROM   sys.sql_expression_dependencies AS sed
                INNER JOIN sys.objects AS o
                  ON sed.referencing_id = o.object_id
                INNER JOIN R
                  ON sed.referencing_id = OBJECT_ID(CONCAT(R.referenced_schema_name + '.', R.referenced_entity_name))
                CROSS APPLY (SELECT OBJECT_ID(CONCAT(sed.referenced_schema_name + '.', sed.referenced_entity_name))) CA(referenced_id)
         WHERE  o.type_desc = 'SQL_STORED_PROCEDURE'
                AND R.referenced_id_path NOT LIKE CONCAT('%/', CA.referenced_id, '/%'))
SELECT OBJECT_SCHEMA_NAME(referenced_id),
       OBJECT_NAME(referenced_id),
       referenced_id,
       referenced_id_path
FROM   R


问:
Prevent Json.NET from interpreting a string as a date
I have some attributes returned from a rest service that are served as an array of name-value pairs.

In some cases the value is a date expressed in universal sortable format:
{
  "name": "Modification-Date",
  "value": "2017-11-13T15:15:13.968Z"
}

When it gets parsed by the deserialiser, the value is identified as a date but given that the object the pair is deserialised into has type string for both name and value, the date is then converted to string and it loses precision: "13/11/2017 15:15:13"

This is easily visible by using a converter for the NameValue type.

```<code>if (reader.TokenType == JsonToken.StartObject)
{
    var item = JObject.Load(reader);

    return new NameValueFacet()
    {
        Name = item["name"].Value<string>(),
        Value = item["value"].Value<string>()
    };
}
</code>```

item["value"].Type shows the type is Date.

How do I get to have Json.NET leave it as a string, "unparsed"?

答:
You can try with Newtonsoft. See below.</p>

```<code>JsonConvert.DeserializeObject<your_object>(your_json, new IsoDateTimeConverter{ DateTimeFormat = "dd/MM/yyy" });
</code>```

Body:
I have some attributes returned from a rest service that are served as an array of name-value pairs.

In some cases the value is a date expressed in universal sortable format:
{
  "name": "Modification-Date",
  "value": "2017-11-13T15:15:13.968Z"
}

When it gets parsed by the deserialiser, the value is identified as a date but given that the object the pair is deserialised into has type string for both name and value, the date is then converted to string and it loses precision: "13/11/2017 15:15:13"

This is easily visible by using a converter for the NameValue type.

if (reader.TokenType == JsonToken.StartObject)
{
    var item = JObject.Load(reader);

    return new NameValueFacet()
    {
        Name = item["name"].Value<string>(),
        Value = item["value"].Value<string>()
    };
}

item["value"].Type shows the type is Date.

How do I get to have Json.NET leave it as a string, "unparsed"?

Body:
You can try with Newtonsoft. See below.

JsonConvert.DeserializeObject<your_object>(your_json, new IsoDateTimeConverter{ DateTimeFormat = "dd/MM/yyy" });


问:
How to duplicate Magento report? Unable Change action function name
I was trying to duplicate Sales->Orders report during which I had an issue. I tried renaming sales function named 'salesAction' to 'sales1Action' located in Mage/reports/etc/adminhtml.xml

```<code>                    <sales translate="title" module="reports">
                        <title>Orders</title>
                        <action>adminhtml/report_sales/sales</action>
                    </sales>
</code>```

to

```<code>                    <sales translate="title" module="reports">
                        <title>Orders</title>
                        <action>adminhtml/report_sales/sales1</action>
                    </sales>
</code>```

due to which I had to rename salesAction function defined in mage/adminhtml/controllers/report/SalesController.php to sales1Action.

Once I am done with the rename, the function sales1Action is called but for some reason it does not show the report interface. Seems to me like it needs another change in some function or file from sales to sales1 to make it work. Anyone has a clue how to do that?

答:
Got the answer from another post here:

Check the file
  app/design/adminhtml/default/default/layout/sales.xml
  for the section
   - which
  matches the requested URL. It has a
  block of type
  "adminhtml/report_sales_sales" which
  is a grid container, grid containers
  automatically create their child grid
  block.

In case anyone is having similar issue, here is the link with details:
Configuring Magento Layout for New Admin Module

Body:
I was trying to duplicate Sales->Orders report during which I had an issue. I tried renaming sales function named 'salesAction' to 'sales1Action' located in Mage/reports/etc/adminhtml.xml

                    <sales translate="title" module="reports">
                        <title>Orders</title>
                        <action>adminhtml/report_sales/sales</action>
                    </sales>

to

                    <sales translate="title" module="reports">
                        <title>Orders</title>
                        <action>adminhtml/report_sales/sales1</action>
                    </sales>

due to which I had to rename salesAction function defined in mage/adminhtml/controllers/report/SalesController.php to sales1Action.

Once I am done with the rename, the function sales1Action is called but for some reason it does not show the report interface. Seems to me like it needs another change in some function or file from sales to sales1 to make it work. Anyone has a clue how to do that?


问:
how to add some data to sqlite database or sharedPrefence when installing apk
how to add some data to sqlite database or sharedPrefence when installing apk, which means the application has not been run once.</p>

答:
I run this in my Application Class. It is a little bit more powerful because it can track updates as well. previous will be 0 on first install.

```<code>public class MyApplication extends Application {

    private static SharedPreferences sPrefs = null;

    /**
     * Corresponds to the version of the app.
     */
    private static final String PREF_APP_VERSION_NAME = "app_version_name";

    /**
     * Corresponds to the version code of the app.
     */
    private static final String PREF_APP_VERSION_CODE = "app_version_code";

    @Override
    public void onCreate() {
        sPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        final int lastVersionCode = sPrefs.getInt(PREF_APP_VERSION_CODE, 0);
        final String lastVersionName = sPrefs.getString(PREF_APP_VERSION_NAME, null);
        if (BuildConfig.VERSION_CODE != sPrefs.getInt(PREF_APP_VERSION_CODE, 0) ||
                !BuildConfig.VERSION_NAME.equals(lastVersionName)) {
            Log.d(LOG_TAG, "App update detected " + lastVersionName + " → " + BuildConfig.VERSION_NAME);
            runOncePerVersion(lastVersionCode, BuildConfig.VERSION_CODE, lastVersionName, BuildConfig.VERSION_NAME);
            sPrefs.edit()
                    .putString(PREF_APP_VERSION_NAME, BuildConfig.VERSION_NAME)
                    .putInt(PREF_APP_VERSION_CODE, BuildConfig.VERSION_CODE)
                    .apply();
        }
    }

    /**
     * This method is to be called only when the app version code has changed.
     *
     * @param current      the current app version code
     * @param previousName {@link BuildConfig#VERSION_NAME} of previous install if known
     * @param currentName  {@link BuildConfig#VERSION_NAME} of current install
     */
    private void runOncePerVersion(int previous,
                                   int current,
                                   @Nullable String previousName,
                                   @NonNull String currentName) {
        UpdateNotifier.runOncePerVersion(this);
        Track.appUpdated(previousName, currentName);
        //Initialize your database from the assets folder
    }
}
</code>```

When you have a custom application class, you must declare it in AndroidManifest.xml

```<code><application
    android:name=".app.MyApplication"
    android:allowBackup="false"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="false"
    android:theme="@style/MyTheme">
</code>```

Body:
I run this in my Application Class. It is a little bit more powerful because it can track updates as well. previous will be 0 on first install.

public class MyApplication extends Application {

    private static SharedPreferences sPrefs = null;

    /**
     * Corresponds to the version of the app.
     */
    private static final String PREF_APP_VERSION_NAME = "app_version_name";

    /**
     * Corresponds to the version code of the app.
     */
    private static final String PREF_APP_VERSION_CODE = "app_version_code";

    @Override
    public void onCreate() {
        sPrefs = PreferenceManager.getDefaultSharedPreferences(this);

        final int lastVersionCode = sPrefs.getInt(PREF_APP_VERSION_CODE, 0);
        final String lastVersionName = sPrefs.getString(PREF_APP_VERSION_NAME, null);
        if (BuildConfig.VERSION_CODE != sPrefs.getInt(PREF_APP_VERSION_CODE, 0) ||
                !BuildConfig.VERSION_NAME.equals(lastVersionName)) {
            Log.d(LOG_TAG, "App update detected " + lastVersionName + " → " + BuildConfig.VERSION_NAME);
            runOncePerVersion(lastVersionCode, BuildConfig.VERSION_CODE, lastVersionName, BuildConfig.VERSION_NAME);
            sPrefs.edit()
                    .putString(PREF_APP_VERSION_NAME, BuildConfig.VERSION_NAME)
                    .putInt(PREF_APP_VERSION_CODE, BuildConfig.VERSION_CODE)
                    .apply();
        }
    }

    /**
     * This method is to be called only when the app version code has changed.
     *
     * @param current      the current app version code
     * @param previousName {@link BuildConfig#VERSION_NAME} of previous install if known
     * @param currentName  {@link BuildConfig#VERSION_NAME} of current install
     */
    private void runOncePerVersion(int previous,
                                   int current,
                                   @Nullable String previousName,
                                   @NonNull String currentName) {
        UpdateNotifier.runOncePerVersion(this);
        Track.appUpdated(previousName, currentName);
        //Initialize your database from the assets folder
    }
}

When you have a custom application class, you must declare it in AndroidManifest.xml

<application
    android:name=".app.MyApplication"
    android:allowBackup="false"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="false"
    android:theme="@style/MyTheme">


问:
FileStream vs/differences StreamWriter?
What is difference between FileStream and StreamWriter in .NET?

What context are you supposed to use it? What is their advantage and disadvantage?

Is it possible to combine these two into one?

答: One key difference (in addition to the above comments), could be that FileStream supports random disk access read and writes to any specified FileStream.Position. For large file modifications, that can be invaluable.

Title: FileStream vs/differences StreamWriter?


问:
How to add secondary legend to JavaFX chart?
When adding a custom node (in my case another legend for a JavaFX chart) with

```<code>val newLegend = MyLegend()
newLegend.isVertical=true

val legend = lookupAll(".chart-legend").first()
</code>```

The legends are cascaded (not a surprise) but at least I know that I can render it:

So to properly align them vertically one after another I've tried to add it to the parent instead:

```<code>legend.getParent().addChildIfPossible( newLegend)
</code>```

But this renders the additional node incorrectly in the upper left corner as just some dots

What am I doing wrong? Can I access the parent container of the first legend in a more clever way?

Full example sources can be found here

答:
The Node with class .chart-legend is infact a com.sun.javafx.charts.Legend, which in turn extends TilePane. If you don't want to deal with the layout constraints of the TilePane, just clear the children off of it, and add whatever layout container you want inside it. In this example I've added a VBox and three labels:

```<code>with (lookupAll(".chart-legend").first()) {
    getChildList()?.clear()
    vbox {
        label("Line 1")
        label("Line 2")
        label("Line 3")
    }
}
</code>```

Since it's clear that the chart doesn't really provide a convenient way for you to manipulate the legend, you could consider creating your own skin for the chart as a more stable solution. That way you can control exactly where the legend is displayed.

Body:
When adding a custom node (in my case another legend for a JavaFX chart) with

val newLegend = MyLegend()
newLegend.isVertical=true

val legend = lookupAll(".chart-legend").first()

The legends are cascaded (not a surprise) but at least I know that I can render it:

So to properly align them vertically one after another I've tried to add it to the parent instead:

legend.getParent().addChildIfPossible( newLegend)

But this renders the additional node incorrectly in the upper left corner as just some dots

What am I doing wrong? Can I access the parent container of the first legend in a more clever way?

Full example sources can be found here

Body:
The Node with class .chart-legend is infact a com.sun.javafx.charts.Legend, which in turn extends TilePane. If you don't want to deal with the layout constraints of the TilePane, just clear the children off of it, and add whatever layout container you want inside it. In this example I've added a VBox and three labels:

with (lookupAll(".chart-legend").first()) {
    getChildList()?.clear()
    vbox {
        label("Line 1")
        label("Line 2")
        label("Line 3")
    }
}

Since it's clear that the chart doesn't really provide a convenient way for you to manipulate the legend, you could consider creating your own skin for the chart as a more stable solution. That way you can control exactly where the legend is displayed.


问:
Incompatible types: String cannot be converted to Word
I know why the compatibility error occurs, but I want to know how you can add a String to an ArrayList of type < Word > which is a class in the program.

In OO principles, a "WordContainer" is a type of "Container", and it contains "Words", which is what I'm trying to implement here, but how do you add a String to a WordContainer that has a list of words of type Word?

```<code>public class Word {
  private String word;
  public String getWord() {
    return this.word;
  }
  public void setWord(String word) {
    this.word = word;
  }
  public Word() {
    this.word = "";
  }
}
</code>```

Container class which contains a list of words that are of type Word:

```<code>import java.util.*;
public class WordContainer {
  private List < Word > words = new ArrayList < Word > ();
  public List < Word > getWords() {
    return this.words;
  }
  public void setWords(List < Word > words) {
    this.words = words;
  }

  public void addWord(Word word) {

    this.words.add(word);
  }

  public void display() {

    words.forEach((word) - > {
      System.out.println(word);
    });

  }

  public WordContainer() {

  }
}
</code>```

Main class:

```<code>public static void main(String[] args) {
  Scanner naughty = new Scanner(System.in);
  WordContainer container1 = new WordContainer();

  while (true) {
    String nextLine = naughty.nextLine();
    if (nextLine.equals("")) {

      container1.display();
      System.exit(0);
    }

    container1.addWord(nextLine); // this bit doesn't work :(
  }

}
</code>```

答:
The method add from your WordContainer class is expecting a Word as argument not a String so what you should do is

in Main.java

```<code>  container1.addWord(new Word(nextLine));
</code>```

And define a constructor in your Word class that accepts a String

In Word.java

```<code>public Word(String word) {
    this.word = word;
}
</code>```

Body:
I know why the compatibility error occurs, but I want to know how you can add a String to an ArrayList of type < Word > which is a class in the program.

In OO principles, a "WordContainer" is a type of "Container", and it contains "Words", which is what I'm trying to implement here, but how do you add a String to a WordContainer that has a list of words of type Word?

public class Word {
  private String word;
  public String getWord() {
    return this.word;
  }
  public void setWord(String word) {
    this.word = word;
  }
  public Word() {
    this.word = "";
  }
}

Container class which contains a list of words that are of type Word:

import java.util.*;
public class WordContainer {
  private List < Word > words = new ArrayList < Word > ();
  public List < Word > getWords() {
    return this.words;
  }
  public void setWords(List < Word > words) {
    this.words = words;
  }

  public void addWord(Word word) {

    this.words.add(word);
  }

  public void display() {

    words.forEach((word) - > {
      System.out.println(word);
    });

  }

  public WordContainer() {

  }
}

Main class:

public static void main(String[] args) {
  Scanner naughty = new Scanner(System.in);
  WordContainer container1 = new WordContainer();

  while (true) {
    String nextLine = naughty.nextLine();
    if (nextLine.equals("")) {

      container1.display();
      System.exit(0);
    }

    container1.addWord(nextLine); // this bit doesn't work :(
  }

}

Body:
The method add from your WordContainer class is expecting a Word as argument not a String so what you should do is

in Main.java

  container1.addWord(new Word(nextLine));

And define a constructor in your Word class that accepts a String

In Word.java

public Word(String word) {
    this.word = word;
}


问:
Tensorflow: labeling issue
```<code>import tensorflow as tf
import numpy as np
import glob
fq=glob.glob("*.jpg")
filename_queue = tf.train.string_input_producer(fq)
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_jpeg(value,channels=3)
my_img=tf.cast(my_img,tf.float32)
resized_image = tf.image.resize_images(my_img, [50, 50])

labels=[1,1,1,0,0]
onehot = tf.one_hot(labels, depth=2)

image_batch = tf.train.batch([resized_image], batch_size=2)

# layer 1
w1 = tf.Variable(tf.truncated_normal([2, 2, 3, 52], stddev=0.01))
b1= tf.Variable(tf.constant(0.01, shape = [52]))
layer1=tf.nn.conv2d(image_batch,w1,[1,1,1,1],padding='SAME')
act1=tf.nn.relu(tf.nn.bias_add(layer1,b1))
pool1=tf.layers.max_pooling2d(act1,2,2)

# layer 2
b2= tf.Variable(tf.constant(0.01, shape = [104]))
w2=tf.Variable(tf.truncated_normal([2, 2,52, 104], stddev=0.01))
layer2=tf.nn.conv2d(pool1,w2,[1,1,1,1],padding='SAME')
act2=tf.nn.relu(tf.nn.bias_add(layer2,b2))
pool2=tf.layers.max_pooling2d(act2,2,2)

#fully connected layer
b3= tf.Variable(tf.constant(0.01, shape = [300]))
w3=tf.Variable(tf.truncated_normal([12*12*104, 300], stddev=0.01))
fcl1=tf.reshape(pool2,[-1,12*12*104])
fcl1 = tf.add(tf.matmul(fcl1, w3), b3)
fcl1 = tf.nn.relu(fcl1)
fcl1 = tf.nn.dropout(fcl1,0.5)

#output layer
b_out=b3= tf.Variable(tf.constant(0.01, shape = [2]))
w_out=tf.Variable(tf.truncated_normal([300, 2], stddev=0.01))
ans=tf.add(tf.matmul(fcl1,w_out),b_out)

#traning , loss , optimizer
logits = ans
prediction = tf.nn.softmax(logits)
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=onehot))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(loss_op)

with tf.Session() as s:
    s.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    for step in range(1, 40):
        s.run(train_op)
        print(step,s.run(loss_op))
    coord.request_stop()
    coord.join(threads)
</code>```

Traceback (most recent call last):
    File "test.py", line 56, in
      logits=logits, labels=onehot))

ValueError: Dimension 0 in both shapes must be equal, but are 2 and 5 for 'SoftmaxCrossEntropyWithLogits' (op: 'SoftmaxCrossEntropyWithLogits') with input shapes: [2,2], [5,2].

Please tell me what is my mistake, I think I need to feed 2 labels at a time but it is taking all 5 at a time. How can I batch labels separately?

答:
You are making input batches, but not label batches. Try feeding label batches as well. Make a placeholder for your labels:

labels = tf.placeholder(tf.int32, [None])
# Keep the tf.one_hot op.
onehot = tf.one_hot(labels, depth=2)
```

<p>and then later:</p>

<pre class="lang-py prettyprint-override"><code>all_labels = [1, 1, 1, 0, 0]
start = 0
with tf.Session() as s:
    # ...
    for step in range(40):
        t = all_labels[start:start+2]  # grab next label batch
        start += 2
        if start > len(all_labels):
            start = 0  # reset to start of list when we overrun the end
        sess.run(train_op, feed_dict={labels: t})
</code>```

Honestly, I would handle both your data batches and your label batches the same way, but I was having trouble figuring out how to get tf.train.batch to work on the output of tf.one_hot, and I was having trouble running tf.train.batch on your raw label array first and then passing it to tf.one_hot.

Title: Tensorflow: labeling issue

Body:
import tensorflow as tf
import numpy as np
import glob
fq=glob.glob("*.jpg")
filename_queue = tf.train.string_input_producer(fq)
reader = tf.WholeFileReader()
key, value = reader.read(filename_queue)
my_img = tf.image.decode_jpeg(value,channels=3)
my_img=tf.cast(my_img,tf.float32)
resized_image = tf.image.resize_images(my_img, [50, 50])

labels=[1,1,1,0,0]
onehot = tf.one_hot(labels, depth=2)

image_batch = tf.train.batch([resized_image], batch_size=2)

# layer 1
w1 = tf.Variable(tf.truncated_normal([2, 2, 3, 52], stddev=0.01))
b1= tf.Variable(tf.constant(0.01, shape = [52]))
layer1=tf.nn.conv2d(image_batch,w1,[1,1,1,1],padding='SAME')
act1=tf.nn.relu(tf.nn.bias_add(layer1,b1))
pool1=tf.layers.max_pooling2d(act1,2,2)

# layer 2
b2= tf.Variable(tf.constant(0.01, shape = [104]))
w2=tf.Variable(tf.truncated_normal([2, 2,52, 104], stddev=0.01))
layer2=tf.nn.conv2d(pool1,w2,[1,1,1,1],padding='SAME')
act2=tf.nn.relu(tf.nn.bias_add(layer2,b2))
pool2=tf.layers.max_pooling2d(act2,2,2)

#fully connected layer
b3= tf.Variable(tf.constant(0.01, shape = [300]))
w3=tf.Variable(tf.truncated_normal([12*12*104, 300], stddev=0.01))
fcl1=tf.reshape(pool2,[-1,12*12*104])
fcl1 = tf.add(tf.matmul(fcl1, w3), b3)
fcl1 = tf.nn.relu(fcl1)
fcl1 = tf.nn.dropout(fcl1,0.5)

#output layer
b_out=b3= tf.Variable(tf.constant(0.01, shape = [2]))
w_out=tf.Variable(tf.truncated_normal([300, 2], stddev=0.01))
ans=tf.add(tf.matmul(fcl1,w_out),b_out)

#traning , loss , optimizer
logits = ans
prediction = tf.nn.softmax(logits)
loss_op = tf.reduce_mean(tf.nn.softmax_cross_entropy_with_logits(
logits=logits, labels=onehot))
optimizer = tf.train.AdamOptimizer(learning_rate=0.001)
train_op = optimizer.minimize(loss_op)

with tf.Session() as s:
    s.run(tf.global_variables_initializer())
    coord = tf.train.Coordinator()
    threads = tf.train.start_queue_runners(coord=coord)
    for step in range(1, 40):
        s.run(train_op)
        print(step,s.run(loss_op))
    coord.request_stop()
    coord.join(threads)

Traceback (most recent call last):
    File "test.py", line 56, in
      logits=logits, labels=onehot))

ValueError: Dimension 0 in both shapes must be equal, but are 2 and 5 for 'SoftmaxCrossEntropyWithLogits' (op: 'SoftmaxCrossEntropyWithLogits') with input shapes: [2,2], [5,2].

Please tell me what is my mistake, I think I need to feed 2 labels at a time but it is taking all 5 at a time. How can I batch labels separately?

Body:
You are making input batches, but not label batches. Try feeding label batches as well. Make a placeholder for your labels:

labels = tf.placeholder(tf.int32, [None])
# Keep the tf.one_hot op.
onehot = tf.one_hot(labels, depth=2)

and then later:

all_labels = [1, 1, 1, 0, 0]
start = 0
with tf.Session() as s:
    # ...
    for step in range(40):
        t = all_labels[start:start+2]  # grab next label batch
        start += 2
        if start > len(all_labels):
            start = 0  # reset to start of list when we overrun the end
        sess.run(train_op, feed_dict={labels: t})

Honestly, I would handle both your data batches and your label batches the same way, but I was having trouble figuring out how to get tf.train.batch to work on the output of tf.one_hot, and I was having trouble running tf.train.batch on your raw label array first and then passing it to tf.one_hot.


问:
Computing Values for Groups of Data Excel
I have a big Excel file with listed participants and dates. I want to calculate, for each date, how many days it is from the first (start) date for each participant. Each start date is different, and each participant has a different number of entries. I know what formula I need to do the calculation, but I'm stumped on how I can recursively calculate for each participant without doing it manually! Example for what I have and want:

```<code>Participant Date    Days from Start
ca002   01/01/1983  0
ca002   10/05/1984  495
ca002   01/01/1986  1096
ca002   01/01/1986  1096
ca002   29/12/1999  6206
ca002   21/03/2001  6654
ca002   31/12/2004  8035
ca004   01/01/1967  0
ca004   01/01/1972  1826
ca004   01/01/1989  8036
ca004   01/01/2006  14245
ca004   01/01/2006  14245
</code>```

Any help greatly appreciated.

答: If you are only interested in the latest date, you could use a PivotTable to get the first and last dates, and then just subtract one from the other:

Body:
I have a big Excel file with listed participants and dates. I want to calculate, for each date, how many days it is from the first (start) date for each participant. Each start date is different, and each participant has a different number of entries. I know what formula I need to do the calculation, but I'm stumped on how I can recursively calculate for each participant without doing it manually! Example for what I have and want:

Participant Date    Days from Start
ca002   01/01/1983  0
ca002   10/05/1984  495
ca002   01/01/1986  1096
ca002   01/01/1986  1096
ca002   29/12/1999  6206
ca002   21/03/2001  6654
ca002   31/12/2004  8035
ca004   01/01/1967  0
ca004   01/01/1972  1826
ca004   01/01/1989  8036
ca004   01/01/2006  14245
ca004   01/01/2006  14245

Any help greatly appreciated.


问:
mumps lanaguage FOR loop related
if i define For K="ABC":1:3 now what is the value of "ABC",how the loop to excute "ABC" or instead of that ABC if i take any "string", how does increment the string "ABC".

Bhas

答:
If you have access to a MUMPS system, it's trivial to find out. Just run the following routine, which could reside e.g. in a file for3.m:

```<code>for3

; routine to test FOR command

   FOR K="ABC":1:3 WRITE "K=",K,! QUIT
</code>```

On my Linux box, I have GT.M installed. You can get it at
   http://sourceforge.net/projects/fis-gtm/

Here's the output:

```<code>$ gtm -run for3
K=0
K=1
K=2
K=3
</code>```

HTH
Nathan

Title: mumps lanaguage FOR loop related

Body:
If you have access to a MUMPS system, it's trivial to find out. Just run the following routine, which could reside e.g. in a file for3.m:

for3

; routine to test FOR command

   FOR K="ABC":1:3 WRITE "K=",K,! QUIT

On my Linux box, I have GT.M installed. You can get it at
   http://sourceforge.net/projects/fis-gtm/

Here's the output:

$ gtm -run for3
K=0
K=1
K=2
K=3

HTH
Nathan


问:
requestAnimationFrame() not refreshing
I'm learning how to use requestAnimationFrame() and the animation changes when refreshing the page. Shouldn't it should continuously change the font size without having to refresh it? </p>

```<code>var x = Math.floor((Math.random() * 100));

function draw(){
  for (i=0; i < 100; i++){
    $("#lw").css("font-size", x);
  }
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);
</code>```

答:
requestAnimationFrame is working like it's supposed to. You're never changing the conditions between calls or loop iterations.

function draw(){
  for (var i = 0, x = Math.floor((Math.random() * 100)); i < x; i++){
    $("#lw").css("font-size", i);
  }
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="lw">Test</span></code>```

Title: requestAnimationFrame() not refreshing

Body:
I'm learning how to use requestAnimationFrame() and the animation changes when refreshing the page. Shouldn't it should continuously change the font size without having to refresh it?

var x = Math.floor((Math.random() * 100));

function draw(){
  for (i=0; i < 100; i++){
    $("#lw").css("font-size", x);
  }
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);

Body:
requestAnimationFrame is working like it's supposed to. You're never changing the conditions between calls or loop iterations.

function draw(){
  for (var i = 0, x = Math.floor((Math.random() * 100)); i < x; i++){
    $("#lw").css("font-size", i);
  }
  requestAnimationFrame(draw);
}

requestAnimationFrame(draw);

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<span id="lw">Test</span>


问:
Java - Factory, Instance
```<code>public class DataFactory {

    class SYNOP implements IDataSources {}
    class WRF implements IDataSources {}

    public abstract class Factory {
        public abstract IDataSources CreateModel();
    }

    public class SYNOPFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new SYNOP();
        }
    }

    public class WRFFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new WRF();
        }
    }

    public static void main(String[] args) {

        Factory factory = new WRFFactory();

    }
}
</code>```

And i got message error like this:

No enclosing instance of type DataFactory is accessible. Must qualify
  the allocation with an enclosing instance of type DataFactory (e.g.
  x.new A() where x is an instance of DataFactory).

What did i do wrong?

Regards

答:
You need the object

private static DataFactory dataFactory;

You need a private Constructor

```<code>    private DataFactory() {
}
</code>```

And you need an instance builder

```<code>    public static DataFactory getInstance() {

    if (DataFactory.dataFactory == null) {
        DataFactory.dataFactory = new DataFactory();

    }

    return DataFactory.dataFactory;

}
</code>```

Then you call it in main

```<code>DataFactory dataFactory = DataFactory.getInstance();
</code>```

This is a true factory Class

Title: Java - Factory, Instance

Body:
public class DataFactory {

    class SYNOP implements IDataSources {}
    class WRF implements IDataSources {}

    public abstract class Factory {
        public abstract IDataSources CreateModel();
    }

    public class SYNOPFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new SYNOP();
        }
    }

    public class WRFFactory extends Factory {

        @Override
        public IDataSources CreateModel() {
            return new WRF();
        }
    }

    public static void main(String[] args) {

        Factory factory = new WRFFactory();

    }
}

And i got message error like this:

No enclosing instance of type DataFactory is accessible. Must qualify
  the allocation with an enclosing instance of type DataFactory (e.g.
  x.new A() where x is an instance of DataFactory).

What did i do wrong?

Regards

Body:
You need the object

private static DataFactory dataFactory;

You need a private Constructor

    private DataFactory() {
}

And you need an instance builder

    public static DataFactory getInstance() {

    if (DataFactory.dataFactory == null) {
        DataFactory.dataFactory = new DataFactory();

    }

    return DataFactory.dataFactory;

}

Then you call it in main

DataFactory dataFactory = DataFactory.getInstance();

This is a true factory Class


问:
Simple JSON Server
How to parse this type of json in android:

```<code>{
"chatCircles": [{
    "id": "59660c155d44f20b46eab438",
    "name": "Hyderabad Circle",
    "description": "Hyderabad"
}]
}
</code>```

I have tried this but UI is not updating.

```<code>try {
        JSONArray chatCircleArray = response.getJSONArray("chatCircle");
        for (int i = 0; i < chatCircleArray.length(); i++){
           JSONObject geoFenceObject = chatCircleArray.getJSONObject(i);
           circleId = geoFenceObject.getString("id");
           String circleName = geoFenceObject.getString("name");
           String location = geoFenceObject.getString("description");
           Log.d(TAG, "GeoFenceObject Chat Circle Id parsed is:\t " + circleId);
           System.out.println("Chat Circle id is: \t" + circleId);

            } catch (JSONException e) {
                e.printStackTrace();
            }
</code>```

Pls help. How to do this json parsing?

答:
The first brace is a JSONObject that you didn't parse.
Try the code below.</p>

```<code>try {
        JSONObject json = new JSONObject(response);

        JSONArray itemArray = json.getJSONArray("chatCircles");
        for (int i = 0; i < itemArray.length(); i++) {
            JSONObject subJson = (JSONObject) itemArray.get(i);
            String id = subJson.getString("id");
            String name = subJson.getString("name");
            String description = subJson.getString("description");
            Log.i("TEST", "id=" + id + ", name=" + name + ", description=" + description);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
</code>```

Title: Simple JSON Server

Body:
How to parse this type of json in android:

{
"chatCircles": [{
    "id": "59660c155d44f20b46eab438",
    "name": "Hyderabad Circle",
    "description": "Hyderabad"
}]
}

I have tried this but UI is not updating.

try {
        JSONArray chatCircleArray = response.getJSONArray("chatCircle");
        for (int i = 0; i < chatCircleArray.length(); i++){
           JSONObject geoFenceObject = chatCircleArray.getJSONObject(i);
           circleId = geoFenceObject.getString("id");
           String circleName = geoFenceObject.getString("name");
           String location = geoFenceObject.getString("description");
           Log.d(TAG, "GeoFenceObject Chat Circle Id parsed is:\t " + circleId);
           System.out.println("Chat Circle id is: \t" + circleId);

            } catch (JSONException e) {
                e.printStackTrace();
            }

Pls help. How to do this json parsing?

Body:
The first brace is a JSONObject that you didn't parse.
Try the code below.

try {
        JSONObject json = new JSONObject(response);

        JSONArray itemArray = json.getJSONArray("chatCircles");
        for (int i = 0; i < itemArray.length(); i++) {
            JSONObject subJson = (JSONObject) itemArray.get(i);
            String id = subJson.getString("id");
            String name = subJson.getString("name");
            String description = subJson.getString("description");
            Log.i("TEST", "id=" + id + ", name=" + name + ", description=" + description);
        }
    } catch (Exception e) {
        e.printStackTrace();
    }


问:
Powershell: Update-TfsWorkspace cmdlet how to update two workspaces
I want to update 2 workspaces from two different tfs in one script using powershell.
The first Workspace is updating without any Problems. After the update is finished powershell connects to the second Workspace, but isn't updating the local data like the first time.

I guess the old Connection might still block the pipe or something like that, but I haven't found any cmd to clean the pipe. My code looks like this:

```<code>param(
      [string]$TestTFS = "http://TestTFS",
      [string]$ProdTFS = "http://ProdTFS",
      [string]$Teamproject="$\TeamprojectPath",
      [string]$LocalTestWorkspace="C:\LocalTestWorkspacePath",
      [string]$LocalProdWorkspace="C:\LocalProdWorkspacePath"
     )

# Import Microsoft.TeamFoundation.PowerShell Snapin
Add-PSSnapin Microsoft.TeamFoundation.PowerShell

# Connect to production-TFS
$ProdEnvServer = Get-TfsServer -Name $ProdTFS
Write-Host "tfsConnect ="$ProdEnvServer

# Get prod teamprojekt
Get-TfsChildItem $Teamprojekt -Server $ProdEnvServer

# Update files in local prod workspace
Update-TfsWorkspace -Force -Recurse $LocalProdWorkspace

# Connect to test-TFS
$TestEnvServer = Get-TfsServer -Name $TestTFS
Write-Host "tfsConnect ="$TestEnvServer

# Get test teamprojekt
Get-TfsChildItem $Teamprojekt -Server $TestEnvServer

# Update files in local test workspace
Update-TfsWorkspace -Force -Recurse $LocalTestWorkspace
</code>```

答:
My approach is very similar to Zittelrittel. Just send the path and it will automatically figure out the workspace.

This will not work in PowerShell ISE (x86), I had to use the 64-bit version!

```<code>Add-PSSnapin Microsoft.TeamFoundation.PowerShell

Write-Host "Updating Workspace1, please wait..."
Update-TfsWorkspace -item C:\dev\Workspace1\code -Recurse | Format-Table

Write-Host "Updating Workspace2, please wait..."
Update-TfsWorkspace -item C:\dev\Workspace1\code -Recurse | Format-Table
</code>```

Body:
I want to update 2 workspaces from two different tfs in one script using powershell.
The first Workspace is updating without any Problems. After the update is finished powershell connects to the second Workspace, but isn't updating the local data like the first time.

I guess the old Connection might still block the pipe or something like that, but I haven't found any cmd to clean the pipe. My code looks like this:

param(
      [string]$TestTFS = "http://TestTFS",
      [string]$ProdTFS = "http://ProdTFS",
      [string]$Teamproject="$\TeamprojectPath",
      [string]$LocalTestWorkspace="C:\LocalTestWorkspacePath",
      [string]$LocalProdWorkspace="C:\LocalProdWorkspacePath"
     )

# Import Microsoft.TeamFoundation.PowerShell Snapin
Add-PSSnapin Microsoft.TeamFoundation.PowerShell

# Connect to production-TFS
$ProdEnvServer = Get-TfsServer -Name $ProdTFS
Write-Host "tfsConnect ="$ProdEnvServer

# Get prod teamprojekt
Get-TfsChildItem $Teamprojekt -Server $ProdEnvServer

# Update files in local prod workspace
Update-TfsWorkspace -Force -Recurse $LocalProdWorkspace

# Connect to test-TFS
$TestEnvServer = Get-TfsServer -Name $TestTFS
Write-Host "tfsConnect ="$TestEnvServer

# Get test teamprojekt
Get-TfsChildItem $Teamprojekt -Server $TestEnvServer

# Update files in local test workspace
Update-TfsWorkspace -Force -Recurse $LocalTestWorkspace

Body:
My approach is very similar to Zittelrittel. Just send the path and it will automatically figure out the workspace.

This will not work in PowerShell ISE (x86), I had to use the 64-bit version!

Add-PSSnapin Microsoft.TeamFoundation.PowerShell

Write-Host "Updating Workspace1, please wait..."
Update-TfsWorkspace -item C:\dev\Workspace1\code -Recurse | Format-Table

Write-Host "Updating Workspace2, please wait..."
Update-TfsWorkspace -item C:\dev\Workspace1\code -Recurse | Format-Table


问:
Displays incorrect values after created Date Dimension table in Power BI
My Fact table "Premiums" has Premium value and DateTime column (EffectiveDate).
If I look at the Premium by MONTH(EffectiveDate) - it looks correct. Sorry, its not sorted.

But then if I create table Dates, join it to Premiums table on EffectiveDate column and try to look at Premiums by Month - it looks completely different.

I tried two different ways to create Calendar table. Still the same incorrect values.

What am I doing wrong?

答:
It looks to me like you are trying to match a datetime (Premiums[EffectiveDate]) to a date (Dates[Date]), so it's not matching most of your rows.

Try adding a calculated column to your Premiums table that converts EffectiveDate to a date type and then match that up with your calendar table. The following are a few ways that should work for your calculated column:

```<code>Calculated Column = Premiums[EffectiveDate].[Date]
Calculated Column = EDATE(Premiums[EffectiveDate],0)
Calculated Column = ROUNDDOWN(Premiums[EffectiveDate],0)
Calculated Column = DATE(YEAR(Premiums[EffectiveDate]),MONTH(Premiums[EffectiveDate]),DAY(Premiums[EffectiveDate]))
Calculated Column = DATEVALUE(FORMAT(Premiums[EffectiveDate],"yyyy/mm/dd"))
</code>```

Edit: If you don't need the time part of the EffectiveDate column for anything, then just convert both that column and the calendar date column to date types, and it should match up.

Body:
It looks to me like you are trying to match a datetime (Premiums[EffectiveDate]) to a date (Dates[Date]), so it's not matching most of your rows.

Try adding a calculated column to your Premiums table that converts EffectiveDate to a date type and then match that up with your calendar table. The following are a few ways that should work for your calculated column:

Calculated Column = Premiums[EffectiveDate].[Date]
Calculated Column = EDATE(Premiums[EffectiveDate],0)
Calculated Column = ROUNDDOWN(Premiums[EffectiveDate],0)
Calculated Column = DATE(YEAR(Premiums[EffectiveDate]),MONTH(Premiums[EffectiveDate]),DAY(Premiums[EffectiveDate]))
Calculated Column = DATEVALUE(FORMAT(Premiums[EffectiveDate],"yyyy/mm/dd"))

Edit: If you don't need the time part of the EffectiveDate column for anything, then just convert both that column and the calendar date column to date types, and it should match up.


问:
Alter Displayed Information in data-bound DataGridView
I have a datagridview that is databound. One of the columns, which is shown below, is linked to a boolean value from an object. The method to retrieve the boolean value would be "curResultSet.Pass". Instead of saying "True" or "False" in a regular cell, I want that column to have a "Pass" icon or "Fail" icon depending on the value of "curResult.Pass".

I am fairly certain that my method of setting a .png to an Icon is wrong, but I can worry about that later. Right now, my biggest concern is I am not sure how to set a certain Icon in the DataGridViewImageViewColumn based on the value of a Boolean as shown in my code below.

```<code>DataGridViewImageColumn imgCol = new DataGridViewImageColumn(true);

foreach(RunResult curResult in curResultSet)
{
     bindingSource1.Add(curResult);
}

resultDataGridView.AutoGenerateColumns = false;
resultDataGridView.DataSource = bindingSource1;

imgCol.Image = Image.FromFile(imageFilePath + "NG icon.png");
imgCol.Icon = Icon.ExtractAssociatedIcon(imageFilePath + "OK icon.png");
imgCol.ValuesAreIcons = true;

resultDataGridView.Columns.Add(imgCol);
resultDataGridView.Columns[resultDataGridView.ColumnCount - 1].DataPropertyName = "Pass";
resultDataGridView.Columns[resultDataGridView.ColumnCount - 1].Name = "status";
</code>```

Anyone have any idea how I can have my "OK icon.png" show when "curResultSet[].Pass == True" and have "NG icon.png" show when "curResultSet[].Pass == False"? Thanks!

答:
You should use a converter and bind the image source to the boolean value:
    public class BoolToUriConverter : IValueConverter
    {
        private const string filePath = "your path";

```<code>    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool val = (bool)value ;
        string path = (val == true) ? $"{filePath}OK icon.png" : $"{filePath}NG icon.png";
        return new Uri(path);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}
</code>```

And use it to bind your boolean column to the image column

```<code><DataGrid ItemsSource="{Binding Collection1}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Field1" Binding="{Binding Field1}"></DataGridTextColumn>
                <DataGridTextColumn Header="Field2" Binding="{Binding Field2}"></DataGridTextColumn>
                <DataGridCheckBoxColumn Header="Field3" Binding="{Binding Field3}"></DataGridCheckBoxColumn>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Field3, Converter={StaticResource boolToUriConverter}}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>
</code>```

Body:
I have a datagridview that is databound. One of the columns, which is shown below, is linked to a boolean value from an object. The method to retrieve the boolean value would be "curResultSet.Pass". Instead of saying "True" or "False" in a regular cell, I want that column to have a "Pass" icon or "Fail" icon depending on the value of "curResult.Pass".

I am fairly certain that my method of setting a .png to an Icon is wrong, but I can worry about that later. Right now, my biggest concern is I am not sure how to set a certain Icon in the DataGridViewImageViewColumn based on the value of a Boolean as shown in my code below.

DataGridViewImageColumn imgCol = new DataGridViewImageColumn(true);

foreach(RunResult curResult in curResultSet)
{
     bindingSource1.Add(curResult);
}

resultDataGridView.AutoGenerateColumns = false;
resultDataGridView.DataSource = bindingSource1;

imgCol.Image = Image.FromFile(imageFilePath + "NG icon.png");
imgCol.Icon = Icon.ExtractAssociatedIcon(imageFilePath + "OK icon.png");
imgCol.ValuesAreIcons = true;

resultDataGridView.Columns.Add(imgCol);
resultDataGridView.Columns[resultDataGridView.ColumnCount - 1].DataPropertyName = "Pass";
resultDataGridView.Columns[resultDataGridView.ColumnCount - 1].Name = "status";

Anyone have any idea how I can have my "OK icon.png" show when "curResultSet[].Pass == True" and have "NG icon.png" show when "curResultSet[].Pass == False"? Thanks!

Body:
You should use a converter and bind the image source to the boolean value:
    public class BoolToUriConverter : IValueConverter
    {
        private const string filePath = "your path";

    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        bool val = (bool)value ;
        string path = (val == true) ? $"{filePath}OK icon.png" : $"{filePath}NG icon.png";
        return new Uri(path);
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

And use it to bind your boolean column to the image column

<DataGrid ItemsSource="{Binding Collection1}" AutoGenerateColumns="False">
            <DataGrid.Columns>
                <DataGridTextColumn Header="Field1" Binding="{Binding Field1}"></DataGridTextColumn>
                <DataGridTextColumn Header="Field2" Binding="{Binding Field2}"></DataGridTextColumn>
                <DataGridCheckBoxColumn Header="Field3" Binding="{Binding Field3}"></DataGridCheckBoxColumn>
                <DataGridTemplateColumn>
                    <DataGridTemplateColumn.CellTemplate>
                        <DataTemplate>
                            <Image Source="{Binding Field3, Converter={StaticResource boolToUriConverter}}"/>
                        </DataTemplate>
                    </DataGridTemplateColumn.CellTemplate>
                </DataGridTemplateColumn>
            </DataGrid.Columns>
        </DataGrid>


问:
Finding average of last column
So i need the program to print out the averages of the average temperatures of each week but i cannot find a solution on how to do so. Currently i have the column that prints out the averages of the temperatures of the week as a System.out.print, so its not in the 2d array but now i need to find the average of those averages. I tried using System.out.print(average/4); to find the averages but the number it prints out isn't correct. How should i write the code for this ?

```<code>import java.text.DecimalFormat;
import java.util.Scanner;

public class TwoDimArray {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // 1) Declare and allocate Storage
        //Each day name is assigned to the array as a String so each name must be enclosed in apostrophes and each string must be separated by commas.
        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        double[][] Temperature = new double[4][7];

        // 2) Populate Array
        for (int i = 0; i < Temperature.length; i++) {
            for (int j = 0; j < Temperature[0].length; j++) {
                //days[j] will print the proper day and "(i+1)" will print the proper day of the week
                System.out.print("Enter " + days[j] + " Temperature " + "for Week " + (i + 1) + ": " + "    ");
                Temperature[i][j] = scan.nextDouble();
            }

        }
        System.out.println();
        System.out.println("              Weekly Temperature Report ");
        System.out.println("Mon     Tue     Wed     Thurs    Fri    Sat     Sun    Average");

        double columnTotal, average;
        // 4) Output Array

        for (int i = 0; i < Temperature.length; i++) {
            System.out.println();
            columnTotal = 0;
            for (int j = 0; j < Temperature[0].length; j++) {
                System.out.print(Temperature[i][j] + "\t");
                columnTotal += Temperature[i][j];
            }
            average = columnTotal / 7;
            System.out.println(average);
        }

        System.out.println();
        System.out.println("------------------------------------------------------------------");
        int avg;
        for (int i = 0; i < Temperature[0].length; i++) {
            columnTotal = 0;
            avg = 0;
            for (int j = 0; j < Temperature.length; j++) {
                columnTotal = columnTotal + Temperature[j][i];

            }
            System.out.print((columnTotal / 4) + "    ");
            System.out.print(average / 4);

        }
    }
}
</code>```

答:
ok do the following changes in ur code

Declare The array of average average[] = new double[Temperature.length];

Replace this  average = columnTotal / 7;System.out.println(average);with this

average[i] = columnTotal / 7 ; System.out.println(average[i]);
so what i am doing storing the averages in array . you were storing the average in a simple variable which was overwritten again and again till the end of loop

And at the end replace the last part of code with

columnTotal = 0;

```<code>for (int i = 0; i < average.length; i++) {
        columnTotal = columnTotal +average[i];
    }
    System.out.print((columnTotal / 4) + "    ");
</code>```

And Finally Your code will look like this

```<code>import java.text.DecimalFormat;
import java.util.Scanner;

public class TwoDimArray {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // 1) Declare and allocate Storage
        //Each day name is assigned to the array as a String so each name must be enclosed in apostrophes and each string must be separated by commas.
        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        double[][] Temperature = new double[4][7];

        // 2) Populate Array
        for (int i = 0; i < Temperature.length; i++) {
            for (int j = 0; j < Temperature[0].length; j++) {
                //days[j] will print the proper day and "(i+1)" will print the proper day of the week
                System.out.print("Enter " + days[j] + " Temperature " + "for Week " + (i + 1) + ": " + "    ");
                Temperature[i][j] = scan.nextDouble();
            }

        }
        System.out.println();
        System.out.println("              Weekly Temperature Report ");
        System.out.println("Mon     Tue     Wed     Thurs    Fri    Sat     Sun    Average");

        double columnTotal, average[] = new double[Temperature.length];
        // 4) Output Array

        for (int i = 0; i < Temperature.length; i++) {
            System.out.println();
            columnTotal = 0;
            for (int j = 0; j < Temperature[0].length; j++) {
                System.out.print(Temperature[i][j] + "\t");
                columnTotal += Temperature[i][j];
            }
            average[i] = columnTotal / 7;
            System.out.println(average[i]);
        }

        System.out.println();
        System.out.println("------------------------------------------------------------------");

        columnTotal = 0;
        for (int i = 0; i < average.length; i++) {
                columnTotal = columnTotal +average[i];
            }
            System.out.print((columnTotal / 4) + "    ");
            //System.out.print(average/4);

        }
    }
</code>```

Title: Finding average of last column

Body:
So i need the program to print out the averages of the average temperatures of each week but i cannot find a solution on how to do so. Currently i have the column that prints out the averages of the temperatures of the week as a System.out.print, so its not in the 2d array but now i need to find the average of those averages. I tried using System.out.print(average/4); to find the averages but the number it prints out isn't correct. How should i write the code for this ?

import java.text.DecimalFormat;
import java.util.Scanner;

public class TwoDimArray {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // 1) Declare and allocate Storage
        //Each day name is assigned to the array as a String so each name must be enclosed in apostrophes and each string must be separated by commas.
        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        double[][] Temperature = new double[4][7];

        // 2) Populate Array
        for (int i = 0; i < Temperature.length; i++) {
            for (int j = 0; j < Temperature[0].length; j++) {
                //days[j] will print the proper day and "(i+1)" will print the proper day of the week
                System.out.print("Enter " + days[j] + " Temperature " + "for Week " + (i + 1) + ": " + "    ");
                Temperature[i][j] = scan.nextDouble();
            }

        }
        System.out.println();
        System.out.println("              Weekly Temperature Report ");
        System.out.println("Mon     Tue     Wed     Thurs    Fri    Sat     Sun    Average");

        double columnTotal, average;
        // 4) Output Array

        for (int i = 0; i < Temperature.length; i++) {
            System.out.println();
            columnTotal = 0;
            for (int j = 0; j < Temperature[0].length; j++) {
                System.out.print(Temperature[i][j] + "\t");
                columnTotal += Temperature[i][j];
            }
            average = columnTotal / 7;
            System.out.println(average);
        }

        System.out.println();
        System.out.println("------------------------------------------------------------------");
        int avg;
        for (int i = 0; i < Temperature[0].length; i++) {
            columnTotal = 0;
            avg = 0;
            for (int j = 0; j < Temperature.length; j++) {
                columnTotal = columnTotal + Temperature[j][i];

            }
            System.out.print((columnTotal / 4) + "    ");
            System.out.print(average / 4);

        }
    }
}

Body:
ok do the following changes in ur code

Declare The array of average average[] = new double[Temperature.length];

Replace this  average = columnTotal / 7;System.out.println(average);with this

average[i] = columnTotal / 7 ; System.out.println(average[i]);
so what i am doing storing the averages in array . you were storing the average in a simple variable which was overwritten again and again till the end of loop

And at the end replace the last part of code with

columnTotal = 0;

for (int i = 0; i < average.length; i++) {
        columnTotal = columnTotal +average[i];
    }
    System.out.print((columnTotal / 4) + "    ");

And Finally Your code will look like this

import java.text.DecimalFormat;
import java.util.Scanner;

public class TwoDimArray {

    public static void main(String[] args) {
        Scanner scan = new Scanner(System.in);

        // 1) Declare and allocate Storage
        //Each day name is assigned to the array as a String so each name must be enclosed in apostrophes and each string must be separated by commas.
        String[] days = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
        double[][] Temperature = new double[4][7];

        // 2) Populate Array
        for (int i = 0; i < Temperature.length; i++) {
            for (int j = 0; j < Temperature[0].length; j++) {
                //days[j] will print the proper day and "(i+1)" will print the proper day of the week
                System.out.print("Enter " + days[j] + " Temperature " + "for Week " + (i + 1) + ": " + "    ");
                Temperature[i][j] = scan.nextDouble();
            }

        }
        System.out.println();
        System.out.println("              Weekly Temperature Report ");
        System.out.println("Mon     Tue     Wed     Thurs    Fri    Sat     Sun    Average");

        double columnTotal, average[] = new double[Temperature.length];
        // 4) Output Array

        for (int i = 0; i < Temperature.length; i++) {
            System.out.println();
            columnTotal = 0;
            for (int j = 0; j < Temperature[0].length; j++) {
                System.out.print(Temperature[i][j] + "\t");
                columnTotal += Temperature[i][j];
            }
            average[i] = columnTotal / 7;
            System.out.println(average[i]);
        }

        System.out.println();
        System.out.println("------------------------------------------------------------------");

        columnTotal = 0;
        for (int i = 0; i < average.length; i++) {
                columnTotal = columnTotal +average[i];
            }
            System.out.print((columnTotal / 4) + "    ");
            //System.out.print(average/4);

        }
    }