问:
How can I print out a single string from two sets of data?
I just started learning Python this week by working on a personal project. The goal of the script I'm working on is to essentially scrape the user's ID and comment from a given news article URL and put them together.

So far it looks like this:

```<code>from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

articleurl = "http://news.nate.com/view/20170401n02609?mid=n1008"

articleid = articleurl[26:40]

print(articleid)

commentslink = "http://comm.news.nate.com/Comment/ArticleComment/list?artc_sq=" + articleid + "&prebest=0&order=O&mid=n1008&domain=&argList=0"
commentslink2 = "http://comm.news.nate.com/Comment/ArticleComment/list?artc_sq=" + articleid + "&order=O&cmtr_fl=0&prebest=0&clean_idx=&user_nm=&fold=&mid=n1008&domain=&argList=0&return_sq=&twitterAuth=N&connectAuth=N&page=2#comment"

print(commentslink)
print(commentslink2)

chrome_path = r"F:\Downloads\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get(commentslink)

userlist = []
commentlist = []

usernames = (driver.find_elements_by_class_name("""nameui"""))
for userid in usernames:
    userlist += userid.text
    userlist.append(userid.text)
    print(userid.text)

comments = (driver.find_elements_by_class_name("""usertxt"""))
for comment in comments:
    commentlist += comment.text
    commentlist.append(comment.text)
    print(comment.text)
</code>```

However, the console spits out the complete list of user ID's followed by the complete list of comments. I would like the user's comment to follow right after the user's ID. Right now, the console gives me this:

```<code>(1) bong****
(2) yang****
(3) hide****
... (continues through rest of user ID list)
(1) 어려보이고 싶어하는 순간 나이 먹은거래...
(2) 예능안보내는 이유가 있었네
(3) 드럽게 재미없네
... (continues through rest of comment list)
</code>```

I've been trying to get it to look like this (numbers are for clarity):

```<code>(1) bong****: (1) 어려보이고 싶어하는 순간 나이 먹은거래...
</code>```

I've been trying to work this out but nothing I've done has worked. I am thinking the problem is with the way the variables or for loops are coded. Are there any ideas on how to fix this?

Any help would be appreciated, thanks!

答:
Use append() and zip():

```<code>userlist = []
commentlist = []

userlist.append("user1")
userlist.append("user2")
commentlist.append("Hello")
commentlist.append("Goodbye")

results = list(zip(userlist, commentlist))
print(results)

for user,comment in results:
    print("{}: {}".format(user,comment) )

--output:--
[('user1', 'Hello'), ('user2', 'Goodbye')]
user1: Hello
user2: Goodbye
</code>```

Here's the difference between append() and +=:

```<code>data1 = []
data2 = []

data1 += "hello"
data2.append("hello")

print(data1)
print(data2)

--output:--
['h', 'e', 'l', 'l', 'o']
['hello']
</code>```

You can think of a string as a list of characters.  += instructs python to take every element of the list on the right hand side and add it to the list on the left hand side. On the other hand, append() adds one thing to a list--the argument.

If you end up with something like this:

```<code>userlist = [
    "user1",
    "user2",
    "user1",
    "user3",
    "user2",
    "user1"
]

commentlist = [
    "Hello",
    "Goodbye",
    "Yellow",
    "Blue",
    "Red",
    "Clouds"
]
</code>```

Then you can do this if you want:

```<code>import itertools as iter

userlist = [
    "user1",
    "user2",
    "user1",
    "user3",
    "user2",
    "user1"
]

commentlist = [
    "Hello",
    "Goodbye",
    "Yellow",
    "Blue",
    "Red",
    "Clouds"
]

results = list(zip(userlist, commentlist))
sorted_results = sorted(results)
print(sorted_results)

for user, group in iter.groupby(sorted_results, lambda t: t[0]):
    print("{}:".format(user) )
    for tuple_ in group:
        print("\t{}".format(tuple_[1]) )

--output:--
[('user1', 'Clouds'), ('user1', 'Hello'), ('user1', 'Yellow'), ('user2', 'Goodbye'), ('user2', 'Red'), ('user3', 'Blue')]

user1:
    Clouds
    Hello
    Yellow
user2:
    Goodbye
    Red
user3:
    Blue
</code>```

By the way, """nameui""" is equivalent to "nameui" and 'nameui', so don't bother using triple double quotes.  Triple quoted strings are for multiline strings.

Also, unless you are doing more complex things, like clicking on links, you can use BeautifulSoup or lxml to scrape web pages.

Body:
I just started learning Python this week by working on a personal project. The goal of the script I'm working on is to essentially scrape the user's ID and comment from a given news article URL and put them together.

So far it looks like this:

from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

articleurl = "http://news.nate.com/view/20170401n02609?mid=n1008"

articleid = articleurl[26:40]

print(articleid)

commentslink = "http://comm.news.nate.com/Comment/ArticleComment/list?artc_sq=" + articleid + "&prebest=0&order=O&mid=n1008&domain=&argList=0"
commentslink2 = "http://comm.news.nate.com/Comment/ArticleComment/list?artc_sq=" + articleid + "&order=O&cmtr_fl=0&prebest=0&clean_idx=&user_nm=&fold=&mid=n1008&domain=&argList=0&return_sq=&twitterAuth=N&connectAuth=N&page=2#comment"

print(commentslink)
print(commentslink2)

chrome_path = r"F:\Downloads\chromedriver_win32\chromedriver.exe"
driver = webdriver.Chrome(chrome_path)
driver.get(commentslink)

userlist = []
commentlist = []

usernames = (driver.find_elements_by_class_name("""nameui"""))
for userid in usernames:
    userlist += userid.text
    userlist.append(userid.text)
    print(userid.text)

comments = (driver.find_elements_by_class_name("""usertxt"""))
for comment in comments:
    commentlist += comment.text
    commentlist.append(comment.text)
    print(comment.text)

However, the console spits out the complete list of user ID's followed by the complete list of comments. I would like the user's comment to follow right after the user's ID. Right now, the console gives me this:

(1) bong****
(2) yang****
(3) hide****
... (continues through rest of user ID list)
(1) 어려보이고 싶어하는 순간 나이 먹은거래...
(2) 예능안보내는 이유가 있었네
(3) 드럽게 재미없네
... (continues through rest of comment list)

I've been trying to get it to look like this (numbers are for clarity):

(1) bong****: (1) 어려보이고 싶어하는 순간 나이 먹은거래...

I've been trying to work this out but nothing I've done has worked. I am thinking the problem is with the way the variables or for loops are coded. Are there any ideas on how to fix this?

Any help would be appreciated, thanks!

Body:
Use append() and zip():

userlist = []
commentlist = []

userlist.append("user1")
userlist.append("user2")
commentlist.append("Hello")
commentlist.append("Goodbye")

results = list(zip(userlist, commentlist))
print(results)

for user,comment in results:
    print("{}: {}".format(user,comment) )

--output:--
[('user1', 'Hello'), ('user2', 'Goodbye')]
user1: Hello
user2: Goodbye

Here's the difference between append() and +=:

data1 = []
data2 = []

data1 += "hello"
data2.append("hello")

print(data1)
print(data2)

--output:--
['h', 'e', 'l', 'l', 'o']
['hello']

You can think of a string as a list of characters.  += instructs python to take every element of the list on the right hand side and add it to the list on the left hand side. On the other hand, append() adds one thing to a list--the argument.

If you end up with something like this:

userlist = [
    "user1",
    "user2",
    "user1",
    "user3",
    "user2",
    "user1"
]

commentlist = [
    "Hello",
    "Goodbye",
    "Yellow",
    "Blue",
    "Red",
    "Clouds"
]

Then you can do this if you want:

import itertools as iter

userlist = [
    "user1",
    "user2",
    "user1",
    "user3",
    "user2",
    "user1"
]

commentlist = [
    "Hello",
    "Goodbye",
    "Yellow",
    "Blue",
    "Red",
    "Clouds"
]

results = list(zip(userlist, commentlist))
sorted_results = sorted(results)
print(sorted_results)

for user, group in iter.groupby(sorted_results, lambda t: t[0]):
    print("{}:".format(user) )
    for tuple_ in group:
        print("\t{}".format(tuple_[1]) )

--output:--
[('user1', 'Clouds'), ('user1', 'Hello'), ('user1', 'Yellow'), ('user2', 'Goodbye'), ('user2', 'Red'), ('user3', 'Blue')]

user1:
    Clouds
    Hello
    Yellow
user2:
    Goodbye
    Red
user3:
    Blue

By the way, """nameui""" is equivalent to "nameui" and 'nameui', so don't bother using triple double quotes.  Triple quoted strings are for multiline strings.

Also, unless you are doing more complex things, like clicking on links, you can use BeautifulSoup or lxml to scrape web pages.


来源: stackexchange

问:
Getting a website with urllib results in HTTP 405 error
Im learning beautifulsoup and was trying to write a small script to find houses on a dutch real estate website. When I try to get the website's content, I'm immediately getting an HTTP405 error:

```<code>  File "funda.py", line 2, in <module>
    html = urlopen("http://www.funda.nl")
  File "<folders>request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "<folders>request.py", line 532, in open
    response = meth(req, response)
  File "<folders>request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "<folders>request.py", line 570, in error
    return self._call_chain(*args)
  File "<folders>request.py", line 504, in _call_chain
    result = func(*args)
  File "<folders>request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 405: Not Allowed
</code>```

What im trying to execute:

```<code>from urllib.request import urlopen
html = urlopen("http://www.funda.nl")
</code>```

Any idea why this is resulting in HTTP405? Im just doing a GET request, right?

答:
It works if you don't use Requests or urllib2:

```<code>import urllib
html = urllib.urlopen("http://www.funda.nl")
</code>```

leovp's comment makes sense.

ContentLicense: CC BY-SA 3.0

Body:
Im learning beautifulsoup and was trying to write a small script to find houses on a dutch real estate website. When I try to get the website's content, I'm immediately getting an HTTP405 error:

  File "funda.py", line 2, in <module>
    html = urlopen("http://www.funda.nl")
  File "<folders>request.py", line 223, in urlopen
    return opener.open(url, data, timeout)
  File "<folders>request.py", line 532, in open
    response = meth(req, response)
  File "<folders>request.py", line 642, in http_response
    'http', request, response, code, msg, hdrs)
  File "<folders>request.py", line 570, in error
    return self._call_chain(*args)
  File "<folders>request.py", line 504, in _call_chain
    result = func(*args)
  File "<folders>request.py", line 650, in http_error_default
    raise HTTPError(req.full_url, code, msg, hdrs, fp)
urllib.error.HTTPError: HTTP Error 405: Not Allowed

What im trying to execute:

from urllib.request import urlopen
html = urlopen("http://www.funda.nl")

Any idea why this is resulting in HTTP405? Im just doing a GET request, right?

Body:
It works if you don't use Requests or urllib2:

import urllib
html = urllib.urlopen("http://www.funda.nl")

leovp's comment makes sense.


