问:
Swift Firebase Doesn't invoke method of observeSingleEvent
I am trying to retrieve data of logged in user from Firebase. However, it doesn't go inside of the method of observeSigleEvent and populate the data, so that, when it comes to the cellForRowAtIndexpath method, posts array returns as nil and gives error of fatal error: Index out of range.

Code is below.

```<code>@IBOutlet var tableView: UITableView!
@IBOutlet var homeActivityIndicator: UIActivityIndicatorView!

var databaseRef = Database.database().reference()
var loggedInUser = Auth.auth().currentUser

var loggedInUserData : AnyObject?

var posts = [AnyObject?]()

override func viewDidLoad() {
    super.viewDidLoad()

    // get loggedinUser Details

    self.databaseRef.child("user_profiles").child(self.loggedInUser!.uid ).observeSingleEvent(of:.value, with: {
        (snapshot) in

        if(snapshot.exists()){
            self.loggedInUserData = snapshot

            // get all posts that are made by user
            self.databaseRef.child("posts/\(self.loggedInUser!.uid)").observe(.childAdded, with:{ (snapshot2) in
                if(snapshot2.exists()){
                    self.posts.append(snapshot2)
                    self.tableView.insertRows(at: [IndexPath (row: 0, section: 0)], with: UITableViewRowAnimation.automatic)
                    self.homeActivityIndicator.stopAnimating()
                }else{return}
            }){(error) in
                print(error.localizedDescription)
            }
        }else{return}
    })
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell : homeViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeViewTableViewCell", for: indexPath) as! homeViewTableViewCell

    let post = posts[(self.posts.count-1) - (indexPath ).row]!.value(forKey: "text") as! String

    cell.configure(profilePic: nil, name: self.loggedInUserData!.value(forKey: "name") as! String, handle: self.loggedInUserData!.value(forKey: "handle") as! String, post: post)

    return cell
}
</code>```

答:
This happens because all the tableView functions are called when the ViewController is first initialised, while the data from Firebase won't come in for a (relatively) long time after initialisation. When

```<code>let post = posts[(self.posts.count-1) - (indexPath ).row]!.value(forKey: "text") as! String
</code>```

Is called, it is trying to access index -1 of an array with nothing in it, hence your exception.

To fix your problem try setting the following to dynamically change the number of rows:

```<code>func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.posts.count
}
</code>```

Each time your child added listener is called, update the tableView with tableView.reloadData().

Body:
I am trying to retrieve data of logged in user from Firebase. However, it doesn't go inside of the method of observeSigleEvent and populate the data, so that, when it comes to the cellForRowAtIndexpath method, posts array returns as nil and gives error of fatal error: Index out of range.

Code is below.

@IBOutlet var tableView: UITableView!
@IBOutlet var homeActivityIndicator: UIActivityIndicatorView!

var databaseRef = Database.database().reference()
var loggedInUser = Auth.auth().currentUser

var loggedInUserData : AnyObject?

var posts = [AnyObject?]()

override func viewDidLoad() {
    super.viewDidLoad()

    // get loggedinUser Details

    self.databaseRef.child("user_profiles").child(self.loggedInUser!.uid ).observeSingleEvent(of:.value, with: {
        (snapshot) in

        if(snapshot.exists()){
            self.loggedInUserData = snapshot

            // get all posts that are made by user
            self.databaseRef.child("posts/\(self.loggedInUser!.uid)").observe(.childAdded, with:{ (snapshot2) in
                if(snapshot2.exists()){
                    self.posts.append(snapshot2)
                    self.tableView.insertRows(at: [IndexPath (row: 0, section: 0)], with: UITableViewRowAnimation.automatic)
                    self.homeActivityIndicator.stopAnimating()
                }else{return}
            }){(error) in
                print(error.localizedDescription)
            }
        }else{return}
    })
}

func numberOfSections(in tableView: UITableView) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return 1
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

    let cell : homeViewTableViewCell = tableView.dequeueReusableCell(withIdentifier: "HomeViewTableViewCell", for: indexPath) as! homeViewTableViewCell

    let post = posts[(self.posts.count-1) - (indexPath ).row]!.value(forKey: "text") as! String

    cell.configure(profilePic: nil, name: self.loggedInUserData!.value(forKey: "name") as! String, handle: self.loggedInUserData!.value(forKey: "handle") as! String, post: post)

    return cell
}

Body:
This happens because all the tableView functions are called when the ViewController is first initialised, while the data from Firebase won't come in for a (relatively) long time after initialisation. When

let post = posts[(self.posts.count-1) - (indexPath ).row]!.value(forKey: "text") as! String

Is called, it is trying to access index -1 of an array with nothing in it, hence your exception.

To fix your problem try setting the following to dynamically change the number of rows:

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return self.posts.count
}

Each time your child added listener is called, update the tableView with tableView.reloadData().


来源: stackexchange

问:
How can I fix the JSON code error in the attached picture from the code below?
JSON-LD markup generated by Google Structured Data Markup Helper.

error description in image.

here

here is my json

```<code>    <script type= "application/ld+json">
       {
"@context" : "http://schema.org",
         "@type" : "Article",
         "headline" : "7 Ways To .........",
         "author" : {
          "@type" : "Person",
          "name" : "xxxxxxxxx",
        },
        "datePublished" : "2017-06-22T08:50",
        "image" : {
        "@type": "imageObject",
         "url":"xxxxx",
       },
        "articleSection" : "Use one of three methods to find the value of the business–cash flow, market or assets. Then boost business value quickly.",
        "url" : "xxxxx",
        "publisher" : {
          "@type" : "Organization",
          "name" : "xxxxxxxxxx",
          "logo": {
          "@type": "imageObject",
          "url": "xxxxxx",
          }
      },
      }</script>
</code>```

答:
several time extra comma in end of the value.

valid JSON below

```<code>{
  "@context": "http://schema.org",
  "@type": "Article",
  "headline": "7 Ways To .........",
  "author": {
    "@type": "Person",
    "name": "xxxxxxxxx"
  },
  "datePublished": "2017-06-22T08:50",
  "image": {
    "@type": "imageObject",
    "url": "xxxxx"
  },
  "articleSection": "Use one of three methods to find the value of the business–cash flow, market or assets. Then boost business value quickly.",
  "url": "xxxxx",
  "publisher": {
    "@type": "Organization",
    "name": "xxxxxxxxxx",
    "logo": {
      "@type": "imageObject",
      "url": "xxxxxx"
    }
  }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
several time extra comma in end of the value.

valid JSON below

{
  "@context": "http://schema.org",
  "@type": "Article",
  "headline": "7 Ways To .........",
  "author": {
    "@type": "Person",
    "name": "xxxxxxxxx"
  },
  "datePublished": "2017-06-22T08:50",
  "image": {
    "@type": "imageObject",
    "url": "xxxxx"
  },
  "articleSection": "Use one of three methods to find the value of the business–cash flow, market or assets. Then boost business value quickly.",
  "url": "xxxxx",
  "publisher": {
    "@type": "Organization",
    "name": "xxxxxxxxxx",
    "logo": {
      "@type": "imageObject",
      "url": "xxxxxx"
    }
  }
}


问:
XPath: Get node below another node
I'm new to XPath, and I need to get the table node after the following:

```<code><p><b>Some unique string</b></p>

<center><table>
<tr>
<th>.....
</code>```

I have been trying things such as:

```<code>"following-sibling::.//p//b[.='Some unique string']"
".//p//b[.='Some unique string']/following:://table"
</code>```

So far I've managed to get rather stuck and confused, would greatly appreciate a pointer in the right direction. So thank you in advance :)

(If it makes a difference, I'm using the lxml.html module in Python 2.6)

答:
This XPath 1.0 expression:

```<code>//b[.='Some unique string']/following::table[1]
</code>```

Meaning: the first following table element of any b element in the whole document having 'Some unique string' as string value

ContentLicense: CC BY-SA 2.5

Title: XPath: Get node below another node

Body:
I'm new to XPath, and I need to get the table node after the following:

Some unique string

.....

I have been trying things such as:

"following-sibling::.//p//b[.='Some unique string']"
".//p//b[.='Some unique string']/following:://table"

So far I've managed to get rather stuck and confused, would greatly appreciate a pointer in the right direction. So thank you in advance :)

(If it makes a difference, I'm using the lxml.html module in Python 2.6)

Body:
This XPath 1.0 expression:

//b[.='Some unique string']/following::table[1]

Meaning: the first following table element of any b element in the whole document having 'Some unique string' as string value


问:
Runtime of triple nested for loops
I'm currently going through "Cracking the coding interview" textbook and I'm reviewing Big-O and runtime. One of the examples were as such:

Print all positive integer solutions to the equation a^3 + b^3 = c^3 + d^3 where a, b, c, d are integers between 1 and 1000.

The psuedo code solution provided is:

```<code>n = 1000;
for c from 1 to n
  for d from 1 to n
    result = c^3 + d^3
    append (c,d) to list at value map[result]

for each result, list in map
  for each pair1 in list
    for each pair2 in list
      print pair1, pair2

The runtime is O(N^2)
</code>```

I'm not sure how O(N^2) is obtained and after extensive googling and trying to figure out why, I still have no idea. My rational is as following:

Top half is O(N^2) because the outer loop goes to n and inner loop executes n times each.

The bottom half I'm not sure how to calculate, but I got O(size of map) * O(size of list) * O(size of list) = O(size of map) * O(size of list^2).

O(N^2) + O(size of map) * O(size of list^2)

The 2 for loops adding the pairs to the list of the map = O(N) * O(N) b/c it's 2 for loops running N times.

The outer for loop for iterating through the map = O(2N-1) = O(N) b/c the size of the map is 2N - 1 which is essentially N.

The 2 for loops for iterating through the pairs of each list = O(N) * O(N) b/c each list is <= N

Total runtime: O(N^2) + O(N) * O(N^2) = O(N^3)

Not sure what I'm missing here

Could someone help me figure out how O(N^2) is obtained or why my solution is incorrect. Sorry if my explanation is a bit confusing. Thanks

答:
This is a very interesting question! cdo256 made some good points, I will try to explain a bit more and complete the picture.

It is more or less obvious that the key questions are - how many integers exist that can be expressed as a sum of two positive cubes in k different ways (where k >= 2), and what is the possible size of k ? This number determines the sizes of lists which are values of map, which determine the total complexity of the program. Our "search space" is from 2 to 2 * 10^9 because c and d both iterate from 1 to 1000, so the sum of their cubes is at most 2 * 10^9. If none of the numbers in the range [2, 2 * 10^9] could be expressed as a sum of two cubes in more than one way, than the complexity of our program would be O(n^2). Why? Well, first part is obviously O(n^2), and the second part depends on the size of lists which are values of map. But in this case all lists have size 1, and there are n^2 keys in map which gives O(n^2).

However, that is not the case, there is a famous example of "taxicub number" 1729, so let us return to our main question - the number of different ways to express an integer as a sum of two cubes of positive integers. This is an active field of research in number theory, and great summary is given in Joseph H. Silverman's article Taxicabs and Sums of Two Cubes. I recommend to read it thoroughly. Current records are given here. Some interesting facts:

smallest integer that can be expressed as a sum of two cubes of positive integers in three different ways is 87,539,319

smallest integer that can be expressed as a sum of two cubes of positive integers in four different ways is 6,963,472,309,248 (> 2*10^9)

smallest integer that can be expressed as a sum of two cubes of positive integers in six different ways is 24,153,319,581,254,312,065,344 (> 2*10^9)

As you can easily see e.g. here, there are only 2184 integers in range [2, 2 * 10^9] that are expressible as a sum of two positive cubes in two or three different ways, and for k = 4,5,.. these numbers are out of our range. Therefore, the number of keys in map is very close to n^2, and sizes of the value lists are at most 3, which implies that the complexity of the code

```<code>  for each pair1 in list
    for each pair2 in list
      print pair1, pair2
