问:
How to select option in drop down using Capybara
I'm trying to select an item from a drop down menu using Capybara (2.1.0).

I want to select by number (meaning select the second, third, etc option).

I've Googled like crazy trying all sorts of things but no luck.

I was able to select it by using the value:

```<code> find("option[value='4c430d62-f1ba-474f-8e8a-4452c55ea0a8']").click
</code>```

But I don't want to use that method b/c the value is something that will change and that will make my test brittle.

The HTML for the drop down is:

```<code><td class="value">
    <select name="organizationSelect" id="organizationSelect" class="required">
     <option value="NULL">Choose...</option>
     <option value="4c430d62-f1ba-474f-8e8a-4452c55ea0a8"> Institution1</option>
     <option value="e1a4efa7-352d-410a-957e-35c8a3b92944"> Institution / test</option>
    </select>
</td>
</code>```

I also tried this:

```<code>  option = find(:xpath, "//*[@id='organizationSelect']/option[2]").text
  select(option, :from => organizationSelect)
</code>```

But it results in this error:

```<code>Ambiguous match, found 2 elements matching option "Institution" (Capybara::Ambiguous)
</code>```

So how can I select the first, second, third, etc option from the drop down (using Capybara) ?

答:
another option is to add a method like this</p>

```<code>  def select_option(css_selector, value)
    find(:css, css_selector).find(:option, value).select_option
  end
</code>```

Body:
I'm trying to select an item from a drop down menu using Capybara (2.1.0).

I want to select by number (meaning select the second, third, etc option).

I've Googled like crazy trying all sorts of things but no luck.

I was able to select it by using the value:

 find("option[value='4c430d62-f1ba-474f-8e8a-4452c55ea0a8']").click

But I don't want to use that method b/c the value is something that will change and that will make my test brittle.

The HTML for the drop down is:

    <select name="organizationSelect" id="organizationSelect" class="required">
     <option value="NULL">Choose...</option>
     <option value="4c430d62-f1ba-474f-8e8a-4452c55ea0a8"> Institution1</option>
     <option value="e1a4efa7-352d-410a-957e-35c8a3b92944"> Institution / test</option>
    </select>

I also tried this:

  option = find(:xpath, "//*[@id='organizationSelect']/option[2]").text
  select(option, :from => organizationSelect)

But it results in this error:

Ambiguous match, found 2 elements matching option "Institution" (Capybara::Ambiguous)

So how can I select the first, second, third, etc option from the drop down (using Capybara) ?

Body:
another option is to add a method like this

  def select_option(css_selector, value)
    find(:css, css_selector).find(:option, value).select_option
  end


来源: stackexchange

问:
Force field/tag when inserting data on influxdb
I am just starting with influxdb as a time series database and i was trying to create some measurements, however it seems like influx automatically determines which fields of the measurements are tags and which are fields, is there any way to force one or another at insertion time (first insertion of a measurement)?? or any other way whatsoever?</p>

答:
No, InfluxDB won't automatically determine which are fields and which are tags. Your "insert string" structure "helps InfluxDB in determining which are tags and which are fields.

For example:

```<code>cpu_load_short,host=server01,region=us-west value=0.64 1434055562000000000
</code>```

In this string, "cpu_load_short" is the measurment name (observe that there is no = sign to form a key/value pair), followed by semi colon.

```<code>host=server01,region=us-west    are tags (in key value formats)
</code>```

Rignt after tags you can see that there is space, which tells following the space are "Fields".

You may refer this documentation for more information.

ContentLicense: CC BY-SA 3.0

Body:
No, InfluxDB won't automatically determine which are fields and which are tags. Your "insert string" structure "helps InfluxDB in determining which are tags and which are fields.

For example:

cpu_load_short,host=server01,region=us-west value=0.64 1434055562000000000

In this string, "cpu_load_short" is the measurment name (observe that there is no = sign to form a key/value pair), followed by semi colon.

host=server01,region=us-west    are tags (in key value formats)

Rignt after tags you can see that there is space, which tells following the space are "Fields".

You may refer this documentation for more information.


问:
How do I allow all Cross Domain Requests on my Django Rest Framework project?
I have tried the following things:

Installed Djagno Cors Headers and added the following code to my settings:

CORS_ORIGIN_ALLOW_ALL = True

I have also added csrf_exempt handlers to all my API views.

Yet, nothing works and I still keep on getting CSRF errors. Any help? What am exactly doing wrong. The exact same code was working on my local server, yet now its broken :/

Even GET requests don't work, which is just odd.

Thanks.

答:
@csrf_exempt just use for POST method.

you can remove @csrf_exempt which above GET api.


问:
file_get_html error, not working
I'm using Simple HTML Dom to try scrape a HTML table.
I follow their instructions and have looked at many other code examples, but the file_get_html just doesn't seem to work.

Here is my code:

```<code><?php

// Simple HTML Dom Parser
include('simple_html_dom.php');

//$worlds = ["Amera", "Antica", "Astera", "Aurera", "Aurora", "Bellona", "Belobra", "Beneva", "Calmera", "Calva", "Calvera", "Candia", "Celesta", "Chrona", "Danera", "Dolera", "Efidia", "Eldera", "Ferobra", "Fidera", "Fortera", "Garnera", "Guardia", "Harmonia", "Honera", "Hydera", "Inferna", "Iona", "Irmada", "Julera", "Justera", "Kenora", "Kronera", "Laudera", "Luminera", "Magera", "Menera", "Morta", "Mortera", "Neptera", "Nerana", "Nika", "Olympa", "Osera", "Pacera", "Premia", "Pythera", "Quilia", "Refugia", "Rowana", "Secura", "Serdebra", "Shivera", "Silvera", "Solera", "Tavara", "Thera", "Umera", "Unitera", "Veludera", "Verlana", "Xantera", "Xylana", "Yanara", "Zanera", "Zeluna"];

//foreach ($worlds as $world) {
  // All HTML from the online list
  $html = file_get_html('https://secure.tibia.com/community/?subtopic=worlds&world=Antica');

  // Search for the online list table content
  foreach ($html->find('tr[class=Table2]') as $row) {
    $name = $row->find('td', 0)->plaintext;
    $level = $row->find('td', 1)->plaintext;
    $vocation = $row->find('td', 2)->plaintext;

    echo $name . ' | ' . $level . ' | ' . $vocation . '<br>';
  }
//}

?>
</code>```

And I get these errors:

```<code>Warning: file_get_contents(): stream does not support seeking in D:\xampp\htdocs\simple_html_dom.php on line 76

Warning: file_get_contents(): Failed to seek to position -1 in the stream in D:\xampp\htdocs\simple_html_dom.php on line 76

Fatal error: Uncaught Error: Call to a member function find() on boolean in D:\xampp\htdocs\index.php:13 Stack trace: #0 {main} thrown in D:\xampp\htdocs\index.php on line 13
</code>```

What am I doing wrong?
The table I am trying to scrape is the "Players Online" table on:
https://secure.tibia.com/community/?subtopic=worlds&world=Antica

答:
This is a simple_html_dom library problem with the latest versions of PHP.
To correct it, simply change "$offset = -1," to "$offset = 0," in the parameters of the "file_get_html" function in the "simple_html_dom.php" file.

Title: file_get_html error, not working

Body:
I'm using Simple HTML Dom to try scrape a HTML table.
I follow their instructions and have looked at many other code examples, but the file_get_html just doesn't seem to work.

Here is my code:

<?php

// Simple HTML Dom Parser
include('simple_html_dom.php');

//$worlds = ["Amera", "Antica", "Astera", "Aurera", "Aurora", "Bellona", "Belobra", "Beneva", "Calmera", "Calva", "Calvera", "Candia", "Celesta", "Chrona", "Danera", "Dolera", "Efidia", "Eldera", "Ferobra", "Fidera", "Fortera", "Garnera", "Guardia", "Harmonia", "Honera", "Hydera", "Inferna", "Iona", "Irmada", "Julera", "Justera", "Kenora", "Kronera", "Laudera", "Luminera", "Magera", "Menera", "Morta", "Mortera", "Neptera", "Nerana", "Nika", "Olympa", "Osera", "Pacera", "Premia", "Pythera", "Quilia", "Refugia", "Rowana", "Secura", "Serdebra", "Shivera", "Silvera", "Solera", "Tavara", "Thera", "Umera", "Unitera", "Veludera", "Verlana", "Xantera", "Xylana", "Yanara", "Zanera", "Zeluna"];

//foreach ($worlds as $world) {
  // All HTML from the online list
  $html = file_get_html('https://secure.tibia.com/community/?subtopic=worlds&world=Antica');

  // Search for the online list table content
  foreach ($html->find('tr[class=Table2]') as $row) {
    $name = $row->find('td', 0)->plaintext;
    $level = $row->find('td', 1)->plaintext;
    $vocation = $row->find('td', 2)->plaintext;

    echo $name . ' | ' . $level . ' | ' . $vocation . '
';
  }
//}

?>

And I get these errors:

Warning: file_get_contents(): stream does not support seeking in D:\xampp\htdocs\simple_html_dom.php on line 76

Warning: file_get_contents(): Failed to seek to position -1 in the stream in D:\xampp\htdocs\simple_html_dom.php on line 76

Fatal error: Uncaught Error: Call to a member function find() on boolean in D:\xampp\htdocs\index.php:13 Stack trace: #0 {main} thrown in D:\xampp\htdocs\index.php on line 13

What am I doing wrong?
The table I am trying to scrape is the "Players Online" table on:
https://secure.tibia.com/community/?subtopic=worlds&world=Antica


问:
Regex: how to stop match on certain words that cannot exists
The title is so confusing, I admit it - if you want to change it you are welcome.

I'm working on PHP and preg_match function.

The problem is this string (just an example)

```<code>ON DELETE SET NULL ON UPDATE CASCADE
</code>```

ON DELETE CASCADE ON UPDATE CASCADE (another example..)

i need to find ON DELETE and ON UPDATE values, but they can't be there both.

So sometimes i have this:

```<code>ON DELETE something
</code>```

and other times:

```<code>ON UPDATE something
</code>```

and other times both.

So, this regex doesn't cover all possibilities:

```<code>/ON DELETE (.+) ON UPDATE (.+)/
</code>```

If i put

/ON DELETE (.+)( ON UPDATE (.*))?/ -- to cover the case in which there isn't ON UPDATE

if ON UPDATE is present, first group results in "SET NULL ON UPDATE CASCADE".

How can i do that?

答:
psuedo code to match occurance of on delete and on update but not both</p>

```<code>function valid(str)
{
 matchDelete=regex(str, 'ON DELETE'); //true for match
 matchUpdate=regex(str, 'ON UPDATE'); //true for match

 if(   (matchDelete || matchUpdate ) && !(matchDelete && matchUpdate)  )
 {
   valid match
 }
}
</code>```

ContentLicense: CC BY-SA 2.5

Body:
The title is so confusing, I admit it - if you want to change it you are welcome.

I'm working on PHP and preg_match function.

The problem is this string (just an example)

ON DELETE SET NULL ON UPDATE CASCADE

