问:
How can I use a button to show more posts?

I'm trying to make a page with posts. And then when i press a button it shows more posts

```<code>$start = 0;
  $end = 5;
  $slice = array_slice($postid_array, $start, $end);
  if(isset($_POST['load_more']) && is_numeric($_POST['load_more'])) {
    $load_more = $_POST['load_more'];
    if($load_more > 0) {
      $start = ($load_more * 5) + 1;
    }
    $end = $start + 4;
    $slice = array_slice($postid_array, $start, $end);
  }
</code>```

This is what I got, I use ajax to increase $load_more with 1:

```<code> var clicked = 0;
function countClicks(){
  clicked += 1;
  var nb_clicked = clicked;
  console.log(nb_clicked);
  $.ajax({
    url: "../home/posts.php",
    type: "POST",
    data: "load_more="+nb_clicked,
    success: function(responseText) {
      $(".posts").append(responseText)
    },
    error: function() {
      console.log("ajax error");
    }
  })
}
</code>```

But instead of getting 5 more posts. I get 10, and when i click again it gives me 15.

I hope this is enough information.

Thank you!

答:
1st , you doing massive operation twice (array_slice) ... do 1st checks , 2nd splice .

2nd , is mistake - 3rd param of array_slice is LENGTH , not offset2 , or so.

so don't do

```<code>$end = $start + 4;
</code>```

it's just 5 .

so best code . ( of course in your styling )

```<code>$start = 0;
$LENGTH = 5;
if(isset($_POST['load_more']) && is_numeric($_POST['load_more'])) {
    $load_more = $_POST['load_more'];
    if($load_more > 0) {
       $start = $load_more * $LENGTH;
    }
}
$slice = array_slice($postid_array, $start, $LENGTH);
</code>```

Body:
I'm trying to make a page with posts. And then when i press a button it shows more posts

$start = 0;
  $end = 5;
  $slice = array_slice($postid_array, $start, $end);
  if(isset($_POST['load_more']) && is_numeric($_POST['load_more'])) {
    $load_more = $_POST['load_more'];
    if($load_more > 0) {
      $start = ($load_more * 5) + 1;
    }
    $end = $start + 4;
    $slice = array_slice($postid_array, $start, $end);
  }

This is what I got, I use ajax to increase $load_more with 1:

 var clicked = 0;
function countClicks(){
  clicked += 1;
  var nb_clicked = clicked;
  console.log(nb_clicked);
  $.ajax({
    url: "../home/posts.php",
    type: "POST",
    data: "load_more="+nb_clicked,
    success: function(responseText) {
      $(".posts").append(responseText)
    },
    error: function() {
      console.log("ajax error");
    }
  })
}

But instead of getting 5 more posts. I get 10, and when i click again it gives me 15.

I hope this is enough information.

Thank you!

Body:
1st , you doing massive operation twice (array_slice) ... do 1st checks , 2nd splice .

2nd , is mistake - 3rd param of array_slice is LENGTH , not offset2 , or so.

so don't do

$end = $start + 4;

it's just 5 .

so best code . ( of course in your styling )

$start = 0;
$LENGTH = 5;
if(isset($_POST['load_more']) && is_numeric($_POST['load_more'])) {
    $load_more = $_POST['load_more'];
    if($load_more > 0) {
       $start = $load_more * $LENGTH;
    }
}
$slice = array_slice($postid_array, $start, $LENGTH);


来源: stackexchange

问:
Report pulling duplicate values with JOIN access
I am pulling a report in access by writing a query in VBA and it has joining of tables.
The problem is the report is now pulling duplicates values in the report.

```<code>ReCrt1 = "SELECT TeamDetails_v1.vName
            FROM TeamDetails_v1
            LEFT JOIN Attendance ON TeamDetails_v1.vName = Attendance.Name
            WHERE ([Attendance!Team] In ('" & Mylist & "'))
                AND ([Attendance!Dates]>Forms!AttendanceSummary!DTPicker0)
                AND ([Attendance!Dates]<Forms!AttendanceSummary!DTPicker6)
                AND ([TeamDetails_v1.vEmployment_Status]='Active')"
DoCmd.OpenReport "Monthly Report", acViewReport, , , , ReCrt1
</code>```

The line breaks in SQL statement is not in code. I put it there for your ease.

I need the report to pull names from "TeamDetails_v1" table which has only unique name records and are 'active' in "vEmployment_Status". And their respective number of records(count formula is used in the Report) in "Attendance" table where dates should be in between the dates from date picker controls."Mylist" is a array containing certain teams filtered based on a list box in the form.

Here, instead of pulling single name records from TeamDetails_v1, the report pulls n number of same data if there is n number of dates.
I have provided only a single textbox in report and its control source is given as "TeamDetails_v1.vName".
Is there any issues with JOIN I used or is it the textbox field control source?

答:
Did you try putting the keyword "Distinct" after SELECT</p>

```<code> ReCrt1 = "SELECT DISTINCT TeamDetails_v1.vName FROM TeamDetails_v1 LEFT JOIN Attendance ON TeamDetails_v1.vName = Attendance.Name
    WHERE ([Attendance!Team] In ('" & Mylist & "')) And ([Attendance!Dates]>Forms!AttendanceSummary!DTPicker0) And
    ([Attendance!Dates]<Forms!AttendanceSummary!DTPicker6) And ([TeamDetails_v1.vEmployment_Status]='Active')"

        DoCmd.OpenReport "Monthly Report", acViewReport, , , , ReCrt1
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I am pulling a report in access by writing a query in VBA and it has joining of tables.
The problem is the report is now pulling duplicates values in the report.

ReCrt1 = "SELECT TeamDetails_v1.vName
            FROM TeamDetails_v1
            LEFT JOIN Attendance ON TeamDetails_v1.vName = Attendance.Name
            WHERE ([Attendance!Team] In ('" & Mylist & "'))
                AND ([Attendance!Dates]>Forms!AttendanceSummary!DTPicker0)
                AND ([Attendance!Dates]<Forms!AttendanceSummary!DTPicker6)
                AND ([TeamDetails_v1.vEmployment_Status]='Active')"
DoCmd.OpenReport "Monthly Report", acViewReport, , , , ReCrt1

The line breaks in SQL statement is not in code. I put it there for your ease.

I need the report to pull names from "TeamDetails_v1" table which has only unique name records and are 'active' in "vEmployment_Status". And their respective number of records(count formula is used in the Report) in "Attendance" table where dates should be in between the dates from date picker controls."Mylist" is a array containing certain teams filtered based on a list box in the form.

Here, instead of pulling single name records from TeamDetails_v1, the report pulls n number of same data if there is n number of dates.
I have provided only a single textbox in report and its control source is given as "TeamDetails_v1.vName".
Is there any issues with JOIN I used or is it the textbox field control source?

Body:
Did you try putting the keyword "Distinct" after SELECT

 ReCrt1 = "SELECT DISTINCT TeamDetails_v1.vName FROM TeamDetails_v1 LEFT JOIN Attendance ON TeamDetails_v1.vName = Attendance.Name
    WHERE ([Attendance!Team] In ('" & Mylist & "')) And ([Attendance!Dates]>Forms!AttendanceSummary!DTPicker0) And
    ([Attendance!Dates]<Forms!AttendanceSummary!DTPicker6) And ([TeamDetails_v1.vEmployment_Status]='Active')"

        DoCmd.OpenReport "Monthly Report", acViewReport, , , , ReCrt1


问:
Spectron/WebdriverIO nth child using $$[n] instead of selector
I am trying to use Spectron to test my Electron application. The documentation says when trying to find the nth child, you can use an nth child selector, or get all children that match selector using $$ and then use index operator ie $$ ("foo")[0] gets first foo.  DOCS

With that knowledge, i expect the following code to output: BAR
I can't get this to work, i try the following:

```<code>const foo = ".foo";
const fooElements = app.client.$$ (foo);
console.log ("FOOELEMENTS", await TP (app.client.getHTML (foo)));
console.log ("BAR", fooElements[0].getText (".bar"));
</code>```

And get the following output:

```<code>console.log components\pages\analysis\__test__\Analysis.spectron.ts:44
    FOOELEMENTS [ '<div class="foo"><div class="bar">BAR</div><div class="baz">BAZ</div></div>',
    '<div class="foo"><div class="bar">BAR2</div><div class="baz">BAZ2</div></div>',
    '<div class="foo"><div class="bar">BAR3</div><div class="baz">BAZ3</div></div>'
    '<div class="foo"><div class="bar">BAR4</div><div class="baz">BAZ4</div></div>' ]

console.log components\pages\analysis\__test__\Analysis.spectron.ts:50
    EXCEPTION TypeError: Cannot read property 'getText' of undefined
        at components\pages\analysis\__test__\Analysis.spectron.ts:45:44
        at Generator.next (<anonymous>)
        at fulfilled (components\pages\analysis\__test__\Analysis.spectron.ts:4:58)
        at <anonymous>
        at process._tickDomainCallback (internal/process/next_tick.js:228:7)
</code>```

As you can see, the output HTML indeed has several .foo divs, but when i try to access the first one, it says fooElements[0] is undefined

sideNote (which should not be relevant): TP is an alias for a function i wrote called toPromise which lets me await the webdriver promises, because TypeScript is confused by the way they are implemented:

```<code>export async function toPromise<T> (client: Webdriver.Client<T>)
{
    return client as any as Promise<T>;
}

// Promise
    interface Client<T> {
        finally(callback: (...args: any[]) => void): Client<T>;

        then<P>(
            onFulfilled?: (value: T) => P | Client<P>,
            onRejected?: (error: any) => P | Client<P>
        ): Client<P>;

        catch<P>(
            onRejected?: (error: any) => P | Client<P>
        ): Client<P>;

        inspect(): {
            state: "fulfilled" | "rejected" | "pending";
            value?: T;
            reason?: any;
        };
    }
</code>```

Any idea what i am doing wrong? Or a suggested alternative? I'd prefer to avoid nth-child selectors if possible.

EDIT: changed to class

答:
First off, you're example is intriguing. I don't know how you got that piece of  to be ran. The id value must be unique:

The id attribute specifies a unique id for an HTML element (the value
  must be unique within the HTML document).

Your code should work after a small change, just remove the #bar selector. You were passing the selector to the ELEMENT object, but it already contains that information via the value of the selector key.

```<code>let locator = 'span[connectqa-device="installed"]'

browser.debug()
</code>```

Output (blocked test in debug-mode):

```<code>> let elems = $$(locator)
[18:10:22]  COMMAND     POST     "/wd/hub/session/775b024e-0b6a-4a60-a5b2-26d4df961d0a/elements"
[18:10:22]  DATA                {"using":"css selector","value":"span[connectqa-device=\"installed\"]"}
[18:10:22]  RESULT              [{"element-6066-11e4-a52e-4f735466cecf":"c6719646-30da-43ff-9b17-40c074b4988a"},{"element-6066-11e4-a52e-4f735466cecf":"d5f8acf2-8f4f-4554-9fe6-7f863555f5b5"},{"element-6066-11e4-a52e-4f735466cecf":"53ff9b0a-2a88-4b13-9e54-9c54411c03c5"}]

