问:
Finding the centroid of a polygon
I use the following code to find the centroid of a polygon (I didn't write the code, it's from another question).

```<code>Point compute2DPolygonCentroid(const std::vector<Point> vertices) {
    Point centroid;
    double signedArea = 0.0;
    double x0 = 0.0; // Current vertex X
    double y0 = 0.0; // Current vertex Y
    double x1 = 0.0; // Next vertex X
    double y1 = 0.0; // Next vertex Y
    double a = 0.0;  // Partial signed area

    // For all vertices except last
    for (int i = 0; i < vertices.size() - 1; ++i) {

        x0 = vertices[i].x;
        y0 = vertices[i].y;
        x1 = vertices[i + 1].x;
        y1 = vertices[i + 1].y;
        a = x0 * y1 - x1 * y0;
        signedArea += a;
        centroid.x += (x0 + x1) * a;
        centroid.y += (y0 + y1) * a;

    }

    // Do last vertex separately to avoid performing an expensive
    // modulus operation in each iteration.
    x0 = vertices.back().x;
    y0 = vertices.back().y;
    x1 = vertices.front().x;
    y1 = vertices.front().y;
    a = x0 * y1 - x1 * y0;
    signedArea += a;
    centroid.x += (x0 + x1) * a;
    centroid.y += (y0 + y1) * a;

    signedArea *= 0.5;
    centroid.x /= (6.0 * signedArea);
    centroid.y /= (6.0 * signedArea);

    return centroid;
}
</code>```

The problem is that it works ONLY when the points in the input vector vertices are in clockwise order. When the points are in counterclockwise order it doesn't work. Here's a picture of what I mean by cw && ccw order:

I don't understand why it doesn't work when just the order of the points change but the points are still the same.

答:
The problem, as it turns out, is that Point had unsigned members. There's also a potential secondary problem, regarding floating point rounding issues.

In this algorithm, if the wind order is the wrong way around, the computed area will be negative, and when you do something like

```<code>centroid.x += (x0 + x1) * a;
</code>```

you'll get an incorrect value because a will be negative and centroid.x is unsigned.

You should store the intermediate centroid values as a floating point of some kind, so that a) you won't get these signed/unsigned issues and b) so that you won't get rounding errors on every vertex; I'm not sure if these errors would end up being large enough to cause you problems, but it seems silly to risk it when it can be so easily avoided. You should cast to unsigned int (or whatever) at the very end when you return.

Title: Finding the centroid of a polygon

Body:
I use the following code to find the centroid of a polygon (I didn't write the code, it's from another question).

Point compute2DPolygonCentroid(const std::vector<Point> vertices) {
    Point centroid;
    double signedArea = 0.0;
    double x0 = 0.0; // Current vertex X
    double y0 = 0.0; // Current vertex Y
    double x1 = 0.0; // Next vertex X
    double y1 = 0.0; // Next vertex Y
    double a = 0.0;  // Partial signed area

    // For all vertices except last
    for (int i = 0; i < vertices.size() - 1; ++i) {

        x0 = vertices[i].x;
        y0 = vertices[i].y;
        x1 = vertices[i + 1].x;
        y1 = vertices[i + 1].y;
        a = x0 * y1 - x1 * y0;
        signedArea += a;
        centroid.x += (x0 + x1) * a;
        centroid.y += (y0 + y1) * a;

    }

    // Do last vertex separately to avoid performing an expensive
    // modulus operation in each iteration.
    x0 = vertices.back().x;
    y0 = vertices.back().y;
    x1 = vertices.front().x;
    y1 = vertices.front().y;
    a = x0 * y1 - x1 * y0;
    signedArea += a;
    centroid.x += (x0 + x1) * a;
    centroid.y += (y0 + y1) * a;

    signedArea *= 0.5;
    centroid.x /= (6.0 * signedArea);
    centroid.y /= (6.0 * signedArea);

    return centroid;
}

The problem is that it works ONLY when the points in the input vector vertices are in clockwise order. When the points are in counterclockwise order it doesn't work. Here's a picture of what I mean by cw && ccw order:

I don't understand why it doesn't work when just the order of the points change but the points are still the same.

Body:
The problem, as it turns out, is that Point had unsigned members. There's also a potential secondary problem, regarding floating point rounding issues.

In this algorithm, if the wind order is the wrong way around, the computed area will be negative, and when you do something like

centroid.x += (x0 + x1) * a;

you'll get an incorrect value because a will be negative and centroid.x is unsigned.

You should store the intermediate centroid values as a floating point of some kind, so that a) you won't get these signed/unsigned issues and b) so that you won't get rounding errors on every vertex; I'm not sure if these errors would end up being large enough to cause you problems, but it seems silly to risk it when it can be so easily avoided. You should cast to unsigned int (or whatever) at the very end when you return.


来源: stackexchange

问:
Elasticsearch fielddata unsupported while index mapping
I'm trying to create an index in Elasticsearch through Python. I have a local instance of ES deployed and queries run fine. However, I have a schema. Here it is:

```<code>{
  "mappings": {
    "payment":{
      "properties":{
        "timestamp":{"type":"date"},
        "base_amount":{"type":"integer"},
        "derived_id":{"type":"keyword", "fielddata": true},
        "attempts":{"type":"integer"},
        "status":{"type":"text","fielddata":true},
        "error_code":{"type":"text","fielddata":true}
      }
    }
  }
}
</code>```

Here is the code I am using to create this index

```<code>import json

import requests

schema = {
    "mappings": {
        "payment": {
            "properties": {
                "timestamp": {"type": "date"},
                "base_amount": {"type": "integer"},
                "derived_key": {"type": "keyword", "fielddata": True},
                "attempts": {"type": "integer"},
                "status": {"type": "text", "fielddata": True},
                "error_code": {"type": "text", "fielddata": True}
            }
        }
    }
}

index = 'http://localhost:9200/payment_index_2016_08_21'
r = requests.put(index, data=json.dumps(schema))

print r.content
</code>```

The error I get is