ON DELETE CASCADE ON UPDATE CASCADE (another example..)

i need to find ON DELETE and ON UPDATE values, but they can't be there both.

So sometimes i have this:

ON DELETE something

and other times:

ON UPDATE something

and other times both.

So, this regex doesn't cover all possibilities:

/ON DELETE (.+) ON UPDATE (.+)/

If i put

/ON DELETE (.+)( ON UPDATE (.*))?/ -- to cover the case in which there isn't ON UPDATE

if ON UPDATE is present, first group results in "SET NULL ON UPDATE CASCADE".

How can i do that?

Body:
psuedo code to match occurance of on delete and on update but not both

function valid(str)
{
 matchDelete=regex(str, 'ON DELETE'); //true for match
 matchUpdate=regex(str, 'ON UPDATE'); //true for match

 if(   (matchDelete || matchUpdate ) && !(matchDelete && matchUpdate)  )
 {
   valid match
 }
}


问:
Javascript If Button is pressed - do stuff
I am looking for something like:

```<code>if (..button1 is pressed..){
some function
}

if (...button2 is pressed...){
some other function
}
</code>```

But all of those need to be a part of some completely different function.

Something like:

```<code>$(document).ready(function () {
$(".Test").hover(function () {
  if (...Button is pressed...) {
 $('.dropdown').slideToggle('medium');
  }
});
});
</code>```

答:
You may use target to find clicked button id and store that id on global variable to use in hover.

```<code>   var id ='';
   $("button").click(function(e){
        id= e.target.id;
    });
</code>```

Later on hover you can use that global variable.

```<code>$(".Test").hover(function () {
  if (id=='matchYourID') {
    $('.dropdown').slideToggle('medium');
  }
});
</code>```

Body:
I am looking for something like:

if (..button1 is pressed..){
some function
}

if (...button2 is pressed...){
some other function
}

But all of those need to be a part of some completely different function.

Something like:

$(document).ready(function () {
$(".Test").hover(function () {
  if (...Button is pressed...) {
 $('.dropdown').slideToggle('medium');
  }
});
});

Body:
You may use target to find clicked button id and store that id on global variable to use in hover.

   var id ='';
   $("button").click(function(e){
        id= e.target.id;
    });

Later on hover you can use that global variable.

$(".Test").hover(function () {
  if (id=='matchYourID') {
    $('.dropdown').slideToggle('medium');
  }
});


