问:
Is function prototype compulsory in C++?
By this I mean that even though I define the function before the function call,is it required to have a function prototype?
I tried a program with definition b4 call,it worked.but in C++ by Herbert schildt it says C++ requires full function prototyping.so am confused.
So,does C++ really require full function prototyping?</p>

答:
Considering the question, I'll assume that you are at the beginner level. First of all, You should start learning from a better book.

Look at the compiler as an intelligent person who reads your program and converts it into machine language.
When the compiler starts compiling your program it may encounter a function call such as: foo();
Now, it has to make the control jump to the function's address for the desired instructions to be executed during run but the compiler doesn't know what or where the function is!
Providing the compiler with a reference helps it to compile your code.

Prototypes are such references, you could also define a function before any function calls and it would still work.

Other than technical reasons, prototypes makes code much more clean in case of big projects.

Otherwise, you would just be scrolling through Functions definitions having no idea what the functions are doing. Remember, you are like a human compiler too!

A usual mistake I've noticed: It is usual that people revolt this idea and define their functions on top. Although, when calling another function from a function, problems can arise.

```<code>int function_1()
{
        return function_2();
}

int function_2()
{
        return function_1();
}
</code>```

Here, there are no arrangements of functions definitions which will work. Prototyping is much better.

Assumptions: There are obviously some more statements to break the endless loop and return values, this is just to illustrate the concept.

Body:
Considering the question, I'll assume that you are at the beginner level. First of all, You should start learning from a better book.

Look at the compiler as an intelligent person who reads your program and converts it into machine language.
When the compiler starts compiling your program it may encounter a function call such as: foo();
Now, it has to make the control jump to the function's address for the desired instructions to be executed during run but the compiler doesn't know what or where the function is!
Providing the compiler with a reference helps it to compile your code.

Prototypes are such references, you could also define a function before any function calls and it would still work.

Other than technical reasons, prototypes makes code much more clean in case of big projects.

Otherwise, you would just be scrolling through Functions definitions having no idea what the functions are doing. Remember, you are like a human compiler too!

A usual mistake I've noticed: It is usual that people revolt this idea and define their functions on top. Although, when calling another function from a function, problems can arise.

int function_1()
{
        return function_2();
}

int function_2()
{
        return function_1();
}

Here, there are no arrangements of functions definitions which will work. Prototyping is much better.

Assumptions: There are obviously some more statements to break the endless loop and return values, this is just to illustrate the concept.


来源: stackexchange

问:
Convert categorical strings to integers in Matlab
I have a vector  that has labels with a char i would like to conver these to integers.
Example:

```<code>Y | Y^
--+--
A | 1
A | 1
B | 2
C | 3
B | 2
B | 2
A | 1
C | 2
</code>```

I have Y and i would like to convert to Y^. Any function or suggestions? Thanks!

答:
The bellow code snippet should produce the desired results:

Y^ = grp2idx(Y)

ContentLicense: CC BY-SA 3.0

Body:
I have a vector  that has labels with a char i would like to conver these to integers.
Example:

Y | Y^
--+--
A | 1
A | 1
B | 2
C | 3
B | 2
B | 2
A | 1
C | 2

I have Y and i would like to convert to Y^. Any function or suggestions? Thanks!


问:
Expand DIV to its UL content
I have a div container and a ul within it. I want that the div be expanded to its content ul. I've tried everything I found (overflow:hidden, clearfix etc ...), but nothing worked.

UPDATE: originally this is a slider with a crossfade effect, where the images are overlapped with each other. So, the solution which causes that the images will be in a column (same left, but different top values) doesn't good for me.
Please, show me the pure HTML/CSS solution, without JS.

.slider {
  position: relative;
  padding: 0;
  margin: 0 auto;
  border: 1px solid black;
}

.slider img {
  max-width: 100%;
  display: block;
}

ul {
  list-style: none;
  margin: 0;
  padding: 0;
}

