问:
Ruby on Rails: Array to Hash with (key, array of values)
Lets say I have an Array of content_categories (content_categories = user.content_categories)

I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set

In PHP something like this is possible:

```<code>foreach ($content_categories as $key => $category) {
  $contentsByCategoryIDArray = Category.getContents($category[id])
  $content_categories[$key][$contentsByCategoryIDArray]
}
</code>```

Is there an easy way in rails to do this?

Greets,

Nico

答:
If i understand correctly, content_categories is an array of categories, which needs to be turned into a hash of categories, and their elements.

```<code>content_categories_array = content_categories
content_categories_hash = {}
content_categories_array.each do |category|
  content_categories_hash[category] = Category.get_contents(category)
end
content_categories = content_categories_hash
</code>```

That is the long version, which you can also write like

```<code>content_categories = {}.tap do |hash|
  content_categories.each { |category| hash[category] = Category.get_contents(category) }
end
</code>```

Body:
Lets say I have an Array of content_categories (content_categories = user.content_categories)

I now want to add every element belonging to a certain categorie to content_categories with the category as a key and the the content-item IDs as elements of a set

In PHP something like this is possible:

foreach ($content_categories as $key => $category) {
  $contentsByCategoryIDArray = Category.getContents($category[id])
  $content_categories[$key][$contentsByCategoryIDArray]
}

Is there an easy way in rails to do this?

Greets,

Nico

Body:
If i understand correctly, content_categories is an array of categories, which needs to be turned into a hash of categories, and their elements.

content_categories_array = content_categories
content_categories_hash = {}
content_categories_array.each do |category|
  content_categories_hash[category] = Category.get_contents(category)
end
content_categories = content_categories_hash

That is the long version, which you can also write like

content_categories = {}.tap do |hash|
  content_categories.each { |category| hash[category] = Category.get_contents(category) }
end


来源: stackexchange

问:
Included Resources in Swagger
I'm writing a REST API using swagger and I'm having trouble defining a easy to read specification that aligns with the jsonapi format (jsonapi.org). The issue is specific to the definition of included resources.

I have multiple included resources all with different attributes.

```<code>"included": [{
                "type": "author",
                "id": "323454",
                "attributes": {
                  "1": "Bob",
                  "2": "Jim"
                },
              {
                "type": "book",
                "id": "323454",
                "attributes": {
                  "3": "The Island"
                  "4": "The Other Island"
                }]
</code>```

I've tried defining multiple $ref objects under the included array but this doesn't work:

```<code>  included:
    type: array
    items:
      - $ref: "#/definitions/includedResource"
      - $ref: "#/definitions/includedResource2"
      - $ref: "#/definitions/includedResource3"
</code>```

Is there nice way to set multiple optional objects? I don't want to call out all attributes in the one resource object as it is not easy to read or align attribute to resource.

答:
In OpenAPI (fka Swagger) 2.0, array items must be of the same type only, e.g. all strings or all includedResource.

Unless I'm misunderstanding something, your example can be described using a single schema for includedResource, with the attributes property being an associative array/dictionary.

```<code>definitions:
  included:
    type: array
    items:
      $ref: '#/definitions/includedResource'

  includedResource:
    type: object
    # required: [type, id, attributes] # Indicate the required properties if needed
    properties:
      type:
        type: string
        # enum: [author, book] # Use enum if needed
      id:
        type: string
      attributes:
        type: object
        additionalProperties:
          type: string
</code>```

ContentLicense: CC BY-SA 3.0

Title: Included Resources in Swagger

Body:
I'm writing a REST API using swagger and I'm having trouble defining a easy to read specification that aligns with the jsonapi format (jsonapi.org). The issue is specific to the definition of included resources.

I have multiple included resources all with different attributes.

"included": [{
                "type": "author",
                "id": "323454",
                "attributes": {
                  "1": "Bob",
                  "2": "Jim"
                },
              {
                "type": "book",
                "id": "323454",
                "attributes": {
                  "3": "The Island"
                  "4": "The Other Island"
                }]

I've tried defining multiple $ref objects under the included array but this doesn't work:

  included:
    type: array
    items:
      - $ref: "#/definitions/includedResource"
      - $ref: "#/definitions/includedResource2"
      - $ref: "#/definitions/includedResource3"

Is there nice way to set multiple optional objects? I don't want to call out all attributes in the one resource object as it is not easy to read or align attribute to resource.

Body:
In OpenAPI (fka Swagger) 2.0, array items must be of the same type only, e.g. all strings or all includedResource.

Unless I'm misunderstanding something, your example can be described using a single schema for includedResource, with the attributes property being an associative array/dictionary.

definitions:
  included:
    type: array
    items:
      $ref: '#/definitions/includedResource'

  includedResource:
    type: object
    # required: [type, id, attributes] # Indicate the required properties if needed
    properties:
      type:
        type: string
        # enum: [author, book] # Use enum if needed
      id:
        type: string
      attributes:
        type: object
        additionalProperties:
          type: string


问:
Multiple tables with the same name in SQL Server
when running the query below, I get a duplicate table returned, even though only one of it exists. Why could that be?

```<code>SELECT
s.Name AS SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
TotalSpaceKB DESC
</code>```

** UPDATE
The database name was displayed with a (In Recovery) tag, I just ran a script to check and it said that it is 11% completed.  Could this also have caused this problem?

答:
As Sean pointed out, you have more than one index on the duplicated tables. To check the index name(s) you can run the slightly modified query: </p>

```<code>SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
i.name,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
    sys.tables t
INNER JOIN
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
    sys.schemas s ON t.schema_id = s.schema_id
WHERE
    t.NAME NOT LIKE 'dt%'
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255
GROUP BY
    t.Name, s.Name, p.Rows, i.name
ORDER BY
    t.name
</code>```

Body:
when running the query below, I get a duplicate table returned, even though only one of it exists. Why could that be?

SELECT
s.Name AS SchemaName,
t.NAME AS TableName,
p.rows AS RowCounts,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
sys.tables t
INNER JOIN
sys.schemas s ON s.schema_id = t.schema_id
INNER JOIN
sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
sys.allocation_units a ON p.partition_id = a.container_id
WHERE
t.NAME NOT LIKE 'dt%'
AND t.is_ms_shipped = 0
AND i.OBJECT_ID > 255
GROUP BY
t.Name, s.Name, p.Rows
ORDER BY
TotalSpaceKB DESC

** UPDATE
The database name was displayed with a (In Recovery) tag, I just ran a script to check and it said that it is 11% completed.  Could this also have caused this problem?

Body:
As Sean pointed out, you have more than one index on the duplicated tables. To check the index name(s) you can run the slightly modified query:

SELECT
t.NAME AS TableName,
s.Name AS SchemaName,
p.rows AS RowCounts,
i.name,
SUM(a.total_pages) * 8 AS TotalSpaceKB,
SUM(a.used_pages) * 8 AS UsedSpaceKB,
(SUM(a.total_pages) - SUM(a.used_pages)) * 8 AS UnusedSpaceKB
FROM
    sys.tables t
INNER JOIN
    sys.indexes i ON t.OBJECT_ID = i.object_id
INNER JOIN
    sys.partitions p ON i.object_id = p.OBJECT_ID AND i.index_id = p.index_id
INNER JOIN
    sys.allocation_units a ON p.partition_id = a.container_id
LEFT OUTER JOIN
    sys.schemas s ON t.schema_id = s.schema_id
WHERE
    t.NAME NOT LIKE 'dt%'
    AND t.is_ms_shipped = 0
    AND i.OBJECT_ID > 255
GROUP BY
    t.Name, s.Name, p.Rows, i.name
ORDER BY
    t.name


问:
Why do we need to use flatMap?
I am starting to use RxJS and I don't understand why in this example we need to use a function like flatMap or concatAll; where is the array of arrays here?

```<code>var requestStream = Rx.Observable.just('https://api.github.com/users');

var responseMetastream = requestStream
  .flatMap(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

responseMetastream.subscribe(url => {console.log(url)})
</code>```

If someone can visually explain what is happening, it will be very helpful.

Title: Why do we need to use flatMap?

Body:
I am starting to use RxJS and I don't understand why in this example we need to use a function like flatMap or concatAll; where is the array of arrays here?

var requestStream = Rx.Observable.just('https://api.github.com/users');

var responseMetastream = requestStream
  .flatMap(function(requestUrl) {
    return Rx.Observable.fromPromise(jQuery.getJSON(requestUrl));
  });

responseMetastream.subscribe(url => {console.log(url)})

If someone can visually explain what is happening, it will be very helpful.

Body:
Simple:

[1,2,3].map(x => [x, x * 10])
// [[1, 10], [2, 20], [3, 30]]

[1,2,3].flatMap(x => [x, x * 10])
// [1, 10, 2, 20, 3, 30]]


问:
How to read atrace data in compressed format
I am using

```<code>atrace -z
</code>```

to get compressed trace file. Is there any way to decompress this file to recover original data

答:
Yes it's possible. There is just one "weird trick" to be done -- atrace prepends all of its output with done\nTRACE:\n string (see the source), so these bytes need to be removed first, and then the rest is just an output from zlib's deflate. See this answer on how to decompress it.

For example (on Linux):

```<code>dd if=<compressed-trace-file> bs=1 skip=13 | zlib-flate -uncompress
</code>```

Body:
I am using

atrace -z

to get compressed trace file. Is there any way to decompress this file to recover original data

Body:
Yes it's possible. There is just one "weird trick" to be done -- atrace prepends all of its output with done\nTRACE:\n string (see the source), so these bytes need to be removed first, and then the rest is just an output from zlib's deflate. See this answer on how to decompress it.

For example (on Linux):

dd if=<compressed-trace-file> bs=1 skip=13 | zlib-flate -uncompress


问:
How to make a live HTML preview textarea safe against HTML/Script Injection
I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.

However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:

```<code></textarea>
     <script>alert("Hello World!");</script>
<textarea style="display: none;">
</code>```

And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).

I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.

These few lines is what I use to live render HTML markup:

```<code>$(".main").on("keyup", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});

$(".main").on("keydown", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});
</code>```

Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?

答:
Edit: Actually, I think this solution is a little cleaner, and makes the below code unnecessary. In the velocity page all that is needed is to take advantage of the Spring framework. So I replace the textarea with this like so:

```<code>#springBindEscaped("myJavaObj.textAreaText" true)
<textarea id="actualTextArea" name="${status.expression}" class="myClass" rows="10" cols="120">$!status.value</textarea>
</code>```

This paired with some backend Java validation and it ends up being a much cleaner solution.

But if you want a non-spring/ velocity solution, then this below works just fine

I cobbled together a quick fix as my main purpose is to eliminate the ability for others to execute scripts easily. It's not ideal, and I"m not claiming it to be the best answer, so if someone finds a better solution, please do share. I created a "sanitize" function like so:

```<code>function sanitize(text){
    var sanitized = text.replace("<script>", "");
    sanitized = sanitized.replace("</script>", "");
    return sanitized;
}
</code>```

Then the previous two event handlers now look like:

```<code>$(".main").on("keyup", "#actualTextArea", function () {
    var textAreaMarkup = $('#actualTextArea').val();
    var sanitizedMarkup = sanitize(textAreaMarkup );
    $('#actualTextArea').val(sanitizedMarkup);
    $('#previewTextArea').html(sanitizedMarkup);
});

 // This one can remain unchanged and infact needs to be
 // If it's the same as above it will wipe the text area
 //  on a highlight-backspace
$(".main").on("keydown", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});
</code>```

Along with Java side sanitation to prevent anything harmful being stored in the DB, this serves my purpose, but I'm very open to a better solution if it exists.

Body:
I'm turning here as a last resort. I've scoured google and I'm having troubles coming to a solution. I have a form with a textarea element that allows you to type html in the area and it will render the HTML markup live as you type if you have the preview mode active. Not too different from the way StackOverflow shows the preview below a new post.

However, I have recently discovered that my functionality has a vulnerability. All I got to do is type something like:

</textarea>

<textarea style="display: none;">

And not only does this run from within the textarea live, if you save the form and reload said data on a different page this code still executes within the textarea on said different page but unbeknownst to the user; to them all the see is a textarea (if there is no alert obviously).

I found this post; Live preview of textarea input with javascript html, and attempted to refactor my JS to the accepted answer there, because I noticed I couldn't write a script tag in the JSFiddle example, though maybe that's some JSFiddle blocking that behaviour, but I couldn't get it working within my JS file.

These few lines is what I use to live render HTML markup:

$(".main").on("keyup", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});