</code>```

is constant, so the total complexity is again O(n^2).

Title: Runtime of triple nested for loops

Body:
I'm currently going through "Cracking the coding interview" textbook and I'm reviewing Big-O and runtime. One of the examples were as such:

Print all positive integer solutions to the equation a^3 + b^3 = c^3 + d^3 where a, b, c, d are integers between 1 and 1000.

The psuedo code solution provided is:

n = 1000;
for c from 1 to n
  for d from 1 to n
    result = c^3 + d^3
    append (c,d) to list at value map[result]

for each result, list in map
  for each pair1 in list
    for each pair2 in list
      print pair1, pair2

The runtime is O(N^2)

I'm not sure how O(N^2) is obtained and after extensive googling and trying to figure out why, I still have no idea. My rational is as following:

Top half is O(N^2) because the outer loop goes to n and inner loop executes n times each.

The bottom half I'm not sure how to calculate, but I got O(size of map) * O(size of list) * O(size of list) = O(size of map) * O(size of list^2).

O(N^2) + O(size of map) * O(size of list^2)

The 2 for loops adding the pairs to the list of the map = O(N) * O(N) b/c it's 2 for loops running N times.

The outer for loop for iterating through the map = O(2N-1) = O(N) b/c the size of the map is 2N - 1 which is essentially N.

The 2 for loops for iterating through the pairs of each list = O(N) * O(N) b/c each list is <= N

Total runtime: O(N^2) + O(N) * O(N^2) = O(N^3)

Not sure what I'm missing here

Could someone help me figure out how O(N^2) is obtained or why my solution is incorrect. Sorry if my explanation is a bit confusing. Thanks

Body:
This is a very interesting question! cdo256 made some good points, I will try to explain a bit more and complete the picture.

It is more or less obvious that the key questions are - how many integers exist that can be expressed as a sum of two positive cubes in k different ways (where k >= 2), and what is the possible size of k ? This number determines the sizes of lists which are values of map, which determine the total complexity of the program. Our "search space" is from 2 to 2 * 10^9 because c and d both iterate from 1 to 1000, so the sum of their cubes is at most 2 * 10^9. If none of the numbers in the range [2, 2 * 10^9] could be expressed as a sum of two cubes in more than one way, than the complexity of our program would be O(n^2). Why? Well, first part is obviously O(n^2), and the second part depends on the size of lists which are values of map. But in this case all lists have size 1, and there are n^2 keys in map which gives O(n^2).

However, that is not the case, there is a famous example of "taxicub number" 1729, so let us return to our main question - the number of different ways to express an integer as a sum of two cubes of positive integers. This is an active field of research in number theory, and great summary is given in Joseph H. Silverman's article Taxicabs and Sums of Two Cubes. I recommend to read it thoroughly. Current records are given here. Some interesting facts:

smallest integer that can be expressed as a sum of two cubes of positive integers in three different ways is 87,539,319

smallest integer that can be expressed as a sum of two cubes of positive integers in four different ways is 6,963,472,309,248 (> 2*10^9)

smallest integer that can be expressed as a sum of two cubes of positive integers in six different ways is 24,153,319,581,254,312,065,344 (> 2*10^9)

As you can easily see e.g. here, there are only 2184 integers in range [2, 2 * 10^9] that are expressible as a sum of two positive cubes in two or three different ways, and for k = 4,5,.. these numbers are out of our range. Therefore, the number of keys in map is very close to n^2, and sizes of the value lists are at most 3, which implies that the complexity of the code

  for each pair1 in list
    for each pair2 in list
      print pair1, pair2

is constant, so the total complexity is again O(n^2).


问:
Error while importing very large dataset to arangoDB
I'm trying to import a huge dataset to ArangoDB via arangoimp. It's about 55 million edges. I alreasy increased the size of the wal.logfiles ( --wal.logfile-size to 1024k from 32k). This solved the last error. But now i get the following error:

```<code>WARNING {collector} got unexpected error in MMFilesCollectorThread::collect: no journal
ERROR cannot create datafile '/usr/local/var/lib/arangodb3/databases/database-1/collection-2088918365-385765492/temp-2153337069.db': Too many open files
</code>```

Importstatement was: arangoimp --file links_de.csv --type csv --collection links

Is there a way to let arangoimp work more iterativ like doing chunks or something? I would be quite complicated to split the CSV in some parts because of its size...

thanks a lot!

答:
i finally solved it:
Too many open files was the hint. You need to raise the limit for open file handles. So before starting arango on unix / mac os run ulimit -n 16384 or higher to raise the limit for this shell session. Afterwards the import still takes several hours but worked for me. You can also increase the journal size of the collection in arango to reduce the number of needed file handles.

Also see there: ArangoDB Too many open files

Body:
I'm trying to import a huge dataset to ArangoDB via arangoimp. It's about 55 million edges. I alreasy increased the size of the wal.logfiles ( --wal.logfile-size to 1024k from 32k). This solved the last error. But now i get the following error:

WARNING {collector} got unexpected error in MMFilesCollectorThread::collect: no journal
ERROR cannot create datafile '/usr/local/var/lib/arangodb3/databases/database-1/collection-2088918365-385765492/temp-2153337069.db': Too many open files

Importstatement was: arangoimp --file links_de.csv --type csv --collection links

Is there a way to let arangoimp work more iterativ like doing chunks or something? I would be quite complicated to split the CSV in some parts because of its size...

thanks a lot!


问:
Grep regex not working with square brackets
So I was trying to write a regex in grep to match square brackets, i.e [ad] should match [ and ]. But I was getting different results on using capturing groups and character classes. Also the result is different on putting ' in the beginning and end of regex string.

So these are the different result that I am getting.

Using capturing groups works fine

```<code>echo "[ad]" | grep -E '(\[|\])'
[ad]
</code>```

Using capturing groups without ' gives syntax error

```<code>echo "[ad]" | grep -E (\[|\])
bash: syntax error near unexpected token `('
</code>```

using character class with [ followed by ] gives no output

```<code>echo "[ad]" | grep -E [\[\]]
</code>```