问:
using index match with sum if
I need to link up a sumif() with an index match (i'm guessing here) but don't really know where to start.

Basically i a table with different classes of pets, their species and quantity. there are 3 stores. I need an output where i can get the quantity of each species from each store dynamically.

data table:

```<code>"A1"                Pet Stores
Species  Class      a   b   c
cat      Fluffy1    1   0   0
cat      Fluffy2    3   0   0
cat      Fluffy3    5   7   1
cat      Fluffy4    6   0   7
dog      Barky1     7   6   9
dog      Barky2     1   3   9
dog      Barky3     0   2   8
dog      Barky4     0   2   3
fish     Swimmy1    0   0   0
fish     Swimmy2    1   3   0
fish     Swimmy3    0   2   3
fish     Swimmy4    0   0   0
</code>```

Output:

```<code>Pet Store   a   <--change this
cat         15  <--output
dog         8   <--output
fish        1   <--output
</code>```

right now my formula for "cat" is =SUMIF($A$3:$A$14,A17,$C$3:$C$14). however, it only looks down the 1 column that i've set. how do i change it such that it searches for the "Pet Store" and returns sum of the respective column?

答:
How about this:

Formula in cell H3 copied down is

```<code>=SUMIF($A$2:$A$13,G3,INDEX($C$2:$E$13,,MATCH(H$2,$C$1:$E$1,0)))
</code>```

Title: using index match with sum if

Body:
I need to link up a sumif() with an index match (i'm guessing here) but don't really know where to start.

Basically i a table with different classes of pets, their species and quantity. there are 3 stores. I need an output where i can get the quantity of each species from each store dynamically.

data table:

"A1"                Pet Stores
Species  Class      a   b   c
cat      Fluffy1    1   0   0
cat      Fluffy2    3   0   0
cat      Fluffy3    5   7   1
cat      Fluffy4    6   0   7
dog      Barky1     7   6   9
dog      Barky2     1   3   9
dog      Barky3     0   2   8
dog      Barky4     0   2   3
fish     Swimmy1    0   0   0
fish     Swimmy2    1   3   0
fish     Swimmy3    0   2   3
fish     Swimmy4    0   0   0

Output:

Pet Store   a   <--change this
cat         15  <--output
dog         8   <--output
fish        1   <--output

right now my formula for "cat" is =SUMIF($A$3:$A$14,A17,$C$3:$C$14). however, it only looks down the 1 column that i've set. how do i change it such that it searches for the "Pet Store" and returns sum of the respective column?

Body:
How about this:

Formula in cell H3 copied down is

=SUMIF($A$2:$A$13,G3,INDEX($C$2:$E$13,,MATCH(H$2,$C$1:$E$1,0)))


问:
Insert PHP variabel in SQL queries Codeigniter
I'm using Codeigniter to use some queries and this is my code so far. is my code correct?

```<code>$this->db->select("(SELECT SUM(grand_total) FROM Sales_order WHERE member = '2') - (SELECT SUM(amount) FROM payment WHERE member_id = '2')  AS total_sales");
</code>```

and how to change number 2 with this variable

  $this->session->userdata('ID')

答:
You can use Query Bindings like below to escape it automatically:</p>

```<code>$sql = "(SELECT SUM(grand_total) FROM Sales_order WHERE member = '?') - (SELECT SUM(amount) FROM payment WHERE member_id = '?')  AS total_sales";
$this->db->query($sql, array($this->session->userdata('ID'),$this->session->userdata('ID')));
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I'm using Codeigniter to use some queries and this is my code so far. is my code correct?

$this->db->select("(SELECT SUM(grand_total) FROM Sales_order WHERE member = '2') - (SELECT SUM(amount) FROM payment WHERE member_id = '2')  AS total_sales");

and how to change number 2 with this variable

  $this->session->userdata('ID')

Body:
You can use Query Bindings like below to escape it automatically:

$sql = "(SELECT SUM(grand_total) FROM Sales_order WHERE member = '?') - (SELECT SUM(amount) FROM payment WHERE member_id = '?')  AS total_sales";
$this->db->query($sql, array($this->session->userdata('ID'),$this->session->userdata('ID')));


问:
AWS CloudFront with Signed URL: 403 Access Denied
I'm configuring an environment with a Amazon S3 Bucket for storage of media files and Amazon CloudFront for restricted distribution purposes.

The access to those media files needs to be private and should be done via a signed URL. So I created the S3 Bucket on South America (São Paulo) region and uploaded some test files. Then I created a CloudFront Distribution with that previous bucket as Origin and it's Bucket Access is restricted. I created a new OAI (Origin Access Identity) and also selected the option Yes, Update Bucket Policy so that it auto-configures the S3 Bucket Policies.
I'm only using the default Behavior and it's configured with HTTP and HTTPS viewer protocol policy and GET, HEAD allowed methods. Restrict Viewer Access (Use Signed URLs or Signed Cookies) is set and the Trusted Signer is set to Self.

Here's some images to clarify the setup:

S3 Bucket Policy

Distribution's Origin

Distribution's Behavior

I'm getting a HTTP 403 while trying to access the signed URL generated with either awscli or cfsign.pl

```<code><Error>
    <Code>AccessDenied</Code>
    <Message>Access denied</Message>
</Error>
</code>```

Is there something missing that I don't know? It looks like I made everything the docs said to do.

答: I also encountered the same issue. Probably, we have to re-generate Clouf Front key-pair.</p>

Body:
I'm configuring an environment with a Amazon S3 Bucket for storage of media files and Amazon CloudFront for restricted distribution purposes.

The access to those media files needs to be private and should be done via a signed URL. So I created the S3 Bucket on South America (São Paulo) region and uploaded some test files. Then I created a CloudFront Distribution with that previous bucket as Origin and it's Bucket Access is restricted. I created a new OAI (Origin Access Identity) and also selected the option Yes, Update Bucket Policy so that it auto-configures the S3 Bucket Policies.
I'm only using the default Behavior and it's configured with HTTP and HTTPS viewer protocol policy and GET, HEAD allowed methods. Restrict Viewer Access (Use Signed URLs or Signed Cookies) is set and the Trusted Signer is set to Self.

Here's some images to clarify the setup:

S3 Bucket Policy

Distribution's Origin

Distribution's Behavior

I'm getting a HTTP 403 while trying to access the signed URL generated with either awscli or cfsign.pl

<Error>
    AccessDenied
    <Message>Access denied</Message>
</Error>

Is there something missing that I don't know? It looks like I made everything the docs said to do.


问:
VBA for loop takes too long
Just starting out on VBA, and my code is painfully slow. I have a number of workbooks on a network drive, each with several worksheets. I am trying to fetch data from a number of non-contiguous ranges in each worksheet to a pre-designed worksheet, using the following code:

```<code>Private Function GetValue(path, file, sheet, ref)
    'retrieve value
    '// code
    GetValue = ExecuteExcel4Macro(arg)
End Function

Sub UpdateModel1()

    sheet = "blah blah"
    Application.ScreenUpdating = False

    'Outputs
    destRow = 31            'destination row
    destCol = 6             'destination column
    srcRow = 50             'source row

    For C = 23 To 31        'loop through source columns
        ref = Cells(srcRow, C).Address
        Cells(destRow, destCol) = GetValue(path, file, sheet, ref)
        destCol = destCol + 1
    Next C

    Application.ScreenUpdating = True

End Sub
</code>```

However, using a nested for loop in the sub procedure takes way too long. Any suggestions on how to improve this code? PS: this is an amateur's code, and I am just looking for something that does the work decently.

答:
Here is a working example of what you are trying to do:

```<code>Sub TestGetSheetValue()
    MsgBox GetSheetValue("N:\Tax Documents\", "Tax Stuff.xlsx", "Sheet1", "R1C3")
End Sub

Function GetSheetValue(strPath As String, strFile As String, strSheet As String, strCellRef As String)
    GetSheetValue = ExecuteExcel4Macro("'" & strPath & "[" & strFile & "]" & strSheet & "'!" & strCellRef)
End Function
</code>```

Obviously change what you pass into the function for your needs, note the address is R1C1 format.

The strSheet is the sheet name, not the sheet index.

Make sure you have a trailing \ on the path

Finally, try not to use names like file, path and sheet for variable names.

Title: VBA for loop takes too long

Body:
Just starting out on VBA, and my code is painfully slow. I have a number of workbooks on a network drive, each with several worksheets. I am trying to fetch data from a number of non-contiguous ranges in each worksheet to a pre-designed worksheet, using the following code:

Private Function GetValue(path, file, sheet, ref)
    'retrieve value
    '// code
    GetValue = ExecuteExcel4Macro(arg)
End Function

Sub UpdateModel1()

    sheet = "blah blah"
    Application.ScreenUpdating = False

    'Outputs
    destRow = 31            'destination row
    destCol = 6             'destination column
    srcRow = 50             'source row

    For C = 23 To 31        'loop through source columns
        ref = Cells(srcRow, C).Address
        Cells(destRow, destCol) = GetValue(path, file, sheet, ref)
        destCol = destCol + 1
    Next C

    Application.ScreenUpdating = True

End Sub

However, using a nested for loop in the sub procedure takes way too long. Any suggestions on how to improve this code? PS: this is an amateur's code, and I am just looking for something that does the work decently.

Body:
Here is a working example of what you are trying to do:

Sub TestGetSheetValue()
    MsgBox GetSheetValue("N:\Tax Documents\", "Tax Stuff.xlsx", "Sheet1", "R1C3")
End Sub

Function GetSheetValue(strPath As String, strFile As String, strSheet As String, strCellRef As String)
    GetSheetValue = ExecuteExcel4Macro("'" & strPath & "[" & strFile & "]" & strSheet & "'!" & strCellRef)
End Function

Obviously change what you pass into the function for your needs, note the address is R1C1 format.

The strSheet is the sheet name, not the sheet index.

Make sure you have a trailing \ on the path

Finally, try not to use names like file, path and sheet for variable names.


问:
Protractor throws error an X Display is required for headless chrome 59
While running ng e2e I get the following

```<code>✓ should display message saying sign up
✗ should be able to sign up with a valid user
  - Failed: unknown error: an X display is required for keycode conversions, consider using Xvfb
    (Session info: headless chrome=59.0.3071.71)
    (Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 3.13.0-48-generic x86_64)
    (Session info: headless chrome=59.0.3071.71)
    (Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 3.13.0-48-generic x86_64)
</code>```

Configuration:

```<code>const { SpecReporter } = require('jasmine-spec-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './e2e/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
      'args': ['show-fps-counter=true', '--no-sandbox', '--headless', '--disable-gpu']
    }
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  beforeLaunch: function() {
    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });
  },
  onPrepare() {
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};
</code>```

From the following link, it seems we do not need Xvfb, so what would be the right configuration?

For now followed configuration from here:
 Using Headless Chrome.

答:
Above issue was due to sendkeys.
As of now there is no solution with just headless browser and sendkeys, refer to Issue.

It works with xvfb for now.

Provision xvfb

sudo apt-get install -y xvfb

sudo apt-get install -y  xfonts-100dpi
xfonts-75dpi xfonts-cyrillic  dbus-x11

xvfb-run -a  -s "-screen 0
2920x2580x24" ng e2e

Body:
While running ng e2e I get the following

✓ should display message saying sign up
✗ should be able to sign up with a valid user
  - Failed: unknown error: an X display is required for keycode conversions, consider using Xvfb
    (Session info: headless chrome=59.0.3071.71)
    (Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 3.13.0-48-generic x86_64)
    (Session info: headless chrome=59.0.3071.71)
    (Driver info: chromedriver=2.29.461571 (8a88bbe0775e2a23afda0ceaf2ef7ee74e822cc5),platform=Linux 3.13.0-48-generic x86_64)

Configuration:

const { SpecReporter } = require('jasmine-spec-reporter');

exports.config = {
  allScriptsTimeout: 11000,
  specs: [
    './e2e/**/*.e2e-spec.ts'
  ],
  capabilities: {
    'browserName': 'chrome',
    'chromeOptions': {
      'args': ['show-fps-counter=true', '--no-sandbox', '--headless', '--disable-gpu']
    }
  },
  directConnect: true,
  baseUrl: 'http://localhost:4200/',
  framework: 'jasmine',
  jasmineNodeOpts: {
    showColors: true,
    defaultTimeoutInterval: 30000,
    print: function() {}
  },
  beforeLaunch: function() {
    require('ts-node').register({
      project: 'e2e/tsconfig.e2e.json'
    });
  },
  onPrepare() {
    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));
  }
};

From the following link, it seems we do not need Xvfb, so what would be the right configuration?

For now followed configuration from here:
 Using Headless Chrome.


问:
Angular $stateProvider - match no route or 'blank' route
I'm using $stateProvider with angular like this:

```<code>var stateConfig = function ($stateProvider, $urlRouterProvider) {

    // Redirect if no route
    $urlRouterProvider.otherwise("");

    $stateProvider.state("home.myState", {
        url: "",
        templateUrl: "/mytemplate.html",
        controller: "MyController"
    });
};
</code>```

... and this works fine for a .NET MVC url like this (with no angular route defined):

```<code>http://hostname/MvcController/id
</code>```

The issue is that sometimes the URL will be in this form:

```<code>http://hostname/MvcController/id#/
</code>```

... and I can change my state definition like this:

```<code>    $stateProvider.state("home.myState", {
        url: "/",
        ...
</code>```

, which matches the new URL, but no longer matches the original URL (without the trailing '#/'). How should I define the state, or configure my routing, so that it matches a URL which can either have a 'blank' route (i.e. with a trailing '#/'), or no route defined at all (no trailing '#/')

答:
I needed to change to this, which sets the route to have a '/' when no route is provided (and the state then matches on a route suffixed with the '/')</p>

```<code>$urlRouterProvider.otherwise("/");

$stateProvider.state("home.myState", {
    url: "/",
    ...
</code>```

Body:
I'm using $stateProvider with angular like this:

var stateConfig = function ($stateProvider, $urlRouterProvider) {

    // Redirect if no route
    $urlRouterProvider.otherwise("");

    $stateProvider.state("home.myState", {
        url: "",
        templateUrl: "/mytemplate.html",
        controller: "MyController"
    });
};

... and this works fine for a .NET MVC url like this (with no angular route defined):

http://hostname/MvcController/id

The issue is that sometimes the URL will be in this form:

http://hostname/MvcController/id#/

... and I can change my state definition like this:

    $stateProvider.state("home.myState", {
        url: "/",
        ...

, which matches the new URL, but no longer matches the original URL (without the trailing '#/'). How should I define the state, or configure my routing, so that it matches a URL which can either have a 'blank' route (i.e. with a trailing '#/'), or no route defined at all (no trailing '#/')

Body:
I needed to change to this, which sets the route to have a '/' when no route is provided (and the state then matches on a route suffixed with the '/')

$urlRouterProvider.otherwise("/");

$stateProvider.state("home.myState", {
    url: "/",
    ...


问:
Value substitution in Ansible template
I am working on an Ansible playbook, where in a template I need to substitute a variable which is a list of dictionaries.

The task file is as follows:

```<code>vars:
locations:
  - context: "/rest"
    server: "http://locahost:8080;"
  - context: "/api"
    server: "http://localhost:9090;"
tasks:
- name: testing the template
  template:
    src: ./conf.j2
    dest: /tmp/test.conf
  with_items: '{{ locations }}'
</code>```

I need to substitute the locations in the template. So the template is as follows:

```<code>{% for location in item %}
     location {{ location['context'] }}
     proxy_pass {{ location['server'] }}
{% endfor %}
</code>```

I was expecting an output as follows:

```<code>location /rest
proxy_pass http://localhost:8080

location /api
proxy_pass htpp://localhost:9090
</code>```

But i am having hard time in getting the substitution correct, can anybody help in pointing out where am I making the mistake.

The error I am getting is

```<code>failed: [127.0.0.1] (item={u'context': u'/rest', u'server':
u'http://localhost:9090;'}) => {"failed": true, "item": {"context":
"/rest", "server": "http://localhost:8080;"}, "msg":
"AnsibleUndefinedVariable: 'context' is undefined"}
failed: [127.0.0.1] (item={u'context': u'/api', u'server':
u'http://locahost:8080;'}) => {"failed": true, "item": {"context":
"/api", "server": "http://locahost:9090;"}, "msg":
"AnsibleUndefinedVariable: 'context' is undefined"}
</code>```

答:
At this moment, because of with_items, you are passing the individual elements of the locations list, so in the first iteration, item becomes the following dictionary:

```<code>context: "/rest"
server: "http://locahost:8080;"
</code>```

Then in the template you try to iterate this dictionary as a list (with for).

You need to decide if you want to loop outside of the template (create multiple files), or inside (create a single file).

Your case looks like the latter, so you don't need to use with_items:

```<code>- name: testing the template
  template:
    src: ./conf.j2
    dest: /tmp/test.conf
</code>```

With the template:

```<code>{% for location in locations %}
  location {{ location['context'] }}
  proxy_pass {{ location['server'] }}
{% endfor %}
</code>```

You ignored my question about the missing semicolon at the end of your expected output, so deal with it yourself.

Title: Value substitution in Ansible template

Body:
I am working on an Ansible playbook, where in a template I need to substitute a variable which is a list of dictionaries.

The task file is as follows:

vars:
locations:
  - context: "/rest"
    server: "http://locahost:8080;"
  - context: "/api"
    server: "http://localhost:9090;"
tasks:
- name: testing the template
  template:
    src: ./conf.j2
    dest: /tmp/test.conf
  with_items: '{{ locations }}'

I need to substitute the locations in the template. So the template is as follows:

{% for location in item %}
     location {{ location['context'] }}
     proxy_pass {{ location['server'] }}
{% endfor %}

I was expecting an output as follows:

location /rest
proxy_pass http://localhost:8080

location /api
proxy_pass htpp://localhost:9090

But i am having hard time in getting the substitution correct, can anybody help in pointing out where am I making the mistake.

The error I am getting is

failed: [127.0.0.1] (item={u'context': u'/rest', u'server':
u'http://localhost:9090;'}) => {"failed": true, "item": {"context":
"/rest", "server": "http://localhost:8080;"}, "msg":
"AnsibleUndefinedVariable: 'context' is undefined"}
failed: [127.0.0.1] (item={u'context': u'/api', u'server':
u'http://locahost:8080;'}) => {"failed": true, "item": {"context":
"/api", "server": "http://locahost:9090;"}, "msg":
"AnsibleUndefinedVariable: 'context' is undefined"}

Body:
At this moment, because of with_items, you are passing the individual elements of the locations list, so in the first iteration, item becomes the following dictionary:

context: "/rest"
server: "http://locahost:8080;"

Then in the template you try to iterate this dictionary as a list (with for).

You need to decide if you want to loop outside of the template (create multiple files), or inside (create a single file).

Your case looks like the latter, so you don't need to use with_items:

- name: testing the template
  template:
    src: ./conf.j2
    dest: /tmp/test.conf

With the template:

{% for location in locations %}
  location {{ location['context'] }}
  proxy_pass {{ location['server'] }}
{% endfor %}

You ignored my question about the missing semicolon at the end of your expected output, so deal with it yourself.


问:
libGDX as a "launcher" app
I have made a light weight java web-server serving html files and static content (made with pure java library nanohttpd), i have successfully made a javaFX launcher window that has a single button, clicking button simply runs the server in the background and opens the localhost URL in Android/PC browser (I was unsuccessful in making an IOS version using javaFX)

I am thinking of using libGDX as "launcher window" because of IOS support and access to mobile specific hardware like SMS/GPS which javaFX don't have.
I am targeting IOS/Android/PC, I'd like to ask libGDX developers how possible is this given my target platforms?

答:
Yes you can

There's a catch though, you may have to build the UI the game dev way

I've made a game or two using it and had rather steep learning curve in the beginning to get a hold on to how it worked. For example you'll have to provide the images for button, background and also, the pressed view of the button... like that. But your app is not a game. So you won't have to worry that much.

Once you learned how to place them in the screen successfully, there is not much to worry about because the API provides everything you need to carry on from there.

Also I found enough resources/tutorials online enough to make a game from ground up. So you'll definitely can.

And there's very little to worry about your multi-platform problem.

Title: libGDX as a "launcher" app


问:
Random NHibernate IndexOutOfRange Exception
Randomly NHibernate seems to fail with an IndexOutOfRange Exception.  The code works most of the, time but causes random application crashes.

```<code>    public T GetByID<T>(Guid Id) where T : Modules.Common.EntityBase
    {
        try
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var product = session
                .CreateCriteria(typeof(T))
                .Add(Restrictions.Eq("Id", Id))
                .UniqueResult<T>();
            return product;
        }
        catch (HibernateException ex)
        {
            NHibernateHelper.CloseSession();
            throw;
        }
    }
</code>```

I'm using the code on a WCF Service where ISessions are managed for each individual httpcontext, so i don't think it's due to thread safety.  The Exception comes from DataReader so I'm going to guess that it is comming from the UniqueResult line.

Here is the get Current Session function

```<code>    public static ISession GetCurrentSession()
    {
        if (HttpContext.Current == null)
        {
            lock (sessionLock)
            {
                if (_session == null)
                    _session = sessionFactory.OpenSession();
            }
            return _session;
        }

        HttpContext context = HttpContext.Current;
        ISession currentSession = context.Items[CurrentSessionKey] as ISession;

        if (currentSession == null)
        {
            currentSession = sessionFactory.OpenSession();
            context.Items[CurrentSessionKey] = currentSession;
        }

        return currentSession;
    }
</code>```

答:
maybe a long shot, but check this
IndexOutOfRangeException Deep in the bowels of NHibernate</p>

Body:
Randomly NHibernate seems to fail with an IndexOutOfRange Exception.  The code works most of the, time but causes random application crashes.

    public T GetByID<T>(Guid Id) where T : Modules.Common.EntityBase
    {
        try
        {
            ISession session = NHibernateHelper.GetCurrentSession();
            var product = session
                .CreateCriteria(typeof(T))
                .Add(Restrictions.Eq("Id", Id))
                .UniqueResult<T>();
            return product;
        }
        catch (HibernateException ex)
        {
            NHibernateHelper.CloseSession();
            throw;
        }
    }

I'm using the code on a WCF Service where ISessions are managed for each individual httpcontext, so i don't think it's due to thread safety.  The Exception comes from DataReader so I'm going to guess that it is comming from the UniqueResult line.

Here is the get Current Session function

    public static ISession GetCurrentSession()
    {
        if (HttpContext.Current == null)
        {
            lock (sessionLock)
            {
                if (_session == null)
                    _session = sessionFactory.OpenSession();
            }
            return _session;
        }

        HttpContext context = HttpContext.Current;
        ISession currentSession = context.Items[CurrentSessionKey] as ISession;

        if (currentSession == null)
        {
            currentSession = sessionFactory.OpenSession();
            context.Items[CurrentSessionKey] = currentSession;
        }

        return currentSession;
    }


问:
CSS filter background images
I'm trying to place a filter over the background image of the div in the code below as done on the homepage of http://www.theverge.com/. Honestly I have no idea how how to get around it.
This is what I have:</p>

```<code><a href="#">
    <div id="box"></div>
</a>

<style>
    #box{
        background-image: url("http://goo.gl/pdyi7R");
        background-size: cover;
        background-position: center center;
        background-repeat: no-repeat;
        border: 1px solid;
        width: 500px;
        height: 300px;
        position: relative;
        opacity: 0.5;
    }
    #box:hover {
        background-color: red;
        opacity: 5;
    }
</style>
</code>```

答:
The div is invalid, since it's a starting tag. Unless you want a navigation bar on top of the div.

For the background of the website it would look like this for the div tag.

```<code> <div class="box" style="background-image:url("");">
   <a href="#"></a>
 </div>
</code>```

Using the background image on the div only, makes it easier for editing.
Now you can use a filter to change the style of the image.

W3 Schools has the list of filter options and styles.

https://www.w3schools.com/cssref/css3_pr_filter.asp

Title: CSS filter background images

Body:
The div is invalid, since it's a starting tag. Unless you want a navigation bar on top of the div.

For the background of the website it would look like this for the div tag.

 <div class="box" style="background-image:url("");">
   <a href="#"></a>
 </div>

Using the background image on the div only, makes it easier for editing.
Now you can use a filter to change the style of the image.

W3 Schools has the list of filter options and styles.

https://www.w3schools.com/cssref/css3_pr_filter.asp


问:
How do you wrap text on IntelliJ(coding Python) when string is over 120 characters?
I am making a dictionary in Python using IntelliJ and the second entry is giving me an error PEP 8(line too long (155 > 120 characters).

```<code>classic_common = {'Abusive Sergeant': 'ADD ME TO YOUR DECK, YOU MAGGOT!',
                  **'Acolyte of Pain': "He trained when he was younger to be an acolyte of joy, but things didn't work out like he thought they would",**
</code>```

How can I wrap the string so it still functions and appears readable.

Thanks.

答:
Without getting into how to get IntelliJ to automatically to do this, here's an explanation on how to wrap long lines (including long strings) in Python in general:

In Python, a single statement can be written out over multiple lines by using either explicit or implicit line joining.

In the former, a backslash ('\', "line continuation character") is used to signal the end of a line. For example (as if entered into the Python Interpreter):

```<code>>>> a = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 \
... + 9 + 10
>>> print(a)
55
</code>```

On the other hand, implicit line joining allows expressions on multiple lines within parentheses, square brackets, or curly braces to be automatically joined together. In other words, any amount of white space is treated the same within these. For example (using poor style for illustrative purposes):

```<code>>>> a = [1, 2, 3, 4, 5, 6  # comments are allowed too
... # as are empty lines
...
... # and even explicit line breaks
... \
... , 7, 8]
>>> print(a)
[1, 2, 3, 4, 5, 6, 7, 8]
</code>```

As it turns out, you were already using implicit line joining in your code snippet when you put your key-value pairs on separate lines.

In addition to implicit line joining, you can take advantage of the fact that Python concatenates consecutive strings with no operator between them. One more example:

```<code>>>> a = 'The quick brown' 'fox'
>>> b = 'The quick brown' + 'fox'
>>> print(a==b)
True
</code>```

Putting this all together, since you are within curly brackets, you can close your string at any point and then place the next part of the string anywhere on the next line. The white space agnosticism within the brackets means that you can align the beginning of each line of the string (notice how "He", "of", and "thought" are aligned below).

Thus can you get something like the answer from idjaw's comment:

```<code>>>> classic_common = {'Abusive Sergeant': 'ADD ME TO YOUR DECK, YOU MAGGOT!',
                      'Acolyte of Pain': "He trained when he was younger to be an acolyte "
                                         "of joy, but things didn't work out like he "
                                         "thought they would",
                      'some_other_key': 'some other value'}
</code>```

Body:
I am making a dictionary in Python using IntelliJ and the second entry is giving me an error PEP 8(line too long (155 > 120 characters).

classic_common = {'Abusive Sergeant': 'ADD ME TO YOUR DECK, YOU MAGGOT!',
                  **'Acolyte of Pain': "He trained when he was younger to be an acolyte of joy, but things didn't work out like he thought they would",**

How can I wrap the string so it still functions and appears readable.

Thanks.

Body:
Without getting into how to get IntelliJ to automatically to do this, here's an explanation on how to wrap long lines (including long strings) in Python in general:

In Python, a single statement can be written out over multiple lines by using either explicit or implicit line joining.

In the former, a backslash ('\', "line continuation character") is used to signal the end of a line. For example (as if entered into the Python Interpreter):

>>> a = 1 + 2 + 3 + 4 + 5 + 6 + 7 + 8 \
... + 9 + 10
>>> print(a)
55

On the other hand, implicit line joining allows expressions on multiple lines within parentheses, square brackets, or curly braces to be automatically joined together. In other words, any amount of white space is treated the same within these. For example (using poor style for illustrative purposes):

>>> a = [1, 2, 3, 4, 5, 6  # comments are allowed too
... # as are empty lines
...
... # and even explicit line breaks
... \
... , 7, 8]
>>> print(a)
[1, 2, 3, 4, 5, 6, 7, 8]

As it turns out, you were already using implicit line joining in your code snippet when you put your key-value pairs on separate lines.

In addition to implicit line joining, you can take advantage of the fact that Python concatenates consecutive strings with no operator between them. One more example:

>>> a = 'The quick brown' 'fox'
>>> b = 'The quick brown' + 'fox'
>>> print(a==b)
True

Putting this all together, since you are within curly brackets, you can close your string at any point and then place the next part of the string anywhere on the next line. The white space agnosticism within the brackets means that you can align the beginning of each line of the string (notice how "He", "of", and "thought" are aligned below).

Thus can you get something like the answer from idjaw's comment:

>>> classic_common = {'Abusive Sergeant': 'ADD ME TO YOUR DECK, YOU MAGGOT!',
                      'Acolyte of Pain': "He trained when he was younger to be an acolyte "
                                         "of joy, but things didn't work out like he "
                                         "thought they would",
                      'some_other_key': 'some other value'}


问:
ERROR_MESSAGE_MAIN ERROR_MESSAGE_REASON on iPad and Iphone in .Net Application
I am using windows.open('url') to download excel from c# web api. It is getting downloaded in every browsers. But for Ipad and Iphone, the file gets download but I get following error on screen

```<code>ERROR_MESSAGE_MAIN ERROR_MESSAGE_REASON
</code>```

I am using the following code to return the excel data which is stored in memory stream

```<code>HttpResponseMessage result = null;

result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(mem);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "myexcel.xlsx"
};
return result;
</code>```

I have seen the same question which is in PHP. I tried checking for the same but he was giving wrong content type. Url:-
ERROR_MESSAGE_MAIN ERROR_MESSAGE_REASON on iPad and iPhone Safari

I checked for the same issue on other places and tried below code changes. I added Desktop variable so that on mobile,I can add another stream as suggested. But it doesn't work.

```<code>if (isDesktop)
{
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
else
{
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "myexcel.xlsx"
};
return result;
</code>```

edited - I am using ClosedXml for creating excel.
Github link for Closed XMl issue - https://github.com/ClosedXML/ClosedXML/issues/279

答: I solved this by using Eppus because I couldn't find any solution for closedXml.

Body:
I am using windows.open('url') to download excel from c# web api. It is getting downloaded in every browsers. But for Ipad and Iphone, the file gets download but I get following error on screen

ERROR_MESSAGE_MAIN ERROR_MESSAGE_REASON

I am using the following code to return the excel data which is stored in memory stream

HttpResponseMessage result = null;

result = Request.CreateResponse(HttpStatusCode.OK);
result.Content = new StreamContent(mem);
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "myexcel.xlsx"
};
return result;

I have seen the same question which is in PHP. I tried checking for the same but he was giving wrong content type. Url:-
ERROR_MESSAGE_MAIN ERROR_MESSAGE_REASON on iPad and iPhone Safari

I checked for the same issue on other places and tried below code changes. I added Desktop variable so that on mobile,I can add another stream as suggested. But it doesn't work.

if (isDesktop)
{
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
}
else
{
    result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
}
result.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
    FileName = "myexcel.xlsx"
};
return result;

edited - I am using ClosedXml for creating excel.
Github link for Closed XMl issue - https://github.com/ClosedXML/ClosedXML/issues/279


问:
No module named 'selenium'
ModuleNotFoundError: No module named 'selenium'

the python version
selenium
pip install selenium ,it reminds me below:
Requirement already satisfied: selenium in d:\program files\python\lib\site-packages

and the directory 'd:\program files\python' is python 3.6

it seems that every thing is wright.
win7,python3.6 and put it in path,selenium3.4 and its wright location,pip9.0 with python3.6.

i dont no where i am wrong.

English is not my motherlangue,i am not so good at it,i try to give more wright information and detail .

答:
It looks like you might be running in a different version of python then your pip is installing.  You can check using pip --version.  For example:

I can check my 3.5 python branch with

pip --version
  pip 9.0.1 from /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages (python 3.5)
  and from here pip freeze will list the modules installed under the python3 branch...

...versus if I check the 2.7 branch:

pip2 --version
  pip 9.0.1 from /Library/Python/2.7/site-packages (python 2.7)
  I will find a different set of packages installed using pip2 freeze.

If you have selenium installed under one branch and are running your code under another branch, that will cause your mysterious error.  Please comment back if you need more help.  Hope this helps!

Title: No module named 'selenium'


问:
Erasing row in 2D Vector - segmentation error
I'm new to C++, and am learning vectors now. I'm trying to delete a row from a 2D vector, but so far all my attempts have been resulting in a segmemtation error. This is the piece of code I've been trying out -

```<code>vector<vector<int> > myVector;
...
vector<vector<int> >::iterator row = myVector.begin();
while(row!=myVector.end())
{
    if((*row)[0] == -1)
        myVector.erase(row);
    else
        row++;
}
</code>```

myVector is a 2D vector that contains values such as:

```<code> 1 0
-1 1
 2 1
-1 0 ...
</code>```

I need to delete any row whose first element is -1.

I've tried using myVector.erase(myVector.begin() + row2delete) but that's giving me a core dump too. Am I doing something wrong? Thank you for the help!

答:
The best you can do is make another 2D vector and shift all the elements which do not have -1 as first element to the new vector and after that when shifting is complete delete the first vector.
For eg:-</p>

```<code>vector<vector<int> > myVector;vector<vector<int> > myVector2;
int i=0;
while(i<myVector.size()){
    if(myVector[i][0] != -1){
        myVector2.push_back(myVector[i]);
}
return myVector2;
</code>```

Body:
I'm new to C++, and am learning vectors now. I'm trying to delete a row from a 2D vector, but so far all my attempts have been resulting in a segmemtation error. This is the piece of code I've been trying out -

vector<vector<int> > myVector;
...
vector<vector<int> >::iterator row = myVector.begin();
while(row!=myVector.end())
{
    if((*row)[0] == -1)
        myVector.erase(row);
    else
        row++;
}

myVector is a 2D vector that contains values such as:

 1 0
-1 1
 2 1
-1 0 ...

I need to delete any row whose first element is -1.

I've tried using myVector.erase(myVector.begin() + row2delete) but that's giving me a core dump too. Am I doing something wrong? Thank you for the help!

Body:
The best you can do is make another 2D vector and shift all the elements which do not have -1 as first element to the new vector and after that when shifting is complete delete the first vector.
For eg:-

vector<vector<int> > myVector;vector<vector<int> > myVector2;
int i=0;
while(i<myVector.size()){
    if(myVector[i][0] != -1){
        myVector2.push_back(myVector[i]);
}
return myVector2;


问:
Optimizing audio preload from a list of elements
I am making a soundboard Chrome extension that has buttons with a class of "myButtons". With that, I have my Javascript look for elements with that class, take their id and use that to make new audio instances off of their ID.
Chrome extensions have external js, must be in a js file not in the html document itself The reason the extension loads so slow is that all 200+ audio files have to load before the popup for the extension appear. I don't know how to turn that preloading off to make my extension load quicker. The problem is that it takes up to 10 seconds to launch my extension with this. Which of course, is not at all ideal.

```<code>var audios = Array.prototype.map.call(document.getElementsByClassName("myButton"), function (el) {
var audio = new Audio();
audio.src = "mp3/" + el.id + ".mp3";
el.onclick = audio.play.bind(audio);
return audio;
});
</code>```

I have seen there is a preload property for audio instances (https://developer.apple.com/documentation/webkitjs/htmlmediaelement/1633059-preload), however, I am unsure how to implement this with my current function.

答:
I need them to load when clicked. So I can have the extension load
  instantly. I don't mind the time it takes to load the individual audio
  files.

Set src of AudioNode to URL pointing to media resource within click handler

```<code>var audios = Array.prototype.map.call(document.getElementsByClassName("myButton")
, function (el) {
    var audio = new Audio();
    var src = "mp3/" + el.id + ".mp3";
    el.onclick = function() {
                   audio.src = src;
                   audio.play();
                 };
    return audio;
});
</code>```

Body:
I am making a soundboard Chrome extension that has buttons with a class of "myButtons". With that, I have my Javascript look for elements with that class, take their id and use that to make new audio instances off of their ID.
Chrome extensions have external js, must be in a js file not in the html document itself The reason the extension loads so slow is that all 200+ audio files have to load before the popup for the extension appear. I don't know how to turn that preloading off to make my extension load quicker. The problem is that it takes up to 10 seconds to launch my extension with this. Which of course, is not at all ideal.

var audios = Array.prototype.map.call(document.getElementsByClassName("myButton"), function (el) {
var audio = new Audio();
audio.src = "mp3/" + el.id + ".mp3";
el.onclick = audio.play.bind(audio);
return audio;
});

I have seen there is a preload property for audio instances (https://developer.apple.com/documentation/webkitjs/htmlmediaelement/1633059-preload), however, I am unsure how to implement this with my current function.

Body:
I need them to load when clicked. So I can have the extension load
  instantly. I don't mind the time it takes to load the individual audio
  files.

Set src of AudioNode to URL pointing to media resource within click handler

var audios = Array.prototype.map.call(document.getElementsByClassName("myButton")
, function (el) {
    var audio = new Audio();
    var src = "mp3/" + el.id + ".mp3";
    el.onclick = function() {
                   audio.src = src;
                   audio.play();
                 };
    return audio;
});


问:
where are Jinja2 variables and files located and how do i find them?
noob here, so please bear with me.
My question is where is the web_include_css file and where is the link or abs_url variable? How do i find them?</p>

```<code>{%- for link in web_include_css %}
<link type="text/css" rel="stylesheet" href="{{ link|abs_url }}">
{%- endfor -%}
</code>```

答: web_include_css is a variable passed down from server see the corresponding view function. Also abs_url is a template tag please see the templates tag folder for more info...

Body:
noob here, so please bear with me.
My question is where is the web_include_css file and where is the link or abs_url variable? How do i find them?

{%- for link in web_include_css %}
<link type="text/css" rel="stylesheet" href="{{ link|abs_url }}">
{%- endfor -%}


问:
How to create Tamil Language Based Web Application in Laravel 5.4
I planed to create Departmental Store Laravel Web Application in Tamil Language Not Using English. How to do it?</p>

答:
You can create web apps using laravel's Localization.
For that, you need to create language strings. Language strings are stored in files within the resources/lang directory.

You need to create locale:

```<code>Route::get('welcome/{locale}', function ($locale) {
   App::setLocale($locale);

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

Then create file within that directory and save it messages.php name like this:

```<code><?php

   return [
      'welcome' => 'Welcome to our application'
   ];
?>
</code>```

Then you need to use this as in any blade file like:

```<code>@lang('messages.welcome')
</code>```

Also, please read the laravel docs from here:
enter link description here

Body:
You can create web apps using laravel's Localization.
For that, you need to create language strings. Language strings are stored in files within the resources/lang directory.

You need to create locale:

Route::get('welcome/{locale}', function ($locale) {
   App::setLocale($locale);

   //
});

Then create file within that directory and save it messages.php name like this:

<?php

   return [
      'welcome' => 'Welcome to our application'
   ];
?>

Then you need to use this as in any blade file like:

@lang('messages.welcome')

Also, please read the laravel docs from here:
enter link description here


问:
register_post_type in wordpress no working template
I have problem with function "register_post_type" in wordpress.

I add code in functions.php (theme path):

```<code>add_action( 'init', 'events' );

function events() {
  register_post_type( 'events', array(
    'labels' => array(
      'name' => 'Wydarzenia',
      'singular_name' => 'events',
     ),
    'description' => 'Wydarzenia',
    'public' => true,
    'menu_position' => 20,
    'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'excerpt')
  ));
}
</code>```

And i add template: single-events.php and archive-events.php but this no working... everytime show: index.php..

single.php no working for events...

Where is problem? Thanks!

答:
I think you are missing page-events.php

After creating your post type events. In your WP admin, create a page called events and then in code create a page page-events.php and then show the listing of all events that u have created in ur custom post type events

```<code><?php
$args = array
(
    'post_type' => 'events',
    'posts_per_page' => 10
);
$events_query = new WP_Query($args);?>
<?php if($events_query->have_posts()):?>
    <ul>
        <?php while($events_query->have_posts()): $events_query->the_post();?>
            <li>
                <a href="<?php the_permalink();?>"><?php the_title();?></a>
            </li>
        <?php endwhile; wp_reset_postdata(); ?>
    </ul>
<?php endif;?>
</code>```

then you can create a single-events.php to show content of a single event.

Body:
I have problem with function "register_post_type" in wordpress.

I add code in functions.php (theme path):

add_action( 'init', 'events' );

function events() {
  register_post_type( 'events', array(
    'labels' => array(
      'name' => 'Wydarzenia',
      'singular_name' => 'events',
     ),
    'description' => 'Wydarzenia',
    'public' => true,
    'menu_position' => 20,
    'supports' => array( 'title', 'editor', 'custom-fields', 'thumbnail', 'excerpt')
  ));
}

And i add template: single-events.php and archive-events.php but this no working... everytime show: index.php..

single.php no working for events...

Where is problem? Thanks!

Body:
I think you are missing page-events.php

After creating your post type events. In your WP admin, create a page called events and then in code create a page page-events.php and then show the listing of all events that u have created in ur custom post type events

<?php
$args = array
(
    'post_type' => 'events',
    'posts_per_page' => 10
);
$events_query = new WP_Query($args);?>
<?php if($events_query->have_posts()):?>
    <ul>
        <?php while($events_query->have_posts()): $events_query->the_post();?>
            <li>
                <a href="<?php the_permalink();?>"><?php the_title();?></a>
            </li>
        <?php endwhile; wp_reset_postdata(); ?>
    </ul>
<?php endif;?>

then you can create a single-events.php to show content of a single event.


问:
How to load nested Entity Framework objects efficiently
I'm trying to load a 3-deep tree into a treeview control using entity framework

Categories, SubCategories and Products
in the code below categories is an IQueryable<ProductCategory> where ProductCategory is an EF4.0 generated object (default code generation)

SubCategories is a FK back to the categories table (so in theory we could go to any depth, but the data domain will only have two levels)

```<code>var container = categories.Where(c=>c.somecondition).Include("Subcategories.Products");
foreach (var cat in container) {
  addtoTree(cat);
  foreach (var sub in cat.SubCategories)
  {
     addtoTree(sub);
     foreach (var prod in sub.Products) addtoTree(prod);

  }
}
</code>```

This is still issuing queries for each inner loop iteration. Am I missing something in the EF configuration (changes to the context?) to stop that happening? Or is there another way of writing this sort of code?

(As a horrendous hack for now, I've created an SQL view that flattens the information, and I iterate that to re-build the nested objects by hand...nasty, but fast!)

答:
When dealing with potentially complex hierarchies, it can help to pull a simplified structure of the data you need. This will avoid the need to eager-load as the data will be joined in the results, loading what is necessary, and typically can take better advantage of indexes on the database server side.

For example if you want to load "basic" details on categories, sub-categories, and products suitable for display in a tree structure:

```<code>var results = dbContext.Categories.Where(c=> /*some condition*/)
    .Select(c=> new {c.CategoryId, c.Name, SubCategories =
        c.SubCategories.Select(sc=> new { sc.SubCategoryId, sc.Name, Products = sc.Products.Select(p=> new {p.ProductId, p.Name}) }) }).ToList();
</code>```

Granted, it may not look pretty, but no magic strings for eager load expressions, and the SQL that EF generates will typically be several orders more efficient & utilize indexes that you'd typically want on those tables.

For simple entities you can use this to .Select down through the child hierarchy, but when dealing with heavier entities where you just want a few key details this can save quite a bit of processing and network bandwidth by only retrieving and transmitting the data you need.

Body:
I'm trying to load a 3-deep tree into a treeview control using entity framework

Categories, SubCategories and Products
in the code below categories is an IQueryable<ProductCategory> where ProductCategory is an EF4.0 generated object (default code generation)

SubCategories is a FK back to the categories table (so in theory we could go to any depth, but the data domain will only have two levels)

var container = categories.Where(c=>c.somecondition).Include("Subcategories.Products");
foreach (var cat in container) {
  addtoTree(cat);
  foreach (var sub in cat.SubCategories)
  {
     addtoTree(sub);
     foreach (var prod in sub.Products) addtoTree(prod);

  }
}

This is still issuing queries for each inner loop iteration. Am I missing something in the EF configuration (changes to the context?) to stop that happening? Or is there another way of writing this sort of code?

(As a horrendous hack for now, I've created an SQL view that flattens the information, and I iterate that to re-build the nested objects by hand...nasty, but fast!)

Body:
When dealing with potentially complex hierarchies, it can help to pull a simplified structure of the data you need. This will avoid the need to eager-load as the data will be joined in the results, loading what is necessary, and typically can take better advantage of indexes on the database server side.

For example if you want to load "basic" details on categories, sub-categories, and products suitable for display in a tree structure:

var results = dbContext.Categories.Where(c=> /*some condition*/)
    .Select(c=> new {c.CategoryId, c.Name, SubCategories =
        c.SubCategories.Select(sc=> new { sc.SubCategoryId, sc.Name, Products = sc.Products.Select(p=> new {p.ProductId, p.Name}) }) }).ToList();

Granted, it may not look pretty, but no magic strings for eager load expressions, and the SQL that EF generates will typically be several orders more efficient & utilize indexes that you'd typically want on those tables.

For simple entities you can use this to .Select down through the child hierarchy, but when dealing with heavier entities where you just want a few key details this can save quite a bit of processing and network bandwidth by only retrieving and transmitting the data you need.


问:
Detect touch screen in iOS
Now I have implemented the fling feature in my ios app,  but I want to stop the fling when a touch on screen happens, this does not only contain tap gesture, maybe other like long press or pinch, I have a BOOL value to indicate whether a touch happens, so should I add all kinds of  gesture recognizers and set to BOOL value as true? Are there any simple solution? Thank you!</p>

答:
There are several methods in UIGestureRecognizerDelegate that will achieve what you want. gestureRecognizerShouldRegognizeSimultaneouslyWithGesture sounds like the best candidate. You will get passed two gesture recognizers. One will be your swipe gesture (the one you want to keep), the other will be the one you want to cancel (tap, long press, pinch) return NO in the correct scenario.

See docs: https://developer.apple.com/documentation/uikit/uigesturerecognizerdelegate

Title: Detect touch screen in iOS


问:
Hide Django logo/name in header Django admin tool
I want to hide/change the name displayed in the header bar, the label that I want to change is "DJANGO" word as the next image shows"

答:
The easiest way is to simply add the following lines to your main urls.py:

```<code>admin.site.site_title = 'My Heading'
admin.site.site_header = 'My Heading'
admin.site.index_title = 'My Heading'
</code>```

See the Django documentation for more attributes.

Body:
The easiest way is to simply add the following lines to your main urls.py:

admin.site.site_title = 'My Heading'
admin.site.site_header = 'My Heading'
admin.site.index_title = 'My Heading'

See the Django documentation for more attributes.


问:
WooCommerce - Free Shipping if shipping class is true AND quantity is over some number
My cart needs to have free shipping if a specific product with shipping class is there and the quantity of that product is over 8. Doesn't matter if it has another product on the cart. The shipping fee will be free.

Because what I have right now looks for the shipping class (which is correct) but counts the quantity of the ENTIRE cart. Not that specific product with shipping class on the cart. How can I do this in PHP?

答:
```<code>add_filter('woocommerce_package_rates', 'show_hide_free_shipping', 10, 2);
function show_hide_free_shipping($available_shipping_methods, $package){
    $minimum_number_of_item = 12; //Give here minumum number of items to allow freeshipping
    $shop_country = 'AU'; //Give here the country code where the store located

    $free_shipping  =   false;
    global $woocommerce;
    $customer_country = $woocommerce->customer->get_shipping_country();

    $item_count = 0;
    foreach (WC()->cart->cart_contents as $key => $item) {
        $item_count += $item['quantity'];
    }

    if( $item_count >= $minimum_number_of_item && $customer_country ==  $shop_country ){
        $free_shipping  =   true;
    }

    if($free_shipping){
        foreach($available_shipping_methods as $shipping_method =>  $method){
            if( strpos( $shipping_method, 'free_shipping' ) === false ) {
                unset($available_shipping_methods[$shipping_method]);
            }
        }
    }
    else{
        foreach($available_shipping_methods as $shipping_method =>  $method){
            if( strpos( $shipping_method, 'free_shipping' ) !== false ) {
                unset($available_shipping_methods[$shipping_method]);
            }
        }
    }
    return $available_shipping_methods;
}
</code>```

Got from below link.
You can use it with some tweaks.

https://www.xadapter.com/showhide-free-shipping-based-item-count-domestic-shipment/

https://www.xadapter.com/hide-shipping-methods-shipping-classes-exist-not-exist-cart/

Body:
add_filter('woocommerce_package_rates', 'show_hide_free_shipping', 10, 2);
function show_hide_free_shipping($available_shipping_methods, $package){
    $minimum_number_of_item = 12; //Give here minumum number of items to allow freeshipping
    $shop_country = 'AU'; //Give here the country code where the store located

    $free_shipping  =   false;
    global $woocommerce;
    $customer_country = $woocommerce->customer->get_shipping_country();

    $item_count = 0;
    foreach (WC()->cart->cart_contents as $key => $item) {
        $item_count += $item['quantity'];
    }

    if( $item_count >= $minimum_number_of_item && $customer_country ==  $shop_country ){
        $free_shipping  =   true;
    }

    if($free_shipping){
        foreach($available_shipping_methods as $shipping_method =>  $method){
            if( strpos( $shipping_method, 'free_shipping' ) === false ) {
                unset($available_shipping_methods[$shipping_method]);
            }
        }
    }
    else{
        foreach($available_shipping_methods as $shipping_method =>  $method){
            if( strpos( $shipping_method, 'free_shipping' ) !== false ) {
                unset($available_shipping_methods[$shipping_method]);
            }
        }
    }
    return $available_shipping_methods;
}

Got from below link.
You can use it with some tweaks.

https://www.xadapter.com/showhide-free-shipping-based-item-count-domestic-shipment/

https://www.xadapter.com/hide-shipping-methods-shipping-classes-exist-not-exist-cart/


问:
Calendar localization in the new codenameone GUI Builder
how can I implement localization for my calendar component in the new codenameone GUI Builder, working in Netbeans IDE. i.e. is there an equivalent of this process described for the old GUI Builder? https://www.codenameone.com/how-do-i---localizetranslate-my-application-apply-i18nl10n-internationalizationlocalization-to-my-app.html.

Alternatively, how can I then access calendar properties implementing code manually, so that I alter the strings to preferred language?; strings for Month titles, days of the week etc.

答:
You can localize the new GUI builder just like the old one in the same old interface you just don't get the same level of preview. We hope to release a better localization tool moving forward.

To localize the calendar strings use syntax like: Calendar.Jan, Calendar.Feb etc.

For the days Calendar.Sunday etc.


问:
Varying iPhone deployment target: Handling Framework constants
I am building an app that needs to work on multiple versions of iPhone OS and makes use of increased accuracy for Core Location in iOS4.

I have code that does the following:

    if ([m_locationManager respondsToSelector:@selector(startMonitoringSignificantLocationChanges)]) {
         m_locationManager.desiredAccuracy = kCLLocationAccuracyBestForNavigation;
    }
    else {
         m_locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    }

in this case, kCLLocationAccuracyBestForNavigation is a constant introduced in iOS 4, and startMonitoringSignificantLocationChanges is a method of m_locationManager only introduced in iOS4.

My problem is, that this code is failing on an iPhone 3.1.3 device.  It is trying to link to kCLLocationAccuracyBestForNavigation, but it can't find the symbol.  My question is, how do I only link to this symbol in the iOS4 version, but not the iPhone 3.1.3 version?

Thanks,
C

答:
You can also test for a constant with:</p>

```<code>if(&kCLLocationAccuracyBestForNavigation != nil)
</code>```

Body:
You can also test for a constant with:

if(&kCLLocationAccuracyBestForNavigation != nil)


问:
Not able to find property
I have a very simple local setup for VueJS and am having problems running a simple example that shows how raw HTML can be output. I'm not including link to JS Fiddle because I want to make it work on local setup only, and sometimes my examples work on JS Fiddle but not on local machine.

Anyway, here's the html code:

```<code><html>
<head>
  <script src="https://unpkg.com/vue"></script>
  <script src="app.js"></script>
</head>
<body>
  <div id="app">
    <!-- Doesn't work! -->
    <p>{{ link }}</p>
    <!-- This works! -->
    <p v-html>{{ link }} </p>
  </div>
</body>
</html>
</code>```

And here's my app.js file:

```<code>window.addEventListener('load', function(){
    new Vue({
        el: '#app',
        data: {
            link: '<a href="http://google.com">Google</a>'
        }
    });
});
</code>```

Now when I load the window, I get twice the following error:

[Vue warn]: Property or method "link" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in <Root>).

Any idea where I'm going wrong?

答:
Can you try this one and see if it works as required. I moved the scripts after the body.</p>

```<code><html>
<head>
</head>
<body>
  <div id="app">
    <!-- Doesn't work! -->
    <p>{{ link }}</p>
    <!-- This works! -->
    <p v-html>{{ link }} </p>
  </div>
</body>
  <script src="https://unpkg.com/vue"></script>
  <script src="app.js"></script>
</html>
</code>```

Title: Not able to find property

Body:
I have a very simple local setup for VueJS and am having problems running a simple example that shows how raw HTML can be output. I'm not including link to JS Fiddle because I want to make it work on local setup only, and sometimes my examples work on JS Fiddle but not on local machine.

Anyway, here's the html code:

{{ link }}

{{ link }}

And here's my app.js file:

window.addEventListener('load', function(){
    new Vue({
        el: '#app',
        data: {
            link: 'Google'
        }
    });
});

Now when I load the window, I get twice the following error:

[Vue warn]: Property or method "link" is not defined on the instance but referenced during render. Make sure to declare reactive data properties in the data option. (found in <Root>).

Any idea where I'm going wrong?

Body:
Can you try this one and see if it works as required. I moved the scripts after the body.

<html>
<head>
</head>
<body>
  <div id="app">
    <!-- Doesn't work! -->
    <p>{{ link }}</p>
    <!-- This works! -->
    <p v-html>{{ link }} </p>
  </div>
</body>
  <script src="https://unpkg.com/vue"></script>
  <script src="app.js"></script>
</html>


问:
How to speed up SELECT .. LIKE queries in MySQL on multiple columns?
I have a MySQL table for which I do very frequent SELECT x, y, z FROM table WHERE x LIKE '%text%' OR y LIKE '%text%' OR z LIKE '%text%' queries. Would any kind of index help speed things up?

There are a few million records in the table. If there is anything that would speed up the search, would it seriously impact disk usage by the database files and the speed of INSERT and DELETE statements? (no UPDATE is ever performed)

Update: Quickly after posting, I have seen a lot of information and discussion about the way LIKE is used in the query; I would like to point out that the solution must use LIKE '%text%' (that is, the text I am looking for is prepended and appended with a % wildcard). The database also has to be local, for many reasons, including security.

答:
Maybe you can try to upgrade mysql5.1 to mysql5.7.

I have about 70,000 records. And run following SQL:

```<code>select * from comics where name like '%test%';
</code>```

It takes 2000ms in mysql5.1.
And it takes 200ms in mysql5.7 or mysql5.6.

Body:
Maybe you can try to upgrade mysql5.1 to mysql5.7.

I have about 70,000 records. And run following SQL:

select * from comics where name like '%test%';

It takes 2000ms in mysql5.1.
And it takes 200ms in mysql5.7 or mysql5.6.


问:
Select Join Table A and Table B while displaying Table B items based on Table A's foreign key
I'm in the midst of writing an SQL statement and I have a problem joining both tables (let's call it Table Enrollment & Product) based on a foreign key column from table Enrollment's column StudentID. The StudentID is read from a variable $StudentID.

Enrollment table

```<code>+--------------+-----------+-----------+

| EnrollmentID | StudentID | ProductID |

+--------------+-----------+-----------+

| 1            | 5         | 1         |

| 2            | 5         | 2         |

|3             | 7         | 2         |

|4             | 7         | 3         |

|5             | 9         | 5         |

+--------------+-----------+-----------+
</code>```

Product Table

```<code>+-----------+-------------+------------+

| ProductID | ProductName | ProductDate|

+-----------+-------------+------------+

|1          | ProductA    | 1/1/2017   |

|2          | ProductB    | 1/2/2017   |

|3          | ProductC    | 1/3/2017   |

|4          | ProductD    | 1/4/2017   |

+-----------+-------------+------------+
</code>```

This is the SQL statement so far i've come up and having trouble with:

```<code>"SELECT product.ProductName, product.ProductDate
                                FROM enrollment WHERE StudentID = '$StudentID'
                                RIGHT JOIN product ON enrollment.productid = product.productid";
</code>```

If $StudentID is 5. I want it to display all items from ProductID that is associated with StudentID 5. Which in this case, Product A and Product B will be the output.

答:
By reading your sql code, I assume you use PHP to generate sql query. Please use {$variable} when ever you want to include variable value inside string in PHP. And you have to join the table first and then apply condition. Use the below query,

```<code>"SELECT product.ProductName, product.ProductDate FROM enrollment inner join student ON enrollment.studentid = student.studentid  RIGHT JOIN product ON enrollment.productid = product.productid WHERE enrollment.StudentID = '{$StudentID}' "
</code>```

Body:
I'm in the midst of writing an SQL statement and I have a problem joining both tables (let's call it Table Enrollment & Product) based on a foreign key column from table Enrollment's column StudentID. The StudentID is read from a variable $StudentID.

Enrollment table

+--------------+-----------+-----------+

| EnrollmentID | StudentID | ProductID |

+--------------+-----------+-----------+

| 1            | 5         | 1         |

| 2            | 5         | 2         |

|3             | 7         | 2         |

|4             | 7         | 3         |

|5             | 9         | 5         |

+--------------+-----------+-----------+

Product Table

+-----------+-------------+------------+

| ProductID | ProductName | ProductDate|

+-----------+-------------+------------+

|1          | ProductA    | 1/1/2017   |

|2          | ProductB    | 1/2/2017   |

|3          | ProductC    | 1/3/2017   |

|4          | ProductD    | 1/4/2017   |

+-----------+-------------+------------+

This is the SQL statement so far i've come up and having trouble with:

"SELECT product.ProductName, product.ProductDate
                                FROM enrollment WHERE StudentID = '$StudentID'
                                RIGHT JOIN product ON enrollment.productid = product.productid";

If $StudentID is 5. I want it to display all items from ProductID that is associated with StudentID 5. Which in this case, Product A and Product B will be the output.

Body:
By reading your sql code, I assume you use PHP to generate sql query. Please use {$variable} when ever you want to include variable value inside string in PHP. And you have to join the table first and then apply condition. Use the below query,

"SELECT product.ProductName, product.ProductDate FROM enrollment inner join student ON enrollment.studentid = student.studentid  RIGHT JOIN product ON enrollment.productid = product.productid WHERE enrollment.StudentID = '{$StudentID}' "


问:
Allocation of arrays in Chapel
Unlike other languages, there seems no allocate or new syntax in Chapel for allocating arrays on the heap, but rather use the usual "declaration"-like syntax. For example, in the following code, I "declare" two arrays A and B in a function based on formal (dummy) arguments:

```<code>proc test( n, D )
{
    var A: [1..n] real;  // local array
    var B: [D] real;     // local array

    writeln( "A.domain = ", A.domain );
    writeln( "B.domain = ", B.domain );
}

test( 3, {2..5} );               // request small arrays
test( 10**7, {-10**7..10**7} );  // request large arrays
</code>```

This gives the following result:

```<code>A.domain = {1..3}
B.domain = {2..5}
A.domain = {1..10000000}
B.domain = {-10000000..10000000}
</code>```

Because no stack overflow occurs (despite the large size of B), is it OK to assume that the above syntax always allocates A and B on the heap regardless of their size?

Also, assignment (or re-assignment) of a domain variable seems to play the role of allocation (or re-allocation) of an array. For example, the following code works as expected. In this case, does the allocation always occur on the heap (again)?

```<code>var domC: domain(1);
var C: [domC] real;
writeln( "C = ", C );

domC = { 1..3 };       // assign a domain
C = 7.0;               // assign some value to the array
writeln( "C = ", C );

domC = { -1..5 };      // re-assign a domain
writeln( "C = ", C );
</code>```

Result:

```<code>C =
C = 7.0 7.0 7.0
C = 0.0 0.0 7.0 7.0 7.0 0.0 0.0
</code>```

Finally, is it not necessary for the user to deallocate or delete these arrays manually, but rather the system automatically deallocates them as needed?

答:
is it OK to assume that the above syntax always allocates A and B on the heap regardless of their size?

At of Chapel 1.15.0, Chapel array elements are always allocated on the heap.  We've discussed adding mechanisms (e.g., custom domain maps) or possibly optimizations that might be used to store arrays' elements on the stack when appropriate, but have not pursued such features yet.  Note that while the array's elements are allocated on the heap, arrays also are implemented using a runtime descriptor which is allocated "in-place" (e.g., on the stack in your examples)---this descriptor refers to the heap-allocated elements.

Also, assignment (or re-assignment) of a domain variable seems to play the role of allocation (or re-allocation) of an array.

That's correct, and it's worth emphasizing that this is a logically rather than physically oriented notion of reallocation.  Specifically, when an array's domain is reassigned, A[i] will continue to store the same value if i was in both the index sets of the old domain and the new one.  This is why when you changed domC from {1..3} to {-1..5} in your code above, A[1..3] was preserved, since it represents the intersection of the two sets.

does the allocation always occur on the heap (again)?

Yes, as with an initial array allocation.

is it not necessary for the user to deallocate or delete these arrays manually, but rather the system automatically deallocates them as needed?

That's correct, array memory management is generally handled by the implementation.  A way to manually manage array memory would be to have a class variable with an array field (since classes are manually memory managed).

Title: Allocation of arrays in Chapel

Body:
Unlike other languages, there seems no allocate or new syntax in Chapel for allocating arrays on the heap, but rather use the usual "declaration"-like syntax. For example, in the following code, I "declare" two arrays A and B in a function based on formal (dummy) arguments:

proc test( n, D )
{
    var A: [1..n] real;  // local array
    var B: [D] real;     // local array

    writeln( "A.domain = ", A.domain );
    writeln( "B.domain = ", B.domain );
}

test( 3, {2..5} );               // request small arrays
test( 10**7, {-10**7..10**7} );  // request large arrays

This gives the following result:

A.domain = {1..3}
B.domain = {2..5}
A.domain = {1..10000000}
B.domain = {-10000000..10000000}

Because no stack overflow occurs (despite the large size of B), is it OK to assume that the above syntax always allocates A and B on the heap regardless of their size?

Also, assignment (or re-assignment) of a domain variable seems to play the role of allocation (or re-allocation) of an array. For example, the following code works as expected. In this case, does the allocation always occur on the heap (again)?

var domC: domain(1);
var C: [domC] real;
writeln( "C = ", C );

domC = { 1..3 };       // assign a domain
C = 7.0;               // assign some value to the array
writeln( "C = ", C );

domC = { -1..5 };      // re-assign a domain
writeln( "C = ", C );

Result:

C =
C = 7.0 7.0 7.0
C = 0.0 0.0 7.0 7.0 7.0 0.0 0.0

Finally, is it not necessary for the user to deallocate or delete these arrays manually, but rather the system automatically deallocates them as needed?


问:
AngularJs/Bootstrap - Bind checkbox in list not works properly
I have a roles list that filter a permissions list. The permissions list has a checkbox indicating that it is selected.

Each role has a list of associated permissions. When a role is selected, all available permissions are displayed and those already associated with them will be checked. By clicking on the checkbox of each permission you can associate or desesociate it.

But the select and unselect permission action does not work properly. I can not figure out what the problem. Can someone help me ? Thanks!!!

Code in Plunker

Page code

```<code> <div class="panel-body">
          <div class="form-group">
            <div class="col-md-6">
              <div class="list-group">
                <a ng-click="selectRole(role)" ng-repeat="role in model.roles" class="list-group-item" ng-class="{active: role.id == model.selectedRole.id}">{{role.name}}</a>
              </div>
            </div>
            <div class="col-md-6">
              <div class="list-group">
                <a ng-repeat="permission in model.permissions" class="list-group-item">{{permission.name}}                  <input type="checkbox" class="pull-right" ng-checked="isSelected(permission.id) > -1" ng-click="clickPermission(permission)" ng-class="{active: permission.id == model.selectedPermission.id}" />
                </a>
              </div>
            </div>
          </div>
        </div>
</code>```

Controller code

```<code>app.controller('PermissionsToRoleController', function($scope) {

  $scope.model = {
    roles: [],
    permissions: [],
    selectedRole: null,
        selectedPermission: null
  };

  $scope.selectRole = function(role) {
    $scope.model.selectedRole = role;
  }

  var findRoles = function() {
    $scope.model.roles = [{id: 1, name: 'ADMIN', permissions: [{id: 1, name:'MASTER'}] },
                          {id: 2, name: 'USER',  permissions: [] }
                         ];

        $scope.model.permissions = [{id: 1, name: 'MASTER'}];

        $scope.model.selectedRole = $scope.model.roles[0];
  };

  $scope.clickPermission = function(permission) {
    $scope.model.selectedPermission = permission;
    var idx = $scope.isSelected(permission.id);
    if (idx > -1) {
      $scope.model.selectedRole.permissions.splice(idx, 1);
    } else {
      $scope.model.selectedRole.permissions.push(permission);
    }
  };

  $scope.isSelected = function(permissionId) {
    for (var i = 0; i < $scope.model.selectedRole.permissions.length ; i++) {
      if ($scope.model.selectedRole.permissions[i].id === permissionId) {
              return i;
      }
    }
    return -1;
  }

  findRoles();

});
</code>```

答:
The problem I found being the checkbox, while functions properly, the display won't "uncheck" when you click on it.

This can be fixed by changing the surrounding element to span instead of a

```<code><span ng-repeat="permission in model.permissions" class="list-group-item">{{permission.name}}
    <input type="checkbox" class="pull-right" ng-checked="isSelected(permission.id) > -1" ng-click="clickPermission(permission)" ng-class="{active: permission.id == model.selectedPermission.id}" />
</span>
</code>```

I'm not sure about the reason behind this, though.

Body:
I have a roles list that filter a permissions list. The permissions list has a checkbox indicating that it is selected.

Each role has a list of associated permissions. When a role is selected, all available permissions are displayed and those already associated with them will be checked. By clicking on the checkbox of each permission you can associate or desesociate it.

But the select and unselect permission action does not work properly. I can not figure out what the problem. Can someone help me ? Thanks!!!

Code in Plunker

Page code

                {{role.name}}

                {{permission.name}}                  <input type="checkbox" class="pull-right" ng-checked="isSelected(permission.id) > -1" ng-click="clickPermission(permission)" ng-class="{active: permission.id == model.selectedPermission.id}" />

Controller code

app.controller('PermissionsToRoleController', function($scope) {

  $scope.model = {
    roles: [],
    permissions: [],
    selectedRole: null,
        selectedPermission: null
  };

  $scope.selectRole = function(role) {
    $scope.model.selectedRole = role;
  }

  var findRoles = function() {
    $scope.model.roles = [{id: 1, name: 'ADMIN', permissions: [{id: 1, name:'MASTER'}] },
                          {id: 2, name: 'USER',  permissions: [] }
                         ];

        $scope.model.permissions = [{id: 1, name: 'MASTER'}];

        $scope.model.selectedRole = $scope.model.roles[0];
  };

  $scope.clickPermission = function(permission) {
    $scope.model.selectedPermission = permission;
    var idx = $scope.isSelected(permission.id);
    if (idx > -1) {
      $scope.model.selectedRole.permissions.splice(idx, 1);
    } else {
      $scope.model.selectedRole.permissions.push(permission);
    }
  };

  $scope.isSelected = function(permissionId) {
    for (var i = 0; i < $scope.model.selectedRole.permissions.length ; i++) {
      if ($scope.model.selectedRole.permissions[i].id === permissionId) {
              return i;
      }
    }
    return -1;
  }

  findRoles();

});

Body:
The problem I found being the checkbox, while functions properly, the display won't "uncheck" when you click on it.

This can be fixed by changing the surrounding element to span instead of a

<span ng-repeat="permission in model.permissions" class="list-group-item">{{permission.name}}
    <input type="checkbox" class="pull-right" ng-checked="isSelected(permission.id) > -1" ng-click="clickPermission(permission)" ng-class="{active: permission.id == model.selectedPermission.id}" />
</span>

I'm not sure about the reason behind this, though.


问:
Is Office 2003 interop supported on Windows server 2008 ..?
I am getting below error while trying to run an interop dependent program on Windows server 2008 its running fine on Win Server 2003 and XP:

System.Runtime.InteropServices.COMException (0x800A03EC): Exception from HRESULT: 0x800A03EC
   at Microsoft.Office.Interop.Excel.WorkbookClass.SaveAs(.......)

According to Microsoft, Windows Server 2008 is not in list of suppoerted OS.

http://www.microsoft.com/downloads/en/details.aspx?familyid=3c9a983a-ac14-4125-8ba0-d36d67e0f4ad&displaylang=en

System Requirements

Supported Operating Systems:Windows 2000 Service Pack 3;Windows Server 2003;Windows XP

Can anybody please confirm this.. has anyone tried it ..?

答: .NET 1.1 is also a requirement, which I don't believe is on Windows Server 2008 (and really shouldn't be, just my opinion) which might be your problem.</p>


问:
Learning how to join tables but receiving an error that says "Not unique table"
I want to join two tables together which are the run table and the restaurant table. From the run table I need the run_id and the restaurant_id and from the restaurant table, I need the created_date so in the end, I have a table that contains the created_date of each restaurant. Both the run and restaurant_history tables have run_id's so that's how I know I can join them. I came up with something like:

```<code>SELECT run_id, restaurant_id, created_date FROM restaurant_history, run
JOIN run ON restaurant_history.run_id = run.run_id;
</code>```

But that gave me an error. Any help would be appreciated :)

(I'm fairly new to sql)

答:
Try this query</p>

```<code>SELECT run_id, restaurant_id, created_date
FROM restaurant_history
INNER JOIN run ON restaurant_history.restaurant_id= run.run_id;
</code>```

Body:
I want to join two tables together which are the run table and the restaurant table. From the run table I need the run_id and the restaurant_id and from the restaurant table, I need the created_date so in the end, I have a table that contains the created_date of each restaurant. Both the run and restaurant_history tables have run_id's so that's how I know I can join them. I came up with something like:

SELECT run_id, restaurant_id, created_date FROM restaurant_history, run
JOIN run ON restaurant_history.run_id = run.run_id;

But that gave me an error. Any help would be appreciated :)

(I'm fairly new to sql)

Body:
Try this query

SELECT run_id, restaurant_id, created_date
FROM restaurant_history
INNER JOIN run ON restaurant_history.restaurant_id= run.run_id;


问:
empty array in angular-schema-form
I'm using angular-schema-form in my project and trying to add an empty array in my model.

I expected that array type schema form will not contain any items but it actually pushed one object in my array and showed it in from.

How can I init form with no items in array?

html

```<code><div ng-app="app" ng-controller="Controller as ctr">
  <form sf-schema="ctr.schema" sf-form="ctr.form" sf-model="ctr.model"></form>
  {{ctr.model.comments}} - Where this object come from? This array was empty. Is it possible to keep it empty on load?
</div>
</code>```

js

```<code>var myApp = angular.module('app', ['schemaForm'])
  .controller("Controller", function() {
    this.schema = {
      "type": "object",
      "title": "Comment",
      "properties": {
        "comments": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "name": {
                "title": "Name",
                "type": "string"
              },
              "comment": {
                "title": "Comment",
                "type": "string",
                "maxLength": 20,
                "validationMessage": "Don't be greedy!"
              }
            }
          }
        }
      }
    };

    this.form = [{
      "key": "comments",
      "items": [
        "comments[]"
      ]
    }];

    this.model = {
      comments: [] // Empty array defined
    };
  });
</code>```

Jsfiddle

答:
The value you are looking for is startEmpty: true this will avoid pre-populating the array with an object.

Angular Schema Form: Array Documentation

The pre-population is defaulted to ensure that the form fields within an array are available when the form loads. The startEmpty: true value can override this behaviour.

Title: empty array in angular-schema-form

Body:
I'm using angular-schema-form in my project and trying to add an empty array in my model.

I expected that array type schema form will not contain any items but it actually pushed one object in my array and showed it in from.

How can I init form with no items in array?

html

  <form sf-schema="ctr.schema" sf-form="ctr.form" sf-model="ctr.model"></form>
  {{ctr.model.comments}} - Where this object come from? This array was empty. Is it possible to keep it empty on load?

js

var myApp = angular.module('app', ['schemaForm'])
  .controller("Controller", function() {
    this.schema = {
      "type": "object",
      "title": "Comment",
      "properties": {
        "comments": {
          "type": "array",
          "items": {
            "type": "object",
            "properties": {
              "name": {
                "title": "Name",
                "type": "string"
              },
              "comment": {
                "title": "Comment",
                "type": "string",
                "maxLength": 20,
                "validationMessage": "Don't be greedy!"
              }
            }
          }
        }
      }
    };

    this.form = [{
      "key": "comments",
      "items": [
        "comments[]"
      ]
    }];

    this.model = {
      comments: [] // Empty array defined
    };
  });

Jsfiddle


问:
WooCommerce: Hooking up product price in custom template
I am trying to get some product prices to show up in one custom template. Is there, perhaps, an integrated woocommerce function that given ID will give me products price?

Something along the lines of: woocommerce_productprice(423)

Basically, I have a custom page template as a catalog and I want to hook product prices up to that template, so whenever something changes, it automatically changes the price without me having to change the custom template.

Help please!

答:
$product = wc_get_product( $product_id );
$price = $product->get_price_html();

woocommerce 3.x, it working!