问:
Calling a variable from one function to the other (Python)
I'll start by saying that I did look up answers to this question and unfortunately, I just couldn't understand them or they didn't seem to work for me. This is of course down to me rather than the people who answered the question, so I do apologise in advance.

So pretty much I'm trying to call a variable that is assigned by the user from one function to the other, I'll give an example:

```<code>def function_one():
    a = input("What is your name?")
    return a
def function_two():
    print("Nice to meet you, "a)

function_one()
function_two()
</code>```

This of course does not work and I'm sure that is down to my own stupidity, I wasn't sure why at first because I saw other people saying to simply return the variable, which I did!

I also tried calling the variable from the other function, for example:

```<code>def function_two()
    a = function_one()
</code>```

but I realised that was pretty stupid since I'm just assigning that function  as a, so it's not going to work.

I'd appreciate some insight, I know these are not the kind of questions you'd expect but yeah... I'm clueless.

答:
I think what you want to do is take user input, store it in a variable, then greet the user using that variable:

```<code>def ask_for_users_name():
    name = input("What is your name?")
    return name
def greet_user(name):
    print("Nice to meet you, " + name)

users_name = ask_for_users_name()
greet_user(users_name)
</code>```

One important thing to note is that I had to concatenated the name with the string "Nice to meet you, " using the + operator.

Edit:

To answer to the question in the comments, you could do something like this in that case:

```<code>def ask_for_user_info():
    name = input("What is your name?")
    age = input("What is your age?")
    return name, age

user_name, user_age = ask_for_user_info()
</code>```

Best practice is to make functions that only do one thing, for many reasons, one is that the name of the function normally replaces any need for inline comments:

```<code>def ask_for_user_name():
    name = input("What is your name?")
    return name
def ask_for_user_age():
    age = input("What is your age?")
    return age
</code>```

In the case of the ask_for_user_info() method, it isn't immediately clear what exactly it is doing from the name.

Edit 2:

You could then use those two functions like this, in either order:

```<code>age = ask_for_user_age()
name = ask_for_user_name()
</code>```

or

```<code>name = ask_for_user_name()
</code>```

or

```<code>age = ask_for_user_name()
</code>```

Body:
I'll start by saying that I did look up answers to this question and unfortunately, I just couldn't understand them or they didn't seem to work for me. This is of course down to me rather than the people who answered the question, so I do apologise in advance.

So pretty much I'm trying to call a variable that is assigned by the user from one function to the other, I'll give an example:

def function_one():
    a = input("What is your name?")
    return a
def function_two():
    print("Nice to meet you, "a)

function_one()
function_two()

This of course does not work and I'm sure that is down to my own stupidity, I wasn't sure why at first because I saw other people saying to simply return the variable, which I did!

I also tried calling the variable from the other function, for example:

def function_two()
    a = function_one()

but I realised that was pretty stupid since I'm just assigning that function  as a, so it's not going to work.

I'd appreciate some insight, I know these are not the kind of questions you'd expect but yeah... I'm clueless.

Body:
I think what you want to do is take user input, store it in a variable, then greet the user using that variable:

def ask_for_users_name():
    name = input("What is your name?")
    return name
def greet_user(name):
    print("Nice to meet you, " + name)

users_name = ask_for_users_name()
greet_user(users_name)

One important thing to note is that I had to concatenated the name with the string "Nice to meet you, " using the + operator.

Edit:

To answer to the question in the comments, you could do something like this in that case:

def ask_for_user_info():
    name = input("What is your name?")
    age = input("What is your age?")
    return name, age

user_name, user_age = ask_for_user_info()

Best practice is to make functions that only do one thing, for many reasons, one is that the name of the function normally replaces any need for inline comments:

def ask_for_user_name():
    name = input("What is your name?")
    return name
def ask_for_user_age():
    age = input("What is your age?")
    return age

In the case of the ask_for_user_info() method, it isn't immediately clear what exactly it is doing from the name.

Edit 2:

You could then use those two functions like this, in either order:

age = ask_for_user_age()
name = ask_for_user_name()

or

name = ask_for_user_name()

or

age = ask_for_user_name()


来源: stackexchange

问:
Creating and returning a model with a relationship in Laravel
I have a couple of endpoints for getting/posting comments on notes in this application.

The GET endpoint uses Eloquent's with method to include the comments' author data with the response:

```<code>public function getComments(Note $note) {
    return $note->comments()->with(['author'])->get();
}
</code>```

How can I also include the author data when creating/returning an Eloquent model? Here is my current method:

```<code>public function postComment(Note $note, Request $request) {
    $user = $this->appUserRepo->getFromRequest($request);
    $text = $request->text;
    $comment = $note->comments()->create([
        'app_user_id' => $user->id,
        'text' => $text
    ]);
    return $comment;
}
</code>```

I'm looking for something like this (but this doesn't work):

```<code>public function postComment(Note $note, Request $request) {
    $user = $this->appUserRepo->getFromRequest($request);
    $text = $request->text;
    $comment = $note->comments()->create([
        'app_user_id' => $user->id,
        'text' => $text
    ]);
    return $comment->with(['author']);
}
</code>```

答:
You should try using:

```<code>$comment->load('author');
return $comment;
</code>```

to load author relationship for comment.

ContentLicense: CC BY-SA 3.0

Body:
I have a couple of endpoints for getting/posting comments on notes in this application.

The GET endpoint uses Eloquent's with method to include the comments' author data with the response:

public function getComments(Note $note) {
    return $note->comments()->with(['author'])->get();
}

How can I also include the author data when creating/returning an Eloquent model? Here is my current method:

public function postComment(Note $note, Request $request) {
    $user = $this->appUserRepo->getFromRequest($request);
    $text = $request->text;
    $comment = $note->comments()->create([
        'app_user_id' => $user->id,
        'text' => $text
    ]);
    return $comment;
}

I'm looking for something like this (but this doesn't work):

public function postComment(Note $note, Request $request) {
    $user = $this->appUserRepo->getFromRequest($request);
    $text = $request->text;
    $comment = $note->comments()->create([
        'app_user_id' => $user->id,
        'text' => $text
    ]);
    return $comment->with(['author']);
}

Body:
You should try using:

$comment->load('author');
return $comment;

to load author relationship for comment.


问:
Using .Get() in a foreach versus generating a list beforehand C#
I have a question regarding performance that I'm curious about. Is it better (performance, not opinion wise) to do the below:

```<code>    foreach (var Obj in SomeData.GetType().GetProperties())
    {
      // Do work
    }
</code>```

Or should one do something like the below instead?

```<code>List<object> DataProperties = SomeData.GetType().GetProperties();
foreach (var Obj in DataProperties)
{
// Do work
}
</code>```

