问:
Firebase query in desc order based on timestamp
I am having trouble returning an array of objects in desc order from firebase and javascript with react native. I am essentially "joining" two firebase parents and then pushing them into an array.

```<code>async loadChats(userId){

 this.chatIdRef = firebase.database().ref("members");
 this.chatIdRef.off();
 this.chatsRef = firebase.database().ref("chats");
 this.chatsRef.off();

 items = [];
 this.chatIdRef.child(userId).on('child_added', snap => {
 this.chatsRef.child(snap.key).startAt().on('value', snapshot => {

    items.push({
      receiverId: snap.val().userId,
      timeStamp: snapshot.val().createdAt,
      name: snap.val().userName,
      key: snapshot.key
    });

  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(items)
  });

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

I have tried using "orderByChild('createdAt')" in my query but no luck.

答:
From the Firebase docs, queries with orderByChild return lists in the following order :-

Children with a null value for the specified child key come first.

Children with a value of false for the specified child key come next. If multiple children have a value of false, they are sorted lexicographically by key.

Children with a value of true for the specified child key come next. If multiple children have a value of true, they are sorted lexicographically by key.

Children with a numeric value come next, sorted in ascending order. If multiple children have the same numerical value for the specified child node, they are sorted by key.

Strings come after numbers and are sorted lexicographically in ascending order. If multiple children have the same value for the specified child node, they are ordered lexicographically by key.

Objects come last and are sorted lexicographically by key in ascending order.

So, from the above, please note that when your data has numerical values, it is returned in ascending order. Now that you know the order in which the data will be retrieved, you can just make changes to your client app to show the data in reverse ( in descending order ). Maybe reverse your list or something similar?

Body:
I am having trouble returning an array of objects in desc order from firebase and javascript with react native. I am essentially "joining" two firebase parents and then pushing them into an array.

async loadChats(userId){

 this.chatIdRef = firebase.database().ref("members");
 this.chatIdRef.off();
 this.chatsRef = firebase.database().ref("chats");
 this.chatsRef.off();

 items = [];
 this.chatIdRef.child(userId).on('child_added', snap => {
 this.chatsRef.child(snap.key).startAt().on('value', snapshot => {

    items.push({
      receiverId: snap.val().userId,
      timeStamp: snapshot.val().createdAt,
      name: snap.val().userName,
      key: snapshot.key
    });

  this.setState({
    dataSource: this.state.dataSource.cloneWithRows(items)
  });

  });
 });
}

I have tried using "orderByChild('createdAt')" in my query but no luck.


来源: stackexchange

问:
Object properties depending on the value of a field
I'm creating a JSON schema for a file that could look like this:

```<code>{
  "name": "My project",
  "debug": {
    "actions": [
      {
        "type": "type 1",
        "options": {
          "option 1 for type 1": "my-project",
          "option 2 for type 1": "whatever"
        }
      },
      {
        "type": "type 2",
        "options": {
          "option 1 for type 2": "my-project",
          "option 2 for type 2": "whatever",
          "option 3 for type 2": "whoohooo"
        }
      }
    ]
  }
}
</code>```

So basically, the "actions" can contain object that all have a "type" property and based on the value of this property, the options should display specific options. In summary, I'd like to be able to do some kind of mapping like:

```<code>"type 1": "#/definitions/type1Options",
"type 2": "#/definitions/type2Options"
</code>```

Is that possible?

答:
Yes, you can apply a schema based on the value of a field using implication.  Start with twos schemas.  Let's call them A and B.  Schema A validates to true if the the field is the required value (Example: type is type 1).  Schema B is what should validate to true if the first schema is true (Example: has specific options).

With those two schemas you can create a statement to conditionally apply schema B based on schema A.  Either A does not validate to true or B validates to true.  This is called implication.

The schema gets a little complicated, but it works.

```<code>{
  "type": "object",
  "properties": {
    "type": { "enum": ["type 1", "type 2"] },
    "options": {
      "type": "object",
      "properties": {
        "option 1 for type 1": { "type": "string" },
        "option 2 for type 1": { "type": "string" },
        "option 1 for type 2": { "type": "string" },
        "option 2 for type 2": { "type": "string" },
        "option 3 for type 2": { "type": "string" }
      }
    }
  },
  "allOf": [
    { "$ref": "#/definitions/type-1" },
    { "$ref": "#/definitions/type-2" }
  ],
  "definitions" {
    "type-1": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/type-is-type-1" } },
        { "$ref": "#/definitions/type-1-options" }
      ]
    },
    "type-2": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/type-is-type-2" } },
        { "$ref": "#/definitions/type-2-options" }
      ]
    },
    "type-is-type-1": {
      "properties": {
        "type": { "enum": ["type 1"] }
      }
    },
    "type-is-type-2": {
      "properties": {
        "type": { "enum": ["type 2"] }
      }
    },
    "type-1-options": {
      "properties": {
        "options": {
          "required": ["option 1 for type 1", "option 2 for type 1"]
        }
      }
    },
    "type-2-options": {
      "properties": {
        "options": {
          "required": ["option 1 for type 2", "option 2 for type 2", "option 3 for type 2"]
        }
      }
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm creating a JSON schema for a file that could look like this:

{
  "name": "My project",
  "debug": {
    "actions": [
      {
        "type": "type 1",
        "options": {
          "option 1 for type 1": "my-project",
          "option 2 for type 1": "whatever"
        }
      },
      {
        "type": "type 2",
        "options": {
          "option 1 for type 2": "my-project",
          "option 2 for type 2": "whatever",
          "option 3 for type 2": "whoohooo"
        }
      }
    ]
  }
}

So basically, the "actions" can contain object that all have a "type" property and based on the value of this property, the options should display specific options. In summary, I'd like to be able to do some kind of mapping like:

"type 1": "#/definitions/type1Options",
"type 2": "#/definitions/type2Options"

Is that possible?

Body:
Yes, you can apply a schema based on the value of a field using implication.  Start with twos schemas.  Let's call them A and B.  Schema A validates to true if the the field is the required value (Example: type is type 1).  Schema B is what should validate to true if the first schema is true (Example: has specific options).

With those two schemas you can create a statement to conditionally apply schema B based on schema A.  Either A does not validate to true or B validates to true.  This is called implication.

The schema gets a little complicated, but it works.

{
  "type": "object",
  "properties": {
    "type": { "enum": ["type 1", "type 2"] },
    "options": {
      "type": "object",
      "properties": {
        "option 1 for type 1": { "type": "string" },
        "option 2 for type 1": { "type": "string" },
        "option 1 for type 2": { "type": "string" },
        "option 2 for type 2": { "type": "string" },
        "option 3 for type 2": { "type": "string" }
      }
    }
  },
  "allOf": [
    { "$ref": "#/definitions/type-1" },
    { "$ref": "#/definitions/type-2" }
  ],
  "definitions" {
    "type-1": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/type-is-type-1" } },
        { "$ref": "#/definitions/type-1-options" }
      ]
    },
    "type-2": {
      "anyOf": [
        { "not": { "$ref": "#/definitions/type-is-type-2" } },
        { "$ref": "#/definitions/type-2-options" }
      ]
    },
    "type-is-type-1": {
      "properties": {
        "type": { "enum": ["type 1"] }
      }
    },
    "type-is-type-2": {
      "properties": {
        "type": { "enum": ["type 2"] }
      }
    },
    "type-1-options": {
      "properties": {
        "options": {
          "required": ["option 1 for type 1", "option 2 for type 1"]
        }
      }
    },
    "type-2-options": {
      "properties": {
        "options": {
          "required": ["option 1 for type 2", "option 2 for type 2", "option 3 for type 2"]
        }
      }
    }
  }
}


问:
Code Signing Certificates for OSX application using Adobe AIR SDK
Please someone help me how it possible to create apple certificate .p12 for OS application code sign using Adobe Air SDK.

Actually i want distribute app for the App Store for example if i have used local p12 certificate I'm getting code sign not object all time and secondly when try to upload app on the app store sandbox error.

So actually i want to know a way how i can create OS X .p12 certificate for Adobe Air desktop.

Thanks

答:
Like Bill Turner said, if you want to get a .p12 to distribute through the App Store you'll have to follow a similar process of signing up for the Apple Developer Program. When generating certficates, you'll have to select "macOS" instead of "iOS, tvOS, watchOS" on the Apple Developer portal: http://help.adobe.com/en_US/flex/mobileapps/WS064a3073e805330f6c6abf312e7545f65e-8000.html

If you already have your developer's certificates, there's a short guide titled Converting a developer certificate into a P12 file at
http://help.adobe.com/en_US/as3/iphone/WS144092a96ffef7cc-371badff126abc17b1f-7fff.html which will let you create a .p12 file.

Also, that's just the first step, there is a guide at https://helpx.adobe.com/flash-player/kb/posting-air-app-mac-app.html that walks you through the process of getting the AIR app ready for the App Store since there are a few steps you have to do manually. It also mentions that you use a self-signed certificate, you could get a warning message.


问:
Cannot read property '_root' of null in React Native when using NativeBase Toast component
I'm using NativeBase's Toast component to show a message after successfully submitting a form, but I get this error message in the console every time I run it.

```<code>_onSubmit error TypeError: Cannot read property '_root' of null
    at Function.show (ToastContainer.js:79)
    at InventoryItemAdd.js:40
    at tryCallOne (core.js:37)
    at core.js:123
    at JSTimers.js:98
    at Object.callTimer (JSTimersExecution.js:95)
    at Object.callImmediatesPass (JSTimersExecution.js:199)
    at Object.callImmediates (JSTimersExecution.js:214)
    at MessageQueue.js:222
    at guard (MessageQueue.js:46)
</code>```

Here's the JSX in my render function:

```<code><Container>
    <Navbar title="Add an Inventory Item" backArrow />
    <Content keyboardShouldPersistTaps="handled">
        <InventoryItemAddForm
            onSubmit={this._onSubmit}
            data={formData}
            enableReinitialize={true}
            initialValues={initialValues}
        />
    </Content>
    <FooterTabs />
</Container>
</code>```

And my _onSubmit function:

```<code>_onSubmit = ({name, inventoryTypeId, internalCode, description = "", measurementUnitId}) => {
    const {inventoryItemCreate, showErrors} = this.props

    return inventoryItemCreate({
        input: {
            name: name.trim(),
            inventoryTypeId,
            internalCode: internalCode.trim(),
            description: description.trim(),
            measurementUnitId,
        }
    })
        .then(({data: {inventoryItemCreate}}) => {
            dismissKeyboard()
            Toast.show({
                text: "Inventory item added successfully!",
                position: "bottom",
                buttonText: "Okay",
                type: "success",
                duration: 2000,
            })
            Actions.InventoryItemDetails({id: inventoryItemCreate.id})
        })
        .catch((error) => {
            console.log('_onSubmit error', error)
            showErrors()
        })
}
</code>```

答: I found out the root component of the app needs to be wrapped in nativebase's <Root> component in order for Toast notifications to work reliably.

Body:
I'm using NativeBase's Toast component to show a message after successfully submitting a form, but I get this error message in the console every time I run it.

_onSubmit error TypeError: Cannot read property '_root' of null
    at Function.show (ToastContainer.js:79)
    at InventoryItemAdd.js:40
    at tryCallOne (core.js:37)
    at core.js:123
    at JSTimers.js:98
    at Object.callTimer (JSTimersExecution.js:95)
    at Object.callImmediatesPass (JSTimersExecution.js:199)
    at Object.callImmediates (JSTimersExecution.js:214)
    at MessageQueue.js:222
    at guard (MessageQueue.js:46)

Here's the JSX in my render function:

<Container>
    <Navbar title="Add an Inventory Item" backArrow />
    <Content keyboardShouldPersistTaps="handled">
        <InventoryItemAddForm
            onSubmit={this._onSubmit}
            data={formData}
            enableReinitialize={true}
            initialValues={initialValues}
        />
    </Content>
    <FooterTabs />
</Container>

And my _onSubmit function:

_onSubmit = ({name, inventoryTypeId, internalCode, description = "", measurementUnitId}) => {
    const {inventoryItemCreate, showErrors} = this.props

    return inventoryItemCreate({
        input: {
            name: name.trim(),
            inventoryTypeId,
            internalCode: internalCode.trim(),
            description: description.trim(),
            measurementUnitId,
        }
    })
        .then(({data: {inventoryItemCreate}}) => {
            dismissKeyboard()
            Toast.show({
                text: "Inventory item added successfully!",
                position: "bottom",
                buttonText: "Okay",
                type: "success",
                duration: 2000,
            })
            Actions.InventoryItemDetails({id: inventoryItemCreate.id})
        })
        .catch((error) => {
            console.log('_onSubmit error', error)
            showErrors()
        })
}


问:
What are my options for navigating through subroutines?
Suppose I want a program Foo.py which has some arbitrary routines Bar(), Quux(), and Fizz(). Let's say that the usual order of execution from a procedural perspective should be Bar() -> Quux() -> Fizz(). However, Fizz() should conditionally call a function Buzz() depending on some runtime action, and calling Buzz() at any time during Fizz() should return the process back to Quux().

I have a fair understanding of how concurrent processes can be implemented in assembly using system calls depending on the architecture, but what options are available to me in Python, where I can't – and frankly would prefer not to – use lots of jumps and directly move an instruction pointer around? When searching for an answer, I found loops and recursion as a suggestion for going back in a program. I don't think a loop would work without stopping the Fizz() process to wait for the condition check for Buzz(), and I'm not sure how recursion could be implemented in this scenario either. (My Buzz() would be like a "Back" button on a GUI).

答:
You don't need anything fancy here. The usual structured programming tools will work fine. Have Fizz return after calling Buzz, and have it return an indicator saying whether to go back to Quux:

```<code>Bar()
while True:
    Quux()
    if not Fizz():
        break
</code>```

(If Buzz's only effect is supposed to be returning execution to Quux, don't have a Buzz at all and just return.)

Body:
You don't need anything fancy here. The usual structured programming tools will work fine. Have Fizz return after calling Buzz, and have it return an indicator saying whether to go back to Quux:

Bar()
while True:
    Quux()
    if not Fizz():
        break

(If Buzz's only effect is supposed to be returning execution to Quux, don't have a Buzz at all and just return.)


问:
Treating numerical variables as text
I was not sure how to title this question, so I'll go straight to the code for you to see what I mean. Really new into this, so bear with me!

I have this code:

```<code>1   #include <cs50.h>
2   #include <stdio.h>
3   #include <string.h>
4
5   int main(int argc, string argv[])
6   {
7
8   if (argc!=2)
9   {
10     printf("error!! Usage: ./caesar k\n");
11     return 1;
12   }
13
14   printf("Plaintext: ");
15   string text=get_string();
16
17   char k=argv[1][0];
18   int n=strlen(text);
19
20
21   for (int i=0; i<n; i++)
22   {
23     if(text[i]>='a' && text[i]<='z')
24     {
25         printf("Cyphertext: %c\n", text[i]+k);
26     }
27   }
28   }
</code>```

What's its purpose?
Well, given a text, it adds k to every character. Which means that, for abc, and k=1, the output would be bcd; for abc and k=3, output would be def.

Now, it is imperative that k is given as a command line argument.

What do I want to do?
Just take k (which is a number), add it to every character of the input string text, and voilà.
Since every letter is a number in ASCII, adding a number can change the character, so... it should work. [I am still trying to figure out how ASCII works, and when do char show up like charcters and not numbers... but anyway].

What is going on?
First, I am having trouble declaring k as an int or char. In line 17, -and although k is a number(!)- the IDE forces me to declare a string or char*: if I declare k as int I receive an error; if I declare char I receive an error too, unless I declare it not only as k=argv[1] but as k=argv[1][0], as shown in the code above.

Second, executing the code above, this is the input/output (the name of the program is caesar):

```<code>$./caesar
error!! Usage: ./caesar k

$./caesar 1
Plaintext: a
Cyphertext: (nothing...)
</code>```

Third, given the error above, I changed the code in line 25 from this:

```<code>printf("Cyphertext: %c\n", text[i]+k);
</code>```

to this:

```<code>printf("Cyphertext: %s\n", text[i]+k);
</code>```

which returned this error message:

```<code>caesar.c:25:38: error: format specifies type 'char *' but the argument has
type 'int' [-Werror,-Wformat]
        printf("Cyphertext: %s", text[i]+k);
                            ~~   ^~~~~~~~~
                            %d`
</code>```

error message I do not understand, given that neither text nor k are int.

Anyway, changing %c to %s did not work, so I tried with %i instead:

```<code>printf("Cyphertext: %i\n", text[i]+k)
</code>```

which at least returned something:

```<code>$./caesar 1
Plaintext: a
Cyphertext: 146

$./caesar 5
Plaintext: a
Cyphertext: 150
</code>```

So, basically, it is adding k to 150 -which is 'û' in ASCII, so...(?).

And, finally, apart from the fact the program returns a number I do not understand, I thought I could make it show up like letters/non-numerical characters adding this:

```<code>printf("Cyphertext: %i\n", (char)text[i]+k);
</code>```

but it actually does not, the program returns exactly the same last output shown above.

So well, this is a much longer question than I expected, but I hope someone in here has the patence and proficency to answer it.

Thank you very much!

答:
If you simply want to convert a digit ('0'-'9') to a number, you can simply subtract the Ascii code for '0' from your input.

```<code>char digit;
int num = digit - '0';
</code>```

You should check your input is within the range first.

```<code>if (digit < '0' || '9' < digit)
    //  error!!
</code>```

Title: Treating numerical variables as text

Body:
I was not sure how to title this question, so I'll go straight to the code for you to see what I mean. Really new into this, so bear with me!

I have this code:

1   #include <cs50.h>
2   #include <stdio.h>
3   #include <string.h>
4
5   int main(int argc, string argv[])
6   {
7
8   if (argc!=2)
9   {
10     printf("error!! Usage: ./caesar k\n");
11     return 1;
12   }
13
14   printf("Plaintext: ");
15   string text=get_string();
16
17   char k=argv[1][0];
18   int n=strlen(text);
19
20
21   for (int i=0; i<n; i++)
22   {
23     if(text[i]>='a' && text[i]<='z')
24     {
25         printf("Cyphertext: %c\n", text[i]+k);
26     }
27   }
28   }

What's its purpose?
Well, given a text, it adds k to every character. Which means that, for abc, and k=1, the output would be bcd; for abc and k=3, output would be def.

Now, it is imperative that k is given as a command line argument.

What do I want to do?
Just take k (which is a number), add it to every character of the input string text, and voilà.
Since every letter is a number in ASCII, adding a number can change the character, so... it should work. [I am still trying to figure out how ASCII works, and when do char show up like charcters and not numbers... but anyway].

What is going on?
First, I am having trouble declaring k as an int or char. In line 17, -and although k is a number(!)- the IDE forces me to declare a string or char*: if I declare k as int I receive an error; if I declare char I receive an error too, unless I declare it not only as k=argv[1] but as k=argv[1][0], as shown in the code above.

Second, executing the code above, this is the input/output (the name of the program is caesar):

$./caesar
error!! Usage: ./caesar k

$./caesar 1
Plaintext: a
Cyphertext: (nothing...)

Third, given the error above, I changed the code in line 25 from this:

printf("Cyphertext: %c\n", text[i]+k);

to this:

printf("Cyphertext: %s\n", text[i]+k);

which returned this error message:

caesar.c:25:38: error: format specifies type 'char *' but the argument has
type 'int' [-Werror,-Wformat]
        printf("Cyphertext: %s", text[i]+k);
                            ~~   ^~~~~~~~~
                            %d`

