问:
Selenium: How to wait for options in a select to be populated?
I am using Selenium for the first time and am overwhelmed by the options. I am using the IDE in Firefox.

When my page loads, it subsequently fetches values via an JSONP request, with which it populates options in a select.

How do I get Selenium to wait for a certain option in the select to be present before proceeding?

答:
I found handy something like:</p>

```<code>wait.until(
    ExpectedConditions
        .presenceOfNestedElementsLocatedBy(By.id(<selectioNId>), By.tagName("option"))
)
</code>```

Body:
I found handy something like:

wait.until(
    ExpectedConditions
        .presenceOfNestedElementsLocatedBy(By.id(<selectioNId>), By.tagName("option"))
)


来源: stackexchange

问:
KSoap2 list handling - is this the correct way?
I have a basic soap service running on glassfish, that returns List<String> like this

```<code><?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:getNamesResponse xmlns:ns2="http://namespace/">
            <return>Name1</return>
            <return>Name2</return>
        </ns2:getNamesResponse>
    </S:Body>
</S:Envelope>
</code>```

now in ksoap2 (android) I have to iterate the soap-object properties to get my list back:

```<code>SoapObject result = (SoapObject) envelope.bodyIn;

for(int i=0;i<result.getPropertyCount();i++)
{
    list.add(result.getProperty(i));
}
</code>```

is there a better way? I couldn't find any class mapper in my implementation.

thanks in advance

答: I am afraid not - you would need to do the mapping yourself.</p>

ContentLicense: CC BY-SA 2.5

Body:
I have a basic soap service running on glassfish, that returns List<String> like this

<?xml version="1.0" encoding="UTF-8"?>
<S:Envelope xmlns:S="http://schemas.xmlsoap.org/soap/envelope/">
    <S:Body>
        <ns2:getNamesResponse xmlns:ns2="http://namespace/">
            <return>Name1</return>
            <return>Name2</return>
        </ns2:getNamesResponse>
    </S:Body>
</S:Envelope>

now in ksoap2 (android) I have to iterate the soap-object properties to get my list back:

SoapObject result = (SoapObject) envelope.bodyIn;

for(int i=0;i<result.getPropertyCount();i++)
{
    list.add(result.getProperty(i));
}

is there a better way? I couldn't find any class mapper in my implementation.

thanks in advance


问:
WSO2DAS Dashboard issue
I've created a gadget on WSO2DAS, it is visible in store, but can't find it in list "Add Gadgets" while creating the dashboard.

Any help  appreciated.

答: Maybe is not a valid answer but instead a workaround. I am facing the same issue but recently I found that, if you add another gadget, the dashboard wizard show the first gadget added before the last one. The last added gadget is not show by the dashboard wizard.</p>

ContentLicense: CC BY-SA 3.0

Title: WSO2DAS Dashboard issue


问:
How to wait for edges in always block?
I am trying to write something like this:

```<code>always@(posedge bus_start)
begin
    @(posedge scl) buffer[7] = sda;
    @(posedge scl) buffer[6] = sda;
    @(posedge scl) buffer[5] = sda;
    @(posedge scl) buffer[4] = sda;
    @(posedge scl) buffer[3] = sda;
    @(posedge scl) buffer[2] = sda;
    @(posedge scl) buffer[1] = sda;
    @(posedge scl) buffer[0] = sda;
end
</code>```

But it is not synthesizable according to the error I got.

I may use FSM to solve this, but that could make it complicated, is there any way to make it synthesizable?

答:
It looks like you're trying to capture data from an I2C interface.
Here is a simple solution for capturing 8 bits of data from sda and storing that into a register called buffer.

```<code>// starts on rising edge of scl or bus_start
always@(posedge bus_start or posedge scl)
begin
    buffer[0] <= sda; // loads sda into the lowest bit of buffer
    buffer[7:1] <= buffer[6:0]; // shifts the lower 6 bits one to
                                // the left, acting as a shift register
end
</code>```

More information about I2C in verilog can be found here
In addition, a basic I2C slave can be found here (you must register and login to view the source code).

Title: How to wait for edges in always block?

Body:
I am trying to write something like this:

always@(posedge bus_start)
begin
    @(posedge scl) buffer[7] = sda;
    @(posedge scl) buffer[6] = sda;
    @(posedge scl) buffer[5] = sda;
    @(posedge scl) buffer[4] = sda;
    @(posedge scl) buffer[3] = sda;
    @(posedge scl) buffer[2] = sda;
    @(posedge scl) buffer[1] = sda;
    @(posedge scl) buffer[0] = sda;
end

But it is not synthesizable according to the error I got.

I may use FSM to solve this, but that could make it complicated, is there any way to make it synthesizable?

Body:
It looks like you're trying to capture data from an I2C interface.
Here is a simple solution for capturing 8 bits of data from sda and storing that into a register called buffer.

// starts on rising edge of scl or bus_start
always@(posedge bus_start or posedge scl)
begin
    buffer[0] <= sda; // loads sda into the lowest bit of buffer
    buffer[7:1] <= buffer[6:0]; // shifts the lower 6 bits one to
                                // the left, acting as a shift register
end

More information about I2C in verilog can be found here
In addition, a basic I2C slave can be found here (you must register and login to view the source code).


问:
Can't figure out how to display output
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

```<code><html>
<head>
  <meta charset="UTF-8">
  <script src="Main.js" type="text/javascript"></script>
  <link href="Main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
        <form id="Awesome">
        <label>Input Text Here: </label><input type="text" id="txtBox">
        <br><br>
        <label>Dec to Roman #: </label><input type="text" id="Results">
        <br><br>
        <input type="button" value="Calculate" id="Execute">

        </div>
        </form>
</body>
</html>
</code>```

Javascript

```<code>function convertToRoman(num) {
var romans = {
M:  1000,
CM: 900,
D:  500,
CD: 400,
C:  100,
XC: 90,
L:  50,
XL: 40,
X:  10,
IX: 9,
V:  5,
IV: 4,
I:  1,
};

var result = '';

for (var key in romans) {
if (num >= romans[key]) {
    result += key.repeat(Math.trunc(num / romans[key]));
    num -= romans[key] * Math.trunc(num / romans[key]);
}
}

return result;

}
</code>```

答:
You can use the JQuery function .val() to set some input value and listen for the event input on your input :

$(function(){
  $('#txtBox').on('input',function(){
    $('#Results').val(convertToRoman($(this).val()));
  });
});