(Which either could also be a (int i = 0; i < [Object].Count; i++) too, I'm not sure if that affects performance as far as using the index versus the object itself)

I would assume the .GetType().GetProperties() enumerator will take some overhead if calling it each time, but will it create more overhead than creating a list and enumerating the object properties once? Or in the end (on a large scale) does the variable performance difference so small that either way would be fine?

I appreciate the feedback!

答: These are identical.  There would be no difference in performance.  System.Type.GetProperties() returns PropertyInfo[], not List<object>.  It would be more expensive to construct a List<object> from PropertyInfo[], e.g. DataProperties = new List<object>(SomeData.GetType().GetProperties()); would have additional overhead.

Body:
I have a question regarding performance that I'm curious about. Is it better (performance, not opinion wise) to do the below:

    foreach (var Obj in SomeData.GetType().GetProperties())
    {
      // Do work
    }

Or should one do something like the below instead?

List<object> DataProperties = SomeData.GetType().GetProperties();
foreach (var Obj in DataProperties)
{
// Do work
}

(Which either could also be a (int i = 0; i < [Object].Count; i++) too, I'm not sure if that affects performance as far as using the index versus the object itself)

I would assume the .GetType().GetProperties() enumerator will take some overhead if calling it each time, but will it create more overhead than creating a list and enumerating the object properties once? Or in the end (on a large scale) does the variable performance difference so small that either way would be fine?

I appreciate the feedback!


问:
tkinter not installed properly in Anaconda Python 2.7 Win64
I believe from this post that this is not an uncommon issue with tkinter and new downloads of Python 2.7 (after re-downloading from 2016 on). I am using the Anaconda 2.7 for win64 on a Windows 7 machine. The filepaths seem almost identical to what is described here, except for "Anaconda2" instead of "Python27"; the "tcl" folder is in it's own directory in C:/Users/user:2312900/tcl and not in the "lib" directory.

Is there any way to fix this for Anaconda? That I tried what was described in the post, but it didn't work for me.

Is there any way to manually install a 64bit python 2.7 compatible wheel for tkinter? Does anyone know of any other packages to make simple GUI's with Python if this is an irreconcilable issue with the Annaconda distribution. I have a lot of other packages that were painfully installed that I do not want to use something else.

答:
Do you have user on your Windows called "user:2312900"? Python (and some other programs) don't like paths with special characters like colon ":". Try to install all your needed programs (Python, Tkinter, etc) in the path without special characters and without spaces " ".

For example: c:\ProgramData\Anaconda3\ or c:\Python27\


问:
How to create a test which waits for record appearance in the database?
I have a method which starts generating some report in another thread while the main thread returns a link to a google folder where created report should be uploaded. After report was created, it inserts a record with some information in the database.

```<code>public Link startReportCreation(ReportRequest reportRequest) {
    Link link = /** some logic **/;
    taskExecutor.execute(() -> {
        /** report creation logic **/
    });
    return link;
</code>```

So what is the best way to test the info of the inserted record without modifying the startReportCreation method?

Update

Currently I have while (taskExecutor.getActiveCount() != 0); kind of lock, which indicates that taskExecutor ended its execution and I can check the database. But I think there is a better approach.

Btw sry for misleading, that is not a unit test, it's just an executor to manually test methods on real data.

Solved

So I've managed to refactor my startReportCreation method and instead of simple taskExecutor I used CompletableFuture, so now it's looks like this:

```<code>public CompletableFuture<Link> startReportCreation(ReportRequest reportRequest) {
    /** some logic **/
    return CompletableFuture.supplyAsync(() -> {
        Link link = /** some logic **/;
        return link;
    }, taskExecutor);
}
</code>```

So in production code I use CompletableFuture.getNow() method and in tests I use CompletableFuture.get() to wait for the report creation.

答:
First of all remember the FIRST principles of unit testing.
F: Fast
I: Independent
R: Repeatable
S: Small
T: Timely

Here you are a linik to review them in detail: https://github.com/ghsukumar/SFDC_Best_Practices/wiki/F.I.R.S.T-Principles-of-Unit-Testing

To achieve what you need, you must prepare the test in this way:

```<code>import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;

public class ReportGeneratorTest {

    //This is executed before each @Test, generally is used for prepare the ambient, instantiate services, start servers and so on.
    @Before
    public void setUp() throws IOException {
        report = MyReportService.createReport();
    }

    //This is executed after each @Test generally this used for tear down your servers or data bases, or delete all the records inserted
    @After
    public void tearDown() {
        MyReportService.deleteById(10);
    }

    @Test
    public void verifyInsertion() throws Exception {
        //Here you can verify that the record of your serive or logic it's ok
        assertTrue(MyReportService.getLastId() > 10); //Or whatever
    }
}
</code>```

EDIT:

From the documentation of concurrent unit: https://github.com/jhalterman/concurrentunit/blob/master/src/test/java/net/jodah/concurrentunit/WaiterTest.java
You could create a Thread and wait for it.

```<code>@Test
public class WaiterTest {
  @Test
  public void shouldSupportMultipleThreads() throws Throwable {
    final Waiter waiter = new Waiter();

    for (int i = 0; i < 5; i++)
      new Thread(new Runnable() {
        public void run() {
          waiter.assertTrue(true);
          waiter.resume();
        }
      }).start();

    waiter.await(0);
  }
</code>```

Body:
I have a method which starts generating some report in another thread while the main thread returns a link to a google folder where created report should be uploaded. After report was created, it inserts a record with some information in the database.

public Link startReportCreation(ReportRequest reportRequest) {
    Link link = /** some logic **/;
    taskExecutor.execute(() -> {
        /** report creation logic **/
    });
    return link;

So what is the best way to test the info of the inserted record without modifying the startReportCreation method?

Update

Currently I have while (taskExecutor.getActiveCount() != 0); kind of lock, which indicates that taskExecutor ended its execution and I can check the database. But I think there is a better approach.

Btw sry for misleading, that is not a unit test, it's just an executor to manually test methods on real data.

Solved

So I've managed to refactor my startReportCreation method and instead of simple taskExecutor I used CompletableFuture, so now it's looks like this:

public CompletableFuture<Link> startReportCreation(ReportRequest reportRequest) {
    /** some logic **/
    return CompletableFuture.supplyAsync(() -> {
        Link link = /** some logic **/;
        return link;
    }, taskExecutor);
}

So in production code I use CompletableFuture.getNow() method and in tests I use CompletableFuture.get() to wait for the report creation.

Body:
First of all remember the FIRST principles of unit testing.
F: Fast
I: Independent
R: Repeatable
S: Small
T: Timely

Here you are a linik to review them in detail: https://github.com/ghsukumar/SFDC_Best_Practices/wiki/F.I.R.S.T-Principles-of-Unit-Testing

To achieve what you need, you must prepare the test in this way:

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import static org.junit.Assert.assertTrue;

public class ReportGeneratorTest {

    //This is executed before each @Test, generally is used for prepare the ambient, instantiate services, start servers and so on.
    @Before
    public void setUp() throws IOException {
        report = MyReportService.createReport();
    }

    //This is executed after each @Test generally this used for tear down your servers or data bases, or delete all the records inserted
    @After
    public void tearDown() {
        MyReportService.deleteById(10);
    }

    @Test
    public void verifyInsertion() throws Exception {
        //Here you can verify that the record of your serive or logic it's ok
        assertTrue(MyReportService.getLastId() > 10); //Or whatever
    }
}

EDIT:

From the documentation of concurrent unit: https://github.com/jhalterman/concurrentunit/blob/master/src/test/java/net/jodah/concurrentunit/WaiterTest.java
You could create a Thread and wait for it.

@Test
public class WaiterTest {
  @Test
  public void shouldSupportMultipleThreads() throws Throwable {
    final Waiter waiter = new Waiter();

    for (int i = 0; i < 5; i++)
      new Thread(new Runnable() {
        public void run() {
          waiter.assertTrue(true);
          waiter.resume();
        }
      }).start();

    waiter.await(0);
  }


问:
All Node.js/Express routes returning 404 on hosted server
I recently began building an app with node.js. After some time I wanted to move it onto my hosting account to really test it.

First I installed nodejs from source.
Then I changed nothing to the code except for Database login. When I ran it, there were no error. Excitedly I tried it out. To my dismay, I got a 404 for every single route I had programed.

For example:

```<code>router.route('/new')
.post(function(req, res){
    //My Route Code
});

app.use('/api', router);
</code>```

Then I go to:

mywebsite.com/api/new

This returns a 404 Not Found Error from my apache server.

I would also like to note that I am using I am using Shared Hosting, and I have also thoroughly tested my code offline on my test server.

How can I fix it so that my code actually routes my request?

答:
sudo service apache2 remove

node app.js

If you need node on apache then see this documentation

Apache and Node.js on the Same Server

Body:
I recently began building an app with node.js. After some time I wanted to move it onto my hosting account to really test it.

First I installed nodejs from source.
Then I changed nothing to the code except for Database login. When I ran it, there were no error. Excitedly I tried it out. To my dismay, I got a 404 for every single route I had programed.

For example:

router.route('/new')
.post(function(req, res){
    //My Route Code
});

app.use('/api', router);

Then I go to:

mywebsite.com/api/new

This returns a 404 Not Found Error from my apache server.

I would also like to note that I am using I am using Shared Hosting, and I have also thoroughly tested my code offline on my test server.

How can I fix it so that my code actually routes my request?


问:
Loading a string containing a list of JSON objects
I have string that has a list of JSON objects in it. How can I access each JSON obj? json.loads() does not work since the string is a list of objects and does not have the proper format.

Here is the format of the string I have:

```<code>myString = '[{"name": "John", "ID": "1"}, {"name": "Jane", "ID": "2"}]'
</code>```

UPDATE:

There is a particular line in the input file that seems to generate the below error when I try to read it (I have isolated that line: https://www.dropbox.com/s/8i9aj64i5r8dmgp/line.00?dl=0):

```<code>            for line in inFile:

            Traceback (most recent call last):
              File "../filterBios.py", line 29, in <module>
                line = json.loads(line);
              File "/N/soft/rhel6/python/2.7.3/lib/python2.7/json/__init__.py", line 326, in loads
                return _default_decoder.decode(s)
              File "/N/soft/rhel6/python/2.7.3/lib/python2.7/json/decoder.py", line 366, in decode
                obj, end = self.raw_decode(s, idx=_w(s, 0).end())
              File "/N/soft/rhel6/python/2.7.3/lib/python2.7/json/decoder.py", line 382, in raw_decode
                obj, end = self.scan_once(s, idx)
            ValueError: Unterminated string starting at: line 1 column 84647 (char 84647)
</code>```

I cannot figure out what is causing the issue.

答:
I figured it out! The input text file had a NEL character and it turns out that:
    codec.open()
cannot handle that. Use instead:
    io.open()
and the " ValueError: Unterminated string" error will go away!</p>

Body:
I have string that has a list of JSON objects in it. How can I access each JSON obj? json.loads() does not work since the string is a list of objects and does not have the proper format.

Here is the format of the string I have:

myString = '[{"name": "John", "ID": "1"}, {"name": "Jane", "ID": "2"}]'

UPDATE:

There is a particular line in the input file that seems to generate the below error when I try to read it (I have isolated that line: https://www.dropbox.com/s/8i9aj64i5r8dmgp/line.00?dl=0):

            for line in inFile:

            Traceback (most recent call last):
              File "../filterBios.py", line 29, in <module>
                line = json.loads(line);
              File "/N/soft/rhel6/python/2.7.3/lib/python2.7/json/__init__.py", line 326, in loads
                return _default_decoder.decode(s)
              File "/N/soft/rhel6/python/2.7.3/lib/python2.7/json/decoder.py", line 366, in decode
                obj, end = self.raw_decode(s, idx=_w(s, 0).end())
              File "/N/soft/rhel6/python/2.7.3/lib/python2.7/json/decoder.py", line 382, in raw_decode
                obj, end = self.scan_once(s, idx)
            ValueError: Unterminated string starting at: line 1 column 84647 (char 84647)

I cannot figure out what is causing the issue.


问:
Full Text Search as well as Terms Search on same filed of Elasticsearch
I'm from MySql background. So I don't know much about elasticsearch and it's working.

Here is my requirements

There will be table of resulted records with sorting option on all the column. There will be filter option from where user will select multiple values for multiple columns (e.g, City should be from City1, City2, City3 and Category should be from Cat2, Cat22, Cat6). There will be also search bar where user will enter some text and full text search will be applied on some fields (i.e, City, Area etc).

This image will give better understanding.

Where I'm facing problem is Full Text Search. I have tried some mapping but every time I have to compromise either on Full Text Search or Terms Search. So I think there is no any way to apply both search on same field. But as I told, I don;t know much about elasticsearch. So if any one have solution, it will be appreciated.

Here is what I have applied currently which makes sorting and Terms Searching enable but Full Text Search is not working.

```<code>{
    "mappings":{
        "my_type":{
            "properties":{
                "city":{
                    "type":"string",
                    "index":"not_analyzed"
                },
                "category":{
                    "type":"string",
                    "index":"not_analyzed"
                },
                "area":{
                    "type":"string",
                    "index":"not_analyzed"
                },
                "zip":{
                    "type":"string",
                    "index":"not_analyzed"
                },
                "state":{
                    "type":"string",
                    "index":"not_analyzed"
                }
            }
        }
    }
}
</code>```

答:
Full-text search won't work on not_analyzed fields and sorting won't work on analyzed fields.

You need to use multi-fields.

It is often useful to index the same field in different ways for different purposes. This is the purpose of multi-fields. For instance, a string field could be mapped as a text field for full-text search, and as a keyword field for sorting or aggregations:

For example :

```<code>{
  "mappings": {
    "my_type": {
      "properties": {
        "city": {
          "type": "text",
          "fields": {
            "raw": {
              "type":  "keyword"
            }
          }
        } ...
      }
    }
  }
}
</code>```

Use the dot notation to sort by city.raw :

```<code>{
  "query": {
    "match": {
      "city": "york"
    }
  },
  "sort": {
    "city.raw": "asc"
  }
}
</code>```

Body:
I'm from MySql background. So I don't know much about elasticsearch and it's working.

Here is my requirements

There will be table of resulted records with sorting option on all the column. There will be filter option from where user will select multiple values for multiple columns (e.g, City should be from City1, City2, City3 and Category should be from Cat2, Cat22, Cat6). There will be also search bar where user will enter some text and full text search will be applied on some fields (i.e, City, Area etc).

This image will give better understanding.

Where I'm facing problem is Full Text Search. I have tried some mapping but every time I have to compromise either on Full Text Search or Terms Search. So I think there is no any way to apply both search on same field. But as I told, I don;t know much about elasticsearch. So if any one have solution, it will be appreciated.

Here is what I have applied currently which makes sorting and Terms Searching enable but Full Text Search is not working.

{
    "mappings":{
        "my_type":{
            "properties":{
                "city":{
                    "type":"string",
                    "index":"not_analyzed"
                },
                "category":{
                    "type":"string",
                    "index":"not_analyzed"
                },
                "area":{
                    "type":"string",
                    "index":"not_analyzed"
                },
                "zip":{
                    "type":"string",
                    "index":"not_analyzed"
                },
                "state":{
                    "type":"string",
                    "index":"not_analyzed"
                }
            }
        }
    }
}

Body:
Full-text search won't work on not_analyzed fields and sorting won't work on analyzed fields.

You need to use multi-fields.

It is often useful to index the same field in different ways for different purposes. This is the purpose of multi-fields. For instance, a string field could be mapped as a text field for full-text search, and as a keyword field for sorting or aggregations:

For example :

{
  "mappings": {
    "my_type": {
      "properties": {
        "city": {
          "type": "text",
          "fields": {
            "raw": {
              "type":  "keyword"
            }
          }
        } ...
      }
    }
  }
}

Use the dot notation to sort by city.raw :

{
  "query": {
    "match": {
      "city": "york"
    }
  },
  "sort": {
    "city.raw": "asc"
  }
}


问:
Fixed div inside scrolling static div
I have an element container, which must remain static. Inside it lies fix, which I need to be fixed when container overflows and I scroll in it.

Example:

```<code><div id="container" style="width: 850px; height: 200px; position: static;">
    <div id="fix"></div>
    <div id="otherStuff" style="width: 2000px;"></div>
</div>
</code>```

Can I do this with CSS?

答:
You can put the content you want to overflow in an element with overflow-x: scroll, and the #fix element will stay where it is.

.overflow {
  overflow-x: scroll;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="container" style="width: 850px; height: 200px; position: static;">
  <div id="fix">fix</div>
  <div class="overflow">
    <div id="otherStuff" style="width: 2000px;">otherstuff</div>
  </div>
</div></code>```

Title: Fixed div inside scrolling static div

Body:
I have an element container, which must remain static. Inside it lies fix, which I need to be fixed when container overflows and I scroll in it.

Example:

Can I do this with CSS?

Body:
You can put the content you want to overflow in an element with overflow-x: scroll, and the #fix element will stay where it is.

.overflow {
  overflow-x: scroll;
}

<div id="container" style="width: 850px; height: 200px; position: static;">
  <div id="fix">fix</div>
  <div class="overflow">
    <div id="otherStuff" style="width: 2000px;">otherstuff</div>
  </div>
</div>


问:
ChromeOptions and DesiredCapabilities relations in Selenium and C#
I've been searching for the correct documentation on how to use ChromeOptions and DesiredCapabilities in the atmosphere of Selenium and C#, but since it's all open sourced, I only find suggestions (and they are not helping sometimes). My question today is how to setup the correct relation between ChromeOptions and DesiredCapabilities. Seems like I'm doing everything correctly, but still getting System.InvalidOperationException: unknown error:cannot parse capability: chromeOptions from unknown error: unrecognized chrome option:Arguments My code is following:

```<code> private static ChromeOptions Ops()
        {
            var options = new ChromeOptions();
            options.AddArgument("--no-startup-window");
            options.BinaryLocation = @"C:\path\path\path\chromedriver.exe";
            return options;
        }
  private static DesiredCapabilities Caps()
        {
            DesiredCapabilities caps = new DesiredCapabilities();
            caps.SetCapability(CapabilityType.BrowserName, "chrome");
            caps.SetCapability(ChromeOptions.Capability,Ops().ToCapabilities());
            return caps;
        }
IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), Caps());
</code>```

Can't find a place where incorrect Arguments are passing. Has anybody faced the same issues? This is ChromeDriver version 2.28 and selenium WebDriver v 3.3.0 Google Chrome browser version is 52.

答:
You don't need to set the browser name; ChromeOptions does that for you.

According to this comment

The .NET bindings are moving toward a pattern where DesiredCapabilites should not be
  used directly, even with RemoteWebDriver. To facilitate that, the ChromeOptions class
  has a ToCapabilities() method

And there's this comment

Much like --disable-javascript, the chromedriver will not work if you use --no-startup-window.
  It needs to launch a window to establish the connection with the AutomationProxy.

So that gets us to this:

```<code>var options = new ChromeOptions();
options.BinaryLocation = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";

IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities());
</code>```

However, are you actually running a grid? If you're testing on a single machine it's even simpler:

```<code>IWebDriver driver = new ChromeDriver();
</code>```

Body:
I've been searching for the correct documentation on how to use ChromeOptions and DesiredCapabilities in the atmosphere of Selenium and C#, but since it's all open sourced, I only find suggestions (and they are not helping sometimes). My question today is how to setup the correct relation between ChromeOptions and DesiredCapabilities. Seems like I'm doing everything correctly, but still getting System.InvalidOperationException: unknown error:cannot parse capability: chromeOptions from unknown error: unrecognized chrome option:Arguments My code is following:

 private static ChromeOptions Ops()
        {
            var options = new ChromeOptions();
            options.AddArgument("--no-startup-window");
            options.BinaryLocation = @"C:\path\path\path\chromedriver.exe";
            return options;
        }
  private static DesiredCapabilities Caps()
        {
            DesiredCapabilities caps = new DesiredCapabilities();
            caps.SetCapability(CapabilityType.BrowserName, "chrome");
            caps.SetCapability(ChromeOptions.Capability,Ops().ToCapabilities());
            return caps;
        }
IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), Caps());

Can't find a place where incorrect Arguments are passing. Has anybody faced the same issues? This is ChromeDriver version 2.28 and selenium WebDriver v 3.3.0 Google Chrome browser version is 52.

Body:
You don't need to set the browser name; ChromeOptions does that for you.

According to this comment

The .NET bindings are moving toward a pattern where DesiredCapabilites should not be
  used directly, even with RemoteWebDriver. To facilitate that, the ChromeOptions class
  has a ToCapabilities() method

And there's this comment

Much like --disable-javascript, the chromedriver will not work if you use --no-startup-window.
  It needs to launch a window to establish the connection with the AutomationProxy.

So that gets us to this:

var options = new ChromeOptions();
options.BinaryLocation = @"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe";

IWebDriver driver = new RemoteWebDriver(new Uri("http://localhost:4444/wd/hub"), options.ToCapabilities());

However, are you actually running a grid? If you're testing on a single machine it's even simpler:

IWebDriver driver = new ChromeDriver();


问:
How To Get user name MVC for Represent in a PermisoAttribute
I have a PermisoAttribute like this

```<code>public class PermisoAttribute : ActionFilterAttribute
        {
            public string username { get; set; }
            public int ProgramId { get; set; }
            public int ModuleId { get; set; }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                base.OnActionExecuting(filterContext);

                if (!permisos(this.username,this.ProgramId,this.ModuleId))
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Home",
                        action = "Denegado"
                    }));
                }
            }
        }