error message I do not understand, given that neither text nor k are int.

Anyway, changing %c to %s did not work, so I tried with %i instead:

printf("Cyphertext: %i\n", text[i]+k)

which at least returned something:

$./caesar 1
Plaintext: a
Cyphertext: 146

$./caesar 5
Plaintext: a
Cyphertext: 150

So, basically, it is adding k to 150 -which is 'û' in ASCII, so...(?).

And, finally, apart from the fact the program returns a number I do not understand, I thought I could make it show up like letters/non-numerical characters adding this:

printf("Cyphertext: %i\n", (char)text[i]+k);

but it actually does not, the program returns exactly the same last output shown above.

So well, this is a much longer question than I expected, but I hope someone in here has the patence and proficency to answer it.

Thank you very much!

Body:
If you simply want to convert a digit ('0'-'9') to a number, you can simply subtract the Ascii code for '0' from your input.

char digit;
int num = digit - '0';

You should check your input is within the range first.

if (digit < '0' || '9' < digit)
    //  error!!


问:
How do I replace only specific match in a match collection?
I am writing a solve method that solves an equation. The method will be recursive; searching for all outer parenthesis and when found recall solve for values inside the parenthesis and return the value when no parenthesis are found.

The process should look like this

```<code>20 * (6+3) / ((4+6)*9)
20 * 9 / ((4+6)*9)
20 * 9 / (10*9)
20 * 9 / 90
2
</code>```

As you see each match may have a different replacement value. I need to replace the parenthesis to what it evaluates to. Is there a way to do this. Here is what I have so far.

```<code>public int solve(string etq)
{
    Regex rgx = new Regex(@"\(([^()]|(?R))*\)");
    MatchCollection matches;

    matches = rgx.Matches(etq);

    foreach(Match m in matches)
    {
        //replace m in etq with unique value here
    }

    //calculations here
    return calculation
}
</code>```

Regex.replace(...) replaces all occurrences of the pattern specified. I want to be able to match to multiple scenario and replace each scenario with different output

答:
This would be an even simpler solution, using the match properties to replace using substring:

public static string Replace(this Match match, string source, string replacement)
{
   return source.Substring(0, match.Index) + replacement + source.Substring(match.Index + match.Length);
}

ContentLicense: CC BY-SA 4.0

Body:
I am writing a solve method that solves an equation. The method will be recursive; searching for all outer parenthesis and when found recall solve for values inside the parenthesis and return the value when no parenthesis are found.

The process should look like this

20 * (6+3) / ((4+6)*9)
20 * 9 / ((4+6)*9)
20 * 9 / (10*9)
20 * 9 / 90
2

As you see each match may have a different replacement value. I need to replace the parenthesis to what it evaluates to. Is there a way to do this. Here is what I have so far.

public int solve(string etq)
{
    Regex rgx = new Regex(@"\(([^()]|(?R))*\)");
    MatchCollection matches;

    matches = rgx.Matches(etq);

    foreach(Match m in matches)
    {
        //replace m in etq with unique value here
    }

    //calculations here
    return calculation
}

Regex.replace(...) replaces all occurrences of the pattern specified. I want to be able to match to multiple scenario and replace each scenario with different output


问:
argument by name color scheme pycharm
I am on PyCharm 2017.1.4 with Darcula theme.
I don't see how to change the color of the named argument, which is currently undistinguishable for me.
I have been into Editors > Colors & Fonts but it seems that everything is tunable apart from that.

答:
What type of file is this? In PyCharm you can configure different color settings for different types of files. Since this is tagged with PyCharm and Python, I'm going to assume it's a Python file. If it's a different kind of file, select the correct type of file instead of Python.

Settings | Editor | Color Scheme | Python | Keyword argument

Side note, I looked at Darcula, and what you show does not look like Darcula for Python. If you really are using Python, I would consider Restore Defaults... for your color scheme, or looking into it more because something seems off to me. This is what Darcula looks like to me.

Title: argument by name color scheme pycharm


问:
getElementID dont work on chrome
I have a code like this:

```<code>parent.document.getElementById("test").value ="1";
</code>```

but it doesnt work on chrome. The error is:

"Uncaught TypeError: Cannot call
  method 'getElementById' of undefined"

any help is apreciated thanks in advance! :)

答:
```<code>document.getElementById("test").value ="1";
</code>```

parent of the scope (window) is null

ContentLicense: CC BY-SA 2.5

Title: getElementID dont work on chrome

Body:
I have a code like this:

parent.document.getElementById("test").value ="1";

but it doesnt work on chrome. The error is:

"Uncaught TypeError: Cannot call
  method 'getElementById' of undefined"

any help is apreciated thanks in advance! :)

Body:
document.getElementById("test").value ="1";

parent of the scope (window) is null


问:
Using grep to recursively search through subdirectories for specific keyword inside specific filename
Im trying to look for the text Elapsed time inside a specific log file names vsim.log. Im not familiar with grep, but after some googling I found that grep -r will allow me to do recursively searches and grep -r "Elapsed time" will do recursive searches for that phrase within all files in my directory. According to this link, I can then do grep -r "Elapsed time" ./vsim* to recursively search through the directories for files starting with vsim and look inside those files for Elapsed time. However, when i tried this i get grep: No match. which i know is not true since I know the files exist there with those keywords. What am i messing up?

答:
Continuing from my comment, you can use find to locate the file vsim.log if you do not know its exact location and then use the -execdir option to find to grep the file for the term Elapsed time, e.g.

```<code>find path -type f -name "vsim.log" -execdir grep -H 'Elapsed time' '{}' +
</code>```

That will return the filename along with the matched text which you can simply parse to isolate the filename if desired. You can process all files that match if you anticipate more than one by feeding the results of the find command into a while read -r loop, e.g.

```<code>while read -r match; do
    # process "$match" as desired
    echo "Term 'Elapsed time' found in file ${match%:*}"
done < <(find path -type f -name "vsim.log" -execdir grep -H 'Elapsed time' '{}' +)
</code>```

Where:

find is the swiss-army knife for finding files on your system

path can be any relative or absolute path to search (e.g. $HOME or /home/dorojevets) to search all files in your home directory

the option -type f tells find to only locate files (see man find for link handling)

the option -name "foo" tell find to only locate files named foo (wildcards allowed)

the -exec and -execdir options allow you to execute the command that follows on each file (represented by '{}')

the grep -H 'Elapsed time' '{}' being the command to execute on each filename

the + being what tells find it has reached the end of the command (\; used with -exec)

finally, the ${match%:*} parameter expansion on the variable $match is used to parse the filename from filename:Elapsed time returned by grep -H (the %:* simply being used to trim everything to the first : from the right of $match)

Give that a try and compare the execution time to a recursive grep of the file tree. What you may be missing in this discussion, is that you use find if you know some part of the filename (or file mod time, or set of permissions, etc) that contains the information you need. It can search millions of files in a file tree vastly quicker than you can recursively grep every single file. If you have no clue what file may contain the needed info -- then use grep and just wait...

Body:
Continuing from my comment, you can use find to locate the file vsim.log if you do not know its exact location and then use the -execdir option to find to grep the file for the term Elapsed time, e.g.

find path -type f -name "vsim.log" -execdir grep -H 'Elapsed time' '{}' +

That will return the filename along with the matched text which you can simply parse to isolate the filename if desired. You can process all files that match if you anticipate more than one by feeding the results of the find command into a while read -r loop, e.g.

while read -r match; do
    # process "$match" as desired
    echo "Term 'Elapsed time' found in file ${match%:*}"
done < <(find path -type f -name "vsim.log" -execdir grep -H 'Elapsed time' '{}' +)

Where:

find is the swiss-army knife for finding files on your system

path can be any relative or absolute path to search (e.g. $HOME or /home/dorojevets) to search all files in your home directory

the option -type f tells find to only locate files (see man find for link handling)

the option -name "foo" tell find to only locate files named foo (wildcards allowed)

the -exec and -execdir options allow you to execute the command that follows on each file (represented by '{}')

the grep -H 'Elapsed time' '{}' being the command to execute on each filename

the + being what tells find it has reached the end of the command (\; used with -exec)

finally, the ${match%:*} parameter expansion on the variable $match is used to parse the filename from filename:Elapsed time returned by grep -H (the %:* simply being used to trim everything to the first : from the right of $match)

Give that a try and compare the execution time to a recursive grep of the file tree. What you may be missing in this discussion, is that you use find if you know some part of the filename (or file mod time, or set of permissions, etc) that contains the information you need. It can search millions of files in a file tree vastly quicker than you can recursively grep every single file. If you have no clue what file may contain the needed info -- then use grep and just wait...


问:
visual code set typescript version locally
I have an angular 4 (cli)/ nodejs app and i use typescript both of two. They are in a same folder, like this:

app

-- public

-- server

And in visuel code I usaly open the root folder (app) to easily edit files in any folder (public, server).

What I need is, how to config visual code to use different typescript versions in public and in server folder?

In public I need typescript 2.3.4 and in server I need 2.4+. Is there a solution for this?

答:
In general, the client and the server should be different projects. They can be located in the same dir (app in your case), but each project (public and server) should have its own package.json, here you can specify a particular version of tsc in the devDependencies section.

VS Code has an integrated terminal (see the menu View). So you can open two terminals inside the IDE - one in the public dir and another in the server one. Then, if your package.json files have a script command defined as

```<code>"tsc": "tsc"
</code>```

you can run tsc in each terminal window like this:

```<code>npm run tsc
</code>```

It'll use the local tsc version defined in the package.json located in the current dir.