> elems[0]
{ ELEMENT: 'c6719646-30da-43ff-9b17-40c074b4988a',
  'element-6066-11e4-a52e-4f735466cecf': 'c6719646-30da-43ff-9b17-40c074b4988a',
  selector: 'span[connectqa-device="installed"]',
  value: { ELEMENT: 'c6719646-30da-43ff-9b17-40c074b4988a' },
  index: 0 }
>
> elems[0].selector
'span[connectqa-device="installed"]'
>
> elems[0].getText()
[18:10:54]  COMMAND     GET      "/wd/hub/session/775b024e-0b6a-4a60-a5b2-26d4df961d0a/element/c6719646-30da-43ff-9b17-40c074b4988a/text"
[18:10:54]  DATA                {}
[18:10:54]  RESULT              "Installed"
'Installed'
</code>```

Alternatively, you could have done this: let retText2 = browser.getText('span[connectqa-device="installed"]') > let retText2 = browser.getText(elems[0].selector). The second example of course is only for didactic purposes, as you'd probably never want to to it that way.

Hope it helps. Cheers!

Body:
I am trying to use Spectron to test my Electron application. The documentation says when trying to find the nth child, you can use an nth child selector, or get all children that match selector using $$ and then use index operator ie $$ ("foo")[0] gets first foo.  DOCS

With that knowledge, i expect the following code to output: BAR
I can't get this to work, i try the following:

const foo = ".foo";
const fooElements = app.client.$$ (foo);
console.log ("FOOELEMENTS", await TP (app.client.getHTML (foo)));
console.log ("BAR", fooElements[0].getText (".bar"));

And get the following output:

console.log components\pages\analysis\__test__\Analysis.spectron.ts:44
    FOOELEMENTS [ '

BAR

BAZ

',
    '

BAR2

BAZ2

',
    '

BAR3

BAZ3

'
    '

BAR4

BAZ4

' ]

console.log components\pages\analysis\__test__\Analysis.spectron.ts:50
    EXCEPTION TypeError: Cannot read property 'getText' of undefined
        at components\pages\analysis\__test__\Analysis.spectron.ts:45:44
        at Generator.next (<anonymous>)
        at fulfilled (components\pages\analysis\__test__\Analysis.spectron.ts:4:58)
        at <anonymous>
        at process._tickDomainCallback (internal/process/next_tick.js:228:7)

As you can see, the output HTML indeed has several .foo divs, but when i try to access the first one, it says fooElements[0] is undefined

sideNote (which should not be relevant): TP is an alias for a function i wrote called toPromise which lets me await the webdriver promises, because TypeScript is confused by the way they are implemented:

export async function toPromise<T> (client: Webdriver.Client<T>)
{
    return client as any as Promise<T>;
}

// Promise
    interface Client<T> {
        finally(callback: (...args: any[]) => void): Client<T>;

        then
(
            onFulfilled?: (value: T) => P | Client
,
            onRejected?: (error: any) => P | Client

        ): Client
;

        catch
(
            onRejected?: (error: any) => P | Client

        ): Client
;

        inspect(): {
            state: "fulfilled" | "rejected" | "pending";
            value?: T;
            reason?: any;
        };
    }

Any idea what i am doing wrong? Or a suggested alternative? I'd prefer to avoid nth-child selectors if possible.

EDIT: changed to class

Body:
First off, you're example is intriguing. I don't know how you got that piece of <html> to be ran. The id value must be unique:

The id attribute specifies a unique id for an HTML element (the value
  must be unique within the HTML document).

Your code should work after a small change, just remove the #bar selector. You were passing the selector to the ELEMENT object, but it already contains that information via the value of the selector key.

let locator = 'span[connectqa-device="installed"]'

browser.debug()

Output (blocked test in debug-mode):

> let elems = $$(locator)
[18:10:22]  COMMAND     POST     "/wd/hub/session/775b024e-0b6a-4a60-a5b2-26d4df961d0a/elements"
[18:10:22]  DATA                {"using":"css selector","value":"span[connectqa-device=\"installed\"]"}
[18:10:22]  RESULT              [{"element-6066-11e4-a52e-4f735466cecf":"c6719646-30da-43ff-9b17-40c074b4988a"},{"element-6066-11e4-a52e-4f735466cecf":"d5f8acf2-8f4f-4554-9fe6-7f863555f5b5"},{"element-6066-11e4-a52e-4f735466cecf":"53ff9b0a-2a88-4b13-9e54-9c54411c03c5"}]

> elems[0]
{ ELEMENT: 'c6719646-30da-43ff-9b17-40c074b4988a',
  'element-6066-11e4-a52e-4f735466cecf': 'c6719646-30da-43ff-9b17-40c074b4988a',
  selector: 'span[connectqa-device="installed"]',
  value: { ELEMENT: 'c6719646-30da-43ff-9b17-40c074b4988a' },
  index: 0 }
>
> elems[0].selector
'span[connectqa-device="installed"]'
>
> elems[0].getText()
[18:10:54]  COMMAND     GET      "/wd/hub/session/775b024e-0b6a-4a60-a5b2-26d4df961d0a/element/c6719646-30da-43ff-9b17-40c074b4988a/text"
[18:10:54]  DATA                {}
[18:10:54]  RESULT              "Installed"
'Installed'

Alternatively, you could have done this: let retText2 = browser.getText('span[connectqa-device="installed"]') > let retText2 = browser.getText(elems[0].selector). The second example of course is only for didactic purposes, as you'd probably never want to to it that way.

Hope it helps. Cheers!


问:
Python - How to create a script which can simulate user actions on a website
Brief:
I want to create a program in Python which can programmatically login to a website and performs functions:
- Click anchor links
- Click buttons
- Type into text fields
- Submit forms

I'm using Python 3.6.2

I've searched for a while now and seem to see selenium as a recommended option, however once I install it and use it I can't seem to work around the errors I get: geckodriver not in PATH even though I specifically set it in the path. That was all on Python 2.7. Could I have an approach which explains where to correctly install selenium or whatever module is needed and some examples of the requirements in the list above.

If you have any questions please ask them I'm here waiting for a reply.

答:
It's saying that gecko driver is not in the path, depends on which system you are:

in ubuntu it should be in /bin
in mac it should be in user/local/bin
in windows it should be specified in the path string

one common solution is to place it in the same directory where you script is
and using webdriver.Firefox('./firefoxdriver')
or however, you called it.


问:
Jenkins Pipeline, PowerShell script hangs
I want to run a Powershell file from the Jenkins Pipeline, using the powershell command. Should be easy, right?

```<code>node()
{
    stage ('Hello World') {
        powershell returnStatus: true, script: 'C:\\HelloWorld.ps1'
    }
}
</code>```

C:\HelloWorld.ps1 is a one-liner:

```<code>Write-Host "Hello World"
</code>```

But running the job causes the process to hang. Here is the console output:

```<code>Started by user Administrator
[Pipeline] node
Running on master in C:\Jenkins\workspace\HelloWorld
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello World)
[Pipeline] powershell
[HelloWorld] Running PowerShell script
</code>```

And then it just hangs until I cancel the job.

What to do?

答:
I have the same problem in about 70 % of my cases. I have a pipeline script that kicks off about 20 parallel jobs spread out over different agents. Each of these tries to run a Powershell script initially. About 30 % of the jobs succeed to run the script, the rest hangs just like it does for Ola.

The build agents are configured exactly the way (clones in a VM cluster). Powershell v4 is used. Upon several tries one single build agent sometimes succeeds in running Powershell, sometimes don't.

I've been running this pipeline for 5-6 weeks and it's just the last week this behavior has been seen. Fortunately the script isn't in production yet :-)

I haven't had the time to do a full investigation. Could it be that some of the pipeline plugins have been updated and introduced this bug?

Body:
I want to run a Powershell file from the Jenkins Pipeline, using the powershell command. Should be easy, right?

node()
{
    stage ('Hello World') {
        powershell returnStatus: true, script: 'C:\\HelloWorld.ps1'
    }
}

C:\HelloWorld.ps1 is a one-liner:

Write-Host "Hello World"

But running the job causes the process to hang. Here is the console output:

Started by user Administrator
[Pipeline] node
Running on master in C:\Jenkins\workspace\HelloWorld
[Pipeline] {
[Pipeline] stage
[Pipeline] { (Hello World)
[Pipeline] powershell
[HelloWorld] Running PowerShell script

And then it just hangs until I cancel the job.

What to do?


问:
python 3 function with one argument returning list of integers
how the 're' function should look like if it must receive just one argument 's' and must return a list with the numbers (integers) from 1 to 12 incl. (for example)?

so the result in the interactive console have to be:

```<code>>>> re(12)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
</code>```

答:
First of all you used def incorrectly, if you want to define you have to enter : and define function in additional indentation below, or if you want to use function, you have to remove def.

Python has built-in range() immutable sequence type, which takes one to three arguments start, stop and step, in this case we only will use first two. However to get list we also need to use another built-in, which is mutable sequence type - list(), you can read more about lists in here. We will use list() as the type constructor: list() or list(iterable) as specified in built-in types page:

Lists may be constructed in several ways:

```<code>Using a pair of square brackets to denote the empty list: []
Using square brackets, separating items with commas: [a], [a, b, c]
Using a list comprehension: [x for x in iterable]
Using the type constructor: list() or list(iterable)
</code>```

The constructor builds a list whose items are the same and in the same
  order as iterable’s items. iterable may be either a sequence, a
  container that supports iteration, or an iterator object. If iterable
  is already a list, a copy is made and returned, similar to
  iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and
  list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the
  constructor creates a new empty list, [].

Now that we understand how list() works, we can go back to range() usage:

The arguments to the range constructor must be integers (either built-in int or any object that implements the index special
  method). If the step argument is omitted, it defaults to 1. If the
  start argument is omitted, it defaults to 0. If step is zero,
  ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints
  are i >= 0 and r[i] > stop.

A range object will be empty if r[0] does not meet the value constraint. Ranges do support negative indices, but these are
  interpreted as indexing from the end of the sequence determined by the
  positive indices.

Ranges containing absolute values larger than sys.maxsize are permitted but some features (such as len()) may raise OverflowError.

Range examples:

```<code>>>>
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]
</code>```

Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can
  only represent sequences that follow a strict pattern and repetition
  and concatenation will usually violate that pattern).

start:
  The value of the start parameter (or 0 if the parameter was not supplied)

stop:
  The value of the stop parameter

step:
  The value of the step parameter (or 1 if the parameter was not supplied)

Many other operations also produce lists, including the sorted() built-in.

The answer to your question looks like that:

```<code>def re(ending_number):
    return list(range(1, ending_number + 1))