$(".main").on("keydown", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});

Is there a way this can be refactored so it's safe? My only idea at the moment is to wipe the live preview and use a toggle on/off and encode it, but I really think this is a cool feature and would like to keep it live instead of toggle. Is there a way to "live encode" it or escape certain tags or something?

Body:
Edit: Actually, I think this solution is a little cleaner, and makes the below code unnecessary. In the velocity page all that is needed is to take advantage of the Spring framework. So I replace the textarea with this like so:

#springBindEscaped("myJavaObj.textAreaText" true)
<textarea id="actualTextArea" name="${status.expression}" class="myClass" rows="10" cols="120">$!status.value</textarea>

This paired with some backend Java validation and it ends up being a much cleaner solution.

But if you want a non-spring/ velocity solution, then this below works just fine

I cobbled together a quick fix as my main purpose is to eliminate the ability for others to execute scripts easily. It's not ideal, and I"m not claiming it to be the best answer, so if someone finds a better solution, please do share. I created a "sanitize" function like so:

function sanitize(text){
    var sanitized = text.replace("<script>", "");
    sanitized = sanitized.replace("</script>", "");
    return sanitized;
}

Then the previous two event handlers now look like:

$(".main").on("keyup", "#actualTextArea", function () {
    var textAreaMarkup = $('#actualTextArea').val();
    var sanitizedMarkup = sanitize(textAreaMarkup );
    $('#actualTextArea').val(sanitizedMarkup);
    $('#previewTextArea').html(sanitizedMarkup);
});

 // This one can remain unchanged and infact needs to be
 // If it's the same as above it will wipe the text area
 //  on a highlight-backspace
$(".main").on("keydown", "#actualTextArea", function () {
    $('#previewTextArea').html($('#actualTextArea').val());
});

Along with Java side sanitation to prevent anything harmful being stored in the DB, this serves my purpose, but I'm very open to a better solution if it exists.


问:
Android IntentService slowing down UI Thread
My IntentService is raising the "Skipped XX frames!  The application may be doing too much work on its main thread." message in  the LogCat, but I don't understand why.

I'm working on an app that communicates with a P2P broker. I decided to move all the communication logic to a Service. Initially I was doing something in that fashion:

```<code>class MyService extends Service {
    @Override
    onCreate() {
        // This info need to stay up as long as the context is
        stablishEndpointAndTransport();
    }

    @Override
    onStartCommand(Intent intent, int startId) {
        registerAccountId(intent.getIntExtra(EXTRA_ACCOUNT_ID));
    }

    @Override
    IBinder onBind(Intent intent) {
        super.onBind(intent);
    }

    @Override
    onDestroy() {
        if (registeredAccount) deleteAccount();
        deleteTransportAndEndpoint();
    }
}
</code>```

It ran OK even though I didn't create a worker thread to handle all that logic. But as I will need to implement more connectivity logic, I decided to move the logic to an IntentService, since it handles everything on a background worker thread.

All I did was rename the base class to IntentService, move the content in the onStartCommand() method to the onHandleIntent(), specify an action constant to that specific case and erase onStartCommand() and onBind() overrides.

How can that change impact the performance of the main thread?

EDIT

Might be related, but both stablishEndpointAndTransport() and registerAccountId() run some methods from a framework that are asynchronous. Specifically, the methods that communicate to the broker are. That being said, I might give up on IntentService because the hardwork is already ran on a different thread (Explainig why it actually runs fine as a Service). Still, I don't get why IntentService is making UI Thread skip frames.

答:
I've found the problem. Given that I was making async calls, i was returning from the onHandleIntent method before the calls would finish. The problem is that stopSelf(int) is called once it returns, as it's implemented by the ServiceHandler:

```<code>@Override
public void handleMessage(Message msg) {
    onHandleIntent((Intent)msg.obj);
    stopSelf(msg.arg1);
}
</code>```

IntentService was not designed to perform the task I was intending. To my scenario, I reimplemented it as BackgroundService and erased stopSelf() along with other modifications to keep the BackgroundService thread active as long as possible (see this gist).

Body:
My IntentService is raising the "Skipped XX frames!  The application may be doing too much work on its main thread." message in  the LogCat, but I don't understand why.

I'm working on an app that communicates with a P2P broker. I decided to move all the communication logic to a Service. Initially I was doing something in that fashion:

class MyService extends Service {
    @Override
    onCreate() {
        // This info need to stay up as long as the context is
        stablishEndpointAndTransport();
    }

    @Override
    onStartCommand(Intent intent, int startId) {
        registerAccountId(intent.getIntExtra(EXTRA_ACCOUNT_ID));
    }

    @Override
    IBinder onBind(Intent intent) {
        super.onBind(intent);
    }

    @Override
    onDestroy() {
        if (registeredAccount) deleteAccount();
        deleteTransportAndEndpoint();
    }
}

It ran OK even though I didn't create a worker thread to handle all that logic. But as I will need to implement more connectivity logic, I decided to move the logic to an IntentService, since it handles everything on a background worker thread.

All I did was rename the base class to IntentService, move the content in the onStartCommand() method to the onHandleIntent(), specify an action constant to that specific case and erase onStartCommand() and onBind() overrides.

How can that change impact the performance of the main thread?

EDIT

Might be related, but both stablishEndpointAndTransport() and registerAccountId() run some methods from a framework that are asynchronous. Specifically, the methods that communicate to the broker are. That being said, I might give up on IntentService because the hardwork is already ran on a different thread (Explainig why it actually runs fine as a Service). Still, I don't get why IntentService is making UI Thread skip frames.

Body:
I've found the problem. Given that I was making async calls, i was returning from the onHandleIntent method before the calls would finish. The problem is that stopSelf(int) is called once it returns, as it's implemented by the ServiceHandler:

@Override
public void handleMessage(Message msg) {
    onHandleIntent((Intent)msg.obj);
    stopSelf(msg.arg1);
}

IntentService was not designed to perform the task I was intending. To my scenario, I reimplemented it as BackgroundService and erased stopSelf() along with other modifications to keep the BackgroundService thread active as long as possible (see this gist).


问:
Dynamically replacing HTML with getJSON by click of button
I have a webpage that displays a news story in the main body, and has a side navigation bars where four other stories are listed. I am trying to use json files to swap out the html text in the main body. Each story has it's own json file. Here is my current javascript code:

```<code>$(document).ready(function() {

$("#nav_list a").click(function(evt) {
    buildName = "../json_files/" + $(this).attr("title") + ".json";
    alert(buildName);
    document.getElementById("main").innerHTML = "";

    $.getJSON(buildName, function(data) {
        $.each(data, function() {
            $.each(this, function(key, value) {
                $("#main").append(
                    "<h1>" + value.title + "</h2>" +
                    "<img src='" + value.image + "'>" +
                    "<h2>" + value.month + "<br>" + value.speaker + "</h2>" +
                    "<p>" + value.text + "</p>";
                );
            }); // inner each
        }); // outer each
    )}; // end of getJSON

}); // end click

}); // end ready
</code>```

Notes:

The alert(buildName) is for my own testing.