Body:
In general, the client and the server should be different projects. They can be located in the same dir (app in your case), but each project (public and server) should have its own package.json, here you can specify a particular version of tsc in the devDependencies section.

VS Code has an integrated terminal (see the menu View). So you can open two terminals inside the IDE - one in the public dir and another in the server one. Then, if your package.json files have a script command defined as

"tsc": "tsc"

you can run tsc in each terminal window like this:

npm run tsc

It'll use the local tsc version defined in the package.json located in the current dir.


问:
How to iterate a string literal type in typescript
How can I iterate a string literal type in typescript?

For example i define this type

```<code>type Name = "Bill Gates" | "Steve Jobs" | "Linus Torvalds";
</code>```

I want to iterate like this

```<code>for (let name of Name) {
    console.log("Possible name: " + name);
}
</code>```

Or is this simply not possible in typescript?

答:
Since typescript 2.4 it is possible to use string typed enums. These enums can easily be iterated:

https://blogs.msdn.microsoft.com/typescript/2017/06/27/announcing-typescript-2-4/

Body:
How can I iterate a string literal type in typescript?

For example i define this type

type Name = "Bill Gates" | "Steve Jobs" | "Linus Torvalds";

I want to iterate like this

for (let name of Name) {
    console.log("Possible name: " + name);
}

Or is this simply not possible in typescript?


问:
How to check if Notepad++ is installed using Powershell
I am writing some powershell script to check if notepad++ is installed on my laptop. Though I'm having some issues with this.

Here's the code:

```<code># Variable(s)

$regkey = "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Notepad++"
#
# Check if Notepad ++ is already installed.

If($regkey)
{
    Write-output "Notepad++ is already installed on your machine."
}
Else
{
    Write-Output "Notepad++ is not installed on your machine."
}
</code>```

I uninstalled notepad++ manually. I then executed the script and the output message that was displayed was that notepad++ is installed, when it isn't. Why is this?

Any help will be much appreciated.

答:
```<code>$w64=Get-ItemProperty HKLM:\Software\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall\* | where-Object DisplayName -like 'NotePad++*'
$w32=Get-ItemProperty HKLM:\Software\Microsoft\Windows\CurrentVersion\Uninstall\*  | where-Object DisplayName -like 'NotePad++*'
if ($w64 -or $w32)
{
    Write-output "Notepad++ is already installed on your machine."
}
Else{
    Write-Output "Notepad++ is not installed on your machine."
}
</code>```

Body:
I am writing some powershell script to check if notepad++ is installed on my laptop. Though I'm having some issues with this.

Here's the code:

# Variable(s)

$regkey = "HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Notepad++"
#
# Check if Notepad ++ is already installed.

If($regkey)
{
    Write-output "Notepad++ is already installed on your machine."
}
Else
{
    Write-Output "Notepad++ is not installed on your machine."
}

I uninstalled notepad++ manually. I then executed the script and the output message that was displayed was that notepad++ is installed, when it isn't. Why is this?

Any help will be much appreciated.


问:
How to generate sequence number for members of each group
I have a table that is similar to this:

```<code>CREATE TABLE dbo.ReportGroups (
    ReportName     VARCHAR(50)    NOT NULL,
    GroupName      VARCHAR(50)    NOT NULL,
    SequenceNumber SMALLINT       NOT NULL,
    CONSTRAINT PK_ReportGroups PRIMARY KEY CLUSTERED (ReportName, GroupName)
)
</code>```

I'm importing into this table from a flat file that just contains the report names and group names, so I need to generate the SequenceNumber. For each report the sequence numbers should restart at 1.

I've seen how to do this with a script task for normal sequence numbers, but restarting for each new report name doesn't seem to be out there. My guess is that I'll need to use the Sort transform and then add code to check for changes in the report name(?) Has anyone done something like this? Any sample code to share?

答:
Yes, I have done this just as you describe; sort the data in the dataflow and use a script to assign the sequence numbers, re-starting every time a certain column's value changed.

And no I don't have any sample code handy.  It was a long time ago.

If I were doing this today, and were able to use a staging table, I would import the data as-is into a staging table, and then call a stored proc that used ROW_NUMBER() to assign the sequence numbers in the destination table.

Body:
I have a table that is similar to this:

CREATE TABLE dbo.ReportGroups (
    ReportName     VARCHAR(50)    NOT NULL,
    GroupName      VARCHAR(50)    NOT NULL,
    SequenceNumber SMALLINT       NOT NULL,
    CONSTRAINT PK_ReportGroups PRIMARY KEY CLUSTERED (ReportName, GroupName)
)

I'm importing into this table from a flat file that just contains the report names and group names, so I need to generate the SequenceNumber. For each report the sequence numbers should restart at 1.

I've seen how to do this with a script task for normal sequence numbers, but restarting for each new report name doesn't seem to be out there. My guess is that I'll need to use the Sort transform and then add code to check for changes in the report name(?) Has anyone done something like this? Any sample code to share?


问:
Debugging Content Security Policy violation in Google Chrome DEV
I'm developing a Cordova Android application, and due to Content Security Policy restrictions, I often get several of this errors, some of which I know how to handle.

The question with Google Chrome Developing Tools, is that it simply mentions the error, without saying which part of the code triggers such error. The information is very vague.

How to know which part of the code triggered this error?

答:
In the 'Sources' tab in dev tool, in the sidebar on the right, theres a pause button.
Clicking that will dropdown a checkbox saying 'Pause On Caught Exceptions'.
If you check that, the browser should stop execution at the point of exception.

If you have multiple exceptions on that site, you might have to press F8 in chrome dev a couple of times to get to the right error you're looking for.


问:
Badge - data structure / models?
I'm trying to figure out how one would set up a database and/or model in order to handle various badges. Lets take the Stack Overflow badges as an example. There are different rules for each and some might be just a variable different (like 10 comments vs 100 comments).

My question is how do you set up this type validation/check within an application? Should each badge have its own method?

答:
That is how I would implement it if I need to:

I'll set up some queue manager (there are a lot of such software) and write a broker, that will process the messages from the queue.

Each time any event occurs, such as: You viewed a topic, you edited your comment, you edited your answer, you edited another person answer, you upvoted, etc etc - you collect one more messages, with event description. Yes, it will be really huge amount of messages there.

After you collect that huge amount of messages - you can start a broker that will process messages by schedule or in real time.

With this schema you could extend a broker to as complex badges as you want.

Title: Badge - data structure / models?


问:
Dynamically append DOM element and if already added then no need to append
I am trying to dynamically add a div to parent div when a button is clicked.But once it is created another same child div should not be created again when the button is clicked. So this is what I tried to do

```<code>$("#b1").click(function(){
        $("#d1").has("#d2").remove($(this));
        $("#d1").append($("<div>",{id:"d2",text:"Dynamically added Second DIV"}));
    });
</code>```

It is working but I am getting "TypeError: expr.replace is not a function" in the console...Please suggest.
Thank you...

答:
function addElement() {
  var parent = $('#container')["0"];
  var elem = document.createElement('div');
  elem.setAttribute('id', 'child');
  var text = document.createTextNode("child");
  elem.append(text);
  if(!parent.children.length > 0) {
    parent.append(elem);
  }

}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">Parent</div>
<button type="button" id="button" onclick="addElement();">Click</button></code>```

Body:
I am trying to dynamically add a div to parent div when a button is clicked.But once it is created another same child div should not be created again when the button is clicked. So this is what I tried to do

$("#b1").click(function(){
        $("#d1").has("#d2").remove($(this));
        $("#d1").append($("
",{id:"d2",text:"Dynamically added Second DIV"}));
    });

It is working but I am getting "TypeError: expr.replace is not a function" in the console...Please suggest.
Thank you...

Body:
function addElement() {
  var parent = $('#container')["0"];
  var elem = document.createElement('div');
  elem.setAttribute('id', 'child');
  var text = document.createTextNode("child");
  elem.append(text);
  if(!parent.children.length > 0) {
    parent.append(elem);
  }

}

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="container">Parent</div>
<button type="button" id="button" onclick="addElement();">Click</button>


问:
How to group by multiple values in same column in Oracle DB
I have a table for user access to a software application. A user may have multiple accesses with different aspects of the application denoted by alphanumeric ids. Similarly, multiple users may have same or different set of accesses.
For eg.

```<code>Table ACCESSTAB
USER             |       USERACCESS
-----------------------------------------
Cust1            |       BA1
Cust1            |       BB2
Cust2            |       BA1
Cust2            |       BB2
Cust3            |       CB1
Cust3            |       BA1
</code>```

I would like to group the customers based the same set of accesses. For eg:

```<code>USER             |       GROUP
-----------------------------------------
Cust1            |       Group1
Cust2            |       Group1
Cust3            |       Group2
</code>```

Currently, I have table created for some important users for this purpose as follows:

```<code>Table USERGROUP
GROUP             |       ACCESS
-----------------------------------------
Group1            |       BA1
Group1            |       BB2
Group2            |       CB1
Group2            |       BA1
</code>```

And the below query comparing both tables.

```<code>select a.USER,u.GROUP from ACCESSTAB a, USERGROUP u where not exists
(select USERACCESS from ACCESSTAB where USER=a.USER order by 1
MINUS
select ACCESS from USERGROUP where GROUP=u.GROUP order by 1)
</code>```

I would like to group the users without using the USERGROUP table as it is difficult to maintain for all users,not to mention addition of accesses would require manual configuration. Performance doesnt matter.

Any advice/assistance is welcome. Thanks in advance.

答:
It looks your relationships are:

a user has one or more privileges

a user belongs to one or more groups

a group has one or more privileges

It's not perfectly clear about what you mean when you said "difficult to maintain for all users", but it looks like you might be saying the set of user's privileges (#1) and the set of group's privileges (#3) must be equal sets and you're concerned that keeping them consistent with each other would be difficult. If I'm correct in my assumptions, then I would suggest you eliminate rule #1, drop the ACCESSTAB table, and rename the USERGROUP table to GROUP_ACCESS. That will eliminate the update anomaly.

Body:
I have a table for user access to a software application. A user may have multiple accesses with different aspects of the application denoted by alphanumeric ids. Similarly, multiple users may have same or different set of accesses.
For eg.

Table ACCESSTAB
USER             |       USERACCESS
-----------------------------------------
Cust1            |       BA1
Cust1            |       BB2
Cust2            |       BA1
Cust2            |       BB2
Cust3            |       CB1
Cust3            |       BA1

I would like to group the customers based the same set of accesses. For eg:

USER             |       GROUP
-----------------------------------------
Cust1            |       Group1
Cust2            |       Group1
Cust3            |       Group2

Currently, I have table created for some important users for this purpose as follows:

Table USERGROUP
GROUP             |       ACCESS
-----------------------------------------
Group1            |       BA1
Group1            |       BB2
Group2            |       CB1
Group2            |       BA1

And the below query comparing both tables.

select a.USER,u.GROUP from ACCESSTAB a, USERGROUP u where not exists
(select USERACCESS from ACCESSTAB where USER=a.USER order by 1
MINUS
select ACCESS from USERGROUP where GROUP=u.GROUP order by 1)

I would like to group the users without using the USERGROUP table as it is difficult to maintain for all users,not to mention addition of accesses would require manual configuration. Performance doesnt matter.

Any advice/assistance is welcome. Thanks in advance.


问:
how to pass variable with require() in PHP
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

```<code><?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."<br>".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>
</code>```

b.php

```<code><?php
echo "<h1>".$msg."</h1>
<form action='' method='post'>
Username: <input type='text' name='username'><br>
Password: <input type='text' name='password'><br>
<input type='submit' name='submit'>
</form>
"