list_of_twelve = re(12) # list_of_twelve will contain [1, 2, ..., 12]
</code>```

Body:
how the 're' function should look like if it must receive just one argument 's' and must return a list with the numbers (integers) from 1 to 12 incl. (for example)?

so the result in the interactive console have to be:

>>> re(12)
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]

Body:
First of all you used def incorrectly, if you want to define you have to enter : and define function in additional indentation below, or if you want to use function, you have to remove def.

Python has built-in range() immutable sequence type, which takes one to three arguments start, stop and step, in this case we only will use first two. However to get list we also need to use another built-in, which is mutable sequence type - list(), you can read more about lists in here. We will use list() as the type constructor: list() or list(iterable) as specified in built-in types page:

Lists may be constructed in several ways:

Using a pair of square brackets to denote the empty list: []
Using square brackets, separating items with commas: [a], [a, b, c]
Using a list comprehension: [x for x in iterable]
Using the type constructor: list() or list(iterable)

The constructor builds a list whose items are the same and in the same
  order as iterable’s items. iterable may be either a sequence, a
  container that supports iteration, or an iterator object. If iterable
  is already a list, a copy is made and returned, similar to
  iterable[:]. For example, list('abc') returns ['a', 'b', 'c'] and
  list( (1, 2, 3) ) returns [1, 2, 3]. If no argument is given, the
  constructor creates a new empty list, [].

Now that we understand how list() works, we can go back to range() usage:

The arguments to the range constructor must be integers (either built-in int or any object that implements the index special
  method). If the step argument is omitted, it defaults to 1. If the
  start argument is omitted, it defaults to 0. If step is zero,
  ValueError is raised.

For a positive step, the contents of a range r are determined by the formula r[i] = start + step*i where i >= 0 and r[i] < stop.

For a negative step, the contents of the range are still determined by the formula r[i] = start + step*i, but the constraints
  are i >= 0 and r[i] > stop.

A range object will be empty if r[0] does not meet the value constraint. Ranges do support negative indices, but these are
  interpreted as indexing from the end of the sequence determined by the
  positive indices.

Ranges containing absolute values larger than sys.maxsize are permitted but some features (such as len()) may raise OverflowError.

Range examples:

>>>
>>> list(range(10))
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> list(range(1, 11))
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> list(range(0, 30, 5))
[0, 5, 10, 15, 20, 25]
>>> list(range(0, 10, 3))
[0, 3, 6, 9]
>>> list(range(0, -10, -1))
[0, -1, -2, -3, -4, -5, -6, -7, -8, -9]
>>> list(range(0))
[]
>>> list(range(1, 0))
[]

Ranges implement all of the common sequence operations except concatenation and repetition (due to the fact that range objects can
  only represent sequences that follow a strict pattern and repetition
  and concatenation will usually violate that pattern).

start:
  The value of the start parameter (or 0 if the parameter was not supplied)

stop:
  The value of the stop parameter

step:
  The value of the step parameter (or 1 if the parameter was not supplied)

Many other operations also produce lists, including the sorted() built-in.

The answer to your question looks like that:

def re(ending_number):
    return list(range(1, ending_number + 1))

list_of_twelve = re(12) # list_of_twelve will contain [1, 2, ..., 12]


问:
Append row to JSON
How I can append array to my JSON after add row to database

```<code>[
  {id: 1, content: "aaaa", date: "2017-12-05T23:00:00.000Z"},
  {id: 2, content: "bbbb", date: "2017-13-05T23:00:00.000Z"},
  {id: 3, content: "cccc", date: "2017-13-05T23:00:00.000Z"},
  {id: 4, content: "dddd", date: "2017-14-05T23:00:00.000Z"},
  {id: 5, content: "eeee", date: "2017-14-05T23:00:00.000Z"},
]
</code>```

and I add quest in my database with date 2017-13-05T23:00:00.000Z and how I have to show this i view, but I have to add this row to last value with date 2017-13-05T23:00:00.000Z.

答:
If you'd like to keep the array sorted by date, you could use push and then sort the array by date like so:

const array = [
  {id: 1, content: "aaaa", date: "2017-12-05T23:00:00.000Z"},
  {id: 2, content: "bbbb", date: "2017-13-05T23:00:00.000Z"},
  {id: 3, content: "cccc", date: "2017-13-05T23:00:00.000Z"},
  {id: 4, content: "dddd", date: "2017-14-05T23:00:00.000Z"},
  {id: 5, content: "eeee", date: "2017-14-05T23:00:00.000Z"},
]

const rowToInsert = {id: 6, content: "ffff", date: "2017-13-05T23:00:00.000Z"}

array.push(rowToInsert)

array.sort(function (a, b) {
  return a.date > b.date;
})

console.log(array)```

Title: Append row to JSON

Body:
How I can append array to my JSON after add row to database

[
  {id: 1, content: "aaaa", date: "2017-12-05T23:00:00.000Z"},
  {id: 2, content: "bbbb", date: "2017-13-05T23:00:00.000Z"},
  {id: 3, content: "cccc", date: "2017-13-05T23:00:00.000Z"},
  {id: 4, content: "dddd", date: "2017-14-05T23:00:00.000Z"},
  {id: 5, content: "eeee", date: "2017-14-05T23:00:00.000Z"},
]

and I add quest in my database with date 2017-13-05T23:00:00.000Z and how I have to show this i view, but I have to add this row to last value with date 2017-13-05T23:00:00.000Z.


问:
Why Would a Loop Skip Values?
For some reason a loop I have is leaving every second list-item from an unordered list instead of removing every list-item. And I am very confused as to why.

The code:

```<code><!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">

<title>Debugging</title>
    <script>

    function testingTesting() {
        var itemList = document.getElementsByTagName('LI');

        document.getElementById('demo').innerHTML = itemList.length;

        for (i = 0; i < itemList.length; i++) {
            document.getElementById('skillList').removeChild(itemList[i]);
        }
    }
    </script>
  </head>
  <body>
    <div id="toDisplay">

         <h2>Heading for Reasons</h2>
        <ul id="skillList">
          <li>Alpha</li>
          <li>Bravo</li>
          <li>Charlie</li>
          <li>Delta</li>
          <li>Foxtrot</li>
          <li>Exxon</li>
        </ul>

        <p id="demo"> </p>
    </div>

    <input type="button" value="Sort!" onclick="testingTesting()">

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

The result (in Chrome and Opera) of hitting the sort button once is:

"Heading for Reasons

Bravo
Delta
Exxon
6"

The result when hitting it twice is:

"Heading for Reasons

Delta
3"

Does anyone know why the list items in the itemList Array of modulo 2n + 1 are skipped?

Thank you.

答:
You are removing items from the container that you’re iterating over.

Cancel the incrementation of i if you remove an item.

Title: Why Would a Loop Skip Values?

Body:
For some reason a loop I have is leaving every second list-item from an unordered list instead of removing every list-item. And I am very confused as to why.

The code:

<!DOCTYPE html>

    <meta charset="UTF-8">

<title>Debugging</title>

Heading for Reasons

Alpha

Bravo

Charlie

Delta

Foxtrot

Exxon

    <input type="button" value="Sort!" onclick="testingTesting()">

The result (in Chrome and Opera) of hitting the sort button once is:

"Heading for Reasons

Bravo
Delta
Exxon
6"

The result when hitting it twice is:

"Heading for Reasons

Delta
3"

Does anyone know why the list items in the itemList Array of modulo 2n + 1 are skipped?

Thank you.


问:
React theme styles
I'm trying to pass theme prop into my component, because I want to have multiple styles assigned to my button component and I'd like to have the ability to choose if I wantto use button with primary class or primary-white class.

Here is my code:

```<code>import React from "react";

import CSSModules from "react-css-modules";

import classNames from "classnames";

import styles from "./Button.module.sass";

export type ButtonTheme =
  | "primary"
  | "primary-white";

export interface ButtonProps {
  onClick: () => void;
  id?: string;
  disabled?: boolean;
  children?: React.ReactNode;
  theme?: ButtonTheme;
}

export const Button: React.SFC<ButtonProps> =
  CSSModules(styles)(
    ({
      theme = "primary",
      children,
      ...restProps
    }: ButtonProps) =>
      <button
        { ...restProps }
        styleName={
          classNames(
            "button",
            theme
          )
        }
      >
        { children }
      </button>
    );
</code>```

And my css file looks like this:

```<code>@import "~@assets/stylesheets/sass-variables"

$button-disabled-background-color: rgba($black, .1)

.button
  display: inline-block
  height: var(--button-height)
  padding: 0 15px
  font-family: "Open Sans", sans-serif
  font-size: 14px
  font-weight: 600
  white-space: nowrap
  cursor: pointer
  border: 0
  border-radius: 6px
  outline: none
  box-sizing: border-box

  &:not([disabled]):hover
    background-color: var(--color-action)

  &:disabled
    color: $button-disabled-color
    cursor: auto
    background-color: $button-disabled-background-color
.primary
  color: var(--color-white)
  background-color: var(--color-primary)
.primary-white
  color: var(--color-primary)
  background-color: var(--color-white)
</code>```

I encountered the following error:

ReactElement styleName property defines multiple module names ("button primary").

How can I pass button and primary class into my compontent?

答:
react-css-modules doesn't allow multiple module names by default, but can be configured to do so.

You'll need to set the allowMultiple option to true:

```<code>const options = { allowMultiple: true };
</code>```

And then pass options to your CSSModules function, along with the styles you're already passing.

See docs here:
https://github.com/gajus/react-css-modules#options

Title: React theme styles

Body:
I'm trying to pass theme prop into my component, because I want to have multiple styles assigned to my button component and I'd like to have the ability to choose if I wantto use button with primary class or primary-white class.

Here is my code:

import React from "react";

import CSSModules from "react-css-modules";

import classNames from "classnames";

import styles from "./Button.module.sass";

export type ButtonTheme =
  | "primary"
  | "primary-white";

export interface ButtonProps {
  onClick: () => void;
  id?: string;
  disabled?: boolean;
  children?: React.ReactNode;
  theme?: ButtonTheme;
}

export const Button: React.SFC<ButtonProps> =
  CSSModules(styles)(
    ({
      theme = "primary",
      children,
      ...restProps
    }: ButtonProps) =>
      <button
        { ...restProps }
        styleName={
          classNames(
            "button",
            theme
          )
        }
      >
        { children }
      </button>
    );

And my css file looks like this:

@import "~@assets/stylesheets/sass-variables"

$button-disabled-background-color: rgba($black, .1)

.button
  display: inline-block
  height: var(--button-height)
  padding: 0 15px
  font-family: "Open Sans", sans-serif
  font-size: 14px
  font-weight: 600
  white-space: nowrap
  cursor: pointer
  border: 0
  border-radius: 6px
  outline: none
  box-sizing: border-box

  &:not([disabled]):hover
    background-color: var(--color-action)

  &:disabled
    color: $button-disabled-color
    cursor: auto
    background-color: $button-disabled-background-color
.primary
  color: var(--color-white)
  background-color: var(--color-primary)
.primary-white
  color: var(--color-primary)
  background-color: var(--color-white)

I encountered the following error:

ReactElement styleName property defines multiple module names ("button primary").

How can I pass button and primary class into my compontent?

Body:
react-css-modules doesn't allow multiple module names by default, but can be configured to do so.

You'll need to set the allowMultiple option to true:

const options = { allowMultiple: true };

And then pass options to your CSSModules function, along with the styles you're already passing.

See docs here:
https://github.com/gajus/react-css-modules#options


问:
Field is present in output, but getting KeyError
Below is my output. As you can see, children is clearly a (dictionary) field in my response.

This code works perfectly, but it keeps any nested fields (lists or dictionaries) as is:

```<code>user = ""
password = getattr(config, 'password')
url = ''
req = requests.post(url = url, auth=(user, password))
print('Authentication succesful!/n')
ans = req.json()

