问:
bootstrap: horizontal centering and background color for image link on phone
I saw a few solutions for horizontal centering elements in bootstrap (col-md-offset-3 and center-block) but none of them appear to work.
My code is:

```<code><div class="col-md-12 col-sm-12 col-xs-12 paper-main">
                            <img class="desert" src="<?= get_template_directory_uri().'/resources/img/prince_-desert2.png' ?>">
                            <div class="col-md-1 col-sm-1 col-xs-1 page-arrow">
                                <div class="center-block">
                                    <?php if ( $paged > 1 ) : ?>
                                        <a href="<?php echo get_previous_posts_page_link(); ?>"><img src="<?= get_template_directory_uri().'/resources/img/little-prince-right-arrow.png' ?>"></a>
                                        <?php else : ?>

                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-md-10 col-sm-10 col-xs-10">
                                <ul class="chapters-list">
                                    <?php
                                    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

                                    $temp = $wp_query;
                                    $wp_query = null;
                                    $wp_query = new WP_Query();
                                    $wp_query->query(['cat' => ($paged+4), 'order' => 'ASC']);
                                    $wp_query->max_num_pages = 3;
                                    ?>
                                    <?php  while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
                                        <li>
                                            <a>
                                                <?php the_title() ?>
                                            </a>
                                        </li>
                                    <?php endwhile; ?>
                                </ul>
                            </div>
                            <div class="col-md-1 col-sm-1 col-xs-1 page-arrow">
                                <?php if ( $paged < 3 ) : ?>
                                    <a href="<?php echo get_next_posts_page_link(); ?>"><img src="<?= get_template_directory_uri().'/resources/img/little-prince-left-arrow.png' ?>"></a>
                                <?php endif; ?>
                            </div>
</code>```

css:

```<code>    .page-arrow { padding: 0; }

.page-arrow img, .paper-pagination img { background-color: #337ab7 }
.page-arrow:hover img, .paper-pagination img:hover { background-color: #23527c }
</code>```

I'm trying to center the pagination images.

Also, the pagination arrows are an image with a filled background.
On the computer view it works fine, but on phones there's a gap I can't close with css:
Phone View:

Regular View:

答:
Can you clarify what you mean abut wanting the arrows to be centered horizontally? Right now they appear to be spaced evenly in terms of horizontal positioning.

Did you mean that you want the arrows to be centered vertically as well? If they were both dead center horizontally then they wouldn't be able to be aligned in the same row across the page, as they are in the screenshots you posted.

If you really did just want to know how to center the arrow images  horizontally, you could try this CSS:

.col-md-12 {max-width: 100%;}
.center-block img {display: block; margin: 0 auto;}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="col-md-12 col-sm-12 col-xs-12 paper-main">
                            <img class="desert" src="<?php  get_template_directory_uri().'/resources/img/prince_-desert2.png' ?>">
                            <div class="col-md-1 col-sm-1 col-xs-1 page-arrow">
                                <div class="center-block">
                                        "><img src="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/png/512/arrow-right-a.png" height="50" width="50">
                                        <?php else : ?>

                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-md-10 col-sm-10 col-xs-10">
                                <ul class="chapters-list">
                                    <?php
                                    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

                                    $temp = $wp_query;
                                    $wp_query = null;
                                    $wp_query = new WP_Query();
                                    $wp_query->query(['cat' => ($paged+4), 'order' => 'ASC']);
                                    $wp_query->max_num_pages = 3;
                                    ?>
                                    <?php  while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
                                        <li>
                                            <a>
                                                <?php the_title() ?>
                                            </a>
                                        </li>
                                    <?php endwhile; ?>
                                </ul>
                            </div>
                            <div class="col-md-1 col-sm-1 col-xs-1 page-arrow center-block">
                                <?php if ( $paged < 3 ) : ?>
                                    "><img src="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/png/512/arrow-left-a.png" height="50" widht="50">
                                <?php endif; ?>
                            </div></code>```

I replaced your site's arrow images with some random arrows hosted by a CDN just so something shows up.

Body:
I saw a few solutions for horizontal centering elements in bootstrap (col-md-offset-3 and center-block) but none of them appear to work.
My code is:

                            <img class="desert" src="<?= get_template_directory_uri().'/resources/img/prince_-desert2.png' ?>">

                                    <?php if ( $paged > 1 ) : ?>
                                        <a href="<?php echo get_previous_posts_page_link(); ?>"><img src="<?= get_template_directory_uri().'/resources/img/little-prince-right-arrow.png' ?>">
                                        <?php else : ?>

                                    <?php endif; ?>

                                    <?php
                                    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

                                    $temp = $wp_query;
                                    $wp_query = null;
                                    $wp_query = new WP_Query();
                                    $wp_query->query(['cat' => ($paged+4), 'order' => 'ASC']);
                                    $wp_query->max_num_pages = 3;
                                    ?>
                                    <?php  while ($wp_query->have_posts()) : $wp_query->the_post(); ?>

                                                <?php the_title() ?>

                                    <?php endwhile; ?>

                                <?php if ( $paged < 3 ) : ?>
                                    <a href="<?php echo get_next_posts_page_link(); ?>"><img src="<?= get_template_directory_uri().'/resources/img/little-prince-left-arrow.png' ?>">
                                <?php endif; ?>

css:

    .page-arrow { padding: 0; }

.page-arrow img, .paper-pagination img { background-color: #337ab7 }
.page-arrow:hover img, .paper-pagination img:hover { background-color: #23527c }

I'm trying to center the pagination images.

Also, the pagination arrows are an image with a filled background.
On the computer view it works fine, but on phones there's a gap I can't close with css:
Phone View:

Regular View:

Body:
Can you clarify what you mean abut wanting the arrows to be centered horizontally? Right now they appear to be spaced evenly in terms of horizontal positioning.

Did you mean that you want the arrows to be centered vertically as well? If they were both dead center horizontally then they wouldn't be able to be aligned in the same row across the page, as they are in the screenshots you posted.

If you really did just want to know how to center the arrow images  horizontally, you could try this CSS:

.col-md-12 {max-width: 100%;}
.center-block img {display: block; margin: 0 auto;}

<div class="col-md-12 col-sm-12 col-xs-12 paper-main">
                            <img class="desert" src="<?php  get_template_directory_uri().'/resources/img/prince_-desert2.png' ?>">
                            <div class="col-md-1 col-sm-1 col-xs-1 page-arrow">
                                <div class="center-block">
                                        <a href="<?php echo get_previous_posts_page_link(); ?>"><img src="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/png/512/arrow-right-a.png" height="50" width="50"></a>
                                        <?php else : ?>
                                        &nbsp;
                                    <?php endif; ?>
                                </div>
                            </div>
                            <div class="col-md-10 col-sm-10 col-xs-10">
                                <ul class="chapters-list">
                                    <?php
                                    $paged = ( get_query_var( 'paged' ) ) ? get_query_var( 'paged' ) : 1;

                                    $temp = $wp_query;
                                    $wp_query = null;
                                    $wp_query = new WP_Query();
                                    $wp_query->query(['cat' => ($paged+4), 'order' => 'ASC']);
                                    $wp_query->max_num_pages = 3;
                                    ?>
                                    <?php  while ($wp_query->have_posts()) : $wp_query->the_post(); ?>
                                        <li>
                                            <a>
                                                <?php the_title() ?>
                                            </a>
                                        </li>
                                    <?php endwhile; ?>
                                </ul>
                            </div>
                            <div class="col-md-1 col-sm-1 col-xs-1 page-arrow center-block">
                                <?php if ( $paged < 3 ) : ?>
                                    <a href="<?php echo get_next_posts_page_link(); ?>"><img src="https://cdnjs.cloudflare.com/ajax/libs/ionicons/2.0.1/png/512/arrow-left-a.png" height="50" widht="50"></a>
                                <?php endif; ?>
                            </div>

I replaced your site's arrow images with some random arrows hosted by a CDN just so something shows up.


来源: stackexchange

问:
Bitwise Addition and Subtraction in a single sql statement
I want to remove a flag from a bitwise fields and at the same time I want to add two flags

```<code>Declare @status int = 3
SET @status &= ~3 -- this will remove 1 and 2 if exists
SET @status |= 12 -- this will add 4 and 8 if exists
</code>```

I want to do both of them together as this is used in an update statement like,

```<code>SET @status = (@status | 12 ) - (CASE WHEN (@status & 2 = 2) THEN 2 ELSE 0 END) - (CASE WHEN (@status & 1 = 1) THEN 1 ELSE 0 END)
</code>```

Anyone knows how to do the subtraction part using bitwise operators along with addition part.

Something like,

```<code>SET @status |= 12 & ~2 --But this doesn't do what I want
</code>```

Thanks in advance.

答:
Doesn't this work?</p>

```<code>SET @status = ((@status & ~3) | 12)
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I want to remove a flag from a bitwise fields and at the same time I want to add two flags

Declare @status int = 3
SET @status &= ~3 -- this will remove 1 and 2 if exists
SET @status |= 12 -- this will add 4 and 8 if exists

I want to do both of them together as this is used in an update statement like,

SET @status = (@status | 12 ) - (CASE WHEN (@status & 2 = 2) THEN 2 ELSE 0 END) - (CASE WHEN (@status & 1 = 1) THEN 1 ELSE 0 END)

Anyone knows how to do the subtraction part using bitwise operators along with addition part.

Something like,

SET @status |= 12 & ~2 --But this doesn't do what I want

Thanks in advance.

Body:
Doesn't this work?

SET @status = ((@status & ~3) | 12)


问:
How to convert anything to a String safely in JavaScript
If I have:

```<code>var test = {toString: function(){alert("evil code"); return "test";}};
</code>```

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.

答:
JavaScript allows you to modify the properties of pretty much any object that is accessible to your script, including Object.prototype itself, meaning any object is vulnerable to "evil code" in the manner that you explained.

Only primitives are guaranteed to be safe, so the only way to ensure that "evil code" is never executed is to do something like this:

```<code>function safeToString(x) {
  switch (typeof x) {
    case 'object':
      return 'object';
    case 'function':
      return 'function';
    default:
      return x + '';
  }
}
</code>```

Body:
If I have:

var test = {toString: function(){alert("evil code"); return "test";}};

how can I convert test to a string? without calling test.toString() and without using a typeof x == "string" check since I want to allow non strings.

Note: this is for a FF extension dealing with objects from a content page's js scope.

Body:
JavaScript allows you to modify the properties of pretty much any object that is accessible to your script, including Object.prototype itself, meaning any object is vulnerable to "evil code" in the manner that you explained.

Only primitives are guaranteed to be safe, so the only way to ensure that "evil code" is never executed is to do something like this:

function safeToString(x) {
  switch (typeof x) {
    case 'object':
      return 'object';
    case 'function':
      return 'function';
    default:
      return x + '';
  }
}

ContentLicense: CC BY-SA 2.5


问:
Events dropped when integrating Azure Functions with Azure Event Hubs
I am setting up an example where I have an Azure Function with a webhook that has an Azure Event Hub as a sink. There are two different consumer groups for this event hub, one of which is used by another Azure Function. The code doesn't do anything too fancy (excerpts are below), but I am observing an odd pattern. For every two messages published, only one appears to trigger the function once.

Publishing web hook:

```<code>module.exports = function (context, req) {
    var statusCode = 400;
    var responseBody = "Invalid request object";

    if (typeof req.body != 'undefined' && typeof req.body == 'object') {
        var eventInformation = req.body;

        context.log("Received event: " + eventInformation);

        context.bindings.outEvent = eventInformation;

        statusCode = 200;
        responseBody = "Event received.";
    }

    context.res = {
        status: statusCode,
        body: responseBody
    };

    context.done();
};
</code>```

Receiving function:

```<code>module.exports = function (context, offerMadeEvent) {
    var connection = new Connection(dbConfig); // Tedious connection
    connection.on('connect', function(err) {
        context.log('Connection established.');
        // Somewhere in the database callbacks:
        context.done();
    });
};
</code>```

答:
Based on @Michael's the response from the "Comment" section above, the issue is related to a bug in the support for non-default consumer groups.

Background

A Function App instance is a process instance for all Functions inside the Function App.  For a Function to execute, at least 1 Function App instance must be running.

Typically, a Function App instance is launched due to one of the following scenarios:

Function App is being accessed via Azure Portal - The UX workflow loads the Function App on behalf of the user, effectively forcing the Function App to come alive.

Function App instance is launched by internal service - There is an internal service that acts as the proxy listener for events on all triggers.  It is responsible for listening for new events, launching a Function App instance if no-active instances exists, and scaling new instances when necessary.

For Functions that are created under the Consumption Plan, the Function App instance will stay alive for 5 minutes.  After 5 minutes, the Function App instance will idle out.  Once the "last" Function App instance idles out, if Scenario #1 does not occur, then the Function will only be triggered by Scenario #2.

Issue

For EventHub triggers, the internal service is currently only listening for events on the default consumer group.  It does not detect when there are new events arriving for other consumer groups and will not wake up the Function App.

This is a known issue and is actively being fixed.  You may track the issue at
https://github.com/Azure/Azure-Functions/issues/230

Body:
I am setting up an example where I have an Azure Function with a webhook that has an Azure Event Hub as a sink. There are two different consumer groups for this event hub, one of which is used by another Azure Function. The code doesn't do anything too fancy (excerpts are below), but I am observing an odd pattern. For every two messages published, only one appears to trigger the function once.

Publishing web hook:

module.exports = function (context, req) {
    var statusCode = 400;
    var responseBody = "Invalid request object";

    if (typeof req.body != 'undefined' && typeof req.body == 'object') {
        var eventInformation = req.body;

        context.log("Received event: " + eventInformation);

        context.bindings.outEvent = eventInformation;

        statusCode = 200;
        responseBody = "Event received.";
    }

    context.res = {
        status: statusCode,
        body: responseBody
    };

    context.done();
};

Receiving function:

module.exports = function (context, offerMadeEvent) {
    var connection = new Connection(dbConfig); // Tedious connection
    connection.on('connect', function(err) {
        context.log('Connection established.');
        // Somewhere in the database callbacks:
        context.done();
    });
};


问:
sort and display names on different lines in ascending order
My professor wants us to Write a JavaScript code that prompts the user to enter 3 names (one at a time). The program should
sort and display the names on different lines in ascending order.

This is what I have so far

```<code><html>
<head>
  <title>Day 2 - Example 2</title>
</head>
<body>
<center>
 <script language="javascript">
   var na1,na2,na3;
   na1=prompt("Enter your first name:","");
   na2=prompt("Enter your second name:","");
   na3=prompt("Enter your third name","");
 </script>
 </center>
</body>
</html>
</code>```

答:
I think your professor wants you learn something in the process, so I try to explain you how to attack the problem. Please feel free to ask any follow up question you have.

So, you have you three names, in three different variables.

You have two main problems: compare the names, and sort them by the result of the comparison.

Let's take one step at time.

What does to compare two names mean? Or, in another worlds, what does it means that one name is before another?

Let's suppose, for simplicity, that the inserted names contains only chars from a to z, both in lower or upper case. There are no numbers, no special chars (like è) or anything else (you can try eventually to expand the code to take care of other characters too).

So, to compare the two names we create a function which takes two names as arguments and returns -1 as result if the first name comes before the second, 0 if they are equal, and 1 otherwise.

The function will be something like this:

```<code>function compare(name1, name2) {
    // Do same magic stuff
    return -1;
}
</code>```

First of all, we can compare the first letter of the names, and check which one comes first.
The best way to take a char out of a string is using the charAt() function. You can also access a string as an array, but it doesn't work on IE7, and from an academic point of view is wrong.

But in real world, writing name[1] is the same of writing name.charAt(1)

```<code>function compare(name1, name2) {
    if (name1.charAt(0) < name2.charAt(0)) return -1;
    if (name1.charAt(0) === name2.charAt(0)) return 0;
    if (name1.charAt(0) > name2.charAt(0)) return 1;
}
</code>```

Uhm, it is a beginning, but this code has a lot of problems.

The second if will make the function returning 0 if the first letter of the two names is the same. This doesn't make any sense.

We know that two names are equal if and only if they are all equals.
We can then change the check to make sure all the chars in the two names are the same:

```<code>function compare(name1, name2) {
    if (name1 === name2) return 0;

    if (name1.charAt(0) < name2.charAt(0)) return -1;
    if (name1.charAt(0) > name2.charAt(0)) return 1;
}
</code>```

Definitely better.

But another problem we have with this code is that if someone inserted her name with a capital letter, she will be always before someone who inserted the name using only lower case letters.

So alice will come after Bob in our case.

We need to compare the same character, so we will compare only lower case chars. To transform our names in all lower case letters, we use the toLowerCase() function

```<code>function compare(name1, name2) {
    name1 = name1.toLowerCase();
    name2 = name2.toLowerCase();

    if (name1 === name2) return 0;

    if (name1.charAt(0) < name2.charAt(0)) return -1;
    if (name1.charAt(0) > name2.charAt(0)) return 1;
}
</code>```

Okay!

But what if the first chars of the two names is the same?

Mhh, we didn't think about it! We have to check for every char as long we do not find one different or one of the two names doesn't have any more char!

First of all, let's find the shortest name:

var lengthOfShorterName = Math.min(name1.length, name2.length)

Math.min will return the littlest number among the ones you pass as arguments.
We can create now a forcycle to compare every char, one by one.

```<code>for (var i = 0; i < lengthOfShorterName; i++) {
    if (name1.charAt(i) > name2.charAt(i)) return 1;
    if (name1.charAt(i) < name2.charAt(i)) return -1;
}
</code>```

But what if one name is a sub-string of the other (that is, Ali and Alice)?

Well, the for cycle will finish, so we need another condition.
Let's say that the shorter name comes first.

```<code>if (name1.lenght < name2.length) return -1;
return 1;
</code>```

We finally have our compare function :)

```<code>function compare(name1, name2) {
    name1 = name1.toLowerCase();
    name2 = name2.toLowerCase();

    if (name1 === name2) return 0;

    var lengthOfShorterName = Math.min(name1.length, name2.length)

    for (var i = 0; i < lengthOfShorterName; i++) {
        if (name1.charAt(i) > name2.charAt(i)) return 1;
        if (name1.charAt(i) < name2.charAt(i)) return -1;
    }

    if (name1.lenght < name2.length) return -1;
    return 1;
}
</code>```

Now we need to sort the elements.

Sorting is a very complex subjects, and there are a lot of different approaches, with a lot of pros and cons. But also an overall analysis would be too much for this answer, so let's do a little trick here: we know we have three names, so we can directly compare them thanks to our new function!

Let's first of all do all the comparison!

```<code>var na1_na2 = compare(na1, na2);
var na1_na3 = compare(na1, na3);
var na2_na3 = compare(na2, na3);

// We create the place where we will save the names
var first, second, third;

if (na1_na2 === -1) {
    // na1 comes before na2! Will it come also before na3?
    if (na1_na3 === -1) {
        // Yes! So na1 is the first!
        first = na1;

        // But who is second?
        if (na2_na3 === -1) {
            // na2 is second!
            second = na2;
            third = na3;
        } else {
            // na3 is second!
            second = na3;
            third = na2;
        }
    } else {
        // na3 is before na1, therefore is first!
        first = na3
        second = na1;
        third = na2;
    }
} else {
    // na2 is before na1. What do we need to compare?
}
</code>```

Now, of course you will not use a solution like this in the real world.
First of all, because I left out a lot of corner cases (and also ignored when the function compare returns 0).

Second, and mainly, because you do not leverage the Javascript native functions.

The answer by @shash679 shows you a real world implementation of the solution.

But anyway, I hope you enjoyed the explanation and mainly you are curious now to find out more about Javascript and computer science in general.

Writing code is not about writing code, it is more about resolving riddles, and it's quite fun.

Good luck with your course!

Body:
My professor wants us to Write a JavaScript code that prompts the user to enter 3 names (one at a time). The program should
sort and display the names on different lines in ascending order.

This is what I have so far

  <title>Day 2 - Example 2</title>

Body:
I think your professor wants you learn something in the process, so I try to explain you how to attack the problem. Please feel free to ask any follow up question you have.

So, you have you three names, in three different variables.

You have two main problems: compare the names, and sort them by the result of the comparison.

Let's take one step at time.

What does to compare two names mean? Or, in another worlds, what does it means that one name is before another?

Let's suppose, for simplicity, that the inserted names contains only chars from a to z, both in lower or upper case. There are no numbers, no special chars (like è) or anything else (you can try eventually to expand the code to take care of other characters too).

So, to compare the two names we create a function which takes two names as arguments and returns -1 as result if the first name comes before the second, 0 if they are equal, and 1 otherwise.

The function will be something like this:

function compare(name1, name2) {
    // Do same magic stuff
    return -1;
}

First of all, we can compare the first letter of the names, and check which one comes first.
The best way to take a char out of a string is using the charAt() function. You can also access a string as an array, but it doesn't work on IE7, and from an academic point of view is wrong.

But in real world, writing name[1] is the same of writing name.charAt(1)

function compare(name1, name2) {
    if (name1.charAt(0) < name2.charAt(0)) return -1;
    if (name1.charAt(0) === name2.charAt(0)) return 0;
    if (name1.charAt(0) > name2.charAt(0)) return 1;
}

Uhm, it is a beginning, but this code has a lot of problems.

The second if will make the function returning 0 if the first letter of the two names is the same. This doesn't make any sense.

We know that two names are equal if and only if they are all equals.
We can then change the check to make sure all the chars in the two names are the same:

function compare(name1, name2) {
    if (name1 === name2) return 0;

    if (name1.charAt(0) < name2.charAt(0)) return -1;
    if (name1.charAt(0) > name2.charAt(0)) return 1;
}

Definitely better.

But another problem we have with this code is that if someone inserted her name with a capital letter, she will be always before someone who inserted the name using only lower case letters.

So alice will come after Bob in our case.

We need to compare the same character, so we will compare only lower case chars. To transform our names in all lower case letters, we use the toLowerCase() function

function compare(name1, name2) {
    name1 = name1.toLowerCase();
    name2 = name2.toLowerCase();

    if (name1 === name2) return 0;

    if (name1.charAt(0) < name2.charAt(0)) return -1;
    if (name1.charAt(0) > name2.charAt(0)) return 1;
}

Okay!

But what if the first chars of the two names is the same?

