问:
Check a variable for NoneType and break a while loop
I am very new to Programming and started teaching myself web-scraping with Python.
I am scraping player data from multiple pages of a site and built a while loop which scrapes a 'next'-button's href to get to the next player's page.
Everything is working out fine, except breaking the while loop after the last player available. The 'next'-button will gray out and have no link behind it, therefore I want to stop the iteration and save everything to a csv.

My script looks like this:

```<code>#name base url and first page to start

BaseUrl = #url
PageUrl = #also url

while True:

  #scraping tables

  try:
      # retrieve link for 'next' player in order
      link = soup.find(attrs={"class": "go_to_next_player"}).get('href')
      # join base url and new link href
      PageUrl = BaseUrl + link
      if link is None:
          break
  except IndexError as e:
      print(e)
      break

#writing to csv
</code>```

I thought I could check if the retrieved href is empty, therefore checking 'is None' and breaking, but I get this error:

```<code>In line > PageUrl = BaseUrl + link
TypeError: must be str, not NoneType
</code>```

Help would be greatly appreciated! I am very new to this, so please disregard my beginner code.

答:
You can check if link is None before doing any operations with it, and then break the loop:

```<code>if link is not None:
    PageUrl = BaseUrl + link
else:
    break
</code>```

Body:
I am very new to Programming and started teaching myself web-scraping with Python.
I am scraping player data from multiple pages of a site and built a while loop which scrapes a 'next'-button's href to get to the next player's page.
Everything is working out fine, except breaking the while loop after the last player available. The 'next'-button will gray out and have no link behind it, therefore I want to stop the iteration and save everything to a csv.

My script looks like this:

#name base url and first page to start

BaseUrl = #url
PageUrl = #also url

while True:

  #scraping tables

  try:
      # retrieve link for 'next' player in order
      link = soup.find(attrs={"class": "go_to_next_player"}).get('href')
      # join base url and new link href
      PageUrl = BaseUrl + link
      if link is None:
          break
  except IndexError as e:
      print(e)
      break

#writing to csv

I thought I could check if the retrieved href is empty, therefore checking 'is None' and breaking, but I get this error:

In line > PageUrl = BaseUrl + link
TypeError: must be str, not NoneType

Help would be greatly appreciated! I am very new to this, so please disregard my beginner code.

Body:
You can check if link is None before doing any operations with it, and then break the loop:

if link is not None:
    PageUrl = BaseUrl + link
else:
    break


来源: stackexchange

问:
using sed to insert file content into a file BEFORE a pattern
I'm new to sed, I'm trying to insert the content of a BFile into the file AFile, BEFORE a pattern (in AFile)

Hereafter's what I've tried :

sed -i '/blah Blah/r BFile' AFile : it's inserting the content of BFile AFTER the pattern in AFile.

sed -i '/blah Blah/i BFile' AFile : it's inserting the string 'BFile' BEFORE the pattern in AFile.

... hmmm

I'm conscious it's because of a wrong comprehension of regexp or sed : I can't understand how the /i and /r work here... I can't find any help in sed --help

Anyone understanding my point ?

Regards,

Stan

答:
[Insert file contents into another file BEFORE pattern]

```<code>sed -i '/PATTERN/r file1' -e //N file2
</code>```

[After Pattern]

```<code>sed -i '/PATTERN/r file1' file2
</code>```

ContentLicense: CC BY-SA 3.0

Body:
[Insert file contents into another file BEFORE pattern]

sed -i '/PATTERN/r file1' -e //N file2

[After Pattern]

sed -i '/PATTERN/r file1' file2


问:
Can't set innerHTML on tbody in IE
I have a table like this:

```<code><table>
<thead>
    <tr>
        <th colspan="1">a</th>
        <th colspan="3">b</th>
    </tr>
</thead>
<tbody id="replaceMe">
    <tr>
        <td>data 1</td>
        <td>data 2</td>
        <td>data 3</td>
        <td>data 4</td>
    </tr>
</tbody>
</table>
</code>```

and a method returns me the following after an ajax request:

```<code><tr>
    <td>data 1 new</td>
    <td>data 2 new</td>
    <td>data 3 new</td>
    <td>data 4 new</td>
</tr>
</code>```

I want to change the innerHTML like

```<code>document.getElementById('replaceMe').innerHTML = data.responseText;
</code>```

However, it seems that IE can't set innerHTML on
. Can anyone help me with a simple workaround for this issue?

答:
That is true, innerHTML on tbody elements is readOnly in IE

The property is read/write for all
  objects except the following, for
  which it is read-only: COL, COLGROUP,
  FRAMESET, HEAD, HTML, STYLE, TABLE,
  TBODY, TFOOT, THEAD, TITLE, TR.

source: http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx

You can do something like this to work around it:

```<code>function setTBodyInnerHTML(tbody, html) {
  var temp = tbody.ownerDocument.createElement('div');
  temp.innerHTML = '<table>' + html + '</table>';

  tbody.parentNode.replaceChild(temp.firstChild.firstChild, tbody);
}
</code>```

Basically it creates a temporary node into which you inject a full table. Then it replaces the tbody with the tbody from the injected table. If it proves to be slow, you could make it faster by caching temp instead of creating it each time.

Title: Can't set innerHTML on tbody in IE

Body:
I have a table like this:

        a
        b

        data 1
        data 2
        data 3
        data 4

and a method returns me the following after an ajax request:

    data 1 new
    data 2 new
    data 3 new
    data 4 new

I want to change the innerHTML like

document.getElementById('replaceMe').innerHTML = data.responseText;

However, it seems that IE can't set innerHTML on
. Can anyone help me with a simple workaround for this issue?

Body:
That is true, innerHTML on tbody elements is readOnly in IE

The property is read/write for all
  objects except the following, for
  which it is read-only: COL, COLGROUP,
  FRAMESET, HEAD, HTML, STYLE, TABLE,
  TBODY, TFOOT, THEAD, TITLE, TR.

source: http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx

You can do something like this to work around it:

function setTBodyInnerHTML(tbody, html) {
  var temp = tbody.ownerDocument.createElement('div');
  temp.innerHTML = '<table>' + html + '</table>';

  tbody.parentNode.replaceChild(temp.firstChild.firstChild, tbody);
}

Basically it creates a temporary node into which you inject a full table. Then it replaces the tbody with the tbody from the injected table. If it proves to be slow, you could make it faster by caching temp instead of creating it each time.


问:
Is there a universal config file for .Net Standard 2.0 Class Library?
I have a Class Library that I'm converting to a .Net Standard 2 class library in order to also use in ASP.Net Core 2.0 projects.

The library has always read from a config file items such as SMTP settings, connection strings etc.

In Web Projects it finds these values in web.config.

In Console/WinForms it finds these values in app.config.

Is there an equivalent config file for .Net Core 2.0 projects that "just works" like the previous examples?

I assume the answer is no, but looking for best way to handle this given the library is used across the organization, so maintaining backwards compatibility is important.

答:
Turns out System.Configuration.ConfigurationManager was added back in .NETStandard 2.0.

Just pull it in from nuget and compile the .NETStandard 2.0 class library project.

Then, the library will work across projects using standard config files:

Net Core 2.0 projects use app.config

Web projects work from web.config

Console and Windows apps work with app.config


问:
How to display number sequences in rows and columns in Python 3?
I have a coding assignment to input row and column length, and create a power table.  THe example below is for 5 rows, 5 columns.

The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work.  It just shows a table of 1's, five by five.

```<code>rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))

x = 1
y = 1
z = 1

line = ""

while x <= cols :
    line = line + format(y**cols, "4d")
    x = x + 1
while z <= rows :
    print(line)
    z = z + 1
</code>```

答:
The basic problem is that you need to nest your loops.  Your second problem is that you never change y.  What you do at the moment is to compute the power sequence for 1 into five different lines -- and then you print that last line only five times.  Try two changes:

Compute a line, then print it immediately.  Then you go to the next line.

Use the correct variable.

After changes:

```<code>while z <= rows:
    while x <= cols:
        line = line + format(x**cols, "4d")   # Note the variable change
        x = x + 1
        print(line)

    z = z + 1
</code>```

Also, look up the for statement, as this will simplify things.  After that, look up list comprehension for even more compression.

Body:
I have a coding assignment to input row and column length, and create a power table.  THe example below is for 5 rows, 5 columns.

The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work.  It just shows a table of 1's, five by five.

rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))

x = 1
y = 1
z = 1

line = ""

while x <= cols :
    line = line + format(y**cols, "4d")
    x = x + 1
while z <= rows :
    print(line)
    z = z + 1

Body:
The basic problem is that you need to nest your loops.  Your second problem is that you never change y.  What you do at the moment is to compute the power sequence for 1 into five different lines -- and then you print that last line only five times.  Try two changes:

Compute a line, then print it immediately.  Then you go to the next line.

Use the correct variable.

After changes:

while z <= rows:
    while x <= cols:
        line = line + format(x**cols, "4d")   # Note the variable change
        x = x + 1
        print(line)

    z = z + 1

Also, look up the for statement, as this will simplify things.  After that, look up list comprehension for even more compression.


问:
improve locality and decrease Cache pollution in a medical image reconstruction implementation
I'm doing a research for my University related to an Image reconstruction algorithm for medical usage.

I'm stuck in something up to 3 weeks, I need to improve the performance of the following code:

```<code>for (lor=lor0[mypid]; lor <= lor1[mypid]; lor++)
{
  LOR_X = P.symmLOR[lor].x;
  LOR_Y = P.symmLOR[lor].y;
  LOR_XY = P.symmLOR[lor].xy;
  lor_z = P.symmLOR[lor].z;
  LOR_Z_X = P.symmLOR[lor_z].x;
  LOR_Z_Y = P.symmLOR[lor_z].y;
  LOR_Z_XY = P.symmLOR[lor_z].xy;

  s0 = P.a2r[lor];
  s1 = P.a2r[lor+1];

  for (s=s0; s < s1; s++)
  {
    pixel     = P.a2b[s];
    v         = P.a2p[s];

    b[lor]    += v * x[pixel];

    p          = P.symm_Xpixel[pixel];
    b[LOR_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel];
    b[LOR_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel];
    b[LOR_XY] += v * x[p];

    // do Z symmetry.
    pixel_z    = P.symm_Zpixel[pixel];
    b[lor_z]  += v * x[pixel_z];

    p          = P.symm_Xpixel[pixel_z];
    b[LOR_Z_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel_z];
    b[LOR_Z_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel_z];
    b[LOR_Z_XY] += v * x[p];

   }

}
</code>```