{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"Mapping
  definition for [derived_key] has unsupported parameters:  [fielddata :
  true]"}],"type":"mapper_parsing_exception","reason":"Failed to parse
  mapping [payment]: Mapping definition for [derived_key] has
  unsupported parameters:  [fielddata :
  true]","caused_by":{"type":"mapper_parsing_exception","reason":"Mapping
  definition for [derived_key] has unsupported parameters:  [fielddata :
  true]"}},"status":400}

I don't understand why the fielddata = true is causing an issue, since I see it's allowed here https://www.elastic.co/guide/en/elasticsearch/reference/current/fielddata.html. Any clue what the issue behind this is?

答: You don't need to enable fielddata on keyword fields. you can do aggregations on keyword fields.

ContentLicense: CC BY-SA 3.0

Body:
I'm trying to create an index in Elasticsearch through Python. I have a local instance of ES deployed and queries run fine. However, I have a schema. Here it is:

{
  "mappings": {
    "payment":{
      "properties":{
        "timestamp":{"type":"date"},
        "base_amount":{"type":"integer"},
        "derived_id":{"type":"keyword", "fielddata": true},
        "attempts":{"type":"integer"},
        "status":{"type":"text","fielddata":true},
        "error_code":{"type":"text","fielddata":true}
      }
    }
  }
}

Here is the code I am using to create this index

import json

import requests

schema = {
    "mappings": {
        "payment": {
            "properties": {
                "timestamp": {"type": "date"},
                "base_amount": {"type": "integer"},
                "derived_key": {"type": "keyword", "fielddata": True},
                "attempts": {"type": "integer"},
                "status": {"type": "text", "fielddata": True},
                "error_code": {"type": "text", "fielddata": True}
            }
        }
    }
}

index = 'http://localhost:9200/payment_index_2016_08_21'
r = requests.put(index, data=json.dumps(schema))

print r.content

The error I get is

{"error":{"root_cause":[{"type":"mapper_parsing_exception","reason":"Mapping
  definition for [derived_key] has unsupported parameters:  [fielddata :
  true]"}],"type":"mapper_parsing_exception","reason":"Failed to parse
  mapping [payment]: Mapping definition for [derived_key] has
  unsupported parameters:  [fielddata :
  true]","caused_by":{"type":"mapper_parsing_exception","reason":"Mapping
  definition for [derived_key] has unsupported parameters:  [fielddata :
  true]"}},"status":400}

I don't understand why the fielddata = true is causing an issue, since I see it's allowed here https://www.elastic.co/guide/en/elasticsearch/reference/current/fielddata.html. Any clue what the issue behind this is?


问:
C# IIS SignalR /signalr/hubs folder
I've got an ASP.NET Web Application with a simple SignalR setup and a hub. When i publish the files, it generates web/packages.config and the /bin/ dlls.

On client side, i can also easily access the hub on the IIS:

```<code>var hubConnection = new HubConnection("http://localhost:80");
IHubProxy proxy = hubConnection.CreateHubProxy("TestHub");
</code>```

When i access http://localhost/signalr/hubs i can see the generated hub, but how exactly does it work? I can't find a /signalr/hubs directory in my IIS folder.
When and how is it being generated?

答:
The directory is not being generated at all, it never exists.

A big piece of ASP.NET, and web frameworks in general, is the router. Basically, you are familiar with static file handlers (that handle routes like "/myFolder/myFile.doc") and serve the file back to the browser.

You also need, however, a way to execute code. Since the primary way to execute requests against a web server is REST; web frameworks route certain URL-verb combinations to code handlers. This is how WebAPI and MVC both work. In the case of SignalR, it registers the "/signalr/hubs" route and returns the generated javascript file when that route is requested.

Title: C# IIS SignalR /signalr/hubs folder

Body:
I've got an ASP.NET Web Application with a simple SignalR setup and a hub. When i publish the files, it generates web/packages.config and the /bin/ dlls.

On client side, i can also easily access the hub on the IIS:

var hubConnection = new HubConnection("http://localhost:80");
IHubProxy proxy = hubConnection.CreateHubProxy("TestHub");

When i access http://localhost/signalr/hubs i can see the generated hub, but how exactly does it work? I can't find a /signalr/hubs directory in my IIS folder.
When and how is it being generated?


问:
EXCEL 2016 - Cannot Use TEXT criteria in Conditional Formatting Rules
I have 3 columns. in the 1st i have ascending numbering, in the 2nd dates & 3rd text

I am trying fill in green color into a cell (of 1st column) which meets the following criteria:
the date is older than TODAY() and
contains specific text "text criteria"

in the conditional formatting rules window i tried the following:

```<code>=AND($M$6:$M$827<TODAY(); $O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())*($O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())+($O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())&($O$6:$O$827="text criteria")
</code>```

All occasions were received without error, however never got the highlight i need.
Because i was sure that the AND function is correct and should have worked i copied it into a 4th column and indeed it worked correctly in all 827 inputs.

On the other hand, i also used only the$M$6:$M$827<TODAY() part into the conditional formatting window and it work. But it also highlighted some entries should not have because it did not have the second criteria.

Is there a problem by using text criteria in conditional formatting?
If yes how should i work around it? (I was thinking to use the newly 4th column; which works correctly; i need the entries that have the value "TRUE")

Thanks in advance for any help

答:
You would only use the upper cell of the columns, making the row relative:

```<code>=AND($M6<TODAY(); $O6 ="text criteria")
</code>```

Then make the Applies To: $M$6:$M$827 this should include all the rows and column you desire to apply the conditional formatting.

Body:
I have 3 columns. in the 1st i have ascending numbering, in the 2nd dates & 3rd text

I am trying fill in green color into a cell (of 1st column) which meets the following criteria:
the date is older than TODAY() and
contains specific text "text criteria"

in the conditional formatting rules window i tried the following:

=AND($M$6:$M$827<TODAY(); $O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())*($O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())+($O$6:$O$827="text criteria")
=($M$6:$M$827<TODAY())&($O$6:$O$827="text criteria")

All occasions were received without error, however never got the highlight i need.
Because i was sure that the AND function is correct and should have worked i copied it into a 4th column and indeed it worked correctly in all 827 inputs.

On the other hand, i also used only the$M$6:$M$827<TODAY() part into the conditional formatting window and it work. But it also highlighted some entries should not have because it did not have the second criteria.

Is there a problem by using text criteria in conditional formatting?
If yes how should i work around it? (I was thinking to use the newly 4th column; which works correctly; i need the entries that have the value "TRUE")

Thanks in advance for any help

Body:
You would only use the upper cell of the columns, making the row relative:

=AND($M6<TODAY(); $O6 ="text criteria")

Then make the Applies To: $M$6:$M$827 this should include all the rows and column you desire to apply the conditional formatting.


问:
click the bottom part of an element?
I have a link that I need to click on that is halfway underneath another element.  Something like this:

```<code>______________________
| A  ____________    | <-- on top
|____|B_________|____|
     |__________| < - on bottom (need to click this one)
</code>```

When I try to click on the bottom link, I get

```<code>(B) is not clickable at point (254, 5). Other element would receive the click: (A).
</code>```

Here is an image (I need to click on the PO Box link).  I don't know exactly what to do here.  Thanks!

Here is the HTML in question.  Selenium is sending the click action to the span labelFieldWrapper:

```<code><div class='clr type_address formFieldContainer'>
    <span class="labelFieldWrapper">
        <label class="placeholder" for="address1">
            <span class="labelText">Address 1</span>
        </label>
        <input id="address1" name="address1" type="text" value="" autofillparam="ON" size="20" maxlength="60"/><span class="asterisk">*</span>
    </span>
    <p class="helpLink">
        <a href="javascript: void(0)"
           onclick="window.open('/checkout/canadian_province_support.jsp',
          'pobox',
          'width=450, \
           height=200, \
           directories=no, \
           location=no, \
           menubar=no, \
           resizable=no, \
           scrollbars=1, \
           status=no, \
           toolbar=no');
          return false;">PO Box?</a>  <-- Trying to click on this link
        </p>
    </div><!-- /formFieldContainer -->
</code>```

答:
I think you can use
xpath= //p[@class="helpLink"]/a

Title: click the bottom part of an element?

Body:
I have a link that I need to click on that is halfway underneath another element.  Something like this:

______________________
| A  ____________    | <-- on top
|____|B_________|____|
     |__________| < - on bottom (need to click this one)

When I try to click on the bottom link, I get

(B) is not clickable at point (254, 5). Other element would receive the click: (A).

Here is an image (I need to click on the PO Box link).  I don't know exactly what to do here.  Thanks!

Here is the HTML in question.  Selenium is sending the click action to the span labelFieldWrapper:

            Address 1

        <input id="address1" name="address1" type="text" value="" autofillparam="ON" size="20" maxlength="60"/>*

        PO Box?  <-- Trying to click on this link


问:
Merging a set of characters if the next row of characters has the same set?
Let's say I have the following string.

```<code>&eThe quick brown fox &djumps over the &dlazy &adog.
</code>```

Each set of color codes &letter, e.g &e will change the color of the following text until another color code appears. It's redundant to have two of the same codes follow after each other because it's both the same color.

```<code>&djumps over the &dlazy
</code>```

I'm trying to merge any duplicate color code that matches the color code before it, so the above string would change into the following:

```<code>&eThe quick brown fox &djumps over the lazy &adog.
</code>```

However I'm not sure how this is done. Can anyone help?

答:
Using String.replace in combination with callback and an outer variable storing the previous color:

let str = '&eThe quick brown fox &djumps over the &dlazy &adog.';

let last = '';
let result = str.replace(/&([a-z])/g, (match, color) =>
  color !== last ? (last = color, match) : ''
);

console.log(result); // &eThe quick brown fox &djumps over the lazy &adog.```

Body:
Let's say I have the following string.

&eThe quick brown fox &djumps over the &dlazy &adog.

Each set of color codes &letter, e.g &e will change the color of the following text until another color code appears. It's redundant to have two of the same codes follow after each other because it's both the same color.

&djumps over the &dlazy

I'm trying to merge any duplicate color code that matches the color code before it, so the above string would change into the following:

&eThe quick brown fox &djumps over the lazy &adog.

However I'm not sure how this is done. Can anyone help?


问:
how to use linq to return all ints in another set of ints for this scenario?
I have the following scenario:

```<code>1. int[] contentPermissions
2. Dictionary<int, int[]> userPermssions
</code>```

In #2 above, the key is the user ID and the value is an int[] of user permission ID's. What would be a good way to write a lambda function to return all user ID's which have a permission id which matches at least 1 permission in contentPermissions?

UPDATE

Does this look like a pretty good solution?:

```<code>  var userIdsWithPermissions = userPermissions.Where(
            x => x.Value.Intersect(contentPermissions).Count() > 1)
            .Select(x => x.Key).ToArray();
</code>```

答:
Your best bet would be to use a Contains() function. A slightly different option using Any()

```<code>        List<int> contentPermissions = new List<int>();
        Dictionary<int, List<int>> userPermssions = new Dictionary<int, List<int>>();

        var A = userPermssions.Where(m => m.Value.Any(n => contentPermissions.Contains(n))).Select(m => m.Key).ToList();
</code>```

Body:
I have the following scenario:

1. int[] contentPermissions
2. Dictionary<int, int[]> userPermssions

In #2 above, the key is the user ID and the value is an int[] of user permission ID's. What would be a good way to write a lambda function to return all user ID's which have a permission id which matches at least 1 permission in contentPermissions?

UPDATE

Does this look like a pretty good solution?:

  var userIdsWithPermissions = userPermissions.Where(
            x => x.Value.Intersect(contentPermissions).Count() > 1)
            .Select(x => x.Key).ToArray();

Body:
Your best bet would be to use a Contains() function. A slightly different option using Any()

        List<int> contentPermissions = new List<int>();
        Dictionary<int, List<int>> userPermssions = new Dictionary<int, List<int>>();

        var A = userPermssions.Where(m => m.Value.Any(n => contentPermissions.Contains(n))).Select(m => m.Key).ToList();

ContentLicense: CC BY-SA 4.0


问:
error: unexpected end of file (expecting "do") for shell script in Dockerfile
I don't want to have another .sh file with a script and going to add a shell script code promptly in the Dockerfile. However, I receive an error message during the image build:

/bin/sh: syntax error: unexpected end of file (expecting "do")

Here is the part of the Dockerfile with a script:

```<code>RUN cat .env | while [ read LINE ] \
do \
    envName=$(echo "$LINE" | grep -o "^[^\=]*") \
    echo "PassEnv $envName" >> httpd.conf \
done
</code>```

Any ideas what is wrong?

答:
Remove the square brackets [], and use ; at the end of lines because docker joins lines when sees your \'s, so the commands get melt.

This is working for me:

```<code>RUN cat .env | while read LINE ;\
    do \
      envName=$(echo "$LINE" | grep -o "^[^\=]*"); \
      echo "PassEnv $envName" >> httpd.conf ;\
    done
</code>```

Body:
I don't want to have another .sh file with a script and going to add a shell script code promptly in the Dockerfile. However, I receive an error message during the image build:

/bin/sh: syntax error: unexpected end of file (expecting "do")

Here is the part of the Dockerfile with a script:

RUN cat .env | while [ read LINE ] \
do \
    envName=$(echo "$LINE" | grep -o "^[^\=]*") \
    echo "PassEnv $envName" >> httpd.conf \
done

Any ideas what is wrong?

Body:
Remove the square brackets [], and use ; at the end of lines because docker joins lines when sees your \'s, so the commands get melt.

This is working for me:

RUN cat .env | while read LINE ;\
    do \
      envName=$(echo "$LINE" | grep -o "^[^\=]*"); \
      echo "PassEnv $envName" >> httpd.conf ;\
    done


问:
What happen if '&' operator is not included in scanf while taking input?
hii everyone i want to ask a question that what happen if '&' operator is not included in scanf.

```<code> #include <stdio.h>
 int main()
 {
     int x;
     scanf("%d", x);
   /* than what type of value will scanf store in x if there is
       not address of operator. */
     printf("%d", x);
     return 0;
  }
</code>```

either program crash or some garbage value prints out. I m little bit confused.

答:
scanf will try to write the value it read to the address stored in x. When you use the & operator, it will write the value to the address of x.

In this case x is a variable on the stack. Variables on the stack are (in C) not automatically initialized, so initially x will probably contain a garbage value. scanf will thus try to write the input value to a garbage address in memory.

This may either cause corruption of the program code or data (which may crash the program or result in unexpected behavior), or cause a segmentation fault (which will cause the OS to abort the program) if the value in x points to memory to which the program is not allowed to write (invalid or read-only memory). What exactly will happen depends on the value of x, which may be a value left over from another program, and this may be different each time you run the program.

Body:
hii everyone i want to ask a question that what happen if '&' operator is not included in scanf.

 #include <stdio.h>
 int main()
 {
     int x;
     scanf("%d", x);
   /* than what type of value will scanf store in x if there is
       not address of operator. */
     printf("%d", x);
     return 0;
  }

either program crash or some garbage value prints out. I m little bit confused.


答:
The while construct expects do to be on a separate line (or, to appear after a semicolon). So you probably want:

RUN cat .env | while [ read LINE ]; \
do \
    envName=$(echo "$LINE" | grep -o "^[^\=]*") \
    echo "PassEnv $envName" >> httpd.conf \
done
```

Note the semicolon on the first line.

Title: error: unexpected end of file (expecting "do") for shell script in Dockerfile

Body:
The while construct expects do to be on a separate line (or, to appear after a semicolon). So you probably want:

RUN cat .env | while [ read LINE ]; \
do \
    envName=$(echo "$LINE" | grep -o "^[^\=]*") \
    echo "PassEnv $envName" >> httpd.conf \
done

Note the semicolon on the first line.


问:
How can I run a single protractor test in IntelliJ?
I develop an Angular application and use Protractor for e2e tests. In Intellij (Ultimate Edition) I created a run/debug configuration for my tests. This works fine if I want to run all the tests. But how can I run only a single spec file or a single test case?

I would expect something like when running JUnit tests in Java where I can click into a test method and select from the context menu to only execute this single test method. Is something like that possible with Protractor?

答: You can either rename the describe block to fdescribe, and only the tests residing in that block will be run, or rename an it block to fit, and only this test will get executed.


问:
asyncio version of `os.chmod` in Python
I have some Python3 code running inside an asyncio event loop.

I want to use the functionality of os.chmod(...), but would ideally like a non-blocking version of this, so that I can use await os.chmod(...), and avoid making a blocking system call.

I don't believe there any libraries available that supply this functionality yet, at least from what I can see.

How would I go about implementing a non-blocking os.chmod(...) from scratch? Better still, is there a pre-existing solution?

答:
UNIX systems have not implemented an asynchronous API for the chmod syscall.
Thus the best you can do is run it in a thread pool:

```<code>await loop.run_in_executor(None, os.chmod, fname, mode)
</code>```

Title: asyncio version of `os.chmod` in Python

Body:
UNIX systems have not implemented an asynchronous API for the chmod syscall.
Thus the best you can do is run it in a thread pool:

await loop.run_in_executor(None, os.chmod, fname, mode)


问:
How to get city name from google map in ionic 2
How to obtain a city name from google map in ionic 2 If I have latitude and longitude coordinates of the area?

I searched all over the internet but I couldn't find the solution.

答:
You can use Geociding, as explained in this thread from Ionic's forum</p>

```<code>import { Geocoder, GeocoderRequest } from 'ionic-native';

let req: GeocoderRequest = { position: location }
  Geocoder.geocode(req).then((results)=>{
})
</code>```

Body:
You can use Geociding, as explained in this thread from Ionic's forum

import { Geocoder, GeocoderRequest } from 'ionic-native';

let req: GeocoderRequest = { position: location }
  Geocoder.geocode(req).then((results)=>{
})


问:
bootstrap glyphicon as button display on table
I'm new to the whole bootstrap thing so even though i tried to solve this for last 3 hours, i could'nt. I need a table to have 2 buttons in a cell that looks like a glypicon (so i can add javascript functions to them later). I managed to do this in 2 ways, but the problem is these buttons expand table row a lot. How do i solve this? maybe alternate method of making a button?

Here is how the table looks right now:

https://puu.sh/wbMUf/50a535e0f9.png

here are the lines used to achieve the result for the cell in the first row:

```<code><td>
    <p class = "btn"><span class = "fa fa-edit"></span></p>
    <p class = "btn"><span class = "fa fa-trash"></span></p>
</td>
</code>```

and for the cell in the second row:

```<code><td>
    <button type = "button" class = "btn btn-link"><span class = "fa fa-edit"></span></button>
    <button type = "button" class = "btn btn-link"><span class = "fa fa-trash"></span></button>
</td>
</code>```

Second option doesnt work, because the glyphs have to styled the same as the rest of the text in the table.

答:
You could do something like this

https://jsfiddle.net/7h4qqx44/2/

```<code><!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container style="margin-top: 50px;">
<table class="table table-inverse">
  <thead>
    <tr>
      <th>Index</th>
      <th>Name</th>
      <th>Surname</th>
      <th>Job</th>
      <th>Wage, €</th>
      <th>bla, €</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
      <td>bla</td>
      <td>blum</td>
      <td>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-edit"></span></p>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-trash"></span></p>
      </td>
    </tr>
    <tr>
      <th scope="row"></th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
      <td>bla</td>
      <td>blum</td>
      <td>
       <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-edit"></span></p>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-trash"></span></p>
      </td>
    </tr>
    <tr>
      <th scope="row"></th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
      <td>bla</td>
      <td>blum</td>
      <td>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-edit"></span></p>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-trash"></span></p>
      </td>
    </tr>
  </tbody>
</table>
</div>

</body>
</html>
</code>```

In the CSS -

```<code> .addSpacing {
  margin-left: 5%;
}
</code>```

You could code functionalities by assigning an id/class to these glyphicons. I hope this helps!

Body:
I'm new to the whole bootstrap thing so even though i tried to solve this for last 3 hours, i could'nt. I need a table to have 2 buttons in a cell that looks like a glypicon (so i can add javascript functions to them later). I managed to do this in 2 ways, but the problem is these buttons expand table row a lot. How do i solve this? maybe alternate method of making a button?

Here is how the table looks right now:

https://puu.sh/wbMUf/50a535e0f9.png

here are the lines used to achieve the result for the cell in the first row:

and for the cell in the second row:

    <button type = "button" class = "btn btn-link"></button>
    <button type = "button" class = "btn btn-link"></button>

Second option doesnt work, because the glyphs have to styled the same as the rest of the text in the table.

Body:
You could do something like this

https://jsfiddle.net/7h4qqx44/2/

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

<div class="container style="margin-top: 50px;">
<table class="table table-inverse">
  <thead>
    <tr>
      <th>Index</th>
      <th>Name</th>
      <th>Surname</th>
      <th>Job</th>
      <th>Wage, €</th>
      <th>bla, €</th>
      <th>Actions</th>
    </tr>
  </thead>
  <tbody>
    <tr>
      <td></td>
      <td>Mark</td>
      <td>Otto</td>
      <td>@mdo</td>
      <td>bla</td>
      <td>blum</td>
      <td>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-edit"></span></p>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-trash"></span></p>
      </td>
    </tr>
    <tr>
      <th scope="row"></th>
      <td>Jacob</td>
      <td>Thornton</td>
      <td>@fat</td>
      <td>bla</td>
      <td>blum</td>
      <td>
       <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-edit"></span></p>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-trash"></span></p>
      </td>
    </tr>
    <tr>
      <th scope="row"></th>
      <td>Larry</td>
      <td>the Bird</td>
      <td>@twitter</td>
      <td>bla</td>
      <td>blum</td>
      <td>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-edit"></span></p>
        <p class="btn" style="width:10%; padding-bottom:0; margin-bottom:0; border-bottom:0"><span class="glyphicon glyphicon-trash"></span></p>
      </td>
    </tr>
  </tbody>
</table>
</div>

</body>
</html>

In the CSS -

 .addSpacing {
  margin-left: 5%;
}

You could code functionalities by assigning an id/class to these glyphicons. I hope this helps!


问:
What is the difference between "keyword" and "reserved word"?
What's the difference between a keyword and a reserved word?

For example, in the proposal for concepts in C++ one can read the following statement:

This proposal introduces five new keywords: concept, concept map, where, axiom, and late check. All of these keywords will also be
  reserved words.

答:
keyword, - a word with special meaning in a particular context.
  It's semantic definition.

reserved word  is a word that cannot be used as an identifier -
  such as, variable, and function name.  It's syntactic definition.

E.g.In Java, all keywords are reserved words. Probably not the reverse.
  goto is reserved word but not used and has no function.

In older languages like FORTRAN there were keywords but no reserved words.

However, keyword and reserved word are used interchangeably.


问:
filter datatable using parent id

I have a datatable and it has 2 fields FolderId,Parent_Id .

I want to filter all children of a parent and save it into another datatable.
I'm able to achieve this using two methods and 3 different loop, isnt there a more simple and fast way to achieve this using Linq or something.

Here is my code

```<code> public DataTable ChildrenOf(string parent, DataTable dtFolders)
{
    DataTable result = new DataTable();
    try
    {
        if (dtFolders != null)
        {
            result = dtFolders.Clone();
            foreach (DataRow child in dtFolders.Rows)
            {

                if (child["FolderId"].ToString() == parent)
                {
                    result.Rows.Add(child.ItemArray);
                }
            }
            foreach (DataRow dr in dtFolders.Rows)
            {
                if (ChildrenOfParent(parent, dtFolders) != null)
                {
                    result.Rows.Add(ChildrenOfParent(parent, dtFolders).ItemArray);
                    parent = ChildrenOfParent(parent, dtFolders).ItemArray[0].ToString();
                }
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
    return result;
}

public DataRow ChildrenOfParent(string parent, DataTable dtChild)
{
    DataRow drChild;
    drChild = null;
    try
    {
        foreach (DataRow dr in dtChild.Rows)
        {
            if (dr["ParentId"].ToString() == parent)
            {
                drChild = dr;
            }
        }
    }
    catch (Exception)
    {
        throw;
    }

    return drChild;
}
</code>```

答:
You can simplify your search for children using Linq. Something like this:

```<code>public DataTable ChildrenOf(string parent, DataTable dtFolders)
{
    return dtFolders.AsEnumerable()
        .Where(row => row.Field<String>("FolderId") == parent)
        .CopyToDataTable();
}
</code>```

I used same method signature like in your example. Just call method with original table and parent ID. Method will return new, filtered table.

Title: filter datatable using parent id

Body:
I have a datatable and it has 2 fields FolderId,Parent_Id .

I want to filter all children of a parent and save it into another datatable.
I'm able to achieve this using two methods and 3 different loop, isnt there a more simple and fast way to achieve this using Linq or something.

Here is my code

 public DataTable ChildrenOf(string parent, DataTable dtFolders)
{
    DataTable result = new DataTable();
    try
    {
        if (dtFolders != null)
        {
            result = dtFolders.Clone();
            foreach (DataRow child in dtFolders.Rows)
            {

                if (child["FolderId"].ToString() == parent)
                {
                    result.Rows.Add(child.ItemArray);
                }
            }
            foreach (DataRow dr in dtFolders.Rows)
            {
                if (ChildrenOfParent(parent, dtFolders) != null)
                {
                    result.Rows.Add(ChildrenOfParent(parent, dtFolders).ItemArray);
                    parent = ChildrenOfParent(parent, dtFolders).ItemArray[0].ToString();
                }
            }
        }
    }
    catch (Exception)
    {
        throw;
    }
    return result;
}

public DataRow ChildrenOfParent(string parent, DataTable dtChild)
{
    DataRow drChild;
    drChild = null;
    try
    {
        foreach (DataRow dr in dtChild.Rows)
        {
            if (dr["ParentId"].ToString() == parent)
            {
                drChild = dr;
            }
        }
    }
    catch (Exception)
    {
        throw;
    }

    return drChild;
}

Body:
You can simplify your search for children using Linq. Something like this:

public DataTable ChildrenOf(string parent, DataTable dtFolders)
{
    return dtFolders.AsEnumerable()
        .Where(row => row.Field<String>("FolderId") == parent)
        .CopyToDataTable();
}

I used same method signature like in your example. Just call method with original table and parent ID. Method will return new, filtered table.


问:
bash assign default value

${parameter:=word}
                Assign Default Values.  If parameter is unset or null, the
  expansion of word is assigned to
  parameter.  The value of parameter is
  then  substituted.   Positional
  parameters  and  special
                parameters may not be assigned to in this way.

I thought I could use this feature to write ${LONG_VARIABLE_NAME:=hello} instead of the longer LONG_VARIABLE_NAME=${LONG_VARIABLE_NAME:-hello}, but now bash also tries to execute 'hello' and that gives a command not found. Any way to avoid that? Or will I have to stick to the latter? Can someone give an example where the assign default is actually useful?

答:
Use a colon:

```<code>: ${A:=hello}
</code>```

The colon is a null command that does nothing and ignores its arguments. It is built into bash so a new process is not created.

Title: bash assign default value

Body:
Use a colon:

: ${A:=hello}

The colon is a null command that does nothing and ignores its arguments. It is built into bash so a new process is not created.

ContentLicense: CC BY-SA 2.5


问:
Disable button in unity without changing its transparency
I have noticed that when I set the interactable property of button to false the button alpha decreases. Does anybody have knowledge on how to achieve this in Unity .

```<code> myButton.interactable = false;
</code>```

It would be immensely helpful if you could help !

Thank you !

答:
You have to change the "Disabled Color" of the Button component. Check the alpha value.

In order to change it by code :

```<code>// Unfortunately, you can't do button.colors.disabledColor.a = 1 ;
UnityEngine.UI.ColorBlock colors = button.colors ;
Color disabledColor = colors.disabledColor ;
disabledColor.a = 1 ;
colors.disabledColor = disabledColor ;
button.colors = colors ;
</code>```

Body:
I have noticed that when I set the interactable property of button to false the button alpha decreases. Does anybody have knowledge on how to achieve this in Unity .

 myButton.interactable = false;

It would be immensely helpful if you could help !

Thank you !

Body:
You have to change the "Disabled Color" of the Button component. Check the alpha value.

In order to change it by code :

// Unfortunately, you can't do button.colors.disabledColor.a = 1 ;
UnityEngine.UI.ColorBlock colors = button.colors ;
Color disabledColor = colors.disabledColor ;
disabledColor.a = 1 ;
colors.disabledColor = disabledColor ;
button.colors = colors ;


问:
Makefile that recompiles only if its dependency actually changed
Let's imagine that I have a file that is generated based not on some other file in the file system, but some external command whose output may or may not change. Can I express this concept in the makefile and have dependent targets only run if the content actually changed?

To specific, I have a file date.h which has the current date, hour and minute (but not seconds), which is generated by a rule like this:

```<code>echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h
</code>```

The default 'app' target depends on date.h and the whole Makefile looks like:

```<code>app: date.h
    echo "Building app"
    touch app

date.h: FORCE
    echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h

FORCE:
</code>```

Now the FORCE target causes date.h to be rebuild every time, which causes app to always be out of date and get rebuilt.

On the other hand, if I don't include the FORCE target, then date.h will only be rebuilt if it doesn't exist (e.g., after a clean or after initially cloning the project), but never again after that.

What I want is for date.h to be out of date only if its contents were actually changed by the echo - that is, when the minute changes, but not otherwise. Is there some way to tell make to only consider date.h changed if its actual bytes changed on disk, rather than going by the timestamp, or another way to achieve this effect?

Echoing the date to a temporary file and then conditionally updating date.h based on comparing their contents crossed my mind, but I'm not sure if it's a reasonable approach.

答:
What you suggested doing in your last paragraph is the usual way of conditionally rebuilding targets only if a particular dependency has actually changed, rather than just if that dependency's time stamp has changed. In the rule that generates the particular dependency, you generate it as a temporary file, check to see if its contents have changed and if so replace the target of the rule with the temporary file. Notably, GCC has been doing this in its makefiles as long as I can remember. It generates source code and header files with things like tables and pattern recognizers that often don't change when one of their dependencies does. Stopping targets that are dependants of these generated files from being rebuilt can make a big difference in build times.

So for your example makefile you could do something like:

```<code>date.h: FORCE
        echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h.tmp
        if test -r date.h;                                              \
        then                                                            \
                cmp date.h.tmp date.h || mv -f date.h.tmp date.h;       \
        else                                                            \
                mv date.h.tmp date.h;                                   \
        fi
</code>```

You might also want to look using at the move-if-change shell script included in the GCC source.

Body:
Let's imagine that I have a file that is generated based not on some other file in the file system, but some external command whose output may or may not change. Can I express this concept in the makefile and have dependent targets only run if the content actually changed?

To specific, I have a file date.h which has the current date, hour and minute (but not seconds), which is generated by a rule like this:

echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h

The default 'app' target depends on date.h and the whole Makefile looks like:

app: date.h
    echo "Building app"
    touch app

date.h: FORCE
    echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h

FORCE:

Now the FORCE target causes date.h to be rebuild every time, which causes app to always be out of date and get rebuilt.

On the other hand, if I don't include the FORCE target, then date.h will only be rebuilt if it doesn't exist (e.g., after a clean or after initially cloning the project), but never again after that.

What I want is for date.h to be out of date only if its contents were actually changed by the echo - that is, when the minute changes, but not otherwise. Is there some way to tell make to only consider date.h changed if its actual bytes changed on disk, rather than going by the timestamp, or another way to achieve this effect?

Echoing the date to a temporary file and then conditionally updating date.h based on comparing their contents crossed my mind, but I'm not sure if it's a reasonable approach.

Body:
What you suggested doing in your last paragraph is the usual way of conditionally rebuilding targets only if a particular dependency has actually changed, rather than just if that dependency's time stamp has changed. In the rule that generates the particular dependency, you generate it as a temporary file, check to see if its contents have changed and if so replace the target of the rule with the temporary file. Notably, GCC has been doing this in its makefiles as long as I can remember. It generates source code and header files with things like tables and pattern recognizers that often don't change when one of their dependencies does. Stopping targets that are dependants of these generated files from being rebuilt can make a big difference in build times.

So for your example makefile you could do something like:

date.h: FORCE
        echo "#define DATE" '"' $$(date '+%D-%H:%M') '"' > date.h.tmp
        if test -r date.h;                                              \
        then                                                            \
                cmp date.h.tmp date.h || mv -f date.h.tmp date.h;       \
        else                                                            \
                mv date.h.tmp date.h;                                   \
        fi

You might also want to look using at the move-if-change shell script included in the GCC source.


问:
SharePoint Online Powershell Folder creation
I need to be able to script folder creation from a csv into a SharePoint Online document library with each folder with permission inheritance disabled and for different user to each folder to be added.

The following code can create the folders and disable the inheritance but it seems to try add a group but not a user. How to make it add a user instead?

Thanks.

### Get the user credentials
$credential = Get-Credential
$username = $credential.UserName
$password = $credential.GetNetworkCredential().Password
$securePassword = ConvertTo-SecureString $password -AsPlainText -Force

### Input Parameters
$url = 'URL HERE'
$csvfilepath='C:\Scripts\data.csv'
$libname ='BUS61'

### References
# Specified the paths where the dll's are located.
Add-Type -Path 'C:\Scripts\SPOCmdlets\Microsoft.SharePoint.Client.dll'
Add-Type -Path 'C:\Scripts\SPOCmdlets\Microsoft.SharePoint.Client.Runtime.dll'

### CreateFolder with Permissions Function
function CreateFolderWithPermissions()
{

    # Connect to SharePoint Online and get ClientContext object.
    $clientContext = New-Object Microsoft.SharePoint.Client.ClientContext($url)
    $credentials = New-Object Microsoft.SharePoint.Client.SharePointOnlineCredentials($username, $securePassword)
    $clientContext.Credentials = $credentials

    Function GetRole
    {
        [CmdletBinding()]
        param
        (
            [Parameter(Mandatory = $true, Position = 1)]
            [Microsoft.SharePoint.Client.RoleType]$rType
        )

        $web = $clientContext.Web
        if ($web -ne $null)
        {
            $roleDefs = $web.RoleDefinitions
            $clientContext.Load($roleDefs)
            $clientContext.ExecuteQuery()
            $roleDef = $roleDefs | Where-Object { $_.RoleTypeKind -eq $rType }
            return $roleDef
        }
        return $null
    }

    # Get the SharePoint web
    $web = $clientContext.Web;
    $clientContext.Load($web)

    #Get the groups
    $groups = $web.SiteGroups
    $clientContext.Load($groups)
    $clientContext.ExecuteQuery()

    #Read CSV File and iterate
    $csv = Import-CSV $csvfilepath
    foreach ($row in $csv)
    {
        #Create Folder
        $folder = $web.Folders.Add($libname + "/" + $row.Folder)
        $clientContext.Load($folder)
        $clientContext.ExecuteQuery()

        #Assign Role
        $group = $groups.GetByName($row.Group)
        $clientContext.Load($group)
        $clientContext.ExecuteQuery()

        $roleType= $row.Role
        $roleTypeObject = [Microsoft.SharePoint.Client.RoleType]$roleType
        $roleObj = GetRole $roleTypeObject
        $usrRDBC = $null
        $usrRDBC = New-Object Microsoft.SharePoint.Client.RoleDefinitionBindingCollection($clientContext)
        $usrRDBC.Add($roleObj)

        # Remove inherited permissions
        $folder.ListItemAllFields.BreakRoleInheritance($false, $true)
        $clientContext.Load($folder.ListItemAllFields.RoleAssignments.Add($group, $usrRDBC))
        $folder.Update()
        $clientContext.ExecuteQuery()

        # Display the folder name and permission
        Write-Host -ForegroundColor Blue 'Folder Name: ' $folder.Name ' Group: '$row.Group ' Role: ' $roleType;

    }
}
#Execute the function
CreateFolderWithPermissions
```

答:
Let's assume that you will define user login in your CSv file. Than you have to change the line:

```<code>$group = $groups.GetByName($row.Group)
</code>```

to

```<code>$user = $web.EnsureUser($row.User)
</code>```

and replace all references to $group variable with $user

More generic approach for searching for a user (with for example display name) would be using Utility.ResolvePrincipal method:

```<code>[Microsoft.SharePoint.Client.Utilities.Utility]::ResolvePrincipal($clientContext, $web, "DisplayName", ([Microsoft.SharePoint.Client.Utilities.PrincipalType]::User), ([Microsoft.SharePoint.Client.Utilities.PrincipalSource]::All), $null, $false)
</code>```

Body:
Let's assume that you will define user login in your CSv file. Than you have to change the line:

$group = $groups.GetByName($row.Group)

to

$user = $web.EnsureUser($row.User)

and replace all references to $group variable with $user

More generic approach for searching for a user (with for example display name) would be using Utility.ResolvePrincipal method:

[Microsoft.SharePoint.Client.Utilities.Utility]::ResolvePrincipal($clientContext, $web, "DisplayName", ([Microsoft.SharePoint.Client.Utilities.PrincipalType]::User), ([Microsoft.SharePoint.Client.Utilities.PrincipalSource]::All), $null, $false)


问:
kendo chart change individual markers type on the same series
Is there a way to assign different markers types (circle, square, triangle, etc) to specific data points on the same series? (I am using scatterLine chart)

I know it can be done with the color:
Assigning specific color to each data point example

And also you can change the type for the whole series: example

But I need to have on the same line at least 2 different types (circles and triangles)

Any suggestion is welcome, thanks

答:
You could use the visual property of the series markers to draw the shape you want e.g.:

```<code>series: [{
  type: "line",
  markers: {
    visual: function (e) {
      var origin = e.rect.origin;
      var center = e.rect.center();
      var bottomRight = e.rect.bottomRight();

      if (e.value < 2){
        return e.createVisual();
      } else {
        var path = new kendo.drawing.Path({
          stroke: {color: e.options.border.color, width: 2},
          fill: { color: "white" }
        })
        .moveTo(origin.x, bottomRight.y)
        .lineTo(bottomRight.x, bottomRight.y)
        .lineTo(center.x, origin.y)
        .close();

        return path;
      }
    }
}
</code>```

DEMO

Body:
You could use the visual property of the series markers to draw the shape you want e.g.:

series: [{
  type: "line",
  markers: {
    visual: function (e) {
      var origin = e.rect.origin;
      var center = e.rect.center();
      var bottomRight = e.rect.bottomRight();

      if (e.value < 2){
        return e.createVisual();
      } else {
        var path = new kendo.drawing.Path({
          stroke: {color: e.options.border.color, width: 2},
          fill: { color: "white" }
        })
        .moveTo(origin.x, bottomRight.y)
        .lineTo(bottomRight.x, bottomRight.y)
        .lineTo(center.x, origin.y)
        .close();

        return path;
      }
    }
}

DEMO


问:
unicode to ASCII (getting junk value when i try to publish values from database)
I have models.py
    from future import unicode_literals
    # -- coding: utf-8 --
    from django.db import models
    from django.utils import timezone
    import datetime
    from datetime import datetime, timedelta
    from django.contrib.auth.models import User

```<code>class some_model(models.Model):
    info=models.CharField(max_length=200)
    message=models.TextField()
    time=models.DateTimeField(auto_now_add=True,)

    def __unicode__(self):
            return self.info
</code>```

I have forms.py:

```<code>class someForm(forms.ModelForm):

class Meta:
    model = some_model
    fields = ('info', 'message',)
</code>```

I have views.py:

```<code>def some_view(request):
    if request.method == "POST":
            form = someForm(request.POST)
            if form.is_valid():
                    post = form.save(commit=False)
                    post.save()
                    return redirect('some_all')

    else:
            form = chatForm()
    return render(request, 'some_view.html', {'form': form,})
</code>```

Now i have filled massage field with some  regional language . saving this form to mysql database , every thing is fine . I can see my message column regional language saved as it is in mysql database . After when i try to fetch the data from database like ,

```<code>for i in some_model.objects.filter(info='some thing'):
    i.message
</code>```

I get some junk value like bellow .

u'\u09b9\u0987'
u'\u09b9\u0987'

But if i print those value like :
    for i in some_model.objects.filter(info='some thing'):
        print i.message

I get the correct input . But i cat print out any thing in django to webpages . So what should i do ?

答:
see ans is simple .

```<code> for i in some_model.objects.filter(info='some thing'):
       i.message[0]
</code>```

This will print out the exact value . Hope this will help you .

Body:
I have models.py
    from future import unicode_literals
    # -- coding: utf-8 --
    from django.db import models
    from django.utils import timezone
    import datetime
    from datetime import datetime, timedelta
    from django.contrib.auth.models import User

class some_model(models.Model):
    info=models.CharField(max_length=200)
    message=models.TextField()
    time=models.DateTimeField(auto_now_add=True,)

    def __unicode__(self):
            return self.info

I have forms.py:

class someForm(forms.ModelForm):

class Meta:
    model = some_model
    fields = ('info', 'message',)

I have views.py:

def some_view(request):
    if request.method == "POST":
            form = someForm(request.POST)
            if form.is_valid():
                    post = form.save(commit=False)
                    post.save()
                    return redirect('some_all')

    else:
            form = chatForm()
    return render(request, 'some_view.html', {'form': form,})

Now i have filled massage field with some  regional language . saving this form to mysql database , every thing is fine . I can see my message column regional language saved as it is in mysql database . After when i try to fetch the data from database like ,

for i in some_model.objects.filter(info='some thing'):
    i.message

I get some junk value like bellow .

u'\u09b9\u0987'
u'\u09b9\u0987'

But if i print those value like :
    for i in some_model.objects.filter(info='some thing'):
        print i.message

I get the correct input . But i cat print out any thing in django to webpages . So what should i do ?

Body:
see ans is simple .

 for i in some_model.objects.filter(info='some thing'):
       i.message[0]

This will print out the exact value . Hope this will help you .


问:
Delete/Remove duplicates from 2D array
I'm trying to remove duplicates from a diagonal array.
If you run my code you will understand better what I'm trying to do.

I want to remove duplicates from that helper array but my duplicate part od the code works for all numbers instead of that diagonal part. Also, please don't include answers with collections.
Here is the part where i'm having trouble:

```<code> boolean dup = false;

        for (int i = 0; i < array.length; i++) {
         for (int j = 0; j <array[i].length; j++) {
             if (i+j ==array.length-1){
                 if(i == j) {
                     System.out.println("Duplicate "+array[i][j]);
                 }
                 if(array[i] ==array[j]){
                     System.out.println("Duplicate "+array[i][j]);
                     dup = true;
                     break;
                 }
                 System.out.print(array[i][j] + " ");
             }

            else System.out.print(" " + " ");
        }
        System.out.println();
        }
</code>```

And here is the whole thing:

```<code>class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter length of N array: ");

        int n = input.nextInt();
        System.out.print("Enter length of M array: ");
        int m = input.nextInt();

        intarray[][] = new int[n][m];

        Random rand = new Random();

        System.out.print("Random nums:");
        for (int i = 0; i <array.length; i++) {
            for (int j = 0; j <array[i].length; j++) {
                System.out.print("X[" +i+ "," +j +"]"+ "-->");
               array[i][j] = rand.nextInt(10);
            }
    }
        for (int i = 0; i <array.length; i++) {
            System.out.println();
        for (int j = 0; j <array[i].length; j++) {
            System.out.print(array[i][j] + " ");
        }
    }
     System.out.println();
     System.out.println("Numbers: ");

        boolean dup = false;

        for (int i = 0; i <array.length; i++) {
         for (int j = 0; j <array[i].length; j++) {
             if (i+j ==array.length-1){
                 if(i == j) {
                     System.out.println("Duplicate "+array[i][j]);
                 }
                 if(array[i] ==array[j]){
                     System.out.println("Duplicate "+array[i][j]);
                     dup = true;
                     break;
                 }
                 System.out.print(array[i][j] + " ");
             }

            else System.out.print(" " + " ");
        }
        System.out.println();
        }

    }
}
</code>```

答:
You have the right idea here to check if i == j but you check for duplicates outside of you if check. Also you're right to look for if niz[i] == niz[j]. The problem is that you're doing each of these checks separately. So you're getting all items on the diagonal with your i==j check, as well as all items that are duplicates with your niz[i] == n[j] check.

Basically, you need to combine these checks: if(i==j) and if(niz[i] == niz[j])
to check that its 1. on the diagonal and 2. is a duplicate.

Try using an if check like: if (i==j && niz[i] == niz[j])

Title: Delete/Remove duplicates from 2D array

Body:
I'm trying to remove duplicates from a diagonal array.
If you run my code you will understand better what I'm trying to do.

I want to remove duplicates from that helper array but my duplicate part od the code works for all numbers instead of that diagonal part. Also, please don't include answers with collections.
Here is the part where i'm having trouble:

 boolean dup = false;

        for (int i = 0; i < array.length; i++) {
         for (int j = 0; j <array[i].length; j++) {
             if (i+j ==array.length-1){
                 if(i == j) {
                     System.out.println("Duplicate "+array[i][j]);
                 }
                 if(array[i] ==array[j]){
                     System.out.println("Duplicate "+array[i][j]);
                     dup = true;
                     break;
                 }
                 System.out.print(array[i][j] + " ");
             }

            else System.out.print(" " + " ");
        }
        System.out.println();
        }

And here is the whole thing:

class Main {

    public static void main(String[] args) {
        Scanner input = new Scanner(System.in);
        System.out.print("Enter length of N array: ");

        int n = input.nextInt();
        System.out.print("Enter length of M array: ");
        int m = input.nextInt();

        intarray[][] = new int[n][m];

        Random rand = new Random();

        System.out.print("Random nums:");
        for (int i = 0; i <array.length; i++) {
            for (int j = 0; j <array[i].length; j++) {
                System.out.print("X[" +i+ "," +j +"]"+ "-->");
               array[i][j] = rand.nextInt(10);
            }
    }
        for (int i = 0; i <array.length; i++) {
            System.out.println();
        for (int j = 0; j <array[i].length; j++) {
            System.out.print(array[i][j] + " ");
        }
    }
     System.out.println();
     System.out.println("Numbers: ");

        boolean dup = false;

        for (int i = 0; i <array.length; i++) {
         for (int j = 0; j <array[i].length; j++) {
             if (i+j ==array.length-1){
                 if(i == j) {
                     System.out.println("Duplicate "+array[i][j]);
                 }
                 if(array[i] ==array[j]){
                     System.out.println("Duplicate "+array[i][j]);
                     dup = true;
                     break;
                 }
                 System.out.print(array[i][j] + " ");
             }

            else System.out.print(" " + " ");
        }
        System.out.println();
        }

    }
}


问:
C: Character input with scanf
I have a simple program that raises a floating point number x to the power of and in integer n. I added a while loop to repeat the process providing the appropriate input (here 'Y' as yes). However, when I type in any any character at scanf(" %c",anwser); the program fails and closes. Any idea?</p>

```<code>float x;
 char *anwser='Y';
 int n,k;
 while (anwser=='Y'){
   printf("Give floating point number x to be raised at the power of n \n ");
   scanf("%f%d",&x,&n);
   printf(" \n result : %f",power(x,n));
   printf("\nDo again?? ");
   scanf(" %c",anwser);
  }

float power(float x , int n){
     int i;
     float pow=1;
     for(i=0;i<n;i++) pow*=x;
     return pow;
}
</code>```

答:
You don't need a char* to store just a char like 'Y'.
Here is your working code, with little mods:

```<code> #include <stdio.h>

 int main(void)
 {
     double base;
     size_t exp;
     double res = 1;
     char answer;
     do {
         printf("Give floating point number x to be raised at the power of n: \n");
         scanf(" %lf%zu", &base, &exp);
         for (size_t i = 0; i < exp; i++) {
             res *= base;
         }
         printf("Result: %lf\n", res);
         printf("Do you want repeat? (y/Y or n/N)\n");
         scanf(" %c", &answer);
         res = 1;
     }while (answer == 'Y' || answer == 'y');
     return 0;
 }
</code>```

Title: C: Character input with scanf

Body:
I have a simple program that raises a floating point number x to the power of and in integer n. I added a while loop to repeat the process providing the appropriate input (here 'Y' as yes). However, when I type in any any character at scanf(" %c",anwser); the program fails and closes. Any idea?

float x;
 char *anwser='Y';
 int n,k;
 while (anwser=='Y'){
   printf("Give floating point number x to be raised at the power of n \n ");
   scanf("%f%d",&x,&n);
   printf(" \n result : %f",power(x,n));
   printf("\nDo again?? ");
   scanf(" %c",anwser);
  }

float power(float x , int n){
     int i;
     float pow=1;
     for(i=0;i<n;i++) pow*=x;
     return pow;
}

Body:
You don't need a char* to store just a char like 'Y'.
Here is your working code, with little mods:

 #include <stdio.h>

 int main(void)
 {
     double base;
     size_t exp;
     double res = 1;
     char answer;
     do {
         printf("Give floating point number x to be raised at the power of n: \n");
         scanf(" %lf%zu", &base, &exp);
         for (size_t i = 0; i < exp; i++) {
             res *= base;
         }
         printf("Result: %lf\n", res);
         printf("Do you want repeat? (y/Y or n/N)\n");
         scanf(" %c", &answer);
         res = 1;
     }while (answer == 'Y' || answer == 'y');
     return 0;
 }


问:
Callback functions in Java
Is there a way to pass a call back function in a Java method?

The behavior I'm trying to mimic is a .Net Delegate being passed to a function.

I've seen people suggesting creating a separate object but that seems overkill, however I am aware that sometimes overkill is the only way to do things.

答: When I need this kind of functionality in Java, I usually use the Observer pattern.  It does imply an extra object, but I think it's a clean way to go, and is a widely understood pattern, which helps with code readability.</p>

OwnerDisplayName: Omar Kooheji

Title: Callback functions in Java

OwnerDisplayName: MattK


问:
captcha or not?
i hate captcha, do you think there is a better solution </p>

答:
if you hate captcha then I can give youe two quick other options:

any kind of authentication(facebook connect you almost know for certain the user is trustworthy).

akismet

Title: captcha or not?


问:
Material arc Movement animation with jquery
Following the Material Design Guidelines of movement, how can I animate it using jQuery?
I have this image with position absolute and I want to move it across the window using this arc movement (or obviously the downward when needed), how can i make it?</p>

答:
I keept trying to make it and created the following function:

```<code>(function ($) {
        $.fn.materialMovement = function (endX, endY, time, params, pro, complete) {
            time = time === null || typeof time === "undefined" ? 350 : time;
            params = params === null || typeof params === "undefined" ? {opacity: 1} : params;
            var el = $(this);
            var startX = parseInt($(el).css("left")), startY = parseInt($(el).css("top"));
            var diffLeft = endX - startX, diffTop = endY - startY;
            var down = endY > startY;
            $(el).animate(params, {
                progress: function (a, p, c) {
                    var top = down ? startY + (diffTop * p) : startY + ((diffTop * p) * p);
                    var left = down ? startX + (diffLeft * p) * p : startX + diffLeft * p;
                    $(el).css({left: left, top: top});
                    if ($.isFunction(pro)) {
                        pro(a, p, c);
                    }
                },
                easing: "swing",
                duration: time,
                complete: function () {
                    if ($.isFunction(complete)) {
                        complete();
                    }
                }
            });
        };
    }(jQuery));
</code>```

But, when it deals with change of size, the animation is a lot different than the one without change of size...

Body:
I keept trying to make it and created the following function:

(function ($) {
        $.fn.materialMovement = function (endX, endY, time, params, pro, complete) {
            time = time === null || typeof time === "undefined" ? 350 : time;
            params = params === null || typeof params === "undefined" ? {opacity: 1} : params;
            var el = $(this);
            var startX = parseInt($(el).css("left")), startY = parseInt($(el).css("top"));
            var diffLeft = endX - startX, diffTop = endY - startY;
            var down = endY > startY;
            $(el).animate(params, {
                progress: function (a, p, c) {
                    var top = down ? startY + (diffTop * p) : startY + ((diffTop * p) * p);
                    var left = down ? startX + (diffLeft * p) * p : startX + diffLeft * p;
                    $(el).css({left: left, top: top});
                    if ($.isFunction(pro)) {
                        pro(a, p, c);
                    }
                },
                easing: "swing",
                duration: time,
                complete: function () {
                    if ($.isFunction(complete)) {
                        complete();
                    }
                }
            });
        };
    }(jQuery));

But, when it deals with change of size, the animation is a lot different than the one without change of size...


问:
Broadcast across network for app pairing
EDIT - On hold until I do further research on specifics for my question.

I am looking to create a service in which two different computer's on the same network will run my app. How can I broadcast across the network that computer A is running my app so that computer B can find it and then begin sharing information.

To me this sounds like sockets, however I have never worked with local networking in C#. I am not familiar with any form of discovery using C# either.

Also what kind of network performance issues could I see, when both apps are broadcasting for a partner on the network?

答:
One way you could try doing this, is to get the app to send some piece of data to the server when it connects over UDP, thereby notifying you that the app is running.

You could then store a list of clients which connected (I think this will be a List<IPEndPoint> and notify all of these endpoints once another client connects.

Hopefully this makes sense, below is a simple UDP example you can use to get started.

Note: If you open the client app from the same computer twice, this will register as 2 clients on the server, so if you need to identify unique computers you may want to do a check for this.

Create 2 Console Applications

UdpServerExample

UdpClientExample

Place the following code in the Server Program.cs.

This simply creates a UdpClient object and tells it to listen on the specified port (11000 in this case).

If any data is received, it will be converted to a string and print the string to the console before sending a response message.

```<code>var udpServer = new UdpClient(11000);

while (true)
{
    // Create endpoint and listen on port 11000
    var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
    var data = udpServer.Receive(ref remoteEP);

    // Convert the byte array to string and display the client address + message
    var stringData = Encoding.Default.GetString(data);
    Console.WriteLine($"receive data from {remoteEP} - {stringData}");

    // Send response back to the client
    var stringToSend = "Message received";
    var bytesToSend = Encoding.Default.GetBytes(stringToSend);
    udpServer.Send(bytesToSend, bytesToSend.Length, remoteEP);
}
</code>```

Now place this code in the Client Program.cs

Here we create a UdpClient, which connects to the server with the specified port and IP

Then we create a byte array from the string "Hello, World! and send it to across the network.

Any response sent back from the server is printed to the conosole

```<code>// Create udp client and connect using the server IP and specified port
var client = new UdpClient();
var ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
client.Connect(ep);

// Convert string to byte array and send
var stringToSend = "Hello, World!";
var bytesToSend = Encoding.Default.GetBytes(stringToSend);
client.Send(bytesToSend, bytesToSend.Length);

// Receive the response
var receivedData = client.Receive(ref ep);
var receivedString = Encoding.Default.GetString(receivedData);

Console.WriteLine($"receive data from {ep} - {receivedString}");

Console.Read();
</code>```

You can test it out by executing UdpServerExample.exe, and at the same time stepping through UdpClientExample in VS.

You should see this in the Server console window after client.Send(bytesToSend, bytesToSend.Length); is called in the client:

And in the client console (once the dat has been received):

Body:
One way you could try doing this, is to get the app to send some piece of data to the server when it connects over UDP, thereby notifying you that the app is running.

You could then store a list of clients which connected (I think this will be a List<IPEndPoint> and notify all of these endpoints once another client connects.

Hopefully this makes sense, below is a simple UDP example you can use to get started.

Note: If you open the client app from the same computer twice, this will register as 2 clients on the server, so if you need to identify unique computers you may want to do a check for this.

Create 2 Console Applications

UdpServerExample

UdpClientExample

Place the following code in the Server Program.cs.

This simply creates a UdpClient object and tells it to listen on the specified port (11000 in this case).

If any data is received, it will be converted to a string and print the string to the console before sending a response message.

var udpServer = new UdpClient(11000);

while (true)
{
    // Create endpoint and listen on port 11000
    var remoteEP = new IPEndPoint(IPAddress.Any, 11000);
    var data = udpServer.Receive(ref remoteEP);

    // Convert the byte array to string and display the client address + message
    var stringData = Encoding.Default.GetString(data);
    Console.WriteLine($"receive data from {remoteEP} - {stringData}");

    // Send response back to the client
    var stringToSend = "Message received";
    var bytesToSend = Encoding.Default.GetBytes(stringToSend);
    udpServer.Send(bytesToSend, bytesToSend.Length, remoteEP);
}

Now place this code in the Client Program.cs

Here we create a UdpClient, which connects to the server with the specified port and IP

Then we create a byte array from the string "Hello, World! and send it to across the network.

Any response sent back from the server is printed to the conosole

// Create udp client and connect using the server IP and specified port
var client = new UdpClient();
var ep = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 11000);
client.Connect(ep);

// Convert string to byte array and send
var stringToSend = "Hello, World!";
var bytesToSend = Encoding.Default.GetBytes(stringToSend);
client.Send(bytesToSend, bytesToSend.Length);

// Receive the response
var receivedData = client.Receive(ref ep);
var receivedString = Encoding.Default.GetString(receivedData);

Console.WriteLine($"receive data from {ep} - {receivedString}");

Console.Read();

You can test it out by executing UdpServerExample.exe, and at the same time stepping through UdpClientExample in VS.

You should see this in the Server console window after client.Send(bytesToSend, bytesToSend.Length); is called in the client:

And in the client console (once the dat has been received):


问:
Correct way to test scenarios with cucumber (rails 2.3.8)
So, I am starting to build a new application, my first big one in rails since moving from .net.

I really want to BDD the entire application so I have cucumber all set up and ready to go.

I have written more then a couple of test for the simple stuff (deleting, adding, updating) and so on but now I am stuck trying to figure out how to test this scenario.

I have these models
User, Account, Plan
each account has a plan, the plans are billable each month (on the same day the account was created).

I want to test selecting a plan, creating an account, check the billing process (even mock, without PayPal at this point).

I would appreciate help with this, just to emphasize, I am not looking for complete code, just an explanation of how (in concept) would you go about and test this.

Also, plan is upgradable and downgrade-able so I want to test this as well.

Thanks in advance for your help

答:
I like to practice outside-in development, where we begin by writing acceptance tests, then drop into unit tests to handle domain logic. Let's take creating an account as an example.

Start by writing a Cucumber story for the desired feature. For example:

```<code>Feature: Create an account
  In order to use the application
  As a user
  I want to create an account

  Scenario: Create an account from home page
    Given I am on the home page
    When I follow "Sign up"
    And I fill in "Username" with "bob"
    And I fill in "Password" with "test123"
    And I press "Create"
    Then I should see "You have successfully signed up! You may now sign in."
</code>```

When we run our Cucumber features using the cucumber features command, the first step in the scenario will fail because the home page does not yet exist. To create it, we may consider it a separate feature. Therefore, we might write another Cucumber feature like:

```<code>  Scenario: Visitor visits the home page
    When I go to the home page
    Then I should see "Welcome to the Website of Awesomeness"
</code>```

Running this feature, we will discover that there is no root route defined in the Rails app. Once we fix that issue, we'll need a controller, view, and the text in the view. So far, we have only written Cucumber tests.

Once all of these features are passing, we realize a username should be required. We can write a Cucumber step to test this case:

```<code>  Scenario: Username must be filled out
    Given I am on the home page
    When I follow "Sign up"
    And I fill in "Password" with "test123"
    And I press "Create"
    Then I should see "Username cannot be blank."
</code>```

To implement this, we must add a validation to our model that will validate the inclusion of a username. Now we will drop to unit testing because we are modifying domain logic. As a general rule, when you modify a model, you should drop into RSpec or Test::Unit and test that modification directly. For example, using RSpec we would add a spec to ensure usernames must be present (and unique, etc). Once this test passes, our scenario should also begin to pass.

This was long-winded, but it should help you start practicing BDD in a very real way. For more information, see the RSpec book (which includes a wealth of information about outside-in practices using Cucumber and RSpec): http://www.pragprog.com/titles/achbd/the-rspec-book

Body:
I like to practice outside-in development, where we begin by writing acceptance tests, then drop into unit tests to handle domain logic. Let's take creating an account as an example.

Start by writing a Cucumber story for the desired feature. For example:

Feature: Create an account
  In order to use the application
  As a user
  I want to create an account

  Scenario: Create an account from home page
    Given I am on the home page
    When I follow "Sign up"
    And I fill in "Username" with "bob"
    And I fill in "Password" with "test123"
    And I press "Create"
    Then I should see "You have successfully signed up! You may now sign in."

When we run our Cucumber features using the cucumber features command, the first step in the scenario will fail because the home page does not yet exist. To create it, we may consider it a separate feature. Therefore, we might write another Cucumber feature like:

  Scenario: Visitor visits the home page
    When I go to the home page
    Then I should see "Welcome to the Website of Awesomeness"

Running this feature, we will discover that there is no root route defined in the Rails app. Once we fix that issue, we'll need a controller, view, and the text in the view. So far, we have only written Cucumber tests.

Once all of these features are passing, we realize a username should be required. We can write a Cucumber step to test this case:

  Scenario: Username must be filled out
    Given I am on the home page
    When I follow "Sign up"
    And I fill in "Password" with "test123"
    And I press "Create"
    Then I should see "Username cannot be blank."

To implement this, we must add a validation to our model that will validate the inclusion of a username. Now we will drop to unit testing because we are modifying domain logic. As a general rule, when you modify a model, you should drop into RSpec or Test::Unit and test that modification directly. For example, using RSpec we would add a spec to ensure usernames must be present (and unique, etc). Once this test passes, our scenario should also begin to pass.

This was long-winded, but it should help you start practicing BDD in a very real way. For more information, see the RSpec book (which includes a wealth of information about outside-in practices using Cucumber and RSpec): http://www.pragprog.com/titles/achbd/the-rspec-book


问:
Google Datastore 1500 byte property limit for embedded entities
According to: https://cloud.google.com/datastore/docs/concepts/entities#embedded_entity

Setting the excludeFromIndexes: true on an embedded entity should remove both it and its properties from being indexed and should therefore allow the properties of that embedded entity to be greater than 1500 bytes.

I am trying to write an embedded entity that has some properties that are longer than 1500 bytes and I'm getting an error:

“Error: The value of property “additionalAttributes” is longer than 1500 bytes.    at /node_modules/grpc/src/node/src/client.js:434:17"

Even though I'm setting the excludeFromIndexes: true (and I can see in the cloud console that the embedded entity is correctly being added without indexing) on the embedded entity.

I see there is a known issue for this at: https://github.com/GoogleCloudPlatform/google-cloud-node/issues/1916. Though I don't see anything as far as a fix or workaround

Any suggestions on what is causing this and how to fix/workaround?

答:
The workaround would be to set excludeFromIndexes=true for at least those properties that you need to support more than 1500 bytes. The JSON for your embedded entity should look like below. Note the text property where we are explicitly setting the excludeFromIndexes.

```<code>{
  "properties": {
    "date": {
      "timestampValue": "2017-06-05T18:53:23.106Z"
    },
    "text": {
      "stringValue": "long text that exceeds 1500 bytes",
      "excludeFromIndexes": true
    }
  }
}
</code>```

Body:
The workaround would be to set excludeFromIndexes=true for at least those properties that you need to support more than 1500 bytes. The JSON for your embedded entity should look like below. Note the text property where we are explicitly setting the excludeFromIndexes.

{
  "properties": {
    "date": {
      "timestampValue": "2017-06-05T18:53:23.106Z"
    },
    "text": {
      "stringValue": "long text that exceeds 1500 bytes",
      "excludeFromIndexes": true
    }
  }
}


问:
How to put a pixel on the screen?
I'm looking for information how to insert a pixel into the screen in my own operating system.
I care about the resolution of 1920x1080, 16K colors and to do it without bios interruptions.
Ideally, the resolution and number of colors will depend on my system

I wrote bootloader and procedure to draw pixel on screen but its only 320x200 resolution and have 256 colors;/
when i try use text modes, its run on VM, but when i start it on real device i have only black screen so i dont want to use bios interruptions (it depend on bios version)

答:
When still in Real Mode, scan all available VESA video modes.

Pick the mode of interest

Select it and switch to it using interrupt

Save all required data - framebuffer, width, height, bits per pixel, pitch etc. and enter real mode

Write pixel at an exact memory address:

Pixel offset: framebuffer address + pixelPosX * BitsPerPixel + PixelPosY * ScrWidth * BitsPerPixel

when you have calculated this, just use:

mov [address], 0x00ff00ff ; [00][red][green][blue]

my example will set the pixel to the color pink (max red and blue)

By the way, this might help: http://forum.osdev.org/viewtopic.php?f=2&t=30186

And, you have to do it using interrupts. If it is not running on real PC you are missing something in your bootloader. Try to run your OS with Bochs, if it runs on Bochs it will probably run on a Real PC. Qemu or VirtualBox might make things that should not be working do work

You can post your bootloader code so maybe we can figure out whats wrong with your interrupts

Title: How to put a pixel on the screen?


问:
Powershell advance through an array in a ForEach loop (or nested Foreach)
Folks,

I found a few answers, but they seem to be for manual arrays, or when you know the definite number.  I'll have an array that I dont know how many will be in there.  Was wondering if I could get help.

Basically - I want it to go thru each server, get the OCX and DLL name, version, and date, and put it in a spreadsheet.

It seems to work fine...only once.  It doesnt go on to the next file in my array.

Im so close, can someone help me tell it (OK, dont advance to the next server until you are done getting ALL the files)

Here's my code so far.  Works great - but only for one file per server.

Many thanks in advance.

```<code>$Servers = Get-Content C:\temp\Servers.txt

$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.WorkBooks.Add()
$sheet=$workbook.worksheets.item(1)
$class = "win32_Share"

$sheet.Cells.item(1,1)=("Server")
$sheet.Cells.item(1,2)=("File Name")
$sheet.Cells.Item(1,3)=("File Version")
$sheet.Cells.Item(1,4)=("Date")
$sheet.Range("A1:D1").interior.colorindex = 43
$x=2

$i = 0

foreach ($Server in $Servers) {

    $infos = Invoke-Command -computername $Server {Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx | Select-Object name,@{label="FileVersion";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}}}

    $info = $infos[$i]

$sheet.Cells.item($x, 1)=($Server)
$sheet.Cells.item($x, 2)=($info.name)
$sheet.Cells.item($x, 3)=($info.FileVersion)
$sheet.Cells.item($x, 4)=($info.Date)
$x++
$i++
}

#Autofit columns when completed
$range = $sheet.usedRange
$range.EntireColumn.Autofit()
</code>```

It never seems to advance thru the $info[$i] array.

答:
Just nest another foreach:

```<code>$x = 2
foreach ($Server in $Servers) {
    $infos = Invoke-Command -computername $Server { Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx | Select-Object  name,@{label="FileVersion";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}}}

    foreach ($info in $infos) {
        $sheet.Cells.item($x, 1)=($Server)
        $sheet.Cells.item($x, 2)=($info.name)
        $sheet.Cells.item($x, 3)=($info.FileVersion)
        $sheet.Cells.item($x, 4)=($info.Date)
        $x++
    }
}
</code>```

I also recommend renaming $x to something more descriptive, like $Row.

Body:
Folks,

I found a few answers, but they seem to be for manual arrays, or when you know the definite number.  I'll have an array that I dont know how many will be in there.  Was wondering if I could get help.

Basically - I want it to go thru each server, get the OCX and DLL name, version, and date, and put it in a spreadsheet.

It seems to work fine...only once.  It doesnt go on to the next file in my array.

Im so close, can someone help me tell it (OK, dont advance to the next server until you are done getting ALL the files)

Here's my code so far.  Works great - but only for one file per server.

Many thanks in advance.

$Servers = Get-Content C:\temp\Servers.txt

$objExcel=New-Object -ComObject Excel.Application
$objExcel.Visible=-1
$WorkBook=$objExcel.WorkBooks.Add()
$sheet=$workbook.worksheets.item(1)
$class = "win32_Share"

$sheet.Cells.item(1,1)=("Server")
$sheet.Cells.item(1,2)=("File Name")
$sheet.Cells.Item(1,3)=("File Version")
$sheet.Cells.Item(1,4)=("Date")
$sheet.Range("A1:D1").interior.colorindex = 43
$x=2

$i = 0

foreach ($Server in $Servers) {

    $infos = Invoke-Command -computername $Server {Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx | Select-Object name,@{label="FileVersion";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}}}

    $info = $infos[$i]

$sheet.Cells.item($x, 1)=($Server)
$sheet.Cells.item($x, 2)=($info.name)
$sheet.Cells.item($x, 3)=($info.FileVersion)
$sheet.Cells.item($x, 4)=($info.Date)
$x++
$i++
}

#Autofit columns when completed
$range = $sheet.usedRange
$range.EntireColumn.Autofit()

It never seems to advance thru the $info[$i] array.

Body:
Just nest another foreach:

$x = 2
foreach ($Server in $Servers) {
    $infos = Invoke-Command -computername $Server { Get-ChildItem "V:\Service\*" -File -Include *.dll, *.ocx | Select-Object  name,@{label="FileVersion";expression={$_.versioninfo.fileversion}},@{label="Date";expression={$_.LastWriteTime}}}

    foreach ($info in $infos) {
        $sheet.Cells.item($x, 1)=($Server)
        $sheet.Cells.item($x, 2)=($info.name)
        $sheet.Cells.item($x, 3)=($info.FileVersion)
        $sheet.Cells.item($x, 4)=($info.Date)
        $x++
    }
}

I also recommend renaming $x to something more descriptive, like $Row.


问:
How should I declare a Stateless Functional Component with Typescript in React?
I've seen two ways of declaring a SFC in React with Typescript, which are these two:

```<code>import * as React from 'react'

interface Props {
  message: string
}

const Component = (props: Props) => {
  const { message } = props
  return (
    <div>{message}</div>
  )
}

export default Component
</code>```

and:

```<code>import * as React from 'react'

interface Props {
  message: string
}

const Component: React.StatelessComponent<Props> = props => {
  const { message } = props
  return (
    <div>{message}</div>
  )
}

export default Component
</code>```

From this question I see that with the second way you can omit children from your interface if you are using it in your component.

Are there any more differences? Which one is the preferred one and why?

答:
The definition for React.StatelessComponent<T> is:

```<code>interface StatelessComponent<P> {
    (props: P & { children?: ReactNode }, context?: any): ReactElement<any>;
    propTypes?: ValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}
</code>```

In your for snippet Component is inferred by the compiler to be:

```<code>(props: Props): ReactElement<any>
</code>```

(or something similar).

If you write the first one like this:

```<code>const Component = (props: Props & { children?: ReactNode }) => {
    ...
}
</code>```

You are pretty much getting the same thing (as long as you don't use the properties of Component)

Body:
I've seen two ways of declaring a SFC in React with Typescript, which are these two:

import * as React from 'react'

interface Props {
  message: string
}

const Component = (props: Props) => {
  const { message } = props
  return (

{message}

  )
}

export default Component

and:

import * as React from 'react'

interface Props {
  message: string
}

const Component: React.StatelessComponent<Props> = props => {
  const { message } = props
  return (

{message}

  )
}

export default Component

From this question I see that with the second way you can omit children from your interface if you are using it in your component.

Are there any more differences? Which one is the preferred one and why?

Body:
The definition for React.StatelessComponent<T> is:

interface StatelessComponent<P> {
    (props: P & { children?: ReactNode }, context?: any): ReactElement<any>;
    propTypes?: ValidationMap<P>;
    contextTypes?: ValidationMap<any>;
    defaultProps?: Partial<P>;
    displayName?: string;
}

In your for snippet Component is inferred by the compiler to be:

(props: Props): ReactElement<any>

(or something similar).

If you write the first one like this:

const Component = (props: Props & { children?: ReactNode }) => {
    ...
}

You are pretty much getting the same thing (as long as you don't use the properties of Component)


问:
From WPF Control to Silverlight Control
we have biuld a complex custom control for WPF.
Now we are going to port our control to Silverlight.

Me and my collaborator, never work with silverlight! :)

Is there some best practice to follow to make a porting activity from WPF to Silverlight?

答:
There are some differences to be aware of, for example there are no Routed Commands in Silverlight. Maybe you want to have a look at those two links:

Contrasting Silverlight and WPF

Guidance on Differences Between WPF and Silverlight

Title: From WPF Control to Silverlight Control


问:
Select specific columns in NumPy array using colon notation
I have a 40000 by 60 Numpy array, and I want to sth like this:

```<code>mat[:,[0:13,19:23,23:31,39:59]]
</code>```

Obviously, it does not work. Is there a smarter way to do this than concatenation?

Body:
I have a 40000 by 60 Numpy array, and I want to sth like this:

mat[:,[0:13,19:23,23:31,39:59]]

Obviously, it does not work. Is there a smarter way to do this than concatenation?

Body:
Use np.r_ -

mat[:,np.r_[0:13,19:23,23:31,39:59]]

Sample run -

In [48]: mat = np.random.rand(100,1000)

In [50]: mat[:,np.r_[0:13,19:23,23:31,39:59]].shape
Out[50]: (100, 45)

In [51]: 13+4+8+20
Out[51]: 45


问:
elastic not returning data if part of string is being used to search
I am having issue while getting data back from elastic
Here is mapping

```<code>"device": {
   "properties": {
      "deviceName": {
         "type": "string",
         "analyzer": "snowball"
       }
    }
}
</code>```

When I am using the full device name(i.e ZACe0933d850f) in the query I am getting the result back.

Working Query

```<code>{"query": {"bool":{"must":[{"query_string":{"query":"ZACe0933d850f","fields":["*name","*Name","*text","*Text"]}}]}}}
</code>```

but when I am trying to search using ZAC only I am not getting any results.

Not Working Query

```<code>{"query": {"bool":{"must":[{"query_string":{"query":"ZAC","fields":["*name","*Name","*text","*Text"]}}]}}}
</code>```

Is it something related to snowball Analyzer? I am pretty new to elastic and need some quick help here.

Thanks a lot in advance...

答: Your problem is that you don't know how exactly elastic searches in text. you'r text will be tokenized and there is a ZACe0933d850f token in your input but not a ZAC. Probably you should use an ngram token filter in your analyzer.

Body:
I am having issue while getting data back from elastic
Here is mapping

"device": {
   "properties": {
      "deviceName": {
         "type": "string",
         "analyzer": "snowball"
       }
    }
}

When I am using the full device name(i.e ZACe0933d850f) in the query I am getting the result back.

Working Query

{"query": {"bool":{"must":[{"query_string":{"query":"ZACe0933d850f","fields":["*name","*Name","*text","*Text"]}}]}}}

but when I am trying to search using ZAC only I am not getting any results.

Not Working Query

{"query": {"bool":{"must":[{"query_string":{"query":"ZAC","fields":["*name","*Name","*text","*Text"]}}]}}}

Is it something related to snowball Analyzer? I am pretty new to elastic and need some quick help here.

Thanks a lot in advance...