#Transform resultList into Pandas DF
solr_df = pd.DataFrame.from_dict(json_normalize(ans['resultList']), orient='columns')
</code>```

I instead would like to normalize the "children" field, so I did the following instead of the last row above:

```<code>solr_df = pd.DataFrame()
for record in ans['resultList']:
    df = pd.DataFrame(record['children'])
    df['contactId'] = record['contactId']
    solr_df = solr_df.append(df)
</code>```

However, I am getting a KeyError: 'children'.

Can anyone suggest what I am doing wrong?

答:
Since the message is KeyError: 'children', the only plausible reason for the error is that the children key is missing in one of the dicts. You can avoid the exception by using a try/except block, or can pass in a default value for the key, like:

```<code>solr_df = pd.DataFrame()
for record in ans['resultList']:
    df = pd.DataFrame(record.get('children', {})
    df['contactId'] = record.get('contactId')
    solr_df = solr_df.append(df)
</code>```

Body:
Below is my output. As you can see, children is clearly a (dictionary) field in my response.

This code works perfectly, but it keeps any nested fields (lists or dictionaries) as is:

user = ""
password = getattr(config, 'password')
url = ''
req = requests.post(url = url, auth=(user, password))
print('Authentication succesful!/n')
ans = req.json()

#Transform resultList into Pandas DF
solr_df = pd.DataFrame.from_dict(json_normalize(ans['resultList']), orient='columns')

I instead would like to normalize the "children" field, so I did the following instead of the last row above:

solr_df = pd.DataFrame()
for record in ans['resultList']:
    df = pd.DataFrame(record['children'])
    df['contactId'] = record['contactId']
    solr_df = solr_df.append(df)

However, I am getting a KeyError: 'children'.

Can anyone suggest what I am doing wrong?

Body:
Since the message is KeyError: 'children', the only plausible reason for the error is that the children key is missing in one of the dicts. You can avoid the exception by using a try/except block, or can pass in a default value for the key, like:

solr_df = pd.DataFrame()
for record in ans['resultList']:
    df = pd.DataFrame(record.get('children', {})
    df['contactId'] = record.get('contactId')
    solr_df = solr_df.append(df)


问:
Unhandled exception in apparently trivial function call
I have a function that reads a text file and successfully returns a vector of the small number of lines in the file.  I passed this vector to a function to process the lines and it threw an error

```<code>Unhandled exception at 0x00267EF9 in Bridge.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00A82000). occurred
</code>```

So, as Ben Voigt pointed out, there was a stack overflow that probably had nothing to do with the function that apparently threw it i.e.

```<code>   int LinesToCards(std::vector<std::string>& lines) {
        int retval = -999;
        return retval;
    }
</code>```

This was called from main which had a line needed by a 3rd party DLL

```<code>    int main()
        {
            std::string cards[MAXDEALS][DDS_HANDS][DDS_SUITS] ;
            int retval = -999;
            retval = LinesToCards(lines);
            return 0;
    }
</code>```

The
    #define DDS_HANDS 4
    #define DDS_SUITS 4
cannot be changed but the original working

```<code>#define MAXDEALS 999
</code>```

now throws the exception.  If I reduce it to

```<code>#define MAXDEALS 890
</code>```

the code runs again.  If I up that to

```<code>#define MAXDEALS 891
</code>```

it crashes.  Is there some magic number between 16240 and 16256?

答:
You're out of stack space.

The function where the failure happens is not the function that's to blame, and that's why it doesn't happen in your small test program.

One of the functions in the call path to the failing code was very greedy and didn't leave enough stack available for the functions it calls.

Look for both large objects on the stack and also too-deep recursion.

Body:
I have a function that reads a text file and successfully returns a vector of the small number of lines in the file.  I passed this vector to a function to process the lines and it threw an error

Unhandled exception at 0x00267EF9 in Bridge.exe: 0xC00000FD: Stack overflow (parameters: 0x00000000, 0x00A82000). occurred

So, as Ben Voigt pointed out, there was a stack overflow that probably had nothing to do with the function that apparently threw it i.e.

   int LinesToCards(std::vector<std::string>& lines) {
        int retval = -999;
        return retval;
    }

This was called from main which had a line needed by a 3rd party DLL

    int main()
        {
            std::string cards[MAXDEALS][DDS_HANDS][DDS_SUITS] ;
            int retval = -999;
            retval = LinesToCards(lines);
            return 0;
    }

The
    #define DDS_HANDS 4
    #define DDS_SUITS 4
cannot be changed but the original working

#define MAXDEALS 999

now throws the exception.  If I reduce it to

#define MAXDEALS 890

the code runs again.  If I up that to

#define MAXDEALS 891

it crashes.  Is there some magic number between 16240 and 16256?


问:
SAML / Shibb authentication in Django
I am newbie to Django, but I know how to create a simple application in python-Django how to add new page , how to link it into url file etc.

Now what I am trying to do, I am trying to create a very simple webapp where On the landing page I will have a login link.

When the user clicks on this link it should go to george washington universities authentication window and then I can enter my university's credential and it should authenticate and come back to a page stating ** Login Successful**

I have gone through many tutorials, but all looks very confusing.

I have installed xmlsec1, pysaml2, djangosaml2 modules but even after that I was clueless what to do next. I never felt so much clueless like I am feeling for this authentication module.

It will be great if anyone can guide me with the process.

答:
You didn't say what web server you were using but, on Apache, I'd recommend you use the mod_shib Apache module in conjunction with the Django authentication middleware.

In broad strokes, you are going to let Apache/mod_shib do the SAML heavy lifting and interact with the IdP and you are going to let Django manage users for you. You are going to connect the two by using a piece of Django authentication middleware that authenticates users using the REMOTE_USER environment variable to communicate between Apache and the Django app.

So, first setup Django using Django authentication as described in the Django documentation. Validate that you can create a user using the admin tools and that you can login and establish a session using the Django authentication methods.

Once you have simple, local login working, install the RemoteUser middleware and validate that, by setting the REMOTE_USER environment variable, you can cause your Django app to log a user in (you can do all this testing using the development server locally on your development machine).

Once you have demonstrated that you can log a user in by having the REMOTE_USER environment set, you need to install the Apache shibboleth module, mod_shib and use it to protect the root of your application.

Assuming your application is located at /mysite the config in your virtualhost section would include:

```<code><Location /mysite>
    ShibRequestSetting redirectToSSL 443
    AuthType shibboleth
    ShibRequestSetting requireSession 1
    Require valid-user