for anyone who wants to know, The code implements the MLEM forward function and all the variables are FLOAT.

After several tests, I had notice that the big delay was on this part of the code. (you know, the 90 - 10 rule).

Later, I used Papi (http://cl.cs.utk.edu/papi/) to measure L1D cache misses. As I thought, Papi confirm that the performance decreases due to higher amount of misses, particularly for the random access to b vector (huge in size).

Reading information on the Internet I just know two options to improve performance so far: improve data locality or decrease data pollution.

To do the first improvement, I'll try to change the code to be cache aware, just like was propossed by Ulrich Drepper on What every programmer should know about the memory (www.akkadia.org/drepper/cpumemory.pdf) A.1 Matrix multiplication.

I believe that blocking the SpMV (sparse matrix-vector Multiplication) will improve the performance.

On the other hand, every time the program tried to access to b vector, we had what is known as cache pollution.

Is there's a way to do a load a value from the b vector with SIMD instruction without using the Cache?

Also, it is possible to use a function like void _mm_stream_ps(float * p , __m128 a ) to store ONE float value on the vector b without polluting the Cache?

I can't use _mm_stream_ps because always store 4 floats but the access to the b vector is clearly random.

I'd hope to be clear in my dilemma.

More info: v is the column value of an Sparse Matrix store with CRS format. I realize that other optimization could be done if I tried to change CRS format to other, however, like I said before, I'd made several test for months and I know that the performance decrease is related to random access on vector b. from 400.000.000 L1D Misses I can go to 100~ Misses when I don't store in vector b.

Thanks.

答:
These are good answers, and I would ask why so much indexing? by index values that don't change much locally?

Also, it wouldn't kill you to do a few random pauses to see where it typically is.

ContentLicense: CC BY-SA 2.5

Body:
I'm doing a research for my University related to an Image reconstruction algorithm for medical usage.

I'm stuck in something up to 3 weeks, I need to improve the performance of the following code:

for (lor=lor0[mypid]; lor <= lor1[mypid]; lor++)
{
  LOR_X = P.symmLOR[lor].x;
  LOR_Y = P.symmLOR[lor].y;
  LOR_XY = P.symmLOR[lor].xy;
  lor_z = P.symmLOR[lor].z;
  LOR_Z_X = P.symmLOR[lor_z].x;
  LOR_Z_Y = P.symmLOR[lor_z].y;
  LOR_Z_XY = P.symmLOR[lor_z].xy;

  s0 = P.a2r[lor];
  s1 = P.a2r[lor+1];

  for (s=s0; s < s1; s++)
  {
    pixel     = P.a2b[s];
    v         = P.a2p[s];

    b[lor]    += v * x[pixel];

    p          = P.symm_Xpixel[pixel];
    b[LOR_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel];
    b[LOR_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel];
    b[LOR_XY] += v * x[p];

    // do Z symmetry.
    pixel_z    = P.symm_Zpixel[pixel];
    b[lor_z]  += v * x[pixel_z];

    p          = P.symm_Xpixel[pixel_z];
    b[LOR_Z_X]  += v * x[p];

    p          = P.symm_Ypixel[pixel_z];
    b[LOR_Z_Y]  += v * x[p];

    p          = P.symm_XYpixel[pixel_z];
    b[LOR_Z_XY] += v * x[p];

   }

}

for anyone who wants to know, The code implements the MLEM forward function and all the variables are FLOAT.

After several tests, I had notice that the big delay was on this part of the code. (you know, the 90 - 10 rule).

Later, I used Papi (http://cl.cs.utk.edu/papi/) to measure L1D cache misses. As I thought, Papi confirm that the performance decreases due to higher amount of misses, particularly for the random access to b vector (huge in size).

Reading information on the Internet I just know two options to improve performance so far: improve data locality or decrease data pollution.

To do the first improvement, I'll try to change the code to be cache aware, just like was propossed by Ulrich Drepper on What every programmer should know about the memory (www.akkadia.org/drepper/cpumemory.pdf) A.1 Matrix multiplication.

I believe that blocking the SpMV (sparse matrix-vector Multiplication) will improve the performance.

On the other hand, every time the program tried to access to b vector, we had what is known as cache pollution.

Is there's a way to do a load a value from the b vector with SIMD instruction without using the Cache?

Also, it is possible to use a function like void _mm_stream_ps(float * p , __m128 a ) to store ONE float value on the vector b without polluting the Cache?

I can't use _mm_stream_ps because always store 4 floats but the access to the b vector is clearly random.

I'd hope to be clear in my dilemma.

More info: v is the column value of an Sparse Matrix store with CRS format. I realize that other optimization could be done if I tried to change CRS format to other, however, like I said before, I'd made several test for months and I know that the performance decrease is related to random access on vector b. from 400.000.000 L1D Misses I can go to 100~ Misses when I don't store in vector b.

Thanks.


问:
How to apply custom logic when mapping fields using modelmapper
How to apply custom logic to field mapping? In this example I want to calculate the int age out of an LocalDate birthdate.

```<code>public class ModelMapperConfigTest {

    @Data
    public static class Person {
        private LocalDate birthdate;
    }

    @Data
    public static class PersonDto {
        private long age;
    }

    // Test data
    LocalDate birthdate = LocalDate.of(1985, 10, 5);
    long age = 32;
    Clock clock = Clock.fixed(birthdate.plusYears(age).atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault());

    @Test
    public void should_calc_age() {

        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        // TODO: How to configure the Mapper so that calcBirthdate is used?

        // test that all fields are mapped
        modelMapper.validate();

        // test that the age is calculated
        Person person = new Person();
        person.setBirthdate(birthdate);
        PersonDto personDto = modelMapper.map(person, PersonDto.class);
        assertTrue(personDto.age == age);
    }

    // This method should be used for mapping. In real, this could be a service call
    private long calcBirthdate(LocalDate birthdate) {
        return YEARS.between(birthdate, LocalDate.now(clock));
    }
}
</code>```

答:
You can use Converters for this. In your case register a Converter<LocalDate, Long> for the mapping from birthdate to age.

This can be done with lambdas like this:

```<code>@Test
public void should_calc_age() {

    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

    modelMapper.createTypeMap(Person.class, PersonDto.class)
            .addMappings(mapper ->
                    mapper
                            // This is your converter.
                            // Here you have access to getSource() (birthdate).
                            .using(ctx -> calcBirthdate((LocalDate) ctx.getSource()))

                            // Now define the mapping birthdate to age
                            .map(Person::getBirthdate, PersonDto::setAge));

    // test that all fields are mapped
    modelMapper.validate();

    // test that the age is calculated
    Person person = new Person();
    person.setBirthdate(birthdate);
    PersonDto personDto = modelMapper.map(person, PersonDto.class);
    assertTrue(personDto.age == age);
}
</code>```

Body:
How to apply custom logic to field mapping? In this example I want to calculate the int age out of an LocalDate birthdate.

public class ModelMapperConfigTest {

    @Data
    public static class Person {
        private LocalDate birthdate;
    }

    @Data
    public static class PersonDto {
        private long age;
    }

    // Test data
    LocalDate birthdate = LocalDate.of(1985, 10, 5);
    long age = 32;
    Clock clock = Clock.fixed(birthdate.plusYears(age).atStartOfDay(ZoneId.systemDefault()).toInstant(), ZoneId.systemDefault());

    @Test
    public void should_calc_age() {

        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        // TODO: How to configure the Mapper so that calcBirthdate is used?

        // test that all fields are mapped
        modelMapper.validate();

        // test that the age is calculated
        Person person = new Person();
        person.setBirthdate(birthdate);
        PersonDto personDto = modelMapper.map(person, PersonDto.class);
        assertTrue(personDto.age == age);
    }

    // This method should be used for mapping. In real, this could be a service call
    private long calcBirthdate(LocalDate birthdate) {
        return YEARS.between(birthdate, LocalDate.now(clock));
    }
}

Body:
You can use Converters for this. In your case register a Converter<LocalDate, Long> for the mapping from birthdate to age.

This can be done with lambdas like this:

@Test
public void should_calc_age() {

    ModelMapper modelMapper = new ModelMapper();
    modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

    modelMapper.createTypeMap(Person.class, PersonDto.class)
            .addMappings(mapper ->
                    mapper
                            // This is your converter.
                            // Here you have access to getSource() (birthdate).
                            .using(ctx -> calcBirthdate((LocalDate) ctx.getSource()))

                            // Now define the mapping birthdate to age
                            .map(Person::getBirthdate, PersonDto::setAge));

    // test that all fields are mapped
    modelMapper.validate();

    // test that the age is calculated
    Person person = new Person();
    person.setBirthdate(birthdate);
    PersonDto personDto = modelMapper.map(person, PersonDto.class);
    assertTrue(personDto.age == age);
}


问:
Why Firefox doesn't get a <form> $_GET variable while Safari does it?
I am sending the content of a an input through a form, from page1 to page2, using a button with action="page2.php":

```<code><form method="get" id="chatform" action="page2.php">
    <input type="text" style="margin-bottom:20px;" class="form-control" id="recipient" name="recipient" placeholder="username" value="">
</form>
</code>```

the button is outside the form but it contains the name of it:

```<code><button type="submit" form="chatform" id="b9" style="font-size: 12px !important;" name="b9" class="buttonmenu toggleForms btn btn-secondary btn-block" style="float:left;">Chat</button>
</code>```

ALSO I am loadind the input with javascript:

```<code>$(".buttonmenu").click(function(){
$('#recipient').val("hellooooo"); }
</code>```

the problem is that everything works fine for Safari but in Firefox I don't get anything in the variable $_GET['recipient'] and I don't understand why.

In page1 there are just forms in series, no nested froms. In Safari everything is working perfectly in page2: I get the name of the 'recipient' variable in the URL and the content, in firefox I get just the name of the 'recipient' variable in the URL but the variable is empty
It seems like Firefox can't get the CONTENT of $_GET['recipient'] from the server, or run the php action IGNORING the javascript.

Any idea?

答:
SOLVED

Firefox needs the 'event' object as function's param.

This is the line:

```<code>$(".buttomenu").click(function(event) {.....
</code>```

Body:
I am sending the content of a an input through a form, from page1 to page2, using a button with action="page2.php":

<form method="get" id="chatform" action="page2.php">
    <input type="text" style="margin-bottom:20px;" class="form-control" id="recipient" name="recipient" placeholder="username" value="">
</form>

the button is outside the form but it contains the name of it:

<button type="submit" form="chatform" id="b9" style="font-size: 12px !important;" name="b9" class="buttonmenu toggleForms btn btn-secondary btn-block" style="float:left;">Chat</button>

ALSO I am loadind the input with javascript:

$(".buttonmenu").click(function(){
$('#recipient').val("hellooooo"); }

the problem is that everything works fine for Safari but in Firefox I don't get anything in the variable $_GET['recipient'] and I don't understand why.

In page1 there are just forms in series, no nested froms. In Safari everything is working perfectly in page2: I get the name of the 'recipient' variable in the URL and the content, in firefox I get just the name of the 'recipient' variable in the URL but the variable is empty
It seems like Firefox can't get the CONTENT of $_GET['recipient'] from the server, or run the php action IGNORING the javascript.

Any idea?

Body:
SOLVED

Firefox needs the 'event' object as function's param.

This is the line:

$(".buttomenu").click(function(event) {.....


问:
Collection was modified; enumeration operation may not execute #10897
I see there are already a lot of questions about this error. I've read through all of them and pretty much every single one is because they are modifying a collection while enumerating over it, which is pretty obvious. However, my case is different.

So here is the exception in question. Note the last line I've modified.

```<code>Source    mscorlib
Method    MoveNext
Message   Collection was modified; enumeration operation may not execute.
Exception System.InvalidOperationException
Stack
   at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
   at System.Windows.Forms.Application.ExitInternal()
   at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
   at System.Windows.Forms.Control.WndProcException(Exception e)
   at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.RunDialog(Form form)
   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
   at System.Windows.Forms.Form.ShowDialog()
   at RandomEventWithinMyApp()
</code>```

I personally have never seen the error or been able to reproduce it. I've only ever seen this error report come in from time to time from users and it has always eluded me.

As you can see, the error is happening within the System.Windows.Forms.Form.ShowDialog, so something is going wrong when trying to open a form. Obviously I don't have a function called RandomEventWithinMyApp, instead the error literally occurs at random in a control event, usually a button click for example as that normally triggers the opening of some form by the user.

Now if the error consistently happened when the user clicks the same button to open the same particular form, then it would be a lot easier to work out. The problem is that the event that triggers the error is random, it can be any event (such as a button click) that opens a form anywhere in the app. The form that is being opened when the error occurs is also random. So I have nothing to go by.

It almost feels like there is something else going wrong within the .Net form loading code that I can't see. Perhaps something that manages the collection of open forms or something... no idea, just wild guesses at this point. Does anyone have any ideas of where I should start investigating?

答:
I would check any form closing events or even form closed events. You can browse the .Net source on MSDN and see that the in Application.ExitIntenal it is iterating over an arraylist of forms to raise FormClosing events. Something may be going on in your form closing events that is modifying that arraylist that is being iterated. </p>

```<code>                // Raise the FormClosing and FormClosed events for each open form
                if (forms != null) {
                    foreach (Form f in OpenFormsInternal) {
                        if (f.RaiseFormClosingOnAppExit()) {
                            cancelExit = true;
                            break; // quit the loop as soon as one form refuses to close
                        }
                    }
                }
</code>```

Body:
I see there are already a lot of questions about this error. I've read through all of them and pretty much every single one is because they are modifying a collection while enumerating over it, which is pretty obvious. However, my case is different.

So here is the exception in question. Note the last line I've modified.

Source    mscorlib
Method    MoveNext
Message   Collection was modified; enumeration operation may not execute.
Exception System.InvalidOperationException
Stack
   at System.Collections.ArrayList.ArrayListEnumeratorSimple.MoveNext()
   at System.Windows.Forms.Application.ExitInternal()
   at System.Windows.Forms.Application.ThreadContext.OnThreadException(Exception t)
   at System.Windows.Forms.Control.WndProcException(Exception e)
   at System.Windows.Forms.Control.ControlNativeWindow.OnThreadException(Exception e)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)
   at System.Windows.Forms.UnsafeNativeMethods.DispatchMessageW(MSG& msg)
   at System.Windows.Forms.Application.ComponentManager.System.Windows.Forms.UnsafeNativeMethods.IMsoComponentManager.FPushMessageLoop(IntPtr dwComponentID, Int32 reason, Int32 pvLoopData)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoopInner(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.ThreadContext.RunMessageLoop(Int32 reason, ApplicationContext context)
   at System.Windows.Forms.Application.RunDialog(Form form)
   at System.Windows.Forms.Form.ShowDialog(IWin32Window owner)
   at System.Windows.Forms.Form.ShowDialog()
   at RandomEventWithinMyApp()

I personally have never seen the error or been able to reproduce it. I've only ever seen this error report come in from time to time from users and it has always eluded me.

As you can see, the error is happening within the System.Windows.Forms.Form.ShowDialog, so something is going wrong when trying to open a form. Obviously I don't have a function called RandomEventWithinMyApp, instead the error literally occurs at random in a control event, usually a button click for example as that normally triggers the opening of some form by the user.

Now if the error consistently happened when the user clicks the same button to open the same particular form, then it would be a lot easier to work out. The problem is that the event that triggers the error is random, it can be any event (such as a button click) that opens a form anywhere in the app. The form that is being opened when the error occurs is also random. So I have nothing to go by.

It almost feels like there is something else going wrong within the .Net form loading code that I can't see. Perhaps something that manages the collection of open forms or something... no idea, just wild guesses at this point. Does anyone have any ideas of where I should start investigating?

Body:
I would check any form closing events or even form closed events. You can browse the .Net source on MSDN and see that the in Application.ExitIntenal it is iterating over an arraylist of forms to raise FormClosing events. Something may be going on in your form closing events that is modifying that arraylist that is being iterated.

                // Raise the FormClosing and FormClosed events for each open form
                if (forms != null) {
                    foreach (Form f in OpenFormsInternal) {
                        if (f.RaiseFormClosingOnAppExit()) {
                            cancelExit = true;
                            break; // quit the loop as soon as one form refuses to close
                        }
                    }
                }


问:
what is wrong with trailing white space in typeScript?
I know that this is due to linting but I'm just curious what is wrong with having trailing spaces?

I will be turning this feature of with tslint.json but before I do so, I'd like to make sure I'm not shooting myself in the foot.

As you know, VS-Code does show wavy underlines when a trailing space is detected. I prefer not to.
My justification is ... at the time of transpiling or for-sure in deployment, those trailing spaces are taken down anyway, so what's the worry?

答:
This is a linting guidance but I'm just curious what is wrong with having trailing spaces?

They are useless stuff that causes git diffing / git logs when there is actually no significant change in the file.

At the time of transpiling, aren't those trailing spaces are taken down anyway?

Yes.

More

You are free to commit empty spaces if this is what you want. Linting is just good guidance.


问:
ASP.NET: Show/hide radio button list items programmatically
I need to know how to do what the following would intuitively do if it worked (imagine useGreek() and useNato() to be states that would be consulted once per load or postback):

```<code><asp:radioButtonList id="rbl" runat="server" autoPostBack="true">
    <asp:listItem value="alpha" text="Alpha" />
    <% if(useGreek()) { %>
        <asp:listItem value="beta" text="Beta" />
        <asp:listItem value="gamma" text="Gamma" />
    <% } else if(useNato()) { %>
        <asp:listItem value="bravo" text="Bravo" />
        <asp:listItem value="charlie" text="Charlie" />
    <% } %>
    <asp:listItem value="delta" text="Delta" />
</asp:radioButtonList>
</code>```

(It will already be apparent that I'm not usually asked to write for IIS.)

Anyway, ASP.NET doesn't like code interleaved with list items, so this is a no-go. I imagine that there's some C#-based way to handle this somehow, but I've been trying for a few days now with no luck.

Also, just to be clear, I'm seeking a server-side solution here. I'm well-versed with jQuery, but we're trying to keep most of the processing of this particular form off the client.

Thanks, and party on.

答:
No C# but i think you understand what i mean:

in codebehind's page_load:

```<code>If Not IsPostBack Then
    Me.rbl.Items.Add(New ListItem("Alpha", "alpha"))
    If (useGreek()) Then
        Me.rbl.Items.Add(New ListItem("Beta", "beta"))
        Me.rbl.Items.Add(New ListItem("Gamma", "gamma"))
    ElseIf (useNato()) Then
        Me.rbl.Items.Add(New ListItem("Bravo", "bravo"))
        Me.rbl.Items.Add(New ListItem("Charlie", "charlie"))
    End If
    Me.rbl.Items.Add(New ListItem("Delta", "delta"))
End If
</code>```

If you have to check on every postback because the state could change fast, you could add an Me.rbl.Items.Clear() to the top and remove the PostBack-check.

EDIT:
C#

```<code>if (!IsPostBack) {
    this.rbl.Items.Add(new ListItem("Alpha", "alpha"));
    if ((useGreek())) {
        this.rbl.Items.Add(new ListItem("Beta", "beta"));
        this.rbl.Items.Add(new ListItem("Gamma", "gamma"));
    } else if ((useNato())) {
        this.rbl.Items.Add(new ListItem("Bravo", "bravo"));
        this.rbl.Items.Add(new ListItem("Charlie", "charlie"));
    }
    this.rbl.Items.Add(new ListItem("Delta", "delta"));
}
</code>```

Because i'm not sure if you already know the codebehind model, have a look at following link:
MSDN: Codebehind and Compilation in ASP.NET 2.0

Body:
I need to know how to do what the following would intuitively do if it worked (imagine useGreek() and useNato() to be states that would be consulted once per load or postback):

<asp:radioButtonList id="rbl" runat="server" autoPostBack="true">
    <asp:listItem value="alpha" text="Alpha" />
    <% if(useGreek()) { %>
        <asp:listItem value="beta" text="Beta" />
        <asp:listItem value="gamma" text="Gamma" />
    <% } else if(useNato()) { %>
        <asp:listItem value="bravo" text="Bravo" />
        <asp:listItem value="charlie" text="Charlie" />
    <% } %>
    <asp:listItem value="delta" text="Delta" />
</asp:radioButtonList>

(It will already be apparent that I'm not usually asked to write for IIS.)

Anyway, ASP.NET doesn't like code interleaved with list items, so this is a no-go. I imagine that there's some C#-based way to handle this somehow, but I've been trying for a few days now with no luck.

Also, just to be clear, I'm seeking a server-side solution here. I'm well-versed with jQuery, but we're trying to keep most of the processing of this particular form off the client.

Thanks, and party on.

Body:
No C# but i think you understand what i mean:

in codebehind's page_load:

If Not IsPostBack Then
    Me.rbl.Items.Add(New ListItem("Alpha", "alpha"))
    If (useGreek()) Then
        Me.rbl.Items.Add(New ListItem("Beta", "beta"))
        Me.rbl.Items.Add(New ListItem("Gamma", "gamma"))
    ElseIf (useNato()) Then
        Me.rbl.Items.Add(New ListItem("Bravo", "bravo"))
        Me.rbl.Items.Add(New ListItem("Charlie", "charlie"))
    End If
    Me.rbl.Items.Add(New ListItem("Delta", "delta"))
End If

If you have to check on every postback because the state could change fast, you could add an Me.rbl.Items.Clear() to the top and remove the PostBack-check.

EDIT:
C#

if (!IsPostBack) {
    this.rbl.Items.Add(new ListItem("Alpha", "alpha"));
    if ((useGreek())) {
        this.rbl.Items.Add(new ListItem("Beta", "beta"));
        this.rbl.Items.Add(new ListItem("Gamma", "gamma"));
    } else if ((useNato())) {
        this.rbl.Items.Add(new ListItem("Bravo", "bravo"));
        this.rbl.Items.Add(new ListItem("Charlie", "charlie"));
    }
    this.rbl.Items.Add(new ListItem("Delta", "delta"));
}

Because i'm not sure if you already know the codebehind model, have a look at following link:
MSDN: Codebehind and Compilation in ASP.NET 2.0


问:
C - accessing index in array of chars gives strange results including lot of other elements
So given this:

```<code>int main ()
{

  char names[23][5] = {
    "BkCan",
    "BkChg",
    "BkDel",
    "BkExc",
    "BkPrg",
    "BkRep",
    "Halt",
    "Order",
    "Price",
    "Trade",
    "UpdPr",
    "lBkCa",
    "lBkCh",
    "lBkDe",
    "lBkEx",
    "lBkPr",
    "lBkRe",
    "lHalt",
    "Orde1",
    "lPric",
    "lTrad",
    "lUpdP",
    "lOrde",
};

  printf("%s\n", names[4]);

  return 0;
}
</code>```

I get the result BkPrgBkRepHalt

which is a concatenation of multiple elements (5,6,7)

what is going on?

Here's a usable online repl/example:

https://repl.it/repls/UnrealisticDefiantPoodle

答:
You need to allocate at least 6 characters for each string, as they each need the null-terminator \0 ("BkCan" is effectively "BkCan\0").

At the moment, printf is continuing to read from the pointer you give it until it reaches a null-terminator (after a 4-character string like "Halt", for example, or one past the end of the array (undefined behaviour)), hence the "concatenation" effect.

Just doing:

```<code>char names[23][6] = ...
</code>```

should be enough.

Body:
So given this:

int main ()
{

  char names[23][5] = {
    "BkCan",
    "BkChg",
    "BkDel",
    "BkExc",
    "BkPrg",
    "BkRep",
    "Halt",
    "Order",
    "Price",
    "Trade",
    "UpdPr",
    "lBkCa",
    "lBkCh",
    "lBkDe",
    "lBkEx",
    "lBkPr",
    "lBkRe",
    "lHalt",
    "Orde1",
    "lPric",
    "lTrad",
    "lUpdP",
    "lOrde",
};

  printf("%s\n", names[4]);

  return 0;
}

I get the result BkPrgBkRepHalt

which is a concatenation of multiple elements (5,6,7)

what is going on?

Here's a usable online repl/example:

https://repl.it/repls/UnrealisticDefiantPoodle

Body:
You need to allocate at least 6 characters for each string, as they each need the null-terminator \0 ("BkCan" is effectively "BkCan\0").

At the moment, printf is continuing to read from the pointer you give it until it reaches a null-terminator (after a 4-character string like "Halt", for example, or one past the end of the array (undefined behaviour)), hence the "concatenation" effect.

Just doing:

char names[23][6] = ...

should be enough.


问:
iOS paint features to my app
I'm trying to add a drawing feature to my app. I have two UIImageViews... the bottom one contains a picture, let's say a photograph, and the second one on top of it is the one I want to paint on.

```<code>- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
    UIView *tappedView = [gesture.view hitTest:[gesture locationInView:gesture.view] withEvent:nil];

    CGPoint currentPoint = [gesture locationInView:_paintOverlay];

    UIGraphicsBeginImageContext(_paintOverlay.frame.size);
    [_paintOverlay.image drawInRect:CGRectMake(0, 0, _paintOverlay.frame.size.width, _paintOverlay.frame.size.height)];
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), 5, 5);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

    CGContextStrokePath(UIGraphicsGetCurrentContext());
   _paintOverlay.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSLog(@"Touch event on view: %@",[tappedView class]);
}
</code>```

This simply isn't working. I can't find any tutorials to help me with this, the one I found (where I derived this code from) wasn't so understandable.

答:
Your code, such as it is, works well enough. I didn't have an image so I omitted that, but by supplying values for brush and so forth I found that tapping on the view made a line appear:

It's a terrible way to paint (paint by tapping? only making lines coming from a single point???), but it does make lines.

However, I naturally configured my tap gesture recognizer and views correctly. You don't say what you did, so who knows? Did you hook the tap gesture recognizer to its action handler? Did you add it to the view? Did you remember to turn on the view's userInteractionEnabled? Did you tap as your gesture? A lot of things can go wrong; you need to debug, see what's happening, and tell us more about it.

Title: iOS paint features to my app

Body:
I'm trying to add a drawing feature to my app. I have two UIImageViews... the bottom one contains a picture, let's say a photograph, and the second one on top of it is the one I want to paint on.

- (void)singleTapGestureCaptured:(UITapGestureRecognizer *)gesture
{
    UIView *tappedView = [gesture.view hitTest:[gesture locationInView:gesture.view] withEvent:nil];

    CGPoint currentPoint = [gesture locationInView:_paintOverlay];

    UIGraphicsBeginImageContext(_paintOverlay.frame.size);
    [_paintOverlay.image drawInRect:CGRectMake(0, 0, _paintOverlay.frame.size.width, _paintOverlay.frame.size.height)];
    CGContextMoveToPoint(UIGraphicsGetCurrentContext(), 5, 5);
    CGContextAddLineToPoint(UIGraphicsGetCurrentContext(), currentPoint.x, currentPoint.y);
    CGContextSetLineCap(UIGraphicsGetCurrentContext(), kCGLineCapRound);
    CGContextSetLineWidth(UIGraphicsGetCurrentContext(), brush );
    CGContextSetRGBStrokeColor(UIGraphicsGetCurrentContext(), red, green, blue, 1.0);
    CGContextSetBlendMode(UIGraphicsGetCurrentContext(),kCGBlendModeNormal);

    CGContextStrokePath(UIGraphicsGetCurrentContext());
   _paintOverlay.image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();

    NSLog(@"Touch event on view: %@",[tappedView class]);
}

This simply isn't working. I can't find any tutorials to help me with this, the one I found (where I derived this code from) wasn't so understandable.


问:
Postgresql in Pgadmin iii (Function IF/ELSE)
I am trying to create a SELECT FROM inside an IF statement inside a function. Here is what i have so far

```<code>CREATE OR REPLACE FUNCTION fn_check_marriage(partner_id INTEGER)
    RETURNS VARCHAR(10) AS
$$
DECLARE
    result text;

BEGIN
    result := ''

    IF EXISTS (SELECT partner_id_1 FROM marriages WHERE divorce_date IS NULL) THEN

    result := 'True';

    ELSE

    result := 'False';

    END IF;

RETURN result;

END;
$$
LANGUAGE 'plpgsql'
</code>```

But it keeps on giving me errors, most recently "error at or near IF".
Any thoughts on how to make this work if at all possible? Thanks in advance

答:
Do a perform then check found or not:</p>

```<code>PERFORM partner_id_1 FROM marriages WHERE divorce_date IS NULL;
IF FOUND THEN
  result := 'True';
ELSE
  result := 'False';
END IF;
</code>```

Body:
I am trying to create a SELECT FROM inside an IF statement inside a function. Here is what i have so far

CREATE OR REPLACE FUNCTION fn_check_marriage(partner_id INTEGER)
    RETURNS VARCHAR(10) AS
$$
DECLARE
    result text;

BEGIN
    result := ''

    IF EXISTS (SELECT partner_id_1 FROM marriages WHERE divorce_date IS NULL) THEN

    result := 'True';

    ELSE

    result := 'False';

    END IF;

RETURN result;

END;
$$
LANGUAGE 'plpgsql'

But it keeps on giving me errors, most recently "error at or near IF".
Any thoughts on how to make this work if at all possible? Thanks in advance

Body:
Do a perform then check found or not:

PERFORM partner_id_1 FROM marriages WHERE divorce_date IS NULL;
IF FOUND THEN
  result := 'True';
ELSE
  result := 'False';
END IF;


问:
Mercurial: block commits if subrepos are dirty?
Is there any simple way to prevent commits to a repository if it has dirty subrepos?

It's really annoying when a subrepo is accidentally committed along with a parent repository.

答:
I don't know where your line for simple lands but you could do a hook like this:

```<code>for subrepo in $(find $(hg root) -type d -name .hg) ; do
  if [ "$(hg --repository ${subrepo$$.hg} status -mard)" != "" ] ; then
    echo Uncommitted subrepo changes in ${subrepo%%.hg}
    exit 1
  fi
done
</code>```

Save that in something like ~/bin/dirtysubrepos and then add this to your ~/.hgrc:

```<code>[hooks]
precommit.dirtysuprepos = ~/bin/dirtysubrepos
</code>```

Disclaimer: This code has never been typed anywhere except this textbox, so it almost certainly has syntax bugs.

Body:
I don't know where your line for simple lands but you could do a hook like this:

for subrepo in $(find $(hg root) -type d -name .hg) ; do
  if [ "$(hg --repository ${subrepo$$.hg} status -mard)" != "" ] ; then
    echo Uncommitted subrepo changes in ${subrepo%%.hg}
    exit 1
  fi
done

Save that in something like ~/bin/dirtysubrepos and then add this to your ~/.hgrc:

[hooks]
precommit.dirtysuprepos = ~/bin/dirtysubrepos

Disclaimer: This code has never been typed anywhere except this textbox, so it almost certainly has syntax bugs.


问:
How to pass traceIds in Hystrix Observables?
I have multiple services, some of which use Hystrix's HystrixObservableCommand to call other services and others use HystrixCommand. How do I pass on traceIds from the calling service to the Observables in HystrixObservableCommand and also have them be passed on if the fallback is called?

All services are using grpc-java.

Sample code that I have:

```<code>WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
        String messageFromWorldService = "";
        String idFromWorldService = "";
        try {

            Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
            messageFromWorldService = greeterReply.getMessage();
            idFromWorldService = greeterReply.getId();
            logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);
        } catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
            logger.warn("Exception when calling WorldService\n" +  e);
        }
</code>```

WorldCommand.java

```<code>public class WorldCommand extends HystrixObservableCommand<Greeter.GreeterReply> {

    private static final Logger logger = LoggerFactory.getLogger(WorldCommand.class.getName());

    private final Greeter.GreeterRequest greeterRequest;
    private final WorldServiceGrpc.WorldServiceStub worldServiceStub;

    public WorldCommand(Greeter.GreeterRequest greeterRequest, WorldServiceGrpc.WorldServiceStub worldServiceStub) {
        super(HystrixCommandGroupKey.Factory.asKey("WorldService"));
        this.greeterRequest = greeterRequest;
        this.worldServiceStub = worldServiceStub;
    }

    @Override
    protected Observable<Greeter.GreeterReply> construct() {
        Context context = Context.current();
        return Observable.create(new Observable.OnSubscribe<Greeter.GreeterReply>() {
            @Override
            public void call(Subscriber<? super Greeter.GreeterReply> observer) {
                logger.info("In WorldCommand");
                if (!observer.isUnsubscribed()) {
                    //pass on the context, if you want only certain headers to pass on then create a new Context and attach it.
                    context.attach();
                    logger.info("In WorldCommand after attach");
                    worldServiceStub.greetWithHelloOrWorld(greeterRequest, new StreamObserver<Greeter.GreeterReply>() {
                        @Override
                        public void onNext(Greeter.GreeterReply greeterReply) {
                            logger.info("Response from WorldService  -- {}, id = {}", greeterReply.getMessage(), greeterReply.getId());
                            observer.onNext(greeterReply);
                            observer.onCompleted();
                        }

                        @Override
                        public void onError(Throwable t) {
                            logger.info("Exception from WorldService  -- {}", t);
                        }

                        @Override
                        public void onCompleted() {

                        }
                    });
                }
            }
        } ).subscribeOn(Schedulers.io());
    }

    @Override
    protected Observable<Greeter.GreeterReply> resumeWithFallback() {
        logger.info("Response from fallback");
        Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("teammate").setId("-1").build();
        return Observable.just(greeterReply);
    }
</code>```

I am using Zipkin grpc tracing and MDCCurrentTraceContext to print the traceId and spanId in the logs.

Both the log entries in the WorldCommand do not print out the trace and span ids, they are called on RxIoScheduler thread.

EDIT

Added ConcurrencyStrategy as suggested by Mike.

```<code>public class CustomHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {

    private static final Logger log = LoggerFactory.getLogger(CustomHystrixConcurrencyStrategy.class);

    public <T> Callable<T> wrapCallable(Callable<T> callable){
        log.info("In CustomHystrixConcurrencyStrategy: callable="+ callable.toString());
        return new ContextCallable<>(callable);
    }
}
</code>```

HelloService calls two services World and Team. The WorldCommand is a HystrixObservableCommand, the TeamCommand is a HystrixCommand.

```<code>logger.info("In the HelloService:greetWithHelloWorld");
Greeter.GreeterRequest greeterRequest = Greeter.GreeterRequest.newBuilder().setId(request.getId()).build();

//Call WorldService
ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
//Async stub instead of blockingStub
WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);

WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
String messageFromWorldService = "";
String idFromWorldService = "";
try {

    Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
    messageFromWorldService = greeterReply.getMessage();
    idFromWorldService = greeterReply.getId();
    logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
    logger.warn("Exception when calling WorldService\n" +  e);
}

//Call TeamService
ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);

String messageFromTeamService = "";
String idFromTeamService = "";
try {
    Greeter.GreeterReply greeterReply = teamCommand.construct().toBlocking().toFuture().get();
    messageFromTeamService = greeterReply.getMessage();
    idFromTeamService = greeterReply.getId();
    logger.info("Response from TeamService  -- {}, id = {}", messageFromTeamService, idFromTeamService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
    logger.warn("Exception when calling TeamService\n" +  e);
}

assert(idFromWorldService.equals(idFromTeamService));
Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
responseObserver.onNext(greeterReply);
responseObserver.onCompleted();
</code>```

PreservableContext class

```<code>public class PreservableContexts {

    //private final TraceContext traceContext;
    private static final Logger logger = LoggerFactory.getLogger(PreservableContexts.class.getName());

    public PreservableContexts() {
        logger.info("Creating new PreservableContexts");
        //this.traceContext = TraceContextHolder.getContext();
    }

    public void set() {
       // if (traceContext != null) {
            //TraceContextHolder.setContext(traceContext);
       // }
    }

    public void clear() {
        //TraceContextHolder.clearContext();
    }
</code>```

The log in PreservableContexts and CustomHystrixConcurrencyStrategy never get printed. I am registering the startegy when I start the HelloServer.

```<code>HystrixConcurrencyStrategy strategy = new CustomHystrixConcurrencyStrategy();
        HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
        context = HystrixRequestContext.initializeContext();
</code>```

EDIT 2

Updated how the Observables are set up:

```<code>    ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
    //Async stub instead of blockingStub
    WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);
    WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);

    //Call TeamService
    ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
    TeamServiceGrpc.TeamServiceStub teamServiceStub = TeamServiceGrpc.newStub(teamChannel);
    //TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
    TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);

    try {
        rx.Observable<Greeter.GreeterReply> worldReplyObservable = worldCommand.observe().subscribeOn(Schedulers.computation());
        rx.Observable<Greeter.GreeterReply> teamReplyObservable = teamCommand.observe().subscribeOn(Schedulers.computation());
        Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
            @Override
            public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
                String messageFromWorldService = worldReply.getMessage();
                String idFromWorldService = worldReply.getId();
                logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);

                String messageFromTeamService = teamReply.getMessage();
                String idFromTeamService = teamReply.getId();
                logger.info("Response from TeamService  -- {}, id = {}", messageFromTeamService, idFromTeamService);

                assert(idFromWorldService.equals(idFromTeamService));
                Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
                logger.info("Final response=" + greeterReply.getMessage());
                responseObserver.onNext(greeterReply);
                responseObserver.onCompleted();
                return null;
            }
        });
    } catch (StatusRuntimeException e) {
        logger.warn("Exception when calling WorldService and/or TeamService\n" +  e);
    }
</code>```

I have a weird problem now, the calls to TeamCommand and WorldCommand doesn't complete as in this code is never executed:

```<code>Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
                @Override
                public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
                    String messageFromWorldService = worldReply.getMessage();
</code>```

Also, if there is a fallback, the hystrix-timer threads doesn't have the MDC anymore.

答: I do not have much knowledge with hysterix, but if you are trying to pass some contextual info like trace IDs around, then io.grpc.Context is the correct class to use. You would need to call context.withValue to create a new context with the traceID. In the places where you want the data, you need to attach the context. Also be sure to detach the context when done, which I do not see happening in your snippet.

Body:
I have multiple services, some of which use Hystrix's HystrixObservableCommand to call other services and others use HystrixCommand. How do I pass on traceIds from the calling service to the Observables in HystrixObservableCommand and also have them be passed on if the fallback is called?

All services are using grpc-java.

Sample code that I have:

WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
        String messageFromWorldService = "";
        String idFromWorldService = "";
        try {

            Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
            messageFromWorldService = greeterReply.getMessage();
            idFromWorldService = greeterReply.getId();
            logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);
        } catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
            logger.warn("Exception when calling WorldService\n" +  e);
        }

WorldCommand.java

public class WorldCommand extends HystrixObservableCommand<Greeter.GreeterReply> {

    private static final Logger logger = LoggerFactory.getLogger(WorldCommand.class.getName());

    private final Greeter.GreeterRequest greeterRequest;
    private final WorldServiceGrpc.WorldServiceStub worldServiceStub;

    public WorldCommand(Greeter.GreeterRequest greeterRequest, WorldServiceGrpc.WorldServiceStub worldServiceStub) {
        super(HystrixCommandGroupKey.Factory.asKey("WorldService"));
        this.greeterRequest = greeterRequest;
        this.worldServiceStub = worldServiceStub;
    }

    @Override
    protected Observable<Greeter.GreeterReply> construct() {
        Context context = Context.current();
        return Observable.create(new Observable.OnSubscribe<Greeter.GreeterReply>() {
            @Override
            public void call(Subscriber<? super Greeter.GreeterReply> observer) {
                logger.info("In WorldCommand");
                if (!observer.isUnsubscribed()) {
                    //pass on the context, if you want only certain headers to pass on then create a new Context and attach it.
                    context.attach();
                    logger.info("In WorldCommand after attach");
                    worldServiceStub.greetWithHelloOrWorld(greeterRequest, new StreamObserver<Greeter.GreeterReply>() {
                        @Override
                        public void onNext(Greeter.GreeterReply greeterReply) {
                            logger.info("Response from WorldService  -- {}, id = {}", greeterReply.getMessage(), greeterReply.getId());
                            observer.onNext(greeterReply);
                            observer.onCompleted();
                        }

                        @Override
                        public void onError(Throwable t) {
                            logger.info("Exception from WorldService  -- {}", t);
                        }

                        @Override
                        public void onCompleted() {

                        }
                    });
                }
            }
        } ).subscribeOn(Schedulers.io());
    }

    @Override
    protected Observable<Greeter.GreeterReply> resumeWithFallback() {
        logger.info("Response from fallback");
        Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("teammate").setId("-1").build();
        return Observable.just(greeterReply);
    }

I am using Zipkin grpc tracing and MDCCurrentTraceContext to print the traceId and spanId in the logs.

Both the log entries in the WorldCommand do not print out the trace and span ids, they are called on RxIoScheduler thread.

EDIT

Added ConcurrencyStrategy as suggested by Mike.

public class CustomHystrixConcurrencyStrategy extends HystrixConcurrencyStrategy {

    private static final Logger log = LoggerFactory.getLogger(CustomHystrixConcurrencyStrategy.class);

    public <T> Callable<T> wrapCallable(Callable<T> callable){
        log.info("In CustomHystrixConcurrencyStrategy: callable="+ callable.toString());
        return new ContextCallable<>(callable);
    }
}

HelloService calls two services World and Team. The WorldCommand is a HystrixObservableCommand, the TeamCommand is a HystrixCommand.

logger.info("In the HelloService:greetWithHelloWorld");
Greeter.GreeterRequest greeterRequest = Greeter.GreeterRequest.newBuilder().setId(request.getId()).build();

//Call WorldService
ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
//Async stub instead of blockingStub
WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);

WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);
String messageFromWorldService = "";
String idFromWorldService = "";
try {

    Greeter.GreeterReply greeterReply = worldCommand.construct().toBlocking().toFuture().get();
    messageFromWorldService = greeterReply.getMessage();
    idFromWorldService = greeterReply.getId();
    logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
    logger.warn("Exception when calling WorldService\n" +  e);
}

//Call TeamService
ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);

String messageFromTeamService = "";
String idFromTeamService = "";
try {
    Greeter.GreeterReply greeterReply = teamCommand.construct().toBlocking().toFuture().get();
    messageFromTeamService = greeterReply.getMessage();
    idFromTeamService = greeterReply.getId();
    logger.info("Response from TeamService  -- {}, id = {}", messageFromTeamService, idFromTeamService);
} catch (StatusRuntimeException | InterruptedException | ExecutionException e) {
    logger.warn("Exception when calling TeamService\n" +  e);
}

assert(idFromWorldService.equals(idFromTeamService));
Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
responseObserver.onNext(greeterReply);
responseObserver.onCompleted();

PreservableContext class

public class PreservableContexts {

    //private final TraceContext traceContext;
    private static final Logger logger = LoggerFactory.getLogger(PreservableContexts.class.getName());

    public PreservableContexts() {
        logger.info("Creating new PreservableContexts");
        //this.traceContext = TraceContextHolder.getContext();
    }

    public void set() {
       // if (traceContext != null) {
            //TraceContextHolder.setContext(traceContext);
       // }
    }

    public void clear() {
        //TraceContextHolder.clearContext();
    }

The log in PreservableContexts and CustomHystrixConcurrencyStrategy never get printed. I am registering the startegy when I start the HelloServer.

HystrixConcurrencyStrategy strategy = new CustomHystrixConcurrencyStrategy();
        HystrixPlugins.getInstance().registerConcurrencyStrategy(strategy);
        context = HystrixRequestContext.initializeContext();

EDIT 2

Updated how the Observables are set up:

    ManagedChannel worldChannel = getChannel("localhost:8081", "helloService-world-client");
    //Async stub instead of blockingStub
    WorldServiceGrpc.WorldServiceStub worldServiceStub = WorldServiceGrpc.newStub(worldChannel);
    WorldCommand worldCommand = new WorldCommand(greeterRequest, worldServiceStub);

    //Call TeamService
    ManagedChannel teamChannel = getChannel("localhost:8082", "helloService-team-client");
    TeamServiceGrpc.TeamServiceStub teamServiceStub = TeamServiceGrpc.newStub(teamChannel);
    //TeamServiceGrpc.TeamServiceBlockingStub teamServiceStub = TeamServiceGrpc.newBlockingStub(teamChannel);
    TeamCommand teamCommand = new TeamCommand(greeterRequest, teamServiceStub);

    try {
        rx.Observable<Greeter.GreeterReply> worldReplyObservable = worldCommand.observe().subscribeOn(Schedulers.computation());
        rx.Observable<Greeter.GreeterReply> teamReplyObservable = teamCommand.observe().subscribeOn(Schedulers.computation());
        Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
            @Override
            public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
                String messageFromWorldService = worldReply.getMessage();
                String idFromWorldService = worldReply.getId();
                logger.info("Response from WorldService  -- {}, id = {}", messageFromWorldService, idFromWorldService);

                String messageFromTeamService = teamReply.getMessage();
                String idFromTeamService = teamReply.getId();
                logger.info("Response from TeamService  -- {}, id = {}", messageFromTeamService, idFromTeamService);

                assert(idFromWorldService.equals(idFromTeamService));
                Greeter.GreeterReply greeterReply = Greeter.GreeterReply.newBuilder().setMessage("Hello" + messageFromWorldService + " from " + messageFromTeamService).setId(idFromWorldService).build();
                logger.info("Final response=" + greeterReply.getMessage());
                responseObserver.onNext(greeterReply);
                responseObserver.onCompleted();
                return null;
            }
        });
    } catch (StatusRuntimeException e) {
        logger.warn("Exception when calling WorldService and/or TeamService\n" +  e);
    }

I have a weird problem now, the calls to TeamCommand and WorldCommand doesn't complete as in this code is never executed:

Observable.zip(worldReplyObservable, teamReplyObservable, new Func2<Greeter.GreeterReply, Greeter.GreeterReply, Object>() {
                @Override
                public Object call(Greeter.GreeterReply worldReply, Greeter.GreeterReply teamReply) {
                    String messageFromWorldService = worldReply.getMessage();

Also, if there is a fallback, the hystrix-timer threads doesn't have the MDC anymore.


问:
How can I get the last event from an Event Store stream with only one HTTP request?
All the docs I can find seem to suggest I need two http requests to do this: one to the stream, giving me a link to the last event, and then one to follow that link.

That seems bizarre, isn't there a way to do this with just one request?

答: The keyword is 'head', like git. So the last event is at [url of the stream]/head.


问:
C++ : How to ensure that a class member variable is modifiable only within a certain method
I am using C++ 14 with clang on MacOS Sierra. I want to enforce a rule by design. Following is the rule.

I have a member variable in my class say:

```<code>unsigned int m_important_num;
</code>```

There are 4 methods in my class.

```<code>fun1();
fun2();
fun3();
fun4();
</code>```

Objective:

I want only fun2() to be able to change the value of m_important_num.

Question:

Is it possible to make it compiler error if any method other than fun2() changes the variable?
One possible way is to declare it const somehow empower fun2() to change const variables? Is this a good solution? Or are their any better solutions?

Secondary question:

Is it a wrong design to try do such a thing?

答:
I know there are lots of good answers, but there is also an option that you sort of alluded to in your question:

One possible way is to declare it const somehow empower fun2() to change const variables?

```<code>#include <iostream>

using uint = unsigned int;

class Test
{
    const uint num;

public:

    Test(uint _num)
        :
          num(_num)
    {}

    uint get_num() const
    {
        return num;
    }

    void can_change_num(uint _new_num)
    {
        uint& n(const_cast<uint&>(num));
        n = _new_num;
    }

    void cant_change_num(uint _new_num)
    {
//      num = _new_num; // Doesn't compile
    }

};

int main()
{
    Test t(1);

    std::cout << "Num is " << t.get_num() << "\n";

    t.can_change_num(10);

    std::cout << "Num is " << t.get_num() << "\n";

    return 0;
}
</code>```

Produces

```<code>Num is 1
Num is 10
</code>```

Body:
I am using C++ 14 with clang on MacOS Sierra. I want to enforce a rule by design. Following is the rule.

I have a member variable in my class say:

unsigned int m_important_num;

There are 4 methods in my class.

fun1();
fun2();
fun3();
fun4();

Objective:

I want only fun2() to be able to change the value of m_important_num.

Question:

Is it possible to make it compiler error if any method other than fun2() changes the variable?
One possible way is to declare it const somehow empower fun2() to change const variables? Is this a good solution? Or are their any better solutions?

Secondary question:

Is it a wrong design to try do such a thing?

Body:
I know there are lots of good answers, but there is also an option that you sort of alluded to in your question:

One possible way is to declare it const somehow empower fun2() to change const variables?

#include <iostream>

using uint = unsigned int;

class Test
{
    const uint num;

public:

    Test(uint _num)
        :
          num(_num)
    {}

    uint get_num() const
    {
        return num;
    }

    void can_change_num(uint _new_num)
    {
        uint& n(const_cast<uint&>(num));
        n = _new_num;
    }

    void cant_change_num(uint _new_num)
    {
//      num = _new_num; // Doesn't compile
    }

};

int main()
{
    Test t(1);

    std::cout << "Num is " << t.get_num() << "\n";

    t.can_change_num(10);

    std::cout << "Num is " << t.get_num() << "\n";

    return 0;
}

Produces

Num is 1
Num is 10


问:
Get a list of mapped drives as a Windows service.
I'm trying to get a list of mapped drives on my machine as a Windows service. I can get a proper list if I run my code as a normal program, but not as a Windows service. I've seen several posts regarding this topic but none give a clear solution.

I'm running the service on the same account that created the service, and the service has admin rights.

Does anyone know how to properly do this?

答:
If you are in Windows 7 with UAC enabled, then the administrative session has different mapped drives then the regular user session. Open an administrative command prompt and run net show and check the mapped drive status.

Update: I have EnabledLinkedConnections set on my Windows 10 workstation so I don't see this issue there.


问:
Android Studo 3.0 SDK Manager, can't find Extras
Using Android Studio 3.0 / SDK Manager

In trying to set up BILLING, tutorials show installing it through Extras in SDK Manager.

I don't have an Extras folder in SDK manager and can't find any reason why, how to get it, what's wrong, or what to do.

Help. please?

UPDATE: Here's what my SDK Manager looks like:

UPDATE: Here's my SDK Manager Updates Tab

答: Correct answer is: don't need Android Studio for Cordova.</p>


问:
How can I pass props down in Angular 2+ like React?
In react I can arbitrarily pass props down like so:

```<code>function SomeComponent(props) {
  const {takeOutProp, ...restOfProps} = props;
  return <div {...restOfProps}/>;
}
</code>```

How can I do the same thing in Angular?

--

More specifically, I want to write a custom dropdown component and pass props down to a select box.

答:
Actually it is not the answer on your question but perhaps it helps you.
You can add one custom directive with all params you need.

```<code>import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[defaultConfig]'
})
export class DefaultDropdownConfigDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
       // your default config

    }
}

<my-dropdown defaultConfig></my-dropdown>
</code>```

For more details you can read this

Body:
In react I can arbitrarily pass props down like so:

function SomeComponent(props) {
  const {takeOutProp, ...restOfProps} = props;
  return
;
}

How can I do the same thing in Angular?

--

More specifically, I want to write a custom dropdown component and pass props down to a select box.

Body:
Actually it is not the answer on your question but perhaps it helps you.
You can add one custom directive with all params you need.

import { Directive, ElementRef } from '@angular/core';

@Directive({
  selector: '[defaultConfig]'
})
export class DefaultDropdownConfigDirective {
    constructor(el: ElementRef) {
       el.nativeElement.style.backgroundColor = 'yellow';
       // your default config

    }
}

<my-dropdown defaultConfig></my-dropdown>

For more details you can read this


问:
How to display number sequences in rows and columns in Python 3?
I have a coding assignment to input row and column length, and create a power table.  THe example below is for 5 rows, 5 columns.

The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work.  It just shows a table of 1's, five by five.

```<code>rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))

x = 1
y = 1
z = 1

line = ""

while x <= cols :
    line = line + format(y**cols, "4d")
    x = x + 1
while z <= rows :
    print(line)
    z = z + 1
</code>```

答:
Instead, try creating a 2D array in Python such as a 2D list.

```<code>Matrix = [[0 for x in range(5)] for y in range(5)]
    for i in range(5):
        for j in range(5):
            Matrix[i][j]=j^i
</code>```

Then, print the data you need using nested for loops.

```<code>for i in range (5):
    for j in range(5):
        print(Matrix[j][i])
</code>```

Body:
I have a coding assignment to input row and column length, and create a power table.  THe example below is for 5 rows, 5 columns.

The code I have so far prints the correct number of rows and columns, but I haven't been able to get the calculations to work.  It just shows a table of 1's, five by five.

rows = int(input("Enter a number of rows: "))
cols = int(input("Enter a number of columns: "))

x = 1
y = 1
z = 1

line = ""

while x <= cols :
    line = line + format(y**cols, "4d")
    x = x + 1
while z <= rows :
    print(line)
    z = z + 1

Body:
Instead, try creating a 2D array in Python such as a 2D list.

Matrix = [[0 for x in range(5)] for y in range(5)]
    for i in range(5):
        for j in range(5):
            Matrix[i][j]=j^i

Then, print the data you need using nested for loops.

for i in range (5):
    for j in range(5):
        print(Matrix[j][i])


问:
Hot update a service that start by upstart or systemd
A service start by Upstart or systemd and I want hot update it. After update, the new service process is running and then kill the old service process that start by upstart or systemd. A at last, the new process can be monitored by the upstart or systemd as the old process.</p>

答:
You didn't say what your service does. I am answering for the easy case, a network service with short-lived connections, such as an HTTP server.

Have systemd own the socket. Search for "systemd socket activation" (stackoverflow search). I describe how to do it in Go here: https://www.darkcoding.net/software/systemd-socket-activation-in-go/

While the service is running, replace the binary on disk with the new one.

systemctl restart <myservice>

In practice there will often also be some state in your service you will need to persist on shutdown, and load on startup.

The service shutting down might need to wait a brief amount of time until all it's requests complete.

For the more difficult case with many long-lived TCP connections (such as an XMPP server), it's no longer about systemd, you have to have your old and new processes co-ordinate to pass the sockets from one to another. I describe it in Online upgrades in Go, but it's a lot more work.


问:
Get-AzureRmVM requires a name parameter?
If I run this powershell command from an Azure cloud shell it executes fine and gives me a list of all VMs in the specified resource group:

Get-AzureRmVM -ResourceGroupName "MyGroup" -Status

If I execute it in a runbook from an automation account I get an error;

Get-AzureRmVM : Cannot process command because of one or more missing
  mandatory parameters: Name. At TestAutomationAccount-Job-StartVM:20 char:20
  +
      + CategoryInfo          : InvalidArgument: (:) [Get-AzureRmVM], ParameterBindingException
      + FullyQualifiedErrorId : MissingMandatoryParameter,Microsoft.Azure.Commands.Compute.GetAzureVMCommand

I'm trying to get a list of VMs within a resource group, and can't figure out why the apparent difference of behavior.

答:
I am able to reproduce the same exception for the Get-AzureRmVM cmdlet when running in the Azure Automation runbook.

The root cause to this issue is simply due to the version mismatch of the Get-AzureRmVM cmdlet in the Azure Automation environment and Azure Cloud Shell (PowerShell) environment.

The Get-AzureRmVM cmdlet is under the AzureRm.Compute PowerShell module.

When I use the below cmdlet to get the version of AzureRm.Compute in the Azure Automation environment.

```<code>Get-Module -ListAvailable -Name AzureRm.Compute -Refresh
</code>```

The version I get is 1.2.1 for the Azure Automation environment as shown below.

When I use the below cmdlet to get the version of AzureRm.Compute in the Azure Cloud Shell (PowerShell) session.

```<code>Get-AzureRmCommand Get-AzureRmVM
</code>```

The version I get is 3.4.1 for the Azure Cloud Shell (PowerShell) environment as shown below.

Hence I believe the AzureRm.Compute module version mismatch in these 2 environments explained the different behavior and parameters expectation for the Get-AzureRmVM cmdlet.

Hope this helps.

Addendum:
If you want to get the same experience for the Get-AzureRmVM cmdlet as it is in the Azure Cloud Shell environment, you can go to the Modules section in your Azure Automation account, select the AzureRm.Compute module and update it to the version to be the same as the Azure Cloud Shell environment.

Body:
I am able to reproduce the same exception for the Get-AzureRmVM cmdlet when running in the Azure Automation runbook.

The root cause to this issue is simply due to the version mismatch of the Get-AzureRmVM cmdlet in the Azure Automation environment and Azure Cloud Shell (PowerShell) environment.

The Get-AzureRmVM cmdlet is under the AzureRm.Compute PowerShell module.

When I use the below cmdlet to get the version of AzureRm.Compute in the Azure Automation environment.

Get-Module -ListAvailable -Name AzureRm.Compute -Refresh

The version I get is 1.2.1 for the Azure Automation environment as shown below.

When I use the below cmdlet to get the version of AzureRm.Compute in the Azure Cloud Shell (PowerShell) session.

Get-AzureRmCommand Get-AzureRmVM

The version I get is 3.4.1 for the Azure Cloud Shell (PowerShell) environment as shown below.

Hence I believe the AzureRm.Compute module version mismatch in these 2 environments explained the different behavior and parameters expectation for the Get-AzureRmVM cmdlet.

Hope this helps.

Addendum:
If you want to get the same experience for the Get-AzureRmVM cmdlet as it is in the Azure Cloud Shell environment, you can go to the Modules section in your Azure Automation account, select the AzureRm.Compute module and update it to the version to be the same as the Azure Cloud Shell environment.


问:
How to remove orphans and widow in multi-line UILabel having justified text alignment?
I am using UILabel to display text. Sometimes, it creates orphan and widow problem in the copy of text, the alignment of the text is set to 'justified', also the hyphenation factor is set to 1.0.

How can I solve the widow & orphan problem?

I want justified text with hyphens for word-wrap and want to remove orphan and widow.

I had set attributed text to label and the size of label is set depending on the device width.

Here is the code for attributed text:

```<code>let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.Justified
    paragraphStyle.hyphenationFactor = 1.0;

let strTwo = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";

let attrlblTwo = NSAttributedString(string: strTwo,
                                             attributes: [
                                                NSParagraphStyleAttributeName: paragraphStyle,
                                                NSBaselineOffsetAttributeName: NSNumber(float: 0),NSKernAttributeName: 0, NSFontAttributeName : lblTwo.font
        ])
    self.lblTwo.attributedText = attrlblTwo
</code>```

答: To get rid of orphans, replace the last space in the text with a non-breaking space.  The non-breaking space character is U+00A0.  You can find it by selecting "Emoji & Symbols" from the edit menu, click on the widget in the upper right to expand the Character Viewer to full size and then type space in the search field. You'll see a few "missing" characters, these are the space characters. Click on them until you find the "No-Break Space", then double click it to insert it into your code. Character Viewer with Non Breaking Space highlighted</p>

Body:
I am using UILabel to display text. Sometimes, it creates orphan and widow problem in the copy of text, the alignment of the text is set to 'justified', also the hyphenation factor is set to 1.0.

How can I solve the widow & orphan problem?

I want justified text with hyphens for word-wrap and want to remove orphan and widow.

I had set attributed text to label and the size of label is set depending on the device width.

Here is the code for attributed text:

let paragraphStyle = NSMutableParagraphStyle()
    paragraphStyle.alignment = NSTextAlignment.Justified
    paragraphStyle.hyphenationFactor = 1.0;

let strTwo = "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum";

let attrlblTwo = NSAttributedString(string: strTwo,
                                             attributes: [
                                                NSParagraphStyleAttributeName: paragraphStyle,
                                                NSBaselineOffsetAttributeName: NSNumber(float: 0),NSKernAttributeName: 0, NSFontAttributeName : lblTwo.font
        ])
    self.lblTwo.attributedText = attrlblTwo


问:
Receiving empty json messages from edge device
I'm sending messages from a particle photon micro controller to a Azure IoT Hub. I monitor the outgoing messages from the particle portal and they seem to be just fine. Below is a recent sample:

```<code>{
  "name": "*****",
  "data": "{\"eventSentUtcTime\": \"2017-11-03 10:42:00\", \"machine\": \"x10\", \"eventType\": \"coffeeMaintenance\", \"data\": {\"category\": \"MillingPlantCoffee\", \"count\": \"24868\"}",
  "ttl": 60,
  "published_at": "2017-11-03T09:42:39.233Z",
  "coreid": "*****",
  "userid": "*****",
  "version": 37,
  "public": false,
  "productID": 1427
}
</code>```

But when I check incoming messages from the Azure IoT Hub, they're empty except the schema. I'm using the Device explorer from Azure's github for monitoring.

```<code>03.11.2017 10:42:09> Device: [*****], Data:[{"data":{"count":"","category":""},"eventType":"","machine":"","eventSentUtcTime":""}]
</code>```

I double checked the incoming messages inside a sql database, which also displays an empty json message except the given schema.

```<code>data,eventType,machine,eventSentUtcTime,EventProcessedUtcTime,PartitionId,EventEnqueuedUtcTime,IoTHub
Record,,,,2017-11-03T10:01:26.8295948Z,1,2017-11-03T10:01:25.7270000Z,Record
</code>```

The access policy I'm using has all permissions checked. I don't know where to problem lies.

答: It seems like your issue is more on the Particle connector side, assuming you are following this tutorial.</p>

Body:
I'm sending messages from a particle photon micro controller to a Azure IoT Hub. I monitor the outgoing messages from the particle portal and they seem to be just fine. Below is a recent sample:

{
  "name": "*****",
  "data": "{\"eventSentUtcTime\": \"2017-11-03 10:42:00\", \"machine\": \"x10\", \"eventType\": \"coffeeMaintenance\", \"data\": {\"category\": \"MillingPlantCoffee\", \"count\": \"24868\"}",
  "ttl": 60,
  "published_at": "2017-11-03T09:42:39.233Z",
  "coreid": "*****",
  "userid": "*****",
  "version": 37,
  "public": false,
  "productID": 1427
}

But when I check incoming messages from the Azure IoT Hub, they're empty except the schema. I'm using the Device explorer from Azure's github for monitoring.

03.11.2017 10:42:09> Device: [*****], Data:[{"data":{"count":"","category":""},"eventType":"","machine":"","eventSentUtcTime":""}]

I double checked the incoming messages inside a sql database, which also displays an empty json message except the given schema.

data,eventType,machine,eventSentUtcTime,EventProcessedUtcTime,PartitionId,EventEnqueuedUtcTime,IoTHub
Record,,,,2017-11-03T10:01:26.8295948Z,1,2017-11-03T10:01:25.7270000Z,Record

The access policy I'm using has all permissions checked. I don't know where to problem lies.


问:
Reading from URL, store data as double?
```<code>public static void getClientUpdate() {
    try {
        String inputLine;
        double version = 0;
        URL url = new URL("http://ds-forums.com/client/version.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        version = inputLine;
        System.out.println("The version is: " + version);
    } catch (Exception x) {
        System.out.println(x);
    }
}
</code>```

This is going to sound really stupid but I have a txt file that contains a double and I want to save it as a double. Instead it wants a string.  Am I doing this wrong or is there just a few steps I need to add?

答:
Well, you need to parse the string into a double. For example, using Double.parseDouble. I should point out that a version string doesn't sound like a great idea to store as a double... you might want to consider using BigDecimal instead. Doubles are generally better for "real world" physical values such as distances - not "artificial" values such as version numbers. I don't think I'd even use BigDecimal to be honest... it's not like version numbers are usually treated in the same way as "normal" numbers.

Have you considered creating your own type to represent a version number?

Title: Reading from URL, store data as double?

Body:
public static void getClientUpdate() {
    try {
        String inputLine;
        double version = 0;
        URL url = new URL("http://ds-forums.com/client/version.txt");
        BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));
        while ((inputLine = in.readLine()) != null)
            System.out.println(inputLine);
        in.close();
        version = inputLine;
        System.out.println("The version is: " + version);
    } catch (Exception x) {
        System.out.println(x);
    }
}

This is going to sound really stupid but I have a txt file that contains a double and I want to save it as a double. Instead it wants a string.  Am I doing this wrong or is there just a few steps I need to add?


答:
It is not possible

please see the following MSDN article

https://msdn.microsoft.com/en-us/library/windows/desktop/ms685143%28v=vs.85%29.aspx?f=255&MSPPError=-2147217396

If a service is configured to run under a user account, the system always creates a new logon session for the user and starts the service in that new logon session. Therefore, a service cannot manage the drive mappings established within the user's other sessions.

Title: Get a list of mapped drives as a Windows service.

Body:
I'm trying to get a list of mapped drives on my machine as a Windows service. I can get a proper list if I run my code as a normal program, but not as a Windows service. I've seen several posts regarding this topic but none give a clear solution.

I'm running the service on the same account that created the service, and the service has admin rights.

Does anyone know how to properly do this?


问:
Android Studio - mergeDebugResources exception
I recently updated the Android Studio to it's latest version, and now I am experiencing a headache with an exception in Gradle build.

Every time I run the project, two or three times before it succeed, I get the following error:

```<code>Gradle: Execution failed for task ': ProjectName:
mergeDebugResources'.
Java.lang.NullPointerException (no error message)
</code>```

After trying again a couple times, the error does not happen again until the next run.

Does anybody have any idea of why this is happening? The project worked just fine 'til the update, never got any error before...

Thanks!

答:
I had the same problem and managed to solve, it simply downgrade your gradle version like this:

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:YOUR_GRADLE_VERSION'
}
</code>```

to

```<code>dependencies {
    classpath 'com.android.tools.build:gradle:OLDER_GRADLE_VERSION_THAT_YOUR'
}
</code>```

for example:

YOUR_GRADLE_VERSION  =  3.0.0

OLDER_GRADLE_VERSION_THAT_YOUR  =  2.3.2

Body:
I recently updated the Android Studio to it's latest version, and now I am experiencing a headache with an exception in Gradle build.

Every time I run the project, two or three times before it succeed, I get the following error:

Gradle: Execution failed for task ': ProjectName:
mergeDebugResources'.
Java.lang.NullPointerException (no error message)

After trying again a couple times, the error does not happen again until the next run.

Does anybody have any idea of why this is happening? The project worked just fine 'til the update, never got any error before...

Thanks!

Body:
I had the same problem and managed to solve, it simply downgrade your gradle version like this:

dependencies {
    classpath 'com.android.tools.build:gradle:YOUR_GRADLE_VERSION'
}

to

dependencies {
    classpath 'com.android.tools.build:gradle:OLDER_GRADLE_VERSION_THAT_YOUR'
}

for example:

YOUR_GRADLE_VERSION  =  3.0.0

OLDER_GRADLE_VERSION_THAT_YOUR  =  2.3.2


问:
C++ template how to overloading operator and accessing private property
I am currently trying to implement a simple template-based linked list that takes a generic key/value-pair in C++11. Elements should be added to the list by the += operator. The code looks like this:

list

```<code>// Forward declarations
template<typename K, typename V>
class list;

template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &list, const std::tuple<K, V> ele) {
    if (!list.head) {
        // list is empty
        list.head = new element(ele, nullptr);
    }

    return list;
};