Mhh, we didn't think about it! We have to check for every char as long we do not find one different or one of the two names doesn't have any more char!

First of all, let's find the shortest name:

var lengthOfShorterName = Math.min(name1.length, name2.length)

Math.min will return the littlest number among the ones you pass as arguments.
We can create now a forcycle to compare every char, one by one.

for (var i = 0; i < lengthOfShorterName; i++) {
    if (name1.charAt(i) > name2.charAt(i)) return 1;
    if (name1.charAt(i) < name2.charAt(i)) return -1;
}

But what if one name is a sub-string of the other (that is, Ali and Alice)?

Well, the for cycle will finish, so we need another condition.
Let's say that the shorter name comes first.

if (name1.lenght < name2.length) return -1;
return 1;

We finally have our compare function :)

function compare(name1, name2) {
    name1 = name1.toLowerCase();
    name2 = name2.toLowerCase();

    if (name1 === name2) return 0;

    var lengthOfShorterName = Math.min(name1.length, name2.length)

    for (var i = 0; i < lengthOfShorterName; i++) {
        if (name1.charAt(i) > name2.charAt(i)) return 1;
        if (name1.charAt(i) < name2.charAt(i)) return -1;
    }

    if (name1.lenght < name2.length) return -1;
    return 1;
}

Now we need to sort the elements.

Sorting is a very complex subjects, and there are a lot of different approaches, with a lot of pros and cons. But also an overall analysis would be too much for this answer, so let's do a little trick here: we know we have three names, so we can directly compare them thanks to our new function!

Let's first of all do all the comparison!

var na1_na2 = compare(na1, na2);
var na1_na3 = compare(na1, na3);
var na2_na3 = compare(na2, na3);

// We create the place where we will save the names
var first, second, third;

if (na1_na2 === -1) {
    // na1 comes before na2! Will it come also before na3?
    if (na1_na3 === -1) {
        // Yes! So na1 is the first!
        first = na1;

        // But who is second?
        if (na2_na3 === -1) {
            // na2 is second!
            second = na2;
            third = na3;
        } else {
            // na3 is second!
            second = na3;
            third = na2;
        }
    } else {
        // na3 is before na1, therefore is first!
        first = na3
        second = na1;
        third = na2;
    }
} else {
    // na2 is before na1. What do we need to compare?
}

Now, of course you will not use a solution like this in the real world.
First of all, because I left out a lot of corner cases (and also ignored when the function compare returns 0).

Second, and mainly, because you do not leverage the Javascript native functions.

The answer by @shash679 shows you a real world implementation of the solution.

But anyway, I hope you enjoyed the explanation and mainly you are curious now to find out more about Javascript and computer science in general.

Writing code is not about writing code, it is more about resolving riddles, and it's quite fun.

Good luck with your course!


问:
How to just skip an element when building new list?
```<code>data =: '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"`

   ];._1 data
MARY
,
PATRICIA
,
LINDA
,
BARBARA
,
ELIZABETH
(one more blank line here)
</code>```

So I want just skip every second line:

```<code>   ]`(0&#);._1 data
MARY

PATRICIA

LINDA

BARBARA

ELIZABETH
(one more blank line here)
</code>```

Doesn't work as I thought.

And I encounter this situation quite often. For example when using code like this:

```<code>]`(Do nothing. Just skip. Just SKIP!!!)@.(some condition)
</code>```

答:
A couple of options to filter out every 2nd element of a list:

```<code>   mylist=: ];._1 data
   (#~ 2 -.@| i.@#) mylist   NB. retain even indexed items
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH
   (_2 {.\ ]) mylist         NB. get first item of pairs
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH
</code>```

A couple of options to parse this data:

```<code>   > '","' splitstring }. }: data
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH

   require 'csv'
   > (',' ; '"') fixdsv data,LF
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH
</code>```

Body:
data =: '"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH"`

   ];._1 data
MARY
,
PATRICIA
,
LINDA
,
BARBARA
,
ELIZABETH
(one more blank line here)

So I want just skip every second line:

   ]`(0&#);._1 data
MARY

PATRICIA

LINDA

BARBARA

ELIZABETH
(one more blank line here)

Doesn't work as I thought.

And I encounter this situation quite often. For example when using code like this:

]`(Do nothing. Just skip. Just SKIP!!!)@.(some condition)

Body:
A couple of options to filter out every 2nd element of a list:

   mylist=: ];._1 data
   (#~ 2 -.@| i.@#) mylist   NB. retain even indexed items
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH
   (_2 {.\ ]) mylist         NB. get first item of pairs
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH

A couple of options to parse this data:

   > '","' splitstring }. }: data
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH

   require 'csv'
   > (',' ; '"') fixdsv data,LF
MARY
PATRICIA
LINDA
BARBARA
ELIZABETH


问:
Broadcast receiver working even after app is killed by user
I have a BroadcastReceiver that checks for network connection declared statically as:

```<code><receiver
            android:name=".core.util.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>
</code>```

Network change receiver does something like:

```<code>public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

    String status = NetworkUtil.getConnectivityStatusString(context);

    if(status == "Not connected to Internet") {
        Intent i = new Intent(context, Dialog.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}
</code>```

}

The problem is that when I manually kill my app and turn off network (airplane mode), the Dialogue activity launches. How is this possible? Is my broadcast receiver still alive in the background?

Question:

is there a way for me to unregister my broadcast receiver once the application is killed? maybe in the application singleton class of Android?

If it is not possible in Application class, do I have to manually unregister it everywhere in onStop()? and register it in onStart() in every activity?

答:
How is this possible?

You registered for the broadcast in the manifest. If a matching broadcast is sent out, your app will respond. If needed, Android will fork a process for you, if your app is not running at the time.

(at least until Android O is released, but that is a story for another time)

is there a way for me to unregister my broadcast receiver once the application is killed?

You need to decide the period of time you want to receive this broadcast:

If it is while some particular activity is in the foreground, use registerReceiver() instead of the manifest, registering for the broadcast in the activity's onStart() method and unregistering in onStop()

If it is while some particular service is running, use registerReceiver() in the service's onCreate() and unregisterReceiver() in onDestroy()

Body:
I have a BroadcastReceiver that checks for network connection declared statically as:

<receiver
            android:name=".core.util.NetworkChangeReceiver"
            android:label="NetworkChangeReceiver">
            <intent-filter>
                <action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
                <action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
            </intent-filter>
        </receiver>

Network change receiver does something like:

public class NetworkChangeReceiver extends BroadcastReceiver {

@Override
public void onReceive(final Context context, final Intent intent) {

    String status = NetworkUtil.getConnectivityStatusString(context);

    if(status == "Not connected to Internet") {
        Intent i = new Intent(context, Dialog.class);
        i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(i);
    }
}

}

The problem is that when I manually kill my app and turn off network (airplane mode), the Dialogue activity launches. How is this possible? Is my broadcast receiver still alive in the background?

Question:

is there a way for me to unregister my broadcast receiver once the application is killed? maybe in the application singleton class of Android?

If it is not possible in Application class, do I have to manually unregister it everywhere in onStop()? and register it in onStart() in every activity?


问:
Retrofit queries without ampersand
I'm trying to send requests to an API that uses semicolon(;) instead of ampersand(&) for query parameters, The url request looks like this:

```<code>http://api.example.com/path/?param1=p1;param2=p2
</code>```

The most similar post I found on the internet suggests to use another method that puts url parts together and then use @Url annotation.

Does retrofit contain any solution for these cases ?

Thanks.

答:
It is possible to use an Interceptor to rewrite the URL from using '&' to ';'. The tricky part is doing it in a way that does not make the URL invalid.

```<code>new Interceptor() {
    Response intercept(Chain chain) throws IOException {
        HttpUrl originalUrl = chain.request().url();
        String query = originalUrl.encodedQuery();
        if (query == null) {
            return chain.proceed(chain.request());
        } else {
            Request.Builder builder = chain.request().newBuilder();
            builder.url(originalUrl.newBuilder()
                .encodedQuery(query.replace('&', ';'))
                .build());
            return chain.proceed(builder.build());
        }
    }
};
</code>```

This OkHttp (the networking library that powers Retrofit) Interceptor will check if the given URL has a query and replace any '&' in the query section with a ';'. In theory this should behave as you specified.

It can be applied by creating the OkHttpClient instance yourself and installing the abovementioned Interceptor while building it.

Title: Retrofit queries without ampersand

Body:
I'm trying to send requests to an API that uses semicolon(;) instead of ampersand(&) for query parameters, The url request looks like this:

http://api.example.com/path/?param1=p1;param2=p2

The most similar post I found on the internet suggests to use another method that puts url parts together and then use @Url annotation.

Does retrofit contain any solution for these cases ?

Thanks.

Body:
It is possible to use an Interceptor to rewrite the URL from using '&' to ';'. The tricky part is doing it in a way that does not make the URL invalid.

new Interceptor() {
    Response intercept(Chain chain) throws IOException {
        HttpUrl originalUrl = chain.request().url();
        String query = originalUrl.encodedQuery();
        if (query == null) {
            return chain.proceed(chain.request());
        } else {
            Request.Builder builder = chain.request().newBuilder();
            builder.url(originalUrl.newBuilder()
                .encodedQuery(query.replace('&', ';'))
                .build());
            return chain.proceed(builder.build());
        }
    }
};

This OkHttp (the networking library that powers Retrofit) Interceptor will check if the given URL has a query and replace any '&' in the query section with a ';'. In theory this should behave as you specified.

It can be applied by creating the OkHttpClient instance yourself and installing the abovementioned Interceptor while building it.


问:
How to execute multiple parallel tasks on completion of a prior task
I have a situation where I need to call a web service and, on successful completion, do multiple things with the results returned from the web service.  I have developed code that "works" -- just not as I intended.  Specifically, I want to take the results from the call to the web service and pass those results onto multiple successive tasks that are to execute in parallel, but what I have at the moment executes the first successive task before starting the second.

I've put together a much simplified example of what I'm currently doing that'll hopefully help illustrate this situation.  First, the implementation:

```<code>public interface IConfigurationSettings
{
    int? ConfigurationSetting { get; set; }
}

public interface IPrintCommandHandler
{
    System.Threading.Tasks.Task<bool> ExecuteAsync(byte[] reportContent);
}

public interface ISaveCommandHandler
{
    System.Threading.Tasks.Task<bool> ExecuteAsync(byte[] reportContent);
}

public interface IWebService
{
    System.Threading.Tasks.Task<object> RetrieveReportAsync(string searchToken, string reportFormat);
}

public class ReportCommandHandler
{
    private readonly IConfigurationSettings _configurationSettings;
    private readonly IPrintCommandHandler _printCommandHandler;
    private readonly ISaveCommandHandler _saveCommandHandler;
    private readonly IWebService _webService;

    public ReportCommandHandler(IWebService webService, IPrintCommandHandler printCommandHandler, ISaveCommandHandler saveCommandHandler, IConfigurationSettings configurationSettings)
    {
        _webService = webService;
        _printCommandHandler = printCommandHandler;
        _saveCommandHandler = saveCommandHandler;
        _configurationSettings = configurationSettings;
    }

    public async Task<bool> ExecuteAsync(string searchToken)
    {
        var reportTask = _webService.RetrieveReportAsync(searchToken, "PDF");
        var nextStepTasks = new List<Task<bool>>();

        // Run "print" task after report task.
        var printTask = await reportTask.ContinueWith(task => _printCommandHandler.ExecuteAsync((byte[]) task.Result));
        nextStepTasks.Add(printTask);

        // Run "save" task after report task.
        if (_configurationSettings.ConfigurationSetting.HasValue)
        {
            var saveTask = await reportTask.ContinueWith(task => _saveCommandHandler.ExecuteAsync((byte[]) task.Result));
            nextStepTasks.Add(saveTask);
        }

        var reportTaskResult = await Task.WhenAll(nextStepTasks);
        return reportTaskResult.Aggregate(true, (current, result) => current & result);
    }
}
</code>```