The next line (w. the innerHTML) should clear the current body content.
** NOTE: This works if I have the $.getJSON method commented out! Otherwise both this and my alert() are entirely ignored.

Because each store has it's own json file, I questioned the necessity of the muliple $.each methods within the getJSON. It didn't make a difference (the format I have below is from my textbook and has worked on a single json file with multiple entries).

I even tried not clearing the initial innerHTML and overwriting, but I may have had some syntax wrong. Here is that attempt:

```<code>        $.getJSON(buildName, function(data) {
            $.each(data, function(key, value) {
                $("#main").append(
                    ("#main h1").innerHTML.replace("<h1>" + value.title + "</h2>");
                    ("#main img").innerHTML.replace("<img src='" + value.image + "'>");
                    ("#main h2").innerHTML.replace("<h2>" + value.month + "<br>" + value.speaker + "</h2>");
                    ("#main p").innerHTML.replace("<p>" + value.text + "</p>");
                )
            }); // endeach
    )}; // end of getJSON
</code>```

What do you guys think? I am absolutely stumped.

答:
I think that the problem might be your json path that you construct.

Try using a standard path "../file.json" or "file.json" to check if you have the result you want or if the $.getJSON() is still ignored.

About the other errors: What is  your devel. environment?

I also noticed that you have a bracket mismatched in your append  function at the title part. So,
"
" + value.title + "
" +
would have to be changed to..

```<code>"<h1>" + value.title + "</h1>" +
</code>```

Body:
I have a webpage that displays a news story in the main body, and has a side navigation bars where four other stories are listed. I am trying to use json files to swap out the html text in the main body. Each story has it's own json file. Here is my current javascript code:

$(document).ready(function() {

$("#nav_list a").click(function(evt) {
    buildName = "../json_files/" + $(this).attr("title") + ".json";
    alert(buildName);
    document.getElementById("main").innerHTML = "";

    $.getJSON(buildName, function(data) {
        $.each(data, function() {
            $.each(this, function(key, value) {
                $("#main").append(
                    "
" + value.title + "
" +
                    "" +
                    "
" + value.month + "
" + value.speaker + "
" +
                    "
" + value.text + "
";
                );
            }); // inner each
        }); // outer each
    )}; // end of getJSON

}); // end click

}); // end ready

Notes:

The alert(buildName) is for my own testing.

The next line (w. the innerHTML) should clear the current body content.
** NOTE: This works if I have the $.getJSON method commented out! Otherwise both this and my alert() are entirely ignored.

Because each store has it's own json file, I questioned the necessity of the muliple $.each methods within the getJSON. It didn't make a difference (the format I have below is from my textbook and has worked on a single json file with multiple entries).