</Location>
</code>```

That configuration will tell apache that the /mysite path requires mod_shib to get involved and forces the communication over ssl/tls.

I will not go through all the configuration steps needed to install and configure shibboleth but, basically, you want to set your application default (shibboleth2.xml file) with REMOTE_USER=eppn (if you want to use another attribute like eptid you would specify that); this tells the module which attribute to stuff in the REMOTE_USER environment variable. Again, the shib doc is pretty clear here so I won't go into detail about how to redirect to your university IdP but, basically, you will create an entry in your Sessions section of the form:

```<code><SSO entityID="https://idp.testshib.org/idp/shibboleth">
</code>```

Where you would substitute your IdP location for the testshib URL shown above.

Note that we are setting REMOTE_USER to the eppn value and that that value will be interpreted by the Django auth middleware as the user's username; you will need to create Django users with usernames that are the same as their eppn for this to work. You can also allow Django to auto-provision new accounts if, for instance, you deem IdP authentication sufficient evidence to create a new user account but, with auto-provisioning, only the minimal bits get setup; you would still need to go into that account and set first name, last name, phone, etc.

The net effect is that, whenever an unauthenticated user tries to visit a location under /mysite, they will be redirected to your university IdP, they will logon there and be redirected back. The mod_shib module (in conjunction with the shibd daemon running in the background) will handle the attribute unpacking and the session state with the IdP and will set the eppn value in the REMOTE _USER environment variable. Assuming that your Django application was setup correctly with apache, it will be invoked and the RemoteUser middleware will use the eppn value set in the REMOTE_USER environment variable to lookup the user with that username in the authentication database. If it finds a user, it will complete the Django login process (i.e. set the user object in the request, set the session state, etc.)

One more thing. To talk to you university IdP and have it release attributes to your application (i.e. eppn), you will need to do three things:

Import their IdP metadata

Export your SP metadata and have your university identity folks import it

Get your university identity team to release eppn to you

Just be aware that those three steps can be a challenge and may take non-trivial time and homework.

One more one more thing: I would recommend verifying the SAML setup separate from your Django app/middleware integration. Using the simplest mechanism you are comfortable with (simple wsgi app, php script, whatever) create a page that will simply dump the REMOTE_USER environment variable when browsed then protect that first. Once you have that page redirecting to your IdP and dumping the correct eppn in REMOTE_USER on return, then you can move on to the Django bits.

Title: SAML / Shibb authentication in Django

Body:
You didn't say what web server you were using but, on Apache, I'd recommend you use the mod_shib Apache module in conjunction with the Django authentication middleware.

In broad strokes, you are going to let Apache/mod_shib do the SAML heavy lifting and interact with the IdP and you are going to let Django manage users for you. You are going to connect the two by using a piece of Django authentication middleware that authenticates users using the REMOTE_USER environment variable to communicate between Apache and the Django app.

So, first setup Django using Django authentication as described in the Django documentation. Validate that you can create a user using the admin tools and that you can login and establish a session using the Django authentication methods.

Once you have simple, local login working, install the RemoteUser middleware and validate that, by setting the REMOTE_USER environment variable, you can cause your Django app to log a user in (you can do all this testing using the development server locally on your development machine).

Once you have demonstrated that you can log a user in by having the REMOTE_USER environment set, you need to install the Apache shibboleth module, mod_shib and use it to protect the root of your application.

Assuming your application is located at /mysite the config in your virtualhost section would include:

<Location /mysite>
    ShibRequestSetting redirectToSSL 443
    AuthType shibboleth
    ShibRequestSetting requireSession 1
    Require valid-user
</Location>

That configuration will tell apache that the /mysite path requires mod_shib to get involved and forces the communication over ssl/tls.

I will not go through all the configuration steps needed to install and configure shibboleth but, basically, you want to set your application default (shibboleth2.xml file) with REMOTE_USER=eppn (if you want to use another attribute like eptid you would specify that); this tells the module which attribute to stuff in the REMOTE_USER environment variable. Again, the shib doc is pretty clear here so I won't go into detail about how to redirect to your university IdP but, basically, you will create an entry in your Sessions section of the form:

<SSO entityID="https://idp.testshib.org/idp/shibboleth">

Where you would substitute your IdP location for the testshib URL shown above.

Note that we are setting REMOTE_USER to the eppn value and that that value will be interpreted by the Django auth middleware as the user's username; you will need to create Django users with usernames that are the same as their eppn for this to work. You can also allow Django to auto-provision new accounts if, for instance, you deem IdP authentication sufficient evidence to create a new user account but, with auto-provisioning, only the minimal bits get setup; you would still need to go into that account and set first name, last name, phone, etc.

The net effect is that, whenever an unauthenticated user tries to visit a location under /mysite, they will be redirected to your university IdP, they will logon there and be redirected back. The mod_shib module (in conjunction with the shibd daemon running in the background) will handle the attribute unpacking and the session state with the IdP and will set the eppn value in the REMOTE _USER environment variable. Assuming that your Django application was setup correctly with apache, it will be invoked and the RemoteUser middleware will use the eppn value set in the REMOTE_USER environment variable to lookup the user with that username in the authentication database. If it finds a user, it will complete the Django login process (i.e. set the user object in the request, set the session state, etc.)

One more thing. To talk to you university IdP and have it release attributes to your application (i.e. eppn), you will need to do three things:

Import their IdP metadata

Export your SP metadata and have your university identity folks import it

Get your university identity team to release eppn to you

Just be aware that those three steps can be a challenge and may take non-trivial time and homework.

One more one more thing: I would recommend verifying the SAML setup separate from your Django app/middleware integration. Using the simplest mechanism you are comfortable with (simple wsgi app, php script, whatever) create a page that will simply dump the REMOTE_USER environment variable when browsed then protect that first. Once you have that page redirecting to your IdP and dumping the correct eppn in REMOTE_USER on return, then you can move on to the Django bits.


问:
Is there any way to round a string?
So i have a string for exampe "-389761456.6570000000" and i need to round this number to 4 characters behind the dor. I wrote a whole function for this but its too long(100 lines).
i cant convert it like this:

```<code>void Calculator::Display(string a)
{
    long double q = stod(a);
    cout << setprecision(4) << q << endl;
}
</code>```

because it will look like this (3.89e^-10 etc)(just an example not the real result)
and i want smth like this "-389761456.6570"
is there any way to do it?

答: Sure, and it only requires a handful of lines of code; certainly not 100. Just consider the rules for rounding: to round to 4 digits, look at the 5th digit; if it's greater than '5', add one to the 4th digit; if it's less than '5', leave the 4th digit alone; if it's exactly '5', if anything after the 4th digit is not zero, add one to the 4th digit; otherwise, apply your tie-break rule (round-to-even, round-to-odd, round toward zero, etc.). When you add one to the 4th digit, it might roll over from '9' to something greater than '9'; if that happens, add one to the 3rd digit, etc. When all that is finished, discard the characters after the 4th digit.

Title: Is there any way to round a string?

Body:
So i have a string for exampe "-389761456.6570000000" and i need to round this number to 4 characters behind the dor. I wrote a whole function for this but its too long(100 lines).
i cant convert it like this:

void Calculator::Display(string a)
{
    long double q = stod(a);
    cout << setprecision(4) << q << endl;
}

because it will look like this (3.89e^-10 etc)(just an example not the real result)
and i want smth like this "-389761456.6570"
is there any way to do it?


问:
What is the difference between [property]= and property in Angular 4 markup?
So lets have following markup for PrimeNG table

```

There obviously is a difference between selectionMode="multiple" and [selection]="multiple" as second variand does not make table selectable. What is the difference??

For a moment i thought that property= will set value once while [property]= would bind that property to input value so it would reflect its changes, but if that is the case, in both variants table should behave the same in my case.

答:
```<code>selectionMode="multiple"
</code>```

Is plain HTML attribute and not related to Angular in any way.

```<code>[selection]="multiple"
</code>```

creates an Angular binding from the field (or expression) multiple to the property selection

Body:
So lets have following markup for PrimeNG table

There obviously is a difference between selectionMode="multiple" and [selection]="multiple" as second variand does not make table selectable. What is the difference??

For a moment i thought that property= will set value once while [property]= would bind that property to input value so it would reflect its changes, but if that is the case, in both variants table should behave the same in my case.

Body:
selectionMode="multiple"

Is plain HTML attribute and not related to Angular in any way.

[selection]="multiple"

creates an Angular binding from the field (or expression) multiple to the property selection


答:
One of your records is probably missing the 'children' key so catch that exception and continue processing the rest of the output.</p>

```<code>solr_df = pd.DataFrame()
for record in ans['resultList']:
  try:
    df = pd.DataFrame(record['children'])
    df['contactId'] = record['contactId']
    solr_df = solr_df.append(df)
  except KeyError as e:
    print("Record {} triggered {}".format(record, e))
</code>```

Title: Field is present in output, but getting KeyError

Body:
One of your records is probably missing the 'children' key so catch that exception and continue processing the rest of the output.

solr_df = pd.DataFrame()
for record in ans['resultList']:
  try:
    df = pd.DataFrame(record['children'])
    df['contactId'] = record['contactId']
    solr_df = solr_df.append(df)
  except KeyError as e:
    print("Record {} triggered {}".format(record, e))


问:
How to launch ECs in an existing VPC using Terraform
I need to create several new EC2, RDS, etc.using Terraform, in an existing AWS VPC. and the existing subnet, security group, iam, etc. they are not created by Terraform. it is created manually.

I heard the right way is to use terraform import (it is correct?). To test how terraform import works, I first tested how to import an existing EC2 in stead of an existing VPC, Because I do not want to accidentally change anything In an exist VPC.

before running

```<code>terraform import aws_instance.example i-XXXXXXXXXX
</code>```

It looks like I need to create a very detailed EC2 resource in my ec2.tf file, such as:

```<code>resource "aws_instance" "example" {
  iam_instance_profile = XXXXXXXXXX
  instance_type = XXXXXXX
  ami = XXXXXXX
  tags {
    Name = XXXXX
    Department = XXXX
    ....
  }
}
</code>```

if I just write:

```<code>resource "aws_instance" "example" {
}
</code>```

it showed I missed ami and instance type,

if I write:

```<code>resource "aws_instance" "example" {
  instance_type = XXXXXXX
  ami = XXXXXXX
}
</code>```

then running "terraform apply"
will change tags of my existing EC2 to nothing, change iam profile to nothing.

I have not tried how to import existing vpc, subnet, security group yet. I am afraid if I try, I have to put a lot of information of the existing vpc, subnet, security group, etc. my system is complex.

is it expected that I need to indicate so many details in my terraform code? isn't there a way so that I just simply indicate the id of existing stuff like vpc's id, and my new stuff will be created based on the existing id? sth. like:

```<code>data "aws_subnet" "public" {
    id = XXXXXXX
}

resource "aws_instance" "example" {
  instance_type = "t2.micro"
  ami = "${var.master_ami}"
  ......
  subnet_id = "${aws_subnet.public.id}"
}
</code>```

答:
You can leave the body of the resource blank during the import, but you'll need to go back in and fill in the specific details once it's been imported.  You can look at the imported resource with the terraform show command, and fill in all of the resource details, so when you try to run terraform plan it should show no changes needed.

But, to answer your question, yes you can use your existing resources without having to import them.   Just create a variables file that holds your existing resource ids that you need for your new resources, and then you can then reference the ones you need.

So you could have a .vars file with something like:

```<code>variable "ami_id" {
  description = "AMI ID"
  default = "ami-xxxxxxxx"
}

variable "subnet_prv1" {
  description = "Private Subnet 1"
  default = "subnet-xxxxxx"
}
</code>```

Then in your main.tf to create the resource:

```<code>resource "aws_instance" "example" {
   instance_type = "t2.micro"
   ami = "${var.ami_id}"
   ......
   subnet_id = "${var.subnet_prv1}"
}
</code>```

Just one way to go about it.  There are others, which you can read up on in the terraform docs for AWS variables

Body:
I need to create several new EC2, RDS, etc.using Terraform, in an existing AWS VPC. and the existing subnet, security group, iam, etc. they are not created by Terraform. it is created manually.

I heard the right way is to use terraform import (it is correct?). To test how terraform import works, I first tested how to import an existing EC2 in stead of an existing VPC, Because I do not want to accidentally change anything In an exist VPC.

before running

terraform import aws_instance.example i-XXXXXXXXXX

It looks like I need to create a very detailed EC2 resource in my ec2.tf file, such as:

resource "aws_instance" "example" {
  iam_instance_profile = XXXXXXXXXX
  instance_type = XXXXXXX
  ami = XXXXXXX
  tags {
    Name = XXXXX
    Department = XXXX
    ....
  }
}

if I just write:

resource "aws_instance" "example" {
}

it showed I missed ami and instance type,

if I write:

resource "aws_instance" "example" {
  instance_type = XXXXXXX
  ami = XXXXXXX
}

then running "terraform apply"
will change tags of my existing EC2 to nothing, change iam profile to nothing.

I have not tried how to import existing vpc, subnet, security group yet. I am afraid if I try, I have to put a lot of information of the existing vpc, subnet, security group, etc. my system is complex.

is it expected that I need to indicate so many details in my terraform code? isn't there a way so that I just simply indicate the id of existing stuff like vpc's id, and my new stuff will be created based on the existing id? sth. like:

data "aws_subnet" "public" {
    id = XXXXXXX
}

resource "aws_instance" "example" {
  instance_type = "t2.micro"
  ami = "${var.master_ami}"
  ......
  subnet_id = "${aws_subnet.public.id}"
}

Body:
You can leave the body of the resource blank during the import, but you'll need to go back in and fill in the specific details once it's been imported.  You can look at the imported resource with the terraform show command, and fill in all of the resource details, so when you try to run terraform plan it should show no changes needed.

But, to answer your question, yes you can use your existing resources without having to import them.   Just create a variables file that holds your existing resource ids that you need for your new resources, and then you can then reference the ones you need.

So you could have a .vars file with something like:

variable "ami_id" {
  description = "AMI ID"
  default = "ami-xxxxxxxx"
}

variable "subnet_prv1" {
  description = "Private Subnet 1"
  default = "subnet-xxxxxx"
}

Then in your main.tf to create the resource:

resource "aws_instance" "example" {
   instance_type = "t2.micro"
   ami = "${var.ami_id}"
   ......
   subnet_id = "${var.subnet_prv1}"
}

Just one way to go about it.  There are others, which you can read up on in the terraform docs for AWS variables

ContentLicense: CC BY-SA 4.0


问:
How to send email while form submission with saving data in database