li {
  position: absolute;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="slider" style="max-width: 880px;">
  <ul>
    <li><img src="https://placeimg.com/400/200/any" style="width:100%"></li>
    <li><img src="https://placeimg.com/400/200/tech" style="width:100%"></li>
    <li><img src="https://placeimg.com/400/200/animals" style="width:100%"></li>
  </ul>
</div></code>```

答:
Remove following line of code from your CSS:

```<code>li {
    position: absolute;
}
</code>```

If you want content (images) to appear in line, use the following code:

```<code>li {
    display:inline-block;
}
</code>```

Title: Expand DIV to its UL content

Body:
Remove following line of code from your CSS:

li {
    position: absolute;
}

If you want content (images) to appear in line, use the following code:

li {
    display:inline-block;
}


问:
Unity Leap Motion Detecting Finger collision with other fingers/palm
I am new to using Unity and Leap motion.

I have copied over the HandModels and LeapHandController from the Unity Asset Pack Desktop demo.

I am trying to activate a function to instantiate an object when the thumbs bone 3 collides with any other part of the hand and i did this by creating a simple script with an OnCollisionEnter function and attaching it to the Bone3 of Thumb but it doesn't seem to activate when the thumb collides with any other part of the hand/finger that it is a child of. If i add a cube to the scene and give it a rigidbody it will successfully trigger the onCollisionEnter of the thumb (shown via a print statement), but it wont trigger oncollisionEnter with any of its siblings in the hand model.

I am unsure how the standard method for detecting finger collisions with other objects using Leap Motion and Unity is, but it doesn't seem to follow the standard Unity Collision system. Is there another way i should be detecting it? It would be helpful if i could detect collisions of a hands child bones, but right now it seems i have to signal to the hand manually that a child bone has collided.

答:
If you've copied over HandModels from a Desktop demo, the physical hand you're working with is probably a RigidRoundHand -- you can confirm this by checking what objects are underneath your HandModels object.

If it is indeed the RigidRoundHand, or otherwise using the RigidHand script to generate the colliders of the hand, the issue you're observing comes from the fact that a hand is all one rigidbody, so the reason you aren't seeing OnCollisionEnter is because the rigidbody doesn't receive OnCollisionEnter when it "collides" with itself.

To accomplish what you're trying to do, instead of relying on the default colliders of the hand, you should place specific Rigidbody + Collider objects (such as the default Unity Cube) on the specific locations of the hand you'd like to detect collision against. I would recommend using the Attachment Hands made available in a recent release to do this: It will make it easy for you to place individual Rigidbodies on specific joints in the hand, such as the tip of the thumb, and the other locations you're trying to collide against.

Make sure you're using the latest version of the Leap Motion Unity SDK, then check out the example scene in LeapMotion/Core/Examples/Attachment Hands/ in your Assets folder. Make sure you have a Kinematic Rigidbody Collider (a SphereCollider is a good choice) under the Attachment Hand's thumb, and add some script like:

public class ThumbCollisionDetector : MonoBehaviour {
  void OnCollisionEnter(Collision c) {
    if (c.gameObject.GetComponent<MiddleFingerIdentifier>() != null) {
      Debug.Log("The thumb collided with the middle finger identifier!");
    }
  }
}
```

<p>In the above example, we're looking for a "MiddleFingertipIdentifier" script in the collision, so we need to make sure there's an object with a Kinematic Rigidbody and a Collider <em>attached</em> (via Attachment Hands) to the tip bone of the middle finger -- the identifier script doesn't even have to contain anything, it just has to be there:
</p>

```public class MiddleFingertipIdentifier : MonoBehaviour { }
```

That logic should get you started detecting internal hand intersections.

Body:
If you've copied over HandModels from a Desktop demo, the physical hand you're working with is probably a RigidRoundHand -- you can confirm this by checking what objects are underneath your HandModels object.

If it is indeed the RigidRoundHand, or otherwise using the RigidHand script to generate the colliders of the hand, the issue you're observing comes from the fact that a hand is all one rigidbody, so the reason you aren't seeing OnCollisionEnter is because the rigidbody doesn't receive OnCollisionEnter when it "collides" with itself.

To accomplish what you're trying to do, instead of relying on the default colliders of the hand, you should place specific Rigidbody + Collider objects (such as the default Unity Cube) on the specific locations of the hand you'd like to detect collision against. I would recommend using the Attachment Hands made available in a recent release to do this: It will make it easy for you to place individual Rigidbodies on specific joints in the hand, such as the tip of the thumb, and the other locations you're trying to collide against.

Make sure you're using the latest version of the Leap Motion Unity SDK, then check out the example scene in LeapMotion/Core/Examples/Attachment Hands/ in your Assets folder. Make sure you have a Kinematic Rigidbody Collider (a SphereCollider is a good choice) under the Attachment Hand's thumb, and add some script like:

public class ThumbCollisionDetector : MonoBehaviour {
  void OnCollisionEnter(Collision c) {
    if (c.gameObject.GetComponent<MiddleFingerIdentifier>() != null) {
      Debug.Log("The thumb collided with the middle finger identifier!");
    }
  }
}

In the above example, we're looking for a "MiddleFingertipIdentifier" script in the collision, so we need to make sure there's an object with a Kinematic Rigidbody and a Collider attached (via Attachment Hands) to the tip bone of the middle finger -- the identifier script doesn't even have to contain anything, it just has to be there:

public class MiddleFingertipIdentifier : MonoBehaviour { }

That logic should get you started detecting internal hand intersections.


问:
How to find which app owns a modal window?
I have a modal window popping up randomly with the message:

Insecure update error!

For security reasons, you need to code sign your application or sign
  your updates with a DSA key. See Sparkle's documentation for more
  information.

I know Sparkle is an autoupdate framework used by Mac applications so how can I find which application is failing on the update process?

答:
You can scan which of your installed apps are using the Sparkle framework by doing this in the Terminal:

```<code>find /Applications -path '*Autoupdate.app/Contents/Info.plist' -exec echo {} \; -exec grep -A1 CFBundleShortVersionString '{}' \; | grep -v CFBundleShortVersionString
</code>```

and then update the ones that are using old Sparkle versions (and therefore are affected by this issue) - or uninstall them if their authors haven't made the necessary updates yet.

Body:
You can scan which of your installed apps are using the Sparkle framework by doing this in the Terminal:

find /Applications -path '*Autoupdate.app/Contents/Info.plist' -exec echo {} \; -exec grep -A1 CFBundleShortVersionString '{}' \; | grep -v CFBundleShortVersionString

and then update the ones that are using old Sparkle versions (and therefore are affected by this issue) - or uninstall them if their authors haven't made the necessary updates yet.


问:
Rewrite URL if specific parameter exists
I have a url like this:  website.co.uk/search.php?a=category&b=test&c=test

I want to rewrite search.php to /search/ and the variable 'a' only if it exists.

So that the url would redirect to: website.co.uk/search/category/?b=test&c=test

If the url was:  website.co.uk/search.php?b=test&c=test

Then this should redirect to website.co.uk/search/?b=test&c=test

Currently I am using:

```<code>RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^search/(.*?)/?$ search.php?a=$1 [L,QSA]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /search\.php\?a=([^\&\ ]+)
RewriteRule ^/?search\.php$ /search/%1? [L,R=301]
</code>```

If I enter the url website.co.uk/search.php?a=category&b=test&c=test

It redirects to website.co.uk/search/category

How do I add the remaining parameters to the end of this URL?

So that it looks like website.co.uk/search/category/?b=test&c=test

答:
You can use these rules in your site root .htaccess:</p>

```<code>Options -MultiViews
RewriteEngine on

RewriteCond %{THE_REQUEST} /search\.php\?a=([^&\s]*)\sHTTP [NC]
RewriteRule ^ /search/%1/? [L,NE,R=301]

RewriteCond %{THE_REQUEST} /search\.php(?:\?a=([^&\s]*)&(\S+))?\sHTTP [NC]
RewriteRule ^ /search/%1/?%2 [L,NE,R=301]

RewriteCond %{THE_REQUEST} /search\.php(?:\?(\S+))?\sHTTP [NC]
RewriteRule ^ /search/?%1 [L,NE,R=301]

RewriteRule ^search/?$ search.php [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^search/([\w-]+)/?$ search.php?a=$1 [L,NC,QSA]
</code>```

Body:
I have a url like this:  website.co.uk/search.php?a=category&b=test&c=test

I want to rewrite search.php to /search/ and the variable 'a' only if it exists.

So that the url would redirect to: website.co.uk/search/category/?b=test&c=test

If the url was:  website.co.uk/search.php?b=test&c=test

Then this should redirect to website.co.uk/search/?b=test&c=test

Currently I am using:

RewriteEngine on
RewriteBase /

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^search/(.*?)/?$ search.php?a=$1 [L,QSA]

RewriteCond %{THE_REQUEST} ^[A-Z]{3,9}\ /search\.php\?a=([^\&\ ]+)
RewriteRule ^/?search\.php$ /search/%1? [L,R=301]

If I enter the url website.co.uk/search.php?a=category&b=test&c=test

It redirects to website.co.uk/search/category

How do I add the remaining parameters to the end of this URL?

So that it looks like website.co.uk/search/category/?b=test&c=test

Body:
You can use these rules in your site root .htaccess:

Options -MultiViews
RewriteEngine on

RewriteCond %{THE_REQUEST} /search\.php\?a=([^&\s]*)\sHTTP [NC]
RewriteRule ^ /search/%1/? [L,NE,R=301]

RewriteCond %{THE_REQUEST} /search\.php(?:\?a=([^&\s]*)&(\S+))?\sHTTP [NC]
RewriteRule ^ /search/%1/?%2 [L,NE,R=301]

RewriteCond %{THE_REQUEST} /search\.php(?:\?(\S+))?\sHTTP [NC]
RewriteRule ^ /search/?%1 [L,NE,R=301]

RewriteRule ^search/?$ search.php [L,NC]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^search/([\w-]+)/?$ search.php?a=$1 [L,NC,QSA]


问:
Laravel Eloquent returns empty model even though ID is correct
so I have an Axios get request to this route:

```<code>/threads/test/{fooId}/get
</code>```

which is handled by this method:

```<code>public function apiThreadsByTag(Foo $foo)
{
    dd($foo);
}
</code>```

Foo is a model, and the {id} is indeed correct. But still, I get an instance of the model without any attributes:

```<code>Foo {#323
    #guarded: []
    #connection: null
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #perPage: 15
    +exists: false
    +wasRecentlyCreated: false
    #attributes: []
    #original: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #events: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}
</code>```

However, it does find it in the database if I change the method to:

```<code>public function apiThreadsByTag($fooId)
{
    dd(Foo::find($fooId));
}
</code>```

So, what could be wrong here? I'm very thankful for any hints!

答: I did everything correct. Well, except for the fact that I set getRouteKeyName() for the Foo model to another value and not the ID. So I had to give it this set value instead of the ID. Thank you!</p>

Body:
so I have an Axios get request to this route:

/threads/test/{fooId}/get

which is handled by this method:

public function apiThreadsByTag(Foo $foo)
{
    dd($foo);
}

Foo is a model, and the {id} is indeed correct. But still, I get an instance of the model without any attributes:

Foo {#323
    #guarded: []
    #connection: null
    #table: null
    #primaryKey: "id"
    #keyType: "int"
    +incrementing: true
    #with: []
    #perPage: 15
    +exists: false
    +wasRecentlyCreated: false
    #attributes: []
    #original: []
    #casts: []
    #dates: []
    #dateFormat: null
    #appends: []
    #events: []
    #observables: []
    #relations: []
    #touches: []
    +timestamps: true
  #hidden: []
  #visible: []
  #fillable: []
}

However, it does find it in the database if I change the method to:

public function apiThreadsByTag($fooId)
{
    dd(Foo::find($fooId));
}

So, what could be wrong here? I'm very thankful for any hints!


问:
How to display a specific user's commits in svn log?
How to display a specific user's commits in svn? I didn't find any switches for that for svn log.</p>

答:
```<code>svn log | grep user
</code>```

works for the most part.

Or to be more accurate:

```<code>svn log | egrep 'r[0-9]+ \| user \|'
</code>```

ContentLicense: CC BY-SA 2.5

Body:
svn log | grep user

works for the most part.

Or to be more accurate:

svn log | egrep 'r[0-9]+ \| user \|'


问:
creating tcl list of first 2 column of matrix
I have matrix of 10 rows and 10 column. I want to crate tcl list where each element of list will be 2 numbers..1 from each row.
    e.g if My matrix is

```<code>$a $b $c $d $e
$f $g $h $i $j
$k $l $m $n $o
$p $q $r $s $t
</code>```

I want to have list that contain elements $a $b, $f $g, $k $l, $p $q.
Can someone tell me how to do this ?

答:
Assuming your matrix is a list of lists, you can use the lmap command:

```<code>$ tclsh
% set matrix {
{a b c d e}
{f g h i j}
{k l m n o}
{p q r s t}
}

{a b c d e}
{f g h i j}
{k l m n o}
{p q r s t}

% lmap sublist $matrix {lrange $sublist 0 1}
{a b} {f g} {k l} {p q}
</code>```

Body:
I have matrix of 10 rows and 10 column. I want to crate tcl list where each element of list will be 2 numbers..1 from each row.
    e.g if My matrix is

$a $b $c $d $e
$f $g $h $i $j
$k $l $m $n $o
$p $q $r $s $t

I want to have list that contain elements $a $b, $f $g, $k $l, $p $q.
Can someone tell me how to do this ?

Body:
Assuming your matrix is a list of lists, you can use the lmap command:

$ tclsh
% set matrix {
{a b c d e}
{f g h i j}
{k l m n o}
{p q r s t}
}

{a b c d e}
{f g h i j}
{k l m n o}
{p q r s t}

% lmap sublist $matrix {lrange $sublist 0 1}
{a b} {f g} {k l} {p q}


问:
Why is this UrlFetch function not working properly?
This is the function I'm trying to run through the JavaScript Tool on my Google Spreadsheet chart, the function is currently working on 4 different websites, where in this example:

$id is the imported value from my spreadsheet cell (belacoin)

```<code>function CoinmarketcapPrice($id) {
  var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v1/ticker/" + $id);
  var html = JSON.parse(response.getContentText());
  try
  {
    return parseFloat(html["price_btc"]);
  }
  catch(err)
  {
    return null;
  }
}
</code>```

this is what that UrlFetch returns:

```<code>[
    {
        "id": "belacoin",
        "name": "BelaCoin",
        "symbol": "BELA",
        "rank": "176",
        "price_usd": "0.212823",
        "price_btc": "0.00008400",
        "24h_volume_usd": "534995.0",
        "market_cap_usd": "7694903.0",
        "available_supply": "36156350.0",
        "total_supply": "36156350.0",
        "percent_change_1h": "0.63",
        "percent_change_24h": "1.88",
        "percent_change_7d": "-17.03",
        "last_updated": "1499549044"
    }
]
</code>```

答:
```<code>return html[0].price_btc;
</code>```

made it work, thank you all!

Body:
This is the function I'm trying to run through the JavaScript Tool on my Google Spreadsheet chart, the function is currently working on 4 different websites, where in this example:

$id is the imported value from my spreadsheet cell (belacoin)

function CoinmarketcapPrice($id) {
  var response = UrlFetchApp.fetch("https://api.coinmarketcap.com/v1/ticker/" + $id);
  var html = JSON.parse(response.getContentText());
  try
  {
    return parseFloat(html["price_btc"]);
  }
  catch(err)
  {
    return null;
  }
}

this is what that UrlFetch returns:

[
    {
        "id": "belacoin",
        "name": "BelaCoin",
        "symbol": "BELA",
        "rank": "176",
        "price_usd": "0.212823",
        "price_btc": "0.00008400",
        "24h_volume_usd": "534995.0",
        "market_cap_usd": "7694903.0",
        "available_supply": "36156350.0",
        "total_supply": "36156350.0",
        "percent_change_1h": "0.63",
        "percent_change_24h": "1.88",
        "percent_change_7d": "-17.03",
        "last_updated": "1499549044"
    }
]

Body:
return html[0].price_btc;

made it work, thank you all!


问:
Redirect in a .NET API action filter
I'd like to be able to read a Request header in an ActionFilterAttribute, and direct the user. I'd also like to maintain the existing Request, or pass the controller and URL params to the new Request. I know this is easy in MVC, but haven't done it in a web API.</p>

答:
Actually it is very easy. You just create HttpResponseMessage object.

```<code>public class RedirectAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
            response.Headers.Location = new Uri("https://www.stackoverflow.com");
            actionContext.Response = response;
        }
    }
</code>```

Title: Redirect in a .NET API action filter

Body:
Actually it is very easy. You just create HttpResponseMessage object.

public class RedirectAttribute : ActionFilterAttribute
    {
        public override void OnActionExecuting(HttpActionContext actionContext)
        {
            var response = actionContext.Request.CreateResponse(HttpStatusCode.Redirect);
            response.Headers.Location = new Uri("https://www.stackoverflow.com");
            actionContext.Response = response;
        }
    }


问:
Qt for Symbian - Detecting touch/non-touch devices
I'm porting a game for Symbian which supports both a touch & non-touch UI.

I need to be able to tell if the device has a touch screen on start-up so I can enable the appropriate mode.

After googling for hours and going though the Qt Docs I found QSysInfo but this merely provides the version of the Symbian device.

Is there a way to get the actual capabilities of the device?
There must be a way to tell if the device has a touch screen...!

I'm using the latest QtCreator with the NokiaSDK.

Thank you in advance,
Nikos.

答:
I found the answer:</p>

```<code>QSystemDeviceInfo cSystemInfo;

bool HasTouchScreen()
{
    DWORD dwFlags = cSystemInfo.inputMethodType();

    if ((dwFlags & (QSystemDeviceInfo::SingleTouch|QSystemDeviceInfo::MultiTouch)) != 0)
        return true;

    return false;
}
</code>```

Body:
I found the answer:

QSystemDeviceInfo cSystemInfo;

bool HasTouchScreen()
{
    DWORD dwFlags = cSystemInfo.inputMethodType();

    if ((dwFlags & (QSystemDeviceInfo::SingleTouch|QSystemDeviceInfo::MultiTouch)) != 0)
        return true;

    return false;
}


问:
XML Schema: Elements in any order and occurring 0-1 times or 0-* times
I am working on an XML Schema (message.xsd) describing the structure of a message.

Here are the expected children of the <message> element (the root):

<from>: Contains the address of the sender. Occurs 0 or 1 times.

<to>: Contains the address of the recipient. Occurs 0 or more times.

<cc>: Contains the address of the recipient in copy. Occurs 0 or more times.

<subject>: Contains the subject of the message. Occurs 0 or 1 times.

: Contains the body of the message. Occurs 0 or 1 times.

The order of elements does not matter, it means that they can be in any order.

Here is a first simple XML example (message-1.xml) that has to be valid:

```<code>$ xmllint --schema message.xsd message-1.xml
<?xml version="1.0"?>
<message xmlns="http://yugiohjcj.1s.fr/message">
    <from>me@domain.com</from>
    <to>you@domain.com</to>
    <subject>How are you?</subject>
    <body>Hello. How are you? Thank you. Best regards.</body>
</message>
message-1.xml validates
</code>```

And it is valid!

Here is a second more complex XML example (message-2.xml) that has to be valid:

```<code>$ xmllint --schema message.xsd message-2.xml
<?xml version="1.0"?>
<message xmlns="http://yugiohjcj.1s.fr/message">
    <subject>How are you?</subject>
    <body>Hello. How are you? Thank you. Best regards.</body>
    <from>me@domain.com</from>
    <to>you@domain.com</to>
    <to>and-you@domain.com</to>
    <cc>someone-else@domain.com</cc>
    <cc>again-someone-else@domain.com</cc>
</message>
message-2.xml validates
</code>```

And it is valid!

Here is a third XML example (message-3.xml) that has to be not valid:

```<code>$ xmllint --schema message.xsd message-3.xml
<?xml version="1.0"?>
<message xmlns="http://yugiohjcj.1s.fr/message">
    <from>me@domain.com</from>
    <from>someone-else@domain.com</from>
    <to>you@domain.com</to>
    <subject>How are you?</subject>
    <subject>How are you again?</subject>
    <body>Hello. How are you? Thank you. Best regards.</body>
    <body>Hello. How are you again? Thank you. Best regards.</body>
</message>
message-3.xml validates
</code>```

But it is valid!
That's the problem.

Here is my XML Schema (message.xsd):

```<code>$ cat message.xsd
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://yugiohjcj.1s.fr/message" targetNamespace="http://yugiohjcj.1s.fr/message" elementFormDefault="qualified">
    <xs:element name="message">
        <xs:complexType>
            <xs:sequence>
                <xs:choice minOccurs="0" maxOccurs="unbounded">
                    <xs:element name="from"/>
                    <xs:element name="to"/>
                    <xs:element name="cc"/>
                    <xs:element name="subject"/>
                    <xs:element name="body"/>
                </xs:choice>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>
</code>```

I guess that I need to set the maxOccurs attribute to the value 1 somewhere or maybe I need to combine differently the <xs:sequence> and <xs:choice> elements but I have not found how to reach my goal.

Any idea how to fix this XML Schema please?

Thank you.

Best regards.

Edit: OK I found a workaround to my problem by using Relax NG instead of XSD 1.0. It works fine and it is compatible with libxml2.

Here is my message.rng file:

```<code>$ cat message.rng
<element name="message" xmlns="http://relaxng.org/ns/structure/1.0">
    <interleave>
        <zeroOrMore>
            <element name="from">
                <text/>
            </element>
        </zeroOrMore>
        <zeroOrMore>
            <element name="to">
                <text/>
            </element>
        </zeroOrMore>
        <zeroOrMore>
            <element name="cc">
                <text/>
            </element>
        </zeroOrMore>
        <optional>
            <element name="subject">
                <text/>
            </element>
        </optional>
        <optional>
            <element name="body">
                <text/>
            </element>
        </optional>
    </interleave>
</element>
</code>```

And here is the result on my 3 XML examples (message-1.xml, message-2.xml and message-3.xml):

```<code>$ xmllint --relaxng message.rng message-1.xml
<?xml version="1.0"?>
<message>
    <from>me@domain.com</from>
    <to>you@domain.com</to>
    <subject>How are you?</subject>
    <body>Hello. How are you? Thank you. Best regards.</body>
</message>
message-1.xml validates
$ xmllint --relaxng message.rng message-2.xml
<?xml version="1.0"?>
<message>
    <subject>How are you?</subject>
    <body>Hello. How are you? Thank you. Best regards.</body>
    <from>me@domain.com</from>
    <to>you@domain.com</to>
    <to>and-you@domain.com</to>
    <cc>someone-else@domain.com</cc>
    <cc>again-someone-else@domain.com</cc>
</message>
message-2.xml validates
$ xmllint --relaxng message.rng message-3.xml
<?xml version="1.0"?>
<message>
    <from>me@domain.com</from>
    <from>someone-else@domain.com</from>
    <to>you@domain.com</to>
    <subject>How are you?</subject>
    <subject>How are you again?</subject>
    <body>Hello. How are you? Thank you. Best regards.</body>
    <body>Hello. How are you again? Thank you. Best regards.</body>
</message>
Relax-NG validity error : Extra element subject in interleave
message-3.xml:7: element subject: Relax-NG validity error : Element message failed to validate content
message-3.xml fails to validate
</code>```

答:
In XSD 1.0 if you want to allow elements to appear in any order then the only way to control how often each element may appear is using xs:all, and this constrains the number of appearances to be zero or one. So you can't achieve what you are attempting.

This restriction is lifted in XSD 1.1.

Body:
I am working on an XML Schema (message.xsd) describing the structure of a message.

Here are the expected children of the <message> element (the root):

<from>: Contains the address of the sender. Occurs 0 or 1 times.

<to>: Contains the address of the recipient. Occurs 0 or more times.

<cc>: Contains the address of the recipient in copy. Occurs 0 or more times.

<subject>: Contains the subject of the message. Occurs 0 or 1 times.

: Contains the body of the message. Occurs 0 or 1 times.

The order of elements does not matter, it means that they can be in any order.

Here is a first simple XML example (message-1.xml) that has to be valid:

$ xmllint --schema message.xsd message-1.xml
<?xml version="1.0"?>
<message xmlns="http://yugiohjcj.1s.fr/message">
    <from>me@domain.com</from>
    <to>you@domain.com</to>
    <subject>How are you?</subject>
    Hello. How are you? Thank you. Best regards.
</message>
message-1.xml validates

And it is valid!

Here is a second more complex XML example (message-2.xml) that has to be valid:

$ xmllint --schema message.xsd message-2.xml
<?xml version="1.0"?>
<message xmlns="http://yugiohjcj.1s.fr/message">
    <subject>How are you?</subject>
    Hello. How are you? Thank you. Best regards.
    <from>me@domain.com</from>
    <to>you@domain.com</to>
    <to>and-you@domain.com</to>
    <cc>someone-else@domain.com</cc>
    <cc>again-someone-else@domain.com</cc>
</message>
message-2.xml validates

And it is valid!

Here is a third XML example (message-3.xml) that has to be not valid:

$ xmllint --schema message.xsd message-3.xml
<?xml version="1.0"?>
<message xmlns="http://yugiohjcj.1s.fr/message">
    <from>me@domain.com</from>
    <from>someone-else@domain.com</from>
    <to>you@domain.com</to>
    <subject>How are you?</subject>
    <subject>How are you again?</subject>
    Hello. How are you? Thank you. Best regards.
    Hello. How are you again? Thank you. Best regards.
</message>
message-3.xml validates

But it is valid!
That's the problem.

Here is my XML Schema (message.xsd):

$ cat message.xsd
<?xml version="1.0" encoding="UTF-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" xmlns="http://yugiohjcj.1s.fr/message" targetNamespace="http://yugiohjcj.1s.fr/message" elementFormDefault="qualified">
    <xs:element name="message">
        <xs:complexType>
            <xs:sequence>
                <xs:choice minOccurs="0" maxOccurs="unbounded">
                    <xs:element name="from"/>
                    <xs:element name="to"/>
                    <xs:element name="cc"/>
                    <xs:element name="subject"/>
                    <xs:element name="body"/>
                </xs:choice>
            </xs:sequence>
        </xs:complexType>
    </xs:element>
</xs:schema>

I guess that I need to set the maxOccurs attribute to the value 1 somewhere or maybe I need to combine differently the <xs:sequence> and <xs:choice> elements but I have not found how to reach my goal.

Any idea how to fix this XML Schema please?

Thank you.

Best regards.

Edit: OK I found a workaround to my problem by using Relax NG instead of XSD 1.0. It works fine and it is compatible with libxml2.

Here is my message.rng file:

$ cat message.rng
<element name="message" xmlns="http://relaxng.org/ns/structure/1.0">
    <interleave>
        <zeroOrMore>
            <element name="from">
                <text/>
            </element>
        </zeroOrMore>
        <zeroOrMore>
            <element name="to">
                <text/>
            </element>
        </zeroOrMore>
        <zeroOrMore>
            <element name="cc">
                <text/>
            </element>
        </zeroOrMore>
        <optional>
            <element name="subject">
                <text/>
            </element>
        </optional>
        <optional>
            <element name="body">
                <text/>
            </element>
        </optional>
    </interleave>
</element>

And here is the result on my 3 XML examples (message-1.xml, message-2.xml and message-3.xml):

$ xmllint --relaxng message.rng message-1.xml
<?xml version="1.0"?>
<message>
    <from>me@domain.com</from>
    <to>you@domain.com</to>
    <subject>How are you?</subject>
    Hello. How are you? Thank you. Best regards.
</message>
message-1.xml validates
$ xmllint --relaxng message.rng message-2.xml
<?xml version="1.0"?>
<message>
    <subject>How are you?</subject>
    Hello. How are you? Thank you. Best regards.
    <from>me@domain.com</from>
    <to>you@domain.com</to>
    <to>and-you@domain.com</to>
    <cc>someone-else@domain.com</cc>
    <cc>again-someone-else@domain.com</cc>
</message>
message-2.xml validates
$ xmllint --relaxng message.rng message-3.xml
<?xml version="1.0"?>
<message>
    <from>me@domain.com</from>
    <from>someone-else@domain.com</from>
    <to>you@domain.com</to>
    <subject>How are you?</subject>
    <subject>How are you again?</subject>
    Hello. How are you? Thank you. Best regards.
    Hello. How are you again? Thank you. Best regards.
</message>
Relax-NG validity error : Extra element subject in interleave
message-3.xml:7: element subject: Relax-NG validity error : Element message failed to validate content
message-3.xml fails to validate


问:
Why can a nested function using a regular variable can't change the namesake variable in the outer scope, while one using an item in a list can?
What is the reason that the nested function in the first example using a regular variable can't change the variable in the outer scope, while the one in the second example using an item in a list can?

I am looking for an answer from language design perspective.

Thanks.

Example one:

```<code>def make_counter():
    count = 0
    def counter():
        count += 1
        return count
    return counter
</code>```

Example two:

```<code>def make_counter():
    count = [0]
    def counter():
        count[0] += 1
        return count[0]
    return counter
</code>```

答:
This is because integers in python are imutable, while lists are not.

Hence, when you write count += 1, this is equivalent to

```<code>count = count + 1
</code>```

which creates a new variable (which is then local to counter), in contrast, when you write count[0] += 1 this is equivalent to

```<code>value = count[0]
value = value + 1
count[0] = value
</code>```

here, count has not been re-assigned to any new value, and you modify the original count, created outside the inner function, by assigning the (newly created) value to it.

Body:
What is the reason that the nested function in the first example using a regular variable can't change the variable in the outer scope, while the one in the second example using an item in a list can?

I am looking for an answer from language design perspective.

Thanks.

Example one:

def make_counter():
    count = 0
    def counter():
        count += 1
        return count
    return counter

Example two:

def make_counter():
    count = [0]
    def counter():
        count[0] += 1
        return count[0]
    return counter

Body:
This is because integers in python are imutable, while lists are not.

Hence, when you write count += 1, this is equivalent to

count = count + 1

which creates a new variable (which is then local to counter), in contrast, when you write count[0] += 1 this is equivalent to

value = count[0]
value = value + 1
count[0] = value

here, count has not been re-assigned to any new value, and you modify the original count, created outside the inner function, by assigning the (newly created) value to it.


问:
How to know which process is changing a file in linux
I'm using an automation tool to build a virtual machine. During the this automation a config file (/etc/myprogram/cofig.ini) is becoming empty.

This file's contents are required complete the automation, but I'm clueless which process is emptying the file.

I want to monitor a file and list the name of processes changed the contents of the file.

I'm using Ubuntu 16.04.

I saw some questions in Stackoverflow but did help. I tried to use audictl inotify and watchdog . Please let me know any better way to do this. Is there a way to do this using python.

答:
The lsof command will show what processes are using which files:

```<code>lsof | grep <filename>
</code>```

Body:
The lsof command will show what processes are using which files:

lsof | grep <filename>


问:
How to select the filled values in the mysql cells
What query should I write for selecting only filled cells? For example, in

```<code>SELECT DISTINCT  color FROM `products` WHERE category=4
</code>```

I am getting the unfilled cells  also. What would be the query for retrieving only cells with values?

答:
You probably need to add this to your WHERE clause:

```<code>and color is not null
</code>```

Body:
What query should I write for selecting only filled cells? For example, in

SELECT DISTINCT  color FROM `products` WHERE category=4

I am getting the unfilled cells  also. What would be the query for retrieving only cells with values?

Body:
You probably need to add this to your WHERE clause:

and color is not null


问:
How to properly keep config files in Laravel?
I've built a piece of software which uses Laravel config module to consume certain settings.

Thing is, we're using Laravel Forge to auto-deploy, and everytime we deploy, configs are reset to the "blank" state, thus breaking some things everytime I deploy.

I have added the files to .gitignore, but doesn't seem to do the trick.

Can anyone point me towards the right direction in order to save this config files without having the re-set them everyime we deploy?

Thanks everyone!

答:
It would be helpful to have an example of your config and .env files

Config files for multiple environments rely on .env files in each environment.

env() returns either the matching variable from your .env or the value specified.

so env('QUEUE_DRIVER', 'sqs') would look into the .env file for the QUEUE_DRIVER variable if it can't find a variable it returns the default 'sqs'.

An example of a queue config file might looks like this.

config/queue.php

```<code><?php

return [
    'default' => env('QUEUE_DRIVER', 'sqs'),
      'connections' => [
        'sync' => [
            'driver' => 'sync',
        ],
        'sqs' => [
            'driver' => 'sqs',
            'key' =>  env('SQS_KEY'),
            'secret' =>  env('SQS_SECRET'),
            'prefix' => env('SQS_URL'),
            'queue' => 'general_queue',
            'region' => 'us-east-1',
        ],
      ],
    ];
</code>```

You would then set your variables in your .env file for each environment.

Production may look like this.

.env

```<code>QUEUE_DRIVER=sqs

SQS_KEY=yoursqskey
SQS_SECRET=yoursqssecret
SQS_URL=yoursqsurl
</code>```

Your local environment might look like this.

.env

```<code>QUEUE_DRIVER=sync
</code>```

You can edit your .env file in forge under Sites > Site Details > Environment

Body:
It would be helpful to have an example of your config and .env files

Config files for multiple environments rely on .env files in each environment.

env() returns either the matching variable from your .env or the value specified.

so env('QUEUE_DRIVER', 'sqs') would look into the .env file for the QUEUE_DRIVER variable if it can't find a variable it returns the default 'sqs'.

An example of a queue config file might looks like this.

config/queue.php

<?php

return [
    'default' => env('QUEUE_DRIVER', 'sqs'),
      'connections' => [
        'sync' => [
            'driver' => 'sync',
        ],
        'sqs' => [
            'driver' => 'sqs',
            'key' =>  env('SQS_KEY'),
            'secret' =>  env('SQS_SECRET'),
            'prefix' => env('SQS_URL'),
            'queue' => 'general_queue',
            'region' => 'us-east-1',
        ],
      ],
    ];

You would then set your variables in your .env file for each environment.

Production may look like this.

.env

QUEUE_DRIVER=sqs

SQS_KEY=yoursqskey
SQS_SECRET=yoursqssecret
SQS_URL=yoursqsurl

Your local environment might look like this.

.env

QUEUE_DRIVER=sync

You can edit your .env file in forge under Sites > Site Details > Environment


问:
Implementing an ADO.NET layer
Are there any tutorials or how-to's that explain how to implement an ADO.NET layer?

That would include implementing a Connection class, etcetera.

I need to do this because I am querying an old proprietary system and I want to wrap the old APIs properly.

答:
See "Building a Custom Data Provider for Use with the .NET Data Access Framework" at http://msdn.microsoft.com/en-us/magazine/cc301611.aspx

Also, Googling for "Custom ADO.NET Data Provider" should give you many possible answers.

OwnerDisplayName: Sklivvz

Title: Implementing an ADO.NET layer

OwnerDisplayName: Bork Blatt

LastEditorDisplayName: Bork Blatt


问:
sharepoint wss 3.0 user domain
I've inherited a sharepoint wss 3.0 farm that is pulling users from 2 different domains, say domainA and domainB. So if I go into Add User and Browse, and type Smith, it is coming up with domainA\jsmith and domainB\jsmith. The company has moved away from domainA and uses only domainB now. So I want to remove domainA from the sharepoint configuration. I don't need to migrate existing sharepoint users, I just want for the domainA users to stop showing up when new users are added. I've been through every page I can find in Central Administration and I don't see where the names of the domain controller(s) are specified. It is using windows auth / NTLM.</p>

答:
You will want to look at peoplepicker-searchadcustomquery property. You can setup an LDAP query which will allows you to specify which users are shown.

http://technet.microsoft.com/en-us/library/cc262988.aspx

To restrict a search for a distribution list to only be corp.fabrikam.com and ntdev.corp.fabrikam.com, use the following syntax:

```<code>stsadm -o setproperty -url http://contoso-370
-pn peoplepicker-distributionlistsearchdomains
-pv corp.fabrikam.com;dev.corp.fabrikam.com
</code>```

The domain name should be a Domain Name Service (DNS) name and should be separated by a semicolon. If no values are set, all trusted domains or the domains listed in the configuration are searched.   To view the current setting for the distributionlistsearchdomains property, use the following syntax:

stsadm -o getproperty -pn
  peoplepicker-distributionlistsearchdomains

http://social.technet.microsoft.com/Forums/en-US/sharepointsearch/thread/b6b02e06-5b8c-41fb-be20-b8bf488bbe7e

Title: sharepoint wss 3.0 user domain

Body:
You will want to look at peoplepicker-searchadcustomquery property. You can setup an LDAP query which will allows you to specify which users are shown.

http://technet.microsoft.com/en-us/library/cc262988.aspx

To restrict a search for a distribution list to only be corp.fabrikam.com and ntdev.corp.fabrikam.com, use the following syntax:

stsadm -o setproperty -url http://contoso-370
-pn peoplepicker-distributionlistsearchdomains
-pv corp.fabrikam.com;dev.corp.fabrikam.com

The domain name should be a Domain Name Service (DNS) name and should be separated by a semicolon. If no values are set, all trusted domains or the domains listed in the configuration are searched.   To view the current setting for the distributionlistsearchdomains property, use the following syntax:

stsadm -o getproperty -pn
  peoplepicker-distributionlistsearchdomains

http://social.technet.microsoft.com/Forums/en-US/sharepointsearch/thread/b6b02e06-5b8c-41fb-be20-b8bf488bbe7e


问:
Remove row any in table use angular2
I want update to page html when click remove row any in table. I used the code of AngularJs 2.0 follow, but not update to page html. Please help me.Thank you very much !

Shipping.Component.html

```<code> `<div class="example table-responsive">
                <table class="table table-bordered">
                    <thead>
                        <tr>
                            <th>Giá trị đơn hàng</th>
                            <th>Giá ship</th>
                            <th>Xóa</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr *ngFor="let row of shipping.shipping_config; let i=index">
                            <td>
                                <input type="number" class="form-control fromgtdonhang gtdonhang" [(ngModel)]="row.from" placeholder="Từ">

                                <input type="number" class="form-control gtdonhang" [(ngModel)]="row.to" placeholder="Đến">
                            </td>
                            <td>
                                <input type="number" class="form-control" [(ngModel)]="row.shipping_fee" placeholder="Giá ship">
                            </td>
                            <td class="formatremove">
                                <a href="javascript:void(0)" (click)="removeKhunggia(i)">
                                    <i class="icon wb-close" aria-hidden="true"></i></a>
                            </td>
                        </tr>
                        <tr>
                            <td colspan="3" class="formatbuttonadd">
                                <button type="button" (click)="addKhunggia()" class="btn btn-outline btn-primary">
                                    <i class="icon wb-plus" aria-hidden="true"></i> Thêm
                                </button>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>`
</code>```

In Shipping.component.ts:

```<code> `ngOnInit() {
        this.shippingService.getShopingConfig().subscribe(res => {
            this.shipping = res;
            this.rowsShippingConfig = res.shipping_config;
        });
    }
removeKhunggia(id: number) {
        this.rowsShippingConfig.slice(id,-1);
    }`
</code>```

答:
You need to assign the value after removing,</p>

```<code>removeKhunggia(id: number) {
  this.rowsShippingConfig =   this.rowsShippingConfig.slice(id,1);
}
</code>```

Title: Remove row any in table use angular2

Body:
I want update to page html when click remove row any in table. I used the code of AngularJs 2.0 follow, but not update to page html. Please help me.Thank you very much !

Shipping.Component.html

 `

                            Giá trị đơn hàng
                            Giá ship
                            Xóa

                                <input type="number" class="form-control fromgtdonhang gtdonhang" [(ngModel)]="row.from" placeholder="Từ">

                                <input type="number" class="form-control gtdonhang" [(ngModel)]="row.to" placeholder="Đến">

                                <input type="number" class="form-control" [(ngModel)]="row.shipping_fee" placeholder="Giá ship">

                                <button type="button" (click)="addKhunggia()" class="btn btn-outline btn-primary">
                                     Thêm
                                </button>

`

In Shipping.component.ts:

 `ngOnInit() {
        this.shippingService.getShopingConfig().subscribe(res => {
            this.shipping = res;
            this.rowsShippingConfig = res.shipping_config;
        });
    }
removeKhunggia(id: number) {
        this.rowsShippingConfig.slice(id,-1);
    }`

Body:
You need to assign the value after removing,

removeKhunggia(id: number) {
  this.rowsShippingConfig =   this.rowsShippingConfig.slice(id,1);
}


问:
Viewing Serialized Hash Rails
I am trying to build a default checklist for my application by serializing a hash. I don't know how to pull the information in my setup_checklist hash to my views. Any help is appreciated.

Here is my user model

```<code>class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  serialize :checklist, Hash

  before_create :setup_checklist

  private

  def setup_checklist
    self.checklist = {
      "Organize Your Finances" => false,
      "Approval Letter" => false,
      "Get a Real Estate Agent and look for houses" => false,
      "Find lawyer" => false,
      "Get the mortgage" => false,
      "Apprisal and inspection" => false,
      "Close the deal" => false
    }
  end
end
</code>```

my view.html.erb

```<code><%= form_for :checklist do |f| %>
  <%= f.check_box :checklist %>
<% end %>
</code>```

I know I am not even close but a steer in the right direction would be great

答:
To display checkboxes from a hash, you need to iterate the hash and create a checkbox for each element; for example:</p>

```<code><%= form_for @user do |f| %>
  <% @user.checklist.each do |key, value| %>
    <%= f.check_box key %>
  <% end %>
<% end %>
</code>```

Title: Viewing Serialized Hash Rails

Body:
I am trying to build a default checklist for my application by serializing a hash. I don't know how to pull the information in my setup_checklist hash to my views. Any help is appreciated.

Here is my user model

class User < ActiveRecord::Base
  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable, :confirmable

  serialize :checklist, Hash

  before_create :setup_checklist

  private

  def setup_checklist
    self.checklist = {
      "Organize Your Finances" => false,
      "Approval Letter" => false,
      "Get a Real Estate Agent and look for houses" => false,
      "Find lawyer" => false,
      "Get the mortgage" => false,
      "Apprisal and inspection" => false,
      "Close the deal" => false
    }
  end
end

my view.html.erb

<%= form_for :checklist do |f| %>
  <%= f.check_box :checklist %>
<% end %>

I know I am not even close but a steer in the right direction would be great

Body:
To display checkboxes from a hash, you need to iterate the hash and create a checkbox for each element; for example:

<%= form_for @user do |f| %>
  <% @user.checklist.each do |key, value| %>
    <%= f.check_box key %>
  <% end %>
<% end %>


问:
Correct JSON string format for the body request in a WebRequest Activity inside of a Orchard Workflow?
I'm trying to make a POST in a WebRequest Activity, but the body is always empty if I select JSON format:

I have tried escaping and unescaping characters, with and without quotes and spaces, etc:

```<code>{\"value\": [{\"@search.action\": \"delete\",\"id\": \"abc-008\"}]}
</code>```

And

```<code>{value:[{@search.action: delete,id: abc-008}]}
</code>```

But formValues is always empty:

```<code>var formValues = activityContext.GetState<string>("FormValues") ?? "";
</code>```

The request works fine if I select Key/Value as the format but I need Json.

Edit: Should add that I tried the valid Json format (JsonLint) plus the examples I gave, with and without spaces and using ' instead of " but it's still empty.

答:
Quick fix:

```<code>(( "value": [(( "@search.action": "delete", "id": "abc - 008" ))] ))
</code>```

Explanation: This is actually an awkward side-effect of how Orchard handles tokens within workflows. Take with a pinch of salt because I have a bad memory but I think it goes like this. So before data is sent to the individual workflow activities, the Workflows module executes the tokens stored. This means all your JSON stored is thrown away because Orchard thinks it is a token (Orchard tokens are formatted so: {Content.Body} etc.) and tries to execute it. I discovered this when trying to store a complex object within a workflow activity and had to hack around the issue. I meant to report it as an issue but I think I forgot (my bad), but seeing this makes me think it is a bug really. So why does the above work? Some selfish genius clearly ran into this issue and updated the code with this hack line:

```<code>var json = formValues.Replace("((", "{").Replace("))", "}");
</code>```

Then left the UI saying:

For JSon, enter a valid JSon string

Massive fail.

To correct my earlier laziness, I've created two issues regarding this. https://github.com/OrchardCMS/Orchard/issues/7760 https://github.com/OrchardCMS/Orchard/issues/7759

Body:
I'm trying to make a POST in a WebRequest Activity, but the body is always empty if I select JSON format:

I have tried escaping and unescaping characters, with and without quotes and spaces, etc:

{\"value\": [{\"@search.action\": \"delete\",\"id\": \"abc-008\"}]}

And

{value:[{@search.action: delete,id: abc-008}]}

But formValues is always empty:

var formValues = activityContext.GetState<string>("FormValues") ?? "";

The request works fine if I select Key/Value as the format but I need Json.

Edit: Should add that I tried the valid Json format (JsonLint) plus the examples I gave, with and without spaces and using ' instead of " but it's still empty.

Body:
Quick fix:

(( "value": [(( "@search.action": "delete", "id": "abc - 008" ))] ))

Explanation: This is actually an awkward side-effect of how Orchard handles tokens within workflows. Take with a pinch of salt because I have a bad memory but I think it goes like this. So before data is sent to the individual workflow activities, the Workflows module executes the tokens stored. This means all your JSON stored is thrown away because Orchard thinks it is a token (Orchard tokens are formatted so: {Content.Body} etc.) and tries to execute it. I discovered this when trying to store a complex object within a workflow activity and had to hack around the issue. I meant to report it as an issue but I think I forgot (my bad), but seeing this makes me think it is a bug really. So why does the above work? Some selfish genius clearly ran into this issue and updated the code with this hack line:

var json = formValues.Replace("((", "{").Replace("))", "}");

Then left the UI saying:

For JSon, enter a valid JSon string

Massive fail.

To correct my earlier laziness, I've created two issues regarding this. https://github.com/OrchardCMS/Orchard/issues/7760 https://github.com/OrchardCMS/Orchard/issues/7759


问:
Is it possible to capture a Ctrl+C signal (SIGINT) and run a cleanup function, in a "defer" fashion?
I want to capture the Ctrl+C (SIGINT) signal sent from the console and print out some partial run totals.

答:
You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.

I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.

https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go

You can do this in a 'defer' fashion.

example for shutting down a server gracefully :

```<code>srv := &http.Server{}

go_shutdown_hook.ADD(func() {
    log.Println("shutting down server")
    srv.Shutdown(nil)
    log.Println("shutting down server-done")
})

l, err := net.Listen("tcp", ":3090")

log.Println(srv.Serve(l))

go_shutdown_hook.Wait()
</code>```

ContentLicense: CC BY-SA 4.0

Body:
You can have a different goroutine that detects syscall.SIGINT and syscall.SIGTERM signals and relay them to a channel using signal.Notify. You can send a hook to that goroutine using a channel and save it in a function slice. When the shutdown signal is detected on the channel, you can execute those functions in the slice. This can be used to clean up the resources, wait for running goroutines to finish, persist data, or print partial run totals.

I wrote a small and simple utility to add and run hooks at shutdown. Hope it can be of help.

https://github.com/ankit-arora/go-utils/blob/master/go-shutdown-hook/shutdown-hook.go

You can do this in a 'defer' fashion.

example for shutting down a server gracefully :

srv := &http.Server{}

go_shutdown_hook.ADD(func() {
    log.Println("shutting down server")
    srv.Shutdown(nil)
    log.Println("shutting down server-done")
})

l, err := net.Listen("tcp", ":3090")

log.Println(srv.Serve(l))

go_shutdown_hook.Wait()


问:
Unresolved external symbol "public: virtual struct QMetaObject const * __thiscall Parent
I inherited a class from QObject :

```<code>class Parent: public QObject
{
    Q_OBJECT
    QObject* cl;

public:
    Parent(QObject *parent=0):QObject(parent) {
        cl = NULL;
    }

    QObject* getCl() const {
        return cl;
    }
    void setCl(QObject *obj) {
        cl = obj;
    }
};
</code>```

But when I write :

```<code>Parent ev;
</code>```

I get the following error:

```<code>main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall Parent::metaObject(void)const " (?metaObject@Parent@@UBEPBUQMetaObject@@XZ)

main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void * __thiscall Parent::qt_metacast(char const *)" (?qt_metacast@Parent@@UAEPAXPBD@Z)

main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual int __thiscall Parent::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@Parent@@UAEHW4Call@QMetaObject@@HPAPAX@Z)
</code>```

答:
I am working in VS2015 with an integrated Perforce p4v client.
In my case Perforce tried to add  moc file to a depo, when I reverted this operation, Perforce removed this moc file from project and deleted it.
The file was recreated after the next compilation, but it wasn't included in project, I have to add it manually to Generated files, when I finally understood what was the problem.</p>

Body:
I inherited a class from QObject :

class Parent: public QObject
{
    Q_OBJECT
    QObject* cl;

public:
    Parent(QObject *parent=0):QObject(parent) {
        cl = NULL;
    }

    QObject* getCl() const {
        return cl;
    }
    void setCl(QObject *obj) {
        cl = obj;
    }
};

But when I write :

Parent ev;

I get the following error:

main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual struct QMetaObject const * __thiscall Parent::metaObject(void)const " (?metaObject@Parent@@UBEPBUQMetaObject@@XZ)

main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual void * __thiscall Parent::qt_metacast(char const *)" (?qt_metacast@Parent@@UAEPAXPBD@Z)

main.obj:-1: error: LNK2001: unresolved external symbol "public: virtual int __thiscall Parent::qt_metacall(enum QMetaObject::Call,int,void * *)" (?qt_metacall@Parent@@UAEHW4Call@QMetaObject@@HPAPAX@Z)


问:
CSRF Token generate different one each GET method (Laravel 5.3 server & Ionic 2 client)
I'm making an application with Ionic 2 to login to Laravel 5.3 server. When i GET CSRF Token from Postman, I see that the CSRF Token will never change even how many time I GET (unless the session is ended). So I can login from Postman when Post the Token with username and password. But from my Ionic 2 app, each time I GET CSRF Token, the CSRF Token is change to an other one. So the CSRF verification always return error.

You can see the CSRF Token has been changed

My GET returned CSRF Token from Laravel server:

```<code>Route::get('api/csrf', function() {
    return Session::token();
});
</code>```

My GET method I do from Ionic app client:

```<code>token() {
    this._token = this.http.get('http://localhost:8000/api/csrf').map((res:Response) => res.text()).subscribe(data => {
        consoler.log(data);
    });
}
</code>```

I understand that the problem is I didn't save the Token right way or some thing with session cookie. If you guys have any idea, please help me! Thank you for read all ask!

p/s:
  1. My English is not good, so please forgive me if I have some mistake.
  2. I'm developing Cordova app with Ionic (Ionic tabs application, i think so) and API server with Laravel

答:
Oh I found the solution, it is stupid basic that i forgot: Laravel has API Authentication it own. So all i need to do is use the token from API Authentication instead of normal Authentication with Cookie of CSRF.
Thanks for read my question! If it bothered you guys, pls forgive me ^^</p>

Body:
I'm making an application with Ionic 2 to login to Laravel 5.3 server. When i GET CSRF Token from Postman, I see that the CSRF Token will never change even how many time I GET (unless the session is ended). So I can login from Postman when Post the Token with username and password. But from my Ionic 2 app, each time I GET CSRF Token, the CSRF Token is change to an other one. So the CSRF verification always return error.

You can see the CSRF Token has been changed

My GET returned CSRF Token from Laravel server:

Route::get('api/csrf', function() {
    return Session::token();
});

My GET method I do from Ionic app client:

token() {
    this._token = this.http.get('http://localhost:8000/api/csrf').map((res:Response) => res.text()).subscribe(data => {
        consoler.log(data);
    });
}

I understand that the problem is I didn't save the Token right way or some thing with session cookie. If you guys have any idea, please help me! Thank you for read all ask!

p/s:
  1. My English is not good, so please forgive me if I have some mistake.
  2. I'm developing Cordova app with Ionic (Ionic tabs application, i think so) and API server with Laravel


问:
Unable to Inter-Lock between processes while using multiprocessing module in Python
I'm somewhat new to Python. I've been learning and researching about the Multiprocessing module and I'm stuck at this issue while using locking.

Here is the test code:

```<code>import multiprocessing
from multiprocessing import Pool

class Param_Class():

#Initialisation.
    def __init__(self):
        self.counter = multiprocessing.Value('i',0)
        self.lock = multiprocessing.Lock()

    def inc_counter(self):
            lk.acquire()
            print('Locked {}'.format(multiprocessing.current_process().name))
            self.counter.value+=1
            lk.release()
            print('Released {}'.format(multiprocessing.current_process().name))

param_class = Param_Class()

def init(lock):
    global lk
    lk = lock

def target():
    param_class.inc_counter()
    code = 0
    return code

def handler(i):
    if i<50:
        code = target()
        print(param_class.counter.value)

if __name__ == '__main__':
    p = Pool(processes=2,initializer=init, initargs=(param_class.lock,))
    p.map_async(handler,range(50))
    p.close()
    p.join()
</code>```

What I expected is each process getting locked while the other one is executing so my counter should increment every time either of the process is executed. However, there is no interlocking happening between the process and the second process is working on the copy of the counter.

Here is the output:

```<code>Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
1
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
2
Released SpawnPoolWorker-2
1
Locked SpawnPoolWorker-1
Locked SpawnPoolWorker-2
Released SpawnPoolWorker-1
Released SpawnPoolWorker-2
3
2
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
4
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
3
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
5
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
4
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
6
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
5
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
7
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
6
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
8
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
7
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
9
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
8
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
10
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
9
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
11
Released SpawnPoolWorker-2
10
Locked SpawnPoolWorker-1
Locked SpawnPoolWorker-2
Released SpawnPoolWorker-1
Released SpawnPoolWorker-2
12
11
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
13
Released SpawnPoolWorker-2
12
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
14
Released SpawnPoolWorker-2
13
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
15
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
14
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
16
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
15
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
17
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
16
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
18
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
17
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
19
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
18
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
20
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
19
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
21
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
20
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
22
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
21
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
23
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
22
Released SpawnPoolWorker-1
24
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
25
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
26
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
27
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
28
</code>```

Desired Output should be something like this:

```<code>Locked SpawnPoolWorker-1
1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
2
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
3
Released SpawnPoolWorker-1
.
.
.
.
.
.
.
Locked SpawnPoolWorker-2
50
Released SpawnPoolWorker-2
</code>```

I've referred to this to learn about initializing a lock and inheriting it. I'm not able to comprehend where I've messed up. Is it the lock or the multiprocessing.Pool call or using class instances or perhaps the target function itself. Please be detailed about it with some theory to back it up. I'd like to learn about this, not just solve it.

Notice how, in the obtained output, it works as expected from value 24 to 28 and process 2 just stopped working. Need clarification on that one too.

P.S.: I'd want to avoid using a Manager as it is heavyweight as mentioned in the linked answer. Also, I don't want to eliminate the partial concurrency of the execution because I'll be using other variables which don't need to be locked and I want the module to stay fast and pythonic.

答:
Apparently, every time the process undergoes an apply, the init of class is called, hence creating a copy for each process.

Hence to overcome this, instead of creating counter as a class attribute, it can be passed in the pool's init and made global.

Also, the lock is insignificant.

Body:
I'm somewhat new to Python. I've been learning and researching about the Multiprocessing module and I'm stuck at this issue while using locking.

Here is the test code:

import multiprocessing
from multiprocessing import Pool

class Param_Class():

#Initialisation.
    def __init__(self):
        self.counter = multiprocessing.Value('i',0)
        self.lock = multiprocessing.Lock()

    def inc_counter(self):
            lk.acquire()
            print('Locked {}'.format(multiprocessing.current_process().name))
            self.counter.value+=1
            lk.release()
            print('Released {}'.format(multiprocessing.current_process().name))

param_class = Param_Class()

def init(lock):
    global lk
    lk = lock

def target():
    param_class.inc_counter()
    code = 0
    return code

def handler(i):
    if i<50:
        code = target()
        print(param_class.counter.value)

if __name__ == '__main__':
    p = Pool(processes=2,initializer=init, initargs=(param_class.lock,))
    p.map_async(handler,range(50))
    p.close()
    p.join()

What I expected is each process getting locked while the other one is executing so my counter should increment every time either of the process is executed. However, there is no interlocking happening between the process and the second process is working on the copy of the counter.

Here is the output:

Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
1
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
2
Released SpawnPoolWorker-2
1
Locked SpawnPoolWorker-1
Locked SpawnPoolWorker-2
Released SpawnPoolWorker-1
Released SpawnPoolWorker-2
3
2
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
4
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
3
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
5
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
4
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
6
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
5
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
7
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
6
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
8
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
7
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
9
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
8
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
10
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
9
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
11
Released SpawnPoolWorker-2
10
Locked SpawnPoolWorker-1
Locked SpawnPoolWorker-2
Released SpawnPoolWorker-1
Released SpawnPoolWorker-2
12
11
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
13
Released SpawnPoolWorker-2
12
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
14
Released SpawnPoolWorker-2
13
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
15
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
14
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
16
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
15
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
17
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
16
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
18
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
17
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
19
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
18
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
20
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
19
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
21
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
20
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
22
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
21
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
23
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
22
Released SpawnPoolWorker-1
24
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
25
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
26
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
27
Locked SpawnPoolWorker-1
Released SpawnPoolWorker-1
28

Desired Output should be something like this:

Locked SpawnPoolWorker-1
1
Released SpawnPoolWorker-1
Locked SpawnPoolWorker-2
2
Released SpawnPoolWorker-2
Locked SpawnPoolWorker-1
3
Released SpawnPoolWorker-1
.
.
.
.
.
.
.
Locked SpawnPoolWorker-2
50
Released SpawnPoolWorker-2

I've referred to this to learn about initializing a lock and inheriting it. I'm not able to comprehend where I've messed up. Is it the lock or the multiprocessing.Pool call or using class instances or perhaps the target function itself. Please be detailed about it with some theory to back it up. I'd like to learn about this, not just solve it.

Notice how, in the obtained output, it works as expected from value 24 to 28 and process 2 just stopped working. Need clarification on that one too.

P.S.: I'd want to avoid using a Manager as it is heavyweight as mentioned in the linked answer. Also, I don't want to eliminate the partial concurrency of the execution because I'll be using other variables which don't need to be locked and I want the module to stay fast and pythonic.


问:
what is need of service layer in spring mvc ? what kind of logic recommended?
( But as per as i know, it is mediator b/w controller and DAO layers. ) or Can we take  dao dependencies in controller directly , is it good practice !! ???  as i shown below </p>

```<code>@Controller
public class HomeController {

    // @Autowired
    // private UserServiceImpl userService;
    @Autowired
     private UserDAOImpl userDAOService;

   @RequestMapping(value = "login", method = RequestMethod.GET)
public String login(..){
   // String res = userService.someOperation();
      String res = userDAOService.someOperation();
      ............
         }
   }
</code>```

答:
One good reason why we need Service layer is for loose coupling:

Lets say you have 100 api's in your controller class and 20 dao methods serving them.

Now if you directly call dao methods in the controllers, and at later point of time you want to have different dao methods serving these controllers.

You have to change all your 100 controllers right?

So if have 20 service methods calling those 20 dao methods.

Now if you want to change your dao methods serving these 100 controllers, you can just change the service methods(i.e 20 methods) to point to new doa methods rather than changing your 100 controller classes.

That's how you achieve loose coupling and is a better way of programming.
Hope this helps you :)

Body:
( But as per as i know, it is mediator b/w controller and DAO layers. ) or Can we take  dao dependencies in controller directly , is it good practice !! ???  as i shown below

@Controller
public class HomeController {

    // @Autowired
    // private UserServiceImpl userService;
    @Autowired
     private UserDAOImpl userDAOService;

   @RequestMapping(value = "login", method = RequestMethod.GET)
public String login(..){
   // String res = userService.someOperation();
      String res = userDAOService.someOperation();
      ............
         }
   }


问:
Select Data with Column's Description not null, and then replace column name with description
I have a table 'PurchaseOrder'. I want select data when column's description is not null. and then replace the column's name with it's description.

table PurchaseOrder

```<code>ID | Product    |  Use    |   Price   |  Comment
-----------------------------------------------------
1  | Cellphone  |  true   |   100     |
2  | Car        |  false  |   10      |
3  | Table      |  true   |   200     |
</code>```

Column

```<code>Name      |    Description
---------------------------
ID        |    Index
Produce   |    Name
Use       |
Price     |    Sale
Comment   |
</code>```

The Select result will be

```<code>Index  |   Name      |    Sale
--------------------------------
1      |   Cellphone |    100
2      |   Car       |    10
3      |   Table     |    200
</code>```

Now, I just get the column with description

```<code>if object_id('tempdb..#dt') is not null drop table #dt
select
    sc.column_id [Position],
    sc.name [Column],
    sc.max_length [Length],
    sep.value [Description]
into #dt
from sys.tables st
inner join sys.columns sc on st.object_id = sc.object_id
left join sys.extended_properties sep on st.object_id = sep.major_id
                                     and sc.column_id = sep.minor_id
                                     and sep.name = 'MS_Description'
where st.name = 'PurchaseOrder' and sep.value is not null
</code>```

How to generate the final data table?

答:
```<code>DECLARE
@TABLE_NAME NVARCHAR(50) = 'PurchaseOrderDetail',
@TABLE_SCHEMA Nvarchar(50) = 'Purchasing',
@COL_LIST NVARCHAR(MAX),
@SQL NVARCHAR(4000),
@COL NVARCHAR(500)

DECLARE c_cursor CURSOR FOR
SELECT sc.name + ' as ' + QUOTENAME(CAST(sep.value AS varchar)) AS Expr1
FROM   sys.tables AS st INNER JOIN
       sys.columns AS sc ON st.object_id = sc.object_id INNER JOIN
       sys.extended_properties AS sep ON st.object_id = sep.major_id AND sc.column_id = sep.minor_id AND sep.name = 'MS_Description'
WHERE st.name = @TABLE_NAME AND sep.value IS NOT NULL

OPEN c_cursor;
FETCH NEXT
FROM c_cursor INTO @COL;
WHILE ( @@FETCH_STATUS = 0 )
BEGIN
SELECT @COL_LIST = COALESCE(@COL_LIST+',' ,'') + @COL
FETCH NEXT FROM c_cursor
INTO @col;
END CLOSE c_cursor;
DEALLOCATE c_cursor;

SET @SQL = ' SELECT ' + @COL_LIST +' FROM ' + QUOTENAME(@TABLE_SCHEMA)+'.'+QUOTENAME(@TABLE_NAME)
PRINT @SQL;
EXEC (@sql);
</code>```

Body:
I have a table 'PurchaseOrder'. I want select data when column's description is not null. and then replace the column's name with it's description.

table PurchaseOrder

ID | Product    |  Use    |   Price   |  Comment
-----------------------------------------------------
1  | Cellphone  |  true   |   100     |
2  | Car        |  false  |   10      |
3  | Table      |  true   |   200     |

Column

Name      |    Description
---------------------------
ID        |    Index
Produce   |    Name
Use       |
Price     |    Sale
Comment   |

The Select result will be

Index  |   Name      |    Sale
--------------------------------
1      |   Cellphone |    100
2      |   Car       |    10
3      |   Table     |    200

Now, I just get the column with description

if object_id('tempdb..#dt') is not null drop table #dt
select
    sc.column_id [Position],
    sc.name [Column],
    sc.max_length [Length],
    sep.value [Description]
into #dt
from sys.tables st
inner join sys.columns sc on st.object_id = sc.object_id
left join sys.extended_properties sep on st.object_id = sep.major_id
                                     and sc.column_id = sep.minor_id
                                     and sep.name = 'MS_Description'
where st.name = 'PurchaseOrder' and sep.value is not null

How to generate the final data table?


问:
Appcompat "java.lang.IllegalArgumentException: parameter must be a descendant of this view" in ViewGroup.offsetRectBetweenParentAndChild
I'm experiencing this problem randomly in the last month:

```<code>java.lang.IllegalArgumentException: parameter must be a descendant of this view
   at android.view.ViewGroup.offsetRectBetweenParentAndChild(ViewGroup.java:4479)
   at android.view.ViewGroup.offsetDescendantRectToMyCoords(ViewGroup.java:4416)
   at android.view.ViewRootImpl.scrollToRectOrFocus(ViewRootImpl.java:2656)
   at android.view.ViewRootImpl.draw(ViewRootImpl.java:2300)
   at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2249)
   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1882)
   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1009)
   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5508)
   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
   at android.view.Choreographer.doCallbacks(Choreographer.java:562)
   at android.view.Choreographer.doFrame(Choreographer.java:532)
   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
   at android.os.Handler.handleCallback(Handler.java:730)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:213)
   at android.app.ActivityThread.main(ActivityThread.java:5225)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
   at dalvik.system.NativeStart.main(NativeStart.java)
</code>```

After a lot of digging and tests, I figured out that the problem was introduced on October 27th after updating the Appcompat lib (android-support-v7-appcompat). Latest version of Appcompat doesn't seem to solve this issue.

I suppose that the problem is not related to similar bugs (like this question) because I've isolated the commit which introduced the problem on my repo and it is the one containing the Appcompat's update.

Any clue on this? Anyone with the same problem out there?

答:
usually on ListView there is method named offsetRectBetweenParentAndChild() that has the job of recycling views on scroll and this method usually throws this exception.

the best answer to this question is

Append a ScrollListener to your Activity, when listView start scrolling, clear current focus.

which I found in this question.

please check it out and let me know if there is other issues.

Body:
I'm experiencing this problem randomly in the last month:

java.lang.IllegalArgumentException: parameter must be a descendant of this view
   at android.view.ViewGroup.offsetRectBetweenParentAndChild(ViewGroup.java:4479)
   at android.view.ViewGroup.offsetDescendantRectToMyCoords(ViewGroup.java:4416)
   at android.view.ViewRootImpl.scrollToRectOrFocus(ViewRootImpl.java:2656)
   at android.view.ViewRootImpl.draw(ViewRootImpl.java:2300)
   at android.view.ViewRootImpl.performDraw(ViewRootImpl.java:2249)
   at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1882)
   at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1009)
   at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5508)
   at android.view.Choreographer$CallbackRecord.run(Choreographer.java:749)
   at android.view.Choreographer.doCallbacks(Choreographer.java:562)
   at android.view.Choreographer.doFrame(Choreographer.java:532)
   at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:735)
   at android.os.Handler.handleCallback(Handler.java:730)
   at android.os.Handler.dispatchMessage(Handler.java:92)
   at android.os.Looper.loop(Looper.java:213)
   at android.app.ActivityThread.main(ActivityThread.java:5225)
   at java.lang.reflect.Method.invokeNative(Method.java)
   at java.lang.reflect.Method.invoke(Method.java:525)
   at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:741)
   at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:557)
   at dalvik.system.NativeStart.main(NativeStart.java)