?>
</code>```

答:
Using $_SESSION will allow you to pass data between different files.

in a.php

```<code>$_SESSION['myName'] = "John";
</code>```

in b.php

```<code>echo $_SESSION['myName']
</code>```

Body:
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

<?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."
".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>

b.php

<?php
echo "
".$msg."

<form action='' method='post'>
Username: <input type='text' name='username'>

Password: <input type='text' name='password'>

<input type='submit' name='submit'>
</form>
"

?>

Body:
Using $_SESSION will allow you to pass data between different files.

in a.php

$_SESSION['myName'] = "John";

in b.php

echo $_SESSION['myName']


问:
What Automatic Resource Management alternatives exist for Scala?
I have seen many examples of ARM (automatic resource management) on the web for Scala. It seems to be a rite-of-passage to write one, though most look pretty much like one another. I did see a pretty cool example using continuations, though.

At any rate, a lot of that code has flaws of one type or another, so I figured it would be a good idea to have a reference here on Stack Overflow, where we can vote up the most correct and appropriate versions.

答:
How about using Type classes</p>

```<code>trait GenericDisposable[-T] {
   def dispose(v:T):Unit
}
...

def using[T,U](r:T)(block:T => U)(implicit disp:GenericDisposable[T]):U = try {
   block(r)
} finally {
   Option(r).foreach { r => disp.dispose(r) }
}
</code>```

Body:
How about using Type classes

trait GenericDisposable[-T] {
   def dispose(v:T):Unit
}
...

def using[T,U](r:T)(block:T => U)(implicit disp:GenericDisposable[T]):U = try {
   block(r)
} finally {
   Option(r).foreach { r => disp.dispose(r) }
}


问:
CLLocationManager works only once
I'm new to swift - currently, my current location is only output once in the console when I first call setupLocationManager() on init through override func awakeFromNib(). When I want it to output my new location by calling locationManager.startUpdatingLocation() when I click a button with the method updateLocation(), it prints an error. Any way to fix this? All help is appreciated.

```<code>import Cocoa
import CoreLocation

class StatusMenuController: NSObject, CLLocationManagerDelegate {

@IBOutlet weak var statusMenu: NSMenu!
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
var locationManager:CLLocationManager!
var currentLocation:CLLocation?

@IBAction func quitClicked(_ sender: NSMenuItem) {
    NSApplication.shared().terminate(self)
}

@IBAction func updateClicked(_ sender: NSMenuItem) {
    updateLocation()
}

func updateLocation() {
    locationManager.startUpdatingLocation()
}

override func awakeFromNib() {
    statusItem.menu = statusMenu
    let icon = NSImage(named: "statusIcon")
    icon?.isTemplate = true
    statusItem.image = icon
    statusItem.menu = statusMenu
    setupLocationManager()
}

func setupLocationManager(){
    locationManager = CLLocationManager()
    locationManager?.delegate = self
    //self.locationManager?.requestAlwaysAuthorization()
    locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager?.startUpdatingLocation()

}

// Below method will provide you current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if currentLocation == nil {
        currentLocation = locations.last
        locationManager?.stopMonitoringSignificantLocationChanges()
        let locationValue:CLLocationCoordinate2D = manager.location!.coordinate

        print(locationValue)

        locationManager?.stopUpdatingLocation()
    }
}

// Below Method will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error")
}

}
</code>```

答:
There is an if condition in the code which suspends updating the location after the location is set once (if currentLocation == nil). You have to reset currentLocation to nil before restarting the manager.

```<code>@IBAction func updateClicked(_ sender: NSMenuItem) {
    currentLocation = nil
    updateLocation()
}
</code>```

Title: CLLocationManager works only once

Body:
I'm new to swift - currently, my current location is only output once in the console when I first call setupLocationManager() on init through override func awakeFromNib(). When I want it to output my new location by calling locationManager.startUpdatingLocation() when I click a button with the method updateLocation(), it prints an error. Any way to fix this? All help is appreciated.

import Cocoa
import CoreLocation

class StatusMenuController: NSObject, CLLocationManagerDelegate {

@IBOutlet weak var statusMenu: NSMenu!
let statusItem = NSStatusBar.system().statusItem(withLength: NSVariableStatusItemLength)
var locationManager:CLLocationManager!
var currentLocation:CLLocation?

@IBAction func quitClicked(_ sender: NSMenuItem) {
    NSApplication.shared().terminate(self)
}

@IBAction func updateClicked(_ sender: NSMenuItem) {
    updateLocation()
}

func updateLocation() {
    locationManager.startUpdatingLocation()
}

override func awakeFromNib() {
    statusItem.menu = statusMenu
    let icon = NSImage(named: "statusIcon")
    icon?.isTemplate = true
    statusItem.image = icon
    statusItem.menu = statusMenu
    setupLocationManager()
}

func setupLocationManager(){
    locationManager = CLLocationManager()
    locationManager?.delegate = self
    //self.locationManager?.requestAlwaysAuthorization()
    locationManager?.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager?.startUpdatingLocation()

}

// Below method will provide you current location.
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

    if currentLocation == nil {
        currentLocation = locations.last
        locationManager?.stopMonitoringSignificantLocationChanges()
        let locationValue:CLLocationCoordinate2D = manager.location!.coordinate

        print(locationValue)

        locationManager?.stopUpdatingLocation()
    }
}

// Below Method will print error if not able to update location.
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
    print("Error")
}

}

Body:
There is an if condition in the code which suspends updating the location after the location is set once (if currentLocation == nil). You have to reset currentLocation to nil before restarting the manager.

@IBAction func updateClicked(_ sender: NSMenuItem) {
    currentLocation = nil
    updateLocation()
}


问:
How to watch store values from vuex?
I am using vuex and vuejs 2 together.

I am new to vuex, I want to watch a store variable change.

I want to add the watch function in my vue component

This is what I have so far:

```<code>import Vue from 'vue';
import {
  MY_STATE,
} from './../../mutation-types';

export default {
  [MY_STATE](state, token) {
    state.my_state = token;
  },
};
</code>```

I want to know if there are any changes in the my_state

How do I watch store.my_state in my vuejs component?

答:
I think the asker wants to use watch with Vuex. </p>

```<code>this.$store.watch(
      (state)=>{
        return this.$store.getters.your_getter
      },
      (val)=>{
       //something changed do something

      },
      {
        deep:true
      }
      );
</code>```

Title: How to watch store values from vuex?

Body:
I am using vuex and vuejs 2 together.

I am new to vuex, I want to watch a store variable change.

I want to add the watch function in my vue component

This is what I have so far:

import Vue from 'vue';
import {
  MY_STATE,
} from './../../mutation-types';

export default {
  [MY_STATE](state, token) {
    state.my_state = token;
  },
};

I want to know if there are any changes in the my_state

How do I watch store.my_state in my vuejs component?

Body:
I think the asker wants to use watch with Vuex.

this.$store.watch(
      (state)=>{
        return this.$store.getters.your_getter
      },
      (val)=>{
       //something changed do something

      },
      {
        deep:true
      }
      );


问:
Send Mail using PHP failing
I am using the same php code I have always used to try and send a form via email and I am getting this message:

Warning: mail() [function.mail]:
  Failed to connect to mailserver at
  "localhost" port 25, verify your
  "SMTP" and "smtp_port" setting in
  php.ini or use ini_set() in
  sendMailSuscribete.php on line 44

this are lines 40 - 54:

```<code>$header .= "From: $email" . "\r\n";
$header .= "Reply-To: $email" . "\r\n";
$header .= "Return-Path: $email" . "\r\n";