Currently, our form is saving data in database on form submission but now we want (for example: to send email to email@example.com) as well. Below is the code but we are not sure, which script and where exactly we need to add.

```<code>              <!-- Nav tabs -->
              <ul class="nav nav-tabs" role="tablist" id="myTabs">
                <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Project Brief Form</a></li>
                <li role="presentation"><a href="#profile" aria-controls="profile" role="tab" data-toggle="tab">Contact Form</a></li>
              </ul>
              <!-- Tab panes -->
              <div class="tab-content">
                <div role="tabpanel" class="tab-pane active" id="home">
                    <form  action="#" method="post" enctype="multipart/form-data" id="project">
                        <div class="row">
                            <div class="col-sm-12">
                                <div class="form-group">
                                    <label>Tell us about your project in your own words? What is, for you, the main goal of the project? *</label>
                                    <textarea class="form-control" rows="4" name="project" required></textarea>
                                </div>
                            </div>
                            <div class="col-sm-6">
                              <div class="form-group">
                                <label>Full name</label>
                                <input type="text" class="form-control" placeholder="Full name" name="name" required>
                              </div>
                              <div class="form-group">
                                <label>Email / Skypename</label>
                                <input type="text" class="form-control" placeholder="Email / Skypename" name="email" required>
                              </div>
                              <div class="form-group">
                                <label>Phone</label>
                                <input type="number" class="form-control" placeholder="Phone" name="phone" required>
                              </div>
                            </div>
                            <div class="col-sm-6">
                              <div class="form-group">
                                <label>How much do you want to spend?</label>
                                <select class="form-control" name="spend" required>
                                  <option value="500 - 3000 $">500 - 3000 $</option>
                                  <option value="3000 - 10000 $">3000 - 10000 $</option>
                                  <option value="10000 - 50000 $">10000 - 50000 $</option>
                                  <option value="50000 - 250000 $">50000 - 250000 $</option>
                                  <option value="250000 $ +">250000 $ +</option>
                                </select>
                              </div>
                              <div class="form-group">
                                <label>Which services are you interested in?</label>
                                <input type="text" class="form-control" placeholder="Which services are you interested in?" name="service" required>
                              </div>
                              <div class="form-group">
                                <label>How did you find out about us?</label>
                                <input type="text" class="form-control" placeholder="Example: Google, Facebook, Behance..." name="about" required>
                              </div>
                            </div>
                            <div class="col-sm-12 text-center">
                                <button type="submit" id="btnSubmit" onclick="SubmitForm('project','dubai','add_project')" class="btn btn-default">Submit</button>
                          </div>
                          <div id="result"></div>
                        </div>
                    </form>
                </div>
                <div role="tabpanel" class="tab-pane" id="profile">
                    <form  action="#" method="post" enctype="multipart/form-data" id="contact">
                        <div class="row">
                            <div class="col-sm-12">
                              <div class="form-group">
                                <label>Full name</label>
                                <input type="text" class="form-control" placeholder="Full name" name="name" required>
                              </div>
                              <div class="form-group">
                                <label>Email</label>
                                <input type="email" class="form-control" placeholder="Email" name="email" required>
                              </div>
                              <div class="form-group">
                                <label>Phone number</label>
                                <input type="number" class="form-control" placeholder="Phone number" name="phone" required>
                              </div>
                            </div>
                            <div class="col-sm-12">
                                <div class="form-group">
                                    <label>Tell us about your project in your own words? What is, for you, the main goal of the project? *</label>
                                    <textarea class="form-control" onclick="SubmitForm('contact','skyhigh','add_contact')" rows="4" name="about"></textarea>
                                </div>
                            </div>
                            <div class="col-sm-12 text-center">
                                <button type="submit" class="btn btn-default">Submit</button>
                            </div>
                            <div id="massage"></div>
                        </div>
                    </form>
                </div>
              </div>
            </div>

            <script type="text/javascript">
                $('#myTabs a').click(function (e) {
                  e.preventDefault()
                  $(this).tab('show');
                });
            </script>
        </div>
    </div>
</div>
</code>```

```<code>              <script type="text/javascript">
function SubmitForm(FormID, Controller, FunctionName) {
           $("#"+FormID).unbind('submit').submit(function (event) {
               var formData = $( this ).serialize();
               $.ajax({
                        type: 'POST',
                        url: "<?php echo $this->config->base_url(); ?>" + Controller + "/"+ FunctionName,
                        data: formData
                    })
                    .done(function (data) {
                        if(FormID=="project")
                        {
                        // $("#"+ ResultDivId).html(data);
                          $('<center><div class="alert alert-success success-order"><h4>Your Data Send Successfully, We will Contact You Soon.</h4></div></center>').insertBefore('#result').delay(10000).fadeOut();
                        }
                        else
                        {
                          $('<center><div class="alert alert-success success-order"><h4>Your Data Send Successfully, We will Contact You Soon.</h4></div></center>').insertBefore('#massage').delay(10000).fadeOut();
                        }
                    });

                    event.preventDefault();
                    $("#"+FormID)[0].reset();
                });
        }
</script>
</code>```

We want to send emails while form submission as its saving data in database only.

答:
You should add code for email sending right where you handling a form data and saving it to database.
To send emails you'll need a properly configured server environment. It's a big topic and you haven't provided any information about your server OS. Anyway, you can just try

```<code>sudo apt-get install mailutils
</code>```

on your server. I am just assuming you're running Ubuntu. Then you'll have to use Swiftmailer package and configure it to use, for example, google's smtp.
Lastly, you'll need to set-up a google account to use for sending e-mails and configure it with correct permissions to use in your app.
Like I said, it's a big topic, a lot of things must be done to achieve what you want, and your question is very general and unclear.
Alternatively, you can look at things like mailgun for simplicity.

Body:
Currently, our form is saving data in database on form submission but now we want (for example: to send email to email@example.com) as well. Below is the code but we are not sure, which script and where exactly we need to add.

Project Brief Form

Contact Form

                    <form  action="#" method="post" enctype="multipart/form-data" id="project">

                                    Tell us about your project in your own words? What is, for you, the main goal of the project? *
                                    <textarea class="form-control" rows="4" name="project" required></textarea>

                                Full name
                                <input type="text" class="form-control" placeholder="Full name" name="name" required>

                                Email / Skypename
                                <input type="text" class="form-control" placeholder="Email / Skypename" name="email" required>

                                Phone
                                <input type="number" class="form-control" placeholder="Phone" name="phone" required>

                                How much do you want to spend?
                                <select class="form-control" name="spend" required>
                                  <option value="500 - 3000 $">500 - 3000 $</option>
                                  <option value="3000 - 10000 $">3000 - 10000 $</option>
                                  <option value="10000 - 50000 $">10000 - 50000 $</option>
                                  <option value="50000 - 250000 $">50000 - 250000 $</option>
                                  <option value="250000 $ +">250000 $ +</option>
                                </select>

                                Which services are you interested in?
                                <input type="text" class="form-control" placeholder="Which services are you interested in?" name="service" required>

                                How did you find out about us?
                                <input type="text" class="form-control" placeholder="Example: Google, Facebook, Behance..." name="about" required>

                                <button type="submit" id="btnSubmit" onclick="SubmitForm('project','dubai','add_project')" class="btn btn-default">Submit</button>

                    </form>

                    <form  action="#" method="post" enctype="multipart/form-data" id="contact">

                                Full name
                                <input type="text" class="form-control" placeholder="Full name" name="name" required>

                                Email
                                <input type="email" class="form-control" placeholder="Email" name="email" required>

                                Phone number
                                <input type="number" class="form-control" placeholder="Phone number" name="phone" required>

                                    Tell us about your project in your own words? What is, for you, the main goal of the project? *
                                    <textarea class="form-control" onclick="SubmitForm('contact','skyhigh','add_contact')" rows="4" name="about"></textarea>

                                <button type="submit" class="btn btn-default">Submit</button>

                    </form>

We want to send emails while form submission as its saving data in database only.

Body:
You should add code for email sending right where you handling a form data and saving it to database.
To send emails you'll need a properly configured server environment. It's a big topic and you haven't provided any information about your server OS. Anyway, you can just try

sudo apt-get install mailutils

on your server. I am just assuming you're running Ubuntu. Then you'll have to use Swiftmailer package and configure it to use, for example, google's smtp.
Lastly, you'll need to set-up a google account to use for sending e-mails and configure it with correct permissions to use in your app.
Like I said, it's a big topic, a lot of things must be done to achieve what you want, and your question is very general and unclear.
Alternatively, you can look at things like mailgun for simplicity.


问:
Compare html type="date" with typescript new Date() object
I have an html code

```<code><div class="form-group row">
          <label class="col-sm-2 col-form-label">Due date: </label>
          <div class="col-sm-10">
            <input type="date" class="form-control" #due_date>
          </div>
</div>
</code>```

and my typscript code is like this but it never enters the condition, so what should I do?

```<code>if(element.due_date <= new Date()){
    //if(element.due_time <= new Date().toLocaleTimeString())
    console.log(element);
    element.notify = true;
  }
</code>```

答:
According to the template, your component code should be like</p>

```<code>export class SomeComponent {
  @ViewChild('due_date') due_date: ElementRef;

  someMethod() {
    const inputDate = new Date(this.due_date.nativeElement.value);
    if (inputDate <= new Date()) {
      //if(element.due_time <= new Date().toLocaleTimeString())
      console.log(this.due_date.nativeElement.value);
      // element.notify = true;
    }
  }
}
</code>```

Body:
I have an html code

          Due date:

            <input type="date" class="form-control" #due_date>

and my typscript code is like this but it never enters the condition, so what should I do?

if(element.due_date <= new Date()){
    //if(element.due_time <= new Date().toLocaleTimeString())
    console.log(element);
    element.notify = true;
  }

Body:
According to the template, your component code should be like

export class SomeComponent {
  @ViewChild('due_date') due_date: ElementRef;

  someMethod() {
    const inputDate = new Date(this.due_date.nativeElement.value);
    if (inputDate <= new Date()) {
      //if(element.due_time <= new Date().toLocaleTimeString())
      console.log(this.due_date.nativeElement.value);
      // element.notify = true;
    }
  }
}


问:
How to build a portable class library without Visual Studio?
I'm trying to build a portable library project on a TFS server and I've got the following error:

"The imported project "C:\Program Files (x86)\MSBuild\Microsoft\Portable\v4.6\Microsoft.Portable.CSharp.targets" was not found. Confirm that the path in the  declaration is correct, and that the file exists on disk"

It's true, I don't have a Portable directory in MSBuild/Microsoft on the server. I have it on my developer computer, so I guess if I install Visual Studio it will work but I don't want to. I've installed the build tools on the server, with all the available UWP features but I still don't have this Portable directory.

答: Just copy C:\Program Files (x86)\MSBuild\Microsoft\Portable folder to your build server. It's pity that build tools 2017 don't create these files automatically.</p>


问:
Session ID cannot be deleted
I am trying to create a login system. At the moment everything seem to be working as expected except I am not able to clear my session ID,

