问:
How to get Python requests to trust a self signed SSL certificate?
```<code>import requests
data = {'foo':'bar'}
url = 'https://foo.com/bar'
r = requests.post(url, data=data)
</code>```

If the URL uses a self signed certificate, this fails with

```<code>requests.exceptions.SSLError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed
</code>```

I know that I can pass False to the verify parameter, like this:

```<code>r = requests.post(url, data=data, verify=False)
</code>```

However, what I would like to do is point requests to a copy of the public key on disk and tell it to trust that certificate.

答:
Case where multiple certificates are needed was solved as follows:
Concatenate the multiple root pem files, myCert-A-Root.pem and myCert-B-Root.pem, to a file. Then set the requests REQUESTS_CA_BUNDLE var to that file in my ./.bash_profile.</p>

```<code>$ cp myCert-A-Root.pem ca_roots.pem
$ cat myCert-B-Root.pem >> ca_roots.pem
$ echo "export REQUESTS_CA_BUNDLE=~/PATH_TO/CA_CHAIN/ca_roots.pem" >> ~/.bash_profile ; source ~/.bash_profile
</code>```

Body:
import requests
data = {'foo':'bar'}
url = 'https://foo.com/bar'
r = requests.post(url, data=data)

If the URL uses a self signed certificate, this fails with

requests.exceptions.SSLError: [Errno 1] _ssl.c:507: error:14090086:SSL routines:SSL3_GET_SERVER_CERTIFICATE:certificate verify failed

I know that I can pass False to the verify parameter, like this:

r = requests.post(url, data=data, verify=False)

However, what I would like to do is point requests to a copy of the public key on disk and tell it to trust that certificate.

Body:
Case where multiple certificates are needed was solved as follows:
Concatenate the multiple root pem files, myCert-A-Root.pem and myCert-B-Root.pem, to a file. Then set the requests REQUESTS_CA_BUNDLE var to that file in my ./.bash_profile.

$ cp myCert-A-Root.pem ca_roots.pem
$ cat myCert-B-Root.pem >> ca_roots.pem
$ echo "export REQUESTS_CA_BUNDLE=~/PATH_TO/CA_CHAIN/ca_roots.pem" >> ~/.bash_profile ; source ~/.bash_profile


来源: stackexchange

问:
ReactNative - SSLException Building Movies Example
I'm new to React Native and have been playing around with one or two examples. When I try and build the Android "Movies" Example on my Mac I get the following error:

```<code>./gradlew :Examples:Movies:android:app:installDebug

:ReactAndroid:downloadJSCHeaders FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':ReactAndroid:downloadJSCHeaders'.
javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair
</code>```

I've done npm install from the react-native directory that gets me this far and have the SDK and NDK locations set in my ./bash_profile. I've read elsewhere that my it could be something to do the the Android NDK version, I've tried using both android-ndk-r10c and android-ndk-r11c

Any help appreciated.

答:
If anyone is looking for the solution, you need to add this line to the buildscript dependencies in the android/build.gradle file

```<code>classpath 'de.undercouch:gradle-download-task:3.1.2'
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I'm new to React Native and have been playing around with one or two examples. When I try and build the Android "Movies" Example on my Mac I get the following error:

./gradlew :Examples:Movies:android:app:installDebug

:ReactAndroid:downloadJSCHeaders FAILED

FAILURE: Build failed with an exception.

* What went wrong:
Execution failed for task ':ReactAndroid:downloadJSCHeaders'.
javax.net.ssl.SSLException: java.lang.RuntimeException: Could not generate DH keypair

I've done npm install from the react-native directory that gets me this far and have the SDK and NDK locations set in my ./bash_profile. I've read elsewhere that my it could be something to do the the Android NDK version, I've tried using both android-ndk-r10c and android-ndk-r11c

Any help appreciated.

Body:
If anyone is looking for the solution, you need to add this line to the buildscript dependencies in the android/build.gradle file

classpath 'de.undercouch:gradle-download-task:3.1.2'


问:
How do I name and retrieve a Git stash by name?
How do I save/apply a stash with a name? I don't want to have to look up its index number in git stash list. I tried git stash save "my_stash_name", but that only changes the stash description, and the corresponding git apply "my_stash_name" doesn't work.

答:
Use git stash save NAME to save.

Then... you can use this script to choose which to apply (or pop):

#!/usr/bin/env ruby
#git-stash-pick by Dan Rosenstark

# can take a command, default is apply
command = ARGV[0]
command = "apply" if !command
ARGV.clear

stashes = []
stashNames = []
`git stash list`.split("\n").each_with_index { |line, index|
    lineSplit = line.split(": ");
    puts "#{index+1}. #{lineSplit[2]}"
    stashes[index] = lineSplit[0]
    stashNames[index] = lineSplit[2]
}
print "Choose Stash or ENTER to exit: "
input = gets.chomp
if input.to_i.to_s == input
    realIndex = input.to_i - 1
    puts "\n\nDoing #{command} to #{stashNames[realIndex]}\n\n"
    puts `git stash #{command} #{stashes[realIndex]}`
end
```

I like being able to see the names of the stashes and choose. Also I use Zshell and frankly didn't know how to use some of the Bash aliases above ;)

Note: As Kevin says, you should use tags and cherry-picks instead.

ContentLicense: CC BY-SA 4.0

Body:
Use git stash save NAME to save.

Then... you can use this script to choose which to apply (or pop):

#!/usr/bin/env ruby
#git-stash-pick by Dan Rosenstark

# can take a command, default is apply
command = ARGV[0]
command = "apply" if !command
ARGV.clear

stashes = []
stashNames = []
`git stash list`.split("\n").each_with_index { |line, index|
    lineSplit = line.split(": ");
    puts "#{index+1}. #{lineSplit[2]}"
    stashes[index] = lineSplit[0]
    stashNames[index] = lineSplit[2]
}
print "Choose Stash or ENTER to exit: "
input = gets.chomp
if input.to_i.to_s == input
    realIndex = input.to_i - 1
    puts "\n\nDoing #{command} to #{stashNames[realIndex]}\n\n"
    puts `git stash #{command} #{stashes[realIndex]}`
end

I like being able to see the names of the stashes and choose. Also I use Zshell and frankly didn't know how to use some of the Bash aliases above ;)

Note: As Kevin says, you should use tags and cherry-picks instead.


问:
How do you reverse an iterator's flow?
Is it possible to access the previous value of an iterator, for example:

```<code>function* gen () {
   yield* [0,1,2,3]
}

var it = gen();

it.next().value // 0
it.next().value // 1
it.last().value // would be awesome if this was 0
</code>```

This is strictly a curiosity question. I've been playing with generators lately and was wondering if anyone uses generators/iterators in this manner?