if(mail($to, $subject, $msg, $header)){
    //Message sent!
    redirect("http://www.domain.com/suscribete.html");
}else{
    // Display error message if the message failed to send
    echo "
    <div class=\"MsgError\">
        <h1>Error…</h1>
        <p>Disculpa <b><?=$name;?></b>, tu mensaje falló en ser enviado. Por favor vuelve a intentar.</p>
</div>";
}
</code>```

I already checked using phpinfo() and I know that the smtp is set to localhost and the port it uses is 25 so I really have no idea what the error may be.

Update
I forgot to say it is running on a Windows server and this php file is the one I've always used for Unix servers, should it contain something different?

答:
mail cannot send e-mails directly (at least not on Windows), it needs an SMTP server. There is no SMTP server running on the host on which the PHP-Script is being executed. Solutions are:

Use a library that can send e-mails directly using SMTP, like PHPMailer or Swiftmailer (github repo).

Edit the php.ini directives to point to a SMTP server that accepts e-mails from you. Ask your hosting provider if you do not know which one to use.

Set up an SMTP server on localhost.

Point 1. is a good idea, because those libraries provide abstractions that make it unnecessary to deal with low level stuff like putting MIME messages together correctly. Point 2. is probably the least trouble. I advice against Point 3. unless you are serious about administering an e-mail server by yourself.

Title: Send Mail using PHP failing

Body:
I am using the same php code I have always used to try and send a form via email and I am getting this message:

Warning: mail() [function.mail]:
  Failed to connect to mailserver at
  "localhost" port 25, verify your
  "SMTP" and "smtp_port" setting in
  php.ini or use ini_set() in
  sendMailSuscribete.php on line 44

this are lines 40 - 54:

$header .= "From: $email" . "\r\n";
$header .= "Reply-To: $email" . "\r\n";
$header .= "Return-Path: $email" . "\r\n";

if(mail($to, $subject, $msg, $header)){
    //Message sent!
    redirect("http://www.domain.com/suscribete.html");
}else{
    // Display error message if the message failed to send
    echo "

Error…

Disculpa <?=$name;?>, tu mensaje falló en ser enviado. Por favor vuelve a intentar.

";
}

I already checked using phpinfo() and I know that the smtp is set to localhost and the port it uses is 25 so I really have no idea what the error may be.

Update
I forgot to say it is running on a Windows server and this php file is the one I've always used for Unix servers, should it contain something different?


问:
How to print FF (form feed) character?
I do some old report conversion and need to add "new page" FF character.
What's the syntax to print FF character from Python?</p>

答:
Like this *Wikipedia article says Form Feed (FF) has decimal value 12 in ASCII. Which is 0x0c in hex:

Form feed is a page-breaking ASCII control character. It forces the
  printer to eject the current page and to continue printing at the top
  of another. Often, it will also cause a carriage return. The form feed
  character code is defined as 12 (0xC in hexadecimal) (..) In the C programming language (and other languages derived from C), the form feed character is represented as '\f'.

So you can:

```<code>print('\x0c',end='')
</code>```

Or you can use - like @martineau says - use '\f':

```<code>print('\f',end='')
</code>```

The end='' is used to prevent Python from printing an additional new line after the form feed character.

Note that it depends on the console (or the device that receives the stream) how the Form Feed is handled. Some consoles might ignore it. Others print a few blank lines, and a printer might for instance decide to start a new page.

Title: How to print FF (form feed) character?

Body:
Like this *Wikipedia article says Form Feed (FF) has decimal value 12 in ASCII. Which is 0x0c in hex:

Form feed is a page-breaking ASCII control character. It forces the
  printer to eject the current page and to continue printing at the top
  of another. Often, it will also cause a carriage return. The form feed
  character code is defined as 12 (0xC in hexadecimal) (..) In the C programming language (and other languages derived from C), the form feed character is represented as '\f'.

So you can:

print('\x0c',end='')

Or you can use - like @martineau says - use '\f':

print('\f',end='')

The end='' is used to prevent Python from printing an additional new line after the form feed character.

Note that it depends on the console (or the device that receives the stream) how the Form Feed is handled. Some consoles might ignore it. Others print a few blank lines, and a printer might for instance decide to start a new page.


问:
MySQL Advanced multidimensional query with CONCAT, JSON and IF statement
I working on one complex listing from database and decide to do all possible requests via one query.

Here is working example:

```<code>"SELECT
    `c`.`categories_id`,
    `c`.`categories_status`,
    IF(`c`.`categories_status` = 1, 'Active', 'Not Active') AS `categories_status_name`,
    TRIM(`cd`.`categories_name`) AS `categories_name`,
    TRIM(`cd`.`concert_date`) AS `concert_date`,
    TRIM(`cd`.`concert_time`) AS `concert_time`,
    TRIM((
        SELECT
            CONCAT(
                '{\"total_quantity\":',
                    SUM(CASE WHEN `p`.`products_quantity` > 0 THEN `p`.`products_quantity` ELSE 0 END),
                ',\"total_price\":\"',
                    SUM(`p`.`products_price`),
                '\"}'
            )
        FROM
            `products_to_categories` `ptc`,
            `products` `p`
        WHERE
            `ptc`.`section_id` = `cd`.`section_id`
        AND
            `p`.`products_id` = `ptc`.`products_id`
    )) AS `products_available`,
    TRIM((
        SELECT
            CONCAT(
                '{\"total_quantity\":',
                    SUM(CASE WHEN `op`.`products_quantity` > 0 THEN `op`.`products_quantity` ELSE 0 END),
                ',\"total_price\":\"',
                    SUM(`op`.`final_price`),
                '\"}'
            )
        FROM
            `products_to_categories` `ptc`,
            `orders_products` `op`
        WHERE
            `ptc`.`section_id` = `cd`.`section_id`
        AND
            `op`.`products_id` = `ptc`.`products_id`
        AND
            `op`.`orders_products_status` != 1
    )) AS `products_sold`,
    TRIM((
        SELECT
            CONCAT(
                '{\"total_quantity\":',
                    SUM(CASE WHEN `op`.`products_quantity` > 0 THEN `op`.`products_quantity` ELSE 0 END),
                ',\"total_price\":\"',
                    SUM(`op`.`final_price`),
                '\"}'
            )
        FROM
            `products_to_categories` `ptc`,
            `orders_products` `op`
        WHERE
            `ptc`.`section_id` = `cd`.`section_id`
        AND
            `op`.`products_id` = `ptc`.`products_id`
        AND
            `op`.`orders_products_status` = 1
    )) AS `products_pending`
FROM
    `categories` `c`,
    `categories_description` `cd`
WHERE
    `c`.`categories_id`  = `c`.`section_id`
AND
    `cd`.`categories_id`  = `c`.`categories_id`
GROUP BY `c`.`categories_id`
ORDER BY `c`.`categories_status` DESC;"
</code>```

This work great but my main problem is how to do check IF/ELSE or CASE WHEN for custom defined new fields: products_available, products_sold and products_pending?

Problem is that if products not exists inside table orders_products I not get my generated JSON and that's made a small conflict inside PHP.

I can do check in PHP but want to avoid that part and just print JSON like:

```<code>{"total_quantity":0,"total_price":"0.0000"}
</code>```

答:
```<code>FROM
    `products_to_categories` `ptc`,
    `orders_products` `op`
    *

WHERE `products_id` =
(SELECT COALESCE(`products_id`,0))

*
AND
    `ptc`.`section_id` = `cd`.`section_id`
</code>```

Body:
I working on one complex listing from database and decide to do all possible requests via one query.

Here is working example:

"SELECT
    `c`.`categories_id`,
    `c`.`categories_status`,
    IF(`c`.`categories_status` = 1, 'Active', 'Not Active') AS `categories_status_name`,
    TRIM(`cd`.`categories_name`) AS `categories_name`,
    TRIM(`cd`.`concert_date`) AS `concert_date`,
    TRIM(`cd`.`concert_time`) AS `concert_time`,
    TRIM((
        SELECT
            CONCAT(
                '{\"total_quantity\":',
                    SUM(CASE WHEN `p`.`products_quantity` > 0 THEN `p`.`products_quantity` ELSE 0 END),
                ',\"total_price\":\"',
                    SUM(`p`.`products_price`),
                '\"}'
            )
        FROM
            `products_to_categories` `ptc`,
            `products` `p`
        WHERE
            `ptc`.`section_id` = `cd`.`section_id`
        AND
            `p`.`products_id` = `ptc`.`products_id`
    )) AS `products_available`,
    TRIM((
        SELECT
            CONCAT(
                '{\"total_quantity\":',
                    SUM(CASE WHEN `op`.`products_quantity` > 0 THEN `op`.`products_quantity` ELSE 0 END),
                ',\"total_price\":\"',
                    SUM(`op`.`final_price`),
                '\"}'
            )
        FROM
            `products_to_categories` `ptc`,
            `orders_products` `op`
        WHERE
            `ptc`.`section_id` = `cd`.`section_id`
        AND
            `op`.`products_id` = `ptc`.`products_id`
        AND
            `op`.`orders_products_status` != 1
    )) AS `products_sold`,
    TRIM((
        SELECT
            CONCAT(
                '{\"total_quantity\":',
                    SUM(CASE WHEN `op`.`products_quantity` > 0 THEN `op`.`products_quantity` ELSE 0 END),
                ',\"total_price\":\"',
                    SUM(`op`.`final_price`),
                '\"}'
            )
        FROM
            `products_to_categories` `ptc`,
            `orders_products` `op`
        WHERE
            `ptc`.`section_id` = `cd`.`section_id`
        AND
            `op`.`products_id` = `ptc`.`products_id`
        AND
            `op`.`orders_products_status` = 1
    )) AS `products_pending`
FROM
    `categories` `c`,
    `categories_description` `cd`
WHERE
    `c`.`categories_id`  = `c`.`section_id`
AND
    `cd`.`categories_id`  = `c`.`categories_id`
GROUP BY `c`.`categories_id`
ORDER BY `c`.`categories_status` DESC;"

This work great but my main problem is how to do check IF/ELSE or CASE WHEN for custom defined new fields: products_available, products_sold and products_pending?

Problem is that if products not exists inside table orders_products I not get my generated JSON and that's made a small conflict inside PHP.

I can do check in PHP but want to avoid that part and just print JSON like:

{"total_quantity":0,"total_price":"0.0000"}


问:
Add values in column for based on name in different column python
I have a dataframe with a column that has participants' full names, and another column  that has the attendance for a specific year. each participant's name appears multiple times with their attendance for that year. I want to add the attendance values for a specific person to see how many times they attended total. Right now I am using this command but it adds all the values in the attendance column.

```<code>StudentinfoAll['Attendance_x'].sum(axis=0)
</code>```

How do I edit this so that it gives me the sum of the attendance values for a specific person? Thank you for your help.

Here is what my data frame looks like
Here is what it looks like

```<code>Full Name  Attendance  Question 1  Question 2
Dan Smith      4         3.0           2.0
Erika Jones    5         6.0           0.0
Dan Smith      3         5.0           7.0
Erika Jones    5         5.0           3.0
</code>```

答:
Assuming you want the total by student (not just for one student at a time), you need a group by operation.  For example, with a test.csv input of:

```<code>Full Name,Attendance,Question 1,Question 2
Dan Smith,4,3.0,2.0
Erika Jones,5,6.0,0.0
Dan Smith,3,5.0,7.0
Erika Jones,5,5.0,3.0
</code>```

And some aggregation code of:

```<code>import numpy as np
import pandas as pd