问:
Excel-VBA MultiPage: move/reorder/index pages at runtime?
I'm working on a little Excel-VBA GUI/Form for the user to read and write data from/to an .ini file. The UserForm has a MultiPage in which the user creates pages at runtime and each page will represent an ini section. Furthermore, these sections are also indexed in a master section for further processing: at this point I'm looping through the MultiPage pages to create this index. Problem is, the user needs to be able to change the order of this index. Now, is it possible to move the pages within a MultiPage at runtime? I was thinking something to the effect of

```<code>Me.MultiPage1.Pages(i).Index = i + 1
</code>```

but obviously that doesn't work. Alternatively, is there a way I can pass a before:= or anything similar to Multipage.Pages.Add to work around it?
If none of this works, I think I'll create a seperate ListBox control with MoveUp/Down buttons. Open for any better solutions.

答:
Say you have a UserForm that looks like this:

Then you can include the sample code below to move the order of the Page items of the MultiPage:

```<code>Option Explicit

'moves selected page to left
Private Sub CommandButton1_Click()

    Dim pag As MSForms.Page
    Dim lngPageCount As Long

    ' get reference to page
    Set pag = Me.MultiPage1.SelectedItem
    ' get number of pages in multipage
    lngPageCount = Me.MultiPage1.Pages.Count
    ' check if trying to go left beyond first page and put to end
    ' otherwise decrement pages position in multipage
    If pag.Index = 0 Then
        pag.Index = lngPageCount - 1
    Else
        pag.Index = pag.Index - 1
    End If

    ' update caption
    Me.Label1.Caption = pag.Name & " is at index " & pag.Index

End Sub

'moves selected page to right
Private Sub CommandButton2_Click()

    Dim pag As MSForms.Page
    Dim lngPageCount As Long

    ' get reference to page
    Set pag = Me.MultiPage1.SelectedItem
    ' get number of pages in multipage
    lngPageCount = Me.MultiPage1.Pages.Count
    ' check if trying to go right beyond number of pages and put to start
    ' otherwise increment pages position in multipage
    If pag.Index = lngPageCount - 1 Then
        pag.Index = 0
    Else
        pag.Index = pag.Index + 1
    End If

    ' update caption
    Me.Label1.Caption = pag.Name & " is at index " & pag.Index

End Sub
</code>```

Body:
I'm working on a little Excel-VBA GUI/Form for the user to read and write data from/to an .ini file. The UserForm has a MultiPage in which the user creates pages at runtime and each page will represent an ini section. Furthermore, these sections are also indexed in a master section for further processing: at this point I'm looping through the MultiPage pages to create this index. Problem is, the user needs to be able to change the order of this index. Now, is it possible to move the pages within a MultiPage at runtime? I was thinking something to the effect of

Me.MultiPage1.Pages(i).Index = i + 1

but obviously that doesn't work. Alternatively, is there a way I can pass a before:= or anything similar to Multipage.Pages.Add to work around it?
If none of this works, I think I'll create a seperate ListBox control with MoveUp/Down buttons. Open for any better solutions.

Body:
Say you have a UserForm that looks like this:

Then you can include the sample code below to move the order of the Page items of the MultiPage:

Option Explicit

'moves selected page to left
Private Sub CommandButton1_Click()

    Dim pag As MSForms.Page
    Dim lngPageCount As Long

    ' get reference to page
    Set pag = Me.MultiPage1.SelectedItem
    ' get number of pages in multipage
    lngPageCount = Me.MultiPage1.Pages.Count
    ' check if trying to go left beyond first page and put to end
    ' otherwise decrement pages position in multipage
    If pag.Index = 0 Then
        pag.Index = lngPageCount - 1
    Else
        pag.Index = pag.Index - 1
    End If

    ' update caption
    Me.Label1.Caption = pag.Name & " is at index " & pag.Index

End Sub

'moves selected page to right
Private Sub CommandButton2_Click()

    Dim pag As MSForms.Page
    Dim lngPageCount As Long

    ' get reference to page
    Set pag = Me.MultiPage1.SelectedItem
    ' get number of pages in multipage
    lngPageCount = Me.MultiPage1.Pages.Count
    ' check if trying to go right beyond number of pages and put to start
    ' otherwise increment pages position in multipage
    If pag.Index = lngPageCount - 1 Then
        pag.Index = 0
    Else
        pag.Index = pag.Index + 1
    End If

    ' update caption
    Me.Label1.Caption = pag.Name & " is at index " & pag.Index

End Sub


问:
How to get a user to input text n times and store it in a txt file
I am writing code that is supposed to take user information and store it in a text file. I would like to know how I can get the user to input the information n times so that if I ask "Enter 5:" after they enter 5, the next prompt should be "Enter 4:" and so on until they exit the while loop.

This function will take, as an argument, a positive integer n, and create a file named nLinesOfText.txt, containing n lines of text obtained through keyboard input. The function should prompt the user to enter text n times, and it should write that information to file.

```<code>def userInput(n):
    fileName = "nLinesOfText.txt"
    outputFile = open(fileName, "w")
    counter = 0
    # make n positive
    n>0
    # use a while loop for when counter is less than n
    while (counter<n):
        # ask user to print n
        textPrint = input("Enter {}:".format(n))
        #convert the text to a string and write it the output File
        outputFile.write(str(textPrint) + "\n")
        # exit out of the loop when counter is equal to n
        counter = n+1
    # close the file
    outputFile.close()
</code>```

答:
Your code is almost OK.

```<code>n > 0
</code>```

this will not make n positive, remove this line.
use instead:

```<code>abs(n)
</code>```

if you need to invert it.. ex. if the value of n is -5, abs(n) will make it 5.

when you ask the user to put text, you are using your n value:

```<code>textPrint = input("Enter {}:".format(n))
</code>```

the result of this will be that your function always prints "Enter 5:"... use instead:

```<code>textPrint = input("Enter {}/{}:".format(counter+1,n))
</code>```

the result will be like "Enter 1/5:", "Enter 2/5:", ...

Then you use:

```<code>counter = n+1
</code>```

This will only make your counter become larger than your while loop condition and exit your function prematurely, after entering just 1 line of text.
use instead:

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

Hope this puts you back on track :-)

Body:
I am writing code that is supposed to take user information and store it in a text file. I would like to know how I can get the user to input the information n times so that if I ask "Enter 5:" after they enter 5, the next prompt should be "Enter 4:" and so on until they exit the while loop.

This function will take, as an argument, a positive integer n, and create a file named nLinesOfText.txt, containing n lines of text obtained through keyboard input. The function should prompt the user to enter text n times, and it should write that information to file.

def userInput(n):
    fileName = "nLinesOfText.txt"
    outputFile = open(fileName, "w")
    counter = 0
    # make n positive
    n>0
    # use a while loop for when counter is less than n
    while (counter<n):
        # ask user to print n
        textPrint = input("Enter {}:".format(n))
        #convert the text to a string and write it the output File
        outputFile.write(str(textPrint) + "\n")
        # exit out of the loop when counter is equal to n
        counter = n+1
    # close the file
    outputFile.close()

Body:
Your code is almost OK.

n > 0

this will not make n positive, remove this line.
use instead:

abs(n)

if you need to invert it.. ex. if the value of n is -5, abs(n) will make it 5.

when you ask the user to put text, you are using your n value:

textPrint = input("Enter {}:".format(n))

the result of this will be that your function always prints "Enter 5:"... use instead:

textPrint = input("Enter {}/{}:".format(counter+1,n))

the result will be like "Enter 1/5:", "Enter 2/5:", ...

Then you use:

counter = n+1

This will only make your counter become larger than your while loop condition and exit your function prematurely, after entering just 1 line of text.
use instead:

counter += 1

Hope this puts you back on track :-)


问:
node/javascript - parse data from external local file
I am sure this is a simple answer but I do not find it.  Working through Eloquent Javascript, I am stumped on 5-2 Mother-Child Age Difference.  The data is provided in a file, ancestry.js.  I have stored this in my working directory.  According to the comment at the bottom of that file, if i require that file in my js file, it will be imported as ANCESTRY_FILE (I am still learning js so maybe I misunderstand this?).  Anyway when I feed my simple js query to node it says ANCESTRY_FILE is not defined.  What am I not getting?  Running 05_ageDiff.js should result in printing 39 to the console.  thx

console:

```<code>$ node ./05_ageDiff.js
/home/EloquentJS/05_ageDiff.js:3
var ancestry = JSON.parse(ANCESTRY_FILE);
                          ^

ReferenceError: ANCESTRY_FILE is not defined
    at Object.<anonymous> (/home/EloquentJS/05_ageDiff.js:3:27)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3
</code>```

05_ageDiff.js

require('./ancestry.js');