After a lot of digging and tests, I figured out that the problem was introduced on October 27th after updating the Appcompat lib (android-support-v7-appcompat). Latest version of Appcompat doesn't seem to solve this issue.

I suppose that the problem is not related to similar bugs (like this question) because I've isolated the commit which introduced the problem on my repo and it is the one containing the Appcompat's update.

Any clue on this? Anyone with the same problem out there?


答:
Python closures work exactly like this.

All free variables (i.e. variables which are neither local vars, nor arguments) are saved in the internal __closure__ property.

```<code>In [1394]: def make_counter():
      ...:     count = 0
      ...:     def counter():
      ...:         nonlocal count
      ...:         count += 1
      ...:         return count
      ...:     return counter
      ...:
In [1395]: f = make_counter()

In [1396]: f
Out[1396]: <function __main__.make_counter.<locals>.counter>

In [1397]: f.__closure__
Out[1397]: (<cell at 0x10af4bd98: int object at 0x10024ac20>,)

In [1399]: f.__closure__[0].cell_contents
Out[1399]: 0
</code>```

It just so happens that, in the first case, ints are immutable, so you are not modifying the original count.

When f is called, the inner function has its own environment frame is created which contains local variable count and is merged with __closure__.

Try calling f, and the counter is incremented:

```<code>In [1400]: f()
Out[1400]: 1

In [1401]: f.__closure__[0].cell_contents
Out[1401]: 1
</code>```