</code>```

and this use permisos for know if the user have permission or not, that class return true o false. But when I use the PermisoAttribute in the controller a recive the behavior error

Error CS0120  An object reference is required for the non-static field,
  method, or property 'Controller.User'

I use the permissoAttribute like this

```<code>[HttpGet]
[Permiso(username = User.Identity.Name, ModuleId = 3, ProgramId = 2)]
public ActionResult Transactions()
{
  //do something here
}
</code>```

I use this code User.Identity.Name for send the user to the PermisoAttribute.

答:
Just change ActionFilterAttribute for don't received a user name Like this

```<code>  public class PermisoAttribute : ActionFilterAttribute
        {
            public string username = HttpContext.Current.User.Identity.Name; // { get; set; }
            public string Program { get; set; }
            public string Module { get; set; }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                base.OnActionExecuting(filterContext);

                if (!permisos(this.username, this.Program, this.Module))
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Home",
                        action = "Denegado"
                    }));
                }
            }
        }
</code>```

and get user name with HttpContext.Current.User.Identity.Name and for call PermisoAttribute just send  [Permiso(Module = "modulename", Program = "programaname")]

Body:
I have a PermisoAttribute like this

public class PermisoAttribute : ActionFilterAttribute
        {
            public string username { get; set; }
            public int ProgramId { get; set; }
            public int ModuleId { get; set; }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                base.OnActionExecuting(filterContext);

                if (!permisos(this.username,this.ProgramId,this.ModuleId))
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Home",
                        action = "Denegado"
                    }));
                }
            }
        }

and this use permisos for know if the user have permission or not, that class return true o false. But when I use the PermisoAttribute in the controller a recive the behavior error

Error CS0120  An object reference is required for the non-static field,
  method, or property 'Controller.User'

I use the permissoAttribute like this

[HttpGet]
[Permiso(username = User.Identity.Name, ModuleId = 3, ProgramId = 2)]
public ActionResult Transactions()
{
  //do something here
}

I use this code User.Identity.Name for send the user to the PermisoAttribute.

Body:
Just change ActionFilterAttribute for don't received a user name Like this

  public class PermisoAttribute : ActionFilterAttribute
        {
            public string username = HttpContext.Current.User.Identity.Name; // { get; set; }
            public string Program { get; set; }
            public string Module { get; set; }

            public override void OnActionExecuting(ActionExecutingContext filterContext)
            {
                base.OnActionExecuting(filterContext);

                if (!permisos(this.username, this.Program, this.Module))
                {
                    filterContext.Result = new RedirectToRouteResult(new RouteValueDictionary(new
                    {
                        controller = "Home",
                        action = "Denegado"
                    }));
                }
            }
        }

and get user name with HttpContext.Current.User.Identity.Name and for call PermisoAttribute just send  [Permiso(Module = "modulename", Program = "programaname")]


问:
How does one create a Python virtualenv in Jenkins?
I am using a Makefile to provide consistent single commands for setting up a virtualenv, running tests, etc.  I have configured my Jenkins instance to pull from a mercurial repo and then run "make virtualenv", which does this:

```<code>virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && pip install -r requirements.txt
</code>```

But for some reason it insists on using the system-installed pip and trying to install my package dependencies in the system site-packages rather than the virtualenv:

```<code>error: could not create '/usr/local/lib/python2.7/dist-packages/flask': Permission denied
</code>```

If I add some debugging commands and explicitly point to the pip in my virtualenv, things get even more confusing:

```<code>virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && ls -l bin && which pip && pwd && ./bin/pip install -r requirements.txt
</code>```

Which generates the following output:

```<code>New python executable in ./bin/python2.7
Not overwriting existing python script ./bin/python (you must use ./bin/python2.7)
Installing setuptools, pip...done.
Running virtualenv with interpreter /usr/bin/python2.7
</code>```

It appears Jenkins doesn't rebuild the environment from scratch for each build, which strikes me as an odd choice, but shouldn't effect my immediate issue

The output from the "ls -l bin" shows pip to be installed in the virtualenv and executable:

```<code>-rw-r--r-- 1 jenkins jenkins    2248 Apr  9 21:14 activate
-rw-r--r-- 1 jenkins jenkins    1304 Apr  9 21:14 activate.csh
-rw-r--r-- 1 jenkins jenkins    2517 Apr  9 21:14 activate.fish
-rw-r--r-- 1 jenkins jenkins    1129 Apr  9 21:14 activate_this.py
-rwxr-xr-x 1 jenkins jenkins     278 Apr  9 21:14 easy_install
-rwxr-xr-x 1 jenkins jenkins     278 Apr  9 21:14 easy_install-2.7
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip2
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip2.7
lrwxrwxrwx 1 jenkins jenkins       9 Apr 10 19:31 python -> python2.7
lrwxrwxrwx 1 jenkins jenkins       9 Apr 10 19:31 python2 -> python2.7
-rwxr-xr-x 1 jenkins jenkins 3349512 Apr 10 19:31 python2.7
</code>```

The output of "which pip" seems to want to use the correct one:

```<code>/var/lib/jenkins/jobs/Run Tests/workspace/bin/pip
</code>```

My current working directory is what I expect it to be:

```<code>/var/lib/jenkins/jobs/Run Tests/workspace
</code>```

But... wtf?

```<code>/bin/sh: 1: ./bin/pip: Permission denied
make: *** [virtualenv] Error 126
Build step 'Execute shell' marked build as failure
Finished: FAILURE
</code>```

答:
I have been using python virtualenvs with Jenkins every day in the last two years, at multiple companies and for small side projects and cannot say I found "THE" answer. Still, I hope that sharing my experience will help others save time. Hopefully I will get further feedback in order to make the decision easier.

Avoid ShiningPanda - it's not well maintained, incompatible with Jenkins2 pipelines and prevents execution of jobs in parallel. Also it has the bad habit of leaving orphan environments on disk.

DIY via bash and virtualenv is my current favourite. Create it inside $WORKSPACE and, if not always cleaning, run relocatable  before activating them. This is because jenkins workspace folder disk location can change between executions of job N and N+1.

If you use multiple builders that do need the same virtualenv, the easiest way is to dump your environment to a file and source it at the beginning of the new builder.

To ease the maintenance I am planning to investigate these:

direnvm

virtualenv-wrapper (mkvirtualenv)

pyenv

If you hit the shebang command line limits the best thing to do is to change your jenkins home directory to just /j.

Body:
I am using a Makefile to provide consistent single commands for setting up a virtualenv, running tests, etc.  I have configured my Jenkins instance to pull from a mercurial repo and then run "make virtualenv", which does this:

virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && pip install -r requirements.txt

But for some reason it insists on using the system-installed pip and trying to install my package dependencies in the system site-packages rather than the virtualenv:

error: could not create '/usr/local/lib/python2.7/dist-packages/flask': Permission denied

If I add some debugging commands and explicitly point to the pip in my virtualenv, things get even more confusing:

virtualenv --python=/usr/bin/python2.7 --no-site-packages . && . ./bin/activate && ls -l bin && which pip && pwd && ./bin/pip install -r requirements.txt

Which generates the following output:

New python executable in ./bin/python2.7
Not overwriting existing python script ./bin/python (you must use ./bin/python2.7)
Installing setuptools, pip...done.
Running virtualenv with interpreter /usr/bin/python2.7

It appears Jenkins doesn't rebuild the environment from scratch for each build, which strikes me as an odd choice, but shouldn't effect my immediate issue

The output from the "ls -l bin" shows pip to be installed in the virtualenv and executable:

-rw-r--r-- 1 jenkins jenkins    2248 Apr  9 21:14 activate
-rw-r--r-- 1 jenkins jenkins    1304 Apr  9 21:14 activate.csh
-rw-r--r-- 1 jenkins jenkins    2517 Apr  9 21:14 activate.fish
-rw-r--r-- 1 jenkins jenkins    1129 Apr  9 21:14 activate_this.py
-rwxr-xr-x 1 jenkins jenkins     278 Apr  9 21:14 easy_install
-rwxr-xr-x 1 jenkins jenkins     278 Apr  9 21:14 easy_install-2.7
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip2
-rwxr-xr-x 1 jenkins jenkins     250 Apr  9 21:14 pip2.7
lrwxrwxrwx 1 jenkins jenkins       9 Apr 10 19:31 python -> python2.7
lrwxrwxrwx 1 jenkins jenkins       9 Apr 10 19:31 python2 -> python2.7
-rwxr-xr-x 1 jenkins jenkins 3349512 Apr 10 19:31 python2.7

The output of "which pip" seems to want to use the correct one:

/var/lib/jenkins/jobs/Run Tests/workspace/bin/pip

My current working directory is what I expect it to be:

/var/lib/jenkins/jobs/Run Tests/workspace

But... wtf?

/bin/sh: 1: ./bin/pip: Permission denied
make: *** [virtualenv] Error 126
Build step 'Execute shell' marked build as failure
Finished: FAILURE

ContentLicense: CC BY-SA 4.0


问:
In Java, how can I use .equalsIgnoreCase to apply to multiple strings?
In Java, how can I use equalsIgnoreCase to apply to multiple strings?
I am new to Java and I want the user to enter a or c or e in either lowercase or uppercase.

答:
String equalsIgnoreCase()

This method compares the two given strings on the basis of content of the string irrespective of case of the string. It is like equals() method but doesn't check case. If any character is not matched, it returns false otherwise it returns true.

As the example

```<code> public class EqualsIgnoreCaseExample{
       public static void main(String args[]){
         String s1="java";
         String s2="java";
         String s3="JAVA";
         String s4="python";

         System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same
         System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored
         System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same
    }}