I even tried not clearing the initial innerHTML and overwriting, but I may have had some syntax wrong. Here is that attempt:

        $.getJSON(buildName, function(data) {
            $.each(data, function(key, value) {
                $("#main").append(
                    ("#main h1").innerHTML.replace("
" + value.title + "
");
                    ("#main img").innerHTML.replace("");
                    ("#main h2").innerHTML.replace("
" + value.month + "
" + value.speaker + "
");
                    ("#main p").innerHTML.replace("
" + value.text + "
");
                )
            }); // endeach
    )}; // end of getJSON

What do you guys think? I am absolutely stumped.

Body:
I think that the problem might be your json path that you construct.

Try using a standard path "../file.json" or "file.json" to check if you have the result you want or if the $.getJSON() is still ignored.

About the other errors: What is  your devel. environment?

I also noticed that you have a bracket mismatched in your append  function at the title part. So,
"<h1>" + value.title + "</h2>" +
would have to be changed to..

"<h1>" + value.title + "</h1>" +


问:
UWP - horizontally scrollable view inside grid view
I'm creating a sort of bookkeeper and would like to make each section horizontally scrollable (kinda like ibooks). I have tried to wrap my Gridview with ScrollViewer but that messed up. Thanks for help! Here's my code snippet:

```<code><ScrollViewer Margin="10,0,0,0">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="5,10,5,5">
        <Grid.RowDefinitions>
            <RowDefinition Height="60"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>
        <TextBlock Text="Romances" FontSize="18"/>
        <GridView Name="JuvenileBooks"  Grid.Row="1"
                  HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch" >
            <GridView.ItemTemplate>
                <DataTemplate x:DataType="data:BookModel">
                    <local:BookshelvesDataTemplate/>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>
</ScrollViewer>
</code>```

答:
I think this is the thing you are looking for</p>

```<code><GridView >
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsWrapGrid Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>
</GridView>
</code>```

Body:
I'm creating a sort of bookkeeper and would like to make each section horizontally scrollable (kinda like ibooks). I have tried to wrap my Gridview with ScrollViewer but that messed up. Thanks for help! Here's my code snippet:

<ScrollViewer Margin="10,0,0,0">
    <Grid Background="{ThemeResource ApplicationPageBackgroundThemeBrush}" Margin="5,10,5,5">
        <Grid.RowDefinitions>
            <RowDefinition Height="60"/>
            <RowDefinition Height="30"/>
        </Grid.RowDefinitions>
        <TextBlock Text="Romances" FontSize="18"/>
        <GridView Name="JuvenileBooks"  Grid.Row="1"
                  HorizontalAlignment="Stretch"
                  VerticalAlignment="Stretch" >
            <GridView.ItemTemplate>
                <DataTemplate x:DataType="data:BookModel">
                    <local:BookshelvesDataTemplate/>
                </DataTemplate>
            </GridView.ItemTemplate>
        </GridView>
</ScrollViewer>

Body:
I think this is the thing you are looking for

<GridView >
    <GridView.ItemsPanel>
        <ItemsPanelTemplate>
            <ItemsWrapGrid Orientation="Horizontal"/>
        </ItemsPanelTemplate>
    </GridView.ItemsPanel>
</GridView>


问:
Conditional variable not working in html using angular 1
The 3rd line is what i wanted, but not working yet, any comments ?</p>

```<code><input name="myFile" id="myFile" type="file" accept=".deb" ng-if="platform === 'ubuntu'" vw-file="newObject.newImage" ng-disabled="!newObject.edit">
<input name="myFile" id="myFile" type="file" accept=".iso" ng-if="platform === 'redhat'" vw-file="newObject.newImage" ng-disabled="!newObject.edit">
<!-- input name="myFile" id="myFile" type="file" accept={{(platform === "ubuntu") ? ".deb" : ".iso"}} vw-file="newObject.newImage" ng-disabled="!newObject.edit" -->
</code>```

答:
That 3rd line should be as follows</p>

```<code><input
  name="myFile"
  id="myFile"
  type="file"
  accept="{{(platform === 'ubuntu') ? '.deb' : '.iso'}}"
  vw-file="newObject.newImage"
  ng-disabled="!newObject.edit">
</code>```

Body:
The 3rd line is what i wanted, but not working yet, any comments ?

<input name="myFile" id="myFile" type="file" accept=".deb" ng-if="platform === 'ubuntu'" vw-file="newObject.newImage" ng-disabled="!newObject.edit">
<input name="myFile" id="myFile" type="file" accept=".iso" ng-if="platform === 'redhat'" vw-file="newObject.newImage" ng-disabled="!newObject.edit">

Body:
That 3rd line should be as follows

<input
  name="myFile"
  id="myFile"
  type="file"
  accept="{{(platform === 'ubuntu') ? '.deb' : '.iso'}}"
  vw-file="newObject.newImage"
  ng-disabled="!newObject.edit">


问:
Online and automatic resource localization in C#
I have a c# winforms project with many forms, now I want to localize these forms to another language, is there any way or code that generates resource files for forms and translate them online?

Thanks

答:
You can use ReSharper plugin and/or  RGreatEx - The ReSharper Great Extension
  and U can easily Move strings to resource to translate them for specific language.</p>

ContentLicense: CC BY-SA 2.5


问:
Compiling Java program with VBScripts? (NetBeans)
I have a Java program created that runs VBSscripts after button clicks.

examplescript.vbs

How do I compile these vbs files and then call them to run in the program code? I've been troubleshooting for several days and can't find an answer. Once again I need to be able to run these scripts, at one point I had an input stream created to it but couldn't get it as a vbs file. Hopefully I'm overlooking something here

Edit:
This is what I currently have. With this code I receive the error "Windows Script Host. There is no script extension for file extension ".BufferedInputStream@4e34904""

```<code>ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("hello.vbs");
    try {
        Runtime.getRuntime().exec("wscript " + is);
    }
    catch( IOException e ) {
    System.out.println(e);
    System.exit(0);
    }
    System.out.print(is);
</code>```

答:
You can run your VBScript as below. </p>

```<code>  Runtime.getRuntime().exec( "wscript path/to/examplescript.vbs" );
</code>```

Body:
I have a Java program created that runs VBSscripts after button clicks.

examplescript.vbs

How do I compile these vbs files and then call them to run in the program code? I've been troubleshooting for several days and can't find an answer. Once again I need to be able to run these scripts, at one point I had an input stream created to it but couldn't get it as a vbs file. Hopefully I'm overlooking something here

Edit:
This is what I currently have. With this code I receive the error "Windows Script Host. There is no script extension for file extension ".BufferedInputStream@4e34904""

ClassLoader classloader = Thread.currentThread().getContextClassLoader();
    InputStream is = classloader.getResourceAsStream("hello.vbs");
    try {
        Runtime.getRuntime().exec("wscript " + is);
    }
    catch( IOException e ) {
    System.out.println(e);
    System.exit(0);
    }
    System.out.print(is);

Body:
You can run your VBScript as below.

  Runtime.getRuntime().exec( "wscript path/to/examplescript.vbs" );


问:
Appending a link title as a query parameter in the url once redirected to a new page
I have a table where several names are their own links and once clicked, it redirects to my landing page.

```<code><a href="#/landing"><span>{{ link.linktitle }}</span></a>
</code>```

That part works fine.

However, I need the url to look like this once redirect to the landing page:

```<code>http://localhost:3000/#/landing/?=link={link title}
</code>```

Is there a simple way to achieve this?

PS. I also need to grab the link title from the query param and have it display somewhere on the landing page.

Thanks!

答:
If the value you want to have is stored in the JS side under link.linktitle, your code has to look like this:

```<code><a href="#/landing/?=link={{ link.linktitle }}">
    <span>{{ link.linktitle }}</span>
</a>
</code>```

Body:
I have a table where several names are their own links and once clicked, it redirects to my landing page.

{{ link.linktitle }}

That part works fine.

However, I need the url to look like this once redirect to the landing page:

http://localhost:3000/#/landing/?=link={link title}

Is there a simple way to achieve this?

PS. I also need to grab the link title from the query param and have it display somewhere on the landing page.

Thanks!

Body:
If the value you want to have is stored in the JS side under link.linktitle, your code has to look like this:

<a href="#/landing/?=link={{ link.linktitle }}">
    <span>{{ link.linktitle }}</span>
</a>


问:
Host monitoring from a docker container
While I believe the answer is no, I feel I should still ask: is it possible to monitor a host system from within a Docker container?  To make deployments and upgrades easier, I was hoping I could put some monitoring tools inside a container.  Specifically, I'm thinking tools like atop, sar, etc.

Thoughts?

Thanks.

答: One thing that I've found that you can do is capture file system events that happen in the host using inotify. I use that in my inotify-command container. But who knows if that will last...</p>

Title: Host monitoring from a docker container


问:
Specflow Contextual Assertions
We use Specflow and currently, most of our assertions are done using Fluent Assertions, ie look something like:

myval.Should().NotBe(null)

All is working well, however there are some cases in which we want the same code to sometimes Assert Inconclusive, and sometimes not.

For example, let us assume we have a step which calls a method to install the AUT.

The test which asserts that the AUT can be installed correctly will use this method as part of a WHEN/THEN step.

In this instance, if installation fails, we want to proceed as normal and fail the test.

GIVEN The AUT is NOT installed
WHEN I install the AUT

However, for all other tests, the same method may be called as part of a GIVEN step or as part of a BeforeScenario / BeforeFeature hook, and in that instance, if the installation fails, the test should be failed as inconclusive, because it was not the test itself that failed, but the Setup stage.

GIVEN the AUT is installed
WHEN I perform function X of the AUT

So in this example, let us assume that the step definitions for WHEN I install the AUT in the first test, and GIVEN the AUT is installed in the second test simply call a helper method with something like AppFacade.Install()

Of course we can litter AppFacade.Install() and all our other helper methods with conditionals etc, but I was wondering if anyone out there has a more elegant solution - ie way to extend an assertion engine so that it automatically applies this logic - I see no barriers on the Specflow side to achieving this insofar as you can examine the Specflow context objects to detect what kind of step you are on.

Ideally we would like to stick with Fluent Assertions, but if this overly complicates things, we would be willing to reconsider.

答:
I was going to suggest you were not asking the right question, since you are implying that when a Specflow step execution fails the test should be inconclusive, but you already realized it.

So to answer the actual question you have:

Is it possible to throw an exception which can mark the test as inconclusive given the above logic?

Yes, you can use the after AfterStep hook (see Specflow hooks here) to check the is there was any exception thrown and execute Assert.Inconclusive() if you're using Nunit or any equivalent method, like Specflow's ScenarioContext.Current.Pending() to not be attached to the testing framework installed, the only caveat is that ScenarioContext.Current.Pending() does not clear ScenarioContext.TestStatus, so your test runner will mark it as red and you'll have to use reflection to set the TestStatus property as described here.

It would look something like this:

```<code>[AfterStep]
public void Check()
{
    if (ScenarioContext.Current.TestError is AssertionException &&
        ScenarioContext.Current.CurrentScenarioBlock == ScenarioBlock.Given)
        Assert.Inconclusive(ScenarioContext.Current.TestError.Message);
}
</code>```

Edit

Here is a demo I created.

Title: Specflow Contextual Assertions

Body:
I was going to suggest you were not asking the right question, since you are implying that when a Specflow step execution fails the test should be inconclusive, but you already realized it.

So to answer the actual question you have:

Is it possible to throw an exception which can mark the test as inconclusive given the above logic?

Yes, you can use the after AfterStep hook (see Specflow hooks here) to check the is there was any exception thrown and execute Assert.Inconclusive() if you're using Nunit or any equivalent method, like Specflow's ScenarioContext.Current.Pending() to not be attached to the testing framework installed, the only caveat is that ScenarioContext.Current.Pending() does not clear ScenarioContext.TestStatus, so your test runner will mark it as red and you'll have to use reflection to set the TestStatus property as described here.

It would look something like this:

[AfterStep]
public void Check()
{
    if (ScenarioContext.Current.TestError is AssertionException &&
        ScenarioContext.Current.CurrentScenarioBlock == ScenarioBlock.Given)
        Assert.Inconclusive(ScenarioContext.Current.TestError.Message);
}

Edit

Here is a demo I created.


答:
There are open source tools which allow to translate resx files. I haven't found a version which uses a online translation service such as google translate or the microsoft translator api or even the bablefish. But I think the Resx Translation Helper (open source project) should be very easy to modify. Note however, that the author explicitly discourage the usage of autogenerated translation:

It does NOT automatically translate because user-translation is currently still much better than automated translation.

Title: Online and automatic resource localization in C#

Body:
I have a c# winforms project with many forms, now I want to localize these forms to another language, is there any way or code that generates resource files for forms and translate them online?

Thanks


问:
Vue list items not re-rendered on state change
I have some array of object, when user click button I fetch new array and display display some results.

It works fine until I fetch second array. When I fetch first array with one element and then fetch array with two elements it change (add or remove) only second element.

How I change array value:

```<code>fetchAsync(result){
  this.issue = result.body;
}
</code>```

How issues looks like?

```<code>const issues = [
  {
    "id":100,
    "key":"DEMO-123",
    "summary":"Demo issue description",
    "devices":[
      {
        "id":100,
        "name":"iPhone6S",
        "browsers":[
          {
            "id":100,
            "name":"Safari",
            "displayVariants":[
              {
                "id":100,
                "issueKey":"DEMO-123",
                "state":1,
                "browserName":"safari",
                "user":"user-1",
                "landScope":false
              }
            ]
          }
        ]
      }
    ]
  }
]
</code>```

and the value which was changed is issues[].devices[].browsers[].displayVariants[].state

How to force Vue to rerender this component when nested change appear?

[ EDIT ]

I render issues like this:

```<code>  <tr v-for="issue in issues">
    <td>
      <div>{{ issue.key }}</div>
      <div class="issue-description">[ {{ issue.summary }} ]</div>
    </td>
    <template v-for="d in issue.devices">
      <td v-for="browser in d.browsers">
        <!--{{ d }}-->
          <device v-for="variant in browser.displayVariants"
                  :variant="variant"
                  :browserId="browser.id"
                  :issueKey="issue.key"
                  :issueId="issue.id"
                  :deviceId="d.id"></device>
      </td>
    </template>
  </tr>
</code>```

and device template

```<code><template>
  <svg viewBox="0 0 30 30" class="mobileSVG" @click="changeState" :class="[state, {landscape: variant.landScope}]">
    <use xlink:href="#mobile"/>
  </svg>
</template>
</code>```

答:
Vue cannot detect the following changes made to the array.
Here is the documentation.

When you directly set an item with the index, e.g.
vm.items[indexOfItem] = newValue

When you modify the length of the array, e.g. vm.items.length = newLength

vm refers to component instance.

To overcome the limitation 1 do:

```<code>Vue.set(items, indexOfItem, newValue)
</code>```

For limitation 2:

```<code>items.splice(newLength)
</code>```

So in your case you could do

```<code>this.$set(this.issues[0].devices[whateverIndex].browsers[anyIndex].displayVariants, indexOfVariant, valueOfVariant)
</code>```

Body:
I have some array of object, when user click button I fetch new array and display display some results.

It works fine until I fetch second array. When I fetch first array with one element and then fetch array with two elements it change (add or remove) only second element.

How I change array value:

fetchAsync(result){
  this.issue = result.body;
}

How issues looks like?

const issues = [
  {
    "id":100,
    "key":"DEMO-123",
    "summary":"Demo issue description",
    "devices":[
      {
        "id":100,
        "name":"iPhone6S",
        "browsers":[
          {
            "id":100,
            "name":"Safari",
            "displayVariants":[
              {
                "id":100,
                "issueKey":"DEMO-123",
                "state":1,
                "browserName":"safari",
                "user":"user-1",
                "landScope":false
              }
            ]
          }
        ]
      }
    ]
  }
]

and the value which was changed is issues[].devices[].browsers[].displayVariants[].state

How to force Vue to rerender this component when nested change appear?

[ EDIT ]

I render issues like this:

{{ issue.key }}

[ {{ issue.summary }} ]

    <template v-for="d in issue.devices">

          <device v-for="variant in browser.displayVariants"
                  :variant="variant"
                  :browserId="browser.id"
                  :issueKey="issue.key"
                  :issueId="issue.id"
                  :deviceId="d.id"></device>

    </template>

and device template

<template>
  <svg viewBox="0 0 30 30" class="mobileSVG" @click="changeState" :class="[state, {landscape: variant.landScope}]">
    <use xlink:href="#mobile"/>
  </svg>
</template>

Body:
Vue cannot detect the following changes made to the array.
Here is the documentation.

When you directly set an item with the index, e.g.
vm.items[indexOfItem] = newValue

When you modify the length of the array, e.g. vm.items.length = newLength

vm refers to component instance.

To overcome the limitation 1 do:

Vue.set(items, indexOfItem, newValue)

For limitation 2:

items.splice(newLength)

So in your case you could do

this.$set(this.issues[0].devices[whateverIndex].browsers[anyIndex].displayVariants, indexOfVariant, valueOfVariant)

ContentLicense: CC BY-SA 4.0


问:
Python logging special characters to file throws exception
I have a logger which logs to file but occasionally when it encounters TM characters it throws an exception and the entry is not logged.

```<code>logging.basicConfig(filename='C:/Users/Administrator/Desktop/logs/log.log',
    level=logging.INFO,
    format='%(asctime)s - %(message)s')
</code>```

What's wrong with it?

Edit:

Those are time and message obviously. The message is being received from google chrome via websocket as a stringified object {log: log} which is then parsed using data=json.loads(obj). Then data["log"] string goes into message.

答:
Instead of allowing logger to open the file, open it yourself and specify an encoding that can handle the character.

```<code>logfile = open('C:/Users/Administrator/Desktop/logs/log.log', 'a', encoding='utf-8')
logging.basicConfig(stream=logfile,
    level=logging.INFO,
    format='%(asctime)s - %(message)s')
</code>```

Body:
I have a logger which logs to file but occasionally when it encounters TM characters it throws an exception and the entry is not logged.

logging.basicConfig(filename='C:/Users/Administrator/Desktop/logs/log.log',
    level=logging.INFO,
    format='%(asctime)s - %(message)s')

What's wrong with it?

Edit:

Those are time and message obviously. The message is being received from google chrome via websocket as a stringified object {log: log} which is then parsed using data=json.loads(obj). Then data["log"] string goes into message.

Body:
Instead of allowing logger to open the file, open it yourself and specify an encoding that can handle the character.

logfile = open('C:/Users/Administrator/Desktop/logs/log.log', 'a', encoding='utf-8')
logging.basicConfig(stream=logfile,
    level=logging.INFO,
    format='%(asctime)s - %(message)s')


问:
How can I dial the phone from Flutter?
I am building a Flutter app, and I'd like to dial a phone number in response to a button tap. What's the best way to do this?

Thanks!

答:
Typically, to interact with the underlying platform, you have to write platform specific code and communicate with the same using platform channels. However, Flutter provides some points of integration with the platform out of the box. To dial the phone for instance, you can use the UrlLauncher.launch API with the tel scheme to dial the phone.

Something like UrlLauncher.launch("tel://<phone_number>"); should work fine on all platforms.

Do note that this will not work in the simulators. So make sure you are using an actual device to test this.

Title: How can I dial the phone from Flutter?


问:
How to determine OpenCV version
How to determine which version of OpenCV I have installed?

I am most interested in knowing a way of doing it programatically (and cross-platform), but I can't even find a way to determine the installed version from outside the code.

I'm working with C++03, on Fedora.

答:
The version string is located in:

https://github.com/opencv/opencv/blob/master/modules/core/include/opencv2/core/version.hpp

```<code>Top of version.hpp, below the BSD license:
#define CV_VERSION_MAJOR    3
#define CV_VERSION_MINOR    2
#define CV_VERSION_REVISION 0
</code>```

Title: How to determine OpenCV version

Body:
The version string is located in:

https://github.com/opencv/opencv/blob/master/modules/core/include/opencv2/core/version.hpp

Top of version.hpp, below the BSD license:
#define CV_VERSION_MAJOR    3
#define CV_VERSION_MINOR    2
#define CV_VERSION_REVISION 0


问:
Counting the number of lines in a UITextView, lines wrapped by frame size
I wanted to know when a text is wrapped by the frame of the text view is there any delimiter with which we can identify whether the text is wrapped or not.

For instance if my text view has a width of 50 px and text is exceeding that, it wraps the text to next line.

I wanted to count the number of lines in my text view. Now "\n" and "\r" are not helping me.

My code is:

```<code>NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"\n\r"];
    NSArray *myArray = [textViewText componentsSeparatedByCharactersInSet:aCharacterSet];
    NSLog(@"%d",[myArray count]);
</code>```

答:
Swift 3:</p>

```<code>let layoutManager:NSLayoutManager = textView.layoutManager
let numberOfGlyphs = layoutManager.numberOfGlyphs
var numberOfLines = 0
var index = 0
var lineRange:NSRange = NSRange()

while (index < numberOfGlyphs) {
    layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
    index = NSMaxRange(lineRange);
    numberOfLines = numberOfLines + 1
}

print(numberOfLines)
</code>```

Body:
I wanted to know when a text is wrapped by the frame of the text view is there any delimiter with which we can identify whether the text is wrapped or not.

For instance if my text view has a width of 50 px and text is exceeding that, it wraps the text to next line.

I wanted to count the number of lines in my text view. Now "\n" and "\r" are not helping me.

My code is:

NSCharacterSet *aCharacterSet = [NSCharacterSet characterSetWithCharactersInString:@"\n\r"];
    NSArray *myArray = [textViewText componentsSeparatedByCharactersInSet:aCharacterSet];
    NSLog(@"%d",[myArray count]);

Body:
Swift 3:

let layoutManager:NSLayoutManager = textView.layoutManager
let numberOfGlyphs = layoutManager.numberOfGlyphs
var numberOfLines = 0
var index = 0
var lineRange:NSRange = NSRange()

while (index < numberOfGlyphs) {
    layoutManager.lineFragmentRect(forGlyphAt: index, effectiveRange: &lineRange)
    index = NSMaxRange(lineRange);
    numberOfLines = numberOfLines + 1
}

print(numberOfLines)


问:
Mysql. Select data from 3 different tables based on column from 1 table
Here is what I want to do:

I have 3 tables: musicItems, photoItems, textItems

Each table has different columns.

```<code>Table "musicItems"
  id
  Owner_id
  audioId
  url
  duration

Table "photoItems"
  id
  albumId
  userId
  photoId
  url

Table "textItems"
  id
  msgText
</code>```

And I have one more table

```<code>"footprints"
  id
  itemType
  itemId
</code>```

I need to retieve last 30 items from table "footprints" with all properties depending on itemType and itemId. How can i do that?

答:
I have made the assumption that the ItemType column contains the table names the ItemID refers to

```<code>SELECT  *
FROM    footprints fp
        LEFT OUTER JOIN musicItems mi ON mi.ID = fp.itemID AND fp.ItemType = 'musicItems'
        LEFT OUTER JOIN photoItems pi ON pi.ID = fp.itemID AND fp.ItemType = 'photoItems'
        LEFT OUTER JOIN textItems ti ON ti.ID = fp.itemID AND fp.ItemType = 'textItems'
LIMIT   30
</code>```

Body:
Here is what I want to do:

I have 3 tables: musicItems, photoItems, textItems

Each table has different columns.

Table "musicItems"
  id
  Owner_id
  audioId
  url
  duration

Table "photoItems"
  id
  albumId
  userId
  photoId
  url

Table "textItems"
  id
  msgText

And I have one more table

"footprints"
  id
  itemType
  itemId

I need to retieve last 30 items from table "footprints" with all properties depending on itemType and itemId. How can i do that?

Body:
I have made the assumption that the ItemType column contains the table names the ItemID refers to

SELECT  *
FROM    footprints fp
        LEFT OUTER JOIN musicItems mi ON mi.ID = fp.itemID AND fp.ItemType = 'musicItems'
        LEFT OUTER JOIN photoItems pi ON pi.ID = fp.itemID AND fp.ItemType = 'photoItems'
        LEFT OUTER JOIN textItems ti ON ti.ID = fp.itemID AND fp.ItemType = 'textItems'
LIMIT   30


问:
How can I get a user's media from Instagram without authenticating as a user?
I'm trying to put a user's recent Instagram media on a sidebar. I'm trying to use the Instagram API to fetch the media.

http://instagram.com/developer/endpoints/users/

The documentation says to GET https://api.instagram.com/v1/users/<user-id>/media/recent/, but it says to pass an OAuth access token. An access token represents the authorization to act on behalf of a user. I don't want users to log into Instagram to see this on the sidebar. They shouldn't even need to have an Instagram account.

For instance, I can go to http://instagram.com/thebrainscoop without being logged into Instagram and see photos. I want to do that through the API.

In the Instagram API, non-user-authenticated requests pass a client_id instead of an access_token. If I try that, though, I get:

```<code>{
  "meta":{
    "error_type":"OAuthParameterException",
    "code":400,
    "error_message":"\"access_token\" URL parameter missing. This OAuth request requires an \"access_token\" URL parameter."
  }
}
</code>```

So, is this not possible? Is there no way to fetch a user's latest (public) media without asking a user to log into an Instagram account through OAuth first?

答:
As of last week, Instagram disabled /media/ URLs, I implemented a workaround, which works pretty well for now.

To solve everyone's problems in this thread, I wrote this: https://github.com/whizzzkid/instagram-reverse-proxy

It provides all of instagram's public data using the following endpoints:

Get user media:

```<code>https://igapi.ga/<username>/media
e.g.: https://igapi.ga/whizzzkid/media
</code>```

Get user media with limit count:

```<code>https://igapi.ga/<username>/media?count=N // 1 < N < 20
e.g.: https://igapi.ga/whizzzkid/media?count=5
</code>```

Use JSONP:

```<code>https://igapi.ga/<username>/media?callback=foo
e.g.: https://igapi.ga/whizzzkid/media?callback=bar
</code>```

The proxy API also appends next page and previous page URLs to the response so you do not need to calculate that at your end.

Body:
I'm trying to put a user's recent Instagram media on a sidebar. I'm trying to use the Instagram API to fetch the media.

http://instagram.com/developer/endpoints/users/

The documentation says to GET https://api.instagram.com/v1/users/<user-id>/media/recent/, but it says to pass an OAuth access token. An access token represents the authorization to act on behalf of a user. I don't want users to log into Instagram to see this on the sidebar. They shouldn't even need to have an Instagram account.

For instance, I can go to http://instagram.com/thebrainscoop without being logged into Instagram and see photos. I want to do that through the API.

In the Instagram API, non-user-authenticated requests pass a client_id instead of an access_token. If I try that, though, I get:

{
  "meta":{
    "error_type":"OAuthParameterException",
    "code":400,
    "error_message":"\"access_token\" URL parameter missing. This OAuth request requires an \"access_token\" URL parameter."
  }
}

So, is this not possible? Is there no way to fetch a user's latest (public) media without asking a user to log into an Instagram account through OAuth first?

Body:
As of last week, Instagram disabled /media/ URLs, I implemented a workaround, which works pretty well for now.

To solve everyone's problems in this thread, I wrote this: https://github.com/whizzzkid/instagram-reverse-proxy

It provides all of instagram's public data using the following endpoints:

Get user media:

https://igapi.ga/<username>/media
e.g.: https://igapi.ga/whizzzkid/media

Get user media with limit count:

https://igapi.ga/<username>/media?count=N // 1 < N < 20
e.g.: https://igapi.ga/whizzzkid/media?count=5

Use JSONP:

https://igapi.ga/<username>/media?callback=foo
e.g.: https://igapi.ga/whizzzkid/media?callback=bar

The proxy API also appends next page and previous page URLs to the response so you do not need to calculate that at your end.


问:
Changing server IP after connecting to CloudFlare
I recently signed up for CloudFlare to take advantage of the security feautres the service provides. Specifically, I'm interested in its use against DDOS attacks (which are a problem I'm facing).

My web application employs nginx as a reverse proxy (with gunicorn as the application server). The Ubuntu-based virtual machine - procured via Azure - has a static/reserved IP (used as a VIP). I've read that after connecting to CloudFlare, it's best practice to change server IP so that malicious actors can't directly DDOS the said server.

Being a newbie, I'm unsure whether this guideline was applicable to the public VIP (virtual IP) or to the internal IP (which is entirely different). Can someone please conceptually and functionally clarify this for me? Can really use some help in setting this up!

答:
What services like CloudFlare do is acting like a CDN for your website. They become front-end of your content delivery to clients while they have vast network for doing so (resources i.e. bandwidth which are consumed by DDoS). Then your IP is just known by the anti-DDoS service provider to fetch the content and deliver on your behalf.

You see if the IP is leaked by any mean the whole defense mechanism become useless since attackers can directly point to your machine while dynamic DNS of CloudFlare would distribute requests to its network and serve clients via them.

Since your website was up for a while before you migrate to CloudFlare your current public IP is known to attackers and hiding behind CloudFlare is useless since they don't ask CloudFlare DNS service and directly attack your server. This is the reason you need a new IP and the new one should not be revealed by any mean. Just set it in your CloudFlare panel and don't use it for other purposes.


问:
How do I use Bindings.bindContent?
I have a polygon that I want to grow in size when the window is resized. I have a DoubleBinding that it the baseline for the size of all of my shapes in the scene. I use this DoubleBinding to create a ListBinding that calculates how big the polygon should be. I tried to use Bindings.bindContent(list1, list2) to bind the ListBinding to the polygon's points, but it doesn't seem to work.

```<code>    Polygon triangle = new Polygon();

    ListBinding<Double> trianglePoints = new ListBinding<Double>() {
        {
            super.bind(width, height);
        }
        @Override
        protected ObservableList<Double> computeValue() {
            ObservableList<Double> points = FXCollections.observableArrayList();
            points.addAll(0.0, 0.0, width.get()/2, height.get()/4, 0.0, height.get()/2);
            return points;
        }
    };
    Bindings.bindContent(triangle.getPoints(), trianglePoints.get());
</code>```

I found that if I add an InvalidationListener to the triangle points and manually change the the polygon points when it fires off, it works.

```<code>    trianglePoints.addListener((InvalidationListener)(listener) -> triangle.getPoints().setAll(trianglePoints.get()));
</code>```

What am I doing wrong?

答:
You should change your binding in following way:

```<code>Bindings.bindContent(triangle.getPoints(), trianglePoints);
</code>```

Your previous binding did not work because trianglePoints.get() is just result of computeValue() call i.e. creating ObservableList with some values calculated upon initial width and height. Thus further changes to width and height properties were not taken into account.

Title: How do I use Bindings.bindContent?

Body:
I have a polygon that I want to grow in size when the window is resized. I have a DoubleBinding that it the baseline for the size of all of my shapes in the scene. I use this DoubleBinding to create a ListBinding that calculates how big the polygon should be. I tried to use Bindings.bindContent(list1, list2) to bind the ListBinding to the polygon's points, but it doesn't seem to work.

    Polygon triangle = new Polygon();

    ListBinding<Double> trianglePoints = new ListBinding<Double>() {
        {
            super.bind(width, height);
        }
        @Override
        protected ObservableList<Double> computeValue() {
            ObservableList<Double> points = FXCollections.observableArrayList();
            points.addAll(0.0, 0.0, width.get()/2, height.get()/4, 0.0, height.get()/2);
            return points;
        }
    };
    Bindings.bindContent(triangle.getPoints(), trianglePoints.get());

I found that if I add an InvalidationListener to the triangle points and manually change the the polygon points when it fires off, it works.

    trianglePoints.addListener((InvalidationListener)(listener) -> triangle.getPoints().setAll(trianglePoints.get()));

What am I doing wrong?

Body:
You should change your binding in following way:

Bindings.bindContent(triangle.getPoints(), trianglePoints);

Your previous binding did not work because trianglePoints.get() is just result of computeValue() call i.e. creating ObservableList with some values calculated upon initial width and height. Thus further changes to width and height properties were not taken into account.


问:
Azure Service Fabric vs Azure Container Services
I understand that both Azure Service Fabric and Azure Container Services can be used to host microservices through containers.

In what scenarios is it practical & cost effective to use one over the other? What are some strong use cases for Azure Service Fabric and Azure Container Services models of hosting

I read this comparison but did not find it comprehensive

Update: A comparison table like one in this diagram would help keep the points "sticky" & memorable while deciding which option to use

Acronyms used in the table - AF - Azure Functions, ASF - Azure Service Fabric, ASE - App Service Environment, ACS - Azure Container Service, VMSS - Virtual Machine Scale Set

The “rank” should not be misconstrued as good or bad

答: Gross over simplification. If your a Linux guy ACS will probably match what you want better. If you are a Windows dev writing windows code ASF will probably serve you better.</p>


问:
DB2 CASE statement and CONCAT
I'm having trouble return the correct information with my select statement

table:

```<code>prefix | suffix | alternate
------ | ------ | --------
A      | 12345  | 0
B      | 67890  | 0
C      | 0      | 555555
</code>```

Here is my query

```<code>SELECT
        CASE WHEN prefix = 'C' THEN alternate
        ELSE CONCAT(prefix, suffix) END as Result
FROM table
</code>```

What I would like to see as a result:

```<code>Result
------
A12345
B67890
555555
</code>```

What I actually see:

```<code>555555
</code>```

if I take out the CONCAT using this select

```<code>SELECT
        CASE WHEN prefix = 'C' THEN alternate
        ELSE suffix END as Result
FROM table
</code>```

I get the number of rows I want but not the correct column values.  I'm missing the prefix in the first two rows.

Result

```<code>12345
67890
555555
</code>```

Thoughts on how I can do this without duplicating code with union?

```<code>Select concat(prefix,suffix) as result from table
union
select alternate as result from table
</code>```

答:
You can do something like this </p>

```<code>SELECT
    CASE WHEN prefix <> 'C'
         THEN prefix||suffix
         ELSE cast (alternate as char(20))
    END as Result
FROM table
</code>```

Title: DB2 CASE statement and CONCAT

Body:
I'm having trouble return the correct information with my select statement

table:

prefix | suffix | alternate
------ | ------ | --------
A      | 12345  | 0
B      | 67890  | 0
C      | 0      | 555555

Here is my query

SELECT
        CASE WHEN prefix = 'C' THEN alternate
        ELSE CONCAT(prefix, suffix) END as Result
FROM table

What I would like to see as a result:

Result
------
A12345
B67890
555555

What I actually see:

555555

if I take out the CONCAT using this select

SELECT
        CASE WHEN prefix = 'C' THEN alternate
        ELSE suffix END as Result
FROM table

I get the number of rows I want but not the correct column values.  I'm missing the prefix in the first two rows.

Result

12345
67890
555555

Thoughts on how I can do this without duplicating code with union?

Select concat(prefix,suffix) as result from table
union
select alternate as result from table

Body:
You can do something like this

SELECT
    CASE WHEN prefix <> 'C'
         THEN prefix||suffix
         ELSE cast (alternate as char(20))
    END as Result
FROM table


问:
Multiple selectors: identify the triggering one?
Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:

Having multiple selectors like

```<code>$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = ???;
});
</code>```

, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)....

Thanks.

答:
The element which triggers an event is available within the function as $(this), i.e.

```<code>$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = $(this);
});
</code>```

You can also test to identify if the element matches a particular selector using is():

```<code>if ($(this).is('a.button'))) { ... }
</code>```

Body:
Here's a very small issue that I was unable to figure out. I'm sure someone can answer in no time:

Having multiple selectors like

$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = ???;
});