var ancestry = JSON.parse(ANCESTRY_FILE);
console.log(ancestry.length);```
</div>
</div>
</p>

<p>ancestry.js data file</p>

<p><div class="snippet" data-lang="js" data-hide="false" data-console="true" data-babel="false">
<div class="snippet-code">
<pre class="snippet-code-js lang-js prettyprint-override"><code>var ANCESTRY_FILE = "[\n  " + [
  '{"name": "Carolus Haverbeke", "sex": "m", "born": 1832, "died": 1905, "father": "Carel Haverbeke", "mother": "Maria van Brussel"}',
  '{"name": "Emma de Milliano", "sex": "f", "born": 1876, "died": 1956, "father": "Petrus de Milliano", "mother": "Sophia van Damme"}',
  '{"name": "Maria de Rycke", "sex": "f", "born": 1683, "died": 1724, "father": "Frederik de Rycke", "mother": "Laurentia van Vlaenderen"}',
  '{"name": "Jan van Brussel", "sex": "m", "born": 1714, "died": 1748, "father": "Jacobus van Brussel", "mother": "Joanna van Rooten"}',
  '{"name": "Philibert Haverbeke", "sex": "m", "born": 1907, "died": 1997, "father": "Emile Haverbeke", "mother": "Emma de Milliano"}',
  '{"name": "Jan Frans van Brussel", "sex": "m", "born": 1761, "died": 1833, "father": "Jacobus Bernardus van Brussel", "mother":null}',
  '{"name": "Pauwels van Haverbeke", "sex": "m", "born": 1535, "died": 1582, "father": "N. van Haverbeke", "mother":null}',
  '{"name": "Clara Aernoudts", "sex": "f", "born": 1918, "died": 2012, "father": "Henry Aernoudts", "mother": "Sidonie Coene"}',
  '{"name": "Emile Haverbeke", "sex": "m", "born": 1877, "died": 1968, "father": "Carolus Haverbeke", "mother": "Maria Sturm"}',
  '{"name": "Lieven de Causmaecker", "sex": "m", "born": 1696, "died": 1724, "father": "Carel de Causmaecker", "mother": "Joanna Claes"}',
  '{"name": "Pieter Haverbeke", "sex": "m", "born": 1602, "died": 1642, "father": "Lieven van Haverbeke", "mother":null}',
  '{"name": "Livina Haverbeke", "sex": "f", "born": 1692, "died": 1743, "father": "Daniel Haverbeke", "mother": "Joanna de Pape"}',
  '{"name": "Pieter Bernard Haverbeke", "sex": "m", "born": 1695, "died": 1762, "father": "Willem Haverbeke", "mother": "Petronella Wauters"}',
  '{"name": "Lieven van Haverbeke", "sex": "m", "born": 1570, "died": 1636, "father": "Pauwels van Haverbeke", "mother": "Lievijne Jans"}',
  '{"name": "Joanna de Causmaecker", "sex": "f", "born": 1762, "died": 1807, "father": "Bernardus de Causmaecker", "mother":null}',
  '{"name": "Willem Haverbeke", "sex": "m", "born": 1668, "died": 1731, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}',
  '{"name": "Pieter Antone Haverbeke", "sex": "m", "born": 1753, "died": 1798, "father": "Jan Francies Haverbeke", "mother": "Petronella de Decker"}',
  '{"name": "Maria van Brussel", "sex": "f", "born": 1801, "died": 1834, "father": "Jan Frans van Brussel", "mother": "Joanna de Causmaecker"}',
  '{"name": "Angela Haverbeke", "sex": "f", "born": 1728, "died": 1734, "father": "Pieter Bernard Haverbeke", "mother": "Livina de Vrieze"}',
  '{"name": "Elisabeth Haverbeke", "sex": "f", "born": 1711, "died": 1754, "father": "Jan Haverbeke", "mother": "Maria de Rycke"}',
  '{"name": "Lievijne Jans", "sex": "f", "born": 1542, "died": 1582, "father":null, "mother":null}',
  '{"name": "Bernardus de Causmaecker", "sex": "m", "born": 1721, "died": 1789, "father": "Lieven de Causmaecker", "mother": "Livina Haverbeke"}',
  '{"name": "Jacoba Lammens", "sex": "f", "born": 1699, "died": 1740, "father": "Lieven Lammens", "mother": "Livina de Vrieze"}',
  '{"name": "Pieter de Decker", "sex": "m", "born": 1705, "died": 1780, "father": "Joos de Decker", "mother": "Petronella van de Steene"}',
  '{"name": "Joanna de Pape", "sex": "f", "born": 1654, "died": 1723, "father": "Vincent de Pape", "mother": "Petronella Wauters"}',
  '{"name": "Daniel Haverbeke", "sex": "m", "born": 1652, "died": 1723, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}',
  '{"name": "Lieven Haverbeke", "sex": "m", "born": 1631, "died": 1676, "father": "Pieter Haverbeke", "mother": "Anna van Hecke"}',
  '{"name": "Martina de Pape", "sex": "f", "born": 1666, "died": 1727, "father": "Vincent de Pape", "mother": "Petronella Wauters"}',
  '{"name": "Jan Francies Haverbeke", "sex": "m", "born": 1725, "died": 1779, "father": "Pieter Bernard Haverbeke", "mother": "Livina de Vrieze"}',
  '{"name": "Maria Haverbeke", "sex": "m", "born": 1905, "died": 1997, "father": "Emile Haverbeke", "mother": "Emma de Milliano"}',
  '{"name": "Petronella de Decker", "sex": "f", "born": 1731, "died": 1781, "father": "Pieter de Decker", "mother": "Livina Haverbeke"}',
  '{"name": "Livina Sierens", "sex": "f", "born": 1761, "died": 1826, "father": "Jan Sierens", "mother": "Maria van Waes"}',
  '{"name": "Laurentia Haverbeke", "sex": "f", "born": 1710, "died": 1786, "father": "Jan Haverbeke", "mother": "Maria de Rycke"}',
  '{"name": "Carel Haverbeke", "sex": "m", "born": 1796, "died": 1837, "father": "Pieter Antone Haverbeke", "mother": "Livina Sierens"}',
  '{"name": "Elisabeth Hercke", "sex": "f", "born": 1632, "died": 1674, "father": "Willem Hercke", "mother": "Margriet de Brabander"}',
  '{"name": "Jan Haverbeke", "sex": "m", "born": 1671, "died": 1731, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}',
  '{"name": "Anna van Hecke", "sex": "f", "born": 1607, "died": 1670, "father": "Paschasius van Hecke", "mother": "Martijntken Beelaert"}',
  '{"name": "Maria Sturm", "sex": "f", "born": 1835, "died": 1917, "father": "Charles Sturm", "mother": "Seraphina Spelier"}',
  '{"name": "Jacobus Bernardus van Brussel", "sex": "m", "born": 1736, "died": 1809, "father": "Jan van Brussel", "mother": "Elisabeth Haverbeke"}'
].join(",\n  ") + "\n]";

// This makes sure the data is exported in node.js —
// `require(./path/to/ancestry.js)` will get you the array.
if (typeof module != "undefined" && module.exports)
  module.exports = ANCESTRY_FILE;</code>```

答:
ANCESTRY_FILE is exported as a CommonJS module, not a global variable, if you use it like you do. So this should work:</p>

```<code>var ANCESTRY_FILE = require('./ancestry.js');

var ancestry = JSON.parse(ANCESTRY_FILE);
console.log(ancestry.length);
</code>```

Body:
I am sure this is a simple answer but I do not find it.  Working through Eloquent Javascript, I am stumped on 5-2 Mother-Child Age Difference.  The data is provided in a file, ancestry.js.  I have stored this in my working directory.  According to the comment at the bottom of that file, if i require that file in my js file, it will be imported as ANCESTRY_FILE (I am still learning js so maybe I misunderstand this?).  Anyway when I feed my simple js query to node it says ANCESTRY_FILE is not defined.  What am I not getting?  Running 05_ageDiff.js should result in printing 39 to the console.  thx

console:

$ node ./05_ageDiff.js
/home/EloquentJS/05_ageDiff.js:3
var ancestry = JSON.parse(ANCESTRY_FILE);
                          ^

ReferenceError: ANCESTRY_FILE is not defined
    at Object.<anonymous> (/home/EloquentJS/05_ageDiff.js:3:27)
    at Module._compile (module.js:570:32)
    at Object.Module._extensions..js (module.js:579:10)
    at Module.load (module.js:487:32)
    at tryModuleLoad (module.js:446:12)
    at Function.Module._load (module.js:438:3)
    at Module.runMain (module.js:604:10)
    at run (bootstrap_node.js:394:7)
    at startup (bootstrap_node.js:149:9)
    at bootstrap_node.js:509:3

05_ageDiff.js

require('./ancestry.js');

var ancestry = JSON.parse(ANCESTRY_FILE);
console.log(ancestry.length);

ancestry.js data file

var ANCESTRY_FILE = "[\n  " + [
  '{"name": "Carolus Haverbeke", "sex": "m", "born": 1832, "died": 1905, "father": "Carel Haverbeke", "mother": "Maria van Brussel"}',
  '{"name": "Emma de Milliano", "sex": "f", "born": 1876, "died": 1956, "father": "Petrus de Milliano", "mother": "Sophia van Damme"}',
  '{"name": "Maria de Rycke", "sex": "f", "born": 1683, "died": 1724, "father": "Frederik de Rycke", "mother": "Laurentia van Vlaenderen"}',
  '{"name": "Jan van Brussel", "sex": "m", "born": 1714, "died": 1748, "father": "Jacobus van Brussel", "mother": "Joanna van Rooten"}',
  '{"name": "Philibert Haverbeke", "sex": "m", "born": 1907, "died": 1997, "father": "Emile Haverbeke", "mother": "Emma de Milliano"}',
  '{"name": "Jan Frans van Brussel", "sex": "m", "born": 1761, "died": 1833, "father": "Jacobus Bernardus van Brussel", "mother":null}',
  '{"name": "Pauwels van Haverbeke", "sex": "m", "born": 1535, "died": 1582, "father": "N. van Haverbeke", "mother":null}',
  '{"name": "Clara Aernoudts", "sex": "f", "born": 1918, "died": 2012, "father": "Henry Aernoudts", "mother": "Sidonie Coene"}',
  '{"name": "Emile Haverbeke", "sex": "m", "born": 1877, "died": 1968, "father": "Carolus Haverbeke", "mother": "Maria Sturm"}',
  '{"name": "Lieven de Causmaecker", "sex": "m", "born": 1696, "died": 1724, "father": "Carel de Causmaecker", "mother": "Joanna Claes"}',
  '{"name": "Pieter Haverbeke", "sex": "m", "born": 1602, "died": 1642, "father": "Lieven van Haverbeke", "mother":null}',
  '{"name": "Livina Haverbeke", "sex": "f", "born": 1692, "died": 1743, "father": "Daniel Haverbeke", "mother": "Joanna de Pape"}',
  '{"name": "Pieter Bernard Haverbeke", "sex": "m", "born": 1695, "died": 1762, "father": "Willem Haverbeke", "mother": "Petronella Wauters"}',
  '{"name": "Lieven van Haverbeke", "sex": "m", "born": 1570, "died": 1636, "father": "Pauwels van Haverbeke", "mother": "Lievijne Jans"}',
  '{"name": "Joanna de Causmaecker", "sex": "f", "born": 1762, "died": 1807, "father": "Bernardus de Causmaecker", "mother":null}',
  '{"name": "Willem Haverbeke", "sex": "m", "born": 1668, "died": 1731, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}',
  '{"name": "Pieter Antone Haverbeke", "sex": "m", "born": 1753, "died": 1798, "father": "Jan Francies Haverbeke", "mother": "Petronella de Decker"}',
  '{"name": "Maria van Brussel", "sex": "f", "born": 1801, "died": 1834, "father": "Jan Frans van Brussel", "mother": "Joanna de Causmaecker"}',
  '{"name": "Angela Haverbeke", "sex": "f", "born": 1728, "died": 1734, "father": "Pieter Bernard Haverbeke", "mother": "Livina de Vrieze"}',
  '{"name": "Elisabeth Haverbeke", "sex": "f", "born": 1711, "died": 1754, "father": "Jan Haverbeke", "mother": "Maria de Rycke"}',
  '{"name": "Lievijne Jans", "sex": "f", "born": 1542, "died": 1582, "father":null, "mother":null}',
  '{"name": "Bernardus de Causmaecker", "sex": "m", "born": 1721, "died": 1789, "father": "Lieven de Causmaecker", "mother": "Livina Haverbeke"}',
  '{"name": "Jacoba Lammens", "sex": "f", "born": 1699, "died": 1740, "father": "Lieven Lammens", "mother": "Livina de Vrieze"}',
  '{"name": "Pieter de Decker", "sex": "m", "born": 1705, "died": 1780, "father": "Joos de Decker", "mother": "Petronella van de Steene"}',
  '{"name": "Joanna de Pape", "sex": "f", "born": 1654, "died": 1723, "father": "Vincent de Pape", "mother": "Petronella Wauters"}',
  '{"name": "Daniel Haverbeke", "sex": "m", "born": 1652, "died": 1723, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}',
  '{"name": "Lieven Haverbeke", "sex": "m", "born": 1631, "died": 1676, "father": "Pieter Haverbeke", "mother": "Anna van Hecke"}',
  '{"name": "Martina de Pape", "sex": "f", "born": 1666, "died": 1727, "father": "Vincent de Pape", "mother": "Petronella Wauters"}',
  '{"name": "Jan Francies Haverbeke", "sex": "m", "born": 1725, "died": 1779, "father": "Pieter Bernard Haverbeke", "mother": "Livina de Vrieze"}',
  '{"name": "Maria Haverbeke", "sex": "m", "born": 1905, "died": 1997, "father": "Emile Haverbeke", "mother": "Emma de Milliano"}',
  '{"name": "Petronella de Decker", "sex": "f", "born": 1731, "died": 1781, "father": "Pieter de Decker", "mother": "Livina Haverbeke"}',
  '{"name": "Livina Sierens", "sex": "f", "born": 1761, "died": 1826, "father": "Jan Sierens", "mother": "Maria van Waes"}',
  '{"name": "Laurentia Haverbeke", "sex": "f", "born": 1710, "died": 1786, "father": "Jan Haverbeke", "mother": "Maria de Rycke"}',
  '{"name": "Carel Haverbeke", "sex": "m", "born": 1796, "died": 1837, "father": "Pieter Antone Haverbeke", "mother": "Livina Sierens"}',
  '{"name": "Elisabeth Hercke", "sex": "f", "born": 1632, "died": 1674, "father": "Willem Hercke", "mother": "Margriet de Brabander"}',
  '{"name": "Jan Haverbeke", "sex": "m", "born": 1671, "died": 1731, "father": "Lieven Haverbeke", "mother": "Elisabeth Hercke"}',
  '{"name": "Anna van Hecke", "sex": "f", "born": 1607, "died": 1670, "father": "Paschasius van Hecke", "mother": "Martijntken Beelaert"}',
  '{"name": "Maria Sturm", "sex": "f", "born": 1835, "died": 1917, "father": "Charles Sturm", "mother": "Seraphina Spelier"}',
  '{"name": "Jacobus Bernardus van Brussel", "sex": "m", "born": 1736, "died": 1809, "father": "Jan van Brussel", "mother": "Elisabeth Haverbeke"}'
].join(",\n  ") + "\n]";