Using character class with ] followed by [ works correctly

```<code>echo "[ad]" | grep -E [\]\[]
[ad]
</code>```

Using character class with ] followed by [ and using ' does not work

```<code>echo "[ad]" | grep -E '[\]\[]'
</code>```

It'd be great if someone could explain the difference between them.

答:
Maybe you provided such a simple example on purpose (after all, it is minimal), but in case all you really want is to check for existence of square brackets (a fixed string, not regex pattern), you can use grep with -F/--fixed-strings and multiple -e options:

```<code>$ echo "[ad]" | grep -F -e '[' -e ']'
[ad]
</code>```

Or, a little bit shorter with fgrep:

```<code>$ echo "[ad]" | fgrep -e '[' -e ']'
[ad]
</code>```

Or, even:

```<code>$ echo "[ad]" | fgrep -e[ -e]
[ad]
</code>```

Body:
So I was trying to write a regex in grep to match square brackets, i.e [ad] should match [ and ]. But I was getting different results on using capturing groups and character classes. Also the result is different on putting ' in the beginning and end of regex string.

So these are the different result that I am getting.

Using capturing groups works fine

echo "[ad]" | grep -E '(\[|\])'
[ad]

Using capturing groups without ' gives syntax error

echo "[ad]" | grep -E (\[|\])
bash: syntax error near unexpected token `('

using character class with [ followed by ] gives no output

echo "[ad]" | grep -E [\[\]]

Using character class with ] followed by [ works correctly

echo "[ad]" | grep -E [\]\[]
[ad]

Using character class with ] followed by [ and using ' does not work

echo "[ad]" | grep -E '[\]\[]'

It'd be great if someone could explain the difference between them.

Body:
Maybe you provided such a simple example on purpose (after all, it is minimal), but in case all you really want is to check for existence of square brackets (a fixed string, not regex pattern), you can use grep with -F/--fixed-strings and multiple -e options:

$ echo "[ad]" | grep -F -e '[' -e ']'
[ad]

Or, a little bit shorter with fgrep:

$ echo "[ad]" | fgrep -e '[' -e ']'
[ad]

Or, even:

$ echo "[ad]" | fgrep -e[ -e]
[ad]


问:
Having two different GIT repo's in one directory for the same project
I wanted to know if it is possible to have 2 different GIT repositories in one root folder for the same project, and if I can add/commit/push to both of them without anything getting messed up.

Example of what I want to achieve:

I have a Django project and I have it in 2 different repositories. One being on https://github.com that I use for automatic deployment on Heroku, and the second repository on https://gitlab.com where I have all my legit commits/Messages/Tickets/Issues/CI/etc.

Is it possible to somehow get both repos to be in 1 directory where my Django project is and then for me to just do

git add .

git commit -m "message"

git push origin "whatever"

and get my commits pushed to both repos?

At the moment I have the project in 2 different directories where the gitlab one is my main project and then I copy paste the files into the github one and push there so I can deploy the changes on Heroku.

P.S I would prefer to have my automatic deploys from the github repo without setting up any deployments from gitlab.

Thanks, please comment if you are downvoting this post, so I can improve quality. This is my 1st question!

Thank you!

EDIT 09-07-2017:

I have found a way to easily deploy my Django Project to Heroku without the need of a github repo. For any future people that might come across this question, here is how I achieved deploying my Django Project to Heroku via a https://gitlab.com repo in the most hacky/fast way without much of a setup:

Locate your Heroku-API key Heroku, if the link no longer works just go to your Heroku Account settings and in there you will find your Heroku API key

After you have setup your Procfile, wsgi.py, etc (all the Deployment setup), push all the changes to your master branch on gitlab.

Finally you want to do the following commands in order to deploy to Heroku:

git remote add heroku https://"API-key"@git.heroku.com/"app_name".git

(without the quotes example: https://xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx@git.heroku.com/django_app.git)

then you fire up this:

git push -f heroku master

This might ask you to authenticate, so just use your heroku credentials.

Hope this was of help to you!

答:
I'm not much of a fan of this idea - having two repositories and then copy-paste from one to another. One approach you can use is using GitFlow. You'll only need one repository (whichever you choose). You will work with branches and you will have one branch for production, that will be used for deployment. You can read more about it (about other workflows as well) here or you can search it by yourself.

Good luck!


问:
preg_split every character, but don't split if is quote
I'm using the following code to split my UTF-8 strings to characters:

```<code>$characters = preg_split('//u', $word, -1, PREG_SPLIT_NO_EMPTY);
</code>```

In some cases, a character might have a single quote after it. for example: hel'lo. I want to keep that quote with the character before it.

Using the regex above, my array is this:

```<code>Array
(
    [0] => h
    [1] => e
    [2] => l
    [3] => '
    [4] => l
    [5] => o
)
</code>```

And I want the array to be:

```<code>Array
(
    [0] => h
    [1] => e
    [2] => l'
    [3] => l
    [4] => o
)
</code>```

How can I do it?
Thanks!

(the single quote can be at the beginning of the string, at the end of it and in the middle of it).

答:
Use ! to prevent from split

```<code>$characters = preg_split("/(?!')/u", $word, -1, PREG_SPLIT_NO_EMPTY);
</code>```

Body:
I'm using the following code to split my UTF-8 strings to characters:

$characters = preg_split('//u', $word, -1, PREG_SPLIT_NO_EMPTY);

In some cases, a character might have a single quote after it. for example: hel'lo. I want to keep that quote with the character before it.

Using the regex above, my array is this:

Array
(
    [0] => h
    [1] => e
    [2] => l
    [3] => '
    [4] => l
    [5] => o
)

And I want the array to be:

Array
(
    [0] => h
    [1] => e
    [2] => l'
    [3] => l
    [4] => o
)

How can I do it?
Thanks!

(the single quote can be at the beginning of the string, at the end of it and in the middle of it).

Body:
Use ! to prevent from split

$characters = preg_split("/(?!')/u", $word, -1, PREG_SPLIT_NO_EMPTY);


问:
How to set firebase read rule and read all siblings if one matches
I have set my firebase rules as follows:

```<code>    {
  "rules": {"users": {
       "$uid": {
         ".read": "auth != null",
        ".write": "$uid === auth.uid"

    }}
  }
}
</code>```

Which allows write only to the node with matching uid and read all child nodes of every uid. But I want it to be like if I query using a child node under uid, only the matching child and it's siblings can be read...

for example this is my json structure:

```<code> {
"users" : {

      "AJkK4yZJsoseeefrJ7i6KIOUBDghtrhgthrtDi1" : {
        "lat" : 20.5001,
        "long" : 68.3755,
        "number" : "9876543210",
        "time" : 1499599788090
      }
    }
}
</code>```

I want to query using the number, and set the read rule as can read lat long and time only where the number matches. How to write the rule?

update: my question now is, how to query the database using number and get other siblings if value of number matches in android? I have tried this but not working:}

```<code>  friend = mDatabase.getReference("users");
  friend.keepSynced(true);

  Query z = LocationActivity.this.friend.orderByChild("number").equalTo("9876054321");

  z.addListenerForSingleValueEvent((new ValueEventListener() {
        long lastseen;
        public void onDataChange(DataSnapshot dataSnapshot) {
            try {
                for (DataSnapshot zoneSnapshot: dataSnapshot.getChildren()) {
                    lastseen = (Long)zoneSnapshot.child("time").getValue();
                    friendLatitude = (Double) zoneSnapshot.child("lat").getValue();
                    friendLongitude = (Double) zoneSnapshot.child("long").getValue();
                }

            } catch (Exception e) {
            }}
</code>```

it returns value null, any help would be appreciated.

答:
In order to query every node, the user needs to have read permission for ALL nodes under the parent.

This is because security rules cannot be used to query data in Firebase.

Body:
I have set my firebase rules as follows:

    {
  "rules": {"users": {
       "$uid": {
         ".read": "auth != null",
        ".write": "$uid === auth.uid"

    }}
  }
}

Which allows write only to the node with matching uid and read all child nodes of every uid. But I want it to be like if I query using a child node under uid, only the matching child and it's siblings can be read...

for example this is my json structure:

 {
"users" : {

      "AJkK4yZJsoseeefrJ7i6KIOUBDghtrhgthrtDi1" : {
        "lat" : 20.5001,
        "long" : 68.3755,
        "number" : "9876543210",
        "time" : 1499599788090
      }
    }
}

I want to query using the number, and set the read rule as can read lat long and time only where the number matches. How to write the rule?

update: my question now is, how to query the database using number and get other siblings if value of number matches in android? I have tried this but not working:}

  friend = mDatabase.getReference("users");
  friend.keepSynced(true);

  Query z = LocationActivity.this.friend.orderByChild("number").equalTo("9876054321");

  z.addListenerForSingleValueEvent((new ValueEventListener() {
        long lastseen;
        public void onDataChange(DataSnapshot dataSnapshot) {
            try {
                for (DataSnapshot zoneSnapshot: dataSnapshot.getChildren()) {
                    lastseen = (Long)zoneSnapshot.child("time").getValue();
                    friendLatitude = (Double) zoneSnapshot.child("lat").getValue();
                    friendLongitude = (Double) zoneSnapshot.child("long").getValue();
                }

            } catch (Exception e) {
            }}

it returns value null, any help would be appreciated.


问:
nodemon is unable to find ts-node in exec-parameter
I'm trying to use ts-node with nodemon. Both are installed using yarn and my package.json has the following structure:

```<code>{
  "name": "yarnTest",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "@types/express": "^4.0.36",
    "bootstrap-sass": "^3.3.7",
    "nodemon": "^1.11.0",
    "typescript": "^2.4.1"
  },
  "dependencies": {
    "@types/chalk": "^0.4.31",
    "chalk": "^2.0.1",
    "express": "^4.15.3",
    "ts-node": "^3.2.0"
  },
  "scripts": {
    "dev": "nodemon --exec 'ts-node --cache-directory .tscache' ./src/www.ts",
    "start": "ts-node --fast ./dist/www.ts"
  }
}
</code>```

Now, when I use "yarn run dev", it executes nodemon and nodemon tries to execute "ts-node" but nodemon tells me that the command "ts-node" does not exist:

Der Befehl "'ts-node" ist entweder falsch geschrieben oder konnte nicht gefunden werden.

Yarn is installed globally but ts-node is installed for my project only.
I already tried:

```<code>  "scripts": {
    "dev": "nodemon --exec 'yarn run ts-node --cache-directory .tscache' ./src/www.ts",
    "start": "ts-node --fast ./dist/www.ts"
  }
</code>```

But this gives me the error that "yarn" is not found :(
Any ideas how to fix this issue?

答:
I finally solved the issue!
After some hours I figured out that nodemon told me, that it's unable to find "'ts-node" (or "'yarn"). The apostroph was confusing me, so I finally replaced both apostrophes in my package.json with " and now my working script command is the following one: </p>

```<code> "dev": "nodemon --exec \"ts-node --cache-directory .tscache\" ./src/www.ts"
</code>```

Body:
I'm trying to use ts-node with nodemon. Both are installed using yarn and my package.json has the following structure:

{
  "name": "yarnTest",
  "version": "1.0.0",
  "main": "index.js",
  "license": "MIT",
  "devDependencies": {
    "@types/express": "^4.0.36",
    "bootstrap-sass": "^3.3.7",
    "nodemon": "^1.11.0",
    "typescript": "^2.4.1"
  },
  "dependencies": {
    "@types/chalk": "^0.4.31",
    "chalk": "^2.0.1",
    "express": "^4.15.3",
    "ts-node": "^3.2.0"
  },
  "scripts": {
    "dev": "nodemon --exec 'ts-node --cache-directory .tscache' ./src/www.ts",
    "start": "ts-node --fast ./dist/www.ts"
  }
}

Now, when I use "yarn run dev", it executes nodemon and nodemon tries to execute "ts-node" but nodemon tells me that the command "ts-node" does not exist:

Der Befehl "'ts-node" ist entweder falsch geschrieben oder konnte nicht gefunden werden.

Yarn is installed globally but ts-node is installed for my project only.
I already tried:

  "scripts": {
    "dev": "nodemon --exec 'yarn run ts-node --cache-directory .tscache' ./src/www.ts",
    "start": "ts-node --fast ./dist/www.ts"
  }

But this gives me the error that "yarn" is not found :(
Any ideas how to fix this issue?

Body:
I finally solved the issue!
After some hours I figured out that nodemon told me, that it's unable to find "'ts-node" (or "'yarn"). The apostroph was confusing me, so I finally replaced both apostrophes in my package.json with " and now my working script command is the following one:

 "dev": "nodemon --exec \"ts-node --cache-directory .tscache\" ./src/www.ts"


问:
Does Unicom System Architect still support using Oracle database?
When System Architect was an IBM product it supported Oracle DB.

The current version is 11.4.4.2.

Reading the vendor's product page does not list Oracle, it only lists MS SQL Server. But a 2016 Unicom report says 11.4 supports Oracle.

Wikipedia and SO say it supports Oracle, but they are both old information.

Does anyone have experience on this?

答:
On the page you refer to press the evaluate-button and you will see

Request for Information

  If you would like to submit a Request for Information for an Enterprise Architecture tool, please send an email to Architect.Sales@unicomsi.com

So why not ask the vendor? I think he will know.


问:
Fatal error: Incompatible file format: The encoded file has format major ID 7, whereas the Loader expects 5 in
i am installing a script on cpanel, which includes zend i think, when i am installing i am getting this error..

```<code>Fatal error: Incompatible file format: The encoded file has format major ID
7, whereas the Loader expects 5 in
/home/digitalcontent/public_html/Core/Base/Init.php on line 0
</code>```

PHP VERSION: 5.4.45

Anyone please help me out what is the issue so far...

I upload a file to check phpinfo() and found this zend engine installed

Should I update the version of Zend Engine or there is some other issue??

Thanks in advance

答:
The Zend Guard encoded versions should be compatible with PHP run time version.
Solution:I
PHP run time version upgraded to 5.6,since this is compatible Zend guard ID 7.
Solution: II
Use Zend Guard version ID 5.
See the compatible table from here
https://zend18.zendesk.com/hc/en-us/articles/217058968</p>

Body:
i am installing a script on cpanel, which includes zend i think, when i am installing i am getting this error..

Fatal error: Incompatible file format: The encoded file has format major ID
7, whereas the Loader expects 5 in
/home/digitalcontent/public_html/Core/Base/Init.php on line 0

PHP VERSION: 5.4.45

Anyone please help me out what is the issue so far...

I upload a file to check phpinfo() and found this zend engine installed

Should I update the version of Zend Engine or there is some other issue??

Thanks in advance


问:
Stop screen to blink on setInterval function on Gmap
I am using setInterval function that calls initalize method which fires ajax to get data on google maps(almost 3 ajax for different sort of data on same map, eg:for customers and drivers).
Each time it executes, the screen blinks seems like its loading the map each time.
How can blinking be removed ? flickering of just data on screen is needed.

Any suggestions?

Thanks

答:
The  effect you are experiencing with setInterval() is normally caused when the function is invoked before  it's completion of  previous call,and setInterval()  repeatedly calls a function or the code snippet you are running and it runs  with a fixed time delay between each and  every call
Use setTimeout(): which is self invoking.
Also check if its not working on every browser.</p>


问:
ES6 Feature: How are Template Strings useful?
AKA Template Literals, String Interpolation. (Wiki here.)

Why are they useful?

When should I not use them?

How are these features similar and different from using JSX with React?

How can I use String.raw() effectively as mentioned in the bottom of the wiki?

答:
Use 1

It's multiline. (In JS, norm strings need backslashes before newline chars.)

Use 2

An alternative style. Compare:

```<code>a: ${a}, b: ${b}, c: ${c}, d: ${d}, e: ${e}
</code>```

.with:

```<code>a: '+a+', b: '+b+', c: '+c+', d: '+d+', e: '+e
</code>```

.And compare:

function generated_function(){
    '+ statement1 +'
    '+ function2_name +'();
    f3();
    f'+ 5*5 +'();
}
```

<p>.with:</p>

```function generated_function(){
    ${statement1}
    ${function2_name}();
    f3();
    f${ 5*5 }();
}
```

Nicety
It's backslash-escaped too—<${> by <\${> or <$\{>.

Nb
It's different to <String.raw>. Cf §.

Body:
Use 1

It's multiline. (In JS, norm strings need backslashes before newline chars.)

Use 2

An alternative style. Compare:

a: ${a}, b: ${b}, c: ${c}, d: ${d}, e: ${e}

.with:

a: '+a+', b: '+b+', c: '+c+', d: '+d+', e: '+e

.And compare:

function generated_function(){
    '+ statement1 +'
    '+ function2_name +'();
    f3();
    f'+ 5*5 +'();
}

.with:

function generated_function(){
    ${statement1}
    ${function2_name}();
    f3();
    f${ 5*5 }();
}

Nicety
It's backslash-escaped too—<${> by <\${> or <$\{>.

Nb
It's different to <String.raw>. Cf §.


问:
How To Upload Laravel Project To shared Hosting without problems
i work with laravel 5.2, i have built a small app i just want to upload it to shared hosting
i tried with 000webhost and byethost and i got problems like

```<code>Wrong COM_STMT_PREPARE response size. Received 7
</code>```

```<code>Whoops, looks like something went wrong.(in two lines without explanation the problem)
</code>```

答:
this problem is in the database engine of the free shared hosting

for example in 000webhost:

edit config/database.php:

```<code>'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    //.......
    'options'   => [PDO::ATTR_EMULATE_PREPARES => true,]
],
</code>```

Body:
i work with laravel 5.2, i have built a small app i just want to upload it to shared hosting
i tried with 000webhost and byethost and i got problems like

Wrong COM_STMT_PREPARE response size. Received 7

Whoops, looks like something went wrong.(in two lines without explanation the problem)

Body:
this problem is in the database engine of the free shared hosting

for example in 000webhost:

edit config/database.php:

'mysql' => [
    'driver' => 'mysql',
    'host' => env('DB_HOST', 'localhost'),
    //.......
    'options'   => [PDO::ATTR_EMULATE_PREPARES => true,]
],


问:
Printing null pointers with %p is undefined behavior?
Is it undefined behavior to print null pointers with the %p conversion specifier?

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

int main(void) {
    void *p = NULL;

    printf("%p", p);

    return 0;
}
</code>```

The question applies to the C standard, and not to C implementations.

答:
The Short Answer

Yes. Printing null pointers with the %p conversion specifier has undefined behavior. Having said that, I'm unaware of any existing conforming implementation that would misbehave.

The answer applies to any of the C standards (C89/C99/C11).

The Long Answer

The %p conversion specifier expects an argument of type pointer to void, the conversion of the pointer to printable characters is implementation-defined. It doesn't state that a null pointer is expected.

The introduction to the standard library functions states that null pointers as arguments to (standard library) functions are considered to be invalid values, unless it is explicitly stated otherwise.

C99 / C11 §7.1.4 p1

[...] If an argument to a function has an invalid value (such as [...] a null pointer, [...] the behavior is undefined.

Examples for (standard library) functions that expect null pointers as valid arguments:

fflush() uses a null pointer for flushing "all streams" (that apply).

freopen() uses a null pointer for indicating the file "currently associated" with the stream.

snprintf() allows to pass a null pointer when 'n' is zero.

realloc() uses a null pointer for allocating a new object.

free() allows to pass a null pointer.

strtok() uses a null pointer for subsequent calls.

If we take the case for snprintf(), it makes sense to allow passing a null pointer when 'n' is zero, but this is not the case for other (standard library) functions that allow a similar zero 'n'. For example: memcpy(), memmove(), strncpy(), memset(), memcmp().

It is not only specified in the introduction to the standard library, but also once again in the introduction to these functions:

C99 §7.21.1 p2 / C11 §7.24.1 p2

Where an argument declared as size_t n specifies the length of the array for a function, n can have the value zero on a call to that function. Unless explicitly stated otherwise in the description of a particular function in this subclause, pointer arguments on such a call shall still have valid values as described in 7.1.4.

Is it intentional?

I don't know whether the UB of %p with a null pointer is in fact intentional, but since the standard explicitly states that null pointers are considered invalid values as arguments to standard library functions, and then it goes and explicitly specifies the cases where a null pointer is a valid argument (snprintf, free, etc), and then it goes and once again repeats the requirement for the arguments to be valid even in zero 'n' cases (memcpy, memmove, memset), then I think it's reasonable to assume that the C standards committee isn't too concerned with having such things undefined.

Body:
Is it undefined behavior to print null pointers with the %p conversion specifier?

#include <stdio.h>

int main(void) {
    void *p = NULL;

    printf("%p", p);

    return 0;
}

The question applies to the C standard, and not to C implementations.


问:
How do I add a Jasmine custom matcher Typescript definition?
I've been looking around and this question seems like a recurring thing. However, none of the solutions I've found seem to work for me.

Using the following:

```<code>{
  "typescript": "2.3.2",
  "jasmine-core": "2.6.1",
  "@types/jasmine": "2.5.47"
}
</code>```

I can't get Typescript to merge the namespace declaration containing my custom matcher definition.

Adding this:

```<code>declare namespace jasmine {
  interface Matchers<T> {
    toBeAnyOf(expected: jasmine.Expected<T>, expectationFailOutput?: any): boolean;
  }
}
</code>```

Hides every other type previously declared on jasmine. Compiler outputs errors such as:

```<code>[ts] Namespace 'jasmine' has no exported member 'CustomMatcherFactories'
[ts] Namespace 'jasmine' has no exported member 'CustomMatcher'.
</code>```

Is there any proper way to add a custom matcher and make it play nicely with Typescript?

There's an additional issue with tslint if you are using tslint:recommended ruleset. Those rules disallow the usage of namespace or module keywords, so I had to disable the linter (or change the "no-namespace" rule) in order to try this out. Unsure how one would get around extending definitions if this is "not recommended".

答:
I had to modify three files when I added custom matchers. I created a file called matchers.ts that contained the actual matchers. I then added an import to test.ts for my matchers.ts file. Finally, I added an interface to the typings.d.ts file which contains my matcher.

matchers.ts (arbitrary name)

```<code>beforeEach(() => {
    jasmine.addMatchers({
        toContainText: () => {
            return {
                compare: (actual: HTMLElement, expectedText: string, customMessage?: string) => {
                    const actualText = actual.textContent;
                    return {
                        pass: actualText.indexOf(expectedText) > -1,
                        get message() {
                            let failureMessage = 'Expected ' + actualText + ' to contain ' + expectedText;

                            if (customMessage) {
                                failureMessage = ' ' + customMessage;
                            }

                            return failureMessage;
                        }
                    };
                }
            };
        },
    });
});
</code>```

test.ts

```<code>import 'test/test-helpers/global/matchers'; (my relative filepath)
</code>```

typings.d.ts

```<code>declare module jasmine {
  interface Matchers {
    toContainText(text: string, message?: string): boolean;
  }
}
</code>```

Body:
I've been looking around and this question seems like a recurring thing. However, none of the solutions I've found seem to work for me.

Using the following:

{
  "typescript": "2.3.2",
  "jasmine-core": "2.6.1",
  "@types/jasmine": "2.5.47"
}

I can't get Typescript to merge the namespace declaration containing my custom matcher definition.

Adding this:

declare namespace jasmine {
  interface Matchers<T> {
    toBeAnyOf(expected: jasmine.Expected<T>, expectationFailOutput?: any): boolean;
  }
}

Hides every other type previously declared on jasmine. Compiler outputs errors such as:

[ts] Namespace 'jasmine' has no exported member 'CustomMatcherFactories'
[ts] Namespace 'jasmine' has no exported member 'CustomMatcher'.

Is there any proper way to add a custom matcher and make it play nicely with Typescript?

There's an additional issue with tslint if you are using tslint:recommended ruleset. Those rules disallow the usage of namespace or module keywords, so I had to disable the linter (or change the "no-namespace" rule) in order to try this out. Unsure how one would get around extending definitions if this is "not recommended".

Body:
I had to modify three files when I added custom matchers. I created a file called matchers.ts that contained the actual matchers. I then added an import to test.ts for my matchers.ts file. Finally, I added an interface to the typings.d.ts file which contains my matcher.

matchers.ts (arbitrary name)

beforeEach(() => {
    jasmine.addMatchers({
        toContainText: () => {
            return {
                compare: (actual: HTMLElement, expectedText: string, customMessage?: string) => {
                    const actualText = actual.textContent;
                    return {
                        pass: actualText.indexOf(expectedText) > -1,
                        get message() {
                            let failureMessage = 'Expected ' + actualText + ' to contain ' + expectedText;

                            if (customMessage) {
                                failureMessage = ' ' + customMessage;
                            }

                            return failureMessage;
                        }
                    };
                }
            };
        },
    });
});

test.ts

import 'test/test-helpers/global/matchers'; (my relative filepath)

typings.d.ts

declare module jasmine {
  interface Matchers {
    toContainText(text: string, message?: string): boolean;
  }
}


问:
One class for two different deserializations
I have a request for two or more different websites. I'm trying to get some data from them and save it to the database. They are basically having the same model of response but with the different names of the JSON fields.
As I know, I can't add more than one @JsonProperty to the field.

First, that came to mind is to create two classes WebOneResponse and WebTwoResponse with @JsonProperty annotation's values that I need, use them for requests to different websites and then parse all of them to some BaseClass that then will be inserted into the database and used inside the application for analysis. (BaseClass, in that case, must have some id that will tell which one of the websites did it came from)

And in that case, I can't even extend any of ****Response from the BaseClass because of annotations. And it becomes very messy.

What is the best practice in that case?

答: Sounds fair and quite normal approach. Additionally i would either create BaseClassFactory that can convert WebOneResponse and WebTwoResponse to  BaseClass, or add toBaseClass methods to each response. However factory approach seems more elegant.


问:
More than one result in a field
If I have a table "messages" and users can send the same message to more than one user, when I show the messages how can I group all the users in a field?

```<code>ID  SUBJECT MESSAGE    FROM     TO
 1  Test 1  Message       1     John
 2  Test 2  Message       2     Jackson
</code>```

THIS IS MY SELECT:

```<code>SELECT messages.id_message, subject, body_message, name_user,
from messages, registro_mensajes
INNER JOIN users on messages.id_user_sender = users.id_user
</code>```

DATABASE:

MESSAGES

```<code>id_message
subject
body_message
id_user_sender
</code>```

REGIST

```<code>id_regist
id_message
id_user_sender
id_user_destin
</code>```

Thx

答:
GROUP_CONCAT() is the excellent, though MySQL-specific, aggregate function for handling this requirement.

You can try something like this.

```<code> SELECT a.message_id, a.message_text,
        GROUP_CONCAT(b.user ORDER BY b.user) users
   FROM message a
   LEFT JOIN destination b ON a.message_id = b.message_id
  GROUP BY a.message_id, a.message_text
</code>```

(Sorry, I cannot figure out your table structure from your question, so this is an example).

The trouble with GROUP_CONCAT(), and the reason some developers avoid it, is this: it converts perfectly good normalized data into a denormalized resultset.  Comma-separated values in columns are a real hassle. But if you only use it for display, it should be fine.

Title: More than one result in a field

Body:
If I have a table "messages" and users can send the same message to more than one user, when I show the messages how can I group all the users in a field?

ID  SUBJECT MESSAGE    FROM     TO
 1  Test 1  Message       1     John
 2  Test 2  Message       2     Jackson

THIS IS MY SELECT:

SELECT messages.id_message, subject, body_message, name_user,
from messages, registro_mensajes
INNER JOIN users on messages.id_user_sender = users.id_user

DATABASE:

MESSAGES

id_message
subject
body_message
id_user_sender

REGIST

id_regist
id_message
id_user_sender
id_user_destin

Thx

Body:
GROUP_CONCAT() is the excellent, though MySQL-specific, aggregate function for handling this requirement.

You can try something like this.

 SELECT a.message_id, a.message_text,
        GROUP_CONCAT(b.user ORDER BY b.user) users
   FROM message a
   LEFT JOIN destination b ON a.message_id = b.message_id
  GROUP BY a.message_id, a.message_text

(Sorry, I cannot figure out your table structure from your question, so this is an example).

The trouble with GROUP_CONCAT(), and the reason some developers avoid it, is this: it converts perfectly good normalized data into a denormalized resultset.  Comma-separated values in columns are a real hassle. But if you only use it for display, it should be fine.


问:
PySpark isin function
I am converting my legacy Python code to Spark using PySpark.

I would like to get a PySpark equivalent of:

```<code>usersofinterest = actdataall[actdataall['ORDValue'].isin(orddata['ORDER_ID'].unique())]['User ID']
</code>```

Both, actdataall and orddata are Spark dataframes.

I don't want to use toPandas() function given the drawback associated with it.

答:
So, you have two spark dataframe. One is actdataall and other is orddata, then use following command to get your desire result.</p>

```<code>usersofinterest  = actdataall.where(actdataall['ORDValue'].isin(orddata.select('ORDER_ID').distinct().rdd.flatMap(lambda x:x).collect()[0])).select('User ID')
</code>```

ContentLicense: CC BY-SA 4.0

Title: PySpark isin function

Body:
I am converting my legacy Python code to Spark using PySpark.

I would like to get a PySpark equivalent of:

usersofinterest = actdataall[actdataall['ORDValue'].isin(orddata['ORDER_ID'].unique())]['User ID']

Both, actdataall and orddata are Spark dataframes.

I don't want to use toPandas() function given the drawback associated with it.

Body:
So, you have two spark dataframe. One is actdataall and other is orddata, then use following command to get your desire result.

usersofinterest  = actdataall.where(actdataall['ORDValue'].isin(orddata.select('ORDER_ID').distinct().rdd.flatMap(lambda x:x).collect()[0])).select('User ID')


问:
Store Ascii Values
how to store Ascii character a to z in any one type of variable using strcpy?</p>

```<code>for(i=97;i<122;i++)
{
    for(j=97;j<122;j++)
    {
        printf("%c%c",i,j);
        int a = strcpy(i,j);
    }
}
</code>```

答:
```<code>int main() {
    int a = 0;
    char c = '\0';
    scanf(" %c", &c);
    a = c + 0;
    printf("%d", a);
}
</code>```

Output: ASCII value of entered character.

I have provided the the code. Please refere it.
Why this is So?
Focus on the addition operation which is assigned to the int variable a. During compilation of this operation compiler finds that the variable c is of char type but; the operator + is next to it and hence compiler uses the ascii value of the character stored in c variable.

I hope it will helpful  for you. Thank you.

Title: Store Ascii Values

Body:
how to store Ascii character a to z in any one type of variable using strcpy?

for(i=97;i<122;i++)
{
    for(j=97;j<122;j++)
    {
        printf("%c%c",i,j);
        int a = strcpy(i,j);
    }
}

Body:
int main() {
    int a = 0;
    char c = '\0';
    scanf(" %c", &c);
    a = c + 0;
    printf("%d", a);
}

Output: ASCII value of entered character.

I have provided the the code. Please refere it.
Why this is So?
Focus on the addition operation which is assigned to the int variable a. During compilation of this operation compiler finds that the variable c is of char type but; the operator + is next to it and hence compiler uses the ascii value of the character stored in c variable.

I hope it will helpful  for you. Thank you.


问:
how can i allow url fopen on .htaccess?
i want to allow the url_fopen on the php.ini settings set to ON, but i dnt have access to this on a shared server, how can i use the .htaccess file to allow this to hapen, thanks :))</p>

答:
You can change the values in your PHP code on the fly http://php.net/manual/en/function.ini-set.php

I agree with @Dan Grossman though - be careful what you're changing.

Title: how can i allow url fopen on .htaccess?


问:
navController.push does not open next page in release-apk
---update 1---

It looks like a minimization issue for prod build.

I can reproduce the error by using ionic cordova build android --prod to create apk and adb install to push the apk to the android device.
The error message is:

```<code>main.js:1 ERROR Error: Uncaught (in promise): Error: No provider for t!
Error: No provider for t!
    at Error (native)
    at O (file:///android_asset/www/build/main.js:1:6087)
    at T (file:///android_asset/www/build/main.js:1:6346)
    at t._throwOrNull (file:///android_asset/www/build/main.js:3:5428)
    at t._getByKeyDefault (file:///android_asset/www/build/main.js:3:5761)
    at t._getByKey (file:///android_asset/www/build/main.js:3:5146)
    at t.get (file:///android_asset/www/build/main.js:3:3554)
    at e.get [as _Logger_81] (file:///android_asset/www/build/main.js:25:21486)
</code>```

---main thread---

I have 3-line code behind a button. The code is attached at the end.

All 3-line functionality works as expected in ionic serve and ionic cordova run android in a real android device.

However, the 3rd line does not work if the code/apk is:

```<code>1. built by `ionic cordova build android --prod --release`,
2. published to google play store,
3. installed to the same android device.
</code>```

It means that DubPage is not opened by clicking the button.

What I troubleshooted:

```<code>1. this.logger.log() does send data to logentries, i.e. `goToDub`
function is called succesfully.
2.  this.player.pause() does stop the html5 video player
3.  I have no idea how to debug `this.navCtrl.push()`.
4. The only possible cause I can come up with is the lazy loading of `DubPage`, even though I dont quite believe it being the reason.
</code>```

Any hint?

```<code>  goToDub() {
    this.logger.log(JSON.stringify(this.video)); //send log to 3rd party cloud log service: logentries
    this.player.pause(); // stop html5 video player video.js in the page
    this.navCtrl.push("DubPage", { video: this.video }); // go to DubPage does NOT work in play store released apk version;
  }
</code>```

In addtion, my package.json

```<code>{
    "name": "dubwork",
    "version": "0.0.1",
    "author": "Ionic Framework",
    "homepage": "http://ionicframework.com/",
    "private": true,
    "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
    },
    "dependencies": {
        "@angular/common": "4.1.2",
        "@angular/compiler": "4.1.2",
        "@angular/compiler-cli": "4.1.2",
        "@angular/core": "4.1.2",
        "@angular/forms": "4.1.2",
        "@angular/http": "4.1.2",
        "@angular/platform-browser": "4.1.2",
        "@angular/platform-browser-dynamic": "4.1.2",
        "@ionic-native/camera": "3.10.2",
        "@ionic-native/core": "3.10.2",
        "@ionic-native/facebook": "^3.10.3",
        "@ionic-native/file": "^3.10.3",
        "@ionic-native/keyboard": "^3.10.3",
        "@ionic-native/media": "^3.10.3",
        "@ionic-native/splash-screen": "3.10.2",
        "@ionic-native/status-bar": "3.10.2",
        "@ionic-native/transfer": "^3.10.3",
        "@ionic/storage": "2.0.1",
        "angular2-logger": "^0.6.0",
        "angularfire2": "^4.0.0-rc.1",
        "cordova-android": "^6.2.3",
        "cordova-plugin-compat": "^1.1.0",
        "cordova-plugin-console": "^1.0.7",
        "cordova-plugin-crosswalk-webview": "^2.3.0",
        "cordova-plugin-device": "^1.1.6",
        "cordova-plugin-facebook4": "^1.9.1",
        "cordova-plugin-file": "^4.3.3",
        "cordova-plugin-file-transfer": "^1.6.3",
        "cordova-plugin-media": "^3.0.1",
        "cordova-plugin-splashscreen": "^4.0.3",
        "cordova-plugin-statusbar": "^2.2.3",
        "cordova-plugin-whitelist": "^1.3.2",
        "cordova-plugin-wkwebview-engine": "git+https://github.com/driftyco/cordova-plugin-wkwebview-engine.git",
        "firebase": "^3.9.0",
        "ionic-angular": "3.3.0",
        "ionic-plugin-keyboard": "^2.2.1",
        "ionicons": "3.0.0",
        "rxjs": "5.1.1",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.11"
    },
    "devDependencies": {
        "@ionic/app-scripts": "1.3.7",
        "@ionic/cli-plugin-cordova": "1.4.0",
        "@ionic/cli-plugin-ionic-angular": "1.3.1",
        "typescript": "2.3.3"
    },
    "description": "An Ionic project",
    "cordova": {
        "plugins": {
            "cordova-plugin-facebook4": {
                "APP_ID": "229997797493525",
                "APP_NAME": "dubLearn-mobile"
            },
            "cordova-plugin-console": {},
            "cordova-plugin-device": {},
            "cordova-plugin-splashscreen": {},
            "cordova-plugin-statusbar": {},
            "cordova-plugin-whitelist": {},
            "ionic-plugin-keyboard": {},
            "cordova-plugin-crosswalk-webview": {
                "XWALK_VERSION": "23+",
                "XWALK_LITEVERSION": "xwalk_core_library_canary:17+",
                "XWALK_COMMANDLINE": "--disable-pull-to-refresh-effect",
                "XWALK_MODE": "embedded",
                "XWALK_MULTIPLEAPK": "true"
            },
            "cordova-plugin-wkwebview-engine": {},
            "cordova-plugin-media": {},
            "cordova-plugin-file-transfer": {}
        },
        "platforms": [
            "android"
        ]
    }
}
</code>```

答:
It turns out that the error was caused by using angular2-logger package alone. logentries is irrelevant.

Steps to reproduce the issue:

ionic start logger-bug blank

npm install --save angular2-logger

add angular2-logger package in app.module.ts provider

add angular2-logger package in home.ts and log a debug message

using ionic cordova run android, the app opens in android device without error

using ionic cordova run android --prod, the app shows promise t error

Body:
---update 1---

It looks like a minimization issue for prod build.

I can reproduce the error by using ionic cordova build android --prod to create apk and adb install to push the apk to the android device.
The error message is:

main.js:1 ERROR Error: Uncaught (in promise): Error: No provider for t!
Error: No provider for t!
    at Error (native)
    at O (file:///android_asset/www/build/main.js:1:6087)
    at T (file:///android_asset/www/build/main.js:1:6346)
    at t._throwOrNull (file:///android_asset/www/build/main.js:3:5428)
    at t._getByKeyDefault (file:///android_asset/www/build/main.js:3:5761)
    at t._getByKey (file:///android_asset/www/build/main.js:3:5146)
    at t.get (file:///android_asset/www/build/main.js:3:3554)
    at e.get [as _Logger_81] (file:///android_asset/www/build/main.js:25:21486)

---main thread---

I have 3-line code behind a button. The code is attached at the end.

All 3-line functionality works as expected in ionic serve and ionic cordova run android in a real android device.

However, the 3rd line does not work if the code/apk is:

1. built by `ionic cordova build android --prod --release`,
2. published to google play store,
3. installed to the same android device.

It means that DubPage is not opened by clicking the button.

What I troubleshooted:

1. this.logger.log() does send data to logentries, i.e. `goToDub`
function is called succesfully.
2.  this.player.pause() does stop the html5 video player
3.  I have no idea how to debug `this.navCtrl.push()`.
4. The only possible cause I can come up with is the lazy loading of `DubPage`, even though I dont quite believe it being the reason.

Any hint?

  goToDub() {
    this.logger.log(JSON.stringify(this.video)); //send log to 3rd party cloud log service: logentries
    this.player.pause(); // stop html5 video player video.js in the page
    this.navCtrl.push("DubPage", { video: this.video }); // go to DubPage does NOT work in play store released apk version;
  }

In addtion, my package.json

{
    "name": "dubwork",
    "version": "0.0.1",
    "author": "Ionic Framework",
    "homepage": "http://ionicframework.com/",
    "private": true,
    "scripts": {
        "clean": "ionic-app-scripts clean",
        "build": "ionic-app-scripts build",
        "lint": "ionic-app-scripts lint",
        "ionic:build": "ionic-app-scripts build",
        "ionic:serve": "ionic-app-scripts serve"
    },
    "dependencies": {
        "@angular/common": "4.1.2",
        "@angular/compiler": "4.1.2",
        "@angular/compiler-cli": "4.1.2",
        "@angular/core": "4.1.2",
        "@angular/forms": "4.1.2",
        "@angular/http": "4.1.2",
        "@angular/platform-browser": "4.1.2",
        "@angular/platform-browser-dynamic": "4.1.2",
        "@ionic-native/camera": "3.10.2",
        "@ionic-native/core": "3.10.2",
        "@ionic-native/facebook": "^3.10.3",
        "@ionic-native/file": "^3.10.3",
        "@ionic-native/keyboard": "^3.10.3",
        "@ionic-native/media": "^3.10.3",
        "@ionic-native/splash-screen": "3.10.2",
        "@ionic-native/status-bar": "3.10.2",
        "@ionic-native/transfer": "^3.10.3",
        "@ionic/storage": "2.0.1",
        "angular2-logger": "^0.6.0",
        "angularfire2": "^4.0.0-rc.1",
        "cordova-android": "^6.2.3",
        "cordova-plugin-compat": "^1.1.0",
        "cordova-plugin-console": "^1.0.7",
        "cordova-plugin-crosswalk-webview": "^2.3.0",
        "cordova-plugin-device": "^1.1.6",
        "cordova-plugin-facebook4": "^1.9.1",
        "cordova-plugin-file": "^4.3.3",
        "cordova-plugin-file-transfer": "^1.6.3",
        "cordova-plugin-media": "^3.0.1",
        "cordova-plugin-splashscreen": "^4.0.3",
        "cordova-plugin-statusbar": "^2.2.3",
        "cordova-plugin-whitelist": "^1.3.2",
        "cordova-plugin-wkwebview-engine": "git+https://github.com/driftyco/cordova-plugin-wkwebview-engine.git",
        "firebase": "^3.9.0",
        "ionic-angular": "3.3.0",
        "ionic-plugin-keyboard": "^2.2.1",
        "ionicons": "3.0.0",
        "rxjs": "5.1.1",
        "sw-toolbox": "3.6.0",
        "zone.js": "0.8.11"
    },
    "devDependencies": {
        "@ionic/app-scripts": "1.3.7",
        "@ionic/cli-plugin-cordova": "1.4.0",
        "@ionic/cli-plugin-ionic-angular": "1.3.1",
        "typescript": "2.3.3"
    },
    "description": "An Ionic project",
    "cordova": {
        "plugins": {
            "cordova-plugin-facebook4": {
                "APP_ID": "229997797493525",
                "APP_NAME": "dubLearn-mobile"
            },
            "cordova-plugin-console": {},
            "cordova-plugin-device": {},
            "cordova-plugin-splashscreen": {},
            "cordova-plugin-statusbar": {},
            "cordova-plugin-whitelist": {},
            "ionic-plugin-keyboard": {},
            "cordova-plugin-crosswalk-webview": {
                "XWALK_VERSION": "23+",
                "XWALK_LITEVERSION": "xwalk_core_library_canary:17+",
                "XWALK_COMMANDLINE": "--disable-pull-to-refresh-effect",
                "XWALK_MODE": "embedded",
                "XWALK_MULTIPLEAPK": "true"
            },
            "cordova-plugin-wkwebview-engine": {},
            "cordova-plugin-media": {},
            "cordova-plugin-file-transfer": {}
        },
        "platforms": [
            "android"
        ]
    }
}


问:
Run command in interactive ncat shell via bash script
I have the below bash script and I'm trying to get the subsequent python command to run within the Ncat shell once a connection is established. Is there a way to do this?

#!/bin/bash
ncat -vnl 443 --ssl
python -c 'import pty;pty.spawn("/bin/bash")'

答: The solution I've come up with is to have Ncat run a bash script containing the python command on the penetration test box when a connection is established rather than /bin/bash. This way only the listener is required on the server and we get our fully interactive shell. </p>


问:
Importing same spring application context file multiple times
I have a big web project which is split across multiple modules. Each of the module has its own spring application context xml file. In the parent project's applicationContext.xml file I have imported all the child module's applicationContext.xml files. Say I have following child applicationContext.xml files

```<code>    -aContext.xml
    -bContext.xml
    -cContext.xml
</code>```

In the parent project's applicationContext.xml file all of these are being imported. But some of the places I see inside aContext.xml bContext.xml and cContext.xml are being imported again?

The hierarchy is something like this -

```<code>     -applicationContext.xml(parent)
         -aContext.xml
             -bContext.xml
             -cContext.xml
         -bContext.xml
         -cContext.xml
</code>```

I can understand that there is no harm doing it as my web application is up and running perfectly. Only thing I am trying understand is, is there any performance glitch of doing it this way? If I remove the nested xml files and import them only once, will I see any performance improvement?

答:
I know this post is quite old, but I though of posting this answer as there are scenarios where such implementation can also cause different issues apart from performance one. When fixed, definitely there will be performance improvement but, if not fixed, it may cause issues to your web application. I have recently got this issue in a high traffic web application where the same application context file was getting initialized multiple times and caused multiple threads hung on the web application server.

During this application context initialization it was trying to
  initialize some Spring MVC classes which further down the line tried
  to initialize some charsets and one of the charset specific to IBM SDK
  - 'IBM1385' tried to access ExtendedCharsets and then AbstractCharsetProvided.aliases which got deadlock because of multiple
  concurrent calls. This is a known issue and more details can be found
  here

This is one instance where initializing same application context file multiple times in a multi threaded env (like web applications) have caused issues and cause a high down time on the server. Similarly there can be even more issues with such implementation and should be avoided.

Also, I agree with  @Shailendra answer and when this will be fixed, it will definitely improve the performance as well as in that case Spring will not instantiate multiple instances of the same class which as such not required by our application.

Hope that helps.

Body:
I have a big web project which is split across multiple modules. Each of the module has its own spring application context xml file. In the parent project's applicationContext.xml file I have imported all the child module's applicationContext.xml files. Say I have following child applicationContext.xml files

    -aContext.xml
    -bContext.xml
    -cContext.xml

In the parent project's applicationContext.xml file all of these are being imported. But some of the places I see inside aContext.xml bContext.xml and cContext.xml are being imported again?

The hierarchy is something like this -

     -applicationContext.xml(parent)
         -aContext.xml
             -bContext.xml
             -cContext.xml
         -bContext.xml
         -cContext.xml

I can understand that there is no harm doing it as my web application is up and running perfectly. Only thing I am trying understand is, is there any performance glitch of doing it this way? If I remove the nested xml files and import them only once, will I see any performance improvement?


问:
How to connect mysql tables
I have two tables in same database, one for pictures and the other table for picture comments. How can i write a sql command to get all the comments belonging to each particular picture?</p>

答:
Joining as mentioned above is a good solution.
But you can also relate the two tables via primary key and foriegn key.
Create a primary key field in picture table and create a foriegn key field in comments table.</p>

Title: How to connect mysql tables


问:
Team Build, copy file target issue
I have this team build target setup to after compile

```<code>  <Target Name="AfterCompile">
    <Copy SourceFiles="$(SolutionRoot)\Development_VS2008\MyCompanyName.SharePoint.12" DestinationFolder="c:\testing"></Copy>
  </Target>
</code>```

I want the folder structure copied from source to destination...

Amazingly I am getting this error

Could not copy the file "C:\TFS\NightlyBuild\Sources\Development_VS2008\MyCompanyName.SharePoint.12\"
    to the destination file "c:\testing\", because the destination is a folder instead of a file.
    To copy the source file into a folder, consider using the DestinationFolder parameter instead of DestinationFiles.

As you can see I am indeed using the destinationfolder parameter, does anyone know what I am doing wrong?

答:
I think it might be just because SourceFiles is a directory rather than the files you want to copy. Try this:

```<code><Target Name="AfterCompile">
    <ItemGroup>
        <FilesToCopy Include="$(SolutionRoot)\Development_VS2008\MyCompanyName.SharePoint.12\**\*.*"/>
    </ItemGroup>

    <Copy SourceFiles="@(FilesToCopy)" DestinationFolder="c:\testing\%(RecursiveDir)"/>
</Target>
</code>```

OwnerDisplayName: Michael L

Title: Team Build, copy file target issue

Body:
I have this team build target setup to after compile

  <Target Name="AfterCompile">
    <Copy SourceFiles="$(SolutionRoot)\Development_VS2008\MyCompanyName.SharePoint.12" DestinationFolder="c:\testing"></Copy>
  </Target>

I want the folder structure copied from source to destination...

Amazingly I am getting this error

Could not copy the file "C:\TFS\NightlyBuild\Sources\Development_VS2008\MyCompanyName.SharePoint.12\"
    to the destination file "c:\testing\", because the destination is a folder instead of a file.
    To copy the source file into a folder, consider using the DestinationFolder parameter instead of DestinationFiles.

As you can see I am indeed using the destinationfolder parameter, does anyone know what I am doing wrong?

Body:
I think it might be just because SourceFiles is a directory rather than the files you want to copy. Try this:

<Target Name="AfterCompile">
    <ItemGroup>
        <FilesToCopy Include="$(SolutionRoot)\Development_VS2008\MyCompanyName.SharePoint.12\**\*.*"/>
    </ItemGroup>

    <Copy SourceFiles="@(FilesToCopy)" DestinationFolder="c:\testing\%(RecursiveDir)"/>
</Target>

OwnerDisplayName: Kent Boogaart

LastEditorDisplayName: Kent Boogaart


问:
Implementing UnitOfWork with Castle.Windsor
Simple question.

How do I use UnitOfWork with Castle.Windsor, nHibernate, and ASP.NET MVC?

Now for the extended details. In my quest to understand the UnitOfWork pattern, I'm having difficulty coming across anything that uses a direct example in conjunction with Castle.Windsor, specifically in regards to the way it needs to be installed.

Here is my understanding so far.

IUnitOfWork

The IUnitOfWork interface is used to declare the pattern

The UnitOfWork class must Commit and Rollback transactions, and Expose a Session.

So with that said, here is my IUnitOfWork. (I am using Fluent nHibernate)

```<code>public interface IUnitOfWork : IDisposable
{
    ISession Session { get; private set; }
    void Rollback();
    void Commit();
}
</code>```

So here is my Castle.Windsor Container Bootstrapper (ASP.NET MVC)

```<code>public class WindsorContainerFactory
{
    private static Castle.Windsor.IWindsorContainer container;
    private static readonly object SyncObject = new object();

    public static Castle.Windsor.IWindsorContainer Current()
    {
        if (container == null)
        {
            lock (SyncObject)
            {
                if (container == null)
                {
                    container = new Castle.Windsor.WindsorContainer();

                    container.Install(new Installers.SessionInstaller());
                    container.Install(new Installers.RepositoryInstaller());
                    container.Install(new Installers.ProviderInstaller());
                    container.Install(new Installers.ControllerInstaller());
                }
            }

        }

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

So now, in my Global.asax file, I have the following...

```<code>    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        // Register the Windsor Container
        ControllerBuilder.Current
            .SetControllerFactory(new Containers.WindsorControllerFactory());
    }
</code>```

Repository

Now I understand that I need to pass the ISession to my Repository. So then, let me assume IMembershipRepository.

```<code>class MembershipRepository : IMembershipRepository
{
   private readonly ISession session;
   public MembershipRepository(ISession session)
   {
      this.session = session;
   }

   public Member RetrieveMember(string email)
   {
      return session.Query<Member>().SingleOrDefault( i => i.Email == email );
   }
}
</code>```

So I am confused, now. Using this method, the ISession doesn't get destroyed properly, and the UnitOfWork never gets used.

I've been informed that UnitOfWork needs to go in the Web Request Level - but I cannot find anything explaining how to actually go about this. I do not use a ServiceLocator of any sort ( as when I tried, I was told this was also bad practice... ).

Confusion -- How does a UnitOfWork get created?

I just don't understand this, in
  general. My thought was that I would
  start passing UnitOfWork into the
  Repository constructors - but if it
  has to go in the Web Request, I'm not
  understanding where the two relate.

Further Code

This is extra code for clarification, simply because I seem to have a habit of never providing the right information for my questions.

Installers

```<code>public class ControllerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            AllTypes.FromThisAssembly()
            .BasedOn<IController>()
            .Configure(c => c.LifeStyle.Transient));
    }
}

public class ProviderInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component
            .For<Membership.IFormsAuthenticationProvider>()
            .ImplementedBy<Membership.FormsAuthenticationProvider>()
            .LifeStyle.Singleton
        );
    }
}

public class RepositoryInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component
            .For<Membership.IMembershipRepository>()
            .ImplementedBy<Membership.MembershipRepository>()
            .LifeStyle.Transient
        );

        container.Register(
            Component
            .For<Characters.ICharacterRepository>()
            .ImplementedBy<Characters.CharacterRepository>()
            .LifeStyle.Transient
        );
    }
}

public class SessionInstaller : Castle.MicroKernel.Registration.IWindsorInstaller
{
    private static ISessionFactory factory;
    private static readonly object SyncObject = new object();

    public void Install(Castle.Windsor.IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<ISessionFactory>()
                .UsingFactoryMethod(SessionFactoryFactory)
                .LifeStyle.Singleton
            );

        container.Register(
            Component.For<ISession>()
            .UsingFactoryMethod(c => SessionFactoryFactory().OpenSession())
            .LifeStyle.Transient
        );
    }

    private static ISessionFactory SessionFactoryFactory()
    {
        if (factory == null)
            lock (SyncObject)
                if (factory == null)
                    factory = Persistence.SessionFactory.Map(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Remote"].ConnectionString);
        return factory;
    }
}
</code>```

UnitOfWork

Here is my UnitOfWork class verbatim.

```<code>public class UnitOfWork : IUnitOfWork
{
    private readonly ISessionFactory sessionFactory;
    private readonly ITransaction transaction;

    public UnitOfWork(ISessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
        Session = this.sessionFactory.OpenSession();
        transaction = Session.BeginTransaction();
    }

    public ISession Session { get; private set; }

    public void Dispose()
    {
        Session.Close();
        Session = null;
    }

    public void Rollback()
    {
        if (transaction.IsActive)
            transaction.Rollback();
    }

    public void Commit()
    {
        if (transaction.IsActive)
            transaction.Commit();
    }
}
</code>```

答:
Your NH Session is a Unit of Work already http://nhforge.org/wikis/patternsandpractices/nhibernate-and-the-unit-of-work-pattern.aspx

So I'm not sure why you would ever need to abstract this out any further. (if anyone reading this answer know's why I would be happy to hear, I've honestly never heard of any reason why you would need to...)

I would implement a simple Session Per Request. I don't know how you would do that with Windsor since I've never used it, but with It's rather simple with StructureMap.

I wrap the structuremap factory to hold my session factory and inject the session into the repositories as required.

```<code>    public static class IoC
    {
        static IoC()
        {
            ObjectFactory.Initialize(x =>
            {
                x.UseDefaultStructureMapConfigFile = false;

                // NHibernate ISessionFactory
                x.ForSingletonOf<ISessionFactory>()
                 .Use(new SessionFactoryManager().CreateSessionFactory());

                // NHibernate ISession
                x.For().HybridHttpOrThreadLocalScoped()
                 .Use(s => s.GetInstance<ISessionFactory>().OpenSession());

                x.Scan(s => s.AssembliesFromApplicationBaseDirectory());
            });

            ObjectFactory.AssertConfigurationIsValid();
        }

        public static T Resolve<T>()
        {
            return ObjectFactory.GetInstance<T>();
        }

        public static void ReleaseAndDisposeAllHttpScopedObjects()
        {
            ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
        }
    }
</code>```

In the global.asax file on Request_End I call the ReleaseAndDisposeAllHttpScopedObjects() method.

```<code>        protected void Application_EndRequest(object sender, EventArgs e)
        {
            IoC.ReleaseAndDisposeAllHttpScopedObjects();
        }
</code>```

So the session is opened when I call my first repository, and when the request is ended it's disposed of. The repositories have a constructor which takes ISession and assigns it to a property. Then I just resolve the repo like:

```<code>var productRepository = IoC.Resolve<IProductRepository>();
</code>```

Hope that helps. There are many other ways of doing it, this is what works for me.

Body:
Simple question.

How do I use UnitOfWork with Castle.Windsor, nHibernate, and ASP.NET MVC?

Now for the extended details. In my quest to understand the UnitOfWork pattern, I'm having difficulty coming across anything that uses a direct example in conjunction with Castle.Windsor, specifically in regards to the way it needs to be installed.

Here is my understanding so far.

IUnitOfWork

The IUnitOfWork interface is used to declare the pattern

The UnitOfWork class must Commit and Rollback transactions, and Expose a Session.

So with that said, here is my IUnitOfWork. (I am using Fluent nHibernate)

public interface IUnitOfWork : IDisposable
{
    ISession Session { get; private set; }
    void Rollback();
    void Commit();
}

So here is my Castle.Windsor Container Bootstrapper (ASP.NET MVC)

public class WindsorContainerFactory
{
    private static Castle.Windsor.IWindsorContainer container;
    private static readonly object SyncObject = new object();

    public static Castle.Windsor.IWindsorContainer Current()
    {
        if (container == null)
        {
            lock (SyncObject)
            {
                if (container == null)
                {
                    container = new Castle.Windsor.WindsorContainer();

                    container.Install(new Installers.SessionInstaller());
                    container.Install(new Installers.RepositoryInstaller());
                    container.Install(new Installers.ProviderInstaller());
                    container.Install(new Installers.ControllerInstaller());
                }
            }

        }

        return container;
    }
}

So now, in my Global.asax file, I have the following...

    protected void Application_Start()
    {
        AreaRegistration.RegisterAllAreas();

        RegisterGlobalFilters(GlobalFilters.Filters);
        RegisterRoutes(RouteTable.Routes);

        // Register the Windsor Container
        ControllerBuilder.Current
            .SetControllerFactory(new Containers.WindsorControllerFactory());
    }

Repository

Now I understand that I need to pass the ISession to my Repository. So then, let me assume IMembershipRepository.

class MembershipRepository : IMembershipRepository
{
   private readonly ISession session;
   public MembershipRepository(ISession session)
   {
      this.session = session;
   }

   public Member RetrieveMember(string email)
   {
      return session.Query<Member>().SingleOrDefault( i => i.Email == email );
   }
}

So I am confused, now. Using this method, the ISession doesn't get destroyed properly, and the UnitOfWork never gets used.

I've been informed that UnitOfWork needs to go in the Web Request Level - but I cannot find anything explaining how to actually go about this. I do not use a ServiceLocator of any sort ( as when I tried, I was told this was also bad practice... ).

Confusion -- How does a UnitOfWork get created?

I just don't understand this, in
  general. My thought was that I would
  start passing UnitOfWork into the
  Repository constructors - but if it
  has to go in the Web Request, I'm not
  understanding where the two relate.

Further Code

This is extra code for clarification, simply because I seem to have a habit of never providing the right information for my questions.

Installers

public class ControllerInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            AllTypes.FromThisAssembly()
            .BasedOn<IController>()
            .Configure(c => c.LifeStyle.Transient));
    }
}

public class ProviderInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component
            .For<Membership.IFormsAuthenticationProvider>()
            .ImplementedBy<Membership.FormsAuthenticationProvider>()
            .LifeStyle.Singleton
        );
    }
}

public class RepositoryInstaller : IWindsorInstaller
{
    public void Install(IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component
            .For<Membership.IMembershipRepository>()
            .ImplementedBy<Membership.MembershipRepository>()
            .LifeStyle.Transient
        );

        container.Register(
            Component
            .For<Characters.ICharacterRepository>()
            .ImplementedBy<Characters.CharacterRepository>()
            .LifeStyle.Transient
        );
    }
}

public class SessionInstaller : Castle.MicroKernel.Registration.IWindsorInstaller
{
    private static ISessionFactory factory;
    private static readonly object SyncObject = new object();

    public void Install(Castle.Windsor.IWindsorContainer container, IConfigurationStore store)
    {
        container.Register(
            Component.For<ISessionFactory>()
                .UsingFactoryMethod(SessionFactoryFactory)
                .LifeStyle.Singleton
            );

        container.Register(
            Component.For<ISession>()
            .UsingFactoryMethod(c => SessionFactoryFactory().OpenSession())
            .LifeStyle.Transient
        );
    }

    private static ISessionFactory SessionFactoryFactory()
    {
        if (factory == null)
            lock (SyncObject)
                if (factory == null)
                    factory = Persistence.SessionFactory.Map(System.Web.Configuration.WebConfigurationManager.ConnectionStrings["Remote"].ConnectionString);
        return factory;
    }
}

UnitOfWork

Here is my UnitOfWork class verbatim.

public class UnitOfWork : IUnitOfWork
{
    private readonly ISessionFactory sessionFactory;
    private readonly ITransaction transaction;

    public UnitOfWork(ISessionFactory sessionFactory)
    {
        this.sessionFactory = sessionFactory;
        Session = this.sessionFactory.OpenSession();
        transaction = Session.BeginTransaction();
    }

    public ISession Session { get; private set; }

    public void Dispose()
    {
        Session.Close();
        Session = null;
    }

    public void Rollback()
    {
        if (transaction.IsActive)
            transaction.Rollback();
    }

    public void Commit()
    {
        if (transaction.IsActive)
            transaction.Commit();
    }
}

Body:
Your NH Session is a Unit of Work already http://nhforge.org/wikis/patternsandpractices/nhibernate-and-the-unit-of-work-pattern.aspx

So I'm not sure why you would ever need to abstract this out any further. (if anyone reading this answer know's why I would be happy to hear, I've honestly never heard of any reason why you would need to...)

I would implement a simple Session Per Request. I don't know how you would do that with Windsor since I've never used it, but with It's rather simple with StructureMap.

I wrap the structuremap factory to hold my session factory and inject the session into the repositories as required.

    public static class IoC
    {
        static IoC()
        {
            ObjectFactory.Initialize(x =>
            {
                x.UseDefaultStructureMapConfigFile = false;

                // NHibernate ISessionFactory
                x.ForSingletonOf<ISessionFactory>()
                 .Use(new SessionFactoryManager().CreateSessionFactory());

                // NHibernate ISession
                x.For().HybridHttpOrThreadLocalScoped()
                 .Use(s => s.GetInstance<ISessionFactory>().OpenSession());

                x.Scan(s => s.AssembliesFromApplicationBaseDirectory());
            });

            ObjectFactory.AssertConfigurationIsValid();
        }

        public static T Resolve<T>()
        {
            return ObjectFactory.GetInstance<T>();
        }

        public static void ReleaseAndDisposeAllHttpScopedObjects()
        {
            ObjectFactory.ReleaseAndDisposeAllHttpScopedObjects();
        }
    }

In the global.asax file on Request_End I call the ReleaseAndDisposeAllHttpScopedObjects() method.

        protected void Application_EndRequest(object sender, EventArgs e)
        {
            IoC.ReleaseAndDisposeAllHttpScopedObjects();
        }

So the session is opened when I call my first repository, and when the request is ended it's disposed of. The repositories have a constructor which takes ISession and assigns it to a property. Then I just resolve the repo like:

var productRepository = IoC.Resolve<IProductRepository>();

Hope that helps. There are many other ways of doing it, this is what works for me.


问:
Using webview in tab bar application
I am using this code to load html content in webview

```<code>    - (void)viewDidLoad {
        [super viewDidLoad];

        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"about.html" ofType:nil]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [webView loadRequest:request];

    }
</code>```

When AboutViewController tab(featured) is selected .Program shows blank screen does loads any kind of html content .
The sample program is given on following link .https://drive.google.com/open?id=0B5pNDpbvZ8SnbEhzMFFTNXJDXzA
Why code is not loading html ?

答:
Reviewing your project, your code is fine but the real problem is that your AboutViewController viewDidLoad is not called, you must change the segue type of your NavigationController from push to rootViewController, to you AboutViewController and start working as should

Edited Code

```<code>- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString *pathString = [[NSBundle mainBundle]pathForResource:@"about.html" ofType:nil];
    if(pathString)
    {
        NSURL *url = [NSURL fileURLWithPath:pathString];
        if(url)
        {
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            [webView loadRequest:request];
        }
        NSLog(@"%@", url.description);
    }
    NSLog(@"%@", pathString);

}
</code>```

WAS

SHOULD BE

RESULT

Hope this helps you

Title: Using webview in tab bar application

Body:
I am using this code to load html content in webview

    - (void)viewDidLoad {
        [super viewDidLoad];

        NSURL *url = [NSURL fileURLWithPath:[[NSBundle mainBundle]pathForResource:@"about.html" ofType:nil]];
        NSURLRequest *request = [NSURLRequest requestWithURL:url];
        [webView loadRequest:request];

    }

When AboutViewController tab(featured) is selected .Program shows blank screen does loads any kind of html content .
The sample program is given on following link .https://drive.google.com/open?id=0B5pNDpbvZ8SnbEhzMFFTNXJDXzA
Why code is not loading html ?

Body:
Reviewing your project, your code is fine but the real problem is that your AboutViewController viewDidLoad is not called, you must change the segue type of your NavigationController from push to rootViewController, to you AboutViewController and start working as should

Edited Code

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSString *pathString = [[NSBundle mainBundle]pathForResource:@"about.html" ofType:nil];
    if(pathString)
    {
        NSURL *url = [NSURL fileURLWithPath:pathString];
        if(url)
        {
            NSURLRequest *request = [NSURLRequest requestWithURL:url];
            [webView loadRequest:request];
        }
        NSLog(@"%@", url.description);
    }
    NSLog(@"%@", pathString);

}

WAS

SHOULD BE

RESULT

Hope this helps you


问:
is it possible to store the multiple phone number for a specific user without using loop in laravel 5.4
I have a relationship in laravel 5.4,

in User model

```<code>public function phones()
    {
        return $this->hasMany(UserPhone::class);
    }
</code>```

in UserPhone model

```<code>public function user()
   {
        return $this->belongsTo(User::class);
   }
</code>```

now if from a form i got to input multiple phones record like:

```<code><input type="text" name="phone[]">
<input type="text" name="phone[]">
<input type="text" name="phone[]">
</code>```

so on then,
 how can I store these phones for the particular user that has logged in currently in laravl5.4???

答:
try this</p>

```<code>$user = User::find($id) ;
$user->phones()->saveMany([
new UserPhone(['phone'=> Input::get('phone')[0] ]) ,
new UserPhone(['phone'=> Input::get('phone')[1] ]),
...
]);
</code>```

Body:
I have a relationship in laravel 5.4,

in User model

public function phones()
    {
        return $this->hasMany(UserPhone::class);
    }

in UserPhone model

public function user()
   {
        return $this->belongsTo(User::class);
   }

now if from a form i got to input multiple phones record like:

<input type="text" name="phone[]">
<input type="text" name="phone[]">
<input type="text" name="phone[]">

so on then,
 how can I store these phones for the particular user that has logged in currently in laravl5.4???

Body:
try this

$user = User::find($id) ;
$user->phones()->saveMany([
new UserPhone(['phone'=> Input::get('phone')[0] ]) ,
new UserPhone(['phone'=> Input::get('phone')[1] ]),
...
]);