So, the web service (third party, nothing to do with me) has an endpoint for doing a search/lookup that, if successful, returns a reference number (I've called it a search token in my example).  This reference number is then used to retrieve the results of the lookup (using a different endpoint) in any of several different formats.

The IWebService interface in this example is representative of an application service I created to manage interaction with the web service.  The actual implementation has other methods on it for doing a lookup, ping, etc.

Just to make things more interesting, one of the successive tasks is required (will always execute after the primary task) but the other successive task is optional, execution subject to a configuration setting set elsewhere in the application.

To more easily demonstrate the issue, I created a unit test:

```<code>public class RhinoMockRepository : IDisposable
{
    private readonly ArrayList _mockObjectRepository;

    public RhinoMockRepository()
    {
        _mockObjectRepository = new ArrayList();
    }

    public T CreateMock<T>() where T : class
    {
        var mock = MockRepository.GenerateMock<T>();
        _mockObjectRepository.Add(mock);
        return mock;
    }

    public T CreateStub<T>() where T : class
    {
        return MockRepository.GenerateStub<T>();
    }

    public void Dispose()
    {
        foreach (var obj in _mockObjectRepository) obj.VerifyAllExpectations();
        _mockObjectRepository.Clear();
    }
}

[TestFixture]
public class TapTest
{
    private const string SearchToken = "F71C8B50-ECD1-4C02-AD3F-6C24F1AF3D9A";

    [Test]
    public void ReportCommandExecutesPrintAndSave()
    {
        using (var repository = new RhinoMockRepository())
        {
            // Arrange
            const string reportContent = "This is a PDF file.";
            var reportContentBytes = System.Text.Encoding.Default.GetBytes(reportContent);

            var retrieveReportResult = System.Threading.Tasks.Task.FromResult<object>(reportContentBytes);
            var webServiceMock = repository.CreateMock<IWebService>();
            webServiceMock.Stub(x => x.RetrieveReportAsync(SearchToken, "PDF")).Return(retrieveReportResult);

            var printCommandHandlerMock = repository.CreateMock<IPrintCommandHandler>();
            var printResult = System.Threading.Tasks.Task.FromResult(true);
            printCommandHandlerMock
                .Expect(x => x.ExecuteAsync(reportContentBytes))
                //.WhenCalled(method => System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)))
                .Return(printResult);

            var configurationSettingsStub = repository.CreateStub<IConfigurationSettings>();
            configurationSettingsStub.ConfigurationSetting = 10;

            var saveCommandHandlerMock = repository.CreateMock<ISaveCommandHandler>();
            var saveResult = System.Threading.Tasks.Task.FromResult(true);
            saveCommandHandlerMock.Expect(x => x.ExecuteAsync(reportContentBytes)).Return(saveResult);

            // Act
            var reportCommandHandler = new ReportCommandHandler(webServiceMock, printCommandHandlerMock, saveCommandHandlerMock, configurationSettingsStub);
            var result = System.Threading.Tasks.Task
                .Run(async () => await reportCommandHandler.ExecuteAsync(SearchToken))
                .Result;

            // Assert
            Assert.That(result, Is.True);
        }
    }
}
</code>```

Ideally, on completion of the call to RetrieveReportAsync() on IWebService both the "print" and "save" command handlers should be executed simultaneously, having received a copy of the results from RetrieveReportAsync().  However, if the call to WhenCalled... in the unit test is uncommented, and on stepping through the implementation of ReportCommandHandler.ExecuteAsync(), you can see that the "print" command executes and completes before it gets to the "save" command.  Now, I am aware that the whole point of await is to suspend execution of the calling async method until the awaited code completes, but it isn't clear to me how to instantiate both the "print" and "save" commands (tasks) as continuations of the "report" task such that they both execute in parallel when the "report" task completes, and the "report" command is then able to return a result that is based on the results from both the "print" and "save" commands (tasks).

答:
Your question really involves addressing two different goals:

How to wait for a task?

How to execute two other tasks concurrently?

I find the mixing of await and ContinueWith() in your code confusing. It's not clear to me why you did that. One of the key things await does for you is to automatically set up a continuation, so you don't have to call ContinueWith() explicitly. Yet, you do anyway.

On the assumption that's simply a mistake, out of lack of full understanding of how to accomplish your goal, here's how I'd have written your method:

```<code>public async Task<bool> ExecuteAsync(string searchToken)
{
    var reportTaskResult = await _webService.RetrieveReportAsync(searchToken, "PDF");
    var nextStepTasks = new List<Task<bool>>();

    // Run "print" task after report task.
    var printTask = _printCommandHandler.ExecuteAsync((byte[]) reportTaskResult);
    nextStepTasks.Add(printTask);

    // Run "save" task after report task.
    if (_configurationSettings.ConfigurationSetting.HasValue)
    {
        var saveTask = _saveCommandHandler.ExecuteAsync((byte[]) reportTaskResult);
        nextStepTasks.Add(saveTask);
    }

    var reportTaskResult = await Task.WhenAll(nextStepTasks);
    return reportTaskResult.Aggregate(false, (current, result) => current | result);
}
</code>```

In other words, do await the original task first. Then you know it's done and have its result. At that time, go ahead and start the other tasks, adding their Task object to your list, but not awaiting each one individually. Finally, await the entire list of tasks.

Body:
I have a situation where I need to call a web service and, on successful completion, do multiple things with the results returned from the web service.  I have developed code that "works" -- just not as I intended.  Specifically, I want to take the results from the call to the web service and pass those results onto multiple successive tasks that are to execute in parallel, but what I have at the moment executes the first successive task before starting the second.

I've put together a much simplified example of what I'm currently doing that'll hopefully help illustrate this situation.  First, the implementation:

public interface IConfigurationSettings
{
    int? ConfigurationSetting { get; set; }
}

public interface IPrintCommandHandler
{
    System.Threading.Tasks.Task<bool> ExecuteAsync(byte[] reportContent);
}

public interface ISaveCommandHandler
{
    System.Threading.Tasks.Task<bool> ExecuteAsync(byte[] reportContent);
}

public interface IWebService
{
    System.Threading.Tasks.Task<object> RetrieveReportAsync(string searchToken, string reportFormat);
}

public class ReportCommandHandler
{
    private readonly IConfigurationSettings _configurationSettings;
    private readonly IPrintCommandHandler _printCommandHandler;
    private readonly ISaveCommandHandler _saveCommandHandler;
    private readonly IWebService _webService;

    public ReportCommandHandler(IWebService webService, IPrintCommandHandler printCommandHandler, ISaveCommandHandler saveCommandHandler, IConfigurationSettings configurationSettings)
    {
        _webService = webService;
        _printCommandHandler = printCommandHandler;
        _saveCommandHandler = saveCommandHandler;
        _configurationSettings = configurationSettings;
    }

    public async Task<bool> ExecuteAsync(string searchToken)
    {
        var reportTask = _webService.RetrieveReportAsync(searchToken, "PDF");
        var nextStepTasks = new List<Task<bool>>();

        // Run "print" task after report task.
        var printTask = await reportTask.ContinueWith(task => _printCommandHandler.ExecuteAsync((byte[]) task.Result));
        nextStepTasks.Add(printTask);

        // Run "save" task after report task.
        if (_configurationSettings.ConfigurationSetting.HasValue)
        {
            var saveTask = await reportTask.ContinueWith(task => _saveCommandHandler.ExecuteAsync((byte[]) task.Result));
            nextStepTasks.Add(saveTask);
        }

        var reportTaskResult = await Task.WhenAll(nextStepTasks);
        return reportTaskResult.Aggregate(true, (current, result) => current & result);
    }
}

So, the web service (third party, nothing to do with me) has an endpoint for doing a search/lookup that, if successful, returns a reference number (I've called it a search token in my example).  This reference number is then used to retrieve the results of the lookup (using a different endpoint) in any of several different formats.

The IWebService interface in this example is representative of an application service I created to manage interaction with the web service.  The actual implementation has other methods on it for doing a lookup, ping, etc.

Just to make things more interesting, one of the successive tasks is required (will always execute after the primary task) but the other successive task is optional, execution subject to a configuration setting set elsewhere in the application.

To more easily demonstrate the issue, I created a unit test:

public class RhinoMockRepository : IDisposable
{
    private readonly ArrayList _mockObjectRepository;

    public RhinoMockRepository()
    {
        _mockObjectRepository = new ArrayList();
    }

    public T CreateMock<T>() where T : class
    {
        var mock = MockRepository.GenerateMock<T>();
        _mockObjectRepository.Add(mock);
        return mock;
    }

    public T CreateStub<T>() where T : class
    {
        return MockRepository.GenerateStub<T>();
    }

    public void Dispose()
    {
        foreach (var obj in _mockObjectRepository) obj.VerifyAllExpectations();
        _mockObjectRepository.Clear();
    }
}

[TestFixture]
public class TapTest
{
    private const string SearchToken = "F71C8B50-ECD1-4C02-AD3F-6C24F1AF3D9A";

    [Test]
    public void ReportCommandExecutesPrintAndSave()
    {
        using (var repository = new RhinoMockRepository())
        {
            // Arrange
            const string reportContent = "This is a PDF file.";
            var reportContentBytes = System.Text.Encoding.Default.GetBytes(reportContent);

            var retrieveReportResult = System.Threading.Tasks.Task.FromResult<object>(reportContentBytes);
            var webServiceMock = repository.CreateMock<IWebService>();
            webServiceMock.Stub(x => x.RetrieveReportAsync(SearchToken, "PDF")).Return(retrieveReportResult);

            var printCommandHandlerMock = repository.CreateMock<IPrintCommandHandler>();
            var printResult = System.Threading.Tasks.Task.FromResult(true);
            printCommandHandlerMock
                .Expect(x => x.ExecuteAsync(reportContentBytes))
                //.WhenCalled(method => System.Threading.Thread.Sleep(TimeSpan.FromSeconds(2)))
                .Return(printResult);

            var configurationSettingsStub = repository.CreateStub<IConfigurationSettings>();
            configurationSettingsStub.ConfigurationSetting = 10;

            var saveCommandHandlerMock = repository.CreateMock<ISaveCommandHandler>();
            var saveResult = System.Threading.Tasks.Task.FromResult(true);
            saveCommandHandlerMock.Expect(x => x.ExecuteAsync(reportContentBytes)).Return(saveResult);

            // Act
            var reportCommandHandler = new ReportCommandHandler(webServiceMock, printCommandHandlerMock, saveCommandHandlerMock, configurationSettingsStub);
            var result = System.Threading.Tasks.Task
                .Run(async () => await reportCommandHandler.ExecuteAsync(SearchToken))
                .Result;

            // Assert
            Assert.That(result, Is.True);
        }
    }
}

Ideally, on completion of the call to RetrieveReportAsync() on IWebService both the "print" and "save" command handlers should be executed simultaneously, having received a copy of the results from RetrieveReportAsync().  However, if the call to WhenCalled... in the unit test is uncommented, and on stepping through the implementation of ReportCommandHandler.ExecuteAsync(), you can see that the "print" command executes and completes before it gets to the "save" command.  Now, I am aware that the whole point of await is to suspend execution of the calling async method until the awaited code completes, but it isn't clear to me how to instantiate both the "print" and "save" commands (tasks) as continuations of the "report" task such that they both execute in parallel when the "report" task completes, and the "report" command is then able to return a result that is based on the results from both the "print" and "save" commands (tasks).

Body:
Your question really involves addressing two different goals:

How to wait for a task?

How to execute two other tasks concurrently?

I find the mixing of await and ContinueWith() in your code confusing. It's not clear to me why you did that. One of the key things await does for you is to automatically set up a continuation, so you don't have to call ContinueWith() explicitly. Yet, you do anyway.

On the assumption that's simply a mistake, out of lack of full understanding of how to accomplish your goal, here's how I'd have written your method:

public async Task<bool> ExecuteAsync(string searchToken)
{
    var reportTaskResult = await _webService.RetrieveReportAsync(searchToken, "PDF");
    var nextStepTasks = new List<Task<bool>>();

    // Run "print" task after report task.
    var printTask = _printCommandHandler.ExecuteAsync((byte[]) reportTaskResult);
    nextStepTasks.Add(printTask);

    // Run "save" task after report task.
    if (_configurationSettings.ConfigurationSetting.HasValue)
    {
        var saveTask = _saveCommandHandler.ExecuteAsync((byte[]) reportTaskResult);
        nextStepTasks.Add(saveTask);
    }

    var reportTaskResult = await Task.WhenAll(nextStepTasks);
    return reportTaskResult.Aggregate(false, (current, result) => current | result);
}

In other words, do await the original task first. Then you know it's done and have its result. At that time, go ahead and start the other tasks, adding their Task object to your list, but not awaiting each one individually. Finally, await the entire list of tasks.


问:
How can I implement a makefile-style algorithm in python
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.

The input to this feature extraction system will be a graph detailing the links between the feature extraction blocks, and I'd like to work out which functions to run when based upon the graph.

An example of such a system might be the following:

```<code>            ,-> [B] -> [D] ----+
input --> [A]           ^      v
            `-> [C] ----+---> [E] --> output
</code>```

and the function calls (assuming each block X is a function of the form output = X(inputs) might be something like:

```<code>a = A(input)
b = B(a)
c = C(a)
d = D(b,c)  # can't call D until both b and c are ready
output = E(d,c)   # can't call E until both c and d are ready
</code>```

I already have the function graph loaded in the form of a dictionary with each dictionary entry of the form (inputs, function) like so:

```<code>blocks = {'A' : (('input'), A),
          'B' : (('A'), B),
          'C' : (('A'), C),
          'D' : (('B','C'), D),
          'output' : (('D','C'), E)}
</code>```

I'm just currently drawing a blank on what the makefile algorithm does exactly, and how to go about implementing it. My google-fu appears to be not-very-helpful here too. If someone at least can give me a pointer to a good discussion of the makefile algorithm that would probably be a good start.

答: Topological sorting</p>

Body:
I am implementing an acoustic feature extraction system in python, and I need to implement a makefile-style algorithm to ensure that all blocks in the feature extraction system are run in the correct order, and without repeating any feature extractions stages.

The input to this feature extraction system will be a graph detailing the links between the feature extraction blocks, and I'd like to work out which functions to run when based upon the graph.

An example of such a system might be the following:

            ,-> [B] -> [D] ----+
input --> [A]           ^      v
            `-> [C] ----+---> [E] --> output

and the function calls (assuming each block X is a function of the form output = X(inputs) might be something like:

a = A(input)
b = B(a)
c = C(a)
d = D(b,c)  # can't call D until both b and c are ready
output = E(d,c)   # can't call E until both c and d are ready

I already have the function graph loaded in the form of a dictionary with each dictionary entry of the form (inputs, function) like so:

blocks = {'A' : (('input'), A),
          'B' : (('A'), B),
          'C' : (('A'), C),
          'D' : (('B','C'), D),
          'output' : (('D','C'), E)}

I'm just currently drawing a blank on what the makefile algorithm does exactly, and how to go about implementing it. My google-fu appears to be not-very-helpful here too. If someone at least can give me a pointer to a good discussion of the makefile algorithm that would probably be a good start.

Body: Topological sorting


问:
SQL Query - Return field where data was found
I have a phone number search query in SQL and I would like to know how I can have a column displaying in what field data was found. There's any way to do that?
This is my query:

```<code>Select DISTINCT ST.SCHOOLID,
ST.STUDENT_NUMBER,
ST.LASTFIRST,
ST.GRADE_LEVEL
FROM PS.STUDENTS ST
LEFT OUTER JOIN PS.U_GUARDIANS GA
ON ST.DCID = GA.STUDENTSDCID
LEFT OUTER JOIN PS.U_DEMO DE
ON ST.DCID = DE.STUDENTSDCID
LEFT OUTER JOIN PS.U_EMERGENCY EME
ON ST.DCID = EME.STUDENTSDCID
LEFT OUTER JOIN PS.U_STUDENT_HISTORY PREV
ON ST.DCID = EME.STUDENTSDCID
WHERE ST.Home_Phone LIKE '%param1%'
OR DE.STUDENT_CELL LIKE '%param1%'
OR GA.G1_PHONE1 LIKE '%param1%'
OR GA.G1_PHONE2 LIKE '%param1%'
OR GA.G1_WORK_PHONE LIKE '%param1%'
OR GA.G2_PHONE1 LIKE '%param1%'
OR GA.G2_PHONE2 LIKE '%param1%'
OR GA.G2_WORK_PHONE LIKE '%param1%'
OR GA.G3_PHONE1 LIKE '%param1%'
OR GA.G3_PHONE2 LIKE '%param1%'
OR GA.G3_WORK_PHONE LIKE '%param1%'
OR GA.G4_PHONE1 LIKE '%param1%'
OR GA.G4_PHONE2 LIKE '%param1%'
OR GA.G4_WORK_PHONE LIKE '%param1%'
OR EME.EC1_Phone1 LIKE '%param1%'
OR EME.EC1_Phone2 LIKE '%param1%'
OR EME.EC2_Phone1 LIKE '%param1%'
OR EME.EC2_Phone2 LIKE '%param1%'
OR EME.EC3_Phone1 LIKE '%param1%'
OR EME.EC3_Phone2 LIKE '%param1%'
OR PREV.Prev_School_Phone LIKE '%param1%'
OR PREV.Prev_School_Fax LIKE '%param1%'
OR ST.Doctor_Phone LIKE '%param1%'
order by ST.lastfirst
</code>```

Thank you

答:
One way would be to use a CROSS APPLY:

```<code>Select DISTINCT
    ST.SCHOOLID,
    ST.STUDENT_NUMBER,
    ST.LASTFIRST,
    ST.GRADE_LEVEL,
    C.Col -- Column name
FROM PS.STUDENTS ST
LEFT OUTER JOIN PS.U_GUARDIANS GA
    ON ST.DCID = GA.STUDENTSDCID
LEFT OUTER JOIN PS.U_DEMO DE
    ON ST.DCID = DE.STUDENTSDCID
LEFT OUTER JOIN PS.U_EMERGENCY EME
    ON ST.DCID = EME.STUDENTSDCID
LEFT OUTER JOIN PS.U_STUDENT_HISTORY PREV
    ON ST.DCID = EME.STUDENTSDCID
CROSS APPLY
(
    VALUES
    ('ST.Home_Phone', ST.Home_Phone),
    ('DE.STUDENT_CELL', DE.STUDENT_CELL),
    ('GA.G1_PHONE1', GA.G1_PHONE1),
    ('GA.G1_PHONE2', GA.G1_PHONE2),
    ('GA.G1_WORK_PHONE', GA.G1_WORK_PHONE),
    ('GA.G2_PHONE1', GA.G2_PHONE1),
    ('GA.G2_PHONE2', GA.G2_PHONE2),
    ('GA.G2_WORK_PHONE', GA.G2_WORK_PHONE),
    ('GA.G3_PHONE1', GA.G3_PHONE1),
    ('GA.G3_PHONE2', GA.G3_PHONE2),
    ('GA.G3_WORK_PHONE', GA.G3_WORK_PHONE),
    ('GA.G4_PHONE1', GA.G4_PHONE1),
    ('GA.G4_PHONE2', GA.G4_PHONE2),
    ('GA.G4_WORK_PHONE', GA.G4_WORK_PHONE),
    ('EME.EC1_Phone1', EME.EC1_Phone1),
    ('EME.EC1_Phone2', EME.EC1_Phone2),
    ('EME.EC2_Phone1', EME.EC2_Phone1),
    ('EME.EC2_Phone2', EME.EC2_Phone2),
    ('EME.EC3_Phone1', EME.EC3_Phone1),
    ('EME.EC3_Phone2', EME.EC3_Phone2),
    ('PREV.Prev_School_Phone', PREV.Prev_School_Phone),
    ('PREV.Prev_School_Fax', PREV.Prev_School_Fax),
    ('ST.Doctor_Phone', ST.Doctor_Phone)
) AS C(Col, Val)
WHERE C.Val LIKE '%param1%'
ORDER BY ST.lastfirst;
</code>```

If the column types are not the same type (e.g. one is an integer), this may throw an error, in which case you'll need to convert the columns to the same type in the cross apply.

This method will also duplicate the rows for each column that matches (e.g. if it matches on columns A and B, you'll get one row with val1, val2, val3, val4, A and one row with val1, val2, val3, val4, B). This could be fixed with a slight adjustment to how the cross apply works if that is an issue.

EDIT:

As an example with sample data, running this will show you what the query should do:

```<code>DECLARE @T TABLE
(
    SchoolID INT NOT NULL, Student_Number INT NOT NULL, LastFirst INT NOT NULL, Grade_Level INT NOT NULL,
    Home_Phone VARCHAR(255), Student_Cell VARCHAR(255), Phone1 VARCHAR(255), Phone2 VARCHAR(255), Phone3 VARCHAR(255),
    Phone4 VARCHAR(255), RandomColumnName VARCHAR(255), ABCDEFGHIJKL VARCHAR(255)
);

INSERT @T (SchoolID, Student_Number, LastFirst, Grade_Level, Home_Phone, Student_Cell, Phone1, Phone2, Phone3, Phone4, RandomColumnName, ABCDEFGHIJKL) VALUES
(1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 'sdgfagagparam1sdasf', NULL, NULL),
(1, 1, 1, 2, NULL, NULL, NULL, NULL, 'asdfparam1sadf', NULL, NULL, NULL),
(1, 1, 1, 3, NULL, NULL, 'param1asdf', NULL, NULL, NULL, NULL, NULL),
(1, 1, 2, 1, NULL, NULL, NULL, NULL, NULL, NULL, 'adfparam1', NULL),
(1, 1, 2, 2, NULL, 'qqqparam1', NULL, NULL, NULL, NULL, NULL, NULL),
(1, 2, 1, 2, NULL, NULL, NULL, NULL, 'param1', NULL, NULL, 'param1'),
(2, 1, 1, 2, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

SELECT DISTINCT
    T.SchoolID,
    T.Student_Number,
    T.LastFirst,
    T.Grade_Level,
    C.Col
FROM @T AS T
CROSS APPLY
(
    VALUES
    ('Home_Phone', Home_Phone),
    ('Student_Cell', Student_Cell),
    ('Phone1', Phone1),
    ('Phone2', Phone2),
    ('Phone3', Phone3),
    ('Phone4', Phone4),
    ('RandomColumnName', RandomColumnName),
    ('ABCDEFGHIJKL', ABCDEFGHIJKL)
) AS C(Col, Val)
WHERE C.Val LIKE '%param1%';
</code>```

Body:
I have a phone number search query in SQL and I would like to know how I can have a column displaying in what field data was found. There's any way to do that?
This is my query:

Select DISTINCT ST.SCHOOLID,
ST.STUDENT_NUMBER,
ST.LASTFIRST,
ST.GRADE_LEVEL
FROM PS.STUDENTS ST
LEFT OUTER JOIN PS.U_GUARDIANS GA
ON ST.DCID = GA.STUDENTSDCID
LEFT OUTER JOIN PS.U_DEMO DE
ON ST.DCID = DE.STUDENTSDCID
LEFT OUTER JOIN PS.U_EMERGENCY EME
ON ST.DCID = EME.STUDENTSDCID
LEFT OUTER JOIN PS.U_STUDENT_HISTORY PREV
ON ST.DCID = EME.STUDENTSDCID
WHERE ST.Home_Phone LIKE '%param1%'
OR DE.STUDENT_CELL LIKE '%param1%'
OR GA.G1_PHONE1 LIKE '%param1%'
OR GA.G1_PHONE2 LIKE '%param1%'
OR GA.G1_WORK_PHONE LIKE '%param1%'
OR GA.G2_PHONE1 LIKE '%param1%'
OR GA.G2_PHONE2 LIKE '%param1%'
OR GA.G2_WORK_PHONE LIKE '%param1%'
OR GA.G3_PHONE1 LIKE '%param1%'
OR GA.G3_PHONE2 LIKE '%param1%'
OR GA.G3_WORK_PHONE LIKE '%param1%'
OR GA.G4_PHONE1 LIKE '%param1%'
OR GA.G4_PHONE2 LIKE '%param1%'
OR GA.G4_WORK_PHONE LIKE '%param1%'
OR EME.EC1_Phone1 LIKE '%param1%'
OR EME.EC1_Phone2 LIKE '%param1%'
OR EME.EC2_Phone1 LIKE '%param1%'
OR EME.EC2_Phone2 LIKE '%param1%'
OR EME.EC3_Phone1 LIKE '%param1%'
OR EME.EC3_Phone2 LIKE '%param1%'
OR PREV.Prev_School_Phone LIKE '%param1%'
OR PREV.Prev_School_Fax LIKE '%param1%'
OR ST.Doctor_Phone LIKE '%param1%'
order by ST.lastfirst

Thank you

Body:
One way would be to use a CROSS APPLY:

Select DISTINCT
    ST.SCHOOLID,
    ST.STUDENT_NUMBER,
    ST.LASTFIRST,
    ST.GRADE_LEVEL,
    C.Col -- Column name
FROM PS.STUDENTS ST
LEFT OUTER JOIN PS.U_GUARDIANS GA
    ON ST.DCID = GA.STUDENTSDCID
LEFT OUTER JOIN PS.U_DEMO DE
    ON ST.DCID = DE.STUDENTSDCID
LEFT OUTER JOIN PS.U_EMERGENCY EME
    ON ST.DCID = EME.STUDENTSDCID
LEFT OUTER JOIN PS.U_STUDENT_HISTORY PREV
    ON ST.DCID = EME.STUDENTSDCID
CROSS APPLY
(
    VALUES
    ('ST.Home_Phone', ST.Home_Phone),
    ('DE.STUDENT_CELL', DE.STUDENT_CELL),
    ('GA.G1_PHONE1', GA.G1_PHONE1),
    ('GA.G1_PHONE2', GA.G1_PHONE2),
    ('GA.G1_WORK_PHONE', GA.G1_WORK_PHONE),
    ('GA.G2_PHONE1', GA.G2_PHONE1),
    ('GA.G2_PHONE2', GA.G2_PHONE2),
    ('GA.G2_WORK_PHONE', GA.G2_WORK_PHONE),
    ('GA.G3_PHONE1', GA.G3_PHONE1),
    ('GA.G3_PHONE2', GA.G3_PHONE2),
    ('GA.G3_WORK_PHONE', GA.G3_WORK_PHONE),
    ('GA.G4_PHONE1', GA.G4_PHONE1),
    ('GA.G4_PHONE2', GA.G4_PHONE2),
    ('GA.G4_WORK_PHONE', GA.G4_WORK_PHONE),
    ('EME.EC1_Phone1', EME.EC1_Phone1),
    ('EME.EC1_Phone2', EME.EC1_Phone2),
    ('EME.EC2_Phone1', EME.EC2_Phone1),
    ('EME.EC2_Phone2', EME.EC2_Phone2),
    ('EME.EC3_Phone1', EME.EC3_Phone1),
    ('EME.EC3_Phone2', EME.EC3_Phone2),
    ('PREV.Prev_School_Phone', PREV.Prev_School_Phone),
    ('PREV.Prev_School_Fax', PREV.Prev_School_Fax),
    ('ST.Doctor_Phone', ST.Doctor_Phone)
) AS C(Col, Val)
WHERE C.Val LIKE '%param1%'
ORDER BY ST.lastfirst;

If the column types are not the same type (e.g. one is an integer), this may throw an error, in which case you'll need to convert the columns to the same type in the cross apply.

This method will also duplicate the rows for each column that matches (e.g. if it matches on columns A and B, you'll get one row with val1, val2, val3, val4, A and one row with val1, val2, val3, val4, B). This could be fixed with a slight adjustment to how the cross apply works if that is an issue.

EDIT:

As an example with sample data, running this will show you what the query should do:

DECLARE @T TABLE
(
    SchoolID INT NOT NULL, Student_Number INT NOT NULL, LastFirst INT NOT NULL, Grade_Level INT NOT NULL,
    Home_Phone VARCHAR(255), Student_Cell VARCHAR(255), Phone1 VARCHAR(255), Phone2 VARCHAR(255), Phone3 VARCHAR(255),
    Phone4 VARCHAR(255), RandomColumnName VARCHAR(255), ABCDEFGHIJKL VARCHAR(255)
);

INSERT @T (SchoolID, Student_Number, LastFirst, Grade_Level, Home_Phone, Student_Cell, Phone1, Phone2, Phone3, Phone4, RandomColumnName, ABCDEFGHIJKL) VALUES
(1, 1, 1, 1, NULL, NULL, NULL, NULL, NULL, 'sdgfagagparam1sdasf', NULL, NULL),
(1, 1, 1, 2, NULL, NULL, NULL, NULL, 'asdfparam1sadf', NULL, NULL, NULL),
(1, 1, 1, 3, NULL, NULL, 'param1asdf', NULL, NULL, NULL, NULL, NULL),
(1, 1, 2, 1, NULL, NULL, NULL, NULL, NULL, NULL, 'adfparam1', NULL),
(1, 1, 2, 2, NULL, 'qqqparam1', NULL, NULL, NULL, NULL, NULL, NULL),
(1, 2, 1, 2, NULL, NULL, NULL, NULL, 'param1', NULL, NULL, 'param1'),
(2, 1, 1, 2, NULL, NULL, NULL, NULL, NULL, NULL, NULL, NULL);

SELECT DISTINCT
    T.SchoolID,
    T.Student_Number,
    T.LastFirst,
    T.Grade_Level,
    C.Col
FROM @T AS T
CROSS APPLY
(
    VALUES
    ('Home_Phone', Home_Phone),
    ('Student_Cell', Student_Cell),
    ('Phone1', Phone1),
    ('Phone2', Phone2),
    ('Phone3', Phone3),
    ('Phone4', Phone4),
    ('RandomColumnName', RandomColumnName),
    ('ABCDEFGHIJKL', ABCDEFGHIJKL)
) AS C(Col, Val)
WHERE C.Val LIKE '%param1%';


问:
Two-Way Binding in Component Scope
Suppose I'm trying to make a simple questionnaire, where the user answers a list of questions.

```<code>new Vue(
{
    el: "#app",
    data:
    {
        questions:
        [
            {
                id: 1,
                name: "What is your favorite color?",
                selectedId: 2,
                choices:
                [
                    { id: 1, name: "red" },
                    { id: 2, name: "green" },
                    { id: 3, name: "blue" },
                ]
            },
            ...
        ]
    }
});
</code>```

How do I go about making a question component with two-way binding.  That is, if the user swaps their favorite color from green to red, by clicking on the respective input, the selectedId will automatically update.  I'm not very clear on how v-model works within a component.  Does it only have access to the components data?  Also, I don't understand the difference between props/data.

答:
There are lots of ways you can approach this, here's my attempt:

let id = 0;

Vue.component('question', {
  template: '#question',
  props: ['question'],
  data() {
    return {
      radioGroup: `question-${id++}`,
    };
  },
  methods: {
    onChange(choice) {
      this.question.selectedId = choice.id;
    },

    isChoiceSelected(choice) {
      return this.question.selectedId === choice.id;
    },
  },
});

new Vue({
  el: '#app',
  data: {
    questions: [
      {
        title: 'What is your favorite color?',
        selectedId: null,
        choices: [
          { id: 1, text: 'Red' },
          { id: 2, text: 'Green' },
          { id: 3, text: 'Blue' },
        ],
      },
      {
        title: 'What is your favorite food?',
        selectedId: null,
        choices: [
          { id: 1, text: 'Beans' },
          { id: 2, text: 'Pizza' },
          { id: 3, text: 'Something else' },
        ],
      },
    ],
  },
});```
<pre class="snippet-code-css lang-css prettyprint-override"><code>.question {
  margin: 20px 0;
}</code>```

  <question v-for="question of questions" :question="question"></question>

<template id="question">

{{ question.title }}

      <input type="radio" :name="radioGroup" :checked="isChoiceSelected(choice)" @change="onChange(choice)"> {{ choice.text }}

selectedId: {{ question.selectedId }}

</template>```

Title: Two-Way Binding in Component Scope

Body:
Suppose I'm trying to make a simple questionnaire, where the user answers a list of questions.

new Vue(
{
    el: "#app",
    data:
    {
        questions:
        [
            {
                id: 1,
                name: "What is your favorite color?",
                selectedId: 2,
                choices:
                [
                    { id: 1, name: "red" },
                    { id: 2, name: "green" },
                    { id: 3, name: "blue" },
                ]
            },
            ...
        ]
    }
});

How do I go about making a question component with two-way binding.  That is, if the user swaps their favorite color from green to red, by clicking on the respective input, the selectedId will automatically update.  I'm not very clear on how v-model works within a component.  Does it only have access to the components data?  Also, I don't understand the difference between props/data.

Body:
There are lots of ways you can approach this, here's my attempt:

let id = 0;

Vue.component('question', {
  template: '#question',
  props: ['question'],
  data() {
    return {
      radioGroup: `question-${id++}`,
    };
  },
  methods: {
    onChange(choice) {
      this.question.selectedId = choice.id;
    },

    isChoiceSelected(choice) {
      return this.question.selectedId === choice.id;
    },
  },
});

new Vue({
  el: '#app',
  data: {
    questions: [
      {
        title: 'What is your favorite color?',
        selectedId: null,
        choices: [
          { id: 1, text: 'Red' },
          { id: 2, text: 'Green' },
          { id: 3, text: 'Blue' },
        ],
      },
      {
        title: 'What is your favorite food?',
        selectedId: null,
        choices: [
          { id: 1, text: 'Beans' },
          { id: 2, text: 'Pizza' },
          { id: 3, text: 'Something else' },
        ],
      },
    ],
  },
});

.question {
  margin: 20px 0;
}

<script src="https://rawgit.com/yyx990803/vue/master/dist/vue.js"></script>

<div id="app">
  <question v-for="question of questions" :question="question"></question>
</div>

<template id="question">
  <div class="question">
    <div>{{ question.title }}</div>
    <div v-for="choice of question.choices">
      <input type="radio" :name="radioGroup" :checked="isChoiceSelected(choice)" @change="onChange(choice)"> {{ choice.text }}
    </div>
    <div>selectedId: {{ question.selectedId }}</div>
  </div>
</template>


问:
SELECT previous year data based on year column
I am trying to develop a SSRS report. I have taken sales values from a transactional table and grouped them by year, month and subcategory. I have created this as a view. Here is the view code:

```<code>SELECT b.FiscalYear AS Year,
       b.FiscalMonth AS Month,
       a.SubCategoryKey,
       MAX(a.SubCategoryDesc) AS SubCategoryDesc,
       SUM(CAST(a.Cost + a.FreightCost AS decimal(18, 2))) AS TotalCost,
       SUM(CAST(a.SalesAmount AS decimal(18, 2))) AS   TotalSales,
SUM(CAST(a.Weight AS decimal(18, 2))) AS Pounds, SUM(CAST(a.SalesAmount -(a.Cost + a.FreightCost) AS decimal(18, 2))) AS Margin
FROM dbo.GrossMargin_CorrectedCosts AS a
LEFT OUTER JOIN dbo.M_DateDim AS b ON a.InvoiceDate = b.Date
GROUP BY b.FiscalYear, b.FiscalMonth, a.SubCategoryKey
</code>```

I am then left with a clean view that looks like this:

```<code>SELECT [Year]
  ,[Month]
  ,[SubCategoryKey]
  ,[SubCategoryDesc]
  ,[TotalCost]
  ,[TotalSales]
  ,[Pounds]
  ,[Margin]
  FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V]\
</code>```

I'd now like to add additonal columns to this query. I am going to run this as a SSRS report and pass both Year and Month parameters. What I'd like to do is when 2017 is selected as the passed Year parameters, then I would like to show previous year values for TotalSales, TotalCost and Pounds.

Whereas the query would look something like this:

```<code>SELECT [Year]
  ,[Month]
  ,[SubCategoryKey]
  ,[SubCategoryDesc]
  ,[TotalCost]
  ,[TotalSales]
  ,[Pounds]
  ,[Margin]
  ,PreviousYearTotalSales
  ,PreviousYearTotalCost
  ,PreviousYearPounds
  FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V]
</code>```

Essentially when a year and month is passed to the report, I'd like to show the previous years totalsales, totalcost and pounds for that given period minus one year. I am having a heck of time doing this.

I feel like I have tried everything but obviously not. Please help.

答:
Something that could work now that you have a view to work with is the following query.

```<code>SELECT CY.[Year]
,CY.[Month]
,CY.[SubCategoryKey]
,CY.[SubCategoryDesc]
,CY.[TotalCost]
,CY.[TotalSales]
,CY.[Pounds]
,CY.[Margin]
,PY.[TotalSales] AS PreviousYearTotalSales
,PY.[TotalCost] AS PreviousYearTotalCost
,PY.[Pounds] AS PreviousYearPounds
FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V] CY LEFT JOIN [FinancialData].[dbo].[SubCategorySalesbyMonth_V] PY
ON CY.[Year] - 1 = PY.[Year]
AND CY.[Month] = PY.[Month]
AND CY.[SubCategoryKey] = PY.[SubCategoryKey]
AND CY.[Month] = PY.[Month]
</code>```

This is just a simple self left join to the same view, but the year from the current year (CY) is joining back to the prior year (PY), year - 1. It is a LEFT JOIN, so the prior year's values will be null if there isn't any prior year/month's data available.

Hope this helps.

Body:
I am trying to develop a SSRS report. I have taken sales values from a transactional table and grouped them by year, month and subcategory. I have created this as a view. Here is the view code:

SELECT b.FiscalYear AS Year,
       b.FiscalMonth AS Month,
       a.SubCategoryKey,
       MAX(a.SubCategoryDesc) AS SubCategoryDesc,
       SUM(CAST(a.Cost + a.FreightCost AS decimal(18, 2))) AS TotalCost,
       SUM(CAST(a.SalesAmount AS decimal(18, 2))) AS   TotalSales,
SUM(CAST(a.Weight AS decimal(18, 2))) AS Pounds, SUM(CAST(a.SalesAmount -(a.Cost + a.FreightCost) AS decimal(18, 2))) AS Margin
FROM dbo.GrossMargin_CorrectedCosts AS a
LEFT OUTER JOIN dbo.M_DateDim AS b ON a.InvoiceDate = b.Date
GROUP BY b.FiscalYear, b.FiscalMonth, a.SubCategoryKey

I am then left with a clean view that looks like this:

SELECT [Year]
  ,[Month]
  ,[SubCategoryKey]
  ,[SubCategoryDesc]
  ,[TotalCost]
  ,[TotalSales]
  ,[Pounds]
  ,[Margin]
  FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V]\

I'd now like to add additonal columns to this query. I am going to run this as a SSRS report and pass both Year and Month parameters. What I'd like to do is when 2017 is selected as the passed Year parameters, then I would like to show previous year values for TotalSales, TotalCost and Pounds.

Whereas the query would look something like this:

SELECT [Year]
  ,[Month]
  ,[SubCategoryKey]
  ,[SubCategoryDesc]
  ,[TotalCost]
  ,[TotalSales]
  ,[Pounds]
  ,[Margin]
  ,PreviousYearTotalSales
  ,PreviousYearTotalCost
  ,PreviousYearPounds
  FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V]

Essentially when a year and month is passed to the report, I'd like to show the previous years totalsales, totalcost and pounds for that given period minus one year. I am having a heck of time doing this.

I feel like I have tried everything but obviously not. Please help.

Body:
Something that could work now that you have a view to work with is the following query.

SELECT CY.[Year]
,CY.[Month]
,CY.[SubCategoryKey]
,CY.[SubCategoryDesc]
,CY.[TotalCost]
,CY.[TotalSales]
,CY.[Pounds]
,CY.[Margin]
,PY.[TotalSales] AS PreviousYearTotalSales
,PY.[TotalCost] AS PreviousYearTotalCost
,PY.[Pounds] AS PreviousYearPounds
FROM [FinancialData].[dbo].[SubCategorySalesbyMonth_V] CY LEFT JOIN [FinancialData].[dbo].[SubCategorySalesbyMonth_V] PY
ON CY.[Year] - 1 = PY.[Year]
AND CY.[Month] = PY.[Month]
AND CY.[SubCategoryKey] = PY.[SubCategoryKey]
AND CY.[Month] = PY.[Month]

This is just a simple self left join to the same view, but the year from the current year (CY) is joining back to the prior year (PY), year - 1. It is a LEFT JOIN, so the prior year's values will be null if there isn't any prior year/month's data available.

Hope this helps.


问:
How to delete object from arrayObject in php?
I want delete object from arrayObject in php, but in deleteComputer method show this error: "Warning: Illegal offset type", help me pls, Im starting with php :)

i've:

```<code>       class ControllerList {

            private $computers;

            function __construct() {
                $this->computers= new ArrayObject();

            }

         public function addComputer($computer) {
             $this->computers->append($computer);
         }

         public function deleteComputer($computerNumber) {
             foreach ($this->computers as $value) {
                 if($value->getNumber() == computerNumber){
                    unset($this->computers[$value]);
                    echo 'Delete!!';
                 } else {
                    echo 'Don't delete!!';
                 }
               }
         }

        }
</code>```

Main file:/

```<code>         $list = new ControllerList();

         $computer1 = new Computer();
         $computer1->setNumber(001);
         $computer1->setColor("Black");

         $computer2 = new Computer();
         $computer2->setNumber(002);
         $computer2->setColor("White");

         $list->addComputer($computer1);
         $list->addComputer($computer2);

         $list->deleteComputer(001);  --> error method
</code>```

答:
$value is an object, not an array index. You need to add the array index to the foreach loop:

```<code>foreach ($this->computers as $i => $value) {
    if($value->getNumber() == $computerNumber){
        unset($this->computers[$i]);
        echo 'Delete!!';
    } else {
        echo 'Don't delete!!';
    }
}
</code>```

Body:
I want delete object from arrayObject in php, but in deleteComputer method show this error: "Warning: Illegal offset type", help me pls, Im starting with php :)

i've:

       class ControllerList {

            private $computers;

            function __construct() {
                $this->computers= new ArrayObject();

            }

         public function addComputer($computer) {
             $this->computers->append($computer);
         }

         public function deleteComputer($computerNumber) {
             foreach ($this->computers as $value) {
                 if($value->getNumber() == computerNumber){
                    unset($this->computers[$value]);
                    echo 'Delete!!';
                 } else {
                    echo 'Don't delete!!';
                 }
               }
         }

        }

Main file:/

         $list = new ControllerList();

         $computer1 = new Computer();
         $computer1->setNumber(001);
         $computer1->setColor("Black");

         $computer2 = new Computer();
         $computer2->setNumber(002);
         $computer2->setColor("White");

         $list->addComputer($computer1);
         $list->addComputer($computer2);

         $list->deleteComputer(001);  --> error method

Body:
$value is an object, not an array index. You need to add the array index to the foreach loop:

foreach ($this->computers as $i => $value) {
    if($value->getNumber() == $computerNumber){
        unset($this->computers[$i]);
        echo 'Delete!!';
    } else {
        echo 'Don't delete!!';
    }
}


问:
Get FullPath in WPF treeview?
If I create a WPF TreeView programmatically, for example:

```<code>// TreeView treeView; <- added in the designer
TreeViewItem rootNode = new TreeViewItem();
rootNode.Header = "RootNode"
treeView.Items.Add(rootNode);

TreeViewItem subNode1 = new TreeViewItem();
subNode1.Header = "SubNode1";
rootNode.Items.Add(subNode1);

TreeViewItem subNode2 = new TreeViewItem();
subNode2.Header = "SubNode2";
rootNode.Items.Add(subNode2);
</code>```

However, I would like to get the path to a certain node in the treeview much like the FullPath property in the System.Windows.Forms.TreeNode class. So the path for subNode2 would be RootNode//SubNode2. How do I do this?

Edit: I am not looking for the manual solution, however I am wondering if there is an equivalent accessor like FullPath or if I'm going about using the WPF TreeView class in the wrong way. Eg. I've looked at DisplayMemberPath and SelectedValuePath but they don't seem to provide the result I'm after.

答:
See below code.

So this function returns a stack in which top most item will be root and last item will be the immediate parent of element.

```<code>public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        TreeViewItem rootNode = new TreeViewItem();
        rootNode.Header = "RootNode";
        treeView.Items.Add(rootNode);

        TreeViewItem subNode1 = new TreeViewItem();
        subNode1.Header = "SubNode1";
        rootNode.Items.Add(subNode1);

        TreeViewItem subNode2 = new TreeViewItem();
        subNode2.Header = "SubNode2";
        rootNode.Items.Add(subNode2);

        TreeViewItem subNode3 = new TreeViewItem();
        subNode3.Header = "SubNode3";
        subNode2.Items.Add(subNode3);
    }

    public static Stack<TreeViewItem> GetNodeParent(UIElement element)
    {
        Stack<TreeViewItem> tempNodePath = new Stack<TreeViewItem>();
        // Walk up the element tree to the nearest tree view item.
        TreeViewItem container = element as TreeViewItem;

        while ((element != null))
        {
            element = VisualTreeHelper.GetParent(element) as UIElement;
            container = element as TreeViewItem;
            if(container!=null)
            tempNodePath.Push(container);
        }

        return tempNodePath;
    }

    private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        Stack<TreeViewItem> path = GetNodeParent(e.NewValue as UIElement);
    }
}
</code>```

Title: Get FullPath in WPF treeview?

Body:
If I create a WPF TreeView programmatically, for example:

// TreeView treeView; <- added in the designer
TreeViewItem rootNode = new TreeViewItem();
rootNode.Header = "RootNode"
treeView.Items.Add(rootNode);

TreeViewItem subNode1 = new TreeViewItem();
subNode1.Header = "SubNode1";
rootNode.Items.Add(subNode1);

TreeViewItem subNode2 = new TreeViewItem();
subNode2.Header = "SubNode2";
rootNode.Items.Add(subNode2);

However, I would like to get the path to a certain node in the treeview much like the FullPath property in the System.Windows.Forms.TreeNode class. So the path for subNode2 would be RootNode//SubNode2. How do I do this?

Edit: I am not looking for the manual solution, however I am wondering if there is an equivalent accessor like FullPath or if I'm going about using the WPF TreeView class in the wrong way. Eg. I've looked at DisplayMemberPath and SelectedValuePath but they don't seem to provide the result I'm after.

Body:
See below code.

So this function returns a stack in which top most item will be root and last item will be the immediate parent of element.

public partial class Window1 : Window
{
    public Window1()
    {
        InitializeComponent();

        TreeViewItem rootNode = new TreeViewItem();
        rootNode.Header = "RootNode";
        treeView.Items.Add(rootNode);

        TreeViewItem subNode1 = new TreeViewItem();
        subNode1.Header = "SubNode1";
        rootNode.Items.Add(subNode1);

        TreeViewItem subNode2 = new TreeViewItem();
        subNode2.Header = "SubNode2";
        rootNode.Items.Add(subNode2);

        TreeViewItem subNode3 = new TreeViewItem();
        subNode3.Header = "SubNode3";
        subNode2.Items.Add(subNode3);
    }

    public static Stack<TreeViewItem> GetNodeParent(UIElement element)
    {
        Stack<TreeViewItem> tempNodePath = new Stack<TreeViewItem>();
        // Walk up the element tree to the nearest tree view item.
        TreeViewItem container = element as TreeViewItem;

        while ((element != null))
        {
            element = VisualTreeHelper.GetParent(element) as UIElement;
            container = element as TreeViewItem;
            if(container!=null)
            tempNodePath.Push(container);
        }

        return tempNodePath;
    }

    private void treeView_SelectedItemChanged(object sender, RoutedPropertyChangedEventArgs<object> e)
    {
        Stack<TreeViewItem> path = GetNodeParent(e.NewValue as UIElement);
    }
}


问:
How do I write a single front-end application to accommodate a shared database/seperate schema data structure?
I'm creating a SaaS application using django rest framework and the django-tenant-schemas package with a postgresql database. Each user in the database has the same base schema. The user can extend the base schema to allow for custom tables/columns.

So If I want to write a single front-end that will be able to account for customized tables how do I do it? (I'm using angular 2 if that helps)

In order to conform to SO's policy of asking questions that can be answered and not just discussed, here are my questions:

1) Is it even possible to write a single front-end application for this type of data structure?

2)Is there a word, concept, or idea for what I'm trying to do? I'd like to be able to research this more but I'm having a hard time knowing what to even google.

If my question seems vague it's because i'm still trying to figure out how to ask it. If you need clarification don't hesitate to ask in the comments. I'm really just looking for an answer to #2 so I can continue my research.

答:
Actually, this sort of setup is purely an API concern, not a frontend concern. Remember your frontend doesn't care about how your database(s) are set up - it only cares about the APIs that it can call. Your API has to do the work having common endpoints that everyone can call and then accessing the correct database based on the current user. This is called a multi-tenant application - and actually, Rails has a gem that provides this functionality (the apartment gem). I know you're using Django, but if Rails has a 'plugin' to assist with this setup, I wouldn't be surprised if Django has something similar.

Note that because different users may have different tables, your front end isn't completely static - it may actually have to include API requests that return user-customised information to help it configure its UI based on the different users' needs. It's not a sticking point - just something to include in your front end application design.


问:
How to pass string value to another form's load event in C #
(I'm currently taking c#, but I've never taken any of the prerequisite classes, so please forgive my limited understanding.)

The answers I've seen so far aren't what I need for this project.

This is what I have so far:

//Form1

```<code>private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strStatus = "";
            if (rdoMarr.Checked)
            {
                strStatus = "Married";
            }
            else
            {
                strStatus = "Single";
            }
                    string strPrint = "Marital Status = " + strStatus + "\n Pay         Period =" + cbPayPd.Text + "\n Dependents =" + cbAllow.Text + "\n Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text + "\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text + "\n Net = " + txtNet.Text;
            var form2 = new Print(strPrint);
            form2.Show();
        }