// Class definition
template<typename K, typename V>
class list {
private:
    struct element {
        const K key;
        const V value;
        element *next;

        element(const std::tuple<K, V> tuple, element *ele) :
                key(std::get<0>(tuple)),
                value(std::get<1>(tuple)),
                next(ele) { }
    };

    element *head = nullptr;

public:
    friend list<K, V> &operator+=<>(list<K, V> &list, const std::tuple<K, V> ele);
};
</code>```

I can't get this to compile. Do I have to put the implementation of the operator into the forward declaration or into the class itself? If I put it in the forward-declaration, like in the snippet, I can't seem to use "list.head = new element(ele, nullptr);". Error: expected type-specifier before ‘element’

If I put it into the class itself, I can't access list.head even tho it's a friend.

答:
You should just leave the declaration of the function template before the class template definition (after the forward declaration), to tell the compiler that operator+= specified in the friend declaration is a template. Then define it later. e.g.

```<code>// Forward declarations
template<typename K, typename V>
class list;

// declaration of function template
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &l, const std::tuple<K, V> ele);

// Class definition
template<typename K, typename V>
class list {
    ...
    friend list<K, V> &operator+=<>(list<K, V> &l, const std::tuple<K, V> ele);
};

// definition of function template
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &l, const std::tuple<K, V> ele) {
    if (!l.head) {
        // list is empty
        l.head = new typename list<K, V>::element(ele, nullptr);
    }

    return l;
}
</code>```

PS:

Don't name the parameter with the name list, which conflicts with the name of class template list.

element is a nested struct, in operator+= you should specify it like typename list<K, V>::element.

Using name list (same as std::list) is not a good idea.

LIVE

Body:
I am currently trying to implement a simple template-based linked list that takes a generic key/value-pair in C++11. Elements should be added to the list by the += operator. The code looks like this:

list

// Forward declarations
template<typename K, typename V>
class list;

template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &list, const std::tuple<K, V> ele) {
    if (!list.head) {
        // list is empty
        list.head = new element(ele, nullptr);
    }

    return list;
};

// Class definition
template<typename K, typename V>
class list {
private:
    struct element {
        const K key;
        const V value;
        element *next;

        element(const std::tuple<K, V> tuple, element *ele) :
                key(std::get<0>(tuple)),
                value(std::get<1>(tuple)),
                next(ele) { }
    };

    element *head = nullptr;

public:
    friend list<K, V> &operator+=<>(list<K, V> &list, const std::tuple<K, V> ele);
};

I can't get this to compile. Do I have to put the implementation of the operator into the forward declaration or into the class itself? If I put it in the forward-declaration, like in the snippet, I can't seem to use "list.head = new element(ele, nullptr);". Error: expected type-specifier before ‘element’

If I put it into the class itself, I can't access list.head even tho it's a friend.

Body:
You should just leave the declaration of the function template before the class template definition (after the forward declaration), to tell the compiler that operator+= specified in the friend declaration is a template. Then define it later. e.g.

// Forward declarations
template<typename K, typename V>
class list;

// declaration of function template
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &l, const std::tuple<K, V> ele);

// Class definition
template<typename K, typename V>
class list {
    ...
    friend list<K, V> &operator+=<>(list<K, V> &l, const std::tuple<K, V> ele);
};

// definition of function template
template<typename K, typename V>
list<K, V> &operator+=(list<K, V> &l, const std::tuple<K, V> ele) {
    if (!l.head) {
        // list is empty
        l.head = new typename list<K, V>::element(ele, nullptr);
    }

    return l;
}

PS:

Don't name the parameter with the name list, which conflicts with the name of class template list.

element is a nested struct, in operator+= you should specify it like typename list<K, V>::element.

Using name list (same as std::list) is not a good idea.

LIVE


问:
How to connect to Amazon Simple AD using ldaps?
I cannot seem to connect to Amazon Simple AD using an ldaps:// url (with the default port number 636). I am getting "Connection refused".

It works with the non-encrypted ldap:// (port 389).

Is there something I need to enable on the AD or VPC or Security Groups settings?

Motivation: I suppose plain LDAP may be secure enough, as it is going via VPC anyway, but the software attached to it (WSO2 Identity Server) seems to insist on LDAPS:

WARN {org.wso2.carbon.user.core.ldap.ActiveDirectoryUserStoreManager} -  Connection to the Active Directory is not secure. Passowrd involved operations such as update credentials and adduser operations will fail

答:
AWS expects you to use a proxy for SSL termination. You could use something like HAProxy. If you want to have it available to the public webs then you would use something like ELB with a cert. Here is the documentation:

https://aws.amazon.com/blogs/security/how-to-configure-an-ldaps-endpoint-for-simple-ad/