, how can I figure out which selector was actually clicked? I need to use it like $(clicked_element)....

Thanks.

Body:
The element which triggers an event is available within the function as $(this), i.e.

$('a.button, span.xyz, a.another').click(function(e) {
   var clicked_element = $(this);
});

You can also test to identify if the element matches a particular selector using is():

if ($(this).is('a.button'))) { ... }


问:
How to call methods from UWP Phone Calling API
How to call methods from UWP Phone Calling API. I want to make a simple uwp phone calling application which just makes a call.</p>

答:
See PhoneCall UWP sample from Microsoft . This is a Mobile only sample :
Phone call sample by Microsoft</p>


问:
How to insert list item into listview without modifying the underlying data set?
I have a ListView that is populated by an ArrayAdapter, and I need to insert an advertisement after every Nth legitimate list item.  The easiest way I can think of to do this would be to modify the array that defines the adapter's data set directly (or indirectly, via ArrayAdapter::add/insert) as follows:

```<code>/**
 * Injects ad entries into the station list after every N legit entries
 *
 * @param adapter the arrayadapter that will generate the views representing our legit and ad list items
 */
private void injectAdEntries(MyArrayAdapter adapter){
    int legitItemCount = adapter.getCount();
    int adStride = 4;
    if(legitItemCount >= adStride) {
        //adstride-1 to account for the 0 index
        for (int legitItemIndex = adStride-1; legitItemIndex < legitItemCount; legitItemIndex += adStride) {
            //create clone of last legit entry, to use as context
            // data for the ad, and mark it 'illegitimate' (ad)
            LegitObject totallyLegit = new LegitObject(adapter.getItem(legitItemIndex));
            totallyLegit.setLegit(false);
            adapter.insert(totallyLegit,legitItemIndex+1);

        }
    }
}
</code>```