If so, I would love to see your solution. (Doesn't need to follow the above syntax) -Thanks

答:
You can wrap the generator in a function that saves previous yields:

const wrapGenerator = gen => (...args) => {
  const it = gen(...args);
  let previous, current;
  return {
    next: () => {
      const r = it.next();
      previous = current;
      current = r.value;
      return r;
    },
    previous: () => ({ value: previous })
  };
};

const gen = wrapGenerator(function * () {
  yield * [0, 1, 2, 3];
});

const it = gen();

console.log(it.next().value);
console.log(it.next().value);
console.log(it.previous().value);```

I changed the function name to previous to avoid confusion (last could mean "the last item").

Title: How do you reverse an iterator's flow?

Body:
Is it possible to access the previous value of an iterator, for example:

function* gen () {
   yield* [0,1,2,3]
}

var it = gen();

it.next().value // 0
it.next().value // 1
it.last().value // would be awesome if this was 0

This is strictly a curiosity question. I've been playing with generators lately and was wondering if anyone uses generators/iterators in this manner?

If so, I would love to see your solution. (Doesn't need to follow the above syntax) -Thanks

Body:
You can wrap the generator in a function that saves previous yields:

const wrapGenerator = gen => (...args) => {
  const it = gen(...args);
  let previous, current;
  return {
    next: () => {
      const r = it.next();
      previous = current;
      current = r.value;
      return r;
    },
    previous: () => ({ value: previous })
  };
};

const gen = wrapGenerator(function * () {
  yield * [0, 1, 2, 3];
});

const it = gen();

console.log(it.next().value);
console.log(it.next().value);
console.log(it.previous().value);

I changed the function name to previous to avoid confusion (last could mean "the last item").


问:
SQL - Need to conditionally join based on value in TableB column
I need to know the rows in TABLE A that have join records in TABLE B based a column value in TABLE B, but I also need to return rows in which a row in TABLE A has no match in TABLE B.

It seems like I need a LEFT JOIN and a LEFT OUTER JOIN, so I'm not sure what to do there. I understand how to do each, but don't understand how to do them together.

The schema looks like:

```<code>TABLE_A
pk

TABLE_B
pk
a_fk
some_value
</code>```

I need the joined rows where Table_A has no join record in Table_B OR Table_A has a join record row in Table_B (it can have many) in which some_value does not equal "thisValue"

Thanks.

答:
A Left join is a left outer join. Outer joins preserve one of the tables which is what you are after so good guess.

```<code>SELECT *
FROM Table A
LEFT JOIN Table B
ON TableA.Column = TableB.Column
AND B.SomeValue <> 'ThisValue'
</code>```

All of the rows with a match will have the B information populated all of those without will have nulls in the B data

Body:
I need to know the rows in TABLE A that have join records in TABLE B based a column value in TABLE B, but I also need to return rows in which a row in TABLE A has no match in TABLE B.

It seems like I need a LEFT JOIN and a LEFT OUTER JOIN, so I'm not sure what to do there. I understand how to do each, but don't understand how to do them together.

The schema looks like:

TABLE_A
pk

TABLE_B
pk
a_fk
some_value

I need the joined rows where Table_A has no join record in Table_B OR Table_A has a join record row in Table_B (it can have many) in which some_value does not equal "thisValue"

Thanks.

Body:
A Left join is a left outer join. Outer joins preserve one of the tables which is what you are after so good guess.

SELECT *
FROM Table A
LEFT JOIN Table B
ON TableA.Column = TableB.Column
AND B.SomeValue <> 'ThisValue'

All of the rows with a match will have the B information populated all of those without will have nulls in the B data


问:
Check if an array of strings contains a substring
I have an array like this:

```<code>array = ["123", "456", "#123"]
</code>```

I want to find the element which contains the substring "#". I tried array.includes("#") and array.indexOf("#") but it didn't work.

How can I check if any of the strings in this array contain the substring "#"?

答:
Because includes will compare '#' with each array element.

Let's try with some or find if you want to find if you want to get exactly element

var array = ["123", "456", "#123"];

var el = array.find(a =>a.includes("#"));

console.log(el)```

Body:
I have an array like this:

array = ["123", "456", "#123"]

I want to find the element which contains the substring "#". I tried array.includes("#") and array.indexOf("#") but it didn't work.

How can I check if any of the strings in this array contain the substring "#"?


问:
How can I destroy the session set using saveSessionSnapshot() in codeception?
The session remains alive even after logout.

This is my login file.

public function loginAsAdmin($wpUserName, $wpPassword) {

```<code>$I = $this->tester;

$I->amOnPage('/wp-admin');

if ($I->loadSessionSnapshot('login')) {
    return;
}

$I->seeElement(self::$wpUserNameField);
$I->fillfield(self::$wpUserNameField, $wpUserName);

$I->seeElement(self::$wpPasswordField);
$I->fillfield(self::$wpPasswordField, $wpPassword);

$I->seeElement(self::$wpSubmitButton);
$I->click(self::$wpSubmitButton);
$I->wait(5);

$I->saveSessionSnapshot('login');
</code>```

}

Details

Codeception version: 2.2.10
PHP Version:
Operating System: OS X
Installation type: Composer
List of installed packages (composer show) I am Using lucatume/wp-browser package for codeception

This is my Suite configuration:

class_name: AcceptanceTester modules:

```<code>enabled:
    - \Helper\Acceptance
    - WPWebDriver
config:
    WPWebDriver:
        host: 'hub-cloud.browserstack.com'
        port: 80
        browser: 'firefox'
        url: ''
        adminUsername: ''
        adminPassword: ''
        adminPath: '/wp-admin'
        capabilities:
           'browserstack.user': ''
           'browserstack.key': ''
          'os': 'OS X'
          'os_version': 'sierra'
          'browserstack.debug': 'true'
</code>```

This works fine I don't log out but in some test cases, I need to log out to validate some assertions. There it creates the problem.

Is this a bug? Can't we destroy the session upon logout?

答:
You can use plain PHP functions inside the Codeception tests.
This should work, if you call it from inside the test: </p>

```<code>session_destroy();
</code>```

Body:
The session remains alive even after logout.

This is my login file.

public function loginAsAdmin($wpUserName, $wpPassword) {

$I = $this->tester;

$I->amOnPage('/wp-admin');

if ($I->loadSessionSnapshot('login')) {
    return;
}

$I->seeElement(self::$wpUserNameField);
$I->fillfield(self::$wpUserNameField, $wpUserName);

$I->seeElement(self::$wpPasswordField);
$I->fillfield(self::$wpPasswordField, $wpPassword);

$I->seeElement(self::$wpSubmitButton);
$I->click(self::$wpSubmitButton);
$I->wait(5);

$I->saveSessionSnapshot('login');

}

Details

Codeception version: 2.2.10
PHP Version:
Operating System: OS X
Installation type: Composer
List of installed packages (composer show) I am Using lucatume/wp-browser package for codeception

This is my Suite configuration:

class_name: AcceptanceTester modules:

enabled:
    - \Helper\Acceptance
    - WPWebDriver
config:
    WPWebDriver:
        host: 'hub-cloud.browserstack.com'
        port: 80
        browser: 'firefox'
        url: ''
        adminUsername: ''
        adminPassword: ''
        adminPath: '/wp-admin'
        capabilities:
           'browserstack.user': ''
           'browserstack.key': ''
          'os': 'OS X'
          'os_version': 'sierra'
          'browserstack.debug': 'true'

This works fine I don't log out but in some test cases, I need to log out to validate some assertions. There it creates the problem.

Is this a bug? Can't we destroy the session upon logout?

Body:
You can use plain PHP functions inside the Codeception tests.
This should work, if you call it from inside the test:

session_destroy();


问:
Elixir - Looping through and adding to map
I'm rebuilding something in Elixir from some code I built in C#.

It was pretty hacked together, but works perfectly (although not on Linux, hence rebuild).

Essentially what it did was check some RSS feeds and see if there was any new content. This is the code:

```<code>Map historic (URL as key, post title as value).
List<string> blogfeeds
while true
for each blog in blogfeeds
   List<RssPost> posts = getposts(blog)
   for each post in posts
        if post.url is not in historic
           dothing(post)
           historic.add(post)
</code>```

I am wondering how I can do Enumeration effectively in Elixir. Also, it seems that my very process of adding things to "historic" is anti-functional programming.

Obviously the first step was declaring my list of URLs, but beyond that the enumeration idea is messing with my head. Could someone help me out? Thanks.

答:
This might help too:

```<code>count_animals_in_area = fn (area, acc) ->
  acc = case Map.has_key?(area, "duck") do
          true ->
            Map.put(acc, "ducks", (acc["ducks"] + area["duck"]))
          false ->
            acc
        end

  acc = case Map.has_key?(area, "goose") do
          true ->
            Map.put(acc, "geese", (acc["geese"] + area["goose"]))
          false ->
            acc
        end

  acc = case Map.has_key?(area, "cat") do
          true ->
            Map.put(acc, "cats", (acc["cats"] + area["cat"]))
          false ->
            acc
        end

  acc
end

count_animals_in_areas = fn(areas) ->
  acc = %{ "ducks" => 0,
           "geese" => 0,
           "cats" => 0 }
  IO.inspect Enum.reduce areas, acc, count_animals_in_area
end

t1 = [ %{"duck" => 3, "goose" => 4, "cat" => 1},
       %{"duck" => 7, "goose" => 2},
       %{"goose" => 12}]

IO.puts "JEA: begin"
count_animals_in_areas.(t1)
IO.puts "JEA: end"
</code>```

Output:

```<code>iex(31)> c "count_animals.exs"
JEA: begin
%{"cats" => 1, "ducks" => 10, "geese" => 18}
JEA: end
[]
</code>```

I am just learning Elixir so the above is undoubtedly suboptimal, but, hopefully slightly informative.

Body:
I'm rebuilding something in Elixir from some code I built in C#.

It was pretty hacked together, but works perfectly (although not on Linux, hence rebuild).

Essentially what it did was check some RSS feeds and see if there was any new content. This is the code:

Map historic (URL as key, post title as value).
List<string> blogfeeds
while true
for each blog in blogfeeds
   List<RssPost> posts = getposts(blog)
   for each post in posts
        if post.url is not in historic
           dothing(post)
           historic.add(post)

I am wondering how I can do Enumeration effectively in Elixir. Also, it seems that my very process of adding things to "historic" is anti-functional programming.

Obviously the first step was declaring my list of URLs, but beyond that the enumeration idea is messing with my head. Could someone help me out? Thanks.

Body:
This might help too:

count_animals_in_area = fn (area, acc) ->
  acc = case Map.has_key?(area, "duck") do
          true ->
            Map.put(acc, "ducks", (acc["ducks"] + area["duck"]))
          false ->
            acc
        end

  acc = case Map.has_key?(area, "goose") do
          true ->
            Map.put(acc, "geese", (acc["geese"] + area["goose"]))
          false ->
            acc
        end

  acc = case Map.has_key?(area, "cat") do
          true ->
            Map.put(acc, "cats", (acc["cats"] + area["cat"]))
          false ->
            acc
        end

  acc
end

count_animals_in_areas = fn(areas) ->
  acc = %{ "ducks" => 0,
           "geese" => 0,
           "cats" => 0 }
  IO.inspect Enum.reduce areas, acc, count_animals_in_area
end

t1 = [ %{"duck" => 3, "goose" => 4, "cat" => 1},
       %{"duck" => 7, "goose" => 2},
       %{"goose" => 12}]

IO.puts "JEA: begin"
count_animals_in_areas.(t1)
IO.puts "JEA: end"

Output:

iex(31)> c "count_animals.exs"
JEA: begin
%{"cats" => 1, "ducks" => 10, "geese" => 18}
JEA: end
[]

I am just learning Elixir so the above is undoubtedly suboptimal, but, hopefully slightly informative.


问:
problem in passing data to url using GET method
```<code>        params = urllib.urlencode(data)
        headers = {"Content-type": "application/x-www-form-urlencoded",
                   "Accept": "text/plain",
                   }

        conn = httplib.HTTPConnection(self.base_url)
        conn.request('GET', url, params, headers)
        response = conn.getresponse()
        response_data = response.read()
        conn.close()
</code>```

Using above code I am passing data to url. When method is POST every thing is fine. But Method is 'GET' i am not getting any data in response.
But when i am trying

```<code>        url_data = urllib.urlopen(url)
        url_data.read()
</code>```

Then I am getting proper result.What could be the reason? Thanks in advance.

答:
When using "GET" , the parameters should be really placed along with the URL - the "body" argument (to which ou are passing "params") is only used in post requests -
In other words, try this instead:</p>

```<code>conn.request('GET', url + "?" + params, None, headers)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
        params = urllib.urlencode(data)
        headers = {"Content-type": "application/x-www-form-urlencoded",
                   "Accept": "text/plain",
                   }

        conn = httplib.HTTPConnection(self.base_url)
        conn.request('GET', url, params, headers)
        response = conn.getresponse()
        response_data = response.read()
        conn.close()

Using above code I am passing data to url. When method is POST every thing is fine. But Method is 'GET' i am not getting any data in response.
But when i am trying

        url_data = urllib.urlopen(url)
        url_data.read()

Then I am getting proper result.What could be the reason? Thanks in advance.

Body:
When using "GET" , the parameters should be really placed along with the URL - the "body" argument (to which ou are passing "params") is only used in post requests -
In other words, try this instead:

conn.request('GET', url + "?" + params, None, headers)


问:
Libgdx. Rectangle position on screen different from code
I’m trying to develop a very simple game for Android using libgdx: there is a bug that appears randomly on the screen and you have to touch it where the bug is to kill it. If you do, the game goes on until you miss three times, and then is game over. Simple enough.

So, I see the bug, I touch it right in the middle, but I miss: the touch point isn’t included in the bug rectangle, which is different from what I see on the screen. I print out the coordinates of both rectangle and point and I see that those of the rectangle were correct a couple of deltaTimes ago, but are no longer, despite of what I see on the screen. I have looked all over the place for a solution, read tutorials, libgdx documentation, but I don’t get it, I'm getting nuts.

This is the code for the touchDown event on the constructor

```<code>Gdx.input.setInputProcessor(new InputAdapter(){
        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            unidadTiempo = unidadTiempo - aceleracion;
            toque.set(screenX, screenY, 0f);
            camara.unproject(toque);

            if (bicho.contains(toque.x, toque.y)) {
                aplastamiento.play();
                bichosLiquidados++;
            } else {
                burla.play();
                vidas--;

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

This is the method drawing the bugs and accelerating the bug appearing pace

```<code>void apareceBicho(){
    ultimoBicho = TimeUtils.nanoTime();
    juego.letra.draw(juego.batch, "Puntuacion: " + bichosLiquidados, 0, altoPantalla);
    bicho.setX(xAleatorio);
    bicho.setY(yAleatorio);
    juego.batch.draw(bichoImagen, bicho.x, bicho.y);

    while (TimeUtils.nanoTime() - ultimoBicho < unidadTiempo && vidas > 0){
        unidadTiempo = unidadTiempo - aceleracion;
        xAleatorio = MathUtils.random(randomx);
        yAleatorio = MathUtils.random(randomy);
    }
    if(vidas == 0){

        risa.play();
        TextureRegion fotogramActual = animacionFinal.getKeyFrame(stateTime, true);
        juego.batch.draw(fotogramActual, bicho.x, bicho.y);
        juego.batch.flush();
        gameover = true;
    }
    if (gameover){
        juego.setScreen(new PantallaFinal(juego, this));
    }
}
</code>```

And lastly, the render method

```<code>@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0.2f, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stateTime += Gdx.graphics.getDeltaTime();

    camara.update();
    juego.batch.setProjectionMatrix(camara.combined);
    juego.batch.begin();

    juego.batch.draw(yerbita, 0, 0, anchoPantalla, altoPantalla);

    apareceBicho();

    juego.batch.end();
}
</code>```

This is what I meant by a couple of deltaTimes ago:

06-04 09:30:05.942 RECTANGLE POSITION AIMED TO: Posicion del bicho: 612.88776, 200.9191, 133.0, 126.0

06-04 09:30:07.950 ACTUAL RECTANGLE POSITION: Posicion del bicho: 426.92572, 111.10537, 133.0, 126.0

06-04 09:30:09.946 TOUCH POSITION: Coordenadas toque = 659.2, 250.3111

答:
Possible reason :

bicho having zero width and height.

If you created rectangle by default constructor then need to be set width and hight of that rectangle.

```<code>bicho = new Rectangle();
bicho.setSize(bichoImagen.getWidth(),bichoImagen.getHeight());
</code>```

Body:
I’m trying to develop a very simple game for Android using libgdx: there is a bug that appears randomly on the screen and you have to touch it where the bug is to kill it. If you do, the game goes on until you miss three times, and then is game over. Simple enough.

So, I see the bug, I touch it right in the middle, but I miss: the touch point isn’t included in the bug rectangle, which is different from what I see on the screen. I print out the coordinates of both rectangle and point and I see that those of the rectangle were correct a couple of deltaTimes ago, but are no longer, despite of what I see on the screen. I have looked all over the place for a solution, read tutorials, libgdx documentation, but I don’t get it, I'm getting nuts.

This is the code for the touchDown event on the constructor

Gdx.input.setInputProcessor(new InputAdapter(){
        @Override
        public boolean touchDown(int screenX, int screenY, int pointer, int button) {
            unidadTiempo = unidadTiempo - aceleracion;
            toque.set(screenX, screenY, 0f);
            camara.unproject(toque);

            if (bicho.contains(toque.x, toque.y)) {
                aplastamiento.play();
                bichosLiquidados++;
            } else {
                burla.play();
                vidas--;

            }
            return true;
        }
    });

This is the method drawing the bugs and accelerating the bug appearing pace

void apareceBicho(){
    ultimoBicho = TimeUtils.nanoTime();
    juego.letra.draw(juego.batch, "Puntuacion: " + bichosLiquidados, 0, altoPantalla);
    bicho.setX(xAleatorio);
    bicho.setY(yAleatorio);
    juego.batch.draw(bichoImagen, bicho.x, bicho.y);

    while (TimeUtils.nanoTime() - ultimoBicho < unidadTiempo && vidas > 0){
        unidadTiempo = unidadTiempo - aceleracion;
        xAleatorio = MathUtils.random(randomx);
        yAleatorio = MathUtils.random(randomy);
    }
    if(vidas == 0){

        risa.play();
        TextureRegion fotogramActual = animacionFinal.getKeyFrame(stateTime, true);
        juego.batch.draw(fotogramActual, bicho.x, bicho.y);
        juego.batch.flush();
        gameover = true;
    }
    if (gameover){
        juego.setScreen(new PantallaFinal(juego, this));
    }
}

And lastly, the render method

@Override
public void render(float delta) {
    Gdx.gl.glClearColor(0, 0.2f, 0, 1);
    Gdx.gl.glClear(GL20.GL_COLOR_BUFFER_BIT);
    stateTime += Gdx.graphics.getDeltaTime();

    camara.update();
    juego.batch.setProjectionMatrix(camara.combined);
    juego.batch.begin();

    juego.batch.draw(yerbita, 0, 0, anchoPantalla, altoPantalla);

    apareceBicho();

    juego.batch.end();
}

This is what I meant by a couple of deltaTimes ago:

06-04 09:30:05.942 RECTANGLE POSITION AIMED TO: Posicion del bicho: 612.88776, 200.9191, 133.0, 126.0

06-04 09:30:07.950 ACTUAL RECTANGLE POSITION: Posicion del bicho: 426.92572, 111.10537, 133.0, 126.0

06-04 09:30:09.946 TOUCH POSITION: Coordenadas toque = 659.2, 250.3111

Body:
Possible reason :

bicho having zero width and height.

If you created rectangle by default constructor then need to be set width and hight of that rectangle.

bicho = new Rectangle();
bicho.setSize(bichoImagen.getWidth(),bichoImagen.getHeight());


问:
Check if something in a dictionary is the same as the max value in that dictionary?
How can I check if something in a dictionary is the same as the max in that dictionary. In other words, get all the max values instead of the max value with lowest position.
I have this code which returns the max variable name and value:

```<code>d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}
print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
print (max(d.items(), key=lambda x: x[1]))
</code>```

Now it prints the variable with the highest value plus the value itself, but what if there are two or three variables with the same max value? I would like to print all of the max values.

Edit:

The user has to fill in a form, which adds values to the variables in the dictionary. When the user is done, there will be one, two or more variables with the highest value. For example, the code gives me this:

2017-06-08 15:05:43 g_dirt4 9 g_destiny2 8 g_southpark 5 g_codww2 8 g_bfront2 8 g_reddead2 7 g_fifa18 8 g_motogp17 9 g_elderscrolls 5 g_crashbandicoot 6
2017-06-08 15:05:43 ('g_dirt4', 9)
```

Now it tells me that g_dirt4 has the highest value of 9, but if you look at motogp17, it also had 9 but it doesn't get printed because it's at a higher position in the dictionary. So how do I print them both? And what if it has 3 variables with the same max value?

答:
Given a dictionary

```<code>d = {'too': 2, 'one': 1, 'two': 2, 'won': 1, 'to': 2}
</code>```

the following command:

```<code>result = [(n,v) for n,v in d.items() if v == max(d.values())]
</code>```

yields: [('too', 2), ('two', 2), ('to', 2)]

Body:
How can I check if something in a dictionary is the same as the max in that dictionary. In other words, get all the max values instead of the max value with lowest position.
I have this code which returns the max variable name and value:

d = {'g_dirt4': g_dirt4, 'g_destiny2': g_destiny2, 'g_southpark': g_southpark, 'g_codww2': g_codww2, 'g_bfront2': g_bfront2, 'g_reddead2': g_reddead2, 'g_fifa18': g_fifa18, 'g_motogp17': g_motogp17, 'g_elderscrolls': g_elderscrolls, 'g_crashbandicoot': g_crashbandicoot}
print("g_dirt4", g_dirt4, "g_destiny2", g_destiny2, "g_southpark", g_southpark, "g_codww2", g_codww2, "g_bfront2", g_bfront2, "g_reddead2", g_reddead2, "g_fifa18", g_fifa18, "g_motogp17", g_motogp17, "g_elderscrolls", g_elderscrolls, "g_crashbandicoot", g_crashbandicoot)
print (max(d.items(), key=lambda x: x[1]))

Now it prints the variable with the highest value plus the value itself, but what if there are two or three variables with the same max value? I would like to print all of the max values.

Edit:

The user has to fill in a form, which adds values to the variables in the dictionary. When the user is done, there will be one, two or more variables with the highest value. For example, the code gives me this:

2017-06-08 15:05:43 g_dirt4 9 g_destiny2 8 g_southpark 5 g_codww2 8 g_bfront2 8 g_reddead2 7 g_fifa18 8 g_motogp17 9 g_elderscrolls 5 g_crashbandicoot 6
2017-06-08 15:05:43 ('g_dirt4', 9)

Now it tells me that g_dirt4 has the highest value of 9, but if you look at motogp17, it also had 9 but it doesn't get printed because it's at a higher position in the dictionary. So how do I print them both? And what if it has 3 variables with the same max value?

Body:
Given a dictionary

d = {'too': 2, 'one': 1, 'two': 2, 'won': 1, 'to': 2}

the following command:

result = [(n,v) for n,v in d.items() if v == max(d.values())]

yields: [('too', 2), ('two', 2), ('to', 2)]


问:
jQuery treetable using events
I need assistance figuring out how to use the events provided with the jQuery plugin treetable.

jQuery treetable (PLUGIN): http://plugins.jquery.com/treetable/

This is what I am trying to solve.

When a branch collapses the plugin should trigger an event called "onNodeCollapse".

When a branch collapses I just need to display a javascript popup that says "A branch has collapsed".  From here I can tie it into our own functions.

I have tried several different methods as well as searching on line for a solution.

Example script:  http://jsfiddle.net/djlerman/yLb25dy9/

```<code><!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>jQuery treetable with event trigger - jsFiddle demo by djlerman</title>

  <link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css">
  <link rel="stylesheet" type="text/css" href="http://ludo.cubicphuse.nl/jquery-treetable/css/screen.css">
  <link rel="stylesheet" type="text/css" href="http://ludo.cubicphuse.nl/jquery-treetable/css/jquery.treetable.css">
  <link rel="stylesheet" type="text/css" href="http://ludo.cubicphuse.nl/jquery-treetable/css/jquery.treetable.theme.default.css">

  <script type='text/javascript' src='//code.jquery.com/jquery-1.11.0.js'></script>
  <script type='text/javascript' src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/jquery-ui.min.js"></script>
  <script type='text/javascript' src="http://ludo.cubicphuse.nl/jquery-treetable/jquery.treetable.js"></script>

  <script type='text/javascript'>//<![CDATA[
    $(window).load(function(){
    $("#example-basic").treetable({ expandable: true });

    /*
        Trying to get this function to happen when
        "onNodeCollapse" event happens
    */
    $("#example-basic").on("onNodeCollapse", function() {
        alert( "A branch has collapsed" );
    });
    });//]]>
  </script>
</head>
<body>
  <table id="example-basic">
    <caption>Basic jQuery treetable Example</caption>
    <thead>
      <tr>
        <th>Tree column</th>
        <th>Additional data</th>
      </tr>
    </thead>
    <tbody>
      <tr data-tt-id="1">
        <td>Node 1: Click on the icon in front of me to expand this branch.</td>
        <td>I live in the second column.</td>
      </tr>
      <tr data-tt-id="1.1" data-tt-parent-id="1">
        <td>Node 1.1: Look, I am a table row <em>and</em> I am part of a tree!</td>
        <td>Interesting.</td>
      </tr>
      <tr data-tt-id="1.1.1" data-tt-parent-id="1.1">
        <td>Node 1.1.1: I am part of the tree too!</td>
        <td>That's it!</td>
      </tr>
      <tr data-tt-id="2">
        <td>Node 2: I am another root node, but without children</td>
        <td>Hurray!</td>
      </tr>
    </tbody>
  </table>

</body>

</html>
</code>```

答:
Following code worked for me:

```<code>function displayNeighborhoodTableTreeDialog(treeHtml){
var nhTreeDlg;
nhTreeDlg = $("#Table_Tree").dialog({
    modal: true,
    title: "BCP Explorer",
    height: 693, width: 525, left:0, top:0,
    button: {
        Ok: function() {$(this).dialog("close")}
    },
    show:{effect:'scale', duration:'300'},
    hide:{effect:'explode', duration:'300'}
});''
nhTreeDlg.prev(".ui-dialog-titlebar").css({"background":"#47669E", "color":"white", "font-size":"13px", "font-weight":"normal"}) ;
$("div#Table_Tree").find("table#nh_table").find("tbody").html(treeHtml);

    var treeRoot = $("div#Table_Tree").find("table#nh_table").find("tbody").html();
    $("div#Table_Tree").find("table#nh_table").find("tbody").html(treeRoot + treeHtml);
$("table#nh_table").find("tbody").html());

    $("#nh_table").treetable({
            expandable: true, clickableNodeNames: false, indent:30,
            onInitialized: function(){
                alert("Tree table initialized");
            },
            onNodeCollapse: function() {
                alert("Tree table Collapse");
                alert($(this.row).data("tt-id") + " has collapsed");
            },
            onNodeExpand: function()  {
                alert("Tree table Expand");
                alert($(this.row).data("tt-id") + " has expanded");
            }});
    nhTreeDlg.dialog("open");
}
</code>```

The treeTable is like this

```<code><div style='height:100%; max-height:520px;width:427px;border:1px #808080 solid;vertical-align:top;display:inline-block;overflow: hidden;'>
<div id="ttSize" style='max-height:520px;height:520px;overflow-y: scroll;'>
            <table id=nh_table style='border:none;'>
        <tbody>
        <tr data-tt-branch='true' data-tt-id='bcp_farm'><td><span class=bcp_farm>Boardwalk Farm</span></td></tr>
  <tr data-tt-id=eportal-2 data-tt-parent-id='eportal' ><td><span class=nh_0>Root</span></td></tr>
  <tr data-tt-branch='true' data-tt-id='collabs-eportal-2' data-tt-parent-id='eportal-2'><td><span class=collab2>Collabs</span></td></tr>
  <tr data-tt-branch='true' data-tt-id='members-eportal-2' data-tt-parent-id='eportal-2'><td><span class=members>Members</span></td></tr>
  <tr data-tt-id=eportal-3 data-tt-parent-id=eportal-2><td><span class=nh_child>Buyer-XX</span></td></tr>
  <tr data-tt-branch='true' data-tt-id='collabs-eportal-3' data-tt-parent-id='eportal-3'><td><span class=collab2>Collabs</span></td></tr>
  <tr data-tt-branch='true' data-tt-id='members-eportal-3' data-tt-parent-id='eportal-3'><td><span class=members>Members</span></td></tr>
    </tbody>
    </table>
</div>
</code>```

Following is the image:

After clicking one node you get following alert

Title: jQuery treetable using events

Body:
I need assistance figuring out how to use the events provided with the jQuery plugin treetable.

jQuery treetable (PLUGIN): http://plugins.jquery.com/treetable/

This is what I am trying to solve.

When a branch collapses the plugin should trigger an event called "onNodeCollapse".

When a branch collapses I just need to display a javascript popup that says "A branch has collapsed".  From here I can tie it into our own functions.

I have tried several different methods as well as searching on line for a solution.

Example script:  http://jsfiddle.net/djlerman/yLb25dy9/

<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>jQuery treetable with event trigger - jsFiddle demo by djlerman</title>

  <link rel="stylesheet" type="text/css" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.0/themes/smoothness/jquery-ui.css">
  <link rel="stylesheet" type="text/css" href="http://ludo.cubicphuse.nl/jquery-treetable/css/screen.css">
  <link rel="stylesheet" type="text/css" href="http://ludo.cubicphuse.nl/jquery-treetable/css/jquery.treetable.css">
  <link rel="stylesheet" type="text/css" href="http://ludo.cubicphuse.nl/jquery-treetable/css/jquery.treetable.theme.default.css">

Basic jQuery treetable Example

        Tree column
        Additional data

        Node 1: Click on the icon in front of me to expand this branch.
        I live in the second column.

        Node 1.1: Look, I am a table row and I am part of a tree!
        Interesting.

        Node 1.1.1: I am part of the tree too!
        That's it!

        Node 2: I am another root node, but without children
        Hurray!

Body:
Following code worked for me:

function displayNeighborhoodTableTreeDialog(treeHtml){
var nhTreeDlg;
nhTreeDlg = $("#Table_Tree").dialog({
    modal: true,
    title: "BCP Explorer",
    height: 693, width: 525, left:0, top:0,
    button: {
        Ok: function() {$(this).dialog("close")}
    },
    show:{effect:'scale', duration:'300'},
    hide:{effect:'explode', duration:'300'}
});''
nhTreeDlg.prev(".ui-dialog-titlebar").css({"background":"#47669E", "color":"white", "font-size":"13px", "font-weight":"normal"}) ;
$("div#Table_Tree").find("table#nh_table").find("tbody").html(treeHtml);

    var treeRoot = $("div#Table_Tree").find("table#nh_table").find("tbody").html();
    $("div#Table_Tree").find("table#nh_table").find("tbody").html(treeRoot + treeHtml);
$("table#nh_table").find("tbody").html());

    $("#nh_table").treetable({
            expandable: true, clickableNodeNames: false, indent:30,
            onInitialized: function(){
                alert("Tree table initialized");
            },
            onNodeCollapse: function() {
                alert("Tree table Collapse");
                alert($(this.row).data("tt-id") + " has collapsed");
            },
            onNodeExpand: function()  {
                alert("Tree table Expand");
                alert($(this.row).data("tt-id") + " has expanded");
            }});
    nhTreeDlg.dialog("open");
}

The treeTable is like this

<div style='height:100%; max-height:520px;width:427px;border:1px #808080 solid;vertical-align:top;display:inline-block;overflow: hidden;'>
<div id="ttSize" style='max-height:520px;height:520px;overflow-y: scroll;'>
            <table id=nh_table style='border:none;'>
        <tbody>
        <tr data-tt-branch='true' data-tt-id='bcp_farm'><td><span class=bcp_farm>Boardwalk Farm</span></td></tr>
  <tr data-tt-id=eportal-2 data-tt-parent-id='eportal' ><td><span class=nh_0>Root</span></td></tr>
  <tr data-tt-branch='true' data-tt-id='collabs-eportal-2' data-tt-parent-id='eportal-2'><td><span class=collab2>Collabs</span></td></tr>
  <tr data-tt-branch='true' data-tt-id='members-eportal-2' data-tt-parent-id='eportal-2'><td><span class=members>Members</span></td></tr>
  <tr data-tt-id=eportal-3 data-tt-parent-id=eportal-2><td><span class=nh_child>Buyer-XX</span></td></tr>
  <tr data-tt-branch='true' data-tt-id='collabs-eportal-3' data-tt-parent-id='eportal-3'><td><span class=collab2>Collabs</span></td></tr>
  <tr data-tt-branch='true' data-tt-id='members-eportal-3' data-tt-parent-id='eportal-3'><td><span class=members>Members</span></td></tr>
    </tbody>
    </table>
</div>

Following is the image:

After clicking one node you get following alert


问:
Quantify the comparison between two columns VBA
Here's what I'm trying to do:
Column "a" contains, let's say, type of car and column "b" contains that car's color. what I need to do is format a table that shows the quantity of, for instance, "Blue Civics" so that I can compare that to "Blue Jeeps" and "Red Landrovers." does anyone know an easy way to do this without initializing a bunch of variables and making a bunch of if statements?

Basically, I'm going to have 4 types of car and each of those cars has 4 possible colors. Right now, I have something like this:

```<code>Dim HondaRed As Integer, HondaBlue As Integer
For Each a In ary
    On Error Resume Next
    cl.Add a, CStr(a)
    'if statements that ask if column "a" is is honda if column "b" is blue, then incramanets HondaBlue by 1'
Next a
</code>```

I could do this in c++ no problem. The problem is, I'm still leraning VB so any help or resources to point me in the right direction would be grately appreciated. Thanks!

答:
If you want a VBA example, say we start with:

Here is some very simple code:

```<code>Sub TableMaker()
    Dim N As Long, i As Long, j As Long, k As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To N
        ca = Cells(i, 1)
        cl = Cells(i, 2)
        If ca = "Honda" Then j = 2
        If ca = "Toyota" Then j = 3
        If ca = "Chevy" Then j = 4
        If ca = "Ford" Then j = 5
        If cl = "Blue" Then k = 5
        If cl = "Black" Then k = 6
        If cl = "Red" Then k = 7
        If cl = "White" Then k = 8
        'MsgBox j & vbCrLf & k & vbCrLf & Cells(j, k)
        Cells(j, k) = Cells(j, k) + 1
    Next i
End Sub
</code>```

will produce:

The headers in the frequency table were added manually.  The i , j values in the IFs are based on the table's location.

Using a Pivot Table is still the best approach.

Body:
Here's what I'm trying to do:
Column "a" contains, let's say, type of car and column "b" contains that car's color. what I need to do is format a table that shows the quantity of, for instance, "Blue Civics" so that I can compare that to "Blue Jeeps" and "Red Landrovers." does anyone know an easy way to do this without initializing a bunch of variables and making a bunch of if statements?

Basically, I'm going to have 4 types of car and each of those cars has 4 possible colors. Right now, I have something like this:

Dim HondaRed As Integer, HondaBlue As Integer
For Each a In ary
    On Error Resume Next
    cl.Add a, CStr(a)
    'if statements that ask if column "a" is is honda if column "b" is blue, then incramanets HondaBlue by 1'
Next a

I could do this in c++ no problem. The problem is, I'm still leraning VB so any help or resources to point me in the right direction would be grately appreciated. Thanks!

Body:
If you want a VBA example, say we start with:

Here is some very simple code:

Sub TableMaker()
    Dim N As Long, i As Long, j As Long, k As Long
    N = Cells(Rows.Count, "A").End(xlUp).Row
    For i = 1 To N
        ca = Cells(i, 1)
        cl = Cells(i, 2)
        If ca = "Honda" Then j = 2
        If ca = "Toyota" Then j = 3
        If ca = "Chevy" Then j = 4
        If ca = "Ford" Then j = 5
        If cl = "Blue" Then k = 5
        If cl = "Black" Then k = 6
        If cl = "Red" Then k = 7
        If cl = "White" Then k = 8
        'MsgBox j & vbCrLf & k & vbCrLf & Cells(j, k)
        Cells(j, k) = Cells(j, k) + 1
    Next i
End Sub

will produce:

The headers in the frequency table were added manually.  The i , j values in the IFs are based on the table's location.

Using a Pivot Table is still the best approach.


问:
js regexp variable parenthesis
So I have a function that receives an argument (namedc), then I create a regular expression like so: regC = new RegExp(c,'gi'). Now this works fine for most characters, but my function can also receive a ( or other paretheses. This cases create an error.
I tried this: regC = '/['+c+']/gi', but it didn't work

答:
Pass the character set '['+c+']'  to RegExp functions as

```<code>regC = new RegExp('['+c+']','gi');
</code>```

Because

```<code>regC = '/['+c+']/gi'
</code>```

Makes a string

Title: js regexp variable parenthesis

Body:
Pass the character set '['+c+']'  to RegExp functions as

regC = new RegExp('['+c+']','gi');

Because

regC = '/['+c+']/gi'

Makes a string


问:
How to load/unload assembly?
I'm working on a C# solution, and I need to compile a project in the solution, load its assemblies and explore its types.

My problem is, once I load the assembly, I can't unload it, so I'm forced to close VS and reopen it if I want to recompile the project whose assembly I'm exploring. I've read that loading the assembly in a different AppDomain can solve my problem, but with that I lose the LoadFrom method and I'm interested in automatically loading dependencies.

So, my question is: how can I load an assembly with its dependencies, explore its types and then unload it?

答:
I ended up solving it the ugly way: copying the assembly file to a temporary folder and opening it from there. That way I can explore it without keeping the original assembly open and throwing errors all around when trying to recompile.

Thanks to everyone for taking time to help.

Title: How to load/unload assembly?


问:
Require at least one of two fields using vee-validate on VueJS 2.0
I am using vee-validate and I have two fields; one for Home Phone and one for Cell Phone. I don't need to make both 'required' for the rules, but what I need is at least one of these required.

So, my question, is it possible to set up a rule that checks both fields for input in at least one of them?

答:
Ok, didn't take long, but I have this working. It just took a bit of digging, so posting my answer so it can help others.

First, my input fields are homephone and cellphone and at least one of them is required.

This is achievable using the computed properties in Vue with the following:

computed: {
    isHomePhoneRequired() {
        if(this.cellphone === '')
            return true; // homephone is required
        return false;
    },
    isCellPhoneRequired() {
        // check if homephone is empty
        if(this.homephone === '')
            return true; // cellphone is required
        return false;
    }
}
```
<p>and my HTML looks like the following:</p>
<pre class="lang-html prettyprint-override"><code><div class="form-group" :class="{'has-error': errors.has('homephone') }">
    <div class="label">Home Phone<i class="fa fa-asterisk required" aria-hidden="true"></i></div>
    <div ><input type="text" class="form-control" v-model="homephone" v-validate ="{ rules: { required: this.isHomePhoneRequired} }" data-vv-name="homephone" data-vv-as="Home Phone" /></div>
    <p class="text-danger" v-if="errors.has('homephone')">{{ errors.first('homephone') }}</p>
</div>
<div class="form-group" :class="{'has-error': errors.has('cellphone') }">
    <div class="label">Cell Phone<i class="fa fa-asterisk required" aria-hidden="true"></i></div>
    <div ><input type="text" class="form-control" v-model="cellphone" v-validate ="{ rules: { required: this.isCellPhoneRequired} }" data-vv-name="cellphone" data-vv-as="Cell Phone" /></div>
    <p class="text-danger" v-if="errors.has('cellphone')">{{ errors.first('cellphone') }}</p>
</div>
</code>```

Notice that v-validate now gets an object passed containing the type (rules), the validation to use (required), and the computed property (isHomePhoneRequired).

Body:
Ok, didn't take long, but I have this working. It just took a bit of digging, so posting my answer so it can help others.

First, my input fields are homephone and cellphone and at least one of them is required.

This is achievable using the computed properties in Vue with the following:

computed: {
    isHomePhoneRequired() {
        if(this.cellphone === '')
            return true; // homephone is required
        return false;
    },
    isCellPhoneRequired() {
        // check if homephone is empty
        if(this.homephone === '')
            return true; // cellphone is required
        return false;
    }
}

and my HTML looks like the following:

<div class="form-group" :class="{'has-error': errors.has('homephone') }">
    <div class="label">Home Phone<i class="fa fa-asterisk required" aria-hidden="true"></i></div>
    <div ><input type="text" class="form-control" v-model="homephone" v-validate ="{ rules: { required: this.isHomePhoneRequired} }" data-vv-name="homephone" data-vv-as="Home Phone" /></div>
    <p class="text-danger" v-if="errors.has('homephone')">{{ errors.first('homephone') }}</p>
</div>
<div class="form-group" :class="{'has-error': errors.has('cellphone') }">
    <div class="label">Cell Phone<i class="fa fa-asterisk required" aria-hidden="true"></i></div>
    <div ><input type="text" class="form-control" v-model="cellphone" v-validate ="{ rules: { required: this.isCellPhoneRequired} }" data-vv-name="cellphone" data-vv-as="Cell Phone" /></div>
    <p class="text-danger" v-if="errors.has('cellphone')">{{ errors.first('cellphone') }}</p>
</div>

Notice that v-validate now gets an object passed containing the type (rules), the validation to use (required), and the computed property (isHomePhoneRequired).


问:
SWFAddress: adding "/" char at the end of an URL via JavaScript
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.

So something like this:

```<code>http://mysite.com/section

// and after click to a specific <a ="#">button</a> get
http://mysite.com/section/#/sub-content

// instead of
http://mysite.com/section#/sub-content
</code>```

I've started with this code to do it:

```<code>$(".time_dot, .time_year").click (function () {
    onClickEvent (this);
});

function onClickEvent (dom) {
    var timer = setTimeout (function () {
        SWFAddress.setValue($(dom).parent().attr("id"));
    }, 200);
    // do something else
}
</code>```

The setTimeout method is used to avoid the  button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....

How can I do that?

答:
you mean like </p>

```<code>$(".time_dot, .time_year").click (function () {
   setTimeout (function () {
         SWFAddress.setValue("/"+$(this).parent().attr("id")+"/");
    }, 200);

});
</code>```

Body:
how can I add the / char at the end of the URL without force the user to write it?
I'm starting to work with SWFAddress using JavaScript and jQuery directly (without Flash) like this wonderful site.

So something like this:

http://mysite.com/section

// and after click to a specific button get
http://mysite.com/section/#/sub-content

// instead of
http://mysite.com/section#/sub-content

I've started with this code to do it:

$(".time_dot, .time_year").click (function () {
    onClickEvent (this);
});

function onClickEvent (dom) {
    var timer = setTimeout (function () {
        SWFAddress.setValue($(dom).parent().attr("id"));
    }, 200);
    // do something else
}

The setTimeout method is used to avoid the  button overwrite the SWFAddress.setValue method, but I don't know a way to change the URL address to url.com/content#/... to url.com/content/#/....

How can I do that?

Body:
you mean like

$(".time_dot, .time_year").click (function () {
   setTimeout (function () {
         SWFAddress.setValue("/"+$(this).parent().attr("id")+"/");
    }, 200);

});


问:
How do I do something every n-th attempt?
I have a game that is based on attempts rather than score. And I wish to display a pop up every 10 attempts. What is the best way, using Swift, to calculate every 10 intervals of something?

Currently I call a function to increment the attempts value which includes: gamesPlayedSaved += 1. The closest question I found on here uses timers, which wouldn't work in my case.

So far, I have this (WHICH IS EXTREMELY UGLY):

```<code>if(gamesPlayedSaved == 10 ||
                    gamesPlayedSaved == 20 ||
                    gamesPlayedSaved == 30 ||
                    gamesPlayedSaved == 40 ||
                    gamesPlayedSaved == 50 ||
                    gamesPlayedSaved == 60 ||
                    gamesPlayedSaved == 70 ||
                    gamesPlayedSaved == 80 ||
                    gamesPlayedSaved == 90 ||
                    gamesPlayedSaved == 100){
    // call pop up
}
</code>```

And it also doesn't account for any intervals over 100.

答:
use modulus %. if (gamesPlayedSaved % 10 == 0)

It will finds the remainder after division of 10

Body:
I have a game that is based on attempts rather than score. And I wish to display a pop up every 10 attempts. What is the best way, using Swift, to calculate every 10 intervals of something?

Currently I call a function to increment the attempts value which includes: gamesPlayedSaved += 1. The closest question I found on here uses timers, which wouldn't work in my case.

So far, I have this (WHICH IS EXTREMELY UGLY):

if(gamesPlayedSaved == 10 ||
                    gamesPlayedSaved == 20 ||
                    gamesPlayedSaved == 30 ||
                    gamesPlayedSaved == 40 ||
                    gamesPlayedSaved == 50 ||
                    gamesPlayedSaved == 60 ||
                    gamesPlayedSaved == 70 ||
                    gamesPlayedSaved == 80 ||
                    gamesPlayedSaved == 90 ||
                    gamesPlayedSaved == 100){
    // call pop up
}

And it also doesn't account for any intervals over 100.


问:
When are check constraints evaluated?
I have a table of Records

```<code>ID
EntityID
Value
Status
</code>```

and a table of Entities

```<code>ID
Col1
Col2
CurrentRecordID
</code>```

CurrentRecordID should be the Record tied to the Entity with a Status of 0

I have two check constraints
One on table Entity that checks to make sure that CurrentRecordID is in fact the current record and one on Record that checks to make sure that, if it has a status of 0, its EntityID has a CurrentRecordID that matches its ID.

So essentially, the two check constraints do the same thing, but separately on each table

Do check constraints run at the very end of a transaction or do they run like triggers after each insert/update on the tables?

If they run after each modification, will these two constraints conflict with one another (meaning, the constraint will throw an error before the next table has a chance to update its value).

Here is an example of a query that runs to insert a new record, and set it as the current for a given Entity

```<code>UPDATE Record SET Status = 1 WHERE Status = 0 AND EntityID = @EntityID
INSERT INTO Record(EntityID, Value, Status) VALUES(@EntityID, 100, 0)
DECLARE @RecordID INT = @@IDENTITY
UPDATE Entity SET CurrentRecordID = RecordID WHERE ID = @EntityID
</code>```

答:
Constraints don't run like a trigger. They evaluate the rules prior to making a change to the data.

The constraint check happens when the data change is attempted. If the attempted change to Table1 fails the check constraint it will through an exception.

Title: When are check constraints evaluated?

Body:
I have a table of Records

ID
EntityID
Value
Status

and a table of Entities

ID
Col1
Col2
CurrentRecordID

CurrentRecordID should be the Record tied to the Entity with a Status of 0

I have two check constraints
One on table Entity that checks to make sure that CurrentRecordID is in fact the current record and one on Record that checks to make sure that, if it has a status of 0, its EntityID has a CurrentRecordID that matches its ID.

So essentially, the two check constraints do the same thing, but separately on each table

Do check constraints run at the very end of a transaction or do they run like triggers after each insert/update on the tables?

If they run after each modification, will these two constraints conflict with one another (meaning, the constraint will throw an error before the next table has a chance to update its value).

Here is an example of a query that runs to insert a new record, and set it as the current for a given Entity

UPDATE Record SET Status = 1 WHERE Status = 0 AND EntityID = @EntityID
INSERT INTO Record(EntityID, Value, Status) VALUES(@EntityID, 100, 0)
DECLARE @RecordID INT = @@IDENTITY
UPDATE Entity SET CurrentRecordID = RecordID WHERE ID = @EntityID


问:
How to set Time To Live (device expiry) without using C# on Azure Notification Hub
I know Improved Per Message Telemetry and device expiry for Notification Hubs article describes setting TTL programmatically, but this seems a bit of a roundabout method, especially when maintaining multiple environments.

Is there any way to perform this through the Azure portal?

答:
At the moment there's no way to set the property through the portal, unfortunately.

One alternative to using C# would be to create/update your hub through REST API by using RegistrationTtl property on NotificationHubDescription object

You can also leave feedback about it and if enough people upvote it, the product team will prioritize the feature.


问:
Data Migration Issue. Need advice
My data was migrated from one database into another one. And I'm concerned about the results. In old database we had a table like this: Old Database

In a new database it looks like this:
New Database

I find it really inconvenient that different cars are listed in one row if they have the same delivery date. Sometimes I need statistical reports on how many cars of each brand and color we have, what is the average age and etc. Would it be possible to get accurate statistical reports if data is organized like this? I think they need to rebuild the whole table. But they say it can stay like that. I showed to them an example of the reports from the old database where each car was listed on a separate row, and they did some formatting in cognos and provided me with a very similar report, with one single column for each attribute and each car listed on a separate line. My question is, will it be OK to leave the structure of the table like in the new database, or is it better to make it the same as it was in the old database? Please, advice. I need accurate numbers in statistical reports, that's my main concern.

答:
Based on what you shared the new structure seems flawed. It seems like you need a schema change after n number of cars. That would be poor DB design.

From a reporting point of view it is not an issue, you can always do a pivot on a data column etc. It is more expensive than the old schema, but if there are other reports that are cheaper, that would be a trade off.

Title: Data Migration Issue. Need advice


问:
C#: Access Enum from another class
I know I can declare an enum directly in the Namespace so everyone can access it being in the same namespace.

But can I declare it in a class to access from other class:

public class Class1
{
    public enum Mode { Selected, New }
}

public class Class2
{
    var class1 = new ();
    // Set the Mode
    class1.Mode = Mode.Selected;
}
```

Is it possible to use enums without declaring it in the namespace?

答:
If you are trying to do what is described below it will not work...

```<code>    public class MyClass1
    {
        private enum Mode { New, Selected };
        public Mode ModeProperty { get; set; }
    }

    public class MyClass2
    {
        public MyClass2()
        {
            var myClass1 = new MyClass1();

            //this will not work due to protection level
            myClass1.ModeProperty = MyClass1.Mode.
        }
    }
</code>```

What you could do however is below, which will work...

```<code>    public interface IEnums
    {
        public enum Mode { New, Selected };
    }

    public class MyClass1
    {
        public IEnums.Mode ModeProperty { get; set; }
    }

    public class MyClass2
    {
        public MyClass2()
        {
            var myClass1 = new MyClass1();

            //this will work
            myClass1.ModeProperty = IEnums.Mode.New;
        }
    }
</code>```

Title: C#: Access Enum from another class

Body:
I know I can declare an enum directly in the Namespace so everyone can access it being in the same namespace.

But can I declare it in a class to access from other class:

public class Class1
{
    public enum Mode { Selected, New }
}

public class Class2
{
    var class1 = new ();
    // Set the Mode
    class1.Mode = Mode.Selected;
}

Is it possible to use enums without declaring it in the namespace?

Body:
If you are trying to do what is described below it will not work...

    public class MyClass1
    {
        private enum Mode { New, Selected };
        public Mode ModeProperty { get; set; }
    }

    public class MyClass2
    {
        public MyClass2()
        {
            var myClass1 = new MyClass1();

            //this will not work due to protection level
            myClass1.ModeProperty = MyClass1.Mode.
        }
    }

What you could do however is below, which will work...

    public interface IEnums
    {
        public enum Mode { New, Selected };
    }

    public class MyClass1
    {
        public IEnums.Mode ModeProperty { get; set; }
    }

    public class MyClass2
    {
        public MyClass2()
        {
            var myClass1 = new MyClass1();

            //this will work
            myClass1.ModeProperty = IEnums.Mode.New;
        }
    }


问:
Wicket.Ajax: Cannot bind a listener for event "click" on element "radioGroup1d" because the element is not in the DOM
I have a page in apache-wicket-7 with RadioGroup. I want to call a method in the backend Page class with ajax. To do this, I add the:

```<code>AjaxFormChoiceComponentUpdatingBehavior
</code>```

The code:

```<code>this.listInput = new RadioGroup<T>("radioGroup", this.model);
       this.listInput.add(new AjaxFormChoiceComponentUpdatingBehavior() {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onUpdate(AjaxRequestTarget arg0) {
                System.out.println("The selected value is " + getComponent().getDefaultModelObjectAsString());
            }
        });
</code>```

The component RadioGroup becomes visible after an earlier ajax call, so it is also rendered asynchronously. But when wicket tries to render the component, the error message appears:

```<code>Wicket.Ajax:  Cannot bind a listener for event "click" on element "radioGroup1d" because the element is not in the DOM
</code>```

Adding:

```<code>setOutputMarkupPlaceholderTag(true)
</code>```

does nothing.
How this can be fixed?

Regards,
Mateusz

答: Make sure you don't use <wicket:cotainer> for it in the HTML template. Those are not rendered.

Body:
I have a page in apache-wicket-7 with RadioGroup. I want to call a method in the backend Page class with ajax. To do this, I add the:

AjaxFormChoiceComponentUpdatingBehavior

The code:

this.listInput = new RadioGroup<T>("radioGroup", this.model);
       this.listInput.add(new AjaxFormChoiceComponentUpdatingBehavior() {

            private static final long serialVersionUID = 1L;

            @Override
            protected void onUpdate(AjaxRequestTarget arg0) {
                System.out.println("The selected value is " + getComponent().getDefaultModelObjectAsString());
            }
        });

The component RadioGroup becomes visible after an earlier ajax call, so it is also rendered asynchronously. But when wicket tries to render the component, the error message appears:

Wicket.Ajax:  Cannot bind a listener for event "click" on element "radioGroup1d" because the element is not in the DOM

Adding:

setOutputMarkupPlaceholderTag(true)

does nothing.
How this can be fixed?

Regards,
Mateusz


问:
Displaying user input html with newlines
I have comments section in my application where users enter input in a text area. I want to prevent the line breaks they enter but also display html as a string. For example, if comment.body is

```<code>Hello, this is the code: <a href='foo'>foo</a>

Bye
</code>```

I want it to be displayed just as above. The same with anything else, including iframe tags.

The closest I got is:

```<code>= simple_format(comment.body)
</code>```

but it sanitizes html code and it's not displayed. Example: foo biz bar is displayed as:

```<code>foo biz bar
</code>```

What should I do to achieve what I want?

答:
HTML safe allows the html in the comment to be used as html, but would skip the newlines, so doing a quick replace of \n with
 would cover the new lines

```<code>comment.body.gsub("\n", "<br />").html_safe
</code>```

If you want the html to be displayed instead of rendered then checkout CGI::escapeHTML(), then do the gsub so that the
 does not get escaped.

```<code>CGI::escapeHTML(comment.body).gsub("\n", "<br />")
</code>```

Body:
I have comments section in my application where users enter input in a text area. I want to prevent the line breaks they enter but also display html as a string. For example, if comment.body is

Hello, this is the code: foo

Bye

I want it to be displayed just as above. The same with anything else, including iframe tags.

The closest I got is:

= simple_format(comment.body)

but it sanitizes html code and it's not displayed. Example: foo biz bar is displayed as:

foo biz bar

What should I do to achieve what I want?

Body:
HTML safe allows the html in the comment to be used as html, but would skip the newlines, so doing a quick replace of \n with <br /> would cover the new lines

comment.body.gsub("\n", "<br />").html_safe

If you want the html to be displayed instead of rendered then checkout CGI::escapeHTML(), then do the gsub so that the <br /> does not get escaped.

CGI::escapeHTML(comment.body).gsub("\n", "<br />")


问:
async js code using generators
I need to proces some data. I can do it in sync and async way like this (simplified):

sync way:

```<code>for (var i in input) {
    result += input[i]
}
</code>```

async way

```<code>function f(input,cb) {
  var result;
  if (!input) {
    setTimeout(function() {cb(result)},500);
  } else {
    f(input.slice(1),function(r) {
      result+=input[0];
    });
  }
}
</code>```

Is it possible to rewrite async code using generators? I wish I had some For loop code instead of recursion.

答:
Using await (a newer ES2017 technology that is built on generators in ES6), and assuming, as you've said:

you have multiple items (in this case ['apple', 'peach', 'banana'])

you wish to perform some async operation on them

You wish to avoid callbacks and .then() (which is a good idea if you're on node 7+ or current browsers)

Then:

```<code>var doThing = async function (input) {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            resolve(`Result for ${input}`)
        }, 2000);
    });
}

var start = async function(listOfThings){
    var result = await Promise.all(listOfThings.map(doThing))
    console.log('All done', result)
}

start(['apple', 'peach', 'banana'])
</code>```

Will return:

```<code>All done [ 'Result for apple', 'Result for peach', 'Result for banana' ]
</code>```

To get some data from the network instead, you can simply replace the the setTimeout with superagent or (if you want to write your own query string encoding, URL handling etc) fetch.

Title: async js code using generators

Body:
I need to proces some data. I can do it in sync and async way like this (simplified):

sync way:

for (var i in input) {
    result += input[i]
}

async way

function f(input,cb) {
  var result;
  if (!input) {
    setTimeout(function() {cb(result)},500);
  } else {
    f(input.slice(1),function(r) {
      result+=input[0];
    });
  }
}

Is it possible to rewrite async code using generators? I wish I had some For loop code instead of recursion.

Body:
Using await (a newer ES2017 technology that is built on generators in ES6), and assuming, as you've said:

you have multiple items (in this case ['apple', 'peach', 'banana'])

you wish to perform some async operation on them

You wish to avoid callbacks and .then() (which is a good idea if you're on node 7+ or current browsers)

Then:

var doThing = async function (input) {
    return new Promise(function(resolve, reject) {
        setTimeout(function(){
            resolve(`Result for ${input}`)
        }, 2000);
    });
}

var start = async function(listOfThings){
    var result = await Promise.all(listOfThings.map(doThing))
    console.log('All done', result)
}

start(['apple', 'peach', 'banana'])

Will return:

All done [ 'Result for apple', 'Result for peach', 'Result for banana' ]

To get some data from the network instead, you can simply replace the the setTimeout with superagent or (if you want to write your own query string encoding, URL handling etc) fetch.


问:
Which is the Postgres version
I have a doubt about my version of Postgres installed in my environment.

This is my os: CentOS Linux release 7.3.1611 (Core)
In /usr/ I can see: pgsql-9.4/ folder.

But when I do: select version(); I get:

```<code>PostgreSQL 9.2.18 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.8.5
20150623 (Red Hat 4.8.5-11), 64-bit
</code>```

So, what version do I have?

答:
To determine the version of the database server, use select version() (from a connection to the database):

```<code>postgres=# select version();
                                                version
----------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.2.14 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16), 64-bit
</code>```

To determine the version of the database client, use psql --version (from your shell command line):

```<code>$ psql --version
psql (PostgreSQL) 9.6.2
</code>```

The server is where data is stored. The client is the software you use to connect to the server. They can be different versions.

Title: Which is the Postgres version

Body:
I have a doubt about my version of Postgres installed in my environment.

This is my os: CentOS Linux release 7.3.1611 (Core)
In /usr/ I can see: pgsql-9.4/ folder.

But when I do: select version(); I get:

PostgreSQL 9.2.18 on x86_64-redhat-linux-gnu, compiled by gcc (GCC) 4.8.5
20150623 (Red Hat 4.8.5-11), 64-bit

So, what version do I have?

Body:
To determine the version of the database server, use select version() (from a connection to the database):

postgres=# select version();
                                                version
----------------------------------------------------------------------------------------------------------------
 PostgreSQL 9.2.14 on x86_64-unknown-linux-gnu, compiled by gcc (GCC) 4.4.7 20120313 (Red Hat 4.4.7-16), 64-bit

To determine the version of the database client, use psql --version (from your shell command line):

$ psql --version
psql (PostgreSQL) 9.6.2

The server is where data is stored. The client is the software you use to connect to the server. They can be different versions.


问:
PHP Session not passing multiple post form data through multiple pages
I am trying to take form input from the user and pass that information to another page with another form then take input again and pass that plus the previous data to another page that will display the input from both forms.

On the first page, the user will enter information, click submit, and open the second page which will display their input from the first page and ask them to enter more information. They will enter information on the second page and click submit again which will bring them to a third page displaying all their input from the previous pages.

When I run my code, it does not carry the post values from the form to the next page.

I know there are multiple questions about issues such as this, but all of the answers I have looked over and tried did not fix my problem.

Here is my code:

page1.php

```<code><?php
session_start();
echo 'session id: ';
echo session_id();
$_SESSION['test1'] = $_POST['test1'];
?>

<html>
<body>
    <p>Page 1 Form</p>
    <form action="page2.php" method="post">
        <input type="text" name="test1"/>
        <input type="submit" name="submit1" value="Submit!" />
    </form>
</body>
</html>
</code>```

page2.php

```<code><?php
session_start();
echo 'page2.php<br />';
echo 'session id: ';
echo session_id();
echo '<br />';
echo 'input from page1.php: ';
echo $_SESSION['test1'];
$_SESSION['test2'] = $_POST['test2'];
?>

<html>
<body>
    <p>Page 2 Form</p>
        <form action="page3.php" method="post">
            <input type="text" name="test2"/>
            <input type="submit" name="submit2" value="Submit!" />
        </form>
</body>
</html>
</code>```

page3.php

```<code><?php
session_start();
echo 'page3.php<br />'
echo 'session id: ';
echo session_id();
echo '<br />';
echo $_SESSION['test1'];
echo $_SESSION['test2'];
?>
</code>```

答:
$_POST['test1'] is never read because page1.php submits to page2.php and page2.php reads test2.

Also you don't need to use the session if you're just POSTing data along. You can do this:

page1.php

```<code><html>
<body>
    <p>Page 1 Form</p>
    <form action="page2.php" method="post">
        <input type="text" name="test1"/>
        <input type="submit" name="submit1" value="Submit!" />
    </form>
</body>
</html>
</code>```

page2.php

```<code><html>
<body>
    <p>Page 2 Form</p>
        <form action="page3.php" method="post">
            <input type="hidden" name="test1" value="<?php echo htmlspecialchars($_POST["test1"]);?>"/>
            <input type="text" name="test2"/>
            <input type="submit" name="submit2" value="Submit!" />
        </form>
</body>
</html>
</code>```

page3.php

```<code><?php
echo 'page3.php<br />'
var_dump($_POST["test1"]);
var_dump($_POST["test2"]);
?>
</code>```

Body:
I am trying to take form input from the user and pass that information to another page with another form then take input again and pass that plus the previous data to another page that will display the input from both forms.

On the first page, the user will enter information, click submit, and open the second page which will display their input from the first page and ask them to enter more information. They will enter information on the second page and click submit again which will bring them to a third page displaying all their input from the previous pages.

When I run my code, it does not carry the post values from the form to the next page.

I know there are multiple questions about issues such as this, but all of the answers I have looked over and tried did not fix my problem.

Here is my code:

page1.php

<?php
session_start();
echo 'session id: ';
echo session_id();
$_SESSION['test1'] = $_POST['test1'];
?>

Page 1 Form

    <form action="page2.php" method="post">
        <input type="text" name="test1"/>
        <input type="submit" name="submit1" value="Submit!" />
    </form>

page2.php

<?php
session_start();
echo 'page2.php
';
echo 'session id: ';
echo session_id();
echo '
';
echo 'input from page1.php: ';
echo $_SESSION['test1'];
$_SESSION['test2'] = $_POST['test2'];
?>

Page 2 Form

        <form action="page3.php" method="post">
            <input type="text" name="test2"/>
            <input type="submit" name="submit2" value="Submit!" />
        </form>

page3.php

<?php
session_start();
echo 'page3.php
'
echo 'session id: ';
echo session_id();
echo '
';
echo $_SESSION['test1'];
echo $_SESSION['test2'];
?>

Body:
$_POST['test1'] is never read because page1.php submits to page2.php and page2.php reads test2.

Also you don't need to use the session if you're just POSTing data along. You can do this:

page1.php

<html>
<body>
    <p>Page 1 Form</p>
    <form action="page2.php" method="post">
        <input type="text" name="test1"/>
        <input type="submit" name="submit1" value="Submit!" />
    </form>
</body>
</html>

page2.php

<html>
<body>
    <p>Page 2 Form</p>
        <form action="page3.php" method="post">
            <input type="hidden" name="test1" value="<?php echo htmlspecialchars($_POST["test1"]);?>"/>
            <input type="text" name="test2"/>
            <input type="submit" name="submit2" value="Submit!" />
        </form>
</body>
</html>

page3.php

<?php
echo 'page3.php<br />'
var_dump($_POST["test1"]);
var_dump($_POST["test2"]);
?>


问:
Issue with Validating Phone number on user input,Int to large c#
Overview of Project:

I am creating a multi form application, which consist of two forms and one parent class. Both Forms have a series of validation functions, such as isLetter() isNumber() and isValidEmail(). My Issue comes when using the isNumber() Function.

```<code>public static bool numValidation(string strNum)
        {
            if (!string.IsNullOrWhiteSpace(strNum))
            {
                int temp;
                if (int.TryParse(strNum, out temp))
                {
                    Console.WriteLine("Phone Number is a valid input: " + temp);
                    return true;
                }
                else
                { Console.WriteLine(temp + "Is not Valid input!!"); }
            }
            return false;
        }
</code>```

At first glance it works fine but once I tried to break it, I realised that when an actual phone number is entered I get an error saying that the number is too high. Any ideas how to get round this constraint ? as the only reason I need this validation is for phone numbers, Fax etc. I simply need this function to accept very large numbers such as phone numbers

答:
From Mauricio Gracia Gutierrez answer

I suggest that you use a regular expresion to validate the
  input in your case

public static bool numValidation(string strNum) {

```<code>Regex regex = new Regex(@"^[0-9]+$");

return (regex.IsMatch(strNum)) ; } Parsing a string and not using that value is not really needed.
</code>```

For more details checkout this answers - Regex for numbers only

You could enhance the expression to check the length of the number:

Between 5 and 10 digits:

```<code>Regex regex = new Regex(@"^[\d]{5,10}+$");
</code>```

Max 10 digits:

```<code>Regex regex = new Regex(@"^[\d]{10}+$");
</code>```

At least 5 digits:

```<code>Regex regex = new Regex(@"^[\d]{5,}+$");
</code>```

Body:
Overview of Project:

I am creating a multi form application, which consist of two forms and one parent class. Both Forms have a series of validation functions, such as isLetter() isNumber() and isValidEmail(). My Issue comes when using the isNumber() Function.

public static bool numValidation(string strNum)
        {
            if (!string.IsNullOrWhiteSpace(strNum))
            {
                int temp;
                if (int.TryParse(strNum, out temp))
                {
                    Console.WriteLine("Phone Number is a valid input: " + temp);
                    return true;
                }
                else
                { Console.WriteLine(temp + "Is not Valid input!!"); }
            }
            return false;
        }

At first glance it works fine but once I tried to break it, I realised that when an actual phone number is entered I get an error saying that the number is too high. Any ideas how to get round this constraint ? as the only reason I need this validation is for phone numbers, Fax etc. I simply need this function to accept very large numbers such as phone numbers

Body:
From Mauricio Gracia Gutierrez answer

I suggest that you use a regular expresion to validate the
  input in your case

public static bool numValidation(string strNum) {

Regex regex = new Regex(@"^[0-9]+$");

return (regex.IsMatch(strNum)) ; } Parsing a string and not using that value is not really needed.

For more details checkout this answers - Regex for numbers only

You could enhance the expression to check the length of the number:

Between 5 and 10 digits:

Regex regex = new Regex(@"^[\d]{5,10}+$");

Max 10 digits:

Regex regex = new Regex(@"^[\d]{10}+$");

At least 5 digits:

Regex regex = new Regex(@"^[\d]{5,}+$");


答:
This can be solved using maths. You just need to decide whether gamesPlayedSaved is a multiple of 10. To do this, find the remainder of gamesPlayedSaved / 10 using the modulo operator % and check if it is 0:

```<code>if gamesPlayedSaved % 10 == 0 && gamesPlayedSaved > 0 {
    // show pop up
}
</code>```

Alternatively, reset the counter every time it reaches 10:

```<code>if gamesPlayedSaved == 10 {
    // show pop up
    gamesPlayedSaved = 0
}
</code>```

Title: How do I do something every n-th attempt?

Body:
This can be solved using maths. You just need to decide whether gamesPlayedSaved is a multiple of 10. To do this, find the remainder of gamesPlayedSaved / 10 using the modulo operator % and check if it is 0:

if gamesPlayedSaved % 10 == 0 && gamesPlayedSaved > 0 {
    // show pop up
}

Alternatively, reset the counter every time it reaches 10:

if gamesPlayedSaved == 10 {
    // show pop up
    gamesPlayedSaved = 0
}


问:
Storing multiple integers in a char array
I've been looking online for a few hours to find this, but haven't found anything yet that's exactly what I need. I have multiple integers that I need to put into a char* (separated by a space) to be later written to a .txt file. My best attempt until now has been this:

```<code>char* temp = (char)input.Z_pos_Camera_Temperature;
</code>```

Where input.Z_pos_Camera_Temperature is a member of a struct. I tried

```<code>char* temp = (char)input.Z_pos_Camera_Temperature + ' ' + input.Z_neg_Camera_Temperature;
</code>```

but that only added the values of the three chars individually. Can someone help me figure this out?

答:
In C, you cannot concatenate characters into a string using the + operator like you can in higher level languages, nor can you concatenate several strings into a larger, separate string using the + operator.

You can, however, use the function snprintf to build a string, like so:

```<code>char buffer[100]; // adjust per your needs
snprintf(buffer, 100, "%d %d", input.Z_pos_Camera_Temperature, input.Z_neg_Camera_Temperature);
</code>```

Body:
I've been looking online for a few hours to find this, but haven't found anything yet that's exactly what I need. I have multiple integers that I need to put into a char* (separated by a space) to be later written to a .txt file. My best attempt until now has been this:

char* temp = (char)input.Z_pos_Camera_Temperature;

Where input.Z_pos_Camera_Temperature is a member of a struct. I tried

char* temp = (char)input.Z_pos_Camera_Temperature + ' ' + input.Z_neg_Camera_Temperature;

but that only added the values of the three chars individually. Can someone help me figure this out?

Body:
In C, you cannot concatenate characters into a string using the + operator like you can in higher level languages, nor can you concatenate several strings into a larger, separate string using the + operator.

You can, however, use the function snprintf to build a string, like so:

char buffer[100]; // adjust per your needs
snprintf(buffer, 100, "%d %d", input.Z_pos_Camera_Temperature, input.Z_neg_Camera_Temperature);


答:
You may want to use snprintf.

char buf[32];
snprintf(buf, 32, "%d %d", input.Z_pos_Camera_Temperature, input.Z_neg_Camera_Temperature);

Title: Storing multiple integers in a char array


问:
Iterate over digits of integers inside of array
I have this code below:

```<code> a = [435,276,434]

 def product(a)
   final = 1
   for e in a
     for p in a[e]
       final*=p
     end
   end
   final
 end

 puts product(a)
</code>```

I'm wondering how I can iterate over this array twice where the result is 4*3*5 = 60, 2*7*6 = 85, and 4*3*4 = 48

I wrote some code up above which I thought would do the trick here but Ruby keeps on returning an error.

答:
If the intent is to just iterate over the digits, you can use the string slice methods too.

```<code>num = a[0].to_s # "435"
final = num[0,1].to_i * num[1,1].to_i * num[2,1].to_i #4*3*5
</code>```

or

```<code>final = num[0..1].to_i * num[1..2].to_i * num[2..3].to_i
</code>```

For the given question, if you know it is an array of 3 digits each, then you can skip the inner loop and the solution could be like this:

```<code>a = [435,276,434]

def product(a)
    a.map! do |digits|
        final = 1
        num = digits.to_s
        final = num[0,1].to_i * num[1,1].to_i * num[2,1].to_i
    end
end

puts product(a).inspect
</code>```

This answer is just for the said question. Since it manipulates the same array, it edits the receiver. For a more detailed and complete solution, check out Cary Swoveland's answer.

Body:
I have this code below:

 a = [435,276,434]

 def product(a)
   final = 1
   for e in a
     for p in a[e]
       final*=p
     end
   end
   final
 end

 puts product(a)

I'm wondering how I can iterate over this array twice where the result is 4*3*5 = 60, 2*7*6 = 85, and 4*3*4 = 48

I wrote some code up above which I thought would do the trick here but Ruby keeps on returning an error.

Body:
If the intent is to just iterate over the digits, you can use the string slice methods too.

num = a[0].to_s # "435"
final = num[0,1].to_i * num[1,1].to_i * num[2,1].to_i #4*3*5

or

final = num[0..1].to_i * num[1..2].to_i * num[2..3].to_i

For the given question, if you know it is an array of 3 digits each, then you can skip the inner loop and the solution could be like this:

a = [435,276,434]

def product(a)
    a.map! do |digits|
        final = 1
        num = digits.to_s
        final = num[0,1].to_i * num[1,1].to_i * num[2,1].to_i
    end
end

puts product(a).inspect

This answer is just for the said question. Since it manipulates the same array, it edits the receiver. For a more detailed and complete solution, check out Cary Swoveland's answer.


问:
Enable or Disable different Panes within an Accordion AJAX control?
I have a checkout process nested within an Accordion control:

Billing Address

Shipping Address

Shipping Method

Credit Card Info

Order Summary

I would like to set the Enabled state to false on page load (except for Billing Address), and sequentially enable each Pane as the user completes the information and clicks the "Continue" button WITHIN each Pane.

Currently, everything works the way I want, except all panes are always enabled.

I need a server side code so that on each continue click I can enable or disable the Accorion pane.

Also I need a code that on clicking Billing Address Pane all other Sectionpane should get disable
I have tried below code but its not working.

```<code>        BillingInformation.HeaderContainer.Enabled = false;
        ShippingInformation.HeaderContainer.Enabled = false;
</code>```

答:
Resolved

On page load event I used to write

```<code>        if (!IsPostBack)
        {
            BillingInformation.HeaderContainer.Style.Add("pointer-events", "auto");
            ShippingInformation.HeaderContainer.Style.Add("pointer-events", "none");
            DelieveryMethodsPanel.HeaderContainer.Style.Add("pointer-events", "none");
            PromoCode.HeaderContainer.Style.Add("pointer-events", "none");
            PaymentInformation.HeaderContainer.Style.Add("pointer-events", "none");
        }
</code>```

and on continue click of billing information I used to write code as below through which only billing and shipping information will get enable and else all will be disable. I am just changing the style of the class through which it will get enable/disable.

```<code>public void Continue1()
    {
            BillingInformation.HeaderContainer.Style.Add("pointer-events", "auto");
            BillingInformation.HeaderContainer.Style.Add("cursor", "pointer");

            ShippingInformation.HeaderContainer.Style.Add("pointer-events", "auto");
            ShippingInformation.HeaderContainer.Style.Add("cursor", "pointer");

            DelieveryMethodsPanel.HeaderContainer.Style.Add("pointer-events", "none");

            PromoCode.HeaderContainer.Style.Add("pointer-events", "none");

            PaymentInformation.HeaderContainer.Style.Add("pointer-events", "none");

    }
</code>```

Body:
I have a checkout process nested within an Accordion control:

Billing Address

Shipping Address

Shipping Method

Credit Card Info

Order Summary

I would like to set the Enabled state to false on page load (except for Billing Address), and sequentially enable each Pane as the user completes the information and clicks the "Continue" button WITHIN each Pane.

Currently, everything works the way I want, except all panes are always enabled.

I need a server side code so that on each continue click I can enable or disable the Accorion pane.

Also I need a code that on clicking Billing Address Pane all other Sectionpane should get disable
I have tried below code but its not working.

        BillingInformation.HeaderContainer.Enabled = false;
        ShippingInformation.HeaderContainer.Enabled = false;

Body:
Resolved

On page load event I used to write

        if (!IsPostBack)
        {
            BillingInformation.HeaderContainer.Style.Add("pointer-events", "auto");
            ShippingInformation.HeaderContainer.Style.Add("pointer-events", "none");
            DelieveryMethodsPanel.HeaderContainer.Style.Add("pointer-events", "none");
            PromoCode.HeaderContainer.Style.Add("pointer-events", "none");
            PaymentInformation.HeaderContainer.Style.Add("pointer-events", "none");
        }

and on continue click of billing information I used to write code as below through which only billing and shipping information will get enable and else all will be disable. I am just changing the style of the class through which it will get enable/disable.

public void Continue1()
    {
            BillingInformation.HeaderContainer.Style.Add("pointer-events", "auto");
            BillingInformation.HeaderContainer.Style.Add("cursor", "pointer");

            ShippingInformation.HeaderContainer.Style.Add("pointer-events", "auto");
            ShippingInformation.HeaderContainer.Style.Add("cursor", "pointer");

            DelieveryMethodsPanel.HeaderContainer.Style.Add("pointer-events", "none");

            PromoCode.HeaderContainer.Style.Add("pointer-events", "none");

            PaymentInformation.HeaderContainer.Style.Add("pointer-events", "none");

    }


答:
Take a look at this:

```<code>for i in 1...100 {
    if i % 10 == 0 {
        print("Yep: \(i)")
    }
}
</code>```

Which outputs:

```<code>Yep: 10
Yep: 20
Yep: 30
Yep: 40
Yep: 50
Yep: 60
Yep: 70
Yep: 80
Yep: 90
Yep: 100
</code>```

The % operator is called modulo, it returns the remainder when dividing a number A with number B. In your case you are interested in the cases when the number of games played is divisible by 10, ie. numberOfGamesPlayed % 10 == 0.

Body:
I have a game that is based on attempts rather than score. And I wish to display a pop up every 10 attempts. What is the best way, using Swift, to calculate every 10 intervals of something?

Currently I call a function to increment the attempts value which includes: gamesPlayedSaved += 1. The closest question I found on here uses timers, which wouldn't work in my case.

So far, I have this (WHICH IS EXTREMELY UGLY):

if(gamesPlayedSaved == 10 ||
                    gamesPlayedSaved == 20 ||
                    gamesPlayedSaved == 30 ||
                    gamesPlayedSaved == 40 ||
                    gamesPlayedSaved == 50 ||
                    gamesPlayedSaved == 60 ||
                    gamesPlayedSaved == 70 ||
                    gamesPlayedSaved == 80 ||
                    gamesPlayedSaved == 90 ||
                    gamesPlayedSaved == 100){
    // call pop up
}

And it also doesn't account for any intervals over 100.

Body:
Take a look at this:

for i in 1...100 {
    if i % 10 == 0 {
        print("Yep: \(i)")
    }
}

Which outputs:

Yep: 10
Yep: 20
Yep: 30
Yep: 40
Yep: 50
Yep: 60
Yep: 70
Yep: 80
Yep: 90
Yep: 100

The % operator is called modulo, it returns the remainder when dividing a number A with number B. In your case you are interested in the cases when the number of games played is divisible by 10, ie. numberOfGamesPlayed % 10 == 0.


问:
Fail to install gitlab on ubuntu
Now I am trying to install gitlab for ubuntu that be hosted on a virtual machine. Its version is 15.10 and it is 64-bit. I try to install it following this tutorial. But I got such error:

```<code>Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package gitlab-ce
</code>```

The content of /etc/apt/sources.list.d/gitlab_gitlab-ce.list is :

```<code># this file was generated by packages.gitlab.com for
# the repository at https://packages.gitlab.com/gitlab/gitlab-ce

deb https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ wily main
deb-src https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ wily main
</code>```

Do you know how can I fix this issue? Thanks a lot in advance!

EDIT:

After I installed a ubuntu with version of 16.04, the previous error does not exist anymore. But now a new one occurs :(
When I run apt-get install gitlab-ce, I got the error of no avaliable space. I ran df -Th and here is the output

```<code>Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  2.6G     0  2.6G   0% /dev
tmpfs          tmpfs     524M  7.7M  516M   2% /run
/dev/sda1      ext4      4.6G  4.1G  245M  95% /
tmpfs          tmpfs     2.6G   21M  2.6G   1% /dev/shm
tmpfs          tmpfs     5.0M  4.0K  5.0M   1% /run/lock
tmpfs          tmpfs     2.6G     0  2.6G   0% /sys/fs/cgroup
tmpfs          tmpfs     524M   56K  524M   1% /run/user/1000
</code>```

So there are some partitions that I can utilize. Do you know how to install the gitlab to those available partitions?

答:
It seems gitlab does not publish a deb for wily -- only for LTS releases (trusty / xenial at the time of writing), you may be able to sneak by with dropping the xenial (16.04) deb onto wily however as they are rather compatible distributions.  (but I would strongly suggest upgrading to an LTS release).

The directions to download and install a specific deb are listed on this page

```<code>curl -LJO https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/xenial/gitlab-ce-XXX.deb/download
dpkg -i gitlab-ce-XXX.deb
</code>```

Title: Fail to install gitlab on ubuntu

Body:
Now I am trying to install gitlab for ubuntu that be hosted on a virtual machine. Its version is 15.10 and it is 64-bit. I try to install it following this tutorial. But I got such error:

Reading package lists... Done
Building dependency tree
Reading state information... Done
E: Unable to locate package gitlab-ce

The content of /etc/apt/sources.list.d/gitlab_gitlab-ce.list is :

# this file was generated by packages.gitlab.com for
# the repository at https://packages.gitlab.com/gitlab/gitlab-ce

deb https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ wily main
deb-src https://packages.gitlab.com/gitlab/gitlab-ce/ubuntu/ wily main

Do you know how can I fix this issue? Thanks a lot in advance!

EDIT:

After I installed a ubuntu with version of 16.04, the previous error does not exist anymore. But now a new one occurs :(
When I run apt-get install gitlab-ce, I got the error of no avaliable space. I ran df -Th and here is the output

Filesystem     Type      Size  Used Avail Use% Mounted on
udev           devtmpfs  2.6G     0  2.6G   0% /dev
tmpfs          tmpfs     524M  7.7M  516M   2% /run
/dev/sda1      ext4      4.6G  4.1G  245M  95% /
tmpfs          tmpfs     2.6G   21M  2.6G   1% /dev/shm
tmpfs          tmpfs     5.0M  4.0K  5.0M   1% /run/lock
tmpfs          tmpfs     2.6G     0  2.6G   0% /sys/fs/cgroup
tmpfs          tmpfs     524M   56K  524M   1% /run/user/1000

So there are some partitions that I can utilize. Do you know how to install the gitlab to those available partitions?

Body:
It seems gitlab does not publish a deb for wily -- only for LTS releases (trusty / xenial at the time of writing), you may be able to sneak by with dropping the xenial (16.04) deb onto wily however as they are rather compatible distributions.  (but I would strongly suggest upgrading to an LTS release).

The directions to download and install a specific deb are listed on this page

curl -LJO https://packages.gitlab.com/gitlab/gitlab-ce/packages/ubuntu/xenial/gitlab-ce-XXX.deb/download
dpkg -i gitlab-ce-XXX.deb


问:
Redirect a page to index in .htaccess
I want to redirect a page to index.php. When I click on a link , it redirects to something like http://example.com/article.php which doesn't exist yet. As it doesn't exist, I want to redirect to index.php.

I tried something like :

```<code>RewriteRule ^article.\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [R=301]
</code>```

This code redirect to index.php but with every link on the site and not only with article.php

答:
You can use this rule instead:

```<code>RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?:^|/)article\.php$ /index.php? [L,NC,R=301]
</code>```

RewriteCond %{REQUEST_FILENAME} !-f ensures that redirect only happens if index.php is not a valid file in your system.

Title: Redirect a page to index in .htaccess

Body:
I want to redirect a page to index.php. When I click on a link , it redirects to something like http://example.com/article.php which doesn't exist yet. As it doesn't exist, I want to redirect to index.php.

I tried something like :

RewriteRule ^article.\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [R=301]

This code redirect to index.php but with every link on the site and not only with article.php

Body:
You can use this rule instead:

RewriteEngine On

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule (?:^|/)article\.php$ /index.php? [L,NC,R=301]

RewriteCond %{REQUEST_FILENAME} !-f ensures that redirect only happens if index.php is not a valid file in your system.