// This makes sure the data is exported in node.js —
// `require(./path/to/ancestry.js)` will get you the array.
if (typeof module != "undefined" && module.exports)
  module.exports = ANCESTRY_FILE;

Body:
ANCESTRY_FILE is exported as a CommonJS module, not a global variable, if you use it like you do. So this should work:

var ANCESTRY_FILE = require('./ancestry.js');

var ancestry = JSON.parse(ANCESTRY_FILE);
console.log(ancestry.length);


问:
Incorrect path to .jar file
I'm using SikuliX in NetBeans to create a test. I added the dependency to my .pom file. When I try to run my test, I get the following error:

```<code>[error] RunTimeINIT: addToClasspath: does not exist - not added:
C:\Users\Jesper\Documents\NetBeansProjects\ElDiablo\Diablo2d\application\file:\C:\Users\Jesper\Documents\NetBeansProjects\ElDiablo\Diablo2d\application\target\diablo2d\diablo2d\modules\ext\com.se.sem4.group2.Core\com-sikulix\sikulixapi.jar!
*** classpath dump
0: /C:/Users/Jesper/Documents/NetBeansProjects/ElDiablo/Diablo2d/application/target/surefire/surefirebooter2216122235168821312.jar
*** classpath dump end
[error] RunTimeINIT:  *** terminating: libs to export not found on above classpath: /sikulixlibs/windows/libs64
</code>```

As you can see, the path to the .jar file is all wrong. If the first "C:\Users\Jesper\Documents\NetBeansProjects\ElDiablo\Diablo2d\application\" had been cut off, the path would be correct.

My question is why the first part of the path has been duplicated, and how do I change it?

答:
I've encountered the same error in Eclipse / Gradle.
The workaround in Gradle is to add a new dependency </p>

```<code> compile group: 'com.sikulix', name: 'sikulixlibswin', version: '1.1.0'
</code>```

<p>The workaround for this is described here https://bugs.launchpad.net/sikuli/+bug/1410072/comments/3 </p>

Title: Incorrect path to .jar file

Body:
I'm using SikuliX in NetBeans to create a test. I added the dependency to my .pom file. When I try to run my test, I get the following error:

[error] RunTimeINIT: addToClasspath: does not exist - not added:
C:\Users\Jesper\Documents\NetBeansProjects\ElDiablo\Diablo2d\application\file:\C:\Users\Jesper\Documents\NetBeansProjects\ElDiablo\Diablo2d\application\target\diablo2d\diablo2d\modules\ext\com.se.sem4.group2.Core\com-sikulix\sikulixapi.jar!
*** classpath dump
0: /C:/Users/Jesper/Documents/NetBeansProjects/ElDiablo/Diablo2d/application/target/surefire/surefirebooter2216122235168821312.jar
*** classpath dump end
[error] RunTimeINIT:  *** terminating: libs to export not found on above classpath: /sikulixlibs/windows/libs64

As you can see, the path to the .jar file is all wrong. If the first "C:\Users\Jesper\Documents\NetBeansProjects\ElDiablo\Diablo2d\application\" had been cut off, the path would be correct.

My question is why the first part of the path has been duplicated, and how do I change it?

Body:
I've encountered the same error in Eclipse / Gradle.
The workaround in Gradle is to add a new dependency

 compile group: 'com.sikulix', name: 'sikulixlibswin', version: '1.1.0'

The workaround for this is described here https://bugs.launchpad.net/sikuli/+bug/1410072/comments/3


问:
angular2, http with credentials. Can't add cookies
I Have been trying for some time to get past this problem. I need to connect to a remote server with my credentials, I am able to this with no problems. Next I need to perform a get for some resource on the server, from my experience in angular 1 I need to use the credentials I got from the login stage I just can't seem to get the right way to do it..

This is how I preform my login:

```<code>import { Injectable } from 'angular2/core';
import { IjobCard } from '../jobCard/jobCard';
import { Http, Response } from 'angular2/http';
import { Observable } from 'rxjs/Observable';
import { Icredentials } from './credentials';

@Injectable()
export class LoginService {
    private _loginUrl = 'MyUrl/Login';
    loginCred: Icredentials = {
        "filed1": "dummy1",
        "filed2": "dummy2",
        "filed3": "dummy3"
    };

    constructor(private _http: Http){

    }

    login(): Observable<any>[] {
        return this._http.post(this._loginUrl, JSON.stringify(this.loginCred))
            .map((response: Response) => <any[]>response.json())
            .catch(this.handleError);

    }

    private handleError(error: Response){
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}
</code>```

And this is how I am trying to execute my next get:

```<code>import { Injectable } from 'angular2/core';
import { IjobCard } from './jobCard';
import { Http, Response, Headers } from 'angular2/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class JobCardService {
    private _jobCardUrl = 'MyUrl/SomeGet';
    constructor(private _http: Http) {
    }

    getJobCard(): Observable<any>[] {
        var myHeders = new Headers();
        myHeders.append('Content-Type', 'application/json');
        return this._http.get(this._jobCardUrl, { headers: myHeders, withCredentials: true} )
        .map((response: Response) => <any[]>response.json())
        .catch(this.handleError);

    }

    private handleError(error: Response){
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}
</code>```

Sadly, what I get back is an 401 unauthorised, I already tried many other methods based on the search result Google provides... no luck.

I was able to connect to the same service from an angular 1 app and by using postman...

*******UPDATE********

Ok, I tried following John Baird answer to my question but I couldn't make it work. But I got some new clues to what the problem could be:

The server respose has the following headers:

Access-Control-Allow-Credentials: true
access-control-allow-headers: content-type,
accept access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin: http://localhost:3000

I also found out that in my angular 1 project the request to contains a header of cookie like so:

```<code>Cookie: B1SESSION=GLWzfesg-sscK-yAH9-PH4m-99r5hCrOdddh; ROUTEID=.node0
</code>```

but my angular2 project did not, even when using the withCredentials flag.

I tried solving it by following some ideas from :
https://github.com/angular/angular/issues/4231
by adding this to my main:

```<code>class MyBaseRequestOptions extends BaseRequestOptions {
    headers: Headers = new Headers({
        'X-Requested-With': 'XMLHttpRequest'
    });
    withCredentials: boolean = true;
}

bootstrap(AppComponent, [
    provide(RequestOptions, {useClass: MyBaseRequestOptions}) ]);
</code>```

but still no cookies are sent with my request.

Is this the right path? Any more ideas to try?

答:
You can try this solution, it works for me</p>

```<code>private getHeaders(){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    return headers;
}

public getAll = (): Observable<Account[]> => {
    return this._http.get(this.actionUrl,{ headers: this.headers, withCredentials: true })
        .map((response: Response) => <Account[]>response.json())
        .catch(this.handleError);
}
</code>```

Body:
I Have been trying for some time to get past this problem. I need to connect to a remote server with my credentials, I am able to this with no problems. Next I need to perform a get for some resource on the server, from my experience in angular 1 I need to use the credentials I got from the login stage I just can't seem to get the right way to do it..

This is how I preform my login:

import { Injectable } from 'angular2/core';
import { IjobCard } from '../jobCard/jobCard';
import { Http, Response } from 'angular2/http';
import { Observable } from 'rxjs/Observable';
import { Icredentials } from './credentials';

@Injectable()
export class LoginService {
    private _loginUrl = 'MyUrl/Login';
    loginCred: Icredentials = {
        "filed1": "dummy1",
        "filed2": "dummy2",
        "filed3": "dummy3"
    };

    constructor(private _http: Http){

    }

    login(): Observable<any>[] {
        return this._http.post(this._loginUrl, JSON.stringify(this.loginCred))
            .map((response: Response) => <any[]>response.json())
            .catch(this.handleError);

    }