df = pd.read_csv('test.csv')
print df.groupby('Full Name').agg({'Attendance': np.sum})
</code>```

you get the following output (attendance by full name):

```<code>             Attendance
Full Name
Dan Smith             7
Erika Jones          10
</code>```

Body:
I have a dataframe with a column that has participants' full names, and another column  that has the attendance for a specific year. each participant's name appears multiple times with their attendance for that year. I want to add the attendance values for a specific person to see how many times they attended total. Right now I am using this command but it adds all the values in the attendance column.

StudentinfoAll['Attendance_x'].sum(axis=0)

How do I edit this so that it gives me the sum of the attendance values for a specific person? Thank you for your help.

Here is what my data frame looks like
Here is what it looks like

Full Name  Attendance  Question 1  Question 2
Dan Smith      4         3.0           2.0
Erika Jones    5         6.0           0.0
Dan Smith      3         5.0           7.0
Erika Jones    5         5.0           3.0

Body:
Assuming you want the total by student (not just for one student at a time), you need a group by operation.  For example, with a test.csv input of:

Full Name,Attendance,Question 1,Question 2
Dan Smith,4,3.0,2.0
Erika Jones,5,6.0,0.0
Dan Smith,3,5.0,7.0
Erika Jones,5,5.0,3.0

And some aggregation code of:

import numpy as np
import pandas as pd

df = pd.read_csv('test.csv')
print df.groupby('Full Name').agg({'Attendance': np.sum})

you get the following output (attendance by full name):

             Attendance
Full Name
Dan Smith             7
Erika Jones          10


问:
Doctrine 2 - Persist Entity with Joined Table's Foreign Key Opposed to Foreign Entity
I'm trying to persist a TradeEntity. A TradeEntity has a OneToOne relationship with a CurrencyEntity.

```<code>  /**
    * @ORM\OneToOne(targetEntity="Repositories\Currency\CurrencyEntity")
    * @ORM\JoinColumn(name="currency", referencedColumnName="id")
    *
    * @var CurrencyEntity
    */
    protected $currency;
</code>```

I have recieved a CurrencyEntity from another object which I'm trying to insert in this new TradeEntity and persist it to the database but get an exception:

```<code>Type: Doctrine\ORM\ORMInvalidArgumentException
Message: Expected value of type "Repositories\Currency\CurrencyEntity"
for association field "Repositories\Trade\TradeEntity#$currency", got "integer" instead.
</code>```

Is there no other way of me persisting TradeEntity without fetching the CurrencyEntity from the database and setting it that way?

答:
In light of my recent discovery, i felt the need to update this answer.

Reading about Doctrine's advanced configuration, i came across Reference Proxies.

The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database.

This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier. You could simply do this:

```<code><?php
// $em instanceof EntityManager, $cart instanceof MyProject\Model\Cart
// $itemId comes from somewhere, probably a request parameter
$item = $em->getReference('MyProject\Model\Item', $itemId);
$cart->addItem($item);
</code>```

Old answer:

What you can do is (it defeats the purpose of an ORM, but it is possible):

```<code>$conn = $entityManager->getConnection();
$conn->insert(
    'table_name',
    array(
        'column_name' => 'column_value',
        // define all the columns here
    )
);
</code>```

See Doctrine's Data Retrieval And Manipulation

Body:
I'm trying to persist a TradeEntity. A TradeEntity has a OneToOne relationship with a CurrencyEntity.

  /**
    * @ORM\OneToOne(targetEntity="Repositories\Currency\CurrencyEntity")
    * @ORM\JoinColumn(name="currency", referencedColumnName="id")
    *
    * @var CurrencyEntity
    */
    protected $currency;

I have recieved a CurrencyEntity from another object which I'm trying to insert in this new TradeEntity and persist it to the database but get an exception:

Type: Doctrine\ORM\ORMInvalidArgumentException
Message: Expected value of type "Repositories\Currency\CurrencyEntity"
for association field "Repositories\Trade\TradeEntity#$currency", got "integer" instead.

Is there no other way of me persisting TradeEntity without fetching the CurrencyEntity from the database and setting it that way?

Body:
In light of my recent discovery, i felt the need to update this answer.

Reading about Doctrine's advanced configuration, i came across Reference Proxies.

The method EntityManager#getReference($entityName, $identifier) lets you obtain a reference to an entity for which the identifier is known, without loading that entity from the database.

This is useful, for example, as a performance enhancement, when you want to establish an association to an entity for which you have the identifier. You could simply do this:

<?php
// $em instanceof EntityManager, $cart instanceof MyProject\Model\Cart
// $itemId comes from somewhere, probably a request parameter
$item = $em->getReference('MyProject\Model\Item', $itemId);
$cart->addItem($item);

Old answer:

What you can do is (it defeats the purpose of an ORM, but it is possible):

$conn = $entityManager->getConnection();
$conn->insert(
    'table_name',
    array(
        'column_name' => 'column_value',
        // define all the columns here
    )
);

See Doctrine's Data Retrieval And Manipulation


问:
How to replace an entire cell with NaN on pandas DataFrame
I want to replace the entire cell that contains the word as circled in the picture with blanks or NaN. However when I try to replace for example '1.25 Dividend' it turned out as '1.25 NaN'. I want to return the whole cell as 'NaN'. Any idea how to work on this?

答:
I would use applymap like this</p>

```<code>df.applymap(lambda x: 'NaN' if (type(x) is str and 'Dividend' in x) else x)
</code>```

Body:
I would use applymap like this

df.applymap(lambda x: 'NaN' if (type(x) is str and 'Dividend' in x) else x)


问:
GWT: 2.6 -> 2.8 System.getProperty("line.separator") not supported anymore
I'm updating my libgdx game to use GWT 2.8 instead of 2.6. I'm however running into the issue that the compiler doesn't accept my few calls to System.getProperty("line.separator"):

```<code>[ERROR] Errors in 'com/hgames/core/dm/grid/TextMapParser.java'
  [ERROR] Line 138: Property 'line.separator' is not defined.
</code>```

I'm puzzled, because it was accepted before and I could not find information regarding emulation of System's properties. I'm building with gradle and specifying gwt's version with "gwtVersion='2.8.0'".

答:
This is a new feature since 2.8.0-beta1 (http://www.gwtproject.org/release-notes.html#Release_Notes_2_8_0_BETA1). You can use System.getProperty to get user defined properties either in the gwt.xml or using command line (-setProperty).

Using command line:

In your module

```<code><define-configuration-property name="project.version" is-multi-valued="false"/>
</code>```

In your gwt compiler/devmode command line

```<code>-setProperty project.version=1.2.3
</code>```

Example https://github.com/ibaca/gwt-dagger2-coffee

Using module only:

In your module

```<code><define-configuration-property name="someConfigurationProperty" is-multi-valued='false'/>
<set-configuration-property name="someConfigurationProperty" value="conf"/>
</code>```

Example https://github.com/gwtproject/gwt/blob/a90832fec9a56f4cb83ed009c7048e0a8d196fe8/user/test/com/google/gwt/emultest/java/lang/SystemTest.java#L320

Body:
I'm updating my libgdx game to use GWT 2.8 instead of 2.6. I'm however running into the issue that the compiler doesn't accept my few calls to System.getProperty("line.separator"):

[ERROR] Errors in 'com/hgames/core/dm/grid/TextMapParser.java'
  [ERROR] Line 138: Property 'line.separator' is not defined.

I'm puzzled, because it was accepted before and I could not find information regarding emulation of System's properties. I'm building with gradle and specifying gwt's version with "gwtVersion='2.8.0'".

Body:
This is a new feature since 2.8.0-beta1 (http://www.gwtproject.org/release-notes.html#Release_Notes_2_8_0_BETA1). You can use System.getProperty to get user defined properties either in the gwt.xml or using command line (-setProperty).

Using command line:

In your module

<define-configuration-property name="project.version" is-multi-valued="false"/>

In your gwt compiler/devmode command line

-setProperty project.version=1.2.3

Example https://github.com/ibaca/gwt-dagger2-coffee

Using module only:

In your module

<define-configuration-property name="someConfigurationProperty" is-multi-valued='false'/>
<set-configuration-property name="someConfigurationProperty" value="conf"/>

Example https://github.com/gwtproject/gwt/blob/a90832fec9a56f4cb83ed009c7048e0a8d196fe8/user/test/com/google/gwt/emultest/java/lang/SystemTest.java#L320


问:
how to copy .htaccess to all 0777 folders
The following command attempts to copy /.htaccess to all folders permission 0777

```<code>find /home/*/www/ -type d -perm 0777 \
| xargs -r -d '\n'  cp -rf /.htaccess
</code>```

am looking to run it with terminal ssh command

i search for all folders have 0777 and copy htaccess to all at once

答:
```<code>find /home/*/www/ -type d -perm 0777 \
| xargs -I '{}' cp -rf  /.htaccess  '{}'
</code>```

Body:
The following command attempts to copy /.htaccess to all folders permission 0777

find /home/*/www/ -type d -perm 0777 \
| xargs -r -d '\n'  cp -rf /.htaccess

am looking to run it with terminal ssh command

i search for all folders have 0777 and copy htaccess to all at once


问:
JSON object parse issue on react
```<code>json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";
   json = JSON.stringify(json);
   model = new Model(json);