function convertToRoman(num) {
var romans = {
M:  1000,
CM: 900,
D:  500,
CD: 400,
C:  100,
XC: 90,
L:  50,
XL: 40,
X:  10,
IX: 9,
V:  5,
IV: 4,
I:  1,
};

var result = '';

for (var key in romans) {
if (num >= romans[key]) {
    result += key.repeat(Math.trunc(num / romans[key]));
    num -= romans[key] * Math.trunc(num / romans[key]);
}
}

return result;

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
  <meta charset="UTF-8">
  <script src="Main.js" type="text/javascript"></script>
  <link href="Main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
        <form id="Awesome">
        <label>Input Text Here: </label><input type="text" id="txtBox">
        <br><br>
        <label>Dec to Roman #: </label><input type="text" id="Results">
        <br><br>
        <input type="button" value="Calculate" id="Execute">

        </div>
        </form>
</body>
</html></code>```

Title: Can't figure out how to display output

Body:
This might sound like a simple thing for you programmers out there but i can't seem to figure it out. I'm making a program that converts Decimal Numbers into Roman Numerals. I've got the core code working but i can't seem to think how i can display the results on the screen. I would like it so that when the user types a number into a text box the result appears in another text box at the press of a button. Thanks for your time & help.

  <meta charset="UTF-8">

  <link href="Main.css" rel="stylesheet" type="text/css"/>

        <form id="Awesome">
        Input Text Here: <input type="text" id="txtBox">

        Dec to Roman #: <input type="text" id="Results">

        <input type="button" value="Calculate" id="Execute">

        </form>

Javascript

function convertToRoman(num) {
var romans = {
M:  1000,
CM: 900,
D:  500,
CD: 400,
C:  100,
XC: 90,
L:  50,
XL: 40,
X:  10,
IX: 9,
V:  5,
IV: 4,
I:  1,
};

var result = '';

for (var key in romans) {
if (num >= romans[key]) {
    result += key.repeat(Math.trunc(num / romans[key]));
    num -= romans[key] * Math.trunc(num / romans[key]);
}
}

return result;

}

Body:
You can use the JQuery function .val() to set some input value and listen for the event input on your input :

$(function(){
  $('#txtBox').on('input',function(){
    $('#Results').val(convertToRoman($(this).val()));
  });
});

function convertToRoman(num) {
var romans = {
M:  1000,
CM: 900,
D:  500,
CD: 400,
C:  100,
XC: 90,
L:  50,
XL: 40,
X:  10,
IX: 9,
V:  5,
IV: 4,
I:  1,
};

var result = '';

for (var key in romans) {
if (num >= romans[key]) {
    result += key.repeat(Math.trunc(num / romans[key]));
    num -= romans[key] * Math.trunc(num / romans[key]);
}
}

return result;

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<head>
  <meta charset="UTF-8">
  <script src="Main.js" type="text/javascript"></script>
  <link href="Main.css" rel="stylesheet" type="text/css"/>
</head>
<body>
        <form id="Awesome">
        <label>Input Text Here: </label><input type="text" id="txtBox">
        <br><br>
        <label>Dec to Roman #: </label><input type="text" id="Results">
        <br><br>
        <input type="button" value="Calculate" id="Execute">

        </div>
        </form>
</body>
</html>


问:
Branching and (re-)joining value pairs in RxJS
I want to create a stream that

splits values and processes each partial on a separate stream

each stream will transform data, I have no control over the applied transformation

(re-)joins the partial values with their corresponding counter part

The reason I want to do this is to ensure the integrity of the value. Or at least for some part of it.

Because each stream could have some async operations they do not appear in order when joining the streams. Using some sort of concat() also doesn't work because it would block all incoming values. Processing should be done in parallel.

To illustrate:

```<code>                            o
                            |
                            | [{a1,b1}, {a2,b2}, ...]
                            |
                            +
                           / \
                   {a<x>} /   \ {b<x>}
                         /     \
                        |       |
                        |       + async(b<x>) -> b'<x>
                        |       |
                        \       /
                         \     /
                          \   /
                           \ /
                            + join(a<x>, b'<x>)
                            |
                            | [{a1,b'1}, {a2,b'2}, ...]
                            |
                       (subscribe)
</code>```

I know this can be done via a result selector function. E.g.

```<code>input$.mergeMap(
  ({a, b}) => Rx.Observable.of(b).let(async),
  ({a}, processedB) => ({a, b:processedB})
);
</code>```

But, (a) this will result in async to always be setup/tear down for each value. I would like the partial stream to only be initialized once. Also, (b) this only works with one asynchronously stream.

I also tried to use window*, but couldn't figure out how to rejoin values again. Also tried to use goupBy with no luck.

EDIT:

Here is my current attempt. It has the mentioned issue (a). Init... and Completed... should only be logged once.

const doSomethignAsync = data$ => {
  console.log('Init...') // Should happen once.
  return data$
    .mergeMap(val => Rx.Observable.of(val.data).delay(val.delay))
    .finally(() => console.log('Completed...')); // Should never happen
};

const input$ = new Rx.Subject();
const out$ = input$
  .mergeMap(
    ({ a, b }) => Rx.Observable.of(b).let(doSomethignAsync),
    ({ a }, asyncResult ) => ({ a, b:asyncResult })
  )

  .subscribe(({a, b}) => {
    if (a === b) {
      console.log(`Re-joined [${a}, ${b}] correctly.`);
    } else {
      console.log(`Joined [${a}, ${b}]...`); // Should never happen
    }
  });

input$.next({ a: 1, b: { data: 1, delay: 2000 } });
input$.next({ a: 2, b: { data: 2, delay: 1000 } });
input$.next({ a: 3, b: { data: 3, delay: 3000 } });
input$.next({ a: 4, b: { data: 4, delay: 0 } });```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://unpkg.com/rxjs/bundles/Rx.min.js"></script></code>```

答:
This is a rather complex problem to solve and exactly how you do it will depend on very specific details to your use case that weren't included.

That said, here's one possible way that makes a bunch of assumptions. It's made to be somewhat generic, like a custom operator to be used with let.

(side note: I named it "collate" but this is a bad and highly misleading name for this, but whatevs no time to name things...)

```<code>const collate = (...segments) => source$ =>
  source$
    .mergeMap((obj, index) => {
      return segments.map(({ key, work }) => {
        const input = obj[key];
        const output$ = work(input);

        return Observable.from(output$).map(output => ({
          index,
          result: { [key]: output }
        }))
      })
    })
    .mergeAll()
    .groupBy(
      obj => obj.index,
      obj => obj.result,
      group$ => group$.skip(segments.length - 1)
    )
    .mergeMap(group$ =>
      group$.reduce(
        (obj, result) => Object.assign(obj, result),
        {}
      )
    );
</code>```

And here's a usage example:

```<code>const result$ = input$.let(
  collate({
    key: 'a',
    work: a => {
      // do stuff with "a"
      return Observable.of(a).map(d => d + '-processed-A');
    }
  }, {
    key: 'b',
    work: b => {
      // do stuff with "b"
      return Observable.of(b).map(d => d + '-processed-B');
    }
  })
);
</code>```

Given input { a: '1', b: '1 } it would output { a: '1-processed-A', b: '1-processed-B' } and so on, grouped correctly while doing as much concurrently as possible--the only buffering it does is to match all the segments together for a particular input.

Here's a running demo https://jsbin.com/yuruvar/edit?js,output

Breakdown

There's probably more clear/simpler ways to doing this, especially if you can hardcode some things instead of making them generic. But let's breakdown what I did.

```<code>const collate = (...segments) => source$ =>
  source$
    // for every input obj we use the index as an ID
    // (which is provided by Rx as autoincrementing)
    .mergeMap((obj, index) => {
      // segments is the configuration of how we should
      // chunk our data into concurrent processing channels.
      // So we're returning an array, which mergeMap will consume
      // as if it were an Observable, or we could have used
      // Observable.from(arr) to be even more clear
      return segments.map(({ key, work }) => {
        const input = obj[key];
        // the `work` function is expected to return
        // something Observable-like
        const output$ = work(input);

        return Observable.from(output$).map(output => ({
          // Placing the index we closed over lets us later
          // stitch each segment back to together
          index,
          result: { [key]: output }
        }))
      })
    })
    // I had returned Array<Observable> in mergeMap
    // so we need to flatten one more level. This is
    // rather confusing...prolly clearer ways but #YOLO
    .mergeAll()
    // now we have a stream of all results for each segment
    // in no guaranteed order so we need to group them together
    .groupBy(
      obj => obj.index,
      obj => obj.result,
      // this is tough to explain. this is used as a notifier
      // to say when to complete() the group$, we want complete() it
      // after we've received every segment for that group, so in the
      // notifier we skip all except the last one we expect
      // but remember this doesn't skip the elements downstream!
      // only as part of the durationSelector notifier
      group$ => group$.skip(segments.length - 1)
    )
    .mergeMap(group$ =>
      // merge every segment object that comes back into one object
      // so it has the same shape as it came in, but which the results
      group$.reduce(
        (obj, result) => Object.assign(obj, result),
        {}
      )
    );
</code>```

I didn't think or worry about how error handling/propagation might work because that's highly dependant on your usecase. If you have no control over the processing of each segment, then also including some sort of timeout and .take(1) would be advised otherwise you may leak subscriptions.

Body:
I want to create a stream that

splits values and processes each partial on a separate stream

each stream will transform data, I have no control over the applied transformation

(re-)joins the partial values with their corresponding counter part

The reason I want to do this is to ensure the integrity of the value. Or at least for some part of it.

Because each stream could have some async operations they do not appear in order when joining the streams. Using some sort of concat() also doesn't work because it would block all incoming values. Processing should be done in parallel.

To illustrate:

                            o
                            |
                            | [{a1,b1}, {a2,b2}, ...]
                            |
                            +
                           / \
                   {a<x>} /   \ {b<x>}
                         /     \
                        |       |
                        |       + async(b<x>) -> b'<x>
                        |       |
                        \       /
                         \     /
                          \   /
                           \ /
                            + join(a<x>, b'<x>)
                            |
                            | [{a1,b'1}, {a2,b'2}, ...]
                            |
                       (subscribe)

I know this can be done via a result selector function. E.g.

input$.mergeMap(
  ({a, b}) => Rx.Observable.of(b).let(async),
  ({a}, processedB) => ({a, b:processedB})
);

But, (a) this will result in async to always be setup/tear down for each value. I would like the partial stream to only be initialized once. Also, (b) this only works with one asynchronously stream.

I also tried to use window*, but couldn't figure out how to rejoin values again. Also tried to use goupBy with no luck.

EDIT:

Here is my current attempt. It has the mentioned issue (a). Init... and Completed... should only be logged once.

const doSomethignAsync = data$ => {
  console.log('Init...') // Should happen once.
  return data$
    .mergeMap(val => Rx.Observable.of(val.data).delay(val.delay))
    .finally(() => console.log('Completed...')); // Should never happen
};

const input$ = new Rx.Subject();
const out$ = input$
  .mergeMap(
    ({ a, b }) => Rx.Observable.of(b).let(doSomethignAsync),
    ({ a }, asyncResult ) => ({ a, b:asyncResult })
  )

  .subscribe(({a, b}) => {
    if (a === b) {
      console.log(`Re-joined [${a}, ${b}] correctly.`);
    } else {
      console.log(`Joined [${a}, ${b}]...`); // Should never happen
    }
  });

input$.next({ a: 1, b: { data: 1, delay: 2000 } });
input$.next({ a: 2, b: { data: 2, delay: 1000 } });
input$.next({ a: 3, b: { data: 3, delay: 3000 } });
input$.next({ a: 4, b: { data: 4, delay: 0 } });

Body:
This is a rather complex problem to solve and exactly how you do it will depend on very specific details to your use case that weren't included.

That said, here's one possible way that makes a bunch of assumptions. It's made to be somewhat generic, like a custom operator to be used with let.

(side note: I named it "collate" but this is a bad and highly misleading name for this, but whatevs no time to name things...)

const collate = (...segments) => source$ =>
  source$
    .mergeMap((obj, index) => {
      return segments.map(({ key, work }) => {
        const input = obj[key];
        const output$ = work(input);

        return Observable.from(output$).map(output => ({
          index,
          result: { [key]: output }
        }))
      })
    })
    .mergeAll()
    .groupBy(
      obj => obj.index,
      obj => obj.result,
      group$ => group$.skip(segments.length - 1)
    )
    .mergeMap(group$ =>
      group$.reduce(
        (obj, result) => Object.assign(obj, result),
        {}
      )
    );

And here's a usage example:

const result$ = input$.let(
  collate({
    key: 'a',
    work: a => {
      // do stuff with "a"
      return Observable.of(a).map(d => d + '-processed-A');
    }
  }, {
    key: 'b',
    work: b => {
      // do stuff with "b"
      return Observable.of(b).map(d => d + '-processed-B');
    }
  })
);

Given input { a: '1', b: '1 } it would output { a: '1-processed-A', b: '1-processed-B' } and so on, grouped correctly while doing as much concurrently as possible--the only buffering it does is to match all the segments together for a particular input.

Here's a running demo https://jsbin.com/yuruvar/edit?js,output

Breakdown

There's probably more clear/simpler ways to doing this, especially if you can hardcode some things instead of making them generic. But let's breakdown what I did.

const collate = (...segments) => source$ =>
  source$
    // for every input obj we use the index as an ID
    // (which is provided by Rx as autoincrementing)
    .mergeMap((obj, index) => {
      // segments is the configuration of how we should
      // chunk our data into concurrent processing channels.
      // So we're returning an array, which mergeMap will consume
      // as if it were an Observable, or we could have used
      // Observable.from(arr) to be even more clear
      return segments.map(({ key, work }) => {
        const input = obj[key];
        // the `work` function is expected to return
        // something Observable-like
        const output$ = work(input);

        return Observable.from(output$).map(output => ({
          // Placing the index we closed over lets us later
          // stitch each segment back to together
          index,
          result: { [key]: output }
        }))
      })
    })
    // I had returned Array<Observable> in mergeMap
    // so we need to flatten one more level. This is
    // rather confusing...prolly clearer ways but #YOLO
    .mergeAll()
    // now we have a stream of all results for each segment
    // in no guaranteed order so we need to group them together
    .groupBy(
      obj => obj.index,
      obj => obj.result,
      // this is tough to explain. this is used as a notifier
      // to say when to complete() the group$, we want complete() it
      // after we've received every segment for that group, so in the
      // notifier we skip all except the last one we expect
      // but remember this doesn't skip the elements downstream!
      // only as part of the durationSelector notifier
      group$ => group$.skip(segments.length - 1)
    )
    .mergeMap(group$ =>
      // merge every segment object that comes back into one object
      // so it has the same shape as it came in, but which the results
      group$.reduce(
        (obj, result) => Object.assign(obj, result),
        {}
      )
    );

I didn't think or worry about how error handling/propagation might work because that's highly dependant on your usecase. If you have no control over the processing of each segment, then also including some sort of timeout and .take(1) would be advised otherwise you may leak subscriptions.


问:
Are there any equivalent of Heavy Job plugin in Jenkins pipeline?
We have different jobs running on our jenkins. Some jobs are heavy and taking a lot of CPU and RAM, some are not. So I would like to have some plugins to help me set the weight for those jobs, just like https://wiki.jenkins-ci.org/display/JENKINS/Heavy+Job+Plugin.

But since we are using Jenkins pipeline which is not supported by Heavy Job plugin (See https://issues.jenkins-ci.org/browse/JENKINS-41940). Is there any other equivalent for pipeline jobs just like that?

答:
Not as flexible as a dynamic weight, but to avoid overload you can create several executors with a different label (such as many with label light and only a few with label heavy) and then use node to target these labels.

This is not a solution to the packing problem, only prevents too many jobs with a heavy class from running at the same time.


问:
Is it possible to factory-reset an HipChat server?
I want to remove all users, messages, ect but keep the vm settings.

Is it possible to entirely factory-reset an HipChat server?

答: There isn't an official way to do this right now. You could try to remove the data from MariaDB, Redis and ElasticSearch and reboot, but it might leave your server in a non-supported state. I would redeploy a fresh OVA/AMI instead.</p>


问:
CoreCompile is skipped. I want it to be happened
My scenario is, I have a set of c# files source controlled. I download it, I build the solution file using this command in command-line.

"C:\Windows\Microsoft.NET\Framework64\v4.0.30319\MSBuild.exe" MyProj.sln /property:Platform=x64

But when I do this, CoreCompile is skipped saying "Skipping target "CoreCompile" because all output files are up-to-date with respect to the input files." The problem is, it produces a dll which does not include many changes in .cs file.

When I do a small change (ex. putting a log) in .cs file, then it is built fine and the produced dll contained all changes.

However, the 32 bit version is built without skipping CoreCompile the first time itself. (the same command but with /property:Platform=x86)

I could not understand this behavior. Please help. Thanks.

答:
MSBuild is able to build incrementally. It does so by detecting changes to input files between and missing output files for each target. If you update a repository and no change to .cs files are made, it should skip CoreCompile. You can look up the inputs and outputs for a recent roslyn version here.

You can force a clean build using /t:Rebuild (which is the same as "/t:Clean;Build").

Also note that changing parameters passed in via /p:name=value usually don't affect the build. Incremental build logic is based on file changes, not on values. If a parameter that affects the output directory changes, then the output is considered missing. if only a parameter changes that has affects some compile setting, it may trigger a target on incremental build. These kind of settings are usually set in the project, which would cause a change to $(MSBuildAllProjects) which is usually an input to incremental targets.

E.g. in .NET Core there was a problem when setting /p:Version=1.2.3 or /p:VersionSuffix=beta1 which did not affect incremental builds.


问:
How do I prevent summary (or scope) "proliferation" migrating from tf.scalar_summary to tf.summary.scalar?
Back before 2016-11-30 I could use TensorFlow/TensorBoard code something like the following to create a single scope containing a variable 'global_step_at_epoch' that showed the global step reached at each epoch of my model runs.

But since replacing scalar_summary with summary.scalar, as below, I get a new scope for each epoch. So that after n epochs have completed, I get scopes, and TensorBoard panels, for 'global_step_at_epoch', 'global_step_at_epoch_1', 'global_step_at_epoch_2', ... 'global_step_at_epoch_n', each with a single point.

How do I migrate from scalar_summary to summary.scalar so that the code below (or something like it) produces consolidates all of the individual scopes into a single one, as scalar_summary used to do?

```<code>global_step = tf.Variable(0, trainable=False, name='global_step')
test_writer = tf.summary.FileWriter(...)

with tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                      log_device_placement=FLAGS.log_device_placement)) as sess:
    sess.run(tf.initialize_all_variables())

    test_writer.add_summary(sess.run(tf.summary.scalar('global_step_at_epoch', 0)), 0)

    for ep in range(epochs):

        mini_batches = ...

        for mini_batch in mini_batches:

            gs = int(sess.run(global_step))

        test_writer.add_summary(sess.run(tf.summary.scalar('global_step_at_epoch', gs)), ep + 1)
</code>```

答:
This can already be accomplished with the tf.name_scope context manager by naming the manager the first time it is used and simply suing it again when you wish to add new items to the existing scope (without "proliferation"):

```<code>with tf.name_scope('foo') as a_scope:
   # some graph elements A

# Elsewhere ...

with tf.name_scope(a_scope):
  # additional graph elements B
</code>```

This will place the A and B elements together in a single scope 'foo', whereas

```<code>with tf.name_scope('foo') as:
   # some graph elements A

with tf.name_scope('foo'):
  # additional graph elements B
</code>```

will place the elements in separate scopes, foo and foo_1, respectively.

Body:
Back before 2016-11-30 I could use TensorFlow/TensorBoard code something like the following to create a single scope containing a variable 'global_step_at_epoch' that showed the global step reached at each epoch of my model runs.

But since replacing scalar_summary with summary.scalar, as below, I get a new scope for each epoch. So that after n epochs have completed, I get scopes, and TensorBoard panels, for 'global_step_at_epoch', 'global_step_at_epoch_1', 'global_step_at_epoch_2', ... 'global_step_at_epoch_n', each with a single point.

How do I migrate from scalar_summary to summary.scalar so that the code below (or something like it) produces consolidates all of the individual scopes into a single one, as scalar_summary used to do?

global_step = tf.Variable(0, trainable=False, name='global_step')
test_writer = tf.summary.FileWriter(...)

with tf.Session(config=tf.ConfigProto(allow_soft_placement=True,
                                      log_device_placement=FLAGS.log_device_placement)) as sess:
    sess.run(tf.initialize_all_variables())

    test_writer.add_summary(sess.run(tf.summary.scalar('global_step_at_epoch', 0)), 0)

    for ep in range(epochs):

        mini_batches = ...

        for mini_batch in mini_batches:

            gs = int(sess.run(global_step))

        test_writer.add_summary(sess.run(tf.summary.scalar('global_step_at_epoch', gs)), ep + 1)

Body:
This can already be accomplished with the tf.name_scope context manager by naming the manager the first time it is used and simply suing it again when you wish to add new items to the existing scope (without "proliferation"):

with tf.name_scope('foo') as a_scope:
   # some graph elements A

# Elsewhere ...

with tf.name_scope(a_scope):
  # additional graph elements B

This will place the A and B elements together in a single scope 'foo', whereas

with tf.name_scope('foo') as:
   # some graph elements A

with tf.name_scope('foo'):
  # additional graph elements B

will place the elements in separate scopes, foo and foo_1, respectively.


问:
Why variables created with querySelector(All) are empty?
In the Vue data object there are the following variables defined:

```<code>  data: function() {
    return {
      sails: document.querySelectorAll('.sail'),
      sailsGroup: document.getElementsByClassName("sail"),
      nameDisplay: document.querySelector('#name'),
      lines: document.getElementById("lines"),
      texts: document.getElementById("texts")
    }
  },
(...)
</code>```

Then, there is this showData() method, in the very same Vue object:

```<code>showData() {
  console.log(sails);
  console.log(sailsGroup);
  console.log(nameDisplay);
  console.log(lines);
  console.log(texts);
},
(...)
</code>```

When the method above is called from mounted() hook, it gives: ReferenceError: nameDisplay is not defined at VueComponent.showData. The error appears in case of nameDisplay and sails variables, so the ones assigned with document.querySelector(All) methods. Calling them with this only gives empty array/value.

Why is it so? How to define variables to have them accessible?

答:
```<code>showData() {
  console.log(sails);
  console.log(sailsGroup);
  console.log(nameDisplay);
  console.log(lines);
  console.log(texts);
},
</code>```

This references variables in some outer scope. But if those are actually attributes you set up in data, then you need to use this.name instead:

```<code>showData() {
  console.log(this.sails);
  console.log(this.sailsGroup);
  console.log(this.nameDisplay);
  console.log(this.lines);
  console.log(this.texts);
},
</code>```

Note that if those elements are elements that are inside the Vue component’s template, then it’s unlikely that you will find any elements since the component (and its data) is constructed before the component is actually mounted to the DOM. So the querySelectorAll calls run before the component is rendered.

In that case, you should either initialize the data later (once the component has been mounted), or use component refs instead.

Body:
In the Vue data object there are the following variables defined:

  data: function() {
    return {
      sails: document.querySelectorAll('.sail'),
      sailsGroup: document.getElementsByClassName("sail"),
      nameDisplay: document.querySelector('#name'),
      lines: document.getElementById("lines"),
      texts: document.getElementById("texts")
    }
  },
(...)

Then, there is this showData() method, in the very same Vue object:

showData() {
  console.log(sails);
  console.log(sailsGroup);
  console.log(nameDisplay);
  console.log(lines);
  console.log(texts);
},
(...)

When the method above is called from mounted() hook, it gives: ReferenceError: nameDisplay is not defined at VueComponent.showData. The error appears in case of nameDisplay and sails variables, so the ones assigned with document.querySelector(All) methods. Calling them with this only gives empty array/value.

Why is it so? How to define variables to have them accessible?

Body:
showData() {
  console.log(sails);
  console.log(sailsGroup);
  console.log(nameDisplay);
  console.log(lines);
  console.log(texts);
},

This references variables in some outer scope. But if those are actually attributes you set up in data, then you need to use this.name instead:

showData() {
  console.log(this.sails);
  console.log(this.sailsGroup);
  console.log(this.nameDisplay);
  console.log(this.lines);
  console.log(this.texts);
},

Note that if those elements are elements that are inside the Vue component’s template, then it’s unlikely that you will find any elements since the component (and its data) is constructed before the component is actually mounted to the DOM. So the querySelectorAll calls run before the component is rendered.

In that case, you should either initialize the data later (once the component has been mounted), or use component refs instead.

ContentLicense: CC BY-SA 4.0


问:
Anaconda virtual environment won't start?
So I'm trying to create a virtual environment that runs python 3.5 with Anaconda. To do that, I created a virtual environment like so:

```<code>conda create --name pythonScrapy python=3.5
</code>```

and then tried to run it by calling:

```<code>activate pythonScrapy
</code>```

But when I then call conda info --envs, while the new environment shows up, the * signifying which environment is being used is stuck on the root one. What can be the reason that the comp is not switching my virual environments??

答: Powershell doesn't support activate.  use cmd or anaconda shell.

Body:
So I'm trying to create a virtual environment that runs python 3.5 with Anaconda. To do that, I created a virtual environment like so:

conda create --name pythonScrapy python=3.5

and then tried to run it by calling:

activate pythonScrapy

But when I then call conda info --envs, while the new environment shows up, the * signifying which environment is being used is stuck on the root one. What can be the reason that the comp is not switching my virual environments??


问:
View in areas cannot be located - Visual Studio 2015, C#, ASP.NET MVC 5
I've found many topic and suggestions on this and I think I've tried all of the combinations.

I had a working application that is going to grow larger so I decided to make use of areas. I sloughed through that and can access the controllers but then the application fails when it tries to return data to a view. I created a test data context, classes, etc. then to be sure that it wasn't something that I did wrong when moving into areas.

It's probably best to work through the somewhat smaller test situation and then apply what works to the larger actual application.

My link from _Layout.cshtml:

```<code><li><a href="#">@Html.ActionLink("Test", "Index", "testclasses")</a></li>
</code>```

My model:

```<code>using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Tracking.Areas.test.Models
{
    public class testclass
    {
        public int ID { get; set; }
    }
}
</code>```

My testAreaRegistration:

```<code>using System.Web.Mvc;

namespace Tracking.Areas.test
{
    public class testAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "test";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "test_default",
                //"test/{controller}/{action}/{id}",
                "test/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
</code>```

My test controller:

```<code>using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Tracking.Areas.test.Models;
using Tracking.DAL.Test;

namespace Tracking.Areas.test.Controllers
{
    [RouteArea("test")]
    public class testclassesController : Controller
    {
        private testcontext db = new testcontext();

        // GET: test/testclasses
        public async Task<ActionResult> Index()
        {
            return View(await db.spas.ToListAsync());
        }

        // GET: test/testclasses/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            testclass testclass = await db.spas.FindAsync(id);
            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // GET: test/testclasses/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: test/testclasses/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "ID")] testclass testclass)
        {
            if (ModelState.IsValid)
            {
                db.spas.Add(testclass);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(testclass);
        }

        // GET: test/testclasses/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            testclass testclass = await db.spas.FindAsync(id);
            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // POST: test/testclasses/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "ID")] testclass testclass)
        {
            if (ModelState.IsValid)
            {
                db.Entry(testclass).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(testclass);
        }

        // GET: test/testclasses/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            testclass testclass = await db.spas.FindAsync(id);

            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // POST: test/testclasses/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            testclass testclass = await db.spas.FindAsync(id);
            db.spas.Remove(testclass);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}
</code>```

My RouteConfig file

```<code>namespace Tracking
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}
</code>```

My Global.asax.cs file

```<code>namespace Tracking
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}
</code>```

I've tried with and without [RouteArea("test")] in the controller; I've tried multiple options with adding a controller to the area registration file, removing the area name from in front of controller in the area registration file, and many other combinations.

The code finds the controller and model as I put breakpoints in those and reach them - when it attempts to return the view I get the error message about the index view not being found in the standard locations - it doesn't search within the areas at all.

Thanks!

答:
I think you have an inconsistence in your "convention over configuration" setup. Might be helpful to add the error message and your solution structure. You should check, for example, that the Index.cshtml is found in the Areas\test\Views\testclasses folder. The only thing that I see at a first glance is that you didn't modify your action link to include the area. You should try:

```<code>@Html.ActionLink("Test", "Index", "testclasses", new { Area = "test" }, new{})
</code>```

P.S.> I would recommend using camel case notation for the class names and areas... you know, for the clean code sake. Not to mention that you never know when you might stumble upon a case sensitive convention....

Body:
I've found many topic and suggestions on this and I think I've tried all of the combinations.

I had a working application that is going to grow larger so I decided to make use of areas. I sloughed through that and can access the controllers but then the application fails when it tries to return data to a view. I created a test data context, classes, etc. then to be sure that it wasn't something that I did wrong when moving into areas.

It's probably best to work through the somewhat smaller test situation and then apply what works to the larger actual application.

My link from _Layout.cshtml:

@Html.ActionLink("Test", "Index", "testclasses")

My model:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace Tracking.Areas.test.Models
{
    public class testclass
    {
        public int ID { get; set; }
    }
}

My testAreaRegistration:

using System.Web.Mvc;

namespace Tracking.Areas.test
{
    public class testAreaRegistration : AreaRegistration
    {
        public override string AreaName
        {
            get
            {
                return "test";
            }
        }

        public override void RegisterArea(AreaRegistrationContext context)
        {
            context.MapRoute(
                "test_default",
                //"test/{controller}/{action}/{id}",
                "test/{controller}/{action}/{id}",
                new { action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

My test controller:

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Linq;
using System.Threading.Tasks;
using System.Net;
using System.Web;
using System.Web.Mvc;
using Tracking.Areas.test.Models;
using Tracking.DAL.Test;

namespace Tracking.Areas.test.Controllers
{
    [RouteArea("test")]
    public class testclassesController : Controller
    {
        private testcontext db = new testcontext();

        // GET: test/testclasses
        public async Task<ActionResult> Index()
        {
            return View(await db.spas.ToListAsync());
        }

        // GET: test/testclasses/Details/5
        public async Task<ActionResult> Details(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            testclass testclass = await db.spas.FindAsync(id);
            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // GET: test/testclasses/Create
        public ActionResult Create()
        {
            return View();
        }

        // POST: test/testclasses/Create
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Create([Bind(Include = "ID")] testclass testclass)
        {
            if (ModelState.IsValid)
            {
                db.spas.Add(testclass);
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }

            return View(testclass);
        }

        // GET: test/testclasses/Edit/5
        public async Task<ActionResult> Edit(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }
            testclass testclass = await db.spas.FindAsync(id);
            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // POST: test/testclasses/Edit/5
        // To protect from overposting attacks, please enable the specific properties you want to bind to, for
        // more details see http://go.microsoft.com/fwlink/?LinkId=317598.
        [HttpPost]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> Edit([Bind(Include = "ID")] testclass testclass)
        {
            if (ModelState.IsValid)
            {
                db.Entry(testclass).State = EntityState.Modified;
                await db.SaveChangesAsync();
                return RedirectToAction("Index");
            }
            return View(testclass);
        }

        // GET: test/testclasses/Delete/5
        public async Task<ActionResult> Delete(int? id)
        {
            if (id == null)
            {
                return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
            }

            testclass testclass = await db.spas.FindAsync(id);

            if (testclass == null)
            {
                return HttpNotFound();
            }
            return View(testclass);
        }

        // POST: test/testclasses/Delete/5
        [HttpPost, ActionName("Delete")]
        [ValidateAntiForgeryToken]
        public async Task<ActionResult> DeleteConfirmed(int id)
        {
            testclass testclass = await db.spas.FindAsync(id);
            db.spas.Remove(testclass);
            await db.SaveChangesAsync();
            return RedirectToAction("Index");
        }

        protected override void Dispose(bool disposing)
        {
            if (disposing)
            {
                db.Dispose();
            }
            base.Dispose(disposing);
        }
    }
}

My RouteConfig file

namespace Tracking
{
    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }
}

My Global.asax.cs file

namespace Tracking
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            AreaRegistration.RegisterAllAreas();
            FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
            RouteConfig.RegisterRoutes(RouteTable.Routes);
            BundleConfig.RegisterBundles(BundleTable.Bundles);
        }
    }
}

I've tried with and without [RouteArea("test")] in the controller; I've tried multiple options with adding a controller to the area registration file, removing the area name from in front of controller in the area registration file, and many other combinations.

The code finds the controller and model as I put breakpoints in those and reach them - when it attempts to return the view I get the error message about the index view not being found in the standard locations - it doesn't search within the areas at all.

Thanks!

Body:
I think you have an inconsistence in your "convention over configuration" setup. Might be helpful to add the error message and your solution structure. You should check, for example, that the Index.cshtml is found in the Areas\test\Views\testclasses folder. The only thing that I see at a first glance is that you didn't modify your action link to include the area. You should try:

@Html.ActionLink("Test", "Index", "testclasses", new { Area = "test" }, new{})

P.S.> I would recommend using camel case notation for the class names and areas... you know, for the clean code sake. Not to mention that you never know when you might stumble upon a case sensitive convention....


问:
C#: I have 100 clients to thread separately, what is the most effective way to send/receive data?
I'm doing a project with one Server and a Client for simulation purpose. The objective is to develop a single Server that can communicate with 100 clients at a same time using TCP and UDP. I am using TCPListener and UDPClient for both Server and Client. And I am using multi threading, creating an object class.

My code has 2 problems:

During the run, UDP packet gets lost, which freezes some of the threads.

The sending/receiving speed for UDP is immensely different (Thread 2 sent 2000 vs Thread 4 sent 900 etc)

Also, when I run 10 Threads, it will work perfectly fine. But when the number of threads increases, it will throw these problems.

I have the following bits of code ↓

Client (receiving function):

```<code>rpacket = new byte[1024];
            //#0: UDP packet timeout
            // is this necessary?? I could use while loop to measure waiting time.
            net.tClient.Client.ReceiveTimeout = 1000;
            net.client.Client.ReceiveTimeout = 1000;
            //net.client.Client.SendTimeout = 2000;

            // #1: message
            _logIt(false, localThreadId, "started receivedata for threadid" + localThreadId);

            // #2: number of received data recording
            int nReceived = 0;

            // #3: loop runs forever...
            while (true)
            {

                // receiving data
                bool recursion = false;
                int recursionCount = 0;
                int bytesReceived = 0;

                // receiving data
                bytesReceived = messageReceive(out recursion);

                while (recursion == true)
                {
                    // check if there are data 3 times
                    bytesReceived = messageReceive(out recursion);
                    recursionCount++;

                    if (recursionCount <= 3)
                    {
                        if (recursionCount == 1 && rIndex > 0)
                        { rIndex--; }
                        // resend message
                        if (net.q[rIndex][1] == 0x00)
                        {

                            // sending data to PICS
                            // changed net.q[rIndex].Length - 1 to changed net.q[rIndex].Length - 2
                            try
                            {
                                int nBytesSend = net.client.Send(tempData, tempData.Length, net.ipEndPoint);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }

                        }

                        // if 0x01, the protocl is TCP
                        else if (net.q[rIndex][1] == 0x01)
                        {
                            try {
                            int nBytesSend = net.tClient.Client.Send(tempData, tempData.Length, SocketFlags.None);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }

                    }
                    else if (recursionCount == 4)
                    {

                        // hoot~ byebye
                        recursion = false;
                        Usage("hoot");

                    }
                }
            }
</code>```

Client (sending function):

```<code>// if 0x00, the protocol is UDP

                    if (net.q[rIndex][1] == 0x00)
                    {

                        // sending data to PICS
                        // changed net.q[rIndex].Length - 1 to changed net.q[rIndex].Length - 2
                        int nBytesSend = net.client.Send(data, net.q[rIndex].Length - 2, net.ipEndPoint);

                    }

                    // if 0x01, the protocl is TCP

                    else if (net.q[rIndex][1] == 0x01)
                    {

                        int nBytesSend = net.tClient.Client.Send(data, net.q[rIndex].Length - 2, SocketFlags.None);
                    }

                    // June 1th, tempData is only used for failed messages
                    if (data.Length != 0)
                    { tempData = data; }
                    Array.Resize(ref tempData, data.Length);

                    net.nSent++;
                    totalSent[localThreadId]++;
                    if (verbosity)
                        _logIt(false, localThreadId, "# of data sent: " + net.nSent);

                    // after sending, set the queue[][0] to 0x00
                    net.q[rIndex][0] = 0x00;
                    // setting queue[][1] is not neccessary...
                    rIndex++;
</code>```

Message Receive(out recursion):

```<code>messageReceive(out bool audi)
        {
            int numBytes = 0;
            audi = false;
            // updated try and catch method, because there can be udp or tcp
            try
            {

                rpacket = net.client.Receive(ref net.ipEndPoint);
                numBytes = rpacket.Length;

            }

            catch (SocketException ex)
            {
                try
                {
                    numBytes = net.tClient.Client.Receive(rpacket);
                    Array.Resize(ref rpacket, numBytes);
                }
                catch (Exception exc)
                {
                    audi = true;
                    Console.WriteLine(exc.Message);
                }

            }

            return numBytes;
        }
</code>```

Server side is same as the client.

FYI: there is a 2-D byte array called queue that stores all of the data that will be sent to the remote user. wIndex is a integer that is used for writing the reply data to the queue. rIndex is a integer that is used for reading the reply data from the queue and sends it to the remote user.

How can I fix my problems?

答:
Warning Using multiple threads to send/receive with socket would lock the sockets and its I/O operation in your program.

When you are working with sockets it's better to work with async that sockets provide, like BeginRead and 'EndRead', because they make that the program will run over the same thread and it avoids the socket-client would get blocked. Also, don't use sleep into the socket-clients, they will block the socket.

Check this answer: C# High CPU usage on Listener thread, sleeping misses disconnect

In this answer i show how to use use the BeginRead and WriteRead.

Body:
I'm doing a project with one Server and a Client for simulation purpose. The objective is to develop a single Server that can communicate with 100 clients at a same time using TCP and UDP. I am using TCPListener and UDPClient for both Server and Client. And I am using multi threading, creating an object class.

My code has 2 problems:

During the run, UDP packet gets lost, which freezes some of the threads.

The sending/receiving speed for UDP is immensely different (Thread 2 sent 2000 vs Thread 4 sent 900 etc)

Also, when I run 10 Threads, it will work perfectly fine. But when the number of threads increases, it will throw these problems.

I have the following bits of code ↓

Client (receiving function):

rpacket = new byte[1024];
            //#0: UDP packet timeout
            // is this necessary?? I could use while loop to measure waiting time.
            net.tClient.Client.ReceiveTimeout = 1000;
            net.client.Client.ReceiveTimeout = 1000;
            //net.client.Client.SendTimeout = 2000;

            // #1: message
            _logIt(false, localThreadId, "started receivedata for threadid" + localThreadId);

            // #2: number of received data recording
            int nReceived = 0;

            // #3: loop runs forever...
            while (true)
            {

                // receiving data
                bool recursion = false;
                int recursionCount = 0;
                int bytesReceived = 0;

                // receiving data
                bytesReceived = messageReceive(out recursion);

                while (recursion == true)
                {
                    // check if there are data 3 times
                    bytesReceived = messageReceive(out recursion);
                    recursionCount++;

                    if (recursionCount <= 3)
                    {
                        if (recursionCount == 1 && rIndex > 0)
                        { rIndex--; }
                        // resend message
                        if (net.q[rIndex][1] == 0x00)
                        {

                            // sending data to PICS
                            // changed net.q[rIndex].Length - 1 to changed net.q[rIndex].Length - 2
                            try
                            {
                                int nBytesSend = net.client.Send(tempData, tempData.Length, net.ipEndPoint);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }

                        }

                        // if 0x01, the protocl is TCP
                        else if (net.q[rIndex][1] == 0x01)
                        {
                            try {
                            int nBytesSend = net.tClient.Client.Send(tempData, tempData.Length, SocketFlags.None);
                            }
                            catch (Exception e)
                            {
                                Console.WriteLine(e.Message);
                            }
                        }

                    }
                    else if (recursionCount == 4)
                    {

                        // hoot~ byebye
                        recursion = false;
                        Usage("hoot");

                    }
                }
            }

Client (sending function):

// if 0x00, the protocol is UDP

                    if (net.q[rIndex][1] == 0x00)
                    {

                        // sending data to PICS
                        // changed net.q[rIndex].Length - 1 to changed net.q[rIndex].Length - 2
                        int nBytesSend = net.client.Send(data, net.q[rIndex].Length - 2, net.ipEndPoint);

                    }

                    // if 0x01, the protocl is TCP

                    else if (net.q[rIndex][1] == 0x01)
                    {

                        int nBytesSend = net.tClient.Client.Send(data, net.q[rIndex].Length - 2, SocketFlags.None);
                    }

                    // June 1th, tempData is only used for failed messages
                    if (data.Length != 0)
                    { tempData = data; }
                    Array.Resize(ref tempData, data.Length);

                    net.nSent++;
                    totalSent[localThreadId]++;
                    if (verbosity)
                        _logIt(false, localThreadId, "# of data sent: " + net.nSent);

                    // after sending, set the queue[][0] to 0x00
                    net.q[rIndex][0] = 0x00;
                    // setting queue[][1] is not neccessary...
                    rIndex++;

Message Receive(out recursion):

messageReceive(out bool audi)
        {
            int numBytes = 0;
            audi = false;
            // updated try and catch method, because there can be udp or tcp
            try
            {

                rpacket = net.client.Receive(ref net.ipEndPoint);
                numBytes = rpacket.Length;

            }

            catch (SocketException ex)
            {
                try
                {
                    numBytes = net.tClient.Client.Receive(rpacket);
                    Array.Resize(ref rpacket, numBytes);
                }
                catch (Exception exc)
                {
                    audi = true;
                    Console.WriteLine(exc.Message);
                }

            }

            return numBytes;
        }

Server side is same as the client.

FYI: there is a 2-D byte array called queue that stores all of the data that will be sent to the remote user. wIndex is a integer that is used for writing the reply data to the queue. rIndex is a integer that is used for reading the reply data from the queue and sends it to the remote user.

How can I fix my problems?


问:
How do i save an C# float to an Mysql float?
I can't find any solution, how to save an float in c# to mysql. It save's only the integer.
If my float is for example 2.5 and i save it into my table, than there it's a 2.

I changed the type to double, but i got the same result.
Can somebody help me?

答:
you can use type of

```<code>DECIMAL
</code>```

some information you can get this

Body:
you can use type of

DECIMAL

some information you can get this


问:
Convert VB.NET Group By expression to C#
I have to convert the following expression from VB.NET to C#:

```<code>Dim z = From d In db.GPSdevice
    Where d.CompanyId = currentuser.CompanyId And d.Type = "Trailer"
    Order By d.ListOrder Descending
    Group d By Geofence = d.GeofenceLocation Into g = Group, Count()
    Order By Count Descending
</code>```

I'm confused with Group By section...

答:
Should be pretty straight forward once you grasp the syntax. You would do something like

group "records" by "records.property" into grouped_set

Then you would do a select to perform get your key (group by property) and associated count. Your linq statement should look something like this:

```<code>from d in db.GPSdevice
where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
group d by d.GeofenceLocation into g
select new { GeofenceLocation = g.Key, Count = g.Count() }
</code>```

Body:
I have to convert the following expression from VB.NET to C#:

Dim z = From d In db.GPSdevice
    Where d.CompanyId = currentuser.CompanyId And d.Type = "Trailer"
    Order By d.ListOrder Descending
    Group d By Geofence = d.GeofenceLocation Into g = Group, Count()
    Order By Count Descending

I'm confused with Group By section...

Body:
Should be pretty straight forward once you grasp the syntax. You would do something like

group "records" by "records.property" into grouped_set

Then you would do a select to perform get your key (group by property) and associated count. Your linq statement should look something like this:

from d in db.GPSdevice
where d.CompanyId == currentuser.CompanyId && d.Type == "Trailer"
group d by d.GeofenceLocation into g
select new { GeofenceLocation = g.Key, Count = g.Count() }


问:
Why can't I valign top inside H1 with doctype html
```<code><!DOCTYPE html><html xmlns="http://www.w3.org/1999/xhtml">

<table border=1><tr><td>iasdfasdfa<br>asdfasdfasdf<br>asdfasdfasdf<br>asdfasdf</td><td valign=top style='vertical-align: top;'><h1>This Text Won't Valign Top</h1></td></tr></table>
</code>```

答:
It does align to the top. It's just that the
 element has a default margin that's pushing it down. Remove it:

h1 {
  margin: 0
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><table border=1>
  <tr>
    <td>iasdfasdfa
      <br>asdfasdfasdf
      <br>asdfasdfasdf
      <br>asdfasdf</td>
    <td style='vertical-align: top;'>
      <h1>This Text Won't Valign Top</h1></td>
  </tr>
</table></code>```

Note: Don't use valign=top as that's been deprecated for ages.

Body:
<!DOCTYPE html>

iasdfasdfa
asdfasdfasdf
asdfasdfasdf
asdfasdf
This Text Won't Valign Top

Body:
It does align to the top. It's just that the <h1> element has a default margin that's pushing it down. Remove it:

h1 {
  margin: 0
}

<table border=1>
  <tr>
    <td>iasdfasdfa
      <br>asdfasdfasdf
      <br>asdfasdfasdf
      <br>asdfasdf</td>
    <td style='vertical-align: top;'>
      <h1>This Text Won't Valign Top</h1></td>
  </tr>
</table>

Note: Don't use valign=top as that's been deprecated for ages.


问:
Merge Keys by common value from the same dictionary
Let's say that I have a dictionary that contains the following:

```<code>myDict = {'A':[1,2], 'B': [4,5], 'C': [1,2]}
</code>```

I want to create a new dictionary, merged that merges keys by having similar values, so my merged would be:

```<code>merged ={['A', 'C']:[1:2], 'B':[4,5]}
</code>```

I have tried using the method suggested in this thread, but cannot replicate what I need.

Any suggestions?

答:
What you have asked for is not possible. Your keys in the hypothetical dictionary use mutable lists. As mutable data can not be hashed, you cant use them as dictionary keys.

Edit, I had a go to doing what you asked for except the keys in this are all tuples. This code is a mess but you may be able to clean it up.

```<code>myDict = {'A':[1,2],
          'B': [4,5],
          'C': [1,2],
          'D': [1, 2],
          }

myDict2 = {k: tuple(v) for k, v in myDict.items()}
print(myDict2) #turn all vlaues into hasable tuples

#make set of unique keys
unique = {tuple(v) for v in myDict.values()}
print(unique) #{(1, 2), (4, 5)}

"""
iterate over each value and make a temp shared_keys list tracking for which
keys the values are found. Add the new key, vlaue pairs into a new
dictionary"""
new_dict = {}
for value in unique:
    shared_keys = []
    for key in myDict:
        if tuple(myDict[key]) == value:
            shared_keys.append(key)
    new_dict[tuple(shared_keys)] = value
print(new_dict) #{('A', 'C'): (1, 2), ('B',): (4, 5)}

#change the values back into mutable lists from tuples
final_dict = {k: list(v) for k, v in new_dict.items()}
print(final_dict)
</code>```

Body:
Let's say that I have a dictionary that contains the following:

myDict = {'A':[1,2], 'B': [4,5], 'C': [1,2]}

I want to create a new dictionary, merged that merges keys by having similar values, so my merged would be:

merged ={['A', 'C']:[1:2], 'B':[4,5]}

I have tried using the method suggested in this thread, but cannot replicate what I need.

Any suggestions?

Body:
What you have asked for is not possible. Your keys in the hypothetical dictionary use mutable lists. As mutable data can not be hashed, you cant use them as dictionary keys.

Edit, I had a go to doing what you asked for except the keys in this are all tuples. This code is a mess but you may be able to clean it up.

myDict = {'A':[1,2],
          'B': [4,5],
          'C': [1,2],
          'D': [1, 2],
          }

myDict2 = {k: tuple(v) for k, v in myDict.items()}
print(myDict2) #turn all vlaues into hasable tuples

#make set of unique keys
unique = {tuple(v) for v in myDict.values()}
print(unique) #{(1, 2), (4, 5)}

"""
iterate over each value and make a temp shared_keys list tracking for which
keys the values are found. Add the new key, vlaue pairs into a new
dictionary"""
new_dict = {}
for value in unique:
    shared_keys = []
    for key in myDict:
        if tuple(myDict[key]) == value:
            shared_keys.append(key)
    new_dict[tuple(shared_keys)] = value
print(new_dict) #{('A', 'C'): (1, 2), ('B',): (4, 5)}

#change the values back into mutable lists from tuples
final_dict = {k: list(v) for k, v in new_dict.items()}
print(final_dict)


问:
Improving UDP reliability
I am building a small UDP based server. the server is based on .Net and uses the Socket class it self. I'm using completion ports through ReceiveMessageFromAsync, and the async send.

My problem is I'm loosing around 5%-10% of my traffic. Now i understand this is normal, but is there any way of improving this statistic?

答: About all you can do is something on the same general order as TCP uses -- keep track of which packets were received, and send back something to ACK/NAK packets to get those that didn't arrive re-sent.</p>

Title: Improving UDP reliability


问:
Is it possible to address child class properties after verifying a required inheritance?
I am working with several child class with the same parent class. I'd like to give an object to a function that can be one of the child classes, then make a veryfication of the child class type and then I want to address the corresponding child class properties directly.</p>

```<code>class human
{
    public string name;
}

class woman : human
{
    public bool isPregnant;
}

class man : human
{
    public int numberOfComputers;
}

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        man Andrew = new man();
    }

    public void checkHuman<T>(T my_human) where T : human
    {
        // is something like this possible??
        if (typeof(my_human).Name == "woman")
            Console.WriteLine(my_human.name & " is " & (my_human.isPregnant ? "pregnant." : "not pregnant."));
        if (typeof(my_human).Name == "man") {
            man m = (man)my_human;
            Console.WriteLine(m.name & " has " & m.numberOfComputers & " computers.");
        }
    }
}
</code>```

答:
It is certainly possible to check the type of an object, cast to that type and access the child properties.  However doing this is a "smell" and indicates your abstraction isn't correct.

Instead you should define the common expected behaviour in your parent class and then implement it in each child class.  That way your calling code doesn't need to know the exact child class it is calling, and instead depends on the contract proposed by the parent class.

```<code>using System;

public abstract class Human
{
    public string Name;

    public abstract string GetDetails();
}

public class Woman : Human
{
    public bool IsPregnant;

    public override string GetDetails()
    {
        return Name + " is " + (IsPregnant ? "pregnant." : "not pregnant.");
    }
}

public class Man : Human
{
    public int NumberOfComputers;

    public override string GetDetails()
    {
        return Name + " has " + NumberOfComputers + " computers.";
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var andrew = new Man
        {
            Name = "Andrew",
            NumberOfComputers = 200
        };

        OutputDetails(andrew);
    }

    public static void OutputDetails(Human myHuman)
    {
        Console.WriteLine(myHuman.GetDetails());
    }
}
</code>```

Body:
I am working with several child class with the same parent class. I'd like to give an object to a function that can be one of the child classes, then make a veryfication of the child class type and then I want to address the corresponding child class properties directly.

class human
{
    public string name;
}

class woman : human
{
    public bool isPregnant;
}

class man : human
{
    public int numberOfComputers;
}

class Program
{
    public static void Main(string[] args)
    {
        Console.WriteLine("Hello World!");
        man Andrew = new man();
    }

    public void checkHuman<T>(T my_human) where T : human
    {
        // is something like this possible??
        if (typeof(my_human).Name == "woman")
            Console.WriteLine(my_human.name & " is " & (my_human.isPregnant ? "pregnant." : "not pregnant."));
        if (typeof(my_human).Name == "man") {
            man m = (man)my_human;
            Console.WriteLine(m.name & " has " & m.numberOfComputers & " computers.");
        }
    }
}

Body:
It is certainly possible to check the type of an object, cast to that type and access the child properties.  However doing this is a "smell" and indicates your abstraction isn't correct.

Instead you should define the common expected behaviour in your parent class and then implement it in each child class.  That way your calling code doesn't need to know the exact child class it is calling, and instead depends on the contract proposed by the parent class.

using System;

public abstract class Human
{
    public string Name;

    public abstract string GetDetails();
}

public class Woman : Human
{
    public bool IsPregnant;

    public override string GetDetails()
    {
        return Name + " is " + (IsPregnant ? "pregnant." : "not pregnant.");
    }
}

public class Man : Human
{
    public int NumberOfComputers;

    public override string GetDetails()
    {
        return Name + " has " + NumberOfComputers + " computers.";
    }
}

public class Program
{
    public static void Main(string[] args)
    {
        var andrew = new Man
        {
            Name = "Andrew",
            NumberOfComputers = 200
        };

        OutputDetails(andrew);
    }

    public static void OutputDetails(Human myHuman)
    {
        Console.WriteLine(myHuman.GetDetails());
    }
}


问:
Azure Application Insights - search HTTP erros?
Is there a way to use Application Insights as a substitute for Web Server Logging? My end goal here is to analyze 4xxs and 5xxs.

Details:

-Right now, i only have the requests info for controllers/action where I manually used TrackRequest

-Web App hosted on Azure.

-SDK added as documents instruct.

-Other parts (SQL Dependency Tracking for example) work out-of-the-box

答:
For some reason the web.config was missing:</p>

```<code><httpModules>
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>
</code>```

Body:
For some reason the web.config was missing:

<httpModules>
  <add name="ApplicationInsightsWebTracking" type="Microsoft.ApplicationInsights.Web.ApplicationInsightsHttpModule, Microsoft.AI.Web" />
</httpModules>


问:
Excel VBA - delay for fraction of second while still using Excel and other applications
I write chemical plant simulations in VBA for Excel. I currently use the Application.OnTime method to delay for 1 second. The simulation procedure runs each second. This allows me to change values in the spreadsheet and do other things on the computer while the simulation is running.

However, I would like to run the simulation procedure faster than 1 second. Application.wait prevents me from doing anything else to the spreadsheet while waiting.

答:
You will need to use the Sleep API for intervals less than a second as shown in this post:

https://stackoverflow.com/a/18603933/5162073

As mentioned by @MWicha, you can also use DoEvents to yield execution if needed.


问:
google chrome submits form even if there is no SUBMIT button
This bug/feature cropped up in one of my pages when viewed in google chrome so i wrote a test page which looks like this

```<code><body>
 <form action="loginhandler.php">
      <input type="text" id="name">
      <input type="text" id="lastname">
      <input type="button" value="Login">
 </form>
</body>
</code>```

Here you can see, the input type is NOT of type submit. So if you press ENTER KEY on IE,Firefox,Opera, nothing happens and that is the expected behavior.
But if you press enter on chrome, it SUBMITS regardless of whether the input type is submit or not.

My question , is this a default feature/bug of chrome or am i doing something wrong here. ?

答: I have the opposite problem. I use custom js-element for my form and when i use style='dispay:none;' for the submit button, chrome does not submit form on enter, although, firefox does :(

Body:
This bug/feature cropped up in one of my pages when viewed in google chrome so i wrote a test page which looks like this

 <form action="loginhandler.php">
      <input type="text" id="name">
      <input type="text" id="lastname">
      <input type="button" value="Login">
 </form>

Here you can see, the input type is NOT of type submit. So if you press ENTER KEY on IE,Firefox,Opera, nothing happens and that is the expected behavior.
But if you press enter on chrome, it SUBMITS regardless of whether the input type is submit or not.

My question , is this a default feature/bug of chrome or am i doing something wrong here. ?


问:
INVALID_ARGUMENT: Application credential header not valid. Please fix the client to pass a valid application credential header
When attempting to run a simple Android Instant App, I receive this error in the console and the app does not open. What does this error mean and how do I pass in a valid credential header?</p>

答:
There's a known issue where emulators are not allowed to talk to the Instant Apps backend, resulting in this error. If you try to use the emulator to launch a published instant app, it'll fail for this reason. We've also seen it on some physical devices, but it's very inconsistent there.

When running an instant app locally, you may still see this error, but it's not the root cause. The loader tries to fall back to the backend if something goes wrong with the local launch. So hopefully there's something further up indicating what went wrong initially.

A change has been submitted to skip the fallback for emulators, to reduce that noise, and that'll be in an upcoming SDK release.


问:
Merging JSON object in Javascript
I have JSON object like this:

```<code> jsonData =[
{
  'ApplicationName':'Chrome',
  'env':'Linux',
  'status':'Work'
},
{
  'ApplicationName':'Chrome',
  'env':'Window',
  'status':'Work'
},
  {
  'ApplicationName':'Chrome',
  'env':'IOS',
  'status':'Not Work'
}];
</code>```

I want to merge in the optimal way so that my returned JSON object look this:

```<code>  jsonData =[
{
  'ApplicationName':'Chrome',
  'GroupedEnv':[{'env':'Linux',status:'Work'},{'env':'Window',status:'Work'},{'env':'IOS',status:'Not Work'}]

}];
</code>```

答:
This is a very quick example:</p>

```<code>const reduced = jsonData.reduce((acc, curr) => {

    var appName = curr.ApplicationName;
    acc[appName] = acc[appName] || [];
    acc[appName].push({
        env: curr.env,
        status: curr.env
    });

    return acc;

}, {});

const asArray = Object.getOwnPropertyNames(reduced).map((prop) => {

    return {
        ApplicationName: prop,
        GroupedEnv: reduced[prop]
    };

});
</code>```

Title: Merging JSON object in Javascript

Body:
I have JSON object like this:

 jsonData =[
{
  'ApplicationName':'Chrome',
  'env':'Linux',
  'status':'Work'
},
{
  'ApplicationName':'Chrome',
  'env':'Window',
  'status':'Work'
},
  {
  'ApplicationName':'Chrome',
  'env':'IOS',
  'status':'Not Work'
}];

I want to merge in the optimal way so that my returned JSON object look this:

  jsonData =[
{
  'ApplicationName':'Chrome',
  'GroupedEnv':[{'env':'Linux',status:'Work'},{'env':'Window',status:'Work'},{'env':'IOS',status:'Not Work'}]

}];

Body:
This is a very quick example:

const reduced = jsonData.reduce((acc, curr) => {

    var appName = curr.ApplicationName;
    acc[appName] = acc[appName] || [];
    acc[appName].push({
        env: curr.env,
        status: curr.env
    });

    return acc;

}, {});

const asArray = Object.getOwnPropertyNames(reduced).map((prop) => {

    return {
        ApplicationName: prop,
        GroupedEnv: reduced[prop]
    };

});


问:
C#: Split string and assign result to multiple string variables
I have a string with several fields separated by a specific character, something like this:

A,B,C

I want to split the string at the commas and assign each resulting field to its own string variable. In Perl I can do that elegantly like this:

```<code>my ($varA, $varB, $varC) = split (/,/, $string);
</code>```

What is the simplest and most elegant way to achieve the same result in C#?

I know that I can split into an array:

```<code>string[] results = string.Split(',');
</code>```

But then I would have to access the fields via their index, e.g. results[2]. That is difficult to read and error-prone - consider not having 3 buth 30 fields. For that reason I prefer having each field value in its own named variable.

答:
@pnvn has a great idea with the Unpack pattern, but it could be improved to iterate over the enumeration in a single pass, provide defaults past the end of the enumerable and work on any type or size of enumerable in a predictable way.

Here is an example using C# 7 out variables feature.

```<code>"A,B,C".Split(',')
    .Unpack(out string varA)
    .Unpack(out string varB);
</code>```

This requires two extension methods, one for the IEnumerable to start, the second on the IEnumerator for each subsequent call.

```<code>public static IEnumerator<T> Unpack<T>(this IEnumerable<T> source, out T item)
{
    var enumerator = source.GetEnumerator();
    if (enumerator.MoveNext())
    {
        item = enumerator.Current;
        return enumerator;
    }
    item = default(T);
    return null;
}

public static IEnumerator<T> Unpack<T>(this IEnumerator<T> enumerator, out T item)
{
    if (enumerator != null && enumerator.MoveNext())
    {
        item = enumerator.Current;
        return enumerator;
    }
    item = default(T);
    return null;
}
</code>```

Body:
I have a string with several fields separated by a specific character, something like this:

A,B,C

I want to split the string at the commas and assign each resulting field to its own string variable. In Perl I can do that elegantly like this:

my ($varA, $varB, $varC) = split (/,/, $string);

What is the simplest and most elegant way to achieve the same result in C#?

I know that I can split into an array:

string[] results = string.Split(',');

But then I would have to access the fields via their index, e.g. results[2]. That is difficult to read and error-prone - consider not having 3 buth 30 fields. For that reason I prefer having each field value in its own named variable.

Body:
@pnvn has a great idea with the Unpack pattern, but it could be improved to iterate over the enumeration in a single pass, provide defaults past the end of the enumerable and work on any type or size of enumerable in a predictable way.

Here is an example using C# 7 out variables feature.

"A,B,C".Split(',')
    .Unpack(out string varA)
    .Unpack(out string varB);

This requires two extension methods, one for the IEnumerable to start, the second on the IEnumerator for each subsequent call.

public static IEnumerator<T> Unpack<T>(this IEnumerable<T> source, out T item)
{
    var enumerator = source.GetEnumerator();
    if (enumerator.MoveNext())
    {
        item = enumerator.Current;
        return enumerator;
    }
    item = default(T);
    return null;
}

public static IEnumerator<T> Unpack<T>(this IEnumerator<T> enumerator, out T item)
{
    if (enumerator != null && enumerator.MoveNext())
    {
        item = enumerator.Current;
        return enumerator;
    }
    item = default(T);
    return null;
}


问:
Why does setting textContent cause layout thrashing?
This blog post suggests that textContent is preferable to innerText for avoiding layout thrashing. But it is focused on retrieving an element's text; for setting element text, the opposite appears to be true -- at least in the following example.

This example uses innerText and produces no layout thrashing:

```<code><style>
    #test {
        background-color: blue;
        float: right;
        width: 100px;
        height: 100%;
    }
</style>
Test test test
<div id="test"></div>
<script>
    setInterval(function() {
        document.querySelector('#test').innerText = 'innerText';
    }, 100);
</script>
</code>```

But replace innerText with textContent and watch it thrash:

Can someone explain this behavior? What can I do to avoid layout thrashing and still change an element's text in a standards-based way?

答:
In addition to Benjamin answer, I noticed that when the value of nodeValue or innerText is different than the previous one, the entire document layout is trashed too, as you can see here: http://jsfiddle.net/5N7Rr/15/

(Full screen, open in new tab)

The browser trashes the entire layout because he don't knows the size of the element, so the trick to avoid entire document trashing is to set a fixed height and width AND set overflow to hidden (Important). This way you tell the browser that whatever the content of the element is, it never is going to exit the element boundaries.

EDIT 30/11/2020: I also needed to add CSS property contain: strict to explicitly tell the browser that the content is not going to exit the container.

Fiddle: http://jsfiddle.net/u9pra25f/

And proof (Full screen again). Notice how the layout update only affects the element:

Body:
This blog post suggests that textContent is preferable to innerText for avoiding layout thrashing. But it is focused on retrieving an element's text; for setting element text, the opposite appears to be true -- at least in the following example.

This example uses innerText and produces no layout thrashing:

Test test test

But replace innerText with textContent and watch it thrash:

Can someone explain this behavior? What can I do to avoid layout thrashing and still change an element's text in a standards-based way?


问:
Switch on ranges of integers in JavaScript
I want to do something like this

```<code>    switch (this.dealer) {
        case 1-4:
            // Do something.
            break;
        case 5-8:
            // Do something.
            break;
        case 9-11:
            // Do something.
            break;
        default:
            break;
    }
</code>```

What is the right syntax for this? Is it possible in JavaScript?

So this.dealer is an integer, and if it's between those values, do something.

答:
If you are trying to do something fast, efficient and readable, use a standard if...then...else structure like this:

```<code>var d = this.dealer;
if (d < 12) {
    if (d < 5) {
        alert("less than five");
    }else if (d < 9) {
        alert("between 5 and 8");
    }else{
        alert("between 9 and 11");
    }
}else{
    alert("none");
}
</code>```

If you want to obfuscate it and make it awful (but small), try this:

```<code>var d=this.dealer;d<12?(d<5?alert("less than five"):d<9?alert("between 5 and 8"):alert("between 9 and 11")):alert("none");
</code>```

BTW, the above code is a JavaScript if...then...else shorthand statement. It is a great example of how NOT to write code unless obfuscation or code minification is the goal. Be aware that code maintenance can be an issue if written this way. Very few people can easily read through it, if at all. The code size, however, is 50% smaller than the standard if...then...else without any loss of performance. This means that in larger codebases, minification like this can greatly speed code delivery across bandwidth constrained or high latency networks.

This, however, should not be considered a good answer. It is just an example of what CAN be done, not what SHOULD be done.

Body:
I want to do something like this

    switch (this.dealer) {
        case 1-4:
            // Do something.
            break;
        case 5-8:
            // Do something.
            break;
        case 9-11:
            // Do something.
            break;
        default:
            break;
    }

What is the right syntax for this? Is it possible in JavaScript?

So this.dealer is an integer, and if it's between those values, do something.

Body:
If you are trying to do something fast, efficient and readable, use a standard if...then...else structure like this:

var d = this.dealer;
if (d < 12) {
    if (d < 5) {
        alert("less than five");
    }else if (d < 9) {
        alert("between 5 and 8");
    }else{
        alert("between 9 and 11");
    }
}else{
    alert("none");
}

If you want to obfuscate it and make it awful (but small), try this:

var d=this.dealer;d<12?(d<5?alert("less than five"):d<9?alert("between 5 and 8"):alert("between 9 and 11")):alert("none");

BTW, the above code is a JavaScript if...then...else shorthand statement. It is a great example of how NOT to write code unless obfuscation or code minification is the goal. Be aware that code maintenance can be an issue if written this way. Very few people can easily read through it, if at all. The code size, however, is 50% smaller than the standard if...then...else without any loss of performance. This means that in larger codebases, minification like this can greatly speed code delivery across bandwidth constrained or high latency networks.

This, however, should not be considered a good answer. It is just an example of what CAN be done, not what SHOULD be done.