why do session_unset() and session_destroy don't seem to have any effect ?

UPDATE: solved below

INDEX.PHP

```<code>  session_start();

  if (array_key_exists('id', $_COOKIE) && $_COOKIE ['id']) {
  $_SESSION['id'] = $_COOKIE['id'];

 print("SESSION ID");
 print("<br>");
 print_r($_SESSION);
 print("<br>");
 print("COOKIE");
 print("<br>");
 print_r($_COOKIE);

  }
</code>```

// SET SESSION

```<code>function setSession($setSessionData) {

    $_SESSION['id'] = $setSessionData[0];

     if ($setSessionData[1] == 'yes') {
       setcookie('id', $setSessionData[0], time() + 60*60*24*365, '/'     );
     }
  };
</code>```

// CLEAR SESSION

```<code>function unSetSession() {

  session_unset();
  setcookie("id", "", time() - 60*60*24*365, '/');
  session_destroy();

}
</code>```

答:
SOLVED:

Had to initialise the session in my function called via Ajax; so the logout function is like so:

```<code>function unSetSession() {

  session_start();
  $_SESSION = array();
  setcookie("id", "", time() - 60*60*24*365, '/');
  session_destroy();

}
</code>```

Title: Session ID cannot be deleted

Body:
I am trying to create a login system. At the moment everything seem to be working as expected except I am not able to clear my session ID,

why do session_unset() and session_destroy don't seem to have any effect ?

UPDATE: solved below