</code>```

What needs to go onto my Form2 to receive this string?

答:
There are many ways to do this. The one below is not what I would recommend, but I think it's the easiest to understand.

Here's one way to do this:

Create a public static property on your Form1 class to hold the value of this variable

Use the property from step #1 for the MessageBox text

Create a method that will update this property with the text you want

Call the method in #3 when your form loads

Create a common EventHandler method that calls the method in #2

Hook up the TextChanged event of the TextBox objects whose text is used in your string to the common EventHandler created in #4

Reference the property in #2 when your Form2 loads

My example assumes you have a Label named label1 on the Form that you want to update with the text

Here's how:

```<code>public partial class Form1 : Form
{
    // 1. This class-level variable will hold our string
    public static string PrintMessage { get; private set; }

    // 2. Reference your strPrint variable for the MessageBox as you were before
    private void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show(PrintMessage);
    }

    // 3. This method will update our string with values from TextBoxes
    private void UpdateText()
    {
        PrintMessage = "Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text +
            "\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text +
            "\n Net = " + txtNet.Text;
    }

    // 4. Call our update method when the Form loads
    private void Form1_Load(object sender, EventArgs e)
    {
        UpdateText();
    }

    // 5. This EventHandler just calls our update method
    private void CommonTextChangedEvent(object sender, EventArgs e)
    {
        UpdateText();
    }

    // I have a `button1` on my Form1, and clicking this button shows Form2
    private void button1_Click(object sender, EventArgs e)
    {
        var form2 = new Form2();
        form2.Show();
    }
