问:
Change image in specified div when checkboxes are selected
I am wanting to display an image in a div when checkboxes or buttons are selected. I need to to be able to select multiple boxes and display a different image based on the total selection.

The selection matrix would be as follows: A, B, C, D, AB, AC, AD, BC, BD, ABC, ABD. C and D cannot appear together. When nothing is selected I want it to display image F.

I was also hoping to use Bootstrap styling to make them look like buttons not checkboxes.

```<code><div>
    <form name="test1">
        <div data-toggle="buttons" class="btn-group itemcontent">
            <label class="btn btn-default"><input type="checkbox" name="myimages" value="01" id="myimages" onclick="check_value(1)" />Selector1</label>
            <label class="btn btn-default"><input type="checkbox" name="myimages" value="02" id="myimages" onclick="check_value(2)" />Selector2</label>
            <label class="btn btn-default"><input type="checkbox" name="myimages" value="03" id="myimages" onclick="check_value(3)" />Selector3</label>
            <label class="btn btn-default"><input type="checkbox" name="myimages" value="04" id="myimages" onclick="check_value(4)" />Selector4</label>
    </form>
</div>
</code>```

I was thinking of using a script like this:

```<code>function check_value(fieldvalue)
{
    switch(fieldvalue)
    {
        case 1:

            document.getElementById("imagetest").innerHTML = "<img src='img/600/600T_W_Base_Model.png'>";
                break;

        case 2:

            document.getElementById("imagetest").innerHTML = "<img src='img/600/600T_W_DW.png'>";
                break;
</code>```

For my image display div:

But I'm honestly not sure where to go from here. I'm VERY new to JavaScript.

Thank you!

UPDATE

With a friends help we were able to come up with a test, but I can't get the code to work correctly...

```<code>            <!DOCTYPE html>
        <html>

        <head>
        <title>Test </title>
        <script src="https://cdnjs.cloudflare.com/.../jquery/1.12.4/jquery.js"></script>
        <script src="https://cdnjs.cloudflare.com/.../jque.../1.12.1/jquery-ui.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/.../jqu.../1.12.1/jquery-ui.css" />
        <script src="https://cdnjs.cloudflare.com/.../3.3.6/js/bootstrap.js"></script>
        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/.../3.3.6/css/bootstrap.css" />
        <style type="text/css">
        input {
        display: none;
        }

        input:checked ~ label {
        background: #00C000;
        border: 1px solid #090;
        color: #fff;
        }

        label {
        background: #ddd;
        -webkit-touch-callout: none;
        /* iOS Safari */
        -webkit-user-select: none;
        /* Chrome/Safari/Opera */
        -khtml-user-select: none;
        /* Konqueror */
        -moz-user-select: none;
        /* Firefox */
        -ms-user-select: none;
        /* Internet Explorer/Edge */
        user-select: none;
        /* Non-prefixed version, currently
        not supported by any browser */
        padding: 10px 30px;
        border: 1px solid #aaa;
        color: #555;
        }
        </style>
        </head>

        <body>
        <div id="form1">
        <form name="test">
        <span><input type="checkbox" id="chk1" onchange="check_value()" data-val="A"><label for="chk1">A</label></span>
        <span><input type="checkbox" id="chk2" onchange="check_value()" data-val="B"><label for="chk2">B</label></span>
        <span><input type="checkbox" id="chk3" onchange="check_value()" data-val="C"><label for="chk3">C</label></span>
        <span><input type="checkbox" id="chk4" onchange="check_value()" data-val="D"><label for="chk4">D</label></span>
        </form>
        </div>
        <div id="imagetest" style="height:200px;width: 200px; border: 5px solid red;">
        </div>
        </body>
        <script type="text/javascript">
        function check_value()
        {
        var myVal = '';
        $("input[type=checkbox]").each(function()
        {
        if ($(this).is(':checked'))
        {
        myVal += $(this).data('val');
        }
        });

        alert(myVal);

        var myDiv = $('#imagetest');
        if (myVal == 'A')
        {
        myDiv.css('background-color', 'blue');
        }
        else if (myVal == 'B')
        {
        myDiv.css('background-color', 'green');
        }
        else if (myVal == 'C')
        {
        myDiv.css('background-color', 'grey');
        }
        else if (myVal == 'D')
        {
        myDiv.css('background-color', 'pink');
        }
        else if (myVal == 'AB')
        {
        myDiv.css('background-color', 'orange');
        }
        else if (myVal == 'AC')
        {
        myDiv.css('background-color', 'yellow');
        }
        else if (myVal == 'AD')
        {
        myDiv.css('background-color', 'black');
        }
        else if (myVal == 'BC')
        {
        myDiv.css('background-color', 'lightblue');
        }
        else if (myVal == 'BD')
        {
        myDiv.css('background-color', 'lightgreen');
        }
        else if (myVal == 'ABC')
        {
        myDiv.css('background-color', 'brown');
        }
        else if (myVal == 'ABD')
        {
        myDiv.css('background-color', 'Cyan');
        }
        else
        {
        myDiv.css('background-color', 'white');
        }
        }
        </script>
        <style type="text/css">
        input {
        display: none;
        }

        input:checked ~ label {
        background: #00C000;
        border: 1px solid #090;
        color: #fff;
        }

        label {
        background: #ddd;
        -webkit-touch-callout: none;
        /* iOS Safari */
        -webkit-user-select: none;
        /* Chrome/Safari/Opera */
        -khtml-user-select: none;
        /* Konqueror */
        -moz-user-select: none;
        /* Firefox */
        -ms-user-select: none;
        /* Internet Explorer/Edge */
        user-select: none;
        /* Non-prefixed version, currently
        not supported by any browser */
        padding: 10px 30px;
        border: 1px solid #aaa;
        color: #555;
        }
        </style>

        </html>
</code>```

What am I doing wrong here..?

答:
Ok, I got it you want to change image in radio-button selection. If you want to select multiple radio-button you must use another type, checkbox.

Vanilla JavaScript

This is a vanilla, pure javascript, code:

function changeImage(elem) {
  var imageUrl = elem.getAttribute('image');
  document.getElementById('imgview').setAttribute('src', imageUrl);
}
document.querySelector('[value="one"]').click();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="form1">
  <form name='test'>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/300/200" name="field" value="one">BASE</span>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/300/300" name="field" value="two">Deep Well </span>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/200/200" name="field" value="three">Extension </span>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/200/300" name="field" value="four">Treadmill</span>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/300/250" name="field" value="five">Stairs </span>
  </form>
</div>
<div id="imagetest">
    <img id="imgview" src="">
</div></code>```

Simple explanation:

You give every radio button an attribute with the link (relative or absolute is your choice) and then in the function call grep the value for that attribute for the clicked element and set it as image element source.

jQuery

If you want to use jQuery to accomplish it this is a sample:

$(document).ready(function() {

  $('#form1 input[name=field][value]').on('click', function(e) {
    var imageUrl = $(this).attr('image');
    $('#imgview').attr('src', imageUrl);
  });

  $('#form1 input[name=field][value=one]').click();

});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="form1">
  <form name='test'>
    <span><input type="radio" image="https://placebear.com/300/200" name="field" value="one">BASE</span>
    <span><input type="radio" image="https://placebear.com/300/300" name="field" value="two">Deep Well </span>
    <span><input type="radio" image="https://placebear.com/200/200" name="field" value="three">Extension </span>
    <span><input type="radio" image="https://placebear.com/200/300" name="field" value="four">Treadmill</span>
    <span><input type="radio" image="https://placebear.com/300/250" name="field" value="five">Stairs </span>
  </form>
</div>
<div id="imagetest">
  <img id="imgview" src="">
</div></code>```

Edit:

Multiple selection with multiple image view

$(document).ready(function() {

  $('#form1 input[name=field][value]').on('click', function(e) {
    var imageUrl = $(this).attr('image');
    var fieldValue = $(this).val();
    var idImage = 'image_' + fieldValue;
    if ($(this).is(':checked')) {
      $('#imagetest').append('');
    } else {
   $('#'+idImage).remove();
    }

  });

  $('#form1 input[name=field][value=one]').click();

});```
<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>
<div id="form1">
  <form name='test'>
    <label><input type="checkbox" image="https://placebear.com/300/200" name="field" value="one">BASE</label>
    <label><input type="checkbox" image="https://placebear.com/300/300" name="field" value="two">Deep Well </label>
    <label><input type="checkbox" image="https://placebear.com/200/200" name="field" value="three">Extension </label>
    <label><input type="checkbox" image="https://placebear.com/200/300" name="field" value="four">Treadmill</label>
    <label><input type="checkbox" image="https://placebear.com/300/250" name="field" value="five">Stairs </label>
  </form>
</div>
<div id="imagetest">
</div></code>```

Body:
I am wanting to display an image in a div when checkboxes or buttons are selected. I need to to be able to select multiple boxes and display a different image based on the total selection.

The selection matrix would be as follows: A, B, C, D, AB, AC, AD, BC, BD, ABC, ABD. C and D cannot appear together. When nothing is selected I want it to display image F.

I was also hoping to use Bootstrap styling to make them look like buttons not checkboxes.

    <form name="test1">

            <input type="checkbox" name="myimages" value="01" id="myimages" onclick="check_value(1)" />Selector1
            <input type="checkbox" name="myimages" value="02" id="myimages" onclick="check_value(2)" />Selector2
            <input type="checkbox" name="myimages" value="03" id="myimages" onclick="check_value(3)" />Selector3
            <input type="checkbox" name="myimages" value="04" id="myimages" onclick="check_value(4)" />Selector4
    </form>

I was thinking of using a script like this:

function check_value(fieldvalue)
{
    switch(fieldvalue)
    {
        case 1:

            document.getElementById("imagetest").innerHTML = "";
                break;

        case 2:

            document.getElementById("imagetest").innerHTML = "";
                break;

For my image display div:

But I'm honestly not sure where to go from here. I'm VERY new to JavaScript.

Thank you!

UPDATE

With a friends help we were able to come up with a test, but I can't get the code to work correctly...

            <!DOCTYPE html>

        <title>Test </title>

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/.../jqu.../1.12.1/jquery-ui.css" />

        <link rel="stylesheet" href="https://cdnjs.cloudflare.com/.../3.3.6/css/bootstrap.css" />

        <form name="test">
        <input type="checkbox" id="chk1" onchange="check_value()" data-val="A">A
        <input type="checkbox" id="chk2" onchange="check_value()" data-val="B">B
        <input type="checkbox" id="chk3" onchange="check_value()" data-val="C">C
        <input type="checkbox" id="chk4" onchange="check_value()" data-val="D">D
        </form>

What am I doing wrong here..?

Body:
Ok, I got it you want to change image in radio-button selection. If you want to select multiple radio-button you must use another type, checkbox.

Vanilla JavaScript

This is a vanilla, pure javascript, code:

function changeImage(elem) {
  var imageUrl = elem.getAttribute('image');
  document.getElementById('imgview').setAttribute('src', imageUrl);
}
document.querySelector('[value="one"]').click();

<div id="form1">
  <form name='test'>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/300/200" name="field" value="one">BASE</span>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/300/300" name="field" value="two">Deep Well </span>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/200/200" name="field" value="three">Extension </span>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/200/300" name="field" value="four">Treadmill</span>
    <span><input onclick="changeImage(this)" type="radio" image="https://placebear.com/300/250" name="field" value="five">Stairs </span>
  </form>
</div>
<div id="imagetest">
    <img id="imgview" src="">
</div>

Simple explanation:

You give every radio button an attribute with the link (relative or absolute is your choice) and then in the function call grep the value for that attribute for the clicked element and set it as image element source.

jQuery

If you want to use jQuery to accomplish it this is a sample:

$(document).ready(function() {

  $('#form1 input[name=field][value]').on('click', function(e) {
    var imageUrl = $(this).attr('image');
    $('#imgview').attr('src', imageUrl);
  });

  $('#form1 input[name=field][value=one]').click();

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="form1">
  <form name='test'>
    <span><input type="radio" image="https://placebear.com/300/200" name="field" value="one">BASE</span>
    <span><input type="radio" image="https://placebear.com/300/300" name="field" value="two">Deep Well </span>
    <span><input type="radio" image="https://placebear.com/200/200" name="field" value="three">Extension </span>
    <span><input type="radio" image="https://placebear.com/200/300" name="field" value="four">Treadmill</span>
    <span><input type="radio" image="https://placebear.com/300/250" name="field" value="five">Stairs </span>
  </form>
</div>
<div id="imagetest">
  <img id="imgview" src="">
</div>

Edit:

Multiple selection with multiple image view

$(document).ready(function() {

  $('#form1 input[name=field][value]').on('click', function(e) {
    var imageUrl = $(this).attr('image');
    var fieldValue = $(this).val();
    var idImage = 'image_' + fieldValue;
    if ($(this).is(':checked')) {
      $('#imagetest').append('<img src="' + imageUrl + '" id="' + idImage + '">');
    } else {
   $('#'+idImage).remove();
    }

  });

  $('#form1 input[name=field][value=one]').click();

});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="form1">
  <form name='test'>
    <label><input type="checkbox" image="https://placebear.com/300/200" name="field" value="one">BASE</label>
    <label><input type="checkbox" image="https://placebear.com/300/300" name="field" value="two">Deep Well </label>
    <label><input type="checkbox" image="https://placebear.com/200/200" name="field" value="three">Extension </label>
    <label><input type="checkbox" image="https://placebear.com/200/300" name="field" value="four">Treadmill</label>
    <label><input type="checkbox" image="https://placebear.com/300/250" name="field" value="five">Stairs </label>
  </form>
</div>
<div id="imagetest">
</div>


来源: stackexchange

问:
MySQL Partitioning in a real-world example
I want to try MySQL Partitioning in a football fantasy game where users are distributed in leagues, and each league has a market where users can sell or buy players. I'm experiencing some deadlocks in this table when a lot of users play at the same time (there are about 50K leagues at the time of writing, each one with about 20 players in the market refreshed every two days), so I was thinking about using MySQL Partitioning, which I haven't used before.

This is the table I would like to partition:

```<code>CREATE TABLE `market` (
  `leagueID` int(10) unsigned NOT NULL,
  `playerID` smallint(5) unsigned NOT NULL,
  `userID` int(10) unsigned DEFAULT,
  `price` int(10) unsigned NOT NULL ,
  `date` int(10) unsigned NOT NULL,
  UNIQUE KEY `league_player` (`leagueID`,`playerID`),
  KEY `user_date` (`userID`,`date`)
);
</code>```

Which approach (column, ranges, number of partitions, etc.) do you recommend?

This is my initial approach:

```<code>ALTER TABLE market
    PARTITION BY HASH(leagueID)
    PARTITIONS 10;
</code>```

答:
I've seen something similar a couple times now, and I'm not convinced that partitioning will solve your problem.

The deadlock you're seeing on the unique index might be due to two non-conflict-violating inserts using the same database page which the lock is on.  Due to the B-tree structure of the index, if a single league is write heavy in a particular window in time (seems plausible), there is a higher probability that there will be a race condition for the mutex on that page being hit.

I'd consider distributing the index "hot spot" physically by changing the order of the two fields in the unique constraint, and adding the existing index as a regular index (for lookup reasons).

```<code>ALTER TABLE `market`
ADD UNIQUE KEY player_league (`playerID`,`leagueID`),
DROP UNIQUE KEY `league_player`,
ADD KEY league_player (`leagueID`,`playerID`);
</code>```

On that note, as you don't have a primary key yet (but InnoDB is gonna create one behind the scenes anyway), it logically makes sense for the new key to take on that role.

```<code>ALTER TABLE `market`
ADD PRIMARY KEY (`playerID`,`leagueID`),
DROP UNIQUE KEY `league_player`,
ADD KEY league_player (`leagueID`,`playerID`);
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to try MySQL Partitioning in a football fantasy game where users are distributed in leagues, and each league has a market where users can sell or buy players. I'm experiencing some deadlocks in this table when a lot of users play at the same time (there are about 50K leagues at the time of writing, each one with about 20 players in the market refreshed every two days), so I was thinking about using MySQL Partitioning, which I haven't used before.

This is the table I would like to partition:

CREATE TABLE `market` (
  `leagueID` int(10) unsigned NOT NULL,
  `playerID` smallint(5) unsigned NOT NULL,
  `userID` int(10) unsigned DEFAULT,
  `price` int(10) unsigned NOT NULL ,
  `date` int(10) unsigned NOT NULL,
  UNIQUE KEY `league_player` (`leagueID`,`playerID`),
  KEY `user_date` (`userID`,`date`)
);

Which approach (column, ranges, number of partitions, etc.) do you recommend?

This is my initial approach:

ALTER TABLE market
    PARTITION BY HASH(leagueID)
    PARTITIONS 10;

Body:
I've seen something similar a couple times now, and I'm not convinced that partitioning will solve your problem.

The deadlock you're seeing on the unique index might be due to two non-conflict-violating inserts using the same database page which the lock is on.  Due to the B-tree structure of the index, if a single league is write heavy in a particular window in time (seems plausible), there is a higher probability that there will be a race condition for the mutex on that page being hit.

I'd consider distributing the index "hot spot" physically by changing the order of the two fields in the unique constraint, and adding the existing index as a regular index (for lookup reasons).

ALTER TABLE `market`
ADD UNIQUE KEY player_league (`playerID`,`leagueID`),
DROP UNIQUE KEY `league_player`,
ADD KEY league_player (`leagueID`,`playerID`);

On that note, as you don't have a primary key yet (but InnoDB is gonna create one behind the scenes anyway), it logically makes sense for the new key to take on that role.

ALTER TABLE `market`
ADD PRIMARY KEY (`playerID`,`leagueID`),
DROP UNIQUE KEY `league_player`,
ADD KEY league_player (`leagueID`,`playerID`);


问:
File validation in python, the better approach and why
I am working on a project for work that involves the parsing of a file for insertion into our local database. In an effort to write efficient robust code I am trying to see what the best approach is for validating the file. I have written two python scripts:

```<code>EXPECTED = 'PubNo|Name|CoverID|Issue|CustomLabel|Split'

with open('test.txt', 'r') as f:
    lines = f.readlines()

test = lines[0].replace(" ", "").strip()

if test[-1] == '|' or test[0] == '|':
    test = test.strip('|')

if test.lower() == EXPECTED.lower():
    print 'Successful Match!'
else:
    print 'Bad match :('
</code>```

and

```<code>import re

with open('test.txt', 'r') as f:
    lines = f.readlines()

patt = re.compile(r"\|?PubNo\|Name\|CoverID\|Issue\|CustomLabel\|Split\|?", re.I)

test = re.sub(r"\s", "", lines[0])
m = re.match(patt, test)

if m.group():
    print 'Successful Match!'
else:
    print 'Bad match :('
</code>```

As I hope is obvious, I am using simple string literal comparisons with various formatting done to ensure some safety, as well as a version that relies purely on regex's. Could anyone explain the pros and cons of these two approaches? They both take the same amount of time to execute and are both fairly readable. The only advantage I can see so far is that using regex's means not having to do so much manual formatting prior to comparing string literals.

答:
Assuming you don't see a problem of loading the whole file, and assuming you fix your regex (the way you presented it the program would break on non-match, you should check if there was a match, not if there is a group within it) those two are not the same. Consider the first line of your file being:

```<code>PubNo | Name | CoverID | Issue | CustomLabel | Split | SomethingMore
</code>```

Your regex 'validator' will mark it successful, your string compare won't. If you want your first column 'validator' to match precisely that string and nothing else, you have to change your regex pattern to r"\|?PubNo\|Name\|CoverID\|Issue\|CustomLabel\|Split\|?$". Also, your regex 'validator' will consume all the whitespace characters in the 'replacement' part including tabs, which your string comparator won't.

All things being equal - string search will be considerably faster in both cases - and that is not counting loading of the regex engine, preparing the patterns and all other supporting structures needed. Even if you cache the pattern, and remove all of the disadvantages of regex, string compare will still be faster. Consider a setup like:

```<code>import re

VALID = "PubNo|Name|CoverID|Issue|CustomLabel|Split"

# prepare the regex patterns
PATTERN_VALID = re.compile(r"\|?{}\|?".format(VALID.replace("|", r"\|")))
PATTERN_STRICT = re.compile(PATTERN_VALID.pattern + "$", re.I)
CLEAR_WHITESPACE = re.compile(r"\s")

# let's not disadvantage the string compare, too
VALID_LOWER = VALID.lower()

def string_valid(data):
    if data.strip("| ").replace(" ", "").lower().startswith(VALID_LOWER):
        return True
    return False

def string_valid_strict(data):
    if data.strip("| \r\n").replace(" ", "").lower() == VALID_LOWER:
        return True
    return False

def regexp_valid(data):
    if PATTERN_VALID.match(CLEAR_WHITESPACE.sub("", data)):
        return True
    return False

def regexp_valid_strict(data):
    if PATTERN_STRICT.match(CLEAR_WHITESPACE.sub("", data)):
        return True
    return False
</code>```

This would cover both cases (strict and matching the beginning only) with both approaches. You weren't considering building your regex pattern to ignore whitespace so you wouldn't need substitution, but it wouldn't speed it up considerably (actually, it will probably run slower than this).

So now if you have 3 files, say good.txt, strict.txt and bad.txt that cover all three cases, you can run an ad-hoc test like this:

```<code># open test files and only get the first lines
with open("good.txt", "r") as g, open("strict.txt", "r") as s, open("bad.txt", "r") as b:
    g = g.readline()  # overwrite is perfectly fine for our test
    s = s.readline()  # overwrite is perfectly fine for our test
    b = b.readline()  # overwrite is perfectly fine for our test

# make sure our functions perform adequately
assert string_valid(g) is regexp_valid(g) is True
assert string_valid_strict(g) is regexp_valid_strict(g) is False
assert string_valid(s) is regexp_valid(s) is True
assert string_valid_strict(s) is regexp_valid_strict(s) is True
assert string_valid(b) is regexp_valid(b) is False
assert string_valid_strict(b) is regexp_valid_strict(b) is False
</code>```

And if you time the calls for each of those (so 3 calls, with 3 different lines per loop) over, say, 100,000 loops you get:

```<code>Python 2.7.11

string_valid:        100,000 loops: 0.31 s, per loop:  3.15 µs
string_valid_strict: 100,000 loops: 0.27 s, per loop:  2.76 µs
regexp_valid:        100,000 loops: 1.34 s, per loop: 13.44 µs
regexp_valid_strict: 100,000 loops: 1.38 s, per loop: 13.83 µs

==

Python 3.5.1

string_valid:        100,000 loops: 0.37 s, per loop:  3.73 µs
string_valid_strict: 100,000 loops: 0.33 s, per loop:  3.37 µs
regexp_valid:        100,000 loops: 1.13 s, per loop: 11.28 µs
regexp_valid_strict: 100,000 loops: 1.22 s, per loop: 12.17 µs
</code>```

And this is the best case scenario for regex - we're even compiling the whitespace removing pattern. OTOH, string search can be optimized even more (slicing instead of startswith() for the non-strict example, etc.).

Regular expressions are great, but only when needed. There is no reason to utilize regex to solve simple problems like this one.

Body:
I am working on a project for work that involves the parsing of a file for insertion into our local database. In an effort to write efficient robust code I am trying to see what the best approach is for validating the file. I have written two python scripts:

EXPECTED = 'PubNo|Name|CoverID|Issue|CustomLabel|Split'

with open('test.txt', 'r') as f:
    lines = f.readlines()

test = lines[0].replace(" ", "").strip()

if test[-1] == '|' or test[0] == '|':
    test = test.strip('|')

if test.lower() == EXPECTED.lower():
    print 'Successful Match!'
else:
    print 'Bad match :('

and

import re

with open('test.txt', 'r') as f:
    lines = f.readlines()

patt = re.compile(r"\|?PubNo\|Name\|CoverID\|Issue\|CustomLabel\|Split\|?", re.I)

test = re.sub(r"\s", "", lines[0])
m = re.match(patt, test)

if m.group():
    print 'Successful Match!'
else:
    print 'Bad match :('

As I hope is obvious, I am using simple string literal comparisons with various formatting done to ensure some safety, as well as a version that relies purely on regex's. Could anyone explain the pros and cons of these two approaches? They both take the same amount of time to execute and are both fairly readable. The only advantage I can see so far is that using regex's means not having to do so much manual formatting prior to comparing string literals.

Body:
Assuming you don't see a problem of loading the whole file, and assuming you fix your regex (the way you presented it the program would break on non-match, you should check if there was a match, not if there is a group within it) those two are not the same. Consider the first line of your file being:

PubNo | Name | CoverID | Issue | CustomLabel | Split | SomethingMore

Your regex 'validator' will mark it successful, your string compare won't. If you want your first column 'validator' to match precisely that string and nothing else, you have to change your regex pattern to r"\|?PubNo\|Name\|CoverID\|Issue\|CustomLabel\|Split\|?$". Also, your regex 'validator' will consume all the whitespace characters in the 'replacement' part including tabs, which your string comparator won't.

All things being equal - string search will be considerably faster in both cases - and that is not counting loading of the regex engine, preparing the patterns and all other supporting structures needed. Even if you cache the pattern, and remove all of the disadvantages of regex, string compare will still be faster. Consider a setup like:

import re

VALID = "PubNo|Name|CoverID|Issue|CustomLabel|Split"

# prepare the regex patterns
PATTERN_VALID = re.compile(r"\|?{}\|?".format(VALID.replace("|", r"\|")))
PATTERN_STRICT = re.compile(PATTERN_VALID.pattern + "$", re.I)
CLEAR_WHITESPACE = re.compile(r"\s")

# let's not disadvantage the string compare, too
VALID_LOWER = VALID.lower()

def string_valid(data):
    if data.strip("| ").replace(" ", "").lower().startswith(VALID_LOWER):
        return True
    return False

def string_valid_strict(data):
    if data.strip("| \r\n").replace(" ", "").lower() == VALID_LOWER:
        return True
    return False

def regexp_valid(data):
    if PATTERN_VALID.match(CLEAR_WHITESPACE.sub("", data)):
        return True
    return False

def regexp_valid_strict(data):
    if PATTERN_STRICT.match(CLEAR_WHITESPACE.sub("", data)):
        return True
    return False

This would cover both cases (strict and matching the beginning only) with both approaches. You weren't considering building your regex pattern to ignore whitespace so you wouldn't need substitution, but it wouldn't speed it up considerably (actually, it will probably run slower than this).

So now if you have 3 files, say good.txt, strict.txt and bad.txt that cover all three cases, you can run an ad-hoc test like this:

# open test files and only get the first lines
with open("good.txt", "r") as g, open("strict.txt", "r") as s, open("bad.txt", "r") as b:
    g = g.readline()  # overwrite is perfectly fine for our test
    s = s.readline()  # overwrite is perfectly fine for our test
    b = b.readline()  # overwrite is perfectly fine for our test

# make sure our functions perform adequately
assert string_valid(g) is regexp_valid(g) is True
assert string_valid_strict(g) is regexp_valid_strict(g) is False
assert string_valid(s) is regexp_valid(s) is True
assert string_valid_strict(s) is regexp_valid_strict(s) is True
assert string_valid(b) is regexp_valid(b) is False
assert string_valid_strict(b) is regexp_valid_strict(b) is False

And if you time the calls for each of those (so 3 calls, with 3 different lines per loop) over, say, 100,000 loops you get:

Python 2.7.11

string_valid:        100,000 loops: 0.31 s, per loop:  3.15 µs
string_valid_strict: 100,000 loops: 0.27 s, per loop:  2.76 µs
regexp_valid:        100,000 loops: 1.34 s, per loop: 13.44 µs
regexp_valid_strict: 100,000 loops: 1.38 s, per loop: 13.83 µs

==

Python 3.5.1

string_valid:        100,000 loops: 0.37 s, per loop:  3.73 µs
string_valid_strict: 100,000 loops: 0.33 s, per loop:  3.37 µs
regexp_valid:        100,000 loops: 1.13 s, per loop: 11.28 µs
regexp_valid_strict: 100,000 loops: 1.22 s, per loop: 12.17 µs

And this is the best case scenario for regex - we're even compiling the whitespace removing pattern. OTOH, string search can be optimized even more (slicing instead of startswith() for the non-strict example, etc.).

Regular expressions are great, but only when needed. There is no reason to utilize regex to solve simple problems like this one.


问:
DSC: Applying one config to various operating systems
This problem has occurred during learning, so I am not sure how likely it is in the real world, but I am still interested to know the best way to handle this sort of thing.

I have the following composite configuration:

```<code>configuration hDefaultServer {
    Param
    (
        [Parameter(Mandatory)]
        [string]$myFileName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [String]$Ensure = "Present"
    )

    WindowsFeature 'InstallGUI'
    {
        Ensure = $Ensure
        Name = 'Server-Gui-Shell'
    }
    File 'Temp'
    {
        Type = 'Directory'
        DestinationPath = "$($env:SystemDrive)\Temp"
        Ensure = $Ensure
    }
    File 'SomeFile'
    {
        Type = 'File'
        DestinationPath = "$($env:SystemDrive)\Temp\$myFileName"
        Contents = 'This file was created by DSC!'
        Ensure = $Ensure
    }
}
</code>```

And compile it into its .MOF with:

```<code>$ConfigData = @{
   AllNodes = @(
      @{ NodeName = "*"; PsDscAllowPlainTextPassword = $true },
      @{ NodeName = 'WMF5-1' }
   )
}

    Configuration DemoDefaultServer
    {
        Param
        (
            [string]$FileName
        )

        Import-DscResource -Name hDefaultServer

        hDefaultServer Demo2
        {
            myFileName = $FileName
            Ensure = "Present"
        }
    }

    DemoDefaultserver -ConfigurationData $ConfigData -OutputPath C:\Configurations\DemoDefaultServer -filename "SomeOtherFile.txt"
</code>```

When I run it on a Windows 10 box, it completes the file and folder stuff, but errors as ServerManager doesn't exist on Windows 10 client:

```<code>PowerShell DSC resource MSFT_RoleResource  failed to execute Test-TargetResource functionality with error message: Installing roles and features using PowerShell Desired State Configuration is supported only on Server
SKU's. It is not supported on Client SKU.
</code>```

Which is fair enough. What is the best way to handle a case like this?

If I do something like this:

```<code>configuration hDefaultServer {
    [cmdletbinding()]
    Param
    (
        [Parameter(Mandatory)]
        [string]$myFileName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [String]$Ensure = "Present"
    )

    $ProductType = (Get-WmiObject -Class Win32_OperatingSystem).ProductType

    If($ProductType -eq 1)
    {
        Write-Verbose "Client OS ($ProductType)"
    }
    elseif($ProductType -eq 2)
    {
        Write-Verbose "Domain Controller ($ProductType)"

        WindowsFeature 'InstallGUI'
        {
            Ensure = $Ensure
            Name = 'Server-Gui-Shell'
        }
    }
    else
    {
        Write-Verbose "Server OS ($ProductType)"

        WindowsFeature 'InstallGUI'
        {
            Ensure = $Ensure
            Name = 'Server-Gui-Shell'
        }
    }
    File 'Temp'
    {
        Type = 'Directory'
        DestinationPath = "$($env:SystemDrive)\Temp"
        Ensure = $Ensure
    }
    File 'SomeFile'
    {
        Type = 'File'
        DestinationPath = "$($env:SystemDrive)\Temp\$myFileName"
        Contents = 'This file was created by DSC!'
        Ensure = $Ensure
    }
}
</code>```

At compile time, the .MOF file is adjusted accordingly. i.e. the InstallGUI section is added or removed.

There is also DependsOn, but from reading, I believe this is to define the order of application within the scope of a configuration. I haven't worked out the pattern on how this works, but for instance, I wanted to make sure the folder was created before the file, I could do (and just to prove it, I've changed the order so the file is listed before the folder):

```<code>configuration hDefaultServer {
    [cmdletbinding()]
    Param
    (
        [Parameter(Mandatory)]
        [string]$myFileName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [String]$Ensure = "Present"
    )

    $ProductType = (Get-WmiObject -Class Win32_OperatingSystem).ProductType

    If($ProductType -eq 1)
    {
        Write-Verbose "Client OS ($ProductType)"
    }
    elseif($ProductType -eq 2)
    {
        Write-Verbose "Domain Controller ($ProductType)"

        WindowsFeature 'InstallGUI'
        {
            Ensure = $Ensure
            Name = 'Server-Gui-Shell'
        }
    }
    else
    {
        Write-Verbose "Server OS ($ProductType)"

        WindowsFeature 'InstallGUI'
        {
            Ensure = $Ensure
            Name = 'Server-Gui-Shell'
        }
    }
    File 'SomeFile'
    {
        Type = 'File'
        DestinationPath = "$($env:SystemDrive)\Temp\$myFileName"
        Contents = 'This file was created by DSC!'
        Ensure = $Ensure
        DependsOn = "[File]Temp"
    }
    File 'Temp'
    {
        Type = 'Directory'
        DestinationPath = "$($env:SystemDrive)\Temp"
        Ensure = $Ensure
    }
}
</code>```

Is there a way with Try / Catch? Similar to the if statement. I did try it, but the .MOF contained the InstallGUI section.

I believe there's probably a better way using ConfigurationData. Something like:

```<code>$configData{
    AllNodes = @(
        @{
            NodeName = "WIN-AQEKG7L9SE8"
            Role = "Setup, WindowsFeatures, IE, SqlServer"
         }
    (
}
</code>```

But I haven't worked this bit out yet. All the examples I have found, using this, seem to use "Role", that I believe is part of ServerManager and therefore not available on Windows 10.

TIA.

答:
I think it would be a good idea to create TWO different DSCs.
It makes no sense to do this type of check.

A DSC is used for mass configuration. Configure 10 web servers, configure 10 sql servers, etc.

Body:
This problem has occurred during learning, so I am not sure how likely it is in the real world, but I am still interested to know the best way to handle this sort of thing.

I have the following composite configuration:

configuration hDefaultServer {
    Param
    (
        [Parameter(Mandatory)]
        [string]$myFileName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [String]$Ensure = "Present"
    )

    WindowsFeature 'InstallGUI'
    {
        Ensure = $Ensure
        Name = 'Server-Gui-Shell'
    }
    File 'Temp'
    {
        Type = 'Directory'
        DestinationPath = "$($env:SystemDrive)\Temp"
        Ensure = $Ensure
    }
    File 'SomeFile'
    {
        Type = 'File'
        DestinationPath = "$($env:SystemDrive)\Temp\$myFileName"
        Contents = 'This file was created by DSC!'
        Ensure = $Ensure
    }
}

And compile it into its .MOF with:

$ConfigData = @{
   AllNodes = @(
      @{ NodeName = "*"; PsDscAllowPlainTextPassword = $true },
      @{ NodeName = 'WMF5-1' }
   )
}

    Configuration DemoDefaultServer
    {
        Param
        (
            [string]$FileName
        )

        Import-DscResource -Name hDefaultServer

        hDefaultServer Demo2
        {
            myFileName = $FileName
            Ensure = "Present"
        }
    }

    DemoDefaultserver -ConfigurationData $ConfigData -OutputPath C:\Configurations\DemoDefaultServer -filename "SomeOtherFile.txt"

When I run it on a Windows 10 box, it completes the file and folder stuff, but errors as ServerManager doesn't exist on Windows 10 client:

PowerShell DSC resource MSFT_RoleResource  failed to execute Test-TargetResource functionality with error message: Installing roles and features using PowerShell Desired State Configuration is supported only on Server
SKU's. It is not supported on Client SKU.

Which is fair enough. What is the best way to handle a case like this?

If I do something like this:

configuration hDefaultServer {
    [cmdletbinding()]
    Param
    (
        [Parameter(Mandatory)]
        [string]$myFileName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [String]$Ensure = "Present"
    )

    $ProductType = (Get-WmiObject -Class Win32_OperatingSystem).ProductType

    If($ProductType -eq 1)
    {
        Write-Verbose "Client OS ($ProductType)"
    }
    elseif($ProductType -eq 2)
    {
        Write-Verbose "Domain Controller ($ProductType)"

        WindowsFeature 'InstallGUI'
        {
            Ensure = $Ensure
            Name = 'Server-Gui-Shell'
        }
    }
    else
    {
        Write-Verbose "Server OS ($ProductType)"

        WindowsFeature 'InstallGUI'
        {
            Ensure = $Ensure
            Name = 'Server-Gui-Shell'
        }
    }
    File 'Temp'
    {
        Type = 'Directory'
        DestinationPath = "$($env:SystemDrive)\Temp"
        Ensure = $Ensure
    }
    File 'SomeFile'
    {
        Type = 'File'
        DestinationPath = "$($env:SystemDrive)\Temp\$myFileName"
        Contents = 'This file was created by DSC!'
        Ensure = $Ensure
    }
}

At compile time, the .MOF file is adjusted accordingly. i.e. the InstallGUI section is added or removed.

There is also DependsOn, but from reading, I believe this is to define the order of application within the scope of a configuration. I haven't worked out the pattern on how this works, but for instance, I wanted to make sure the folder was created before the file, I could do (and just to prove it, I've changed the order so the file is listed before the folder):

configuration hDefaultServer {
    [cmdletbinding()]
    Param
    (
        [Parameter(Mandatory)]
        [string]$myFileName,

        [Parameter()]
        [ValidateSet("Present","Absent")]
        [String]$Ensure = "Present"
    )

    $ProductType = (Get-WmiObject -Class Win32_OperatingSystem).ProductType

    If($ProductType -eq 1)
    {
        Write-Verbose "Client OS ($ProductType)"
    }
    elseif($ProductType -eq 2)
    {
        Write-Verbose "Domain Controller ($ProductType)"

        WindowsFeature 'InstallGUI'
        {
            Ensure = $Ensure
            Name = 'Server-Gui-Shell'
        }
    }
    else
    {
        Write-Verbose "Server OS ($ProductType)"

        WindowsFeature 'InstallGUI'
        {
            Ensure = $Ensure
            Name = 'Server-Gui-Shell'
        }
    }
    File 'SomeFile'
    {
        Type = 'File'
        DestinationPath = "$($env:SystemDrive)\Temp\$myFileName"
        Contents = 'This file was created by DSC!'
        Ensure = $Ensure
        DependsOn = "[File]Temp"
    }
    File 'Temp'
    {
        Type = 'Directory'
        DestinationPath = "$($env:SystemDrive)\Temp"
        Ensure = $Ensure
    }
}

Is there a way with Try / Catch? Similar to the if statement. I did try it, but the .MOF contained the InstallGUI section.

I believe there's probably a better way using ConfigurationData. Something like:

$configData{
    AllNodes = @(
        @{
            NodeName = "WIN-AQEKG7L9SE8"
            Role = "Setup, WindowsFeatures, IE, SqlServer"
         }
    (
}

But I haven't worked this bit out yet. All the examples I have found, using this, seem to use "Role", that I believe is part of ServerManager and therefore not available on Windows 10.

TIA.


问:
Can I use two different TTK themes in one Tkinter (tk.Tk) root window?
This question concerns Python and Tkinter.

I'd like to use two different ttk themes simultaneously, e.g. 'clam' and 'vista' in one Tkinter window. So I wrote this:

```<code>import tkinter as tk
import tkinter.ttk as ttk

class GUI(tk.Tk):

    def __init__(self):

        super().__init__()
        Button_v1()
        Button_v2()

class Button_v1(ttk.Button):

    def __init__(self, default_text="Test"):

        super().__init__(text=default_text)

        s = ttk.Style()
        s.theme_use('clam')
        s.configure(self.winfo_class(), foreground='blue')
        self.pack()

class Button_v2(ttk.Button):

    def __init__(self, default_text="Test2"):

        super().__init__(text=default_text)

        s2 = ttk.Style()
        s2.theme_use('vista')
        s2.configure(self.winfo_class(), foreground='red')
        self.pack()

GUI().mainloop()
</code>```

The code loads, however:

I expected the first Button's foreground to be blue and the second Button's foreground to be red, and for two separate themes to be used.

Instead, both buttons have a red foreground, and both apply the same theme.

Is it possible to use two separate ttk themes in one Tkinter program?

答:
No, it is not possible to use two different themes at the same time.

From the canonical documentation [1] for the function underlying the theme_use method (emphasis added by me):

Without an argument the result is the name of the current theme. Otherwise this command sets the current theme to themeName, and refreshes all widgets.

Here is a simple example showing how you can switch themes on the fly:

```<code># python  2
import Tkinter as tk
import ttk

# python 3
#import tkinter as tk
#import tkinter.ttk as ttk

def switch_theme(theme):
    style = ttk.Style()
    style.theme_use(theme)

root = tk.Tk()

style = ttk.Style()
for theme in style.theme_names():
    button = ttk.Button(root, text=theme,
                        command=lambda theme=theme: switch_theme(theme))
    button.pack(side="top", padx=4, pady=4)

root.mainloop()
</code>```

Body:
This question concerns Python and Tkinter.

I'd like to use two different ttk themes simultaneously, e.g. 'clam' and 'vista' in one Tkinter window. So I wrote this:

import tkinter as tk
import tkinter.ttk as ttk

class GUI(tk.Tk):

    def __init__(self):

        super().__init__()
        Button_v1()
        Button_v2()

class Button_v1(ttk.Button):

    def __init__(self, default_text="Test"):

        super().__init__(text=default_text)

        s = ttk.Style()
        s.theme_use('clam')
        s.configure(self.winfo_class(), foreground='blue')
        self.pack()

class Button_v2(ttk.Button):

    def __init__(self, default_text="Test2"):

        super().__init__(text=default_text)

        s2 = ttk.Style()
        s2.theme_use('vista')
        s2.configure(self.winfo_class(), foreground='red')
        self.pack()

GUI().mainloop()

The code loads, however:

I expected the first Button's foreground to be blue and the second Button's foreground to be red, and for two separate themes to be used.

Instead, both buttons have a red foreground, and both apply the same theme.

Is it possible to use two separate ttk themes in one Tkinter program?

Body:
No, it is not possible to use two different themes at the same time.

From the canonical documentation [1] for the function underlying the theme_use method (emphasis added by me):

Without an argument the result is the name of the current theme. Otherwise this command sets the current theme to themeName, and refreshes all widgets.

Here is a simple example showing how you can switch themes on the fly:

# python  2
import Tkinter as tk
import ttk

# python 3
#import tkinter as tk
#import tkinter.ttk as ttk

def switch_theme(theme):
    style = ttk.Style()
    style.theme_use(theme)

root = tk.Tk()

style = ttk.Style()
for theme in style.theme_names():
    button = ttk.Button(root, text=theme,
                        command=lambda theme=theme: switch_theme(theme))
    button.pack(side="top", padx=4, pady=4)

root.mainloop()


问:
Unable to find a @SpringBootConfiguration when doing a JpaTest
I'm trying to run a simple Junit test to see if my CrudRepositories are indeed working.

The error I keep getting is:

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
java.lang.IllegalStateException

Doesn't Spring Boot configure itself?

My Test Class:

```<code>@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class JpaTest {

@Autowired
private AccountRepository repository;

@After
public void clearDb(){
    repository.deleteAll();
}

 @Test
 public void createAccount(){
     long id = 12;
     Account u = new Account(id,"Tim Viz");
     repository.save(u);

     assertEquals(repository.findOne(id),u);

 }

 @Test
 public void findAccountByUsername(){
     long id = 12;
     String username = "Tim Viz";
     Account u = new Account(id,username);
     repository.save(u);

     assertEquals(repository.findByUsername(username),u);

 }

</code>```

My Spring Boot application starter:

```<code>@SpringBootApplication
@EnableJpaRepositories(basePackages = {"domain.repositories"})
@ComponentScan(basePackages = {"controllers","domain"})
@EnableWebMvc
@PropertySources(value    {@PropertySource("classpath:application.properties")})
    @EntityScan(basePackages={"domain"})
    public class Application extends SpringBootServletInitializer {
        public static void main(String[] args) {
            ApplicationContext ctx = SpringApplication.run(Application.class, args);

        }
    }
</code>```

My Repository:

```<code>public interface AccountRepository extends CrudRepository<Account,Long> {

    public Account findByUsername(String username);

    }
}
</code>```

答:
In addition to what Thomas Kåsene said, you can also add

```<code>@SpringBootTest(classes=com.package.path.class)
</code>```

to the test annotation to specify where it should look for the other class if you didn't want to refactor your file hierarchy. This is what the error message hints at by saying:

```<code>Unable to find a @SpringBootConfiguration, you need to use
@ContextConfiguration or @SpringBootTest(classes=...) ...
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm trying to run a simple Junit test to see if my CrudRepositories are indeed working.

The error I keep getting is:

Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
java.lang.IllegalStateException

Doesn't Spring Boot configure itself?

My Test Class:

@RunWith(SpringRunner.class)
@DataJpaTest
@SpringBootTest(webEnvironment = WebEnvironment.RANDOM_PORT)
public class JpaTest {

@Autowired
private AccountRepository repository;

@After
public void clearDb(){
    repository.deleteAll();
}

 @Test
 public void createAccount(){
     long id = 12;
     Account u = new Account(id,"Tim Viz");
     repository.save(u);

     assertEquals(repository.findOne(id),u);

 }

 @Test
 public void findAccountByUsername(){
     long id = 12;
     String username = "Tim Viz";
     Account u = new Account(id,username);
     repository.save(u);

     assertEquals(repository.findByUsername(username),u);

 }

My Spring Boot application starter:

@SpringBootApplication
@EnableJpaRepositories(basePackages = {"domain.repositories"})
@ComponentScan(basePackages = {"controllers","domain"})
@EnableWebMvc
@PropertySources(value    {@PropertySource("classpath:application.properties")})
    @EntityScan(basePackages={"domain"})
    public class Application extends SpringBootServletInitializer {
        public static void main(String[] args) {
            ApplicationContext ctx = SpringApplication.run(Application.class, args);

        }
    }

My Repository:

public interface AccountRepository extends CrudRepository<Account,Long> {

    public Account findByUsername(String username);

    }
}

Body:
In addition to what Thomas Kåsene said, you can also add

@SpringBootTest(classes=com.package.path.class)

to the test annotation to specify where it should look for the other class if you didn't want to refactor your file hierarchy. This is what the error message hints at by saying:

Unable to find a @SpringBootConfiguration, you need to use
@ContextConfiguration or @SpringBootTest(classes=...) ...


问:
Data type mismatch on a join using dates
I have a function, lastday, that returns the last day of a given month. Code below...

```<code>Function lastday(dteAny As Date) As Date
lastday = DateSerial(Year(dteAny), Month(dteAny) + 1, 1) - 1
End Function
</code>```

I am attempting to run a query you see below..

```<code>Select cc.cred_id,  lastday(dateadd("m", 5, date())) as [due],
lastday(dateadd("m", 36, a.activity_date)) as [report]

from cred_core as cc

inner join activity as a on (a.cred_id = cc.cred_id and a.activity_type =
"recred sent" and lastday(dateadd("m", 5, date())) = lastday(dateadd("m",
36, a.activity_date)) )
</code>```

I get an error alerting me of a data type mismatch on the second half of the join, where I use the lastday function.

I tried surrounding the lastday function with the # delimeters hoping that it would convert it to something it could actually compare, but I assume those delimeters don't work on functions?

Any idea what I can do to solve this problem? activity_date is, of course, a date/time data type. Using Access 2007-2013.

答:
Those type of joins are not supported in Access. Try to set the dates in criteria.</p>

```<code>SELECT cc.cred_id,  lastday(DateAdd("m", 5, Date())) As [due],
       lastday(DateAdd("m", 36, a.activity_date)) As [report]
FROM cred_core as cc INNER JOIN activity As a ON (a.cred_id = cc.cred_id)
WHERE a.activity_type = "recred sent"
  AND lastday(DateAdd("m", 5, date())) = lastday(DateAdd("m", 36, a.activity_date));
</code>```

Body:
I have a function, lastday, that returns the last day of a given month. Code below...

Function lastday(dteAny As Date) As Date
lastday = DateSerial(Year(dteAny), Month(dteAny) + 1, 1) - 1
End Function

I am attempting to run a query you see below..

Select cc.cred_id,  lastday(dateadd("m", 5, date())) as [due],
lastday(dateadd("m", 36, a.activity_date)) as [report]

from cred_core as cc

inner join activity as a on (a.cred_id = cc.cred_id and a.activity_type =
"recred sent" and lastday(dateadd("m", 5, date())) = lastday(dateadd("m",
36, a.activity_date)) )

I get an error alerting me of a data type mismatch on the second half of the join, where I use the lastday function.

I tried surrounding the lastday function with the # delimeters hoping that it would convert it to something it could actually compare, but I assume those delimeters don't work on functions?

Any idea what I can do to solve this problem? activity_date is, of course, a date/time data type. Using Access 2007-2013.

Body:
Those type of joins are not supported in Access. Try to set the dates in criteria.

SELECT cc.cred_id,  lastday(DateAdd("m", 5, Date())) As [due],
       lastday(DateAdd("m", 36, a.activity_date)) As [report]
FROM cred_core as cc INNER JOIN activity As a ON (a.cred_id = cc.cred_id)
WHERE a.activity_type = "recred sent"
  AND lastday(DateAdd("m", 5, date())) = lastday(DateAdd("m", 36, a.activity_date));


问:
PHP, PDO Building right query for displaying most popular topics
I almost made it by unfortunately I stuck and spent hours on unsuccessful attempts to make it work right :(

So, I'm making a forum/blog. Users can create topics and discuss them with the comments. And I wanna display most popular topics (7 for example), those that have most comments (will be perfect to make it show most popular topics for last week or something). The problem is my DB structure, topics and user_comments are different tables. Here is how it is approximately like:

```<code>topics:
- id
- title
- date

user_comments:
-id
-topic_id
-comment
-date
</code>```

topic_id in user_comments is used to define to which topic comments belong. What I'm trying is to select all topic_id from user_comments that have most comments of all and use it to display title of the most popular topics.
Here is my code example:

```<code>$stmt = $db->prepare('SELECT topic_id FROM user_comments ORDER BY comment DESC LIMIT 7');
$stmt->execute();
$topicsID = $stmt->fetchAll();

foreach ($topicsID as $row) {
  // Problem is starting here, it displays topic_id multiple times
  echo 'Most popular topic is: ' . $row['topic_id'] . '<br>';
  $topic_id = $row['topic_id'];
}
  $stmt = $db->prepare('SELECT title FROM topics WHERE id = :topic_id');
  $stmt->bindValue(':topic_id', $topic_id);
  $stmt->execute();
  $title = $stmt->fetchAll();

  foreach ($title as $row) {
    echo 'Most popular topic title is: ' . $row['title'] . '<br>';
  }
</code>```

At the moment it displays every topic multiple times (like one time per comment or something). I will be very happy for any help, thanks everyone!

答:
you could obtain with a single query  with join .. count and group by</p>

```<code>  SELECT t.title, count(*)
  FROM topics t
  inner join user_comments  u on u.topic_id = t.id
  GROUP BY t.title
  ORDER BY count(*)  DESC
  LIMIT 7
</code>```

Body:
I almost made it by unfortunately I stuck and spent hours on unsuccessful attempts to make it work right :(

So, I'm making a forum/blog. Users can create topics and discuss them with the comments. And I wanna display most popular topics (7 for example), those that have most comments (will be perfect to make it show most popular topics for last week or something). The problem is my DB structure, topics and user_comments are different tables. Here is how it is approximately like:

topics:
- id
- title
- date

user_comments:
-id
-topic_id
-comment
-date

topic_id in user_comments is used to define to which topic comments belong. What I'm trying is to select all topic_id from user_comments that have most comments of all and use it to display title of the most popular topics.
Here is my code example:

$stmt = $db->prepare('SELECT topic_id FROM user_comments ORDER BY comment DESC LIMIT 7');
$stmt->execute();
$topicsID = $stmt->fetchAll();

foreach ($topicsID as $row) {
  // Problem is starting here, it displays topic_id multiple times
  echo 'Most popular topic is: ' . $row['topic_id'] . '
';
  $topic_id = $row['topic_id'];
}
  $stmt = $db->prepare('SELECT title FROM topics WHERE id = :topic_id');
  $stmt->bindValue(':topic_id', $topic_id);
  $stmt->execute();
  $title = $stmt->fetchAll();

  foreach ($title as $row) {
    echo 'Most popular topic title is: ' . $row['title'] . '
';
  }

At the moment it displays every topic multiple times (like one time per comment or something). I will be very happy for any help, thanks everyone!

Body:
you could obtain with a single query  with join .. count and group by

  SELECT t.title, count(*)
  FROM topics t
  inner join user_comments  u on u.topic_id = t.id
  GROUP BY t.title
  ORDER BY count(*)  DESC
  LIMIT 7


问:
libGDX: smooth movement if justTouched
I want to check if the touchscreen is touched and move the position of my texture. With the check input.isTouched() it works well and i get a smooth movement of my texture while my touchscreen is touched.

```<code>public void update() {
   if(input.isTouched()){
      x += 60 * Gdx.graphics.getDeltaTime()
   }
}

public void render(SpriteBatch batch){
   batch.begin();
   batch.draw(texture, x, y);
   batch.end();
}
</code>```

Now I want to implement the movement of my texture when input.justTouched(). In this case my texture will move in only one frame when i'm doing x += 600;. My idea is a second render method in my render method, but i think that's not efficient and honestly i don't really know how it works.

答:
```<code>if(Gdx.input.isTouched()){    // condition true when screen is currently touched.
    x += 60 * Gdx.graphics.getDeltaTime();
}
</code>```

So somehow we need to maintain condition/flag true for required number of frame to reach destination that is 600 in your case.

Having many possible solution to achieve this, and the simplest is :

```<code>public class GdxTest extends ApplicationAdapter {

   Texture texture;
   SpriteBatch spriteBatch;
   float x,y,endX;

   @Override
   public void create() {

      texture=new Texture("badlogic.jpg");
      spriteBatch=new SpriteBatch();
      y=20;
      x= endX=10;
   }

   @Override
   public void render() {

      Gdx.gl.glClearColor(1,1,1,1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      spriteBatch.begin();
      spriteBatch.draw(texture,x,y);
      spriteBatch.end();

      if(Gdx.input.justTouched()){   // when new touch down event just occurred.
        endX=600;  // give destination
      }

      if(x<endX){    // this condition will true unless x reaches endX or crossed
        x+=60 * Gdx.graphics.getDeltaTime();
      }
   }

   @Override
   public void dispose() {
       texture.dispose();
       spriteBatch.dispose();
   }
}
</code>```

Title: libGDX: smooth movement if justTouched

Body:
I want to check if the touchscreen is touched and move the position of my texture. With the check input.isTouched() it works well and i get a smooth movement of my texture while my touchscreen is touched.

public void update() {
   if(input.isTouched()){
      x += 60 * Gdx.graphics.getDeltaTime()
   }
}

public void render(SpriteBatch batch){
   batch.begin();
   batch.draw(texture, x, y);
   batch.end();
}

Now I want to implement the movement of my texture when input.justTouched(). In this case my texture will move in only one frame when i'm doing x += 600;. My idea is a second render method in my render method, but i think that's not efficient and honestly i don't really know how it works.

Body:
if(Gdx.input.isTouched()){    // condition true when screen is currently touched.
    x += 60 * Gdx.graphics.getDeltaTime();
}

So somehow we need to maintain condition/flag true for required number of frame to reach destination that is 600 in your case.

Having many possible solution to achieve this, and the simplest is :

public class GdxTest extends ApplicationAdapter {

   Texture texture;
   SpriteBatch spriteBatch;
   float x,y,endX;

   @Override
   public void create() {

      texture=new Texture("badlogic.jpg");
      spriteBatch=new SpriteBatch();
      y=20;
      x= endX=10;
   }

   @Override
   public void render() {

      Gdx.gl.glClearColor(1,1,1,1);
      Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);

      spriteBatch.begin();
      spriteBatch.draw(texture,x,y);
      spriteBatch.end();

      if(Gdx.input.justTouched()){   // when new touch down event just occurred.
        endX=600;  // give destination
      }

      if(x<endX){    // this condition will true unless x reaches endX or crossed
        x+=60 * Gdx.graphics.getDeltaTime();
      }
   }

   @Override
   public void dispose() {
       texture.dispose();
       spriteBatch.dispose();
   }
}


问:
ngIf-else in template
I'm trying to load pictureA or pictureB.
My first solution is like this:

```<code> <img *ngIf="my_picture" src="{{my_picture}}" width="180" height="80" >
 <img *ngIf="default_picture && !my_picture" src="{{default_picture}}">
</code>```

But I would like to use if-else like on API Reference:

```<code><div *ngIf="condition; else elseBlock">...</div>
<ng-template #elseBlock>...</ng-template>
</code>```

So, I'm trying to do it like this:

```<code> <div *ngIf="my_picture; else elseBlock">
     <img src="{{my_picture}}" >
 </div>
 <ng-template #elseBlock>
      <img src="{{default_picture}}" >
 </ng-template>
</code>```

But I'm getting a big exception stack trace:

```<code>zone.js:388 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngIfElse' since it isn't a known property of 'div'. ("
        -->

        <div [ERROR ->]*ngIf="my_picture; else elseBlock">
            <img src="{{my_picture}}"): UserComponent@15:13
Property binding ngIfElse not used by any directive on an embedded template. Make sure that the property name is spelled correctly and
</code>```

all directives are listed in the "@NgModule.declarations". ("
              -->

```<code>        [ERROR ->]<div *ngIf="my_picture; else elseBlock">
            <img src="{{my_picture}}" width="180" height="8"): UserComponent@15:8
'ng-template' is not a known element
</code>```

How can I implement a simple if-else block?

答:
ngIf/Else syntax is not available in angular 2 but is available in angular 4

For angular 2, you need to use ngIf two times, and in second time you negate the value being compared (not using the !=, but having ampersand with the value)

```<code><div class="text-center" *ngIf='userName'> Hello {{userName}}, how are you </div>
<div class="text-center" *ngIf='userName == ""'> Hello, please login to access the app</div>
</code>```

For angular 4 onwards

```<code><div *ngIf="userName; else showLoginRequestMessage">
  Hello {{userName}}, how are you
</div>
<ng-template #showLoginRequestMessage>
 <div class="text-center"> Hello, please login to access the app</div>
</ng-template>
</code>```

Title: ngIf-else in template

Body:
I'm trying to load pictureA or pictureB.
My first solution is like this:

But I would like to use if-else like on API Reference:

...

<ng-template #elseBlock>...</ng-template>

So, I'm trying to do it like this:

 <ng-template #elseBlock>

 </ng-template>

But I'm getting a big exception stack trace:

zone.js:388 Unhandled Promise rejection: Template parse errors:
Can't bind to 'ngIfElse' since it isn't a known property of 'div'. ("
        -->

]*ngIf="my_picture; else elseBlock">
            <img src="{{my_picture}}"): UserComponent@15:13
Property binding ngIfElse not used by any directive on an embedded template. Make sure that the property name is spelled correctly and

all directives are listed in the "@NgModule.declarations". ("
              -->

        [ERROR ->]

            <img src="{{my_picture}}" width="180" height="8"): UserComponent@15:8
'ng-template' is not a known element

How can I implement a simple if-else block?

Body:
ngIf/Else syntax is not available in angular 2 but is available in angular 4

For angular 2, you need to use ngIf two times, and in second time you negate the value being compared (not using the !=, but having ampersand with the value)

<div class="text-center" *ngIf='userName'> Hello {{userName}}, how are you </div>
<div class="text-center" *ngIf='userName == ""'> Hello, please login to access the app</div>

For angular 4 onwards

<div *ngIf="userName; else showLoginRequestMessage">
  Hello {{userName}}, how are you
</div>
<ng-template #showLoginRequestMessage>
 <div class="text-center"> Hello, please login to access the app</div>
</ng-template>


问:
Print stylish text on image in php
Is it possible to print html div tag with style on image in PHP?. if not, then what is the alternative way?</p>

答: There is no easy way to print text on images using html/css on server side, because php can't parse html, so you'd better find another solution like php GD.</p>

ContentLicense: CC BY-SA 2.5

Title: Print stylish text on image in php


问:
How to remove CRLF in Vi editor
I am copying  "E)H@McQfTjWnZr4t7w!z%C*F-JaNdRgU"  to a file using vi editor. The file size should be 32 bytes but its 33bytes. I opened the same file using notepad++ and found that CRLF is being added at the end of the text.

How can i remove CRLF in vi editor.

答:
Try this in vi

```<code>:set noendofline binary
:w
</code>```

This will remove any line endings from the file and give you the 32 byte file you're expecting to see.

Also note you can use these other commands to change the line ending types in vi as well.

```<code>:set ff=dos
:w
</code>```

Or

```<code>:set ff=unix
:w
</code>```

You can also do this from the commandline to perform on multiple files with something like

```<code>for file in $files; do
    vi +':w ++ff=unix' +':q' $file
done
</code>```

Title: How to remove CRLF in Vi editor

Body:
Try this in vi

:set noendofline binary
:w

This will remove any line endings from the file and give you the 32 byte file you're expecting to see.

Also note you can use these other commands to change the line ending types in vi as well.

:set ff=dos
:w

Or

:set ff=unix
:w

You can also do this from the commandline to perform on multiple files with something like

for file in $files; do
    vi +':w ++ff=unix' +':q' $file
done


问:
Rails 4 Routing within Namespace
I am trying to set the base address www.myplace.com/admin to be directed to www.myplace.com/admin/adminhub within the namespace coding below. I have tried every combination I can think of, but to no avail. I was trying to follow the same code used for the / of the app.

```<code>namespace :admin do
    ...
    get "adminhub"
    get 'admin', to: 'adminhub'

  end
</code>```

答:
Sounds like you want to redirect the browser to the new URL. You can do this with the redirect helper in the routes.

```<code>get '/admin', to: redirect('/admin/adminhub')
</code>```

This allows you to redirect from one path to another. See the Redirection section in the Rails Routing Guide for more details.

Title: Rails 4 Routing within Namespace

Body:
I am trying to set the base address www.myplace.com/admin to be directed to www.myplace.com/admin/adminhub within the namespace coding below. I have tried every combination I can think of, but to no avail. I was trying to follow the same code used for the / of the app.

namespace :admin do
    ...
    get "adminhub"
    get 'admin', to: 'adminhub'

  end

Body:
Sounds like you want to redirect the browser to the new URL. You can do this with the redirect helper in the routes.

get '/admin', to: redirect('/admin/adminhub')

This allows you to redirect from one path to another. See the Redirection section in the Rails Routing Guide for more details.


问:
How to set current year and previous year in variables using php?

there is one scenario. assume that:

financial year =  01/04/2017 to 31/03/2018

I have one input field with datepicker and date column in database.
If any user will select    today's date e.g 08/06/2017

then there should display data for this    current year i.e from
01/04/2017 to 08/06/2017 with the help of date    table

and at the same it should display previous year's data i.e from
01/04/2016 to 31/03/2017

For the time I am using $currentdate = date('d/m/Y') to display
whole data from db till current date.

$A1 = mysqli_query($conn,'SELECT sum(netvalue) FROMfintranWHERE
 groupNo = 21 AND docDate <= "'.$currentdate.'" ');

We can create some formula but i am so poor to build logic so please help me

答:
You can use the following method for generating date one year back:

```<code>function get_year_back_date($date, $format='d/m/Y') {
    return date($format, strtotime($date . ' -1 year'));
}

$previous_year = get_year_back_date('01/04/2017');
</code>```

Here you can see this code in action: http://ideone.com/eXRoYB.

Body:
You can use the following method for generating date one year back:

function get_year_back_date($date, $format='d/m/Y') {
    return date($format, strtotime($date . ' -1 year'));
}

$previous_year = get_year_back_date('01/04/2017');

Here you can see this code in action: http://ideone.com/eXRoYB.


问:
flash_set, flash_get in PHP?
so i got told in this question:
PHP/Javascript passing message to another page

to use flash_set and flash_get, concept called "Rails flash".. Now can you use them in php those function? I can really find them in php library site, so im not sure..

答:
There's no a built-in function in PHP to achieve this, but if you use some frameworks as CakePHP (which is inspired on rails), you'll find it quite simple:

```<code>// In the controller
$this->Session->setFlash('message to flash');

// In the view
$session->flash();
</code>```

I bet some other frameworks have this covered.

Title: flash_set, flash_get in PHP?

Body:
There's no a built-in function in PHP to achieve this, but if you use some frameworks as CakePHP (which is inspired on rails), you'll find it quite simple:

// In the controller
$this->Session->setFlash('message to flash');

// In the view
$session->flash();

I bet some other frameworks have this covered.


问:
how to add image in button with text?
```<code>enter code here

package buttonfx;

/**
*
* @author 1407305
*/
          import javafx.application.*;
          import javafx.event.*;
          import javafx.scene.*;
          import javafx.scene.control.*;
          import javafx.scene.image.Image;
          import javafx.scene.image.ImageView;
          import javafx.scene.layout.*;
          import javafx.stage.*;
          public class Buttonfx extends Application {
          Label l=new Label("press the button");    // adding label
  public void start(Stage mystage) throws Exception  //starting   mystage
          {
          mystage.setTitle(("Button new gen"));
          FlowPane f=new FlowPane(); //creating flowpane
          //  Pane f=new Pane();
          Scene myscene=new Scene(f, 500,300);
          mystage.setScene(myscene);   //setting scene to stage
          ImageView imageDecline = new ImageView("C:\\Users\\kiit\\Documents\\icons\\colour.png");
          Button b=new Button("alpha" , imageDecline);
          Button b1=new Button("Beta" , imageDecline) ;
          b.setOnAction(MEHANDLER1);
          b1.setOnAction(MEHANDLER1);
          b.setLayoutX(200);
          b.setLayoutY(100);
          f.getChildren().addAll(l , b, b1);
          mystage.show();
          }
          EventHandler<ActionEvent> MEHANDLER1 = new EventHandler<ActionEvent>()
          {
          public void handle(ActionEvent ae)
          {
          String str=((Button)ae.getTarget()).getText();
          if(str.equals("Alpha"))
          {
          l.setText( str + " was pressed");
          }
          if (str.equals("Beta"))
          {
          l.setText(str + " was pressed");
          }
          }
          };
          public static void main(String[] args) throws Exception {
          launch(args);
          }
          }
</code>```

In this code i am unable to insert image in button. in this m using two buttons which doing some small operation my only intension is to add image in both the button so please rectify this programe , and give me the correct way to do it.

答:
Try the code

```<code>b1.setGraphic(imageDecline);
b2.setGraphic(imageDecline);
</code>```

and instantiate the buttons without the imageView.

Title: how to add image in button with text?

Body:
enter code here

package buttonfx;

/**
*
* @author 1407305
*/
          import javafx.application.*;
          import javafx.event.*;
          import javafx.scene.*;
          import javafx.scene.control.*;
          import javafx.scene.image.Image;
          import javafx.scene.image.ImageView;
          import javafx.scene.layout.*;
          import javafx.stage.*;
          public class Buttonfx extends Application {
          Label l=new Label("press the button");    // adding label
  public void start(Stage mystage) throws Exception  //starting   mystage
          {
          mystage.setTitle(("Button new gen"));
          FlowPane f=new FlowPane(); //creating flowpane
          //  Pane f=new Pane();
          Scene myscene=new Scene(f, 500,300);
          mystage.setScene(myscene);   //setting scene to stage
          ImageView imageDecline = new ImageView("C:\\Users\\kiit\\Documents\\icons\\colour.png");
          Button b=new Button("alpha" , imageDecline);
          Button b1=new Button("Beta" , imageDecline) ;
          b.setOnAction(MEHANDLER1);
          b1.setOnAction(MEHANDLER1);
          b.setLayoutX(200);
          b.setLayoutY(100);
          f.getChildren().addAll(l , b, b1);
          mystage.show();
          }
          EventHandler<ActionEvent> MEHANDLER1 = new EventHandler<ActionEvent>()
          {
          public void handle(ActionEvent ae)
          {
          String str=((Button)ae.getTarget()).getText();
          if(str.equals("Alpha"))
          {
          l.setText( str + " was pressed");
          }
          if (str.equals("Beta"))
          {
          l.setText(str + " was pressed");
          }
          }
          };
          public static void main(String[] args) throws Exception {
          launch(args);
          }
          }

In this code i am unable to insert image in button. in this m using two buttons which doing some small operation my only intension is to add image in both the button so please rectify this programe , and give me the correct way to do it.

Body:
Try the code

b1.setGraphic(imageDecline);
b2.setGraphic(imageDecline);

and instantiate the buttons without the imageView.


问:
How do I specify the path to node in SublimeText3 for Sublime-JSHint plugin in Windows
After installing node.js then the Sublime-JSHint plugin on Windows XP with SublimeText3, I get the following error:

"Node.js was not found in the default path. Please specify the location."

This is a known configuration issue and is documented by the author, however I can't work out how to specify the path. Can anyone tell me how to specify the path in Windows XP?

https://github.com/victorporof/Sublime-JSHint#oh-noez-command-not-found

I have tried

```<code>"node_path": "/Program Files/nodejs",

"node_path": "C:/Program Files/nodejs",

"node_path": "/Program Files/nodejs/node.exe",

"node_path": "C:/Program Files/nodejs/node.exe",
</code>```

答:
In my case this setting DOES NOT work

```<code>"node_path": "/usr/lib/nodejs/node-v6.11.0/bin/node",
</code>```

but this WORKS

```<code>"node_path": { "linux" : "/usr/lib/nodejs/node-v6.11.0/bin/node" }
</code>```

This change has to be made in the JSHint.sublime-settings file.

Hope this helps! Although changes are effective right away, I would try restarting the Sublime after the change to make sure if this resolves your problem.

Body:
After installing node.js then the Sublime-JSHint plugin on Windows XP with SublimeText3, I get the following error:

"Node.js was not found in the default path. Please specify the location."

This is a known configuration issue and is documented by the author, however I can't work out how to specify the path. Can anyone tell me how to specify the path in Windows XP?

https://github.com/victorporof/Sublime-JSHint#oh-noez-command-not-found

I have tried

"node_path": "/Program Files/nodejs",

"node_path": "C:/Program Files/nodejs",

"node_path": "/Program Files/nodejs/node.exe",

"node_path": "C:/Program Files/nodejs/node.exe",

Body:
In my case this setting DOES NOT work

"node_path": "/usr/lib/nodejs/node-v6.11.0/bin/node",

but this WORKS

"node_path": { "linux" : "/usr/lib/nodejs/node-v6.11.0/bin/node" }

This change has to be made in the JSHint.sublime-settings file.

Hope this helps! Although changes are effective right away, I would try restarting the Sublime after the change to make sure if this resolves your problem.


问:
Combining Parallel loop with thread logic
I have written a code which looks like this:

```<code>var allParams = new List<string>(); // supposingly has 10 items inside it
var secondCollection = new List<string>(); // collection of 100
Parallel.For(0, secondCollection.Count(), new ParallelOptions {
MaxDegreeOfParallelism = 10 }, counter =>
{
    callingSomeMethod(params[counter]);
});
</code>```

I'm trying to figure out the best way here how to combine my params collection with the parallel for loop to make somethnig like following:

when 10 threads start at the same time, I'd like to pass all 10 elements inside the callingSomeMethod method, and when one of these threads end, then I'd like to just simply start allover again passing element at position 0 , 1, 2, 3,4,5,6,7,8,9,0,1,2,3...

And so the cycle would repeat itself until the Parallel.For loop would end it's cycle...

Is this doable with Paralllel loops? I'm not really sure how would I implement this, can someone help me out ?

答:
So you have sort of a "jagged array," two lists of different lengths that need to be zipped together for processing, with the shorter of the two lists repeating as needed.  That about it?

How about something like this?

```<code>var allParams = new List<string>(); // supposingly has 10 items inside it
var secondCollection = new List<string>(); // collection of 100
var queue = new ConcurrentQueue<string>(secondCollection); //Copy of 100

while (queue.Count > 0)
{
    Parallel.ForEach(allParams, new ParallelOptions { MaxDegreeOfParallelism = 10 },
    (param) =>
    {
        string item;
        bool ok = queue.TryDequeue(out item);
        if (ok)
        {
            callingSomeMethod(param, item);
        }
    });
}
</code>```

The idea is that you put items from the longer list in a ConcurrentQueue, then iterate over the shorter list repeatedly until the queue is empty.  Each iteration gets an item from the iterator in foreach loop and from the queue, and can process both items together.

Body:
I have written a code which looks like this:

var allParams = new List<string>(); // supposingly has 10 items inside it
var secondCollection = new List<string>(); // collection of 100
Parallel.For(0, secondCollection.Count(), new ParallelOptions {
MaxDegreeOfParallelism = 10 }, counter =>
{
    callingSomeMethod(params[counter]);
});

I'm trying to figure out the best way here how to combine my params collection with the parallel for loop to make somethnig like following:

when 10 threads start at the same time, I'd like to pass all 10 elements inside the callingSomeMethod method, and when one of these threads end, then I'd like to just simply start allover again passing element at position 0 , 1, 2, 3,4,5,6,7,8,9,0,1,2,3...

And so the cycle would repeat itself until the Parallel.For loop would end it's cycle...

Is this doable with Paralllel loops? I'm not really sure how would I implement this, can someone help me out ?

Body:
So you have sort of a "jagged array," two lists of different lengths that need to be zipped together for processing, with the shorter of the two lists repeating as needed.  That about it?

How about something like this?

var allParams = new List<string>(); // supposingly has 10 items inside it
var secondCollection = new List<string>(); // collection of 100
var queue = new ConcurrentQueue<string>(secondCollection); //Copy of 100

while (queue.Count > 0)
{
    Parallel.ForEach(allParams, new ParallelOptions { MaxDegreeOfParallelism = 10 },
    (param) =>
    {
        string item;
        bool ok = queue.TryDequeue(out item);
        if (ok)
        {
            callingSomeMethod(param, item);
        }
    });
}

The idea is that you put items from the longer list in a ConcurrentQueue, then iterate over the shorter list repeatedly until the queue is empty.  Each iteration gets an item from the iterator in foreach loop and from the queue, and can process both items together.


问:
In C language, Structure, subtle difference in definition
I have seen format below for defining a structure

```<code>typedef struct Tag
{
  type Member1;
  type Member2;
  <and so on..>
};
</code>```

Some places I see the format below for defining a structure

```<code>typedef struct Tag
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;
</code>```

and some places I see the format below for defining a structure

```<code>typedef struct
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;
</code>```

If you notice the Tag syntax is after struct and also at the closing brace.

Questions.

1) What is the difference between the 3?

2) Is one preferred over the other or When are the best conditions you may want to use one over the other?

答:
The first example creates a definition for a struct named Tag.  The second also creates a variable (which happens to be a Tag struct) named Tag.  The third creates a variable named Tag with the specified structure - but the struct is never named so you can't use it again.  </p>

<p>Which to use?  Personally I'd use the first one and the separately declare any type Tag variables.  If you are trying to eliminate a line of code, the second one works fine.  If you are only going to use the struct once, you could use the third one.  </p>

Body:
I have seen format below for defining a structure

typedef struct Tag
{
  type Member1;
  type Member2;
  <and so on..>
};

Some places I see the format below for defining a structure

typedef struct Tag
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;

and some places I see the format below for defining a structure

typedef struct
{
  type Member1;
  type Member2;
  <and so on..>
} Tag;

If you notice the Tag syntax is after struct and also at the closing brace.

Questions.

1) What is the difference between the 3?

2) Is one preferred over the other or When are the best conditions you may want to use one over the other?

Body:
The first example creates a definition for a struct named Tag.  The second also creates a variable (which happens to be a Tag struct) named Tag.  The third creates a variable named Tag with the specified structure - but the struct is never named so you can't use it again.

Which to use?  Personally I'd use the first one and the separately declare any type Tag variables.  If you are trying to eliminate a line of code, the second one works fine.  If you are only going to use the struct once, you could use the third one.


问:
Prism: ViewModelLocator creates the view model instance(s) but how can I target it?
Is there a way whereby I can identify a ChildViewModel instance, which was created by prism's ViewModelLocator, upon opening it's corresponding window?

I would like to trigger that the ChildViewModel should load it's data, based on  parameters originating from the MasterViewModel.

In code, in MasterViewModel has an ICommand in a  which is responsible for requesting opening a new child window by publishing an event, and there is a corresponding subscriber.

```<code>public ICommand OpenNewChildWindow()
{
    Publish(new OpenNewChildWindowPubSubEvent());

    // Maybe I can publish a new PubSubEvent here
    // but how can I target just the recently created ChildViewModel?
}
</code>```

Notice that the MasterViewModel knows nothing about the UI implementation.

The the subscriber calls ShowWindow method on a custom WindowManager which basically resolves the View (Window in this instance) which corresponds to the ViewModel which was passed in.

```<code>public void ShowWindow(Type viewModelType)
{
   Type view = ResolveView(viewModelType);
   Window w = (Window)Activator.CreateInstance(view);
   w.Show();
}
</code>```

The xaml for the window the appropiate

```<code>ViewModelLocator.AutoWireViewModel="True"
</code>```

答:
Go for a view model-first style of navigation. If you pass a (child-)view model instance (instead of a type) to ShowWindow, you can create that with whatever data you need.

Probably, you pass the data around as payload of the OpenNewChildWindowPubSubEvent, and the subscriber then creates the view model. Or you create the view model immediately in the command and pass that on as payload of the event.

Anyway, don't resolve the view type from the view model type just to resolve the view model type from the view :-)

BTW, the ViewModelLocator is great and really simplifies things, but you don't want to use it here, because you're not navigating within one shell, but creating new windows. If you would, your view model would implement INavigationAware and you'd pass the data to the child view model as parameter to RequestNavigate...

Body:
Is there a way whereby I can identify a ChildViewModel instance, which was created by prism's ViewModelLocator, upon opening it's corresponding window?

I would like to trigger that the ChildViewModel should load it's data, based on  parameters originating from the MasterViewModel.

In code, in MasterViewModel has an ICommand in a  which is responsible for requesting opening a new child window by publishing an event, and there is a corresponding subscriber.

public ICommand OpenNewChildWindow()
{
    Publish(new OpenNewChildWindowPubSubEvent());

    // Maybe I can publish a new PubSubEvent here
    // but how can I target just the recently created ChildViewModel?
}

Notice that the MasterViewModel knows nothing about the UI implementation.

The the subscriber calls ShowWindow method on a custom WindowManager which basically resolves the View (Window in this instance) which corresponds to the ViewModel which was passed in.

public void ShowWindow(Type viewModelType)
{
   Type view = ResolveView(viewModelType);
   Window w = (Window)Activator.CreateInstance(view);
   w.Show();
}

The xaml for the window the appropiate

ViewModelLocator.AutoWireViewModel="True"


问:
how to put the minimum value equal 0 in axes x in Chart C#
good afternoon!

I would like to know if it is possible to put the value zero in scale in chart
The chart is in logarithmic with base 10 and value maximum is 100 and minimum 0.001, I want to put o minimum value in zero.
Here's an image of the graph tasks
enter image description here

答:
"On a logarithmic scale, each tick mark on the scale is the previous tick mark multiplied by some number -base- (Wiki)."

So the 0 does not exist in log!

What you can do is to put something very close to 0 but not a 0.

Somehow this question could be considered a duplicate of this one, have a look.


问:
How to proper design a REST API response?
We have a case where we have a rest endpoint and the response will be different depending on the application flow. The properties inside the json will differ, so the question is whether we want a response containing a json that will have different structure depending on application flow.

We basically have three options as I see it now. Either we could have two properties and one of them will always be null (customer or businessCustomer):

```<code>{
  "data": {
    "target": "Business",
    "customer": null,
    "businessCustomer": {
        ....
    }
}

{
  "data": {
    "target": "Customer",
    "customer": {
        ....
    },
    "businessCustomer": null,
}
</code>```

Or we will have only one property where the the contents of that json object will differ (customer always populated):

```<code>{
  "data": {
    "target": "Customer or business",
    "customer": {
        ....
    }
}
</code>```

I'm thinking it might be hard to consume the data with only one property. How would you serialize that in a smooth way in strongly typed langauges...

Which way is best? Thanks in advance!

答:
I would suggest to have common response format. You can observe similar example in real world (Example : HTTP Request/Response).

You can standardise it like below:

```<code>{
  "statusCode": 0,
  "statusDesc": "Response description",
  "value": null
}
</code>```

Here statusCode and statusDesc would be common across all your response and value would change depending on the api (In your case u can pass customer or businessCustomer respectively). By doing so, Client can use common utility to understand if it is success/failure and take respective action.

Body:
We have a case where we have a rest endpoint and the response will be different depending on the application flow. The properties inside the json will differ, so the question is whether we want a response containing a json that will have different structure depending on application flow.

We basically have three options as I see it now. Either we could have two properties and one of them will always be null (customer or businessCustomer):

{
  "data": {
    "target": "Business",
    "customer": null,
    "businessCustomer": {
        ....
    }
}

{
  "data": {
    "target": "Customer",
    "customer": {
        ....
    },
    "businessCustomer": null,
}

Or we will have only one property where the the contents of that json object will differ (customer always populated):

{
  "data": {
    "target": "Customer or business",
    "customer": {
        ....
    }
}

I'm thinking it might be hard to consume the data with only one property. How would you serialize that in a smooth way in strongly typed langauges...

Which way is best? Thanks in advance!

Body:
I would suggest to have common response format. You can observe similar example in real world (Example : HTTP Request/Response).

You can standardise it like below:

{
  "statusCode": 0,
  "statusDesc": "Response description",
  "value": null
}

Here statusCode and statusDesc would be common across all your response and value would change depending on the api (In your case u can pass customer or businessCustomer respectively). By doing so, Client can use common utility to understand if it is success/failure and take respective action.


问:
How to prevent deadlocks in the following C# code?
The following C# class is used in a multithreaded enviroment. I removed very much of the actual code. The problem occurs when calling MethodA and MethodB almost simultaneously. The order of the lock in the IsDepleted property doesn't solves the problem. Removing lock(WaitingQueue) from the IsDepleted property solves the deadlock, but this solution causes a problem when another thread adds/removes an item from the WaitingQueue between the WaitingQueue.Count == 0 and Processing.Count == 0 statements.</p>

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

class Example
{
    bool IsDepleted
    {
        get
        {
            lock (Processing)
            {
                lock (WaitingQueue)
        {
                    return WaitingQueue.Count == 0
             && Processing.Count == 0;
        }
            }
        }
    }

    private readonly List<object> Processing = new List<object>();
    private readonly Queue<object> WaitingQueue = new Queue<object>();

    public void MethodA(object item)
    {
        lock (WaitingQueue)
        {
            if (WaitingQueue.Count > 0)
            {
                if (StartItem(WaitingQueue.Peek()))
                {
                    WaitingQueue.Dequeue();
                }
            }
        }
    }

    public void MethodB(object identifier)
    {
        lock (Processing)
        {
            Processing.Remove(identifier);
            if (!IsDepleted)
            {
                return;
            }
        }
    //Do something...
    }

    bool StartItem(object item)
    {
        //Do something and return a value
    }
}
</code>```

答:
It depends if you want a quick fix or a rigorous fix.

A quick fix would be just to use one lock object in all cases.

e.g. private readonly object _lock = new object();

And then just lock on that. However, depending on your situation, that may impact performance more than you can accept.

I.e. your code would become this:

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

class Example
{
    private readonly object _lock = new object();

    bool IsDepleted
    {
        get
        {
            lock (_lock)
            {
                return WaitingQueue.Count == 0
                 && Processing.Count == 0;
            }
        }
    }

    private readonly List<object> Processing = new List<object>();
    private readonly Queue<object> WaitingQueue = new Queue<object>();

    public void MethodA(object item)
    {
        lock (_lock)
        {
            if (WaitingQueue.Count > 0)
            {
                if (StartItem(WaitingQueue.Peek()))
                {
                    WaitingQueue.Dequeue();
                }
            }
        }
    }

    public void MethodB(object identifier)
    {
        lock (_lock)
        {
            Processing.Remove(identifier);
            if (!IsDepleted)
            {
                return;
            }
        }
        //Do something...
    }

    bool StartItem(object item)
    {
        //Do something and return a value
    }
}
</code>```

OwnerDisplayName: Vernicht

Body:
The following C# class is used in a multithreaded enviroment. I removed very much of the actual code. The problem occurs when calling MethodA and MethodB almost simultaneously. The order of the lock in the IsDepleted property doesn't solves the problem. Removing lock(WaitingQueue) from the IsDepleted property solves the deadlock, but this solution causes a problem when another thread adds/removes an item from the WaitingQueue between the WaitingQueue.Count == 0 and Processing.Count == 0 statements.

using System.Collections.Generic;

class Example
{
    bool IsDepleted
    {
        get
        {
            lock (Processing)
            {
                lock (WaitingQueue)
        {
                    return WaitingQueue.Count == 0
             && Processing.Count == 0;
        }
            }
        }
    }

    private readonly List<object> Processing = new List<object>();
    private readonly Queue<object> WaitingQueue = new Queue<object>();

    public void MethodA(object item)
    {
        lock (WaitingQueue)
        {
            if (WaitingQueue.Count > 0)
            {
                if (StartItem(WaitingQueue.Peek()))
                {
                    WaitingQueue.Dequeue();
                }
            }
        }
    }

    public void MethodB(object identifier)
    {
        lock (Processing)
        {
            Processing.Remove(identifier);
            if (!IsDepleted)
            {
                return;
            }
        }
    //Do something...
    }

    bool StartItem(object item)
    {
        //Do something and return a value
    }
}

Body:
It depends if you want a quick fix or a rigorous fix.

A quick fix would be just to use one lock object in all cases.

e.g. private readonly object _lock = new object();

And then just lock on that. However, depending on your situation, that may impact performance more than you can accept.

I.e. your code would become this:

using System.Collections.Generic;

class Example
{
    private readonly object _lock = new object();

    bool IsDepleted
    {
        get
        {
            lock (_lock)
            {
                return WaitingQueue.Count == 0
                 && Processing.Count == 0;
            }
        }
    }

    private readonly List<object> Processing = new List<object>();
    private readonly Queue<object> WaitingQueue = new Queue<object>();

    public void MethodA(object item)
    {
        lock (_lock)
        {
            if (WaitingQueue.Count > 0)
            {
                if (StartItem(WaitingQueue.Peek()))
                {
                    WaitingQueue.Dequeue();
                }
            }
        }
    }

    public void MethodB(object identifier)
    {
        lock (_lock)
        {
            Processing.Remove(identifier);
            if (!IsDepleted)
            {
                return;
            }
        }
        //Do something...
    }

    bool StartItem(object item)
    {
        //Do something and return a value
    }
}

OwnerDisplayName: Andrew Rollings


问:
Dealing with Large Bitmaps (tiling a small bitmap to create wallpaper)
I'm having memory problems and think it might have to do with creating large bitmaps.

The task at hand is to get a fairly small tile image and create a larger tiled image and set this as the phone wallpaper. The way I'm doing this is:

1) Create a view that is 2 * screen width, 1 * screen height

2) Set the view background to a BitmapDrawable with the tile mode set to repeat

3) Create a bitmap with the views dimensions

4) draw the view to the bitmap by: view.draw(new Canvas(bitmap))

5) set wallpper: getApplicationContext().setWallpaper(bitmap)

This works fine on my phone (HTC Magic) and other phones that I have tried. But I am getting bug reports relating to this issue. I tried to recreate the problem by doubling the required dimensions and the problem seems to be happening in the 4th step when the view is being drawn to the bitmap:

ERROR/dalvikvm-heap(124): Heap Massage needed (7372800-byte external allocation too big)

I'm not sure how to go about solving this. Please help!
Thanks

答:
Not exactly sure if this is your solution, but have you looked at  ? BitmapFactory.Options.inTempStorage

The way you use it is:

```<code>
BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
Bitmap bitmap_origin = BitmapFactory.decodeFile(path, options);
</code>```

Body:
Not exactly sure if this is your solution, but have you looked at  ? BitmapFactory.Options.inTempStorage

The way you use it is:

BitmapFactory.Options options = new BitmapFactory.Options();
options.inTempStorage = new byte[16*1024];
Bitmap bitmap_origin = BitmapFactory.decodeFile(path, options);