INDEX.PHP

  session_start();

  if (array_key_exists('id', $_COOKIE) && $_COOKIE ['id']) {
  $_SESSION['id'] = $_COOKIE['id'];

 print("SESSION ID");
 print("
");
 print_r($_SESSION);
 print("
");
 print("COOKIE");
 print("
");
 print_r($_COOKIE);

  }

// SET SESSION

function setSession($setSessionData) {

    $_SESSION['id'] = $setSessionData[0];

     if ($setSessionData[1] == 'yes') {
       setcookie('id', $setSessionData[0], time() + 60*60*24*365, '/'     );
     }
  };

// CLEAR SESSION

function unSetSession() {

  session_unset();
  setcookie("id", "", time() - 60*60*24*365, '/');
  session_destroy();

}

Body:
SOLVED:

Had to initialise the session in my function called via Ajax; so the logout function is like so:

function unSetSession() {

  session_start();
  $_SESSION = array();
  setcookie("id", "", time() - 60*60*24*365, '/');
  session_destroy();

}


问:
How can I extract the Author of the book using Jsoup?
I´m trying to extract the authors of the books at this Amazon page using Jsoup: Link

I have been able to scrape the tittles:

```<code>public static final String URL_LITERATURE_FICTION="https://www.amazon.com/b/ref=s9_acss_bw_en_BGG15eve_d_1_6_w?_encoding=UTF8&node=17&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=merchandised-search-top-3&pf_rd_r=8Z2ERCN30FREH3ZD6AHC&pf_rd_r=8Z2ERCN30FREH3ZD6AHC&pf_rd_t=101&pf_rd_p=c0b03f4d-c947-45e3-9b66-2bd220509181&pf_rd_p=c0b03f4d-c947-45e3-9b66-2bd220509181&pf_rd_i=283155";
Document doc = Jsoup.connect(URL_LITERATURE_FICTION).userAgent("Mozilla").get();
Elements link = doc.select(".s-result-list-parent-container > ul > li .s-access-title");
</code>```

But I don´t know how to extract the authors. Any ideas?
Thanks in advance.

答:
Following the link you provide in the question, a valid DOM selector for your scraping needs is:</p>

```<code>.a-fixed-left-grid .a-fixed-left-grid-inner .a-row.a-spacing-none .a-size-small.a-color-secondary .a-link-normal.a-text-normal
</code>```

Body:
I´m trying to extract the authors of the books at this Amazon page using Jsoup: Link

I have been able to scrape the tittles:

public static final String URL_LITERATURE_FICTION="https://www.amazon.com/b/ref=s9_acss_bw_en_BGG15eve_d_1_6_w?_encoding=UTF8&node=17&pf_rd_m=ATVPDKIKX0DER&pf_rd_s=merchandised-search-top-3&pf_rd_r=8Z2ERCN30FREH3ZD6AHC&pf_rd_r=8Z2ERCN30FREH3ZD6AHC&pf_rd_t=101&pf_rd_p=c0b03f4d-c947-45e3-9b66-2bd220509181&pf_rd_p=c0b03f4d-c947-45e3-9b66-2bd220509181&pf_rd_i=283155";
Document doc = Jsoup.connect(URL_LITERATURE_FICTION).userAgent("Mozilla").get();
Elements link = doc.select(".s-result-list-parent-container > ul > li .s-access-title");

But I don´t know how to extract the authors. Any ideas?
Thanks in advance.

Body:
Following the link you provide in the question, a valid DOM selector for your scraping needs is:

.a-fixed-left-grid .a-fixed-left-grid-inner .a-row.a-spacing-none .a-size-small.a-color-secondary .a-link-normal.a-text-normal


问:
Need with Javascript function for Select check
I tried to create a function to check on a drop-down option on select box. It requires a user to select a user name before submit. I put '0' and check if this = 0, then return false, but it didn't work.

I added a function to check radio buttons and they all worked fine. However, the select Staff doesn't work. I mean, when I click on Submit after checking all radio boxes, it get submitted anyway. How do I fix it to make it work?

Can you help me?

```<code><script language="javascript">
function validateForm(daForm) {
nCount = document.frmReport.txtCount.value;
    // check all rb radio buttons
    for (var i = 1; i < nCount; i++) {
        if (! getCheckedRadioValue(daForm["Report"+i])) {
            alert ("Please select a value for option " + i)
            return false
         }
if (UserID.options[UserID.selectedIndex].value == 0) {
                alert("Please select a user");
                return false
    }
    // add other checks here...
                alert ("Thank you!")
                window.open("Search.asp")
    return true
}
<body>
<form action="" method="post" id="newMenu" name="frmReport" onSubmit="return validateForm(this)">
    <select name="UserID">
          <option value=0>Staff name:</option>
          <option value=1>Jenny</option>
          <option value=2>David</option>
     </select>
    <input type="submit" value="Submit">
</form>
</code>```

Thank you very much!

答:
You cannot just use UserID and work on it with JavaScript. That is the name of the select element. What you need to do is to select it using JavaScript and then work with it.

```<code>var UserID = document.getElementsByName("UserID")[0];
if (UserID.options[UserID.selectedIndex].value == 0) {
                alert("Please select a staff");
                return false
    }
    // add other checks here...
                alert ("Thank you!")
    return true;
}
</code>```

<== Fiddle Me ==>

Body:
You cannot just use UserID and work on it with JavaScript. That is the name of the select element. What you need to do is to select it using JavaScript and then work with it.

var UserID = document.getElementsByName("UserID")[0];
if (UserID.options[UserID.selectedIndex].value == 0) {
                alert("Please select a staff");
                return false
    }
    // add other checks here...
                alert ("Thank you!")
    return true;
}

<== Fiddle Me ==>


问:
composer.json correct structure for multiple PHP packages
I got this composer.json to install/update packages and I know its structure isn't correct:

```<code>{
  "config": {
    "vendor-dir": "d/sdk/paypal/"
  },
  "require": {
    "paypal/rest-api-sdk-php": "*"
  },
  "config": {
    "vendor-dir": "d/sdk/push/"
  },
  "require": {
    "minishlink/web-push": "*"
  },
  "config": {
    "vendor-dir": "d/sdk/phpmailer/"
  },
  "require": {
    "phpmailer/phpmailer": "~6.0"
  }
}
</code>```

can someone please show me correct structure? All I can find is examples for one single package. Thank you in advance for your help!

答:
Have you looked at the composer docs? Setting up your composer.json is very simple, next time please read the documentation before posting a question.

```<code>{
  "config": {
    "vendor-dir": "d/sdk"
  },
  "require": {
    "phpmailer/phpmailer": "~6.0",
    "minishlink/web-push": "*",
    "paypal/rest-api-sdk-php": "*"
  }
}
</code>```

You don't need to specify a vendor-dir, as it will automatically create a vendor directory and save all your dependencies there.

Body:
I got this composer.json to install/update packages and I know its structure isn't correct:

{
  "config": {
    "vendor-dir": "d/sdk/paypal/"
  },
  "require": {
    "paypal/rest-api-sdk-php": "*"
  },
  "config": {
    "vendor-dir": "d/sdk/push/"
  },
  "require": {
    "minishlink/web-push": "*"
  },
  "config": {
    "vendor-dir": "d/sdk/phpmailer/"
  },
  "require": {
    "phpmailer/phpmailer": "~6.0"
  }
}

can someone please show me correct structure? All I can find is examples for one single package. Thank you in advance for your help!

Body:
Have you looked at the composer docs? Setting up your composer.json is very simple, next time please read the documentation before posting a question.

{
  "config": {
    "vendor-dir": "d/sdk"
  },
  "require": {
    "phpmailer/phpmailer": "~6.0",
    "minishlink/web-push": "*",
    "paypal/rest-api-sdk-php": "*"
  }
}

You don't need to specify a vendor-dir, as it will automatically create a vendor directory and save all your dependencies there.


答:
The difference is the decorator used under the hood.

For cases like this [property]="" the component ts file implements that property with the @Input decorator.

For cases like this property="" the component ts file implements that property with the @Attribute decorator.

See this example:

```<code>export class MyComponent {

    @Input() public title1: string;
    public title2: string;

    constructor(@Attribute('title2') titleAttr) {
        this.title2 = titleAttr;
    }

}
</code>```

So then, you can use it like:

```<code><my-component [title1]="'testing'" title2="testing2"></my-component>
</code>```

Another thing to have in mind and be able to decide when to use which one is the type of value you want to pass in. While the input accepts variables coming from your component context, the attribute only accepts values passed in line.

Notice in the example above that for the input I am using single quotes to pass a string in line, but it could be without the quotes and a name of a existing variable.

Title: What is the difference between [property]= and property in Angular 4 markup?

Body:
The difference is the decorator used under the hood.

For cases like this [property]="" the component ts file implements that property with the @Input decorator.

For cases like this property="" the component ts file implements that property with the @Attribute decorator.

See this example:

export class MyComponent {

    @Input() public title1: string;
    public title2: string;

    constructor(@Attribute('title2') titleAttr) {
        this.title2 = titleAttr;
    }

}

So then, you can use it like:

<my-component [title1]="'testing'" title2="testing2"></my-component>

Another thing to have in mind and be able to decide when to use which one is the type of value you want to pass in. While the input accepts variables coming from your component context, the attribute only accepts values passed in line.

Notice in the example above that for the input I am using single quotes to pass a string in line, but it could be without the quotes and a name of a existing variable.


问:
How to read HL7 file and parse it using Apache Camel, Hapi & Spring (Java config)
I'm trying to read a hl7 file which contains the following message

```<code>MSH|^~\\&|MYSENDER|MYRECEIVER|MYAPPLICATION||200612211200||QRY^A19|1234|P|2.3
QRD|200612211200|R|I|GetPatient|||1^RD|0101701234|DEM||
</code>```

using Apache camel, Hapi & Spring framework (Java config). I want to parse the above message and get segment details from it. I'm using HL7 version 2.3. Following is my RouteBuilder class;

```<code>import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
import example.springcamel.processors.Hl7MessageProcessor;

@Component
public class SimpleRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("file://E:/projects/hl7/file_to_read/input/")
            .process(new Hl7MessageProcessor())
            .end();
        }
    }
</code>```

E:/projects/hl7/file_to_read/input/ This is the location where i'm having a file named hl7_message.hl7 with above message.

Following is the Processor class;

```<code>import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import ca.uhn.hl7v2.model.Message;

public class Hl7MessageProcessor implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception {
       Message message = exchange.getIn().getBody(Message.class);
       System.out.println("Original message: " + message);
    }
}
</code>```

From above code, i'm getting the original message as null. I'm following the documentation given at this link from Apache Camel http://camel.apache.org/hl7.html

Following are the configuration files and main application:

SpringConfiguration.java

```<code>import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "example.springcamel")
public class SpringConfiguration {

}
</code>```

RoutesConfiguration.java

```<code>import org.apache.camel.spring.javaconfig.CamelConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "example.springcamel.routes")
public class RoutesConfiguration extends CamelConfiguration {

}
</code>```

MainApplication.java

```<code>import org.apache.camel.CamelContext;
import org.apache.camel.spring.SpringCamelContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import example.springcamel.configuration.SpringConfiguration;

public class MainApplication {
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws Exception {
        AbstractApplicationContext springContext = new
                AnnotationConfigApplicationContext(SpringConfiguration.class);
        CamelContext camelContext = SpringCamelContext.springCamelContext(springContext, false);
        try {
            camelContext.start();
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            camelContext.stop();
            springContext.close();
        }
    }
}
</code>```

I'm completely new to HL7, someone kindly help me on parsing the above HL7 message and getting segment details from it.

答:
I think that you are missing some steps in your route. Try to convert your file message to String first and then unmarshall it to HL7:

```<code>from("file:src/test/resources/hl7?noop=true")
    .convertBodyTo(String.class)
    .unmarshal()
    .hl7(false)
    .log("The Message body is: ${body}")
    .process(new Processor() {
        public void process(Exchange exchange) throws Exception {
            final Message message = exchange.getIn().getBody(Message.class);
            System.out.println("Original message: " + message);
        }
    })
    .to("mock:result");
</code>```

That put, I've tried to process your output but I got this error:

```<code>ca.uhn.hl7v2.HL7Exception: The HL7 version 2.3 QRD is not recognized
</code>```

I think I was missing the \r character at the end of the line. But I validate the test with this message:

```<code>MSH|^~\&|HL7ABLAB|HNA500|HNAM|HNAM|20090911132151||ADT^A01|
Q30235031T29347435X328970|A|2.3|123
EVN|A01|20090911132100|||^DRONE_PM1^DRONE_PM^^^^^^^Personnel
PID|1||1357920591||IntFace1101A^WinTask^^^^^Current||19801117|M||||||||||
10000476524^^^FIN^FIN NBR|100000451||||||0
PV1|1|Inpatient|CD:16067689^CD:16067691^CD:16067741^Uniontown Hospit^^Bed(s)
^Uniontown Hospit||||||||||||||501455^Orr^Maggi^^^^^^External ID^Personnel^^^
External
Identifier~25584^Orr^Maggi^^^^^^PERSONNEL PRIMARY
IDENTIFIER^Personnel^^^Personnel Primary Identifier|Inpatient|||||||||||||||||||
||
Uniontown Hospit||Active|||20090911132100
</code>```

The test:

```<code>@Test
public void test() throws InterruptedException {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    mock.expectedBodyReceived().body(Message.class);

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

The Result:

```<code>Original message: MSH|^~\&|HL7ABLAB|HNA500|HNAM|HNAM|20090911132151||ADT^A01|Q30235031T29347435X328970|A|2.3|123
EVN|A01|20090911132100|||^DRONE_PM1^DRONE_PM^^^^^^^Personnel
PID|1||1357920591||IntFace1101A^WinTask^^^^^Current||19801117|M||||||||||
10000476524^^^FIN^FIN NBR|100000451||||||0
PV1|1|Inpatient|CD:16067689^CD:16067691^CD:16067741^Uniontown Hospit^^Bed(s)
^Uniontown Hospit||||||||||||||501455^Orr^Maggi^^^^^^External ID^Personnel^^^
External
Identifier~25584^Orr^Maggi^^^^^^PERSONNEL PRIMARY
IDENTIFIER^Personnel^^^Personnel Primary Identifier|Inpatient|||||||||||||||||||
||
Uniontown Hospit||Active|||20090911132100
</code>```

Dependencies:

```<code><dependency>
    <groupId>ca.uhn.hapi</groupId>
    <artifactId>hapi-structures-v23</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-hl7</artifactId>
</dependency>
</code>```

You may access the complete test in this repo.

Cheers!

Body:
I'm trying to read a hl7 file which contains the following message

MSH|^~\\&|MYSENDER|MYRECEIVER|MYAPPLICATION||200612211200||QRY^A19|1234|P|2.3
QRD|200612211200|R|I|GetPatient|||1^RD|0101701234|DEM||

using Apache camel, Hapi & Spring framework (Java config). I want to parse the above message and get segment details from it. I'm using HL7 version 2.3. Following is my RouteBuilder class;

import org.apache.camel.builder.RouteBuilder;
import org.springframework.stereotype.Component;
import example.springcamel.processors.Hl7MessageProcessor;

@Component
public class SimpleRouteBuilder extends RouteBuilder {
    @Override
    public void configure() throws Exception {
        from("file://E:/projects/hl7/file_to_read/input/")
            .process(new Hl7MessageProcessor())
            .end();
        }
    }

E:/projects/hl7/file_to_read/input/ This is the location where i'm having a file named hl7_message.hl7 with above message.

Following is the Processor class;

import org.apache.camel.Exchange;
import org.apache.camel.Processor;
import ca.uhn.hl7v2.model.Message;

public class Hl7MessageProcessor implements Processor {
    @Override
    public void process(Exchange exchange) throws Exception {
       Message message = exchange.getIn().getBody(Message.class);
       System.out.println("Original message: " + message);
    }
}

From above code, i'm getting the original message as null. I'm following the documentation given at this link from Apache Camel http://camel.apache.org/hl7.html

Following are the configuration files and main application:

SpringConfiguration.java

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "example.springcamel")
public class SpringConfiguration {

}

RoutesConfiguration.java

import org.apache.camel.spring.javaconfig.CamelConfiguration;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;

@Configuration
@ComponentScan(basePackages = "example.springcamel.routes")
public class RoutesConfiguration extends CamelConfiguration {

}

MainApplication.java

import org.apache.camel.CamelContext;
import org.apache.camel.spring.SpringCamelContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.support.AbstractApplicationContext;
import example.springcamel.configuration.SpringConfiguration;

public class MainApplication {
    @SuppressWarnings("deprecation")
    public static void main(String[] args) throws Exception {
        AbstractApplicationContext springContext = new
                AnnotationConfigApplicationContext(SpringConfiguration.class);
        CamelContext camelContext = SpringCamelContext.springCamelContext(springContext, false);
        try {
            camelContext.start();
            Thread.sleep(3000);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            camelContext.stop();
            springContext.close();
        }
    }
}

I'm completely new to HL7, someone kindly help me on parsing the above HL7 message and getting segment details from it.

Body:
I think that you are missing some steps in your route. Try to convert your file message to String first and then unmarshall it to HL7:

from("file:src/test/resources/hl7?noop=true")
    .convertBodyTo(String.class)
    .unmarshal()
    .hl7(false)
    .log("The Message body is: ${body}")
    .process(new Processor() {
        public void process(Exchange exchange) throws Exception {
            final Message message = exchange.getIn().getBody(Message.class);
            System.out.println("Original message: " + message);
        }
    })
    .to("mock:result");

That put, I've tried to process your output but I got this error:

ca.uhn.hl7v2.HL7Exception: The HL7 version 2.3 QRD is not recognized

I think I was missing the \r character at the end of the line. But I validate the test with this message:

MSH|^~\&|HL7ABLAB|HNA500|HNAM|HNAM|20090911132151||ADT^A01|
Q30235031T29347435X328970|A|2.3|123
EVN|A01|20090911132100|||^DRONE_PM1^DRONE_PM^^^^^^^Personnel
PID|1||1357920591||IntFace1101A^WinTask^^^^^Current||19801117|M||||||||||
10000476524^^^FIN^FIN NBR|100000451||||||0
PV1|1|Inpatient|CD:16067689^CD:16067691^CD:16067741^Uniontown Hospit^^Bed(s)
^Uniontown Hospit||||||||||||||501455^Orr^Maggi^^^^^^External ID^Personnel^^^
External
Identifier~25584^Orr^Maggi^^^^^^PERSONNEL PRIMARY
IDENTIFIER^Personnel^^^Personnel Primary Identifier|Inpatient|||||||||||||||||||
||
Uniontown Hospit||Active|||20090911132100

The test:

@Test
public void test() throws InterruptedException {
    MockEndpoint mock = getMockEndpoint("mock:result");
    mock.expectedMessageCount(1);
    mock.expectedBodyReceived().body(Message.class);

    assertMockEndpointsSatisfied();
}

The Result:

Original message: MSH|^~\&|HL7ABLAB|HNA500|HNAM|HNAM|20090911132151||ADT^A01|Q30235031T29347435X328970|A|2.3|123
EVN|A01|20090911132100|||^DRONE_PM1^DRONE_PM^^^^^^^Personnel
PID|1||1357920591||IntFace1101A^WinTask^^^^^Current||19801117|M||||||||||
10000476524^^^FIN^FIN NBR|100000451||||||0
PV1|1|Inpatient|CD:16067689^CD:16067691^CD:16067741^Uniontown Hospit^^Bed(s)
^Uniontown Hospit||||||||||||||501455^Orr^Maggi^^^^^^External ID^Personnel^^^
External
Identifier~25584^Orr^Maggi^^^^^^PERSONNEL PRIMARY
IDENTIFIER^Personnel^^^Personnel Primary Identifier|Inpatient|||||||||||||||||||
||
Uniontown Hospit||Active|||20090911132100

Dependencies:

<dependency>
    <groupId>ca.uhn.hapi</groupId>
    <artifactId>hapi-structures-v23</artifactId>
</dependency>
<dependency>
    <groupId>org.apache.camel</groupId>
    <artifactId>camel-hl7</artifactId>
</dependency>

You may access the complete test in this repo.

Cheers!