After the injection, MyArrayAdapter's getView override can detect the false legit value and handle advertisement entries differently from legitimate entries.

The trouble is that I don't want to pollute the legitimate data array.   Ideally, I would insert these advertisement list items without modifying the underlying data set in any way.  Is there a way to make an adapter produce views that aren't reflected in its data set?

Edit

I also need all the items in the legitimate data set to be displayed in the ListView; the ad list items need to appear 'in addition to' rather than 'instead of' legitimate list items.

答:
I will assume that you are using a recyclerView as a list. So, to have heterogenous layouts (i.e.: YOUR ACTUAL ITEM LAYOUT + AD LAYOUT) you should follow these steps:

Override getItemView like

```<code>@Override
public int getItemViewType(int position) {
    // insert an Ad every multiple of 5
    if (position % 5 == 0) {
        return AD_POSITION;
    }
    return NORMAL_POSITION;
}
</code>```

Next, you need to override the onCreateViewHolder method to tell the RecyclerView.Adapter about which RecyclerView.ViewHolder object to create based on the viewType returned.

```<code>@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    RecyclerView.ViewHolder viewHolder;
    LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());

    switch (viewType) {
        case AD_POSITION:
            View v1 = inflater.inflate(R.layout.list_item_ad, viewGroup, false);
            viewHolder = new AdViewHolder(v1);
            break;
        default:
            // NORMAL_POSITION
            View v = inflater.inflate(R.layout.list_item, viewGroup, false);
            viewHolder = new NormalViewHolder(v);
            break;
    }
    return viewHolder;
}
</code>```