</code>```

Body:
String equalsIgnoreCase()

This method compares the two given strings on the basis of content of the string irrespective of case of the string. It is like equals() method but doesn't check case. If any character is not matched, it returns false otherwise it returns true.

As the example

 public class EqualsIgnoreCaseExample{
       public static void main(String args[]){
         String s1="java";
         String s2="java";
         String s3="JAVA";
         String s4="python";

         System.out.println(s1.equalsIgnoreCase(s2));//true because content and case both are same
         System.out.println(s1.equalsIgnoreCase(s3));//true because case is ignored
         System.out.println(s1.equalsIgnoreCase(s4));//false because content is not same
    }}


问:
How do i check i am Inside of House or outside of House using android Device?
Have any sensor that detects the android device is inside of a house or outside of
 a house. If I use light sensor it gives me an error because when I detect in night mood its give me wrong information. How do I check that?</p>

答:
That is not currently possible. Device location can be acquired using cell towers, GPS or marked WIFI spots if it is connected to one.

Whether you are indoors or not is a different issue all together and in most cases, GPS does not penetrate buildings well while cell tower signal deteriorates especially in basements.


问:
Javascript Uncaught TypeError: Cannot read property 'append' of null in code
I have this html page with a javascript function on it. It is not returning anything on the page but I am getting this on the console:

Uncaught TypeError: Cannot read property 'append' of null at index.html:82

Here is the full page code:

```<code><!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>

    <script>

function checkDistance(lat1,lon1,lat2,lon2) {
  var R = 6371; // Radius of the earth in km
  var dLat = deg2rad(lat2-lat1);  // deg2rad below
  var dLon = deg2rad(lon2-lon1);
  var a =
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(deg2rad(lat1)) * Math.cos(deg2rad(lat2)) *
    Math.sin(dLon/2) * Math.sin(dLon/2)
    ;
  var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
  var d = R * c; // Distance in km
  return d;
}

function deg2rad(deg) {
  return deg * (Math.PI/180)
}

var fixedlat = 51.714236;
var fixedlon = 50.710236;
var miles = 20;
var distanceLimit = miles * 1.6; //(km)
var data = [
  {
    "name": "Paul Brooks",
    "location": {
      "lat": 51.714236,
      "lon": 50.710236
    }
  },
  {
    "name": "Jason Orange",
    "location": {
      "lat": 52.030778298795856,
      "lon": 0.364888567109396
    }
  },
  {
    "name": "Mark Way",
    "location": {
      "lat": 53.41899784623413,
      "lon": -1.9138465628943413
    }
  },
  {
    "name": "Ben Bon",
    "location": {
      "lat": 52.30976192959104,
      "lon": -0.4014670363034498
    }
  },
  {
    "name": "Chris Col",
    "location": {
      "lat": 53.45301856182801,
      "lon": -1.8765834388107732
    }
  },
  {
    "name": "Von Van",
    "location": {
      "lat": 53.82771812914788,
      "lon": -0.7563793003592991
    }
  }
];