    private handleError(error: Response){
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

And this is how I am trying to execute my next get:

import { Injectable } from 'angular2/core';
import { IjobCard } from './jobCard';
import { Http, Response, Headers } from 'angular2/http';
import { Observable } from 'rxjs/Observable';

@Injectable()
export class JobCardService {
    private _jobCardUrl = 'MyUrl/SomeGet';
    constructor(private _http: Http) {
    }

    getJobCard(): Observable<any>[] {
        var myHeders = new Headers();
        myHeders.append('Content-Type', 'application/json');
        return this._http.get(this._jobCardUrl, { headers: myHeders, withCredentials: true} )
        .map((response: Response) => <any[]>response.json())
        .catch(this.handleError);

    }

    private handleError(error: Response){
        console.error(error);
        return Observable.throw(error.json().error || 'Server error');
    }
}

Sadly, what I get back is an 401 unauthorised, I already tried many other methods based on the search result Google provides... no luck.

I was able to connect to the same service from an angular 1 app and by using postman...

*******UPDATE********

Ok, I tried following John Baird answer to my question but I couldn't make it work. But I got some new clues to what the problem could be:

The server respose has the following headers:

Access-Control-Allow-Credentials: true
access-control-allow-headers: content-type,
accept access-control-allow-methods: GET, POST, PUT, PATCH, DELETE, OPTIONS
access-control-allow-origin: http://localhost:3000

I also found out that in my angular 1 project the request to contains a header of cookie like so:

Cookie: B1SESSION=GLWzfesg-sscK-yAH9-PH4m-99r5hCrOdddh; ROUTEID=.node0

but my angular2 project did not, even when using the withCredentials flag.

I tried solving it by following some ideas from :
https://github.com/angular/angular/issues/4231
by adding this to my main:

class MyBaseRequestOptions extends BaseRequestOptions {
    headers: Headers = new Headers({
        'X-Requested-With': 'XMLHttpRequest'
    });
    withCredentials: boolean = true;
}

bootstrap(AppComponent, [
    provide(RequestOptions, {useClass: MyBaseRequestOptions}) ]);

but still no cookies are sent with my request.

Is this the right path? Any more ideas to try?

Body:
You can try this solution, it works for me

private getHeaders(){
    let headers = new Headers();
    headers.append('Content-Type', 'application/json');
    headers.append('Accept', 'application/json');
    return headers;
}

public getAll = (): Observable<Account[]> => {
    return this._http.get(this.actionUrl,{ headers: this.headers, withCredentials: true })
        .map((response: Response) => <Account[]>response.json())
        .catch(this.handleError);
}


问:
Is there a way to open camera and view it on screen and make is so it is not able to take pictures or record videos.
I am creating a android app which has the following requirement and can you tell how to implement it.

1) Open Camera in a fragment,
2) Should not be able to record videos or take pictures.

I am new to android, so it will very helpful if you guys help me out here.

Thanks in advance.

答:
If you just want the camera view and not its actions(buttons). You can use SurfaceView to create your own camera. This will just open camera. You can find surface view tutorial here.You can just exclude the part where they are adding the start, stop and capture buttons.

don't forget the permission
<uses-permission android:name="android.permission.CAMERA" ></uses-permission> in your manifest .


问:
C# in Windows Forms : "Index was outside the bounds of the array" at a try to auto-add new space
I really can't understand where's from this error and how to fix it.

My idea is to grow the space with 1 every time I read a new object, that's why I use int m = a.GetLength(0)+1;

 a[m, j] = Convert.ToString(m); is j=1 which means the number of account which is in fact m, last position from array.

How can I made this works without writing a lot of lines and copy vector in another with +1 line every time I want to add new element?

// "Index was outside the bounds of the array."

// "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in code.exe"

photo with code&error:

```<code>    private void adauga_Click(object sender, EventArgs e)
    {

        int m = a.GetLength(0)+1;
            for (int j = 0; j < 7; j++)
            {   a[m, j] = Convert.ToString(m);
                a[m, j] = textnume.Text;
                a[m, j] = textprenume.Text;
                a[m, j] = textcnp.Text;
                a[m, j] = textserie.Text;
                a[m, j] = textnumar.Text;
                a[m, j] = textdebcre.Text;
                b[m] = Convert.ToInt32(textsuma.Text); } }
</code>```

Where a and b are :
        static string [,]a = new string[1,1];
        static int[] b=new int1;

答:
Your problem occurs as you are trying to access an entry in the array which does not exist. This is not allowed, and therefore an exception is thrown.

Your array at this point in time has the size you've defined at the first line:

```<code>static string [,] a= new string [1,1];
</code>```

Which means the only valid entry is at a[0,0]. To access other entries you need to explicitly resize the array to the new size you want: How to resize multidimensional (2D) array in C#?

I'm guessing you want to save entries from your application in this array once the user clicks on that button. I'd recommend you solve this problem with objects and List<T>, rather than multidimensional arrays:

Create an object which contains the properties you want to save, similar to this:

```<code>class MyClass
{
    public string Nume {get; set;}
    public string PreNume {get; set;}
    //your other properties here
}
</code>```

Then create a List to save you objects into. Lists have the advantage to arrays that they can grow even after you've defined them.
The T in List is for an arbitrary class, you can use here the MyClass we defined above. So:

```<code>List<MyClass> myList = new List<MyClass>();
</code>```

Now put it all together:

```<code>private List<MyClass> _myList = new List<MyClass>();
private void adauga_Click(object sender, EventArgs e)
{
    //create a myClass Object
    var myClass = new MyClass();
    myClass.Nume = textnume.Text;
    myClass.PreNume = textprenume.Text;
    //continue here...

    //add it to the list
    _myList.add(myClass);
}
</code>```

Body:
I really can't understand where's from this error and how to fix it.

My idea is to grow the space with 1 every time I read a new object, that's why I use int m = a.GetLength(0)+1;

 a[m, j] = Convert.ToString(m); is j=1 which means the number of account which is in fact m, last position from array.

How can I made this works without writing a lot of lines and copy vector in another with +1 line every time I want to add new element?

// "Index was outside the bounds of the array."

// "An unhandled exception of type 'System.IndexOutOfRangeException' occurred in code.exe"

photo with code&error:

    private void adauga_Click(object sender, EventArgs e)
    {

        int m = a.GetLength(0)+1;
            for (int j = 0; j < 7; j++)
            {   a[m, j] = Convert.ToString(m);
                a[m, j] = textnume.Text;
                a[m, j] = textprenume.Text;
                a[m, j] = textcnp.Text;
                a[m, j] = textserie.Text;
                a[m, j] = textnumar.Text;
                a[m, j] = textdebcre.Text;
                b[m] = Convert.ToInt32(textsuma.Text); } }

Where a and b are :
        static string [,]a = new string[1,1];
        static int[] b=new int1;

Body:
Your problem occurs as you are trying to access an entry in the array which does not exist. This is not allowed, and therefore an exception is thrown.

Your array at this point in time has the size you've defined at the first line:

static string [,] a= new string [1,1];

Which means the only valid entry is at a[0,0]. To access other entries you need to explicitly resize the array to the new size you want: How to resize multidimensional (2D) array in C#?

I'm guessing you want to save entries from your application in this array once the user clicks on that button. I'd recommend you solve this problem with objects and List<T>, rather than multidimensional arrays:

Create an object which contains the properties you want to save, similar to this:

class MyClass
{
    public string Nume {get; set;}
    public string PreNume {get; set;}
    //your other properties here
}

Then create a List to save you objects into. Lists have the advantage to arrays that they can grow even after you've defined them.
The T in List is for an arbitrary class, you can use here the MyClass we defined above. So:

List<MyClass> myList = new List<MyClass>();

Now put it all together:

private List<MyClass> _myList = new List<MyClass>();
private void adauga_Click(object sender, EventArgs e)
{
    //create a myClass Object
    var myClass = new MyClass();
    myClass.Nume = textnume.Text;
    myClass.PreNume = textprenume.Text;
    //continue here...

    //add it to the list
    _myList.add(myClass);
}


问:
How to Remove Swipe Previous / Next Post in Blogger
In Blogger / Blogspot, mobile templates come with a swipe feature that you can't apparently disable and that will go to the previous/next post if you swipe left or right.

This is nice and all, but my post has a table and the swipe feature won't allow me to scroll horizontally. Which kinda sucks.

Is there a way to disable scrolling?

答:
Combining the answer by OdraEncoded above, together with the suggestion from Blog Matheus Produções in Blogger Help Forum, I think the final code below should be limiting the disabling of id=main events to the posts in mobile pages.

```<code><b:if cond='data:blog.isMobile'>
  <b:if cond='data:blog.pageType == "item"'>

    <script>
      // hackiest thing in the universe so disable the stupid swiping from blogger
      document.getElementById('main').addEventListener = function() {}
    </script>

  </b:if>
</b:if>
</code>```

Body:
Combining the answer by OdraEncoded above, together with the suggestion from Blog Matheus Produções in Blogger Help Forum, I think the final code below should be limiting the disabling of id=main events to the posts in mobile pages.

<b:if cond='data:blog.isMobile'>
  <b:if cond='data:blog.pageType == &quot;item&quot;'>

    <script>
      // hackiest thing in the universe so disable the stupid swiping from blogger
      document.getElementById('main').addEventListener = function() {}
    </script>

  </b:if>
</b:if>


问:
Reduce inner margins of the tokens of NSTokenField
I feel the tokens in NSTokenField have way too much inner margins, i.e. i believe the two semicircles (on the each side) should be closer to the text. The default setting wastes way too much space.

How do I reduce these margins, and make the tokens more compact?

答: I had to do some subclassing of a class which is not a part of the public API. I got an idea of what to do through the code of BWTokenField in BWToolkit. It works, but I would have wanted to do it without public APIs, as I might want to go on the Mac App Store one day. I have submitted a bug report asking for making the API public, and they marked the report as a duplicate. I'm not optimistic they'll do anything about it.</p>

ContentLicense: CC BY-SA 2.5


问:
How Aem content traversed and get resolved into presentation layer?
Can any one explain me what will happen internally into Aem content. How it gets resolved and represented back to presentation layer.?  Am more curious about the Sling internal mechanism on top of content delivery resolvation.</p>

答:
The answer to this question could be very detailed, because there is a lot going on when "content" is resolved and presented (by the presentation layer).

You can find a more detailed explanation in the official AEM documentation.

The gist of it is, that Sling will look at the URL that is called and will try to find out to which "content" (or more precisely "resource")  this URL points to in the repository. Usually, there is a one to one relationship between a URL and a resource.

But here it gets a bit more complicated. Most of the time this "resource" is a page. And a page is composed of a lot of smaller parts. Those parts are called "components". A simple example would be a page with a blog post. You might have a component for the header of the page, the footer, the navigation and all of the other content in between, like the text and images of the blog post. All those different parts are components.

Sling will find all of the components that are on the page and will render all of them separately to build the page. Most components will have a JSP or HTL (Sightly) template which Sling uses to render the component. Those templates on the other hand might have their own internal logic which might use OSGi services or servlets to build the content that is displayed.

This was just a simple example to show you how it basically works. But it is far more complicated under the hood. There is a myriad of different things going on behind the scenes that you, as a developer, can use to influence this process. One example for this would be Sling Filter.


问:
How can instanceof be preformed inside a method with no specific object?
My code is full of things like this:

```<code>Block attackedBlock = (fixtureA.getUserData() instanceof  Block) ?  (Block) fixtureA.getUserData() :  (Block) fixtureB.getUserData();
Bullet bullet       = (fixtureA.getUserData() instanceof Bullet) ? (Bullet) fixtureA.getUserData() : (Bullet) fixtureB.getUserData();
</code>```

And this works, but it's quite messy IMO, so I made a method to shorten the lines:

```<code>Fixture getFixture(Class USER_DATA) {
    return (fixtureA.getUserData() instanceof USER_DATA) ? fixtureA : fixtureB;
}
</code>```