For more details you can check this link out.

Body:
I have a ListView that is populated by an ArrayAdapter, and I need to insert an advertisement after every Nth legitimate list item.  The easiest way I can think of to do this would be to modify the array that defines the adapter's data set directly (or indirectly, via ArrayAdapter::add/insert) as follows:

/**
 * Injects ad entries into the station list after every N legit entries
 *
 * @param adapter the arrayadapter that will generate the views representing our legit and ad list items
 */
private void injectAdEntries(MyArrayAdapter adapter){
    int legitItemCount = adapter.getCount();
    int adStride = 4;
    if(legitItemCount >= adStride) {
        //adstride-1 to account for the 0 index
        for (int legitItemIndex = adStride-1; legitItemIndex < legitItemCount; legitItemIndex += adStride) {
            //create clone of last legit entry, to use as context
            // data for the ad, and mark it 'illegitimate' (ad)
            LegitObject totallyLegit = new LegitObject(adapter.getItem(legitItemIndex));
            totallyLegit.setLegit(false);
            adapter.insert(totallyLegit,legitItemIndex+1);

        }
    }
}

After the injection, MyArrayAdapter's getView override can detect the false legit value and handle advertisement entries differently from legitimate entries.

The trouble is that I don't want to pollute the legitimate data array.   Ideally, I would insert these advertisement list items without modifying the underlying data set in any way.  Is there a way to make an adapter produce views that aren't reflected in its data set?

Edit

I also need all the items in the legitimate data set to be displayed in the ListView; the ad list items need to appear 'in addition to' rather than 'instead of' legitimate list items.

Body:
I will assume that you are using a recyclerView as a list. So, to have heterogenous layouts (i.e.: YOUR ACTUAL ITEM LAYOUT + AD LAYOUT) you should follow these steps:

Override getItemView like

@Override
public int getItemViewType(int position) {
    // insert an Ad every multiple of 5
    if (position % 5 == 0) {
        return AD_POSITION;
    }
    return NORMAL_POSITION;
}

Next, you need to override the onCreateViewHolder method to tell the RecyclerView.Adapter about which RecyclerView.ViewHolder object to create based on the viewType returned.

@Override
public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int viewType) {
    RecyclerView.ViewHolder viewHolder;
    LayoutInflater inflater = LayoutInflater.from(viewGroup.getContext());

    switch (viewType) {
        case AD_POSITION:
            View v1 = inflater.inflate(R.layout.list_item_ad, viewGroup, false);
            viewHolder = new AdViewHolder(v1);
            break;
        default:
            // NORMAL_POSITION
            View v = inflater.inflate(R.layout.list_item, viewGroup, false);
            viewHolder = new NormalViewHolder(v);
            break;
    }
    return viewHolder;
}

For more details you can check this link out.


问:
C# Index is unpredictable when adding controls to a panel
I have no code to show because this is a problem with me not understanding the behavior of the designer in VS2015 using C#. I have added a series of labels to a panel, so I can iterate through them in code. The problem is, it seems no matter what order I add the labels to the panel, the indexes of the controls make no sense.

Here is a screen shot. The back colored labels to the right are all contained in a separate panel. I have coded the labels to show their index within the panel container.

These were added one at a time from the bottom up. How can I manually add the labels and still have predictable indexes?

Any help is appreciated.

This is the result after making the labels the same size, renaminging them lbl0, lbl1 etc. and adding them one at a time from top to bottom....

答:
You can see where controls are added to the control collection if you look in the Form.Designer.cs file, which is part of the class definition for your form.

Here you will see a section that begins with // Form, and under that you will see where it calls `this.Controls.Add();

The items in this list appear in the order in which you dropped them onto the form (at least for me they do). I just copy/pasted 10 labels onto the form, and I see this:

```<code>//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 684);
this.Controls.Add(this.label10);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);
</code>```

At runtime, the controls are found in the collection exactly as you would expect from reading the code above; the last control added is at index [0]:

Now, adding a panel is a slightly different story, but not much. Because the Panel is a container object, the labels get added to the Panel controls collection:

```<code>//
// panel1
//
this.panel1.Controls.Add(this.label18);
this.panel1.Controls.Add(this.label17);
this.panel1.Controls.Add(this.label16);
this.panel1.Controls.Add(this.label15);
this.panel1.Controls.Add(this.label14);
this.panel1.Controls.Add(this.label13);
this.panel1.Controls.Add(this.label12);
this.panel1.Controls.Add(this.label11);
this.panel1.Location = new System.Drawing.Point(37, 366);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(200, 172);
this.panel1.TabIndex = 13;
</code>```

Note, however, that the behavior is the same. The most recent control is added to the Controls collection first, and will be in the Panel.Controls[0] position.

Body:
You can see where controls are added to the control collection if you look in the Form.Designer.cs file, which is part of the class definition for your form.

Here you will see a section that begins with // Form, and under that you will see where it calls `this.Controls.Add();

The items in this list appear in the order in which you dropped them onto the form (at least for me they do). I just copy/pasted 10 labels onto the form, and I see this:

//
// Form1
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(284, 684);
this.Controls.Add(this.label10);
this.Controls.Add(this.label9);
this.Controls.Add(this.label8);
this.Controls.Add(this.label7);
this.Controls.Add(this.label6);
this.Controls.Add(this.label5);
this.Controls.Add(this.label4);
this.Controls.Add(this.label3);
this.Controls.Add(this.label2);
this.Controls.Add(this.label1);

At runtime, the controls are found in the collection exactly as you would expect from reading the code above; the last control added is at index [0]:

Now, adding a panel is a slightly different story, but not much. Because the Panel is a container object, the labels get added to the Panel controls collection:

//
// panel1
//
this.panel1.Controls.Add(this.label18);
this.panel1.Controls.Add(this.label17);
this.panel1.Controls.Add(this.label16);
this.panel1.Controls.Add(this.label15);
this.panel1.Controls.Add(this.label14);
this.panel1.Controls.Add(this.label13);
this.panel1.Controls.Add(this.label12);
this.panel1.Controls.Add(this.label11);
this.panel1.Location = new System.Drawing.Point(37, 366);
this.panel1.Name = "panel1";
this.panel1.Size = new System.Drawing.Size(200, 172);
this.panel1.TabIndex = 13;

Note, however, that the behavior is the same. The most recent control is added to the Controls collection first, and will be in the Panel.Controls[0] position.


问:
SQL export to ListView using C#
I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!

```<code>string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}
</code>```

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

```<code>foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}
</code>```

答:
The standaard solution would be: listbox1.DataSource = poplb6ds;
If you need any specific formatting, please elaborate on that.

Title: SQL export to ListView using C#

Body:
I have a query that selects 3 columns from a SQL table, I need to export the resulting query into a listview.  I don't need any help with the SQL setup, just how to format it into the listview.  There is where I am stuck.  Any help is appreciated.  Thanks!