for(var i = 0;i < data.length;i++){

    var result = checkDistance(fixedlat,fixedlon,data[i].location.lat,data[i].location.lon);

    if(result <= distanceLimit){
        var resultList = document.getElementById('resultList');
        resultList.append(data[i].name + ', ');
    }
}

    </script>

</head>
<body>

   <div id="resultList"></div>

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

Why I'm I getting this error and how can I fix it?

Body:
I have this html page with a javascript function on it. It is not returning anything on the page but I am getting this on the console:

Uncaught TypeError: Cannot read property 'append' of null at index.html:82

Here is the full page code:

<!DOCTYPE html>

  <meta charset="utf-8" />
  <title></title>

Why I'm I getting this error and how can I fix it?

Body:
The script begins executing before the DOM is fully loaded, so the call to document.getElementById('resultList'); returns null.

One way to fix, move your <script> tag to appear after the <body> element

Another way, wrap your code in a call to document.addEventListener:

document.addEventListener("DOMContentLoaded", function(event) {
   // copy code here
});

Or use jQuery:

$(document).ready(function(event) {
   // copy code here
});


问:
python function for list of lists n long, with each element 0-m
I need to make a function so that I can put in two parameters, an order, and a max, and return a list of all of the lists 'order' long and with each element ranging from 0 to 'max'. I suspect I may need to use recursion, but I am getting lost in this.

so order = 2 max = 3 should return

```<code>[[0,0], [0,1], [0,2], [0,3], [1,0], [1,1], ... ,[3,3]]
</code>```

and order=4, max=5 should return

```<code>[[0,0,0,0], [0,0,0,1], [0,0,0,2], ...  [3,3,3,3]]
</code>```

Thanks for the help

答:
Here's a function that uses recursion to solve the problem. When you are dealing with recursion, make sure you have a base case and a general case.

```<code>def recurseNumbers(order, mx):
    if order == 1:
        return [[n] for n in range(mx + 1)]
    else:
        total_array = []
        for num in range(mx + 1):
            numbers = recurseNumbers(order - 1, mx)
            for number in numbers:
                total_array.append([num] + number)
        return total_array
</code>```

Also note that Python list addition makes this relatively simple. ["a"] + ["b"] = ["a", "b"]

Body:
I need to make a function so that I can put in two parameters, an order, and a max, and return a list of all of the lists 'order' long and with each element ranging from 0 to 'max'. I suspect I may need to use recursion, but I am getting lost in this.

so order = 2 max = 3 should return

[[0,0], [0,1], [0,2], [0,3], [1,0], [1,1], ... ,[3,3]]

and order=4, max=5 should return

[[0,0,0,0], [0,0,0,1], [0,0,0,2], ...  [3,3,3,3]]

Thanks for the help

Body:
Here's a function that uses recursion to solve the problem. When you are dealing with recursion, make sure you have a base case and a general case.

def recurseNumbers(order, mx):
    if order == 1:
        return [[n] for n in range(mx + 1)]
    else:
        total_array = []
        for num in range(mx + 1):
            numbers = recurseNumbers(order - 1, mx)
            for number in numbers:
                total_array.append([num] + number)
        return total_array

Also note that Python list addition makes this relatively simple. ["a"] + ["b"] = ["a", "b"]


问:
Passing and returning a struct from a function
I have a function with a book struct array, but when i try to return it to my main it does not return the values and store them in the array. If the addBook function has to be void how would i work around that so that i can access the array elements later.</p>

```<code>void addBook(struct Book book[], int *size) {

    if (*size == MAX_BOOKS) {
        printf("The inventory is full\n");

    }
    else {

        printf("ISBN:");
        scanf("%d", &book[*size]._isbn);
        printf("Title:");
        scanf("%s", book[*size]._title);
        getchar();
        printf("Year:");
        scanf("%d", &book[*size]._year);
        printf("Price:");
        scanf("%f", &book[*size]._price);
        printf("Quantity:");
        scanf("%d", &book[*size]._qty);
        *size++;
        printf("The book is successfully added to the inventory.\n");
    }
    return book;
}

int main(void) {

    struct Book book[MAX_BOOKS];
    int size = 0;
    int i;
    int option;

    printf("Welcome to the Book Store\n");
    printf("=========================\n");

    do {
        menu();
        printf("Select: ");
        scanf("%d", &option);

        switch (option) {

        case 0:
            printf("Goodbye!\n");
            break;
        case 1:
            displayInventory(book, size);
            break;
        case 2:
            addBook(book, &size);
            break;
        case 3:
            //checkPrice();
            break;
        default:
            printf("Invalid input, try again:\n");
        }
    } while (option != 0);
}
</code>```

答:
I think your problem is in the line *size++;. You should use parenthesis, otherwise you are modifying the pointer to size, not the value. It should be (*size)++.
Also, the addBook function should not return anything, since it is void, and it is changing the content of the array book already.

Body:
I have a function with a book struct array, but when i try to return it to my main it does not return the values and store them in the array. If the addBook function has to be void how would i work around that so that i can access the array elements later.

void addBook(struct Book book[], int *size) {

    if (*size == MAX_BOOKS) {
        printf("The inventory is full\n");

    }
    else {

        printf("ISBN:");
        scanf("%d", &book[*size]._isbn);
        printf("Title:");
        scanf("%s", book[*size]._title);
        getchar();
        printf("Year:");
        scanf("%d", &book[*size]._year);
        printf("Price:");
        scanf("%f", &book[*size]._price);
        printf("Quantity:");
        scanf("%d", &book[*size]._qty);
        *size++;
        printf("The book is successfully added to the inventory.\n");
    }
    return book;
}

int main(void) {

    struct Book book[MAX_BOOKS];
    int size = 0;
    int i;
    int option;

    printf("Welcome to the Book Store\n");
    printf("=========================\n");

    do {
        menu();
        printf("Select: ");
        scanf("%d", &option);

        switch (option) {

        case 0:
            printf("Goodbye!\n");
            break;
        case 1:
            displayInventory(book, size);
            break;
        case 2:
            addBook(book, &size);
            break;
        case 3:
            //checkPrice();
            break;
        default:
            printf("Invalid input, try again:\n");
        }
    } while (option != 0);
}


问:
java - get a button to change color when the mouse hovers over it
So i want to make a menu for a simple java game where the buttons changes colors when the mouse hovers over them. I am not using JButton but a picture of a button that uses mouselistener to detect the click. How do i make it so MouseEntered is called when you hover over a specific area where the button is?

```<code>public void mouseEntered(MouseEvent e) {
    if(e.getX() < 950 && e.getX() > 350 && e.getY() < 300 && e.getY() > 200){
        menuImage2 = true;
        menuImage1 = false;
    }
}
</code>```

This is what i have so far

答:
This is how I did it.  It also plays a sound too.  You just use flags.  Notice, I used mouseMoved rather than mouseEntered.

Class MouseInput

```<code>@Override
public void mouseMoved(MouseEvent e) {
        int x=e.getX();
        int y=e.getY();

        if (x>100&&x<200&&y>150&&y<200) {
            if (mouseInStart==false) {     <---- if this line is true, means mouse entered for first time.
                Sound.playSound(soundEnum.BUTTONHOVER);
            }
            mouseInStart=true;
        } else {
            mouseInStart=false;
        }
}

public boolean mouseInStart() {    <--use this in your update method
    return mouseInStart;
}
</code>```

And in my other class (Class Menu)

```<code>public void render(Graphics2D g) {
    ....
    ....
    gradient = new GradientPaint(100, 150, setStartColor(), 200, 200,        Color.gray);
    g.setPaint(gradient);
    g.fill(startButton);

}

public Color setStartColor() {
    if (mouseInStart) {
        return Color.red;
    } else {
        return Color.white;
    }
}

public void update() {     <--- and this is to keep checking if your mouse is in start.  This is part of the giant game loop.
    mouseInStart=mouseInput.mouseInStart();
    mouseInLoad=mouseInput.mouseInLoad();
    mouseInQuit=mouseInput.mouseInQuit();
}
</code>```

Body:
So i want to make a menu for a simple java game where the buttons changes colors when the mouse hovers over them. I am not using JButton but a picture of a button that uses mouselistener to detect the click. How do i make it so MouseEntered is called when you hover over a specific area where the button is?

public void mouseEntered(MouseEvent e) {
    if(e.getX() < 950 && e.getX() > 350 && e.getY() < 300 && e.getY() > 200){
        menuImage2 = true;
        menuImage1 = false;
    }
}

This is what i have so far

Body:
This is how I did it.  It also plays a sound too.  You just use flags.  Notice, I used mouseMoved rather than mouseEntered.

Class MouseInput

@Override
public void mouseMoved(MouseEvent e) {
        int x=e.getX();
        int y=e.getY();

        if (x>100&&x<200&&y>150&&y<200) {
            if (mouseInStart==false) {     <---- if this line is true, means mouse entered for first time.
                Sound.playSound(soundEnum.BUTTONHOVER);
            }
            mouseInStart=true;
        } else {
            mouseInStart=false;
        }
}

public boolean mouseInStart() {    <--use this in your update method
    return mouseInStart;
}

And in my other class (Class Menu)

public void render(Graphics2D g) {
    ....
    ....
    gradient = new GradientPaint(100, 150, setStartColor(), 200, 200,        Color.gray);
    g.setPaint(gradient);
    g.fill(startButton);

}

public Color setStartColor() {
    if (mouseInStart) {
        return Color.red;
    } else {
        return Color.white;
    }
}

public void update() {     <--- and this is to keep checking if your mouse is in start.  This is part of the giant game loop.
    mouseInStart=mouseInput.mouseInStart();
    mouseInLoad=mouseInput.mouseInLoad();
    mouseInQuit=mouseInput.mouseInQuit();
}


问:
How do I set scons system include path
Using scons I can easily set my include paths:

```<code>env.Append( CPPPATH=['foo'] )
</code>```

This passes the flag

```<code>-Ifoo
</code>```

to gcc

However I'm trying to compile with a lot of warnings enabled.
In particular with

```<code>env.Append( CPPFLAGS=['-Werror', '-Wall', '-Wextra'] )
</code>```

which dies horribly on certain boost includes ... I can fix this by adding the boost includes to the system include path rather than the include path as gcc treats system includes differently.