In the latter case, you're modifying an entry in the list, which is mutable. The reference is copied into the __closure__ property.

By the way, make_counter is a global function, and so has an empty __closure__ attribute:

```<code>In [1403]: print(make_counter.__closure__)
None
</code>```

Your second example, modified a bit:

```<code>In [1404]: def make_counter():
      ...:     count = [0]
      ...:     print(id(count))
      ...:     def counter():
      ...:         nonlocal count
      ...:         count[0] += 1
      ...:         return count[0]
      ...:     return counter
      ...:

In [1405]: f = make_counter()
4495587464

In [1408]: id(f.__closure__[0].cell_contents)
Out[1408]: 4495587464
</code>```

The id is identical.

Title: Why can a nested function using a regular variable can't change the namesake variable in the outer scope, while one using an item in a list can?

Body:
What is the reason that the nested function in the first example using a regular variable can't change the variable in the outer scope, while the one in the second example using an item in a list can?

I am looking for an answer from language design perspective.

Thanks.

Example one:

def make_counter():
    count = 0
    def counter():
        count += 1
        return count
    return counter

Example two:

def make_counter():
    count = [0]
    def counter():
        count[0] += 1
        return count[0]
    return counter

Body:
Python closures work exactly like this.

All free variables (i.e. variables which are neither local vars, nor arguments) are saved in the internal __closure__ property.