string sql = "select distinct pro,ds,date from dbo.Sge where date IN (select max(date) from dbo.Storage) order by project";
SqlConnection con = new SqlConnection("Data Source= ;Initial Catalog= ;Integrated Security= SSPI");
con.Open();
DataSet ds = new DataSet();
SqlDataAdapter adapter = new SqlDataAdapter(sql,con);
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
    for(int i=0; i< ds.Tables[0].Columns.Count; i++))
}

Edit: Sorry guys, i mentioned ListBox originally and i meant ListView. My ListView is detailed and had a column for each of my columns in my select, i just simply need the SQL export to go to the right column.

This is what I have come up with, but it doesn't add to each column, just to the first column

foreach (DataRow row in poplb6ds.Tables[0].Rows)
{
    listView1.Items.Add(row["Pro"].ToString());
    listView1.Items.Add(row["size"].ToString());
    listView1.Items.Add(row["Date"].ToString());
}


问:
Cryptic "client does not exist" error after signing into my Node.js app with Azure AD
I am attempting to use the passport-azure-ad library to authenticate users for my Node.js web application.

Accessing the sign in route I have configured in the app takes me to a Microsoft Azure sign in page (which is the expected behavior). However, when I sign in, I am taken to an error page (https://login.live.com/err.srf?lc=1033#error=unauthorized_client&error_description=The+client+does+not+exist.+If+you+are+the+application+developer%2c+configure+a+new+application+through+the+application+management+site+at+https://apps.dev.microsoft.com/.&state=H08LUScEDdzg92Cq8gujjtT5LPKJ4sNJ) that says "Client does not exist." However, I have supplied the client ID and the client secret matching the application ID and application secret generated by the Microsoft Azure Active Directory app registration for my app, so the app clearly does exist. Also, the apps.dev.microsoft.com link is broken.

How exactly can this problem be fixed?

答:
Registering an app at the Azure Portal under App Registrations will create a standard Azure AD app. This app can sign in Azure AD users in your tenant, and in any Azure AD tenant if configured to be multi-tenant.

The error you have above is for the Microsoft Account STS. These are outlook.com, hotmail.com, live.com, etc accounts.  Since your app is not registered in this system, the service doesn't recognize your app.  If you would like to support these as well as Azure AD sign in, you need to register a converged app at the App Registration Portal.

Use the app configs from that site instead of the ones you got from the Azure Portal and this should resolve the error you're getting.


问:
Way to determine number of elements in array when number is smaller than initialized index?
I have an array initialized to 17 that is storing a certain number of elements. The issue is that when I try to find the size using the sizeof() method or a loop and counter for each element, I get 17, but that is not the number of elements stored in the array, just the size. Does anyone know how to find the actual number of elements in an array, not just its initialized size?

The code I have tried so far:

Method 1:

```<code>int arr[17];
//after reading in the data from the file
cout << sizeof(arr)/sizeof(arr[0])<< endl;
//this just prints 17
</code>```

Method 2:

```<code>int arr[17]
int counter = 0;
for (int i: arr)
{
 counter++;
}
cout << counter << endl;
//just prints 17
</code>```

答:
sizeof() is evaluated at compile-time, not at runtime.  Taking the size of a fixed array will be a constant value, regardless of how many values you store in it.

You have three options:

define a sentry value that will never appear in the actual data, pre-fill the array with that value, and then count the number of elements that do not equal that value:

```<code>#include <algorithm>

bool isNotSentry(int value) { return (value != -1); }

...

int arr[17];
std::fill(arr, arr+17, -1);

...

//when adding a value to the array...
arr[index] = ...;

...

//after reading in the values from the file
int count = std::count_if(arr, arr+17, isNotSentry);
std::cout << count << std::endl;
</code>```

Or, if using C++11 or later:

```<code>#include <array>

std::array<int, 17> arr;
arr.fill(-1);

...

//when adding a value to the array...
arr[index] = ...;

...

//after reading in the values from the file
int count = std::count_if(arr.cbegin(), arr.cend(), [](const int value){ return (value != -1); });
std::cout << count << std::endl;
</code>```

manually keep track of how many values you put in the array:

```<code>int arr[17];
int count = 0;

...

//when adding a value to the array...
arr[count++] = ...;

...

//after reading in the values from the file
std::cout << count << endl;
</code>```

The above approaches assume the data will never be more than 17 values max.  But if you don't know up front how many values may actually be present, then simply don't use a fixed length array to begin with.  Use a std::vector instead, which resizes itself dynamically as needed:

```<code>#include <vector>

std::vector<int> arr;
arr.reserve(17); // <-- optional

...

//when adding a value to the vector...
arr.push_back(...);

...

//after reading in the values from the file
std::cout << arr.size() << std::endl;
</code>```

Body:
I have an array initialized to 17 that is storing a certain number of elements. The issue is that when I try to find the size using the sizeof() method or a loop and counter for each element, I get 17, but that is not the number of elements stored in the array, just the size. Does anyone know how to find the actual number of elements in an array, not just its initialized size?

The code I have tried so far:

Method 1:

int arr[17];
//after reading in the data from the file
cout << sizeof(arr)/sizeof(arr[0])<< endl;
//this just prints 17

Method 2:

int arr[17]
int counter = 0;
for (int i: arr)
{
 counter++;
}
cout << counter << endl;
//just prints 17

Body:
sizeof() is evaluated at compile-time, not at runtime.  Taking the size of a fixed array will be a constant value, regardless of how many values you store in it.

You have three options:

define a sentry value that will never appear in the actual data, pre-fill the array with that value, and then count the number of elements that do not equal that value:

#include <algorithm>

bool isNotSentry(int value) { return (value != -1); }

...

int arr[17];
std::fill(arr, arr+17, -1);

...

//when adding a value to the array...
arr[index] = ...;

...

//after reading in the values from the file
int count = std::count_if(arr, arr+17, isNotSentry);
std::cout << count << std::endl;

Or, if using C++11 or later:

#include <array>

std::array<int, 17> arr;
arr.fill(-1);

...

//when adding a value to the array...
arr[index] = ...;

...

//after reading in the values from the file
int count = std::count_if(arr.cbegin(), arr.cend(), [](const int value){ return (value != -1); });
std::cout << count << std::endl;

manually keep track of how many values you put in the array:

int arr[17];
int count = 0;

...

//when adding a value to the array...
arr[count++] = ...;

...

//after reading in the values from the file
std::cout << count << endl;

The above approaches assume the data will never be more than 17 values max.  But if you don't know up front how many values may actually be present, then simply don't use a fixed length array to begin with.  Use a std::vector instead, which resizes itself dynamically as needed:

#include <vector>

std::vector<int> arr;
arr.reserve(17); // <-- optional

...

//when adding a value to the vector...
arr.push_back(...);

...

//after reading in the values from the file
std::cout << arr.size() << std::endl;


问:
Calling void function before main()
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block...

```<code>#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}

int g_foo = (earlyInit(), 0);

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}
</code>```

...I have no need for g_foo and would rather it not exist. Is there a way to call void functions without an intermediate temp variable?

答:
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block.

The language does not provide any such mechanism. As other answers have pointed out, there maybe compiler-specific ways to do that.

However, I don't see anything wrong with your approach. I use the following pattern a lot.

```<code>#include <iostream>

namespace mainNS  // A file-specific namespace.
{
   void earlyInit()
   {
      std::cout << "The void before the world." << std::endl;
   }

   struct Initializer
   {
      Initializer();
   };
}

using namespace mainNS;
static Initializer initializer;

Initializer::Initializer()
{
   earlyInit();
   // Call any other functions that makes sense for your application.
}

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}
</code>```

Title: Calling void function before main()

Body:
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block...

#include <iostream>

void earlyInit()
{
  std::cout << "The void before the world." << std::endl;
}

int g_foo = (earlyInit(), 0);

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}

...I have no need for g_foo and would rather it not exist. Is there a way to call void functions without an intermediate temp variable?

Body:
I wanted to know if it was possible to call a void function without using a temp variable. E.g. in the following code block.

The language does not provide any such mechanism. As other answers have pointed out, there maybe compiler-specific ways to do that.

However, I don't see anything wrong with your approach. I use the following pattern a lot.

#include <iostream>

namespace mainNS  // A file-specific namespace.
{
   void earlyInit()
   {
      std::cout << "The void before the world." << std::endl;
   }

   struct Initializer
   {
      Initializer();
   };
}

using namespace mainNS;
static Initializer initializer;

Initializer::Initializer()
{
   earlyInit();
   // Call any other functions that makes sense for your application.
}

int main( int argc, char* argv[] )
{
  std::cout << "Hello, world!" << std::endl;
}


问:
jQuery UI Sortable: order of events
Does anyone know in which order the jQuery sortable events are being triggered?
I'm asking this because I had a problem with stop and update. It made more sense to me that update event would come after stop event but that was not the case.

Is this documented anywhere or did someone investigate this? I couldn't manage to find a proper list and I don't feel like looking through the code just yet.

答:
The order of events is:

create - Triggered when the sortable is created

start - Triggered when sorting starts

activate - Triggered for every connected list on drag start

over - Triggered when a sortable item is moved into a sortable list

sort - Triggered during sorting

change - Triggered during sorting, but only when DOM position has changed

beforeStop - Triggered before sorting stops, placeholder/helper

update - Triggered when stopped sorting and DOM position has changed

deactivate - Triggered before sorting stopped, propagated to all possible connected lists

out - Triggered when a sortable item is moved away from a sortable list

stop - Triggered when sorting has stopped

There are other events which can occur too:

receive/remove - Triggered when items are moved between lists

No idea why this isn't clearer on the jQueryUI site.

Note that, depending upon the event triggered, the ui arguments differs. It's worth looking at the API documentation to be clear what this is and to debug it.

http://api.jqueryui.com/sortable/

Title: jQuery UI Sortable: order of events