I get the error that USER_DATA isn't a class, which is understandable, but how do I make it look in the specified class? It also says that that condiotion will always evaluate to false/ What should I do?

答: You need a parameter of type Class, so call getFixture(Player.class).

Body:
My code is full of things like this:

Block attackedBlock = (fixtureA.getUserData() instanceof  Block) ?  (Block) fixtureA.getUserData() :  (Block) fixtureB.getUserData();
Bullet bullet       = (fixtureA.getUserData() instanceof Bullet) ? (Bullet) fixtureA.getUserData() : (Bullet) fixtureB.getUserData();

And this works, but it's quite messy IMO, so I made a method to shorten the lines:

Fixture getFixture(Class USER_DATA) {
    return (fixtureA.getUserData() instanceof USER_DATA) ? fixtureA : fixtureB;
}

I get the error that USER_DATA isn't a class, which is understandable, but how do I make it look in the specified class? It also says that that condiotion will always evaluate to false/ What should I do?


问:
TCP/IP Client and Server basic using and references
I have installed TCP/IP  from VS15 NuGet Packeges into my project and in References it is as SimpleTCP, I've rebuild project, but for  SimpleTcpClient client; it says:

Suppression State Error  CS0246  The type or namespace name
  'SimpleTcpServer' could not be found (are you missing a using
  directive or an assembly reference?)

not sure what can be cause of that, maybe I missed some references or even using.

Client:

```<code>using System;
using System.Text;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SimpleTcpClient client;

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            client.WriteLineAndGetReplay(txtMessage.Text, TimeSpan.FromSeconds(5));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            client = new SimpleTcpClient();
            client.StringEncoder = Encoding.UTF8;
            client.DataRecevived += Client_DataReceived;
        }

        private void Client_DataReceived(object sender, SimpleTCP.Message e)
        {
            textBox1.Invoke((MethodInvoker)delegate ()
            {
                textBox1.Text += e.MessageString;
            });
        }
    }
}
</code>```

Server:

```<code>using System;
using System.Text;
using System.Windows.Forms;

namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SimpleTcpServer server;

        private void Form1_Load(object sender, EventArgs e)
        {
            server = new SimpleTcpServer();
            server.Delimeter = 0x13;
            server.StringEncoder = Encoding.UTF8;
            server.DataReceived += Server_DataReceived;
        }

        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            txtStatus.Invoke((MethodInvoker)delegate ()
            {
                txtStatus.Text += e.MessageString;
                e.ReplyLine(string.Format("You said: {0}", e.MessageString));
            });
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            txtStatus.Text += "Server starting...";
            System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(txtHost.Text));
            server.Start(ip, Convert.ToInt32(txtPort.Text));
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (server.IsStarted)
            {
                server.Stop();
            }
        }
    }
}
</code>```

答:
To answer your question, you get this error because you have not included using SimpleTCP; in your code.

The start of each of your forms should look something like this:

```<code>using SimpleTCP;
using System;
using System.Net;
using System.Windows.Forms;
</code>```

With that said, the code would still have some problems.

You do not have client.Connect(IP, PORT); in your client form. In order to create a server < > client connection, there must be a listening server and a client to connect to it. In your case, there is only a listening server.

In your server form, you should be calling IPAddress.Parse() instead. Usage example: IPAddress.Parse("127.0.0.1");

You do not need to Invoke any of your Form members as you are not using any sort of multi-threading, unless SimpleTCP does so by default, which is very unlikely.

Furthermore, the whole project seems to be a mess. If you're still starting out, I would highly recommend using Console Application as they're more forgiving and rather simple to use.

I would also recommend learning more about C# events and how they work.

Here is a server < > client project using SimpleTCP, your configurations and Console Application to get you started.

Server:

```<code>using System;
using System.Net;
using SimpleTCP;
using System.Text;

namespace server
{
    class Program
    {
        static void Main(string[] args)
        {
            SimpleTcpServer server = new SimpleTcpServer(); //Instantiate server.
            server.Delimiter = 0x13; //Config
            server.StringEncoder = Encoding.UTF8; //Config
            server.DataReceived += Server_DataReceived; //Subscribe to DataRecieved event.
            IPAddress ip = IPAddress.Parse("127.0.0.1"); //IP Address using .Parse()
            int port = 6500; //Port number
            server.Start(ip, port); //Start listening to incoming connections and data.
            Console.ReadKey(); //Pause the console.
        }

        static void Server_DataReceived(object sender, SimpleTCP.Message m)
        {
            Console.WriteLine(m.MessageString); //Write message to console.
            string replyMessage = String.Format("You said {0}", m.MessageString); //This is the reply message
            m.ReplyLine(replyMessage); //Send reply message back to client.
        }
    }
}
</code>```

Client:

```<code>using System;
using System.Net;
using SimpleTCP;
using System.Text;

namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            SimpleTcpClient client = new SimpleTcpClient(); //Instantiate the client
            client.StringEncoder = Encoding.UTF8; //Config
            client.DataReceived += Client_DataReceived; //Subscribe to the DataRecieved event.
            client.Connect("127.0.0.1", 6500); //Connect to the server
            while(true) //Keep the console open until you close it.
            {
                //As long as the console is open, every message you type will be sent to the server.
                client.WriteLineAndGetReply(Console.ReadLine(), TimeSpan.FromSeconds(5));
            }
        }
        static void Client_DataReceived(object sender, Message m)
        {
            Console.WriteLine(m.MessageString); //Write recieved reply from server to console.
        }
    }
}
</code>```

I hope this helps you on your journey, goodluck!

Body:
I have installed TCP/IP  from VS15 NuGet Packeges into my project and in References it is as SimpleTCP, I've rebuild project, but for  SimpleTcpClient client; it says:

Suppression State Error  CS0246  The type or namespace name
  'SimpleTcpServer' could not be found (are you missing a using
  directive or an assembly reference?)

not sure what can be cause of that, maybe I missed some references or even using.

Client:

using System;
using System.Text;
using System.Windows.Forms;

namespace Client
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SimpleTcpClient client;

        private void button1_Click(object sender, EventArgs e)
        {
            button1.Enabled = false;
        }

        private void button2_Click(object sender, EventArgs e)
        {
            client.WriteLineAndGetReplay(txtMessage.Text, TimeSpan.FromSeconds(5));
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            client = new SimpleTcpClient();
            client.StringEncoder = Encoding.UTF8;
            client.DataRecevived += Client_DataReceived;
        }

        private void Client_DataReceived(object sender, SimpleTCP.Message e)
        {
            textBox1.Invoke((MethodInvoker)delegate ()
            {
                textBox1.Text += e.MessageString;
            });
        }
    }
}

Server:

using System;
using System.Text;
using System.Windows.Forms;

namespace Server
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        SimpleTcpServer server;

        private void Form1_Load(object sender, EventArgs e)
        {
            server = new SimpleTcpServer();
            server.Delimeter = 0x13;
            server.StringEncoder = Encoding.UTF8;
            server.DataReceived += Server_DataReceived;
        }

        private void Server_DataReceived(object sender, SimpleTCP.Message e)
        {
            txtStatus.Invoke((MethodInvoker)delegate ()
            {
                txtStatus.Text += e.MessageString;
                e.ReplyLine(string.Format("You said: {0}", e.MessageString));
            });
        }

        private void btnStart_Click(object sender, EventArgs e)
        {
            txtStatus.Text += "Server starting...";
            System.Net.IPAddress ip = new System.Net.IPAddress(long.Parse(txtHost.Text));
            server.Start(ip, Convert.ToInt32(txtPort.Text));
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            if (server.IsStarted)
            {
                server.Stop();
            }
        }
    }
}

Body:
To answer your question, you get this error because you have not included using SimpleTCP; in your code.

The start of each of your forms should look something like this:

using SimpleTCP;
using System;
using System.Net;
using System.Windows.Forms;

With that said, the code would still have some problems.

You do not have client.Connect(IP, PORT); in your client form. In order to create a server < > client connection, there must be a listening server and a client to connect to it. In your case, there is only a listening server.

In your server form, you should be calling IPAddress.Parse() instead. Usage example: IPAddress.Parse("127.0.0.1");

You do not need to Invoke any of your Form members as you are not using any sort of multi-threading, unless SimpleTCP does so by default, which is very unlikely.

Furthermore, the whole project seems to be a mess. If you're still starting out, I would highly recommend using Console Application as they're more forgiving and rather simple to use.

I would also recommend learning more about C# events and how they work.

Here is a server < > client project using SimpleTCP, your configurations and Console Application to get you started.

Server:

using System;
using System.Net;
using SimpleTCP;
using System.Text;

namespace server
{
    class Program
    {
        static void Main(string[] args)
        {
            SimpleTcpServer server = new SimpleTcpServer(); //Instantiate server.
            server.Delimiter = 0x13; //Config
            server.StringEncoder = Encoding.UTF8; //Config
            server.DataReceived += Server_DataReceived; //Subscribe to DataRecieved event.
            IPAddress ip = IPAddress.Parse("127.0.0.1"); //IP Address using .Parse()
            int port = 6500; //Port number
            server.Start(ip, port); //Start listening to incoming connections and data.
            Console.ReadKey(); //Pause the console.
        }

        static void Server_DataReceived(object sender, SimpleTCP.Message m)
        {
            Console.WriteLine(m.MessageString); //Write message to console.
            string replyMessage = String.Format("You said {0}", m.MessageString); //This is the reply message
            m.ReplyLine(replyMessage); //Send reply message back to client.
        }
    }
}

Client:

using System;
using System.Net;
using SimpleTCP;
using System.Text;

namespace client
{
    class Program
    {
        static void Main(string[] args)
        {
            SimpleTcpClient client = new SimpleTcpClient(); //Instantiate the client
            client.StringEncoder = Encoding.UTF8; //Config
            client.DataReceived += Client_DataReceived; //Subscribe to the DataRecieved event.
            client.Connect("127.0.0.1", 6500); //Connect to the server
            while(true) //Keep the console open until you close it.
            {
                //As long as the console is open, every message you type will be sent to the server.
                client.WriteLineAndGetReply(Console.ReadLine(), TimeSpan.FromSeconds(5));
            }
        }
        static void Client_DataReceived(object sender, Message m)
        {
            Console.WriteLine(m.MessageString); //Write recieved reply from server to console.
        }
    }
}

I hope this helps you on your journey, goodluck!


问:
How to send JSON data to my wordpress website?
I have 2 websites.

Website A (normal PHP, HTML website).

Website B (wordpress).

I need to post JSON data from website A to website B. I need to know how to set up a URL in my website B which can be used in POST action in Website A.

答:
You can use file_get_contents() or php cURL. Reference for cURL is given below:

First, Add an api.php on your website A.

api.php

```<code><?php
if($_REQUEST['key'] != '555')
{
    $final = array('error' => 'Invalid Key');
    echo json_encode($final);
    exit();
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_a";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$action = $_REQUEST['action'];

//update, del, get by id, get all
switch($action)
{

    case 'get_all':
        $sql = 'SELECT * FROM tbl_a';
        $rs = mysqli_query($conn,$sql);
        $final = array();
        while($row = mysqli_fetch_assoc($rs))
        {
            $final[] = $row;
        }

        echo json_encode($final);
        break;

    default:
        $final = array('error' => 'Invalid Command');
        echo json_encode($final);
}
?>
</code>```