In [1394]: def make_counter():
      ...:     count = 0
      ...:     def counter():
      ...:         nonlocal count
      ...:         count += 1
      ...:         return count
      ...:     return counter
      ...:
In [1395]: f = make_counter()

In [1396]: f
Out[1396]: <function __main__.make_counter.<locals>.counter>

In [1397]: f.__closure__
Out[1397]: (<cell at 0x10af4bd98: int object at 0x10024ac20>,)

In [1399]: f.__closure__[0].cell_contents
Out[1399]: 0

It just so happens that, in the first case, ints are immutable, so you are not modifying the original count.

When f is called, the inner function has its own environment frame is created which contains local variable count and is merged with __closure__.

Try calling f, and the counter is incremented:

In [1400]: f()
Out[1400]: 1

In [1401]: f.__closure__[0].cell_contents
Out[1401]: 1

In the latter case, you're modifying an entry in the list, which is mutable. The reference is copied into the __closure__ property.

By the way, make_counter is a global function, and so has an empty __closure__ attribute:

In [1403]: print(make_counter.__closure__)
None

Your second example, modified a bit:

In [1404]: def make_counter():
      ...:     count = [0]
      ...:     print(id(count))
      ...:     def counter():
      ...:         nonlocal count
      ...:         count[0] += 1
      ...:         return count[0]
      ...:     return counter
      ...:

In [1405]: f = make_counter()
4495587464

In [1408]: id(f.__closure__[0].cell_contents)
Out[1408]: 4495587464

The id is identical.


问:
Convert Between 3D Skeletal Systems DirectX
I'm trying to convert between two different skeletal formats.  I have a hierarchical skeleton.

Now in one format, a given node's matrix is calculated by (DirectX) (recurively,
from bottom node to top, where matScale/matRotate/matTranslationFromParent are that particular nodes SRT):

appliedMatrices = appliedMatrices * matScale * matRotate * matTranslationFromParent;

But I need to convert it to a format that uses (recurively, from bottom node to top, where the translationIn is vector subtraction of (ParentPos - EndPartPos) and translation out is (EndPartPos - ParentPos), andmatScale/matRotate/matTranslationFromParent are that particular nodes SRT):

appliedMatrices = appliedMatrices * matScale * matTranslationOut * matRotate * matTranslationIn * matTranslationFromParent;

How do I convert from the first format to the second skeletal format (and back)?

答:
If we compare the two versions, we see that the following two parts need to match:

```<code>matRotate1 * matTranslationFromParent1
            = matTranslationOut * matRotate2 * matTranslationIn * matTranslationFromParent2
</code>```

Since matRotate1 and matRotate2 are the only rotations, those two have to be equal. So this is simple:

```<code>matRotate1 = matRotate2
</code>```

Then, for the two conversions, only one unknown is left:

```<code>//conversion 1 -> 2
matTranslationFromParent2 = (matTranslationOut * matRotate2 * matTranslationIn)^-1 * matRotate1 * matTranslationFromParent1
//conversion 2 -> 1
matTranslationFromParent1 = matRotate1^-1 * matTranslationOut * matRotate2 * matTranslationIn * matTranslationFromParent2
</code>```

If performance is critical, you can do these calculations only on the translation vectors and not the entire matrices.

Body:
If we compare the two versions, we see that the following two parts need to match:

matRotate1 * matTranslationFromParent1
            = matTranslationOut * matRotate2 * matTranslationIn * matTranslationFromParent2

Since matRotate1 and matRotate2 are the only rotations, those two have to be equal. So this is simple:

matRotate1 = matRotate2

Then, for the two conversions, only one unknown is left:

//conversion 1 -> 2
matTranslationFromParent2 = (matTranslationOut * matRotate2 * matTranslationIn)^-1 * matRotate1 * matTranslationFromParent1
//conversion 2 -> 1
matTranslationFromParent1 = matRotate1^-1 * matTranslationOut * matRotate2 * matTranslationIn * matTranslationFromParent2

If performance is critical, you can do these calculations only on the translation vectors and not the entire matrices.