So what I need to get passed to gcc instead of -Ifoo is

```<code>-isystem foo
</code>```

I guess I could do this with the CPPFLAGS variable, but was wondering if there was a better solution built into scons.

答:
Expanding on the idea proposed by @LangerJan and @BenG... Here's a full cross-platform example (replace env['IS_WINDOWS'] with your windows platform checking)

```<code>from SCons.Util import is_List
def enable_extlib_headers(env, include_paths):
    """Enables C++ builders with current 'env' to include external headers
    specified in the include_paths (list or string value).
    Special treatment to avoid scanning these for changes and/or warnings.
    This speeds up the C++-related build configuration.
    """
    if not is_List(include_paths):
        include_paths = [include_paths]

    include_options = []
    if env['IS_WINDOWS']:
        # Simply go around SCons scanners and add compiler options directly
        include_options = ['-I' + p for p in include_paths]
    else:
        # Tag these includes as system, to avoid scanning them for dependencies,
        # and make compiler ignore any warnings
        for p in include_paths:
            include_options.append('-isystem')
            include_options.append(p)
   env.Append(CXXFLAGS = include_options)
</code>```

Now, when configuring the use of external libraries, instead of

```<code>env.AppendUnique(CPPPATH=include_paths)
</code>```

call

```<code>enable_extlib_headers(env, include_paths)
</code>```

In my case this reduced the pruned dependency tree (as produced with --tree=prune)  by 1000x on Linux and 3000x on Windows! It sped up the no-action build time (i.e. all targets up to date) by 5-7x
The pruned dependency tree before this change had 4 million includes from Boost. That's insane.

ContentLicense: CC BY-SA 2.5

Title: How do I set scons system include path

Body:
Using scons I can easily set my include paths:

env.Append( CPPPATH=['foo'] )

This passes the flag

-Ifoo

to gcc

However I'm trying to compile with a lot of warnings enabled.
In particular with

env.Append( CPPFLAGS=['-Werror', '-Wall', '-Wextra'] )

which dies horribly on certain boost includes ... I can fix this by adding the boost includes to the system include path rather than the include path as gcc treats system includes differently.

So what I need to get passed to gcc instead of -Ifoo is

-isystem foo

I guess I could do this with the CPPFLAGS variable, but was wondering if there was a better solution built into scons.

Body:
Expanding on the idea proposed by @LangerJan and @BenG... Here's a full cross-platform example (replace env['IS_WINDOWS'] with your windows platform checking)

from SCons.Util import is_List
def enable_extlib_headers(env, include_paths):
    """Enables C++ builders with current 'env' to include external headers
    specified in the include_paths (list or string value).
    Special treatment to avoid scanning these for changes and/or warnings.
    This speeds up the C++-related build configuration.
    """
    if not is_List(include_paths):
        include_paths = [include_paths]

    include_options = []
    if env['IS_WINDOWS']:
        # Simply go around SCons scanners and add compiler options directly
        include_options = ['-I' + p for p in include_paths]
    else:
        # Tag these includes as system, to avoid scanning them for dependencies,
        # and make compiler ignore any warnings
        for p in include_paths:
            include_options.append('-isystem')
            include_options.append(p)
   env.Append(CXXFLAGS = include_options)

Now, when configuring the use of external libraries, instead of

env.AppendUnique(CPPPATH=include_paths)

call

enable_extlib_headers(env, include_paths)

In my case this reduced the pruned dependency tree (as produced with --tree=prune)  by 1000x on Linux and 3000x on Windows! It sped up the no-action build time (i.e. all targets up to date) by 5-7x
The pruned dependency tree before this change had 4 million includes from Boost. That's insane.


问:
VS 2010 VB Find Control on Form
My daughter has school homework and is making a snakes and ladders game and she has created a 7 x 7 grid with labels. When she wants to set the position of the player she has multiple if statements and I knew there was a quicker and more efficient way. But it has been years since I played with VS2010

Basically I thought should could do something like this

```<code>Form.FindControl("Label"+player1position).Text = "x"
</code>```

instead of doing

```<code>if player1position = 1 then
   label1.text = "x"
end if
if player1position = 2 then
   label2.text = "x"
end if
</code>```

and so on.

答:
Sure, assuming WinForms, you can do something like:

```<code>Dim matches() As Control = Me.Controls.Find("Label" + player1position, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Label Then
    Dim lbl As Label = DirectCast(matches(0), Label)
    lbl.Text = "x"
End If
</code>```

The above snippet will find the Label no matter how deeply nested it is, and also will find them if they are in different containers.

If the Labels are all in the same container, then you can shorten it to something like:

```<code>Me.Controls("Label" + player1position).Text = "x"
</code>```

That would find the Label if it is directly on the Form.  For a different container, replace "Me" with the name, such as "Panel1":

```<code>Panel1.Controls("Label" + player1position).Text = "x"
</code>```

Title: VS 2010 VB Find Control on Form

Body:
My daughter has school homework and is making a snakes and ladders game and she has created a 7 x 7 grid with labels. When she wants to set the position of the player she has multiple if statements and I knew there was a quicker and more efficient way. But it has been years since I played with VS2010

Basically I thought should could do something like this

Form.FindControl("Label"+player1position).Text = "x"

instead of doing

if player1position = 1 then
   label1.text = "x"
end if
if player1position = 2 then
   label2.text = "x"
end if

and so on.

Body:
Sure, assuming WinForms, you can do something like:

Dim matches() As Control = Me.Controls.Find("Label" + player1position, True)
If matches.Length > 0 AndAlso TypeOf matches(0) Is Label Then
    Dim lbl As Label = DirectCast(matches(0), Label)
    lbl.Text = "x"
End If

The above snippet will find the Label no matter how deeply nested it is, and also will find them if they are in different containers.

If the Labels are all in the same container, then you can shorten it to something like:

Me.Controls("Label" + player1position).Text = "x"

That would find the Label if it is directly on the Form.  For a different container, replace "Me" with the name, such as "Panel1":

Panel1.Controls("Label" + player1position).Text = "x"


问:
Issues with variables with html checkbox
I've got this code:

```<code><HTML>
<BODY>

<FORM action = "respuestas.php" METHOD "post">
1. ¿Cuál es la capital de México?<br>
<INPUT TYPE = "radio" VALUE="nayarit" CHECKED NAME = "capital">Nayarit<br>
<INPUT TYPE = "radio" VALUE="cdmx" NAME = "capital" >Ciudad de México<br>
<INPUT TYPE = "radio" VALUE="yucatan" NAME = "capital">Yucatán<br>

2. ¿Cuánto es 9 x 5?<br>
<INPUT TYPE = "radio" VALUE="catorce" CHECKED NAME = "operacion">14<br>
<INPUT TYPE = "radio" VALUE="setenta" NAME = "operacion">70<br>
<INPUT TYPE = "radio" VALUE="cuarentacinco" NAME = "operacion">45<br>

3. ¿Cuántos colores tiene un arcoiris?<br>
<INPUT TYPE = "radio" VALUE="siete" CHECKED NAME = "color">7<br>
<INPUT TYPE = "radio" VALUE="nueve" NAME = "color">9<br>
<INPUT TYPE = "radio" VALUE="ocho" NAME = "color">8<br>

<INPUT TYPE = "submit" VALUE = "Aceptar" NAME= "aceptar"/>
</FORM>

</BODY>
</HTML>
</code>```

And this PHP code:

```<code><?php

$capital= "";
$operacion = "";
$color = "";
   if($capital == "cdmx") {
       echo"Respuesta 1: Correcto!<br>";
   } else{
       echo"Respuesta 1: Incorrecto!<br>";
   }
   if($operacion == "cuarentacinco"){
       echo"Respuesta 2: Correcto!<br>";
   } else{
       echo"Respuesta 2: Incorrecto!<br>";
   }
       if($color == "siete"){
       echo"Respuesta 3: Correcto!<br>";
   } else{
       echo"Respuesta 3: Incorrecto!<br>";
   }

?>
</code>```

It is supposed to print "Respuesta 1: Correcto!" when you check te correct answer, but for the 3 echo's it writes the false way that is "Respuesta 1: Correcto!", I think that html isn't sending the variables that are checked to the php code, i assure myself that the PHP file is called "respuestas.php", so I don't know how to fix it.

Thanks.

答:
In addition to the answers,  there is an issue with your form.  Change the method attribute to method ="post"
It might be a typo from your side but please verify </p>

Body:
I've got this code:

<FORM action = "respuestas.php" METHOD "post">
1. ¿Cuál es la capital de México?

<INPUT TYPE = "radio" VALUE="nayarit" CHECKED NAME = "capital">Nayarit

<INPUT TYPE = "radio" VALUE="cdmx" NAME = "capital" >Ciudad de México

<INPUT TYPE = "radio" VALUE="yucatan" NAME = "capital">Yucatán

2. ¿Cuánto es 9 x 5?

<INPUT TYPE = "radio" VALUE="catorce" CHECKED NAME = "operacion">14

<INPUT TYPE = "radio" VALUE="setenta" NAME = "operacion">70

<INPUT TYPE = "radio" VALUE="cuarentacinco" NAME = "operacion">45

3. ¿Cuántos colores tiene un arcoiris?

<INPUT TYPE = "radio" VALUE="siete" CHECKED NAME = "color">7

<INPUT TYPE = "radio" VALUE="nueve" NAME = "color">9

<INPUT TYPE = "radio" VALUE="ocho" NAME = "color">8

<INPUT TYPE = "submit" VALUE = "Aceptar" NAME= "aceptar"/>
</FORM>

And this PHP code:

<?php

$capital= "";
$operacion = "";
$color = "";
   if($capital == "cdmx") {
       echo"Respuesta 1: Correcto!
";
   } else{
       echo"Respuesta 1: Incorrecto!
";
   }
   if($operacion == "cuarentacinco"){
       echo"Respuesta 2: Correcto!
";
   } else{
       echo"Respuesta 2: Incorrecto!
";
   }
       if($color == "siete"){
       echo"Respuesta 3: Correcto!
";
   } else{
       echo"Respuesta 3: Incorrecto!
";
   }

?>