</code>```

Now, hook up the event handler. The easiest way is:

One at a time, select one of the textboxes whose Text is used in our string

In the Properties window, click the Events button (looks like a lightning bolt)

Choose the TextChanged event, and assign our new method to it

Now, in your Form2 class, you should be able to reference the Form1 property you created in #1:

```<code>public partial class Form2 : Form
{
    private void Form2_Load(object sender, EventArgs e)
    {
        label1.Text = Form1.PrintMessage;
    }
</code>```

To test it, just run the project, change the text in the text boxes, and click the button to load Form2

Body:
(I'm currently taking c#, but I've never taken any of the prerequisite classes, so please forgive my limited understanding.)

The answers I've seen so far aren't what I need for this project.

This is what I have so far:

//Form1

private void printToolStripMenuItem_Click(object sender, EventArgs e)
        {
            string strStatus = "";
            if (rdoMarr.Checked)
            {
                strStatus = "Married";
            }
            else
            {
                strStatus = "Single";
            }
                    string strPrint = "Marital Status = " + strStatus + "\n Pay         Period =" + cbPayPd.Text + "\n Dependents =" + cbAllow.Text + "\n Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text + "\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text + "\n Net = " + txtNet.Text;
            var form2 = new Print(strPrint);
            form2.Show();
        }

What needs to go onto my Form2 to receive this string?

Body:
There are many ways to do this. The one below is not what I would recommend, but I think it's the easiest to understand.

Here's one way to do this:

Create a public static property on your Form1 class to hold the value of this variable

Use the property from step #1 for the MessageBox text

Create a method that will update this property with the text you want

Call the method in #3 when your form loads

Create a common EventHandler method that calls the method in #2

Hook up the TextChanged event of the TextBox objects whose text is used in your string to the common EventHandler created in #4

Reference the property in #2 when your Form2 loads

My example assumes you have a Label named label1 on the Form that you want to update with the text

Here's how:

public partial class Form1 : Form
{
    // 1. This class-level variable will hold our string
    public static string PrintMessage { get; private set; }

    // 2. Reference your strPrint variable for the MessageBox as you were before
    private void printToolStripMenuItem_Click(object sender, EventArgs e)
    {
        MessageBox.Show(PrintMessage);
    }

    // 3. This method will update our string with values from TextBoxes
    private void UpdateText()
    {
        PrintMessage = "Gross = " + txtGross.Text + "\n Fit = " + txtFit.Text +
            "\n Soc = " + txtSoc.Text + "\n Med = " + txtMed.Text +
            "\n Net = " + txtNet.Text;
    }

    // 4. Call our update method when the Form loads
    private void Form1_Load(object sender, EventArgs e)
    {
        UpdateText();
    }

    // 5. This EventHandler just calls our update method
    private void CommonTextChangedEvent(object sender, EventArgs e)
    {
        UpdateText();
    }

    // I have a `button1` on my Form1, and clicking this button shows Form2
    private void button1_Click(object sender, EventArgs e)
    {
        var form2 = new Form2();
        form2.Show();
    }

Now, hook up the event handler. The easiest way is:

One at a time, select one of the textboxes whose Text is used in our string

In the Properties window, click the Events button (looks like a lightning bolt)

Choose the TextChanged event, and assign our new method to it

Now, in your Form2 class, you should be able to reference the Form1 property you created in #1:

public partial class Form2 : Form
{
    private void Form2_Load(object sender, EventArgs e)
    {
        label1.Text = Form1.PrintMessage;
    }

To test it, just run the project, change the text in the text boxes, and click the button to load Form2