问:
Unexpected Illegal Token in javascript from CDN - scripts contains only garbled text
I'm trying to host a webpage on my PC (Running Windows 7), and intend to use bootstrap css/javascript library, but I am having trouble using the bootstrap javascript library from a CDN. Here is a minimal example, index.html

<!DOCTYPE html>

    <title>Hello world</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" >

Hello world

```

<p>I have tried to host the page on localhost using both "python -m SimpleHTTPServer" and using node.js + express, but I get the same result, where I get the message "Uncaught SyntaxError: Unexpected token ILLEGAL" with reference to bootstrap.min.js:1 in chrome's javascript/html debugger.
If I open bootstrap.min.js it only shows lots of chinese signs (which is translated to meaningless text in google translate). All this goes for other CDN scripts also, such as socket.io.</p>

<p>*Edit 1:
I tried downloading the source and loading the bootstrap.min.js script locally
with </p>

<pre class="lang-html prettyprint-override"><code><script src="/js/bootstrap.min.js"></script>
</code>```

but I get the excact same problem as before.

答:
In my case the character coding made the same issue.
As soon as I forced the output to save as UTF-8, the issue gone.</p>

Body:
I'm trying to host a webpage on my PC (Running Windows 7), and intend to use bootstrap css/javascript library, but I am having trouble using the bootstrap javascript library from a CDN. Here is a minimal example, index.html

<!DOCTYPE html>

    <title>Hello world</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">

    <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.4/css/bootstrap.min.css" rel="stylesheet" >

Hello world

I have tried to host the page on localhost using both "python -m SimpleHTTPServer" and using node.js + express, but I get the same result, where I get the message "Uncaught SyntaxError: Unexpected token ILLEGAL" with reference to bootstrap.min.js:1 in chrome's javascript/html debugger.
If I open bootstrap.min.js it only shows lots of chinese signs (which is translated to meaningless text in google translate). All this goes for other CDN scripts also, such as socket.io.

*Edit 1:
I tried downloading the source and loading the bootstrap.min.js script locally
with

but I get the excact same problem as before.


问:
Count possible combination for coins array using Backtracking
The problem deals with the following.

For a given array

```<code>int coins[2] = { 1, 2 };
</code>```

It supposed to return 3.
Since there's the possible combinations.

```<code>1 + 1 + 1 + 1 = 4
1 + 1 + 2 = 4
2 + 2 = 4
</code>```

But my function returns 5, Any ideas why?

```<code>int change(int coins[], int n, int sum, int index);

int main() {
    int coins[2] = { 1, 2 };
    int c = change(coins, 2, 4, 0);
    printf("%d", c);
}

int change(int coins[], int n, int sum, int index) {
    if (sum == 0)
        return 1;
    if (sum < 0) {
        return -1;
    }

    for (int i = 0; i < n; i++) {
        if (coins[i] > sum)
            continue;
        int k = change(coins, n, sum - coins[i], index);
        if (k > -1)
            return k + 1;
    }
    return -1;
}
</code>```

答:
Try this at the code of line which calls your function:

```<code>int c = change(coins,2,4,0) - 1;
</code>```

and try with different cases.

Body:
The problem deals with the following.

For a given array

int coins[2] = { 1, 2 };

It supposed to return 3.
Since there's the possible combinations.

1 + 1 + 1 + 1 = 4
1 + 1 + 2 = 4
2 + 2 = 4

But my function returns 5, Any ideas why?

int change(int coins[], int n, int sum, int index);

int main() {
    int coins[2] = { 1, 2 };
    int c = change(coins, 2, 4, 0);
    printf("%d", c);
}

int change(int coins[], int n, int sum, int index) {
    if (sum == 0)
        return 1;
    if (sum < 0) {
        return -1;
    }

    for (int i = 0; i < n; i++) {
        if (coins[i] > sum)
            continue;
        int k = change(coins, n, sum - coins[i], index);
        if (k > -1)
            return k + 1;
    }
    return -1;
}

Body:
Try this at the code of line which calls your function:

int c = change(coins,2,4,0) - 1;

and try with different cases.


问:
VBA Access check if Parent form exists
in MS Acces I'm opening a Dialog Form from another Dialog form.

So formA, opens formB. But they user can potentially open formB as standalone, I would like to avoid having errors in this case.

I thought about checking for and Existing parent for formB.

But when I do it I get still get the Error 2452: The expression you entered has invalid to the Parent property.

I tried:

```<code>If Not IsError(Me.Parent) Then
    Me.Parent.cboTraining.Requery
End If
</code>```

And

```<code>If Not IsNull(Me.Parent) Then
    Me.Parent.cboTraining.Requery
End If
</code>```

答:
Here is another example.</p>

```<code>Const conObjStateClosed = 0
Const conDesignView = 0

If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
    If Forms(strFormName).CurrentView <> conDesignView Then
        MC_FormIsLoaded = True
    End If
End Ifere
</code>```

Title: VBA Access check if Parent form exists

Body:
in MS Acces I'm opening a Dialog Form from another Dialog form.

So formA, opens formB. But they user can potentially open formB as standalone, I would like to avoid having errors in this case.

I thought about checking for and Existing parent for formB.

But when I do it I get still get the Error 2452: The expression you entered has invalid to the Parent property.

I tried:

If Not IsError(Me.Parent) Then
    Me.Parent.cboTraining.Requery
End If

And

If Not IsNull(Me.Parent) Then
    Me.Parent.cboTraining.Requery
End If

Body:
Here is another example.

Const conObjStateClosed = 0
Const conDesignView = 0

If SysCmd(acSysCmdGetObjectState, acForm, strFormName) <> conObjStateClosed Then
    If Forms(strFormName).CurrentView <> conDesignView Then
        MC_FormIsLoaded = True
    End If
End Ifere


问:
What is an example where you use getBaseContext()?
if i understand correctly, you use getContext() to get the context of a view object. You use activity context or this if you want to create a new object that exist as long as activity exist, if not the activity wont be destroyed and eventually lead to memory leaks. You use getApplicationContext() if you want a context that is tied to the global lifecycle of the application and should be used wherever we need to create a object that exist beyond the current activity.

Is my understanding correct ?

But what is getBaseContext() and where do you use it exactly.. One simple and solid example would be great

答:
View.getContext() usually returns the context the view of current Activity. ContextWrapper.getBaseContext()is used while accessing a Context from within another context example Activity.

See at - [Difference between getContext() , getApplicationContext() , getBaseContext() and] "this"7]: Difference between getContext() , getApplicationContext() , getBaseContext() and "this"


问:
Private property can't access in this class in angular 2
Codes are below

```<code>export class HighlightDirective implements OnInit {
    private _defaultColor: 'green';

    ngOnInit():any {
        console.log(this._defaultColor);
    }
}
</code>```

I can't access _defaultColor property

答:
I think you better to declare your variable like this.</p>

```<code>private _defaultColor: string = 'green';
</code>```

Body:
Codes are below

export class HighlightDirective implements OnInit {
    private _defaultColor: 'green';

    ngOnInit():any {
        console.log(this._defaultColor);
    }
}

I can't access _defaultColor property

Body:
I think you better to declare your variable like this.

private _defaultColor: string = 'green';