Next, add following code in your website B.

```<code><?php
 $cSession = curl_init();
 curl_setopt($cSession,CURLOPT_URL,"http://yoursite.com/api.php?key=555&action=get_all");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result=curl_exec($cSession);
curl_close($cSession);
$arr = json_decode($result);
echo '```';
print_r($arr);
echo '```';
?>
</code>```

You may make more secure or may tweak it in your way adding more functions to insert, del, get by id but this is the basic idea. Hope it helps. :)

Body:
You can use file_get_contents() or php cURL. Reference for cURL is given below:

First, Add an api.php on your website A.

api.php

<?php
if($_REQUEST['key'] != '555')
{
    $final = array('error' => 'Invalid Key');
    echo json_encode($final);
    exit();
}
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "db_a";

// Create connection
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$action = $_REQUEST['action'];

//update, del, get by id, get all
switch($action)
{

    case 'get_all':
        $sql = 'SELECT * FROM tbl_a';
        $rs = mysqli_query($conn,$sql);
        $final = array();
        while($row = mysqli_fetch_assoc($rs))
        {
            $final[] = $row;
        }

        echo json_encode($final);
        break;

    default:
        $final = array('error' => 'Invalid Command');
        echo json_encode($final);
}
?>

Next, add following code in your website B.

<?php
 $cSession = curl_init();
 curl_setopt($cSession,CURLOPT_URL,"http://yoursite.com/api.php?key=555&action=get_all");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false);
$result=curl_exec($cSession);
curl_close($cSession);
$arr = json_decode($result);
echo '<pre>';
print_r($arr);
echo '</pre>';
?>

You may make more secure or may tweak it in your way adding more functions to insert, del, get by id but this is the basic idea. Hope it helps. :)


问:
Difference in uses between malloc and calloc
```<code>gcc 4.5.1 c89
</code>```

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

```<code>dev = malloc(number * sizeof *devices);
</code>```

is equal to this calloc. I am not concerned about clearing the memory.

```<code>dev = calloc(number, sizeof *devices);
</code>```

What is that exactly, compared to doing this 5 times in a while loop:

```<code>dev = malloc(sizeof *devices);
</code>```

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

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

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}
</code>```

答: The first two create an array of 5 devices in contiguous memory.  The last malloc, done five times, will create 5 individual devices which are not guaranteed to be in contiguous memory.</p>

Body:
gcc 4.5.1 c89

I have written this source code for my better understanding of malloc and calloc.

I understand, but just have a few questions.

dev = malloc(number * sizeof *devices);

is equal to this calloc. I am not concerned about clearing the memory.

dev = calloc(number, sizeof *devices);

What is that exactly, compared to doing this 5 times in a while loop:

dev = malloc(sizeof *devices);

I guess the first one and the second is creating a pointer to 5 struct device. And the third is creating a single pointer to a struct device?

My program illustrates this 3 different methods compiled and ran with valgrind --leak-check=full.

Many thanks for any advice.

#include <stdio.h>
#include <stdlib.h>

struct Devices {
#define MAX_NAME_SIZE 80
    size_t id;
    char name[MAX_NAME_SIZE];
};

struct Devices* create_device(struct Devices *dev);
void destroy_device(struct Devices *dev);

int main(void)
{
    size_t num_devices = 5;
    size_t i = 0;
    struct Devices *device = NULL;
    struct Devices *dev_malloc = NULL;
    struct Devices *dev_calloc = NULL;

    for(i = 0; i < num_devices; i++) {
        device = create_device(device);
        /* Assign values */
        device->id = i + 1;
        sprintf(device->name, "Device%zu", device->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", device->id);
        printf("Name --- [ %s ]\n", device->name);
        /* Test free */
        destroy_device(device);
    }

    printf("\n");
    dev_malloc = malloc(num_devices * sizeof *dev_malloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_malloc->id = i + 1;
        sprintf(dev_malloc->name, "dev_malloc%zu", dev_malloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_malloc->id);
        printf("Name --- [ %s ]\n", dev_malloc->name);
    }
    /* Test free */
    destroy_device(dev_malloc);

    printf("\n");
    dev_calloc = calloc(num_devices, sizeof *dev_calloc);
    for(i = 0; i < num_devices; i++) {
        /* Assign values */
        dev_calloc->id = i + 1;
        sprintf(dev_calloc->name, "dev_calloc%zu", dev_calloc->id);
        /* Print values */
        printf("ID ----- [ %zu ]\n", dev_calloc->id);
        printf("Name --- [ %s ]\n", dev_calloc->name);
    }
    /* Test free */
    destroy_device(dev_calloc);

    return 0;
}

struct Devices* create_device(struct Devices *dev)
{
    /* Not checking for memory error - just simple test */
    return dev = malloc(sizeof *dev);
}

void destroy_device(struct Devices *dev)
{
    if(dev != NULL) {
        free(dev);
    }
}


问:
Querying documents in mongoose
Consider the following sample document

```<code>[{
"Name" : "John doe",
"age"  : 22,
"email" : "john@doe.com"
},
{
"Name" : "William",
"age"  : 28,
"email" : "william@william.com"
},
{
"Name" : "jack",
"age"  : 22,
"email" : "jack@jack.com"
}]
</code>```

I have an array of objects with me with the following structure

[{'name':'jack','age':10},{'name':'john','age':20}]

  How do I perform a query in the document in a way such that I can match the name field and age field of my array of objects of each element.
Basically, the name jack and the age 10 should query with the sample and after that the name john and the age 20 should perform the query.

I know that $elemMatch could have been used if it was the other way around where I had to query with single elements in an array. Is there any way of doing this?

答:
If you are not talking about searching the retrieved documents. You can search database like this:</p>

```<code>    var searchArr = [{name:'jack',age:10},{name:'john', age:20}]

    searchArr.forEach(function(element){
        var query = Model.find(element)

        query.then(function(result){
            console.log(result)
        })
    })
</code>```

Title: Querying documents in mongoose

Body:
Consider the following sample document

[{
"Name" : "John doe",
"age"  : 22,
"email" : "john@doe.com"
},
{
"Name" : "William",
"age"  : 28,
"email" : "william@william.com"
},
{
"Name" : "jack",
"age"  : 22,
"email" : "jack@jack.com"
}]

I have an array of objects with me with the following structure

[{'name':'jack','age':10},{'name':'john','age':20}]

  How do I perform a query in the document in a way such that I can match the name field and age field of my array of objects of each element.
Basically, the name jack and the age 10 should query with the sample and after that the name john and the age 20 should perform the query.

I know that $elemMatch could have been used if it was the other way around where I had to query with single elements in an array. Is there any way of doing this?

Body:
If you are not talking about searching the retrieved documents. You can search database like this:

    var searchArr = [{name:'jack',age:10},{name:'john', age:20}]

    searchArr.forEach(function(element){
        var query = Model.find(element)

        query.then(function(result){
            console.log(result)
        })
    })


问:
use spring data jpa with ninja java
ninja is an awesome framework but coming from a  spring background, I need to use spring data jpa with ninja.

I want to Autowire a JpaRepository and use it in ninja. Although ninja uses Guice Inject. I keep getting a No implementations found for my class.

the repository:

```<code>public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {

PortalUser getPortalUserByUsername(String username);

PortalUser getPortalUserByEmail(String email);
}
</code>```

the injection

```<code>public class SetupDaoV2 {

@Inject
PortalUserRepository portalUserRepository;

public void setup() {
    try {
        List<PortalUser> portalUsers = portalUserRepository.findAll();
        if (portalUsers.size() == 0) {
            // Create a new user and save it
            PortalUser portalUser = new PortalUser("lsadjfl", "lsdlfs", "kkk lll",
                    "llskfls@gmail.com", "lsdlfss@",
                    "lsdfls@gmail.com",
                    new Timestamp(System.currentTimeMillis()), Boolean.TRUE,
                    Boolean.TRUE, GenericStatusConstant.ACTIVE, Boolean.TRUE
            );
            portalUserRepository.save(portalUser);
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
}
</code>```

the error

com.google.inject.CreationException: Unable to create injector, see
  the following errors:

1) No implementation for com.bw.dd.dsl.repository.PortalUserRepository was bound.

答:
Well, I finally had to implement the whole thing. A shame I couldn't port the wonderful features from spring data jpa into ninja. I coulda used spring, but for office policy on the project.

If someone finds a way, pls holla.

```<code>public abstract class JpaRepository<E, K> {

public abstract void create(E entity);

public abstract void edit(E entity) throws Exception;

public abstract void remove(K key) throws IllegalOrphanException, NonexistentEntityException;

public abstract List<E>  findAll();

public abstract E findOne(K key);

public abstract int count();
</code>```

}