</code>```

it dosen't recognise the json object when it have quotes on

```<code> var json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";
</code>```

it works when removes quotes

```<code>   json = { elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'};
</code>```

I have tried JSON.parse(json); it dosen't work, would anyone please suggest solution, please?

答:
If you have JSON in a string, then you should do JSON.parse, not JSON.stringify.

Also, single quotes are invalid in JSON, so always use double-quotes for that.

```<code>// I fixed the JSON
var json = '{ elements: [ {type: "radiogroup", choices: ["Yes","No","Maybe","Never"], isRequired: true, name: "Test_01", title: "Do you like ice cream?" }],showQuestionNumbers: "off"}';
// The thing you would expect
var obj = JSON.parse(json);
</code>```

Title: JSON object parse issue on react

Body:
json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";
   json = JSON.stringify(json);
   model = new Model(json);

it dosen't recognise the json object when it have quotes on

 var json = "{ elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'}";

it works when removes quotes

   json = { elements: [ {type: 'radiogroup', choices: ['Yes','No','Maybe','Never'], isRequired: true, name: 'Test_01', title: 'Do you like ice cream?' }],showQuestionNumbers: 'off'};

I have tried JSON.parse(json); it dosen't work, would anyone please suggest solution, please?

Body:
If you have JSON in a string, then you should do JSON.parse, not JSON.stringify.

Also, single quotes are invalid in JSON, so always use double-quotes for that.

// I fixed the JSON
var json = '{ elements: [ {type: "radiogroup", choices: ["Yes","No","Maybe","Never"], isRequired: true, name: "Test_01", title: "Do you like ice cream?" }],showQuestionNumbers: "off"}';
// The thing you would expect
var obj = JSON.parse(json);


问:
Register .net MVC3 ControllerContext into windsor container
With ASP.NET MVC3 what would be the best way to register the requests ControllerContext into castle windsor container? Ultimately I'd like to be able to say

```<code>container.Resolve<ControllerContext>();
</code>```

and have the requests controller context returned.

More detail

The vast majority of my actions are just going to do some validation, authentication, etc.. before sending a message to nservicebus to actually do the work.  To avoid having to copy/paste these 20/30 lines of code all over the place I have put them into a handler class which my controllers take a dependency on in the constructor, the actions then call this class which leaves my actions containing just one line of code.

One of the child classes that makes up the handler needs to know about the route that was taken, I could just pass the controller to the handler and then onto this class but it seems a bit messy.  It would be nice if there was a way to get Windsor registered to provide it for me.

答:
Not really an answer to the original question but I can't stand dubious architectural moves :) It seems for me like ControllerContext isn't a best (well, not even a good one) place to try to extend from. The ModelBinders and ActionAttributes are the places to help with repeating code. They can take model mapping, binding and validation on their own thus freeing controllers from that responsibility.

Well, generally, what you'd really want to do is to use Dependency Injection for Controllers themselves injecting configured instances of somewhat IAuthenticationService and IValidationService (concrete implementations of them would contain all those 20/30 reusable lines of code). Then in Controllers you just call them in one line of code (or even use the MVC3 Global Filters feature to make that completely transparent).

Body:
With ASP.NET MVC3 what would be the best way to register the requests ControllerContext into castle windsor container? Ultimately I'd like to be able to say

container.Resolve<ControllerContext>();

and have the requests controller context returned.

More detail

The vast majority of my actions are just going to do some validation, authentication, etc.. before sending a message to nservicebus to actually do the work.  To avoid having to copy/paste these 20/30 lines of code all over the place I have put them into a handler class which my controllers take a dependency on in the constructor, the actions then call this class which leaves my actions containing just one line of code.

One of the child classes that makes up the handler needs to know about the route that was taken, I could just pass the controller to the handler and then onto this class but it seems a bit messy.  It would be nice if there was a way to get Windsor registered to provide it for me.


问:
Click on Leaflet map closes modal, click on marker opens modal
My Leaflet map has markers that open modals.

When a user clicks on the map, however, I would like for the modal to close. But the bit of code that makes that happen (below) interacts with the marker, and forces it to close as soon as it opens:

```<code>map.on('click', function(e) {
$('.modal').modal('hide'); });
</code>```

I did get this to work—see the JSFiddle here: https://jsfiddle.net/askebos/Lh1y12uq/

But as you can see, the only reason it seems to be working is because it creates the following error:

Uncaught TypeError: e.preventDefault is not a function.

I imagine it's because the map.on('click'...) function is prevented from executing.

Any thoughts on how I can get to the same behaviour without the error?

答:
The solution is to add an init() function that keeps track when a marker is clicked. Inspiration came from this question.

First, add the init() function to your code:

```<code>function init() {
    init.called = true;
}
</code>```

Then call the function when the marker is clicked:

```<code>function markerOnClick(e) {
  init();
...
}
</code>```

Make a function that fires when the map is clicked, but include an if/else statement that checks whether init.called has been set to true. If this is the case, reset init.called. If it has not been set to true, then the map was clicked elsewhere and any modals may close.

```<code>function mapClick () {
if(init.called) {
    init.called = false;
}
else{
  $('.modal').modal('hide');
}
}
</code>```

Finally, bind the mapClick function to map clicks.

```<code>map.on('click', mapClick);
</code>```

The function will no longer override marker clicks, and the error has been resolved as well. That still doesn't tell me why e.preventDefault caused an error, so any explanations would be welcome!

A working JSFiddle can be found here: https://jsfiddle.net/askebos/oesh59jr/

Body:
My Leaflet map has markers that open modals.

When a user clicks on the map, however, I would like for the modal to close. But the bit of code that makes that happen (below) interacts with the marker, and forces it to close as soon as it opens:

map.on('click', function(e) {
$('.modal').modal('hide'); });

I did get this to work—see the JSFiddle here: https://jsfiddle.net/askebos/Lh1y12uq/

But as you can see, the only reason it seems to be working is because it creates the following error:

Uncaught TypeError: e.preventDefault is not a function.

I imagine it's because the map.on('click'...) function is prevented from executing.

Any thoughts on how I can get to the same behaviour without the error?

Body:
The solution is to add an init() function that keeps track when a marker is clicked. Inspiration came from this question.

First, add the init() function to your code:

function init() {
    init.called = true;
}

Then call the function when the marker is clicked:

function markerOnClick(e) {
  init();
...
}

Make a function that fires when the map is clicked, but include an if/else statement that checks whether init.called has been set to true. If this is the case, reset init.called. If it has not been set to true, then the map was clicked elsewhere and any modals may close.

function mapClick () {
if(init.called) {
    init.called = false;
}
else{
  $('.modal').modal('hide');
}
}

Finally, bind the mapClick function to map clicks.

map.on('click', mapClick);

The function will no longer override marker clicks, and the error has been resolved as well. That still doesn't tell me why e.preventDefault caused an error, so any explanations would be welcome!

A working JSFiddle can be found here: https://jsfiddle.net/askebos/oesh59jr/


答:
I'm not sure what your trouble is but your example should work.  This most definitely works:

a.php

```<code><?php
$from_a = 'hey';
require "b.php";
print $from_b;
</code>```

b.php

```<code>print $from_a;
$from_b = 'okay';
</code>```

The above is perfectly valid PHP and will work as intended with no errors.  A script which is required by another script has full access to its variables and vice-versa.

Title: how to pass variable with require() in PHP

Body:
I'm stuck trying to pass variables between 2 PHP files a.php and b.php  using require(). I learned that PHP variables have a single scope, which means that if a.php includes b.php, it can read its variables. However, I would like b.php to be able to read a variable from a.php with my current setup. For example, I can print out $msg if it is set in b.php but not a.php. Is there a simple way to do this?

a.php

<?php

$msg = "Welcome NEW USER ! We can't wait for you to check out our books!";
require("connect.php");
require("b.php");
$table = "SELECT * FROM `login`";
if ($query_run=mysqli_query($cnn,$table)){

$username = $_POST['username'];
$pw = $_POST['password'];

$sql = "INSERT INTO login (username,password) VALUES ('{$username}','{$pw}')";

if($cnn->query($sql)===TRUE){echo "Query ran successfully";}
else{echo "Error: ".$sql."
".$cnn->error;}
}
else{die("table connection failed");}
$cnn.close();

?>

b.php

<?php
echo "
".$msg."

<form action='' method='post'>
Username: <input type='text' name='username'>

Password: <input type='text' name='password'>

<input type='submit' name='submit'>
</form>
"

?>

Body:
I'm not sure what your trouble is but your example should work.  This most definitely works:

a.php

<?php
$from_a = 'hey';
require "b.php";
print $from_b;

b.php

print $from_a;
$from_b = 'okay';

The above is perfectly valid PHP and will work as intended with no errors.  A script which is required by another script has full access to its variables and vice-versa.