It is supposed to print "Respuesta 1: Correcto!" when you check te correct answer, but for the 3 echo's it writes the false way that is "Respuesta 1: Correcto!", I think that html isn't sending the variables that are checked to the php code, i assure myself that the PHP file is called "respuestas.php", so I don't know how to fix it.

Thanks.


问:
Regex for breadcrumb to url pattern
I have following pattern

"Parts > Home Automation & Security > DSC Alaram Package"

I want to convert it to

"Parts/Home-Automation-Security/DSC-Alaram-Package"

I can have any number of " > " in my source string.

I would really appreciate if someone can help me writing a regex or extension method in C# for this.

答:
Why not use use the String.Replace() function?</p>

```<code>string original = "Parts > Home Automation & Security > DSC Alaram Package";
string modified = original.Replace(" > ", "/");
</code>```

Title: Regex for breadcrumb to url pattern

Body:
Why not use use the String.Replace() function?

string original = "Parts > Home Automation & Security > DSC Alaram Package";
string modified = original.Replace(" > ", "/");


问:
Canvas repeating rectangles aren't unique
I'm trying to write a function that allows to make repeated rectangles with different text values, and a flag that changes the color of the box.  I'm having trouble getting the text for each call to the function as well as the correct color to appear on each respective box.  I end up with the last box in a series of calls being the only one with visible text.  What am I doing wrong?

```<code>var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

this.buildBox = function(xpos, ypos, width, height, text, colorFlag) {
    ctx.font = '12px Arial';
    ctx.strokeStyle = 'black';
    ctx.fillStyle = colorFlag === true ? '#ff6666' : '#fff';
    ctx.rect(xpos, ypos, width, height);
    ctx.fill();
    ctx.stroke();

    function textFill(text, offset) {
    }

    if(text !== null && text !== undefined) {
      ctx.strokeText(text, xpos + 10, ypos + 20);
    }
}
// test data
this.buildBox(84,10,64,44, 888, true);
this.buildBox(84,64,64,44, 999, false);
this.buildBox(84,118,64,44, 777, true);
</code>```

To test, try commenting out some of the calls to buildBox and see the results in the fiddle below.

JSFiddle

答:
To make the draw methods apply only to the things you do in one function call, add the following line as the first in your function:

```<code>ctx.beginPath();
</code>```

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

this.buildBox = function(xpos, ypos, width, height, text, colorFlag) {
    ctx.beginPath();
    ctx.font = '12px Arial';
    ctx.strokeStyle = 'black';
    ctx.fillStyle = colorFlag === true ? '#ff6666' : '#fff';
    ctx.rect(xpos, ypos, width, height);
    ctx.fill();
    ctx.stroke();

    function textFill(text, offset) {
    }

    if(text !== null && text !== undefined) {
      ctx.strokeText(text, xpos + 10, ypos + 20);
    }
}

// test data
this.buildBox(84,10,64,44, 888, true);
this.buildBox(84,64,64,44, 999, false);
this.buildBox(84,118,64,44, 777, true);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="canvas"></canvas></code>```

Without this line, the methods fill and stroke apply to all you have drawn so far. With beginPath you consolidate what was done before, and start with a new "section".

Body:
I'm trying to write a function that allows to make repeated rectangles with different text values, and a flag that changes the color of the box.  I'm having trouble getting the text for each call to the function as well as the correct color to appear on each respective box.  I end up with the last box in a series of calls being the only one with visible text.  What am I doing wrong?

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

this.buildBox = function(xpos, ypos, width, height, text, colorFlag) {
    ctx.font = '12px Arial';
    ctx.strokeStyle = 'black';
    ctx.fillStyle = colorFlag === true ? '#ff6666' : '#fff';
    ctx.rect(xpos, ypos, width, height);
    ctx.fill();
    ctx.stroke();

    function textFill(text, offset) {
    }

    if(text !== null && text !== undefined) {
      ctx.strokeText(text, xpos + 10, ypos + 20);
    }
}
// test data
this.buildBox(84,10,64,44, 888, true);
this.buildBox(84,64,64,44, 999, false);
this.buildBox(84,118,64,44, 777, true);

To test, try commenting out some of the calls to buildBox and see the results in the fiddle below.

JSFiddle

Body:
To make the draw methods apply only to the things you do in one function call, add the following line as the first in your function:

ctx.beginPath();

var canvas = document.getElementById('canvas');
var ctx = canvas.getContext('2d');

this.buildBox = function(xpos, ypos, width, height, text, colorFlag) {
    ctx.beginPath();
    ctx.font = '12px Arial';
    ctx.strokeStyle = 'black';
    ctx.fillStyle = colorFlag === true ? '#ff6666' : '#fff';
    ctx.rect(xpos, ypos, width, height);
    ctx.fill();
    ctx.stroke();

    function textFill(text, offset) {
    }

    if(text !== null && text !== undefined) {
      ctx.strokeText(text, xpos + 10, ypos + 20);
    }
}

// test data
this.buildBox(84,10,64,44, 888, true);
this.buildBox(84,64,64,44, 999, false);
this.buildBox(84,118,64,44, 777, true);

<canvas id="canvas"></canvas>

Without this line, the methods fill and stroke apply to all you have drawn so far. With beginPath you consolidate what was done before, and start with a new "section".


问:
How to create a package in Cognos - SDK?
I have been trying to create a package for Cognos via the sdk.

So far so good. I can created a package but I cannot add a datasource to that package. So basicly it does not do anything.

I am getting:

ANS-MES-0003 A server error occurred. Unable to complete the action.

when launching the package with the analysis studio.

答:
If you are using IIS, you may not be getting the underlying issue because IIS will intercept the error. The error may be bad permissions or corrupt user data, but the error code returned seems to be an umbrella for specifics.

As outlined in this troubleshooting page, you can see the original error by setting httpErrors to PassThough. Replace:

```<code><httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">
  <error statusCode="401" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="401.htm" />
  <error statusCode="403" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="403.htm" />
  <error statusCode="404" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="404.htm" />
  <error statusCode="405" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="405.htm" />
  <error statusCode="406" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="406.htm" />
  <error statusCode="412" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="412.htm" />
  <error statusCode="500" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="500.htm" />
  <error statusCode="501" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="501.htm" />
  <error statusCode="502" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="502.htm" />
</httpErrors>
</code>```

with:

```<code><httpErrors existingResponse="PassThrough" />
</code>```

in you IIS config file.

OR

List item

Stop IIS

Open the IIS config file

Search for
 and change Deny to Allow.

Look for <httpErrors> in <system.webserver>. If it has lockAllAttributesExcept="errorMode", remove the attribute and value.

In command, run %windir%\system32\inetsrv\appcmd.exe set config "<Your Website>/<Your virtual directory>" -section:system.webServer/httpErrors - existingResponse:PassThrough

Start IIS.

Body:
If you are using IIS, you may not be getting the underlying issue because IIS will intercept the error. The error may be bad permissions or corrupt user data, but the error code returned seems to be an umbrella for specifics.

As outlined in this troubleshooting page, you can see the original error by setting httpErrors to PassThough. Replace:

<httpErrors lockAttributes="allowAbsolutePathsWhenDelegated,defaultPath">
  <error statusCode="401" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="401.htm" />
  <error statusCode="403" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="403.htm" />
  <error statusCode="404" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="404.htm" />
  <error statusCode="405" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="405.htm" />
  <error statusCode="406" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="406.htm" />
  <error statusCode="412" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="412.htm" />
  <error statusCode="500" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="500.htm" />
  <error statusCode="501" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="501.htm" />
  <error statusCode="502" prefixLanguageFilePath="%SystemDrive%\inetpub\custerr" path="502.htm" />
</httpErrors>

with:

<httpErrors existingResponse="PassThrough" />

in you IIS config file.

OR

List item

Stop IIS

Open the IIS config file

Search for <section name="httpErrors" overrideModeDefault="Deny" /> and change Deny to Allow.

Look for <httpErrors> in <system.webserver>. If it has lockAllAttributesExcept="errorMode", remove the attribute and value.

In command, run %windir%\system32\inetsrv\appcmd.exe set config "<Your Website>/<Your virtual directory>" -section:system.webServer/httpErrors - existingResponse:PassThrough

Start IIS.


问:
Array of observables type
I am just curious, what will be the correct type of Observables array?

I tried:

```<code>let myObservables: Observable[] = new Array();
let myObservables: Observable<Array<any>> = new Array();
let myObservables: Observable<[]> = new Array();
</code>```

but none of them are working.

I just want an array in which i can push observables so that i can pass it to Observable.forkJoin(myObservables)

答:
Could you not just do:</p>

```<code>let myObservables: any = [];

Observable.forkJoin(myObservables)
</code>```

Title: Array of observables type

Body:
I am just curious, what will be the correct type of Observables array?

I tried:

let myObservables: Observable[] = new Array();
let myObservables: Observable<Array<any>> = new Array();
let myObservables: Observable<[]> = new Array();

but none of them are working.

I just want an array in which i can push observables so that i can pass it to Observable.forkJoin(myObservables)

Body:
Could you not just do:

let myObservables: any = [];

Observable.forkJoin(myObservables)


问:
Variables created in Jquery not appearing in Debugger
I have written some code in Jquery that when a button is pressed, creates a new variable and displays it on the screen.  I'd like to take whatever data is entered into this new variable and store it in a database however before I get there I have to figure out to access the variables information properly.

In HTML I have 3 text boxes created and a button to add up to 7 more for a total of 10.  My code looks like this (and these store in the database just fine):

```<code><table style="width:90%" class="Long-Term-Conditions">
<center>
 <tr>
  <td><b><center>Long term condition 1:</center></b></td>
  <td><center><input type='text' id="Var1" name ='Var1' value='%Var1%' /></center></td>
 </tr>
 <tr>
  <td><b><center>Long term condition 2:</center></b></td>
  <td><center><input type='text' id="Var2" name ='Var2' value='%Var2%' /></center></td>
 </tr>
 <tr>
  <td><b><center>Long term condition 3:</center></b></td>
  <td><center><input type='text' id="Var3" name ='Var3' value='%Var3%' /></center></td>
 </tr>