```<code>public class PortalUserRepository extends JpaRepository<PortalUser, Long> {

private EntityManagerFactory emf = null;

public PortalUserRepository() {
}

public PortalUserRepository(EntityManagerFactory emf) {
    this.emf = emf;
}

public EntityManager getEntityManager() {
    return emf.createEntityManager();
}

public void create(PortalUser entity) {
    if (entity.getUserTokens() == null) {
        entity.setUserTokens(new ArrayList<UserToken>());
    }
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Collection<UserToken> attachedUserTokens = new ArrayList<UserToken>();
        for (UserToken userTokensUserTokenToAttach : entity.getUserTokens()) {
            userTokensUserTokenToAttach = em.getReference(userTokensUserTokenToAttach.getClass(), userTokensUserTokenToAttach.getId());
            attachedUserTokens.add(userTokensUserTokenToAttach);
        }
        entity.setUserTokens(attachedUserTokens);
        em.persist(entity);
        for (UserToken userTokensUserToken : entity.getUserTokens()) {
            PortalUser oldPortalUserOfUserTokensUserToken = userTokensUserToken.getPortalUser();
            userTokensUserToken.setPortalUser(entity);
            userTokensUserToken = em.merge(userTokensUserToken);
            if (oldPortalUserOfUserTokensUserToken != null) {
                oldPortalUserOfUserTokensUserToken.getUserTokens().remove(userTokensUserToken);
                oldPortalUserOfUserTokensUserToken = em.merge(oldPortalUserOfUserTokensUserToken);
            }
        }
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public void edit(PortalUser entity) throws Exception {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        PortalUser persistentPortalUser = em.find(PortalUser.class, entity.getId());
        Collection<UserToken> userTokensOld = persistentPortalUser.getUserTokens();
        Collection<UserToken> userTokensNew = entity.getUserTokens();
        List<String> illegalOrphanMessages = null;
        for (UserToken userTokensOldUserToken : userTokensOld) {
            if (!userTokensNew.contains(userTokensOldUserToken)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain UserToken " + userTokensOldUserToken + " since its entity field is not nullable.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        Collection<UserToken> attachedUserTokensNew = new ArrayList<UserToken>();
        for (UserToken userTokensNewUserTokenToAttach : userTokensNew) {
            userTokensNewUserTokenToAttach = em.getReference(userTokensNewUserTokenToAttach.getClass(), userTokensNewUserTokenToAttach.getId());
            attachedUserTokensNew.add(userTokensNewUserTokenToAttach);
        }
        userTokensNew = attachedUserTokensNew;
        entity.setUserTokens(userTokensNew);
        entity = em.merge(entity);
        for (UserToken userTokensNewUserToken : userTokensNew) {
            if (!userTokensOld.contains(userTokensNewUserToken)) {
                PortalUser oldPortalUserOfUserTokensNewUserToken = userTokensNewUserToken.getPortalUser();
                userTokensNewUserToken.setPortalUser(entity);
                userTokensNewUserToken = em.merge(userTokensNewUserToken);
                if (oldPortalUserOfUserTokensNewUserToken != null && !oldPortalUserOfUserTokensNewUserToken.equals(entity)) {
                    oldPortalUserOfUserTokensNewUserToken.getUserTokens().remove(userTokensNewUserToken);
                    oldPortalUserOfUserTokensNewUserToken = em.merge(oldPortalUserOfUserTokensNewUserToken);
                }
            }
        }
        em.getTransaction().commit();
    } catch (Exception ex) {
        String msg = ex.getLocalizedMessage();
        if (msg == null || msg.length() == 0) {
            Long id = entity.getId();
            if (findOne(id) == null) {
                throw new NonexistentEntityException("The entity with id " + id + " no longer exists.");
            }
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public void remove(Long key) throws IllegalOrphanException, NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        PortalUser portalUser;
        try {
            portalUser = em.getReference(PortalUser.class, key);
            portalUser.getId();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The portalUser with id " + key + " no longer exists.", enfe);
        }
        List<String> illegalOrphanMessages = null;
        Collection<UserToken> userTokensOrphanCheck = portalUser.getUserTokens();
        for (UserToken userTokensOrphanCheckUserToken : userTokensOrphanCheck) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("This PortalUser (" + portalUser + ") cannot be destroyed since the UserToken " + userTokensOrphanCheckUserToken + " in its userTokens field has a non-nullable portalUser field.");
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        em.remove(portalUser);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public List<PortalUser> findAll() {
    EntityManager em = getEntityManager();
    try {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(PortalUser.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    } finally {
        em.close();
    }
}

public PortalUser findOne(Long key) {
    EntityManager em = getEntityManager();
    try {
        return em.find(PortalUser.class, key);
    } finally {
        em.close();
    }
}

public int count() {
    EntityManager em = getEntityManager();
    try {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<PortalUser> rt = cq.from(PortalUser.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    } finally {
        em.close();
    }
}

public PortalUser findPortalUserByUsername(String username){
    EntityManager em = getEntityManager();
    try {
        Query q = em.createQuery("select s from PortalUser s where s.username = '" + username + "'");
        return (PortalUser)q.getSingleResult();
    } finally {
        em.close();
    }
}
</code>```

Title: use spring data jpa with ninja java

Body:
ninja is an awesome framework but coming from a  spring background, I need to use spring data jpa with ninja.

I want to Autowire a JpaRepository and use it in ninja. Although ninja uses Guice Inject. I keep getting a No implementations found for my class.

the repository:

public interface PortalUserRepository extends JpaRepository<PortalUser, Long> {

PortalUser getPortalUserByUsername(String username);

PortalUser getPortalUserByEmail(String email);
}

the injection

public class SetupDaoV2 {

@Inject
PortalUserRepository portalUserRepository;

public void setup() {
    try {
        List<PortalUser> portalUsers = portalUserRepository.findAll();
        if (portalUsers.size() == 0) {
            // Create a new user and save it
            PortalUser portalUser = new PortalUser("lsadjfl", "lsdlfs", "kkk lll",
                    "llskfls@gmail.com", "lsdlfss@",
                    "lsdfls@gmail.com",
                    new Timestamp(System.currentTimeMillis()), Boolean.TRUE,
                    Boolean.TRUE, GenericStatusConstant.ACTIVE, Boolean.TRUE
            );
            portalUserRepository.save(portalUser);
        }
    }catch (Exception ex){
        ex.printStackTrace();
    }
}
}

the error

com.google.inject.CreationException: Unable to create injector, see
  the following errors:

1) No implementation for com.bw.dd.dsl.repository.PortalUserRepository was bound.

Body:
Well, I finally had to implement the whole thing. A shame I couldn't port the wonderful features from spring data jpa into ninja. I coulda used spring, but for office policy on the project.

If someone finds a way, pls holla.

public abstract class JpaRepository<E, K> {

public abstract void create(E entity);

public abstract void edit(E entity) throws Exception;

public abstract void remove(K key) throws IllegalOrphanException, NonexistentEntityException;

public abstract List<E>  findAll();

public abstract E findOne(K key);

public abstract int count();

}

public class PortalUserRepository extends JpaRepository<PortalUser, Long> {

private EntityManagerFactory emf = null;

public PortalUserRepository() {
}

public PortalUserRepository(EntityManagerFactory emf) {
    this.emf = emf;
}

public EntityManager getEntityManager() {
    return emf.createEntityManager();
}

public void create(PortalUser entity) {
    if (entity.getUserTokens() == null) {
        entity.setUserTokens(new ArrayList<UserToken>());
    }
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        Collection<UserToken> attachedUserTokens = new ArrayList<UserToken>();
        for (UserToken userTokensUserTokenToAttach : entity.getUserTokens()) {
            userTokensUserTokenToAttach = em.getReference(userTokensUserTokenToAttach.getClass(), userTokensUserTokenToAttach.getId());
            attachedUserTokens.add(userTokensUserTokenToAttach);
        }
        entity.setUserTokens(attachedUserTokens);
        em.persist(entity);
        for (UserToken userTokensUserToken : entity.getUserTokens()) {
            PortalUser oldPortalUserOfUserTokensUserToken = userTokensUserToken.getPortalUser();
            userTokensUserToken.setPortalUser(entity);
            userTokensUserToken = em.merge(userTokensUserToken);
            if (oldPortalUserOfUserTokensUserToken != null) {
                oldPortalUserOfUserTokensUserToken.getUserTokens().remove(userTokensUserToken);
                oldPortalUserOfUserTokensUserToken = em.merge(oldPortalUserOfUserTokensUserToken);
            }
        }
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public void edit(PortalUser entity) throws Exception {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        PortalUser persistentPortalUser = em.find(PortalUser.class, entity.getId());
        Collection<UserToken> userTokensOld = persistentPortalUser.getUserTokens();
        Collection<UserToken> userTokensNew = entity.getUserTokens();
        List<String> illegalOrphanMessages = null;
        for (UserToken userTokensOldUserToken : userTokensOld) {
            if (!userTokensNew.contains(userTokensOldUserToken)) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("You must retain UserToken " + userTokensOldUserToken + " since its entity field is not nullable.");
            }
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        Collection<UserToken> attachedUserTokensNew = new ArrayList<UserToken>();
        for (UserToken userTokensNewUserTokenToAttach : userTokensNew) {
            userTokensNewUserTokenToAttach = em.getReference(userTokensNewUserTokenToAttach.getClass(), userTokensNewUserTokenToAttach.getId());
            attachedUserTokensNew.add(userTokensNewUserTokenToAttach);
        }
        userTokensNew = attachedUserTokensNew;
        entity.setUserTokens(userTokensNew);
        entity = em.merge(entity);
        for (UserToken userTokensNewUserToken : userTokensNew) {
            if (!userTokensOld.contains(userTokensNewUserToken)) {
                PortalUser oldPortalUserOfUserTokensNewUserToken = userTokensNewUserToken.getPortalUser();
                userTokensNewUserToken.setPortalUser(entity);
                userTokensNewUserToken = em.merge(userTokensNewUserToken);
                if (oldPortalUserOfUserTokensNewUserToken != null && !oldPortalUserOfUserTokensNewUserToken.equals(entity)) {
                    oldPortalUserOfUserTokensNewUserToken.getUserTokens().remove(userTokensNewUserToken);
                    oldPortalUserOfUserTokensNewUserToken = em.merge(oldPortalUserOfUserTokensNewUserToken);
                }
            }
        }
        em.getTransaction().commit();
    } catch (Exception ex) {
        String msg = ex.getLocalizedMessage();
        if (msg == null || msg.length() == 0) {
            Long id = entity.getId();
            if (findOne(id) == null) {
                throw new NonexistentEntityException("The entity with id " + id + " no longer exists.");
            }
        }
        throw ex;
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public void remove(Long key) throws IllegalOrphanException, NonexistentEntityException {
    EntityManager em = null;
    try {
        em = getEntityManager();
        em.getTransaction().begin();
        PortalUser portalUser;
        try {
            portalUser = em.getReference(PortalUser.class, key);
            portalUser.getId();
        } catch (EntityNotFoundException enfe) {
            throw new NonexistentEntityException("The portalUser with id " + key + " no longer exists.", enfe);
        }
        List<String> illegalOrphanMessages = null;
        Collection<UserToken> userTokensOrphanCheck = portalUser.getUserTokens();
        for (UserToken userTokensOrphanCheckUserToken : userTokensOrphanCheck) {
            if (illegalOrphanMessages == null) {
                illegalOrphanMessages = new ArrayList<String>();
            }
            illegalOrphanMessages.add("This PortalUser (" + portalUser + ") cannot be destroyed since the UserToken " + userTokensOrphanCheckUserToken + " in its userTokens field has a non-nullable portalUser field.");
        }
        if (illegalOrphanMessages != null) {
            throw new IllegalOrphanException(illegalOrphanMessages);
        }
        em.remove(portalUser);
        em.getTransaction().commit();
    } finally {
        if (em != null) {
            em.close();
        }
    }
}

public List<PortalUser> findAll() {
    EntityManager em = getEntityManager();
    try {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        cq.select(cq.from(PortalUser.class));
        Query q = em.createQuery(cq);
        return q.getResultList();
    } finally {
        em.close();
    }
}

public PortalUser findOne(Long key) {
    EntityManager em = getEntityManager();
    try {
        return em.find(PortalUser.class, key);
    } finally {
        em.close();
    }
}

public int count() {
    EntityManager em = getEntityManager();
    try {
        CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
        Root<PortalUser> rt = cq.from(PortalUser.class);
        cq.select(em.getCriteriaBuilder().count(rt));
        Query q = em.createQuery(cq);
        return ((Long) q.getSingleResult()).intValue();
    } finally {
        em.close();
    }
}

public PortalUser findPortalUserByUsername(String username){
    EntityManager em = getEntityManager();
    try {
        Query q = em.createQuery("select s from PortalUser s where s.username = '" + username + "'");
        return (PortalUser)q.getSingleResult();
    } finally {
        em.close();
    }
}