</center>
</table>
<a href="#" title="" class="add-cond" id="add-cond">Add another long-term health condition</a>
<div id="Message"></div>
</code>```

My problem now is that my Jquery variables cant be inspected (says not available) and no data is passed to the database after.  My Jquery looks like this:

```<code><script>

  //Adds another row to the above table.
 var counter = 3;
 jQuery('a.add-cond').click(function(event){
    event.preventDefault();
    if (counter < 10) {
  counter++;
  var newRow = jQuery('<tr><td><b><center>'+ "Long term condition "+  counter + ":" + '</center></td> <td><center><input type="text" name="Var' +
    counter + '" id="Var' + counter + 'value="%Var' + counter + '%"/></center></b></td></tr>');
  jQuery('table.Long-Term-Conditions').append(newRow);
 }
  else
     {
  document.getElementById("add-cond").style.visibility = "hidden";
  document.getElementById("Message").innerHTML = '<font color="Red">Please
contact us</font>';
 }
});

</script>
</code>```

The code works in creating the new variable however any data entered into the newly created text box is never passed to the debugger or the database.  What am I doing wrong?  Any help is appreciated.

答:
The problem you are having is that when you bind the click event to the elements it only binds to the elements that already exist on the document. So when you add new ones it won't trigger that click event because you didn't bind it to the new ones.

A simple solution to this is to add the click event listener to the body like so:

```<code>jQuery('body').on('click', 'a.add-cond', function(event){
</code>```

I think that is what you are looking for.

Also like the other guy mentioned you are missing a closing quote and a space

```<code>id="Var' + counter + 'value="%Var' + counter + '%"
</code>```

Should be:

```<code>id="Var' + counter + '" value="%Var' + counter + '%"
</code>```

Body:
I have written some code in Jquery that when a button is pressed, creates a new variable and displays it on the screen.  I'd like to take whatever data is entered into this new variable and store it in a database however before I get there I have to figure out to access the variables information properly.

In HTML I have 3 text boxes created and a button to add up to 7 more for a total of 10.  My code looks like this (and these store in the database just fine):

  Long term condition 1:
  <input type='text' id="Var1" name ='Var1' value='%Var1%' />

  Long term condition 2:
  <input type='text' id="Var2" name ='Var2' value='%Var2%' />

  Long term condition 3:
  <input type='text' id="Var3" name ='Var3' value='%Var3%' />

Add another long-term health condition

My problem now is that my Jquery variables cant be inspected (says not available) and no data is passed to the database after.  My Jquery looks like this:

The code works in creating the new variable however any data entered into the newly created text box is never passed to the debugger or the database.  What am I doing wrong?  Any help is appreciated.

Body:
The problem you are having is that when you bind the click event to the elements it only binds to the elements that already exist on the document. So when you add new ones it won't trigger that click event because you didn't bind it to the new ones.

A simple solution to this is to add the click event listener to the body like so:

jQuery('body').on('click', 'a.add-cond', function(event){

I think that is what you are looking for.

Also like the other guy mentioned you are missing a closing quote and a space

id="Var' + counter + 'value="%Var' + counter + '%"

Should be:

id="Var' + counter + '" value="%Var' + counter + '%"


问:
Why is function being called without clicking on button?
I am trying to move the smaller block 'onclick' of the button in html. But either it is not calling that function or may be it is calling it even before the button is clicked. How to find out and solve to get the required response?</p>

```<code><html>
<head>
<script>
var pos = 0;
//getting box element
var box = document.getElementById("box");
var time = setInterval(move, 10);
document.getElementById("btn1").onclick = move(){
    if(pos >= 150){
        clearInterval(time);
    } else{
        pos += 1;
        box.style.left = pos+"px";
    }
};
</script>
</head>
<body>
<h1><p id="p1" style="color:#dd3333">Sample Game</p></h1>
<p id="p2" styel="color:#b5b5b5">Click on the button below</p>
<style>
#container{
width:200px;
height:200px;
background:green;
position:relative;
}
#box{
width:50px;
height:50px;
background:red;
position:absolute;
}
</style>
<div id="container">
<div id="box"></div>
</div>
<br></br>
<button id="btn1">Click Me</button>
</body>

</html>
</code>```

答:
You're directly calling a function move. Instead:

```<code>function move(){
    if(pos >= 150){
        clearInterval(time);
    } else{
        pos += 1;
        box.style.left = pos+"px";
    }
}

document.getElementById("btn1").addEventListener("click", move);
</code>```

Additionally, since you don't use any DOM ready handler to make sure the document is ready and parsed by JS - place your

```

Body:
I am trying to move the smaller block 'onclick' of the button in html. But either it is not calling that function or may be it is calling it even before the button is clicked. How to find out and solve to get the required response?

Sample Game

Click on the button below

<button id="btn1">Click Me</button>

Body:
You're directly calling a function move. Instead:

function move(){
    if(pos >= 150){
        clearInterval(time);
    } else{
        pos += 1;
        box.style.left = pos+"px";
    }
}

document.getElementById("btn1").addEventListener("click", move);

Additionally, since you don't use any DOM ready handler to make sure the document is ready and parsed by JS - place your <script> file before the closing </body> tag. or do a quick google how to incorporate such a function that will tell you JS can safely operate over DOM elements. (jQuery here, for example is your friend)

<!DOCTYPE html>
<html>

<head>
</head>

<body>

  <style>
    #container {
      width: 200px;
      height: 200px;
      background: green;
      position: relative;
    }
    #box {
      width: 50px;
      height: 50px;
      background: red;
      position: absolute;
    }
  </style>

  <div id="container">
    <div id="box"></div>
  </div>

  <button id="btn1">Click Me</button>

  <script>
    var pos = 0;
    var box = document.getElementById("box");
    var time = null;

    function move() {
      if (pos >= 150) {
        clearInterval(time);
      } else {
        pos += 1;
        box.style.left = pos + "px";
      }
    }

    document.getElementById("btn1").addEventListener("click", function() {
      time = setInterval(move, 10);
    });
  </script>
</body>

</html>


问:
String in list, into a function
```<code>myList = ['100', 'sin(x)', '0', '1']
</code>```

I read these strings from a text file.  I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.

I have tried the following with no success.

```<code>myList[1].replace("'", "")
</code>```

I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.

The end goal is to get this function, where myList[1] should turn to sin(x)

```<code>from math import sin
def f(x):
    return myList[1]
</code>```

Thus f(x) will give the computed value of sin(x) from this list.

答:
With sympy.sympify and highlighting the warning

Warning : sympify uses eval. Don’t use it on unsanitized input.

you can solve this as

```<code>myList = ['100', 'sin(x)', '0', '1']

from sympy.abc import x
from sympy import sympify

N, expr, a,b = myList

# convert strings to objects
N=int(N); a=float(a); b=float(b);
expr = sympify(expr)

# define user function
def f(xval): return expr.subs(x,xval)
</code>```

or for multi-point evaluation replace the last line with

```<code>from sympy import lambdify
f = lambdify(x, expr, "numpy")

# integrate as left Riemann sum (order 1)
from numpy import linspace
xlist = linspace(a,b,N)

integral = sum(f(xlist))*(b-a)/N
</code>```

Title: String in list, into a function

Body:
myList = ['100', 'sin(x)', '0', '1']

I read these strings from a text file.  I now want to execute the function call sin(x) from that string -- I want this to be a general interpretation of the string for any function expression.

I have tried the following with no success.

myList[1].replace("'", "")

I guess what I am asking is how to pull a string from a list and use it's 'raw text' so to speak.

The end goal is to get this function, where myList[1] should turn to sin(x)

from math import sin
def f(x):
    return myList[1]

Thus f(x) will give the computed value of sin(x) from this list.

Body:
With sympy.sympify and highlighting the warning

Warning : sympify uses eval. Don’t use it on unsanitized input.

you can solve this as

myList = ['100', 'sin(x)', '0', '1']

from sympy.abc import x
from sympy import sympify

N, expr, a,b = myList

# convert strings to objects
N=int(N); a=float(a); b=float(b);
expr = sympify(expr)

# define user function
def f(xval): return expr.subs(x,xval)

or for multi-point evaluation replace the last line with

from sympy import lambdify
f = lambdify(x, expr, "numpy")

# integrate as left Riemann sum (order 1)
from numpy import linspace
xlist = linspace(a,b,N)

integral = sum(f(xlist))*(b-a)/N


问:
Div stuck at bottom of parent
I have the situation in the screenshot below:

I want the div surrounded in blue to be aligned to the top of the parent div (surrounded in black) as the image (surrounded in red) is. How can I accomplish this?

I know top -10px is an option (where 10 is replaced with the exact number) but I need this to work on various screen sizes so finding the exact value that fixes the problem with that method is not an option.

The html for the divs is below:

```<code><div class="product">
    <img class="productImg" src="http://placehold.it/300x240">
    <div class="productTxt">
        <h1>Title</h1>
        <h3>Price</h3>
        <p>Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description </p>
    </div>
</div>
</code>```

And the CSS:

```<code>.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    height: 330px;
    border: 5px solid black;
}

.productImg {
    width: 240px;
    height: 300px;
    display: inline-block;
    border: 3px solid red;
}

.productTxt {
    border: 3px solid blue;
    display: inline-block;
}
</code>```

答:
Use flexbox. And align it like this:

```<code>.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    height: 330px;
    border: 5px solid black;
    display:flex;
    align-items:flex-start;
}
</code>```

Here is a fiddle: http://codepen.io/ruchiccio/pen/ZemOyV

Title: Div stuck at bottom of parent

Body:
I have the situation in the screenshot below:

I want the div surrounded in blue to be aligned to the top of the parent div (surrounded in black) as the image (surrounded in red) is. How can I accomplish this?

I know top -10px is an option (where 10 is replaced with the exact number) but I need this to work on various screen sizes so finding the exact value that fixes the problem with that method is not an option.

The html for the divs is below:

Title

Price

Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description Short Description

And the CSS:

.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    height: 330px;
    border: 5px solid black;
}

.productImg {
    width: 240px;
    height: 300px;
    display: inline-block;
    border: 3px solid red;
}

.productTxt {
    border: 3px solid blue;
    display: inline-block;
}

Body:
Use flexbox. And align it like this:

.product {
    box-sizing: border-box;
    margin: 0px;
    padding: 10px;
    width: 100%;
    height: 330px;
    border: 5px solid black;
    display:flex;
    align-items:flex-start;
}

Here is a fiddle: http://codepen.io/ruchiccio/pen/ZemOyV