问:
git commit does not commit new files
I am having an issue using bitbucket and codeanywhere. I was trying to install CakePHP onto the PHP based server running on ubuntu.

I have attached my container to the git and pulled all the latest changes from the latest commit. Then I made my own changes and I did:git commit --all and also pushed it with git push.

However my issue is that none of the folders that I created such as "tmp" or "logs" or even files I renamed got committed onto the bitbucket.

I am running this command from the main directory

```<code>cabox@box-codeanywhere:~/workspace$
</code>```

And now even with the files being different if I try to commit again it says the following:

```<code>nothing to commit, working directory clean
</code>```

答:
git commit --all will only commit changes to files that are already being tracked. Files git does not already know about ("untracked" files) are ignored by that command.

If you really want to add all untracked files, the simplest way is to go to the root of the project and use:

```<code>git add .
git commit
</code>```

That will add any untracked files, and will also stage modifications to already-tracked files. And then commit the changes that have been staged.

If you want to double-check what was staged for commit before you actually commit, just git status in between add and commit. It will show you all the paths that are staged for the next commit.

Title: git commit does not commit new files

Body:
I am having an issue using bitbucket and codeanywhere. I was trying to install CakePHP onto the PHP based server running on ubuntu.

I have attached my container to the git and pulled all the latest changes from the latest commit. Then I made my own changes and I did:git commit --all and also pushed it with git push.

However my issue is that none of the folders that I created such as "tmp" or "logs" or even files I renamed got committed onto the bitbucket.

I am running this command from the main directory

cabox@box-codeanywhere:~/workspace$

And now even with the files being different if I try to commit again it says the following:

nothing to commit, working directory clean

Body:
git commit --all will only commit changes to files that are already being tracked. Files git does not already know about ("untracked" files) are ignored by that command.

If you really want to add all untracked files, the simplest way is to go to the root of the project and use:

git add .
git commit

That will add any untracked files, and will also stage modifications to already-tracked files. And then commit the changes that have been staged.

If you want to double-check what was staged for commit before you actually commit, just git status in between add and commit. It will show you all the paths that are staged for the next commit.


来源: stackexchange

问:
Select Top 1 In SQL Server
Please help me in select top 1

The data like this

```<code>Code    Amp      Price
-----------------------
00001   10       1000
00002   75-100   1500
00003   50-60    1200
00004   15       1100
</code>```

Note : datatype for column Amp is VarChar

I want to select with Amp 75 and I want get the price is 1500

So I use this statement:

```<code>SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC
</code>```

but the result price I get is 1200 is record with code : 00003 (wrong), actually I want the result is code : 00002 and the price is 1500

But if I want to select with Amp 76 the result is true with the syntax :

```<code>SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC
</code>```

What is the true select for my case? Please help me

答:
The problem is that SQL Server is not going to sort a varchar column like an int.

Sorting issue example:

```<code>select *
from (
    select '125' as nbr
    union all
    select '24' as nbr
    ) as a
order by a.nbr asc
</code>```

1 is less than 2 (the first character in each nbr), so it will sort thinking that 125 < 24 (not true), even though it looks pretty simple to anyone that 24 should show up first, which is how it would be sorted if the datatype of the column were an int.

What needs to happen is to split the amp column into ranges, or max and min. Using the - as the delimeter, you can use charindex to split the numbers up and cast them as ints instead.

Sample Data Setup:

```<code>declare @cable table
    (
        code char(5) not null
        , amp varchar(10) not null
        , price int not null
    )

insert into @cable
values
        ('00001','10'       ,10000),
        ('00002','75-100'   ,15000),
        ('00003','50-60'    ,12000),
        ('00004','15'       ,11000)
</code>```

Answer:

```<code>declare @amp_nbr int = 75

select top 1 *
from (
    select c.code
    , cast(iif(charindex('-', c.amp, 0) > 0, left(c.amp, charindex('-', c.amp, 0) - 1), c.amp) as int) as amp_min
    , cast(iif(charindex('-', c.amp, 0) > 0, right(c.amp, len(c.amp) - charindex('-', c.amp, 0)), c.amp) as int) as amp_max
    , c.price
    from @cable as c
    ) as a
where 1=1
and @amp_nbr between a.amp_min and a.amp_max
order by a.amp_min desc
</code>```

After that, a simple between constraint in the where clause will do the trick.

ContentLicense: CC BY-SA 3.0

Title: Select Top 1 In SQL Server

Body:
Please help me in select top 1

The data like this

Code    Amp      Price
-----------------------
00001   10       1000
00002   75-100   1500
00003   50-60    1200
00004   15       1100

Note : datatype for column Amp is VarChar

I want to select with Amp 75 and I want get the price is 1500

So I use this statement:

SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC

but the result price I get is 1200 is record with code : 00003 (wrong), actually I want the result is code : 00002 and the price is 1500

But if I want to select with Amp 76 the result is true with the syntax :

SELECT TOP 1 *
FROM Cable
WHERE (Amp <= '75')
ORDER BY Amp DESC

What is the true select for my case? Please help me

Body:
The problem is that SQL Server is not going to sort a varchar column like an int.

Sorting issue example:

select *
from (
    select '125' as nbr
    union all
    select '24' as nbr
    ) as a
order by a.nbr asc

1 is less than 2 (the first character in each nbr), so it will sort thinking that 125 < 24 (not true), even though it looks pretty simple to anyone that 24 should show up first, which is how it would be sorted if the datatype of the column were an int.

What needs to happen is to split the amp column into ranges, or max and min. Using the - as the delimeter, you can use charindex to split the numbers up and cast them as ints instead.

Sample Data Setup:

declare @cable table
    (
        code char(5) not null
        , amp varchar(10) not null
        , price int not null
    )

insert into @cable
values
        ('00001','10'       ,10000),
        ('00002','75-100'   ,15000),
        ('00003','50-60'    ,12000),
        ('00004','15'       ,11000)

Answer:

declare @amp_nbr int = 75

select top 1 *
from (
    select c.code
    , cast(iif(charindex('-', c.amp, 0) > 0, left(c.amp, charindex('-', c.amp, 0) - 1), c.amp) as int) as amp_min
    , cast(iif(charindex('-', c.amp, 0) > 0, right(c.amp, len(c.amp) - charindex('-', c.amp, 0)), c.amp) as int) as amp_max
    , c.price
    from @cable as c
    ) as a
where 1=1
and @amp_nbr between a.amp_min and a.amp_max
order by a.amp_min desc

After that, a simple between constraint in the where clause will do the trick.


问:
Align right side of a group of labels
I'm making an HTML page with a list of fields for filling out billing info.
Since the labels are in-line, their width is determined by the text contained in them, thus making them different widths which makes the input boxes unaligned. This makes a very ugly, unorganized look.

<fieldset>
    <legend>Billing Information</legend>

    Card Number: <input type="text">

    Expiration Month: <input type="number">

    Expiration Year: <input type="number">

    Name on Card: <input type="text">

    Address: <input type="text">

    City: <input type="text">

    State: <input type="text">

    Country: <input type="text">

    ZIP Code: <input type="number">

</fieldset>
```

What do I need to do to my HTML code to align the right side of the labels and the left side of the input boxes?

答:
Use table structure for your lists of fields for proper alignment.

    <fieldset>
        <legend>Billing Information</legend>

Card Number:	<input type="text">

Expiration Month:	 <input type="number">

Expiration Year:	 <input type="number">

Name on Card:	 <input type="text">

Address:	 <input type="text">

City:	 <input type="text">

State:	 <input type="text">

Country:	 <input type="text">

ZIP Code:	 <input type="number">

    </fieldset>```

Title: Align right side of a group of labels

Body:
I'm making an HTML page with a list of fields for filling out billing info.
Since the labels are in-line, their width is determined by the text contained in them, thus making them different widths which makes the input boxes unaligned. This makes a very ugly, unorganized look.

<fieldset>
    <legend>Billing Information</legend>

    Card Number: <input type="text">

    Expiration Month: <input type="number">

    Expiration Year: <input type="number">

    Name on Card: <input type="text">

    Address: <input type="text">

    City: <input type="text">

    State: <input type="text">

    Country: <input type="text">

    ZIP Code: <input type="number">

</fieldset>

What do I need to do to my HTML code to align the right side of the labels and the left side of the input boxes?

Body:
Use table structure for your lists of fields for proper alignment.

    <fieldset>
        <legend>Billing Information</legend>
        <table>
          <tr><td>Card Number:</td><td><input type="text"></td></tr>
          <tr><td>Expiration Month:</td><td> <input type="number"></td></tr>
          <tr><td>Expiration Year:</td><td> <input type="number"></td></tr>
          <tr><td>Name on Card:</td><td> <input type="text"></td></tr>
          <tr><td>Address:</td><td> <input type="text"></td></tr>
          <tr><td>City:</td><td> <input type="text"></td></tr>
          <tr><td>State:</td><td> <input type="text"></td></tr>
          <tr><td>Country:</td><td> <input type="text"></td></tr>
          <tr><td>ZIP Code:</td><td> <input type="number"></td></tr>
        </table>
    </fieldset>


问:
add tabindex attribute to a class mark dynamically
I am new to angularjs. I am using a textangular to show a html document. I want to highlight some words from that html and also want to focus that word.So, I am using tabindex and class = mark to highlight and focus. So, Here At first I am adding

```<code><span class="mark">ABC</span>
</code>```

so that It will get highlighted, after that I want to add a tabindex=1 attribute to this .So that It become like

```<code><span class="mark" tabindex="1">ABC</span>
</code>```

Here I want to add this tabindex dynamically. That means , I want to find that text and then add a tabindex to that text only.How can I achieve this ?At a time tabindex can be applied to only one word.

答:
You can try with contains() like this.
Change span to a to get default href highlighter.

$("button").click(function() {
  $("a.mark:contains('ABC')").attr("tabindex", 1);
  $("a.mark1:contains('ABC')").attr("tabindex", 2);
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
ABC
ABC
<button>Next</button></code>```

Body:
I am new to angularjs. I am using a textangular to show a html document. I want to highlight some words from that html and also want to focus that word.So, I am using tabindex and class = mark to highlight and focus. So, Here At first I am adding

ABC

so that It will get highlighted, after that I want to add a tabindex=1 attribute to this .So that It become like

ABC

Here I want to add this tabindex dynamically. That means , I want to find that text and then add a tabindex to that text only.How can I achieve this ?At a time tabindex can be applied to only one word.

Body:
You can try with contains() like this.
Change span to a to get default href highlighter.

$("button").click(function() {
  $("a.mark:contains('ABC')").attr("tabindex", 1);
  $("a.mark1:contains('ABC')").attr("tabindex", 2);
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<a class="mark" href="#">ABC</a>
<a class="mark1" href="#">ABC</a>
<button>Next</button>


问:
RcppArmadillo sample.h compiling error
I'm writing a package with some functions calling RcppArmadillo::sample from RcppArmadillo.
However I met the following error when compiling.

In file included from Citrus.cpp:2:
  ./R/x86_64-unknown-linux-gnu-library/3.0/RcppArmadillo/include/RcppArmadilloExtensions/sample.h: In function ‘T Rcpp::RcppArmadillo::sample(const T&, int, bool, Rcpp::NumericVector) [with T = arma::subview_col]’:
  Citrus.cpp:241:   instantiated from here
  ./R/x86_64-unknown-linux-gnu-library/3.0/RcppArmadillo/include/RcppArmadilloExtensions/sample.h:45: error: ‘const struct arma::subview_col’ has no member named ‘size’
  ./R/x86_64-unknown-linux-gnu-library/3.0/RcppArmadillo/include/RcppArmadilloExtensions/sample.h:48: error: no matching function for call to ‘arma::subview_col::subview_col(const int&)’
  ./R/x86_64-unknown-linux-gnu-library/3.0/RcppArmadillo/include/armadillo_bits/subview_bones.hpp:236: note: candidates are: arma::subview_col::subview_col() [with eT = double]
  ./R/x86_64-unknown-linux-gnu-library/3.0/RcppArmadillo/include/armadillo_bits/subview_meat.hpp:2608: note:                 arma::subview_col::subview_col(const arma::Mat&, arma::uword, arma::uword, arma::uword) [with eT = double]
  ./R/x86_64-unknown-linux-gnu-library/3.0/RcppArmadillo/include/armadillo_bits/subview_meat.hpp:2597: note:                 arma::subview_col::subview_col(const arma::Mat&, arma::uword) [with eT = double]
  ./R/x86_64-unknown-linux-gnu library/3.0/RcppArmadillo/include/armadillo_bits/forward_bones.hpp:29: note:                 arma::subview_col::subview_col(const arma::subview_col&)
  make: *** [Citrus.o] Error 1

The RcppArmadillo I'm using is 0.7.700.0.0.

The same error appeared on both linux and OSX. When compiling using Rstudio, the error message as follows:
no member named 'size' in 'arma::subview_col<double>'.
no matching constructor for initialization of 'arma::subview_col<double>'

I used RcppArmadillo::sample in my previous work a lot. It suddenly doesn't work. I appreciate any help.

答:
This feature works on pre-subset data in either arma::vec or NumericVector Always has and always will. Do not use this with an intermediary vector obtained from a subset operation (e.g. .col(), .cols(), or .submat()).

The issue you are running into is you've decided to subset the data within the call to sample. (You've omitted code to diagnose this part, so I'm speculating here.) Since sample() needs to work with both Rcpp and Armadillo data types there never was a call to Armadillo specific size member functions. Instead, the library opted to call the .size() member function of an STL container, which armadillo supported, since that was shared between both objects. However, armadillo limits where the member function was implemented to the "active" data structures and not temporaries. As a result, the .size() member function was not implemented for subview_col.  So, we end up with the error of:

error: ‘const struct arma::subview_col’ has no member named ‘size’

To get around this limitation and save memory, use an advanced vec ctor that will reuse memory and, thus, avoiding the need for an intermediary arma::subview_col to be created.

```<code>// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>

#include <RcppArmadilloExtensions/sample.h>

// [[Rcpp::export]]
void adv_rnd(int nrow, int ncol, bool replace = true){
    // Create a matrix of given dimensions
    arma::mat X(nrow, ncol);
    X.randn();

    // Show state before randomization
    Rcpp::Rcout << "Before Randomization:" << std::endl << X << std::endl;

    // Randomize each column
    for(int i = 0; i < ncol; ++i){
        arma::vec Y(X.colptr(i), nrow, false, true);
        X.col(i) = Rcpp::RcppArmadillo::sample(Y, nrow, replace);
    }

    // Show state after randomization
    Rcpp::Rcout << "After Randomization:" << std::endl << X << std::endl;

}
</code>```

Sample output:

```<code>> adv_rnd(3,3)
Before Randomization:
  -0.7197   1.2590  -0.5898
   0.0253   0.1493  -0.0685
  -0.6074   1.3843   0.0400

After Randomization:
  -0.7197   1.2590   0.0400
  -0.6074   1.2590  -0.5898
  -0.6074   0.1493  -0.0685
</code>```

Title: RcppArmadillo sample.h compiling error

Body:
This feature works on pre-subset data in either arma::vec or NumericVector Always has and always will. Do not use this with an intermediary vector obtained from a subset operation (e.g. .col(), .cols(), or .submat()).

The issue you are running into is you've decided to subset the data within the call to sample. (You've omitted code to diagnose this part, so I'm speculating here.) Since sample() needs to work with both Rcpp and Armadillo data types there never was a call to Armadillo specific size member functions. Instead, the library opted to call the .size() member function of an STL container, which armadillo supported, since that was shared between both objects. However, armadillo limits where the member function was implemented to the "active" data structures and not temporaries. As a result, the .size() member function was not implemented for subview_col.  So, we end up with the error of:

error: ‘const struct arma::subview_col’ has no member named ‘size’

To get around this limitation and save memory, use an advanced vec ctor that will reuse memory and, thus, avoiding the need for an intermediary arma::subview_col to be created.

// [[Rcpp::depends(RcppArmadillo)]]
#include <RcppArmadillo.h>

#include <RcppArmadilloExtensions/sample.h>

// [[Rcpp::export]]
void adv_rnd(int nrow, int ncol, bool replace = true){
    // Create a matrix of given dimensions
    arma::mat X(nrow, ncol);
    X.randn();

    // Show state before randomization
    Rcpp::Rcout << "Before Randomization:" << std::endl << X << std::endl;

    // Randomize each column
    for(int i = 0; i < ncol; ++i){
        arma::vec Y(X.colptr(i), nrow, false, true);
        X.col(i) = Rcpp::RcppArmadillo::sample(Y, nrow, replace);
    }

    // Show state after randomization
    Rcpp::Rcout << "After Randomization:" << std::endl << X << std::endl;

}

Sample output:

> adv_rnd(3,3)
Before Randomization:
  -0.7197   1.2590  -0.5898
   0.0253   0.1493  -0.0685
  -0.6074   1.3843   0.0400

After Randomization:
  -0.7197   1.2590   0.0400
  -0.6074   1.2590  -0.5898
  -0.6074   0.1493  -0.0685


答:
You will find it much easier if you put your elements into suitable containers and use CSS to do the hard work.

```<code><style type="text/css">
    label {
        display: inline-block;
        font-weight: bold;
        width: 10em;
    }
</style>
<fieldset>
    <legend>Billing Information</legend><br>
        <p><label for="card-number">Card Number:</label><input type="text" name="card-number" id="card-number"></p>
        <p><label for="expiration-month">Expiration Month:</label><input type="text" name="expiration-month" id="expiration-month"></p>
        <!-- etc -->
</fieldset>
</code>```

Here the label does 3 jobs:

It creates a clickable text to activate your input box.

It makes the purpose of the text clear for screen readers and other software.

You can easily apply CSS to the element.

The label element can either be wrapped around the input element:

```<code><label>Expiration Month: <input …></label>
</code>```

or attached with the for attribute. The for attribute references an id, which is independent of the name attribute. As you see in the example, they are often set to the same value.

In the CSS, we set the width to something reasonable. However, the label needs to be displayed as an inline-block for the width to take effect.

Title: Align right side of a group of labels

Body:
You will find it much easier if you put your elements into suitable containers and use CSS to do the hard work.

<style type="text/css">
    label {
        display: inline-block;
        font-weight: bold;
        width: 10em;
    }
</style>
<fieldset>
    <legend>Billing Information</legend><br>
        <p><label for="card-number">Card Number:</label><input type="text" name="card-number" id="card-number"></p>
        <p><label for="expiration-month">Expiration Month:</label><input type="text" name="expiration-month" id="expiration-month"></p>
        <!-- etc -->
</fieldset>

Here the label does 3 jobs:

It creates a clickable text to activate your input box.

It makes the purpose of the text clear for screen readers and other software.

You can easily apply CSS to the element.

The label element can either be wrapped around the input element:

<label>Expiration Month: <input …></label>

or attached with the for attribute. The for attribute references an id, which is independent of the name attribute. As you see in the example, they are often set to the same value.

In the CSS, we set the width to something reasonable. However, the label needs to be displayed as an inline-block for the width to take effect.


问:
SQL Query for Left join and Count of Max Value of Top 5
I have 2 tables as category and task,in category i have 2 fields as catID and catName, and in task i have only 1 field as catID which can be duplicate. what i want is to have a sql query to match the task.catID with category table to get catName, and in return i want to verify the count of that catname in TASK table. i have tried some different queries but can't retrieve the results. queries are as below.

```<code>SELECT categories.catId, categories.catName, MAX(catName)
FROM tasks
    LEFT JOIN categories ON tasks.catId = categories.catId
WHERE tasks.catId = categories.catId
</code>```

2nd query is

```<code>SELECT MAX(catId), count(catid) as countof
from tasks
group by catId
ORDER BY `countof` DESC
LIMIT 5
</code>```

my table is like as

```<code>Category                   task
catID --- catName          catID
1         ABC1              1
2         ABC2              1
3         ABC3              1
4         ABC4              2
5         ABC5              3
6         ABC6              2
7         ABC7              5
8         ABC8              5
</code>```

I WANT TO HAVE THE RESULTS AS BELOW for top 5 count.

```<code>catName  catName Count
ABC1      3
ABC2      2
ABC5      2
</code>```

any help in this regard would be appreciated. kindly help me to get these results.

答:
This website always help me a lot to complete my tasks. appreciated response from seniors and experts to help juniors. </p>

```<code>select categories.catName, Count(categories.catName) countof
from tasks
join categories on categories.catID = tasks.catID
group by categories.catID
order by countof desc limit 5
</code>```

Body:
I have 2 tables as category and task,in category i have 2 fields as catID and catName, and in task i have only 1 field as catID which can be duplicate. what i want is to have a sql query to match the task.catID with category table to get catName, and in return i want to verify the count of that catname in TASK table. i have tried some different queries but can't retrieve the results. queries are as below.

SELECT categories.catId, categories.catName, MAX(catName)
FROM tasks
    LEFT JOIN categories ON tasks.catId = categories.catId
WHERE tasks.catId = categories.catId

2nd query is

SELECT MAX(catId), count(catid) as countof
from tasks
group by catId
ORDER BY `countof` DESC
LIMIT 5

my table is like as

Category                   task
catID --- catName          catID
1         ABC1              1
2         ABC2              1
3         ABC3              1
4         ABC4              2
5         ABC5              3
6         ABC6              2
7         ABC7              5
8         ABC8              5

I WANT TO HAVE THE RESULTS AS BELOW for top 5 count.

catName  catName Count
ABC1      3
ABC2      2
ABC5      2

any help in this regard would be appreciated. kindly help me to get these results.

Body:
This website always help me a lot to complete my tasks. appreciated response from seniors and experts to help juniors.

select categories.catName, Count(categories.catName) countof
from tasks
join categories on categories.catID = tasks.catID
group by categories.catID
order by countof desc limit 5


问:
How to receive and use a json in ajax sended from php?
I want to receive json from php to ajax and want to access the different field values in json.</p>

答:
In jQuery it will be implementing something like this:    </p>

```<code>var user = {};

$.ajax({
  url: 'http://mysite.com/api/user.json',
  data: {'id': '42'},
  success: function(data){user = data;},
});

$('#name').val(user.name);
$('#email').val(user.email);
</code>```

ContentLicense: CC BY-SA 2.5

Body:
In jQuery it will be implementing something like this:

var user = {};

$.ajax({
  url: 'http://mysite.com/api/user.json',
  data: {'id': '42'},
  success: function(data){user = data;},
});

$('#name').val(user.name);
$('#email').val(user.email);


问:
Unity prefabs acting differently based on whether dragging them into the scene statically or having them dynamically generated by code
If I instantiate a prefab like so:

```<code>GameObject asteroid = GameObject.Instantiate(thing2spawn);
//then set the location and some other stuff
</code>```

The prefabbed asteroid's collisions do not register at all, but If I simply drag the asteroid into the scene, the collisions work exactly as expected.

答:
Figured it out.

My asteroid object has two child objects which contain colliders that do different things. Hitting a certain part of the asteroid heals you, while hitting the other part damages you. These two children had rigid body components so when I set the speed of the asteroid (the parent object) in code, the two children wouldn't move with it. So it seemed like the colliders weren't working when really they were just left behind in some other place. Removing the rigid bodies from the children fixed the problem.

Weird.

Body:
If I instantiate a prefab like so:

GameObject asteroid = GameObject.Instantiate(thing2spawn);
//then set the location and some other stuff

The prefabbed asteroid's collisions do not register at all, but If I simply drag the asteroid into the scene, the collisions work exactly as expected.


问:
iOS: Force apply current device orientation after callback
I'm currently building an iOS app (supporting iOS >= 8) that has initial splash screen animation on start up. This animation blocks the entire screen during 2~3 seconds and then hides itself.

Goal is that the screen orientation should be fixed to portrait mode, and be released when the animation is over. This can be easily achieved by the following code:

```<code>- (void)onSplashAnimationEnded {
    _isFinished = YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (_isFinished) {
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}
</code>```

The problem is that when a user launched the app in landscape mode, and when the animation is finished, the device orientation (currently in landscape mode) does not apply to the app (locked in portrait mode, as intended).

It seems natural that the current orientation of device is automatically applied to the app right after the animation is over. I tried the followings to solve this and none of them works.

```<code>- (void)onSplashAnimationEnded {
    _isFinished = YES;

    // #1
    [UIViewController attemptRotationToDeviceOrientation];

    // #2
    [[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];

    // #3
    [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidChangeStatusBarOrientationNotification object:[UIApplication sharedApplication]];
}
</code>```

I really hope someone to share any workarounds for this issue.

Edit #1

I have read the other question that is linked to mine, and want to add some detail about it.

It is possible to lock or unlock device rotation in a certain situation as described in the link, and I already implemented the feature in other way.

What is left can be regenerated by the following procedure:

Set iPad in landscape mode.

Launch the app (which will force the orientation in portrait mode), without rotating the device.

When the animation is over, the device remains in portrait mode (which is odd because the device is in landscape mode).

Orientation can be fixed when user tries to rotate to portrait > landscape mode one or twice.

What I do want to do is to eliminate the step #4.

答:
After all, it is possible to implement the feature I wanted by the following combination, without any other settings in other view controllers:

```<code>// Control device orientation only in AppDelegate.m
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return _isFinished ? UIInterfaceOrientationMaskAll : UIInterfaceOrientationMaskPortrait;
}

- (void)onSplashAnimationEnded {
    _isFinished = YES;

    // Invoke OS orientation change message
    [UIViewController attemptRotationToDeviceOrientation];
}
</code>```

For this, device orientation should be available in other view controllers.

Body:
I'm currently building an iOS app (supporting iOS >= 8) that has initial splash screen animation on start up. This animation blocks the entire screen during 2~3 seconds and then hides itself.

Goal is that the screen orientation should be fixed to portrait mode, and be released when the animation is over. This can be easily achieved by the following code:

- (void)onSplashAnimationEnded {
    _isFinished = YES;
}

- (UIInterfaceOrientationMask)supportedInterfaceOrientations {
    if (_isFinished) {
        return UIInterfaceOrientationMaskAll;
    }
    return UIInterfaceOrientationMaskPortrait;
}

The problem is that when a user launched the app in landscape mode, and when the animation is finished, the device orientation (currently in landscape mode) does not apply to the app (locked in portrait mode, as intended).

It seems natural that the current orientation of device is automatically applied to the app right after the animation is over. I tried the followings to solve this and none of them works.

- (void)onSplashAnimationEnded {
    _isFinished = YES;

    // #1
    [UIViewController attemptRotationToDeviceOrientation];

    // #2
    [[NSNotificationCenter defaultCenter] postNotificationName:UIDeviceOrientationDidChangeNotification object:[UIDevice currentDevice]];

    // #3
    [[NSNotificationCenter defaultCenter] postNotificationName:UIApplicationDidChangeStatusBarOrientationNotification object:[UIApplication sharedApplication]];
}

I really hope someone to share any workarounds for this issue.

Edit #1

I have read the other question that is linked to mine, and want to add some detail about it.

It is possible to lock or unlock device rotation in a certain situation as described in the link, and I already implemented the feature in other way.

What is left can be regenerated by the following procedure:

Set iPad in landscape mode.

Launch the app (which will force the orientation in portrait mode), without rotating the device.

When the animation is over, the device remains in portrait mode (which is odd because the device is in landscape mode).

Orientation can be fixed when user tries to rotate to portrait > landscape mode one or twice.

What I do want to do is to eliminate the step #4.

Body:
After all, it is possible to implement the feature I wanted by the following combination, without any other settings in other view controllers:

// Control device orientation only in AppDelegate.m
- (UIInterfaceOrientationMask)application:(UIApplication *)application supportedInterfaceOrientationsForWindow:(UIWindow *)window
{
    return _isFinished ? UIInterfaceOrientationMaskAll : UIInterfaceOrientationMaskPortrait;
}

- (void)onSplashAnimationEnded {
    _isFinished = YES;

    // Invoke OS orientation change message
    [UIViewController attemptRotationToDeviceOrientation];
}

For this, device orientation should be available in other view controllers.


问:
How to avoid showing characters like Ä in android keyboard
I am stuck in an issue where one of my user entering characters like Ä in an edittext and I am preparing an XML from that data. Due to encoding issue I can't prepare a valid XML from these kind of characters. Is there anyway I can stop user to enter such kind of characters or can I hide these characters from android default keyboard itself ?

Regards

答:
Hide suggestion string in your edittext.</p>

```<code>android:inputType="textFilter"
</code>```

Body:
Hide suggestion string in your edittext.

android:inputType="textFilter"


问:
How do I pass an std::string to a function that expects char*?

Possible Duplicate:

  Can I get a non-const C string back from a C++ string?

Do I need to convert it first? I saw in another post that .c_str() can be used if the function expected const char*. What about for just char*?

答:
There are three scenarios:

If the function is outside of your control, and it either modifies the string, or you don't and can't know if it modifies the string:

Then, copy the string into a temporary buffer, and pass that to the function, like so:

```<code>void callFoo(std::string& str);
{
    char* tmp = new char str(str.length() +1);
    strncpy(tmp, str.c_str(), str.length());
    foo(tmp);
    // Include the following line if you want the modified value:
    str = tmp;
    delete [] tmp;
}
</code>```

If the function is outside of your control, but you are certain it does not modify the string, and that not taking the argument as const is simply a mistake on the API's part.

Then, you can cast the const away and pass that to the function

```<code>void callFoo(const std::string& str)
{
    foo(const_cast<char*> str.c_str());
}
</code>```

You are in control of the function (and it would not be overly disruptive to change the signature).

In that case, change the function to accept either a string& (if it modifies the input buffer) or either const char* or const string& if it does not.

Body:
There are three scenarios:

If the function is outside of your control, and it either modifies the string, or you don't and can't know if it modifies the string:

Then, copy the string into a temporary buffer, and pass that to the function, like so:

void callFoo(std::string& str);
{
    char* tmp = new char str(str.length() +1);
    strncpy(tmp, str.c_str(), str.length());
    foo(tmp);
    // Include the following line if you want the modified value:
    str = tmp;
    delete [] tmp;
}

If the function is outside of your control, but you are certain it does not modify the string, and that not taking the argument as const is simply a mistake on the API's part.

Then, you can cast the const away and pass that to the function

void callFoo(const std::string& str)
{
    foo(const_cast<char*> str.c_str());
}

You are in control of the function (and it would not be overly disruptive to change the signature).

In that case, change the function to accept either a string& (if it modifies the input buffer) or either const char* or const string& if it does not.


问:
PHP/CURL Empty Reply from Server
I have a NodeJS App running on my server and i have a CURL that submits a post request to where the app's port on my server. I am able to normally do it if i visit the PHP page, but trying to execute it as a command line is a different story. It keeps returning with the HTTP response code 0 and the error being "Empty Reply from Server"

PHP Curl (OOP) [$this->domain = http://domain:port , $url = /path/to/something]:

```<code>protected function post($url, $data)
{
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'
    ));
    curl_setopt($ch,CURLOPT_URL,$this->domain.$url);
    curl_setopt($ch,CURLOPT_POST,count($data));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);
    //error_log(curl_error($ch));
    return $result;
}
</code>```

Command Line Execution:

```<code>curl https://rbx.shopping/Secure/IPNCron.php
</code>```

Default page when visiting domain:port

Example on what should be returning:
https://rbx.shopping/Bot

答:
try to add cookie jar:

```<code>$ckfile = tempnam (sys_get_temp_dir(), rand().'cookiename');
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);
</code>```

Also add this:

```<code>curl_setopt($handle, CURLOPT_ENCODING, 'identity');
</code>```

Title: PHP/CURL Empty Reply from Server

Body:
I have a NodeJS App running on my server and i have a CURL that submits a post request to where the app's port on my server. I am able to normally do it if i visit the PHP page, but trying to execute it as a command line is a different story. It keeps returning with the HTTP response code 0 and the error being "Empty Reply from Server"

PHP Curl (OOP) [$this->domain = http://domain:port , $url = /path/to/something]:

protected function post($url, $data)
{
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_HTTPHEADER, array(
            'Content-Type: application/json',
            'User-Agent: Mozilla/5.0 (Windows NT 6.3; WOW64; rv:31.0) Gecko/20100101 Firefox/31.0'
    ));
    curl_setopt($ch,CURLOPT_URL,$this->domain.$url);
    curl_setopt($ch,CURLOPT_POST,count($data));
    curl_setopt($ch,CURLOPT_POSTFIELDS,$data);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);

    $result = curl_exec($ch);
    //error_log(curl_error($ch));
    return $result;
}

Command Line Execution:

curl https://rbx.shopping/Secure/IPNCron.php

Default page when visiting domain:port

Example on what should be returning:
https://rbx.shopping/Bot

Body:
try to add cookie jar:

$ckfile = tempnam (sys_get_temp_dir(), rand().'cookiename');
curl_setopt ($ch, CURLOPT_COOKIEJAR, $ckfile);
curl_setopt ($ch, CURLOPT_COOKIEFILE, $ckfile);

Also add this:

curl_setopt($handle, CURLOPT_ENCODING, 'identity');


问:
Unescaped left brace regex error
I’m not an expert in regex and can't figure what I am supposed to change here.

I get these two errors

Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/^(.*?)(\\)?\${ <-- HERE ([^{}]+)}(.*)$/ at /usr/share/perl5/Debconf/Question.pm line 72.

Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/\${ <-- HERE ([^}]+)}/ at /usr/share/perl5/Debconf/Config.pm line 30.

When I jump to the line 72 this is what I see

```<code>while ($rest =~ m/^(.*?)(\\)?\${([^{}]+)}(.*)$/sg) {
</code>```

答:
It's a deprecation warning indicating the code will stop working in the future.

If you want to match a { literally, you should escape it.

In other words, you can fix the issue (silencing the warning) by replacing the first { with \{.

Title: Unescaped left brace regex error

Body:
I’m not an expert in regex and can't figure what I am supposed to change here.

I get these two errors

Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/^(.*?)(\\)?\${ <-- HERE ([^{}]+)}(.*)$/ at /usr/share/perl5/Debconf/Question.pm line 72.

Unescaped left brace in regex is deprecated, passed through in regex; marked by <-- HERE in m/\${ <-- HERE ([^}]+)}/ at /usr/share/perl5/Debconf/Config.pm line 30.

When I jump to the line 72 this is what I see

while ($rest =~ m/^(.*?)(\\)?\${([^{}]+)}(.*)$/sg) {


问:
Javascript object list. take a name and a list, then return list of all names etc function
I've been trying to figure out what's the best code to make for this function, but the codes i'd tried isn't working.

Here are the instructions.

Should take a name and a list of people,and return a list of all the names that  is not friends with", function use isFriends irrirate each object if comes back false that is on the friend list

```<code>var data = [
  {name: "Jimmy", friends:["Sara", "Liza"]},
  {name: "Bob", friends:[]},
  {name: "Liza", friends: ["Jimmy"]},
  {name: "Sara", friends: ["Jimmy"]}
];

assert.deepEqual(nonFriends("Jimmy", data), ["Bob"]);
assert.deepEqual(nonFriends("Bob", data), ["Jimmy", "Liza", "Sara"]);
assert.deepEqual(nonFriends("Sara", data), ["Bob","Liza"]);
</code>```

this is my code for isFriends function

isFriend() : Should take a name and an object and return true if  is a friend of  and false otherwise"

```<code>function isFriend(name, obj) {
  if(Array.isArray(obj.friends) && obj.hasOwnProperty("friends")) {
    for(var i = 0; i < obj.friends.length; i++) {
      if(name === obj.friends[i]) {
        return true;
      }
    }
  }
 return false;
}
</code>```

how do i create a nonFriend function as described to implement isFriend function. can you also explain it to me in details. i'm not confident on if else statements and etc. thank you

答:
The nonFirends() method include the following things to do:

Extract all people name.

Find if the input name is a name in the list, if not that means all people are not friends.

Compare the friend list of the target object with the full list of
names.

The following code should work.

```<code>function nonFriends(name, arr){
    var nameList = [];
    var result = [];
    var current = null;
    for(var i=0; i<arr.length; i++){
        if(name === arr[i].name){
            current = arr[i];
        }else{
            nameList.push(arr[i].name);
        }
    }

    if(current === null){
        return nameList;
    }

    for(var i=0; i<nameList.length; i++){
        if(current.friends.indexOf(nameList[i]) == -1){
            result.push(nameList[i]);
        }
    }

    return result;

}
</code>```

Body:
I've been trying to figure out what's the best code to make for this function, but the codes i'd tried isn't working.

Here are the instructions.

Should take a name and a list of people,and return a list of all the names that  is not friends with", function use isFriends irrirate each object if comes back false that is on the friend list

var data = [
  {name: "Jimmy", friends:["Sara", "Liza"]},
  {name: "Bob", friends:[]},
  {name: "Liza", friends: ["Jimmy"]},
  {name: "Sara", friends: ["Jimmy"]}
];

assert.deepEqual(nonFriends("Jimmy", data), ["Bob"]);
assert.deepEqual(nonFriends("Bob", data), ["Jimmy", "Liza", "Sara"]);
assert.deepEqual(nonFriends("Sara", data), ["Bob","Liza"]);

this is my code for isFriends function

isFriend() : Should take a name and an object and return true if  is a friend of  and false otherwise"

function isFriend(name, obj) {
  if(Array.isArray(obj.friends) && obj.hasOwnProperty("friends")) {
    for(var i = 0; i < obj.friends.length; i++) {
      if(name === obj.friends[i]) {
        return true;
      }
    }
  }
 return false;
}

how do i create a nonFriend function as described to implement isFriend function. can you also explain it to me in details. i'm not confident on if else statements and etc. thank you

Body:
The nonFirends() method include the following things to do:

Extract all people name.

Find if the input name is a name in the list, if not that means all people are not friends.

Compare the friend list of the target object with the full list of
names.

The following code should work.

function nonFriends(name, arr){
    var nameList = [];
    var result = [];
    var current = null;
    for(var i=0; i<arr.length; i++){
        if(name === arr[i].name){
            current = arr[i];
        }else{
            nameList.push(arr[i].name);
        }
    }

    if(current === null){
        return nameList;
    }

    for(var i=0; i<nameList.length; i++){
        if(current.friends.indexOf(nameList[i]) == -1){
            result.push(nameList[i]);
        }
    }

    return result;

}


问:
How to apply WHERE clause to multiple SELECT statements in SQL Server
I am creating an query that selects data from multiple tables. I have completed all the query but now I have to apply the WHERE clause to the whole query.
I have 9 select statements, and these are working fine. Data is being selected from different tables. Now I want to declare date session and I want all data to be filtered according to the date provided. I am using the below query:

```<code>SELECT
    (SELECT COUNT(DISTINCT OrderItems.ProductID)
     FROM OrderItems) AS 'TotalSoldItemsDistinct',
    (SELECT COUNT(OrderItems.ProductID)
     FROM OrderItems) AS 'TotalSoldItemsInDistinct',
    (SELECT COUNT(Orders.OrderID)
     FROM Orders) AS 'TotalOrders',
   (SELECT COUNT(Orders.OrderID)
    FROM Orders
    WHERE Orders.OrderStatusID = @CompleteOStatusID) AS 'CompleteOrders',
   (SELECT COUNT(Orders.OrderID)
    FROM Orders
    WHERE Orders.OrderStatusID = @PendingOStatusID) AS 'PendingOrders',
   (SELECT COUNT(Orders.ClientID)
    FROM Orders
    WHERE Orders.ClientID != @WalkingCustID) AS 'namedcustomers',
   (SELECT COUNT(Orders.ClientID)
    FROM Orders
    WHERE Orders.ClientID = @WalkingCustID) AS 'WalkingCustomers',
   (SELECT SUM(OrderItems.PurchasePrice)
    FROM OrderItems) AS 'TotalPurchasePrice',
   (SELECT SUM(OrderItems.SalePrice)
    FROM OrderItems) AS 'TotalSalePrice'
</code>```

I am selecting data from 2 tables named 'Orders' and 'OrderItems', I have column TransactionDate in 'Orders' table and column OrderDate in OrderItems table on that I want to use where filter. Can anybody please suggest how to apply filter to whole query?

答:
It is not fully clear what you want as a result, but here 2 approaches.

Try the following for selecting data from 2 tables at the same time (replace the date with your criteria):

SELECT * FROM Orders AS o INNER JOIN OrderItems AS i WHERE o.TransactionDate = '2015-02-12' AND i.OrderDate = '2015-02-12';

The SELECT * selects all columns from both tables as a result and the WHERE ... AND ...-clause filters for results only with your defined date.

Try the following for selecting order item data only for Data that matches the date on a specific order.

SELECT i.* FROM Orders AS o INNER JOIN OrderItems AS i WHERE o.TransactionDate = i.OrderDate AND o.OrderID = '12345';

The SELECT i.* tells the query to only return the columns of the OrderItems. And the WHERE o.TransactionDate = i.OrderDate ensures that only order items from the same date of the order with the OrderID "12345" are returned (which is defined with the AND o.OrderID = '12345'. This would work given you have a field "OrderID" on your Order table and you want to use it as a criteria.

Body:
I am creating an query that selects data from multiple tables. I have completed all the query but now I have to apply the WHERE clause to the whole query.
I have 9 select statements, and these are working fine. Data is being selected from different tables. Now I want to declare date session and I want all data to be filtered according to the date provided. I am using the below query:

SELECT
    (SELECT COUNT(DISTINCT OrderItems.ProductID)
     FROM OrderItems) AS 'TotalSoldItemsDistinct',
    (SELECT COUNT(OrderItems.ProductID)
     FROM OrderItems) AS 'TotalSoldItemsInDistinct',
    (SELECT COUNT(Orders.OrderID)
     FROM Orders) AS 'TotalOrders',
   (SELECT COUNT(Orders.OrderID)
    FROM Orders
    WHERE Orders.OrderStatusID = @CompleteOStatusID) AS 'CompleteOrders',
   (SELECT COUNT(Orders.OrderID)
    FROM Orders
    WHERE Orders.OrderStatusID = @PendingOStatusID) AS 'PendingOrders',
   (SELECT COUNT(Orders.ClientID)
    FROM Orders
    WHERE Orders.ClientID != @WalkingCustID) AS 'namedcustomers',
   (SELECT COUNT(Orders.ClientID)
    FROM Orders
    WHERE Orders.ClientID = @WalkingCustID) AS 'WalkingCustomers',
   (SELECT SUM(OrderItems.PurchasePrice)
    FROM OrderItems) AS 'TotalPurchasePrice',
   (SELECT SUM(OrderItems.SalePrice)
    FROM OrderItems) AS 'TotalSalePrice'

I am selecting data from 2 tables named 'Orders' and 'OrderItems', I have column TransactionDate in 'Orders' table and column OrderDate in OrderItems table on that I want to use where filter. Can anybody please suggest how to apply filter to whole query?


问:
How to check if there is empty texbox in a panel?
I want to have warning message if there is empty textbox in a panel, is there any way? please help.</p>

答:
You can use this code on each one so you can show a different message each time depending on the data that should be wirten in the textbox: </p>

```<code>If textbox1.Text = "" Then
    MsgBox("Your message here", MsgBoxStyle.Critical)
End If
</code>```

Body:
You can use this code on each one so you can show a different message each time depending on the data that should be wirten in the textbox:

If textbox1.Text = "" Then
    MsgBox("Your message here", MsgBoxStyle.Critical)
End If


问:
Why does this html table definition not validate?
I'm getting this W3C HTML validation error:

```<code>end tag for "table" which is not finished
</code>```

for this code:

```<code><table id="myTable">
</table>
</code>```

This is my DOCTYPE:

```<code><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
</code>```

I thought that table definition was perfectly fine!?

答:
A XHTML 1.0 table is required to have at least a tbody or a tr child.  See the DTD, specifically the table element:

```<code><!ELEMENT table
     (caption?, (col*|colgroup*), thead?, tfoot?, (tbody+|tr+))>
</code>```

Note the last part.

Body:
I'm getting this W3C HTML validation error:

end tag for "table" which is not finished

for this code:

This is my DOCTYPE:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">

I thought that table definition was perfectly fine!?

Body:
A XHTML 1.0 table is required to have at least a tbody or a tr child.  See the DTD, specifically the table element:

<!ELEMENT table
     (caption?, (col*|colgroup*), thead?, tfoot?, (tbody+|tr+))>

Note the last part.


问:
Assembly: troubles with my linear search code
For an assignment I have to finish the code for a program that uses a loop to compare each array element to a target value that's provided through user input. So for example, when the program asks me to type a number and I type the number 6, it should give me the sixth number in this list. '7','3','2','1','0','5','6','4','8','9'

I typed what the comments told me to type but I keep getting this error when I try to compile it.

```<code>main.o: In function `getNextElement':
main.asm:(.text+0x92): relocation truncated to fit: R_386_8 against '.data'
</code>```

Can anyone tell me what I'm doing wrong here?

```<code>    ;;;;;;;;;;;;;;;;;;;;    MACRO DEFINITIONS   ;;;;;;;;;;;;;;;;;;;;
; A macro with two parameters
; Implements the write system call
    %macro writestring 2
        mov eax, 4  ;sys_write system call number
        mov ebx, 1  ;file descriptor std_out
        mov ecx, %1 ;message to write from parameter 1
        mov edx, %2 ;message length from parameter 2
        int 0x80
    %endmacro
; A macro with two parameters
; Implements the sys_read call
    %macro read_string 2
        mov eax, 3  ;sys_write system call number
        mov ebx, 2  ;file descriptor std_in
        mov ecx, %1 ;variable/array to hold data, pass by reference in param 1
        mov edx, %2 ;number of bytes to read passed by value in param 2
        int 0x80
    %endmacro

;;;;;;;;;;;;;;;;;;;;    DATA SEGMENT    ;;;;;;;;;;;;;;;;;;;;
section .data
msg1 db 'Here are the elements: '
lenmsg1 equ $-msg1
msg2 db 'Enter a number to search for: '
lenmsg2 equ $-msg2
msg3 db 'The target value was found at index '
lenmsg3 equ $-msg3
msg4 db 'The target value was NOT found...',0x0a, 0x0d
lenmsg4 equ $-msg4
asciinums db '7','3','2','1','0','5','6','4','8','9'
lenasciinums equ $-asciinums
crlf db 0x0d, 0x0a
lencrlf equ $ - crlf
target db 0x00
targetlocation db 0x30

section .text
    global _start
_start:
    writestring msg1, lenmsg1
    writestring asciinums, lenasciinums
    writestring crlf, lencrlf
    writestring msg2, lenmsg2
    read_string target, 1
    writestring crlf, lencrlf
    mov eax, asciinums  ;eax holds base address
    mov ecx, 0          ;ecx is index register
getNextElement:
    mov [eax+ecx], al   ;copy value from asciinums into an 8-bit register
    cmp al, target      ;compare the 8-bit register to target value
    je  targetlocation  ;jump if equal to the found label
    inc ecx             ;increment index register
    cmp ecx, 10         ;compare index register to decimal 10
    jne getNextElement  ;if index register not equal to 10 go to getNextElement

    writestring msg4, lenmsg4
    jmp terminate
found:
    add [targetlocation], ecx
    writestring msg3, lenmsg3
    writestring targetlocation, 1
    writestring crlf, lencrlf
terminate:
    mov eax, 1          ;terminate program
    int 0x80
</code>```

I also know that the problem is from this section of the code.

```<code>    mov eax, asciinums  ;eax holds base address
    mov ecx, 0          ;ecx is index register
getNextElement:
    mov [eax+ecx], al   ;copy value from asciinums into an 8-bit register
    cmp al, target      ;compare the 8-bit register to target value
    je  targetlocation  ;jump if equal to the found label
    inc ecx             ;increment index register
    cmp ecx, 10         ;compare index register to decimal 10
    jne getNextElement  ;if index register not equal to 10 go to getNextElement
</code>```

This is the website I used to compile. Any help would be greatly appreciated.

https://www.tutorialspoint.com/compile_assembly_online.php

答:
Assuming that you're writing code for x86 architecture the problem is je instruction in getNextElement. je instruction is a short jump, it expects relative address as a parameter only and it can't be used to make indirect jumps. Here you can look at the difference between je and jmp instructions:

http://x86.renejeschke.de/html/file_module_x86_id_146.html

http://x86.renejeschke.de/html/file_module_x86_id_147.html

Added:

mov [eax+ecx], al   ;copy value from asciinums into an 8-bit register

Here you're moving al into memory and comment says the opposite. Fix it, use je found and try again.

Added:

And another one:
mov [eax+ecx], al   ;copy value from asciinums into an 8-bit register
here you're ruining eax register by loading data into al. On the next loop you'll fetch garbage from memory.

Checked, after fixing all mentioned mistakes it works perfectly.

```<code>;;;;;;;;;;;;;;;;;;;;    MACRO DEFINITIONS   ;;;;;;;;;;;;;;;;;;;;
; A macro with two parameters
; Implements the write system call
    %macro writestring 2
        mov eax, 4  ;sys_write system call number
        mov ebx, 1  ;file descriptor std_out
        mov ecx, %1 ;message to write from parameter 1
        mov edx, %2 ;message length from parameter 2
        int 0x80
    %endmacro
; A macro with two parameters
; Implements the sys_read call
    %macro read_string 2
        mov eax, 3  ;sys_write system call number
        mov ebx, 2  ;file descriptor std_in
        mov ecx, %1 ;variable/array to hold data, pass by reference in param 1
        mov edx, %2 ;number of bytes to read passed by value in param 2
        int 0x80
    %endmacro

;;;;;;;;;;;;;;;;;;;;    DATA SEGMENT    ;;;;;;;;;;;;;;;;;;;;
section .data
msg1 db 'Here are the elements: '
lenmsg1 equ $-msg1
msg2 db 'Enter a number to search for: '
lenmsg2 equ $-msg2
msg3 db 'The target value was found at index '
lenmsg3 equ $-msg3
msg4 db 'The target value was NOT found...',0x0a, 0x0d
lenmsg4 equ $-msg4
asciinums db '7','3','2','1','0','5','6','4','8','9'
lenasciinums equ $-asciinums
crlf db 0x0d, 0x0a
lencrlf equ $ - crlf
target db 0x00
targetlocation db 0x30

section .text
    global _start
_start:
    writestring msg1, lenmsg1
    writestring asciinums, lenasciinums
    writestring crlf, lencrlf
    writestring msg2, lenmsg2
    read_string target, 1
    writestring crlf, lencrlf
    mov eax, asciinums  ;eax holds base address
    mov ecx, 0          ;ecx is index register
getNextElement:
    mov bl, [eax+ecx]   ;copy value from asciinums into an 8-bit register
    cmp bl, [target]    ;compare the 8-bit register to target value
    je  found           ;jump if equal to the found label
    inc ecx             ;increment index register
    cmp ecx, 10         ;compare index register to decimal 10
    jne getNextElement  ;if index register not equal to 10 go to getNextElement

    writestring msg4, lenmsg4
    jmp terminate
found:
    add [targetlocation], ecx
    writestring msg3, lenmsg3
    writestring targetlocation, 1
    writestring crlf, lencrlf
terminate:
    mov eax, 1          ;terminate program
    int 0x80
</code>```

Body:
For an assignment I have to finish the code for a program that uses a loop to compare each array element to a target value that's provided through user input. So for example, when the program asks me to type a number and I type the number 6, it should give me the sixth number in this list. '7','3','2','1','0','5','6','4','8','9'

I typed what the comments told me to type but I keep getting this error when I try to compile it.

main.o: In function `getNextElement':
main.asm:(.text+0x92): relocation truncated to fit: R_386_8 against '.data'

Can anyone tell me what I'm doing wrong here?

    ;;;;;;;;;;;;;;;;;;;;    MACRO DEFINITIONS   ;;;;;;;;;;;;;;;;;;;;
; A macro with two parameters
; Implements the write system call
    %macro writestring 2
        mov eax, 4  ;sys_write system call number
        mov ebx, 1  ;file descriptor std_out
        mov ecx, %1 ;message to write from parameter 1
        mov edx, %2 ;message length from parameter 2
        int 0x80
    %endmacro
; A macro with two parameters
; Implements the sys_read call
    %macro read_string 2
        mov eax, 3  ;sys_write system call number
        mov ebx, 2  ;file descriptor std_in
        mov ecx, %1 ;variable/array to hold data, pass by reference in param 1
        mov edx, %2 ;number of bytes to read passed by value in param 2
        int 0x80
    %endmacro

;;;;;;;;;;;;;;;;;;;;    DATA SEGMENT    ;;;;;;;;;;;;;;;;;;;;
section .data
msg1 db 'Here are the elements: '
lenmsg1 equ $-msg1
msg2 db 'Enter a number to search for: '
lenmsg2 equ $-msg2
msg3 db 'The target value was found at index '
lenmsg3 equ $-msg3
msg4 db 'The target value was NOT found...',0x0a, 0x0d
lenmsg4 equ $-msg4
asciinums db '7','3','2','1','0','5','6','4','8','9'
lenasciinums equ $-asciinums
crlf db 0x0d, 0x0a
lencrlf equ $ - crlf
target db 0x00
targetlocation db 0x30

section .text
    global _start
_start:
    writestring msg1, lenmsg1
    writestring asciinums, lenasciinums
    writestring crlf, lencrlf
    writestring msg2, lenmsg2
    read_string target, 1
    writestring crlf, lencrlf
    mov eax, asciinums  ;eax holds base address
    mov ecx, 0          ;ecx is index register
getNextElement:
    mov [eax+ecx], al   ;copy value from asciinums into an 8-bit register
    cmp al, target      ;compare the 8-bit register to target value
    je  targetlocation  ;jump if equal to the found label
    inc ecx             ;increment index register
    cmp ecx, 10         ;compare index register to decimal 10
    jne getNextElement  ;if index register not equal to 10 go to getNextElement

    writestring msg4, lenmsg4
    jmp terminate
found:
    add [targetlocation], ecx
    writestring msg3, lenmsg3
    writestring targetlocation, 1
    writestring crlf, lencrlf
terminate:
    mov eax, 1          ;terminate program
    int 0x80

I also know that the problem is from this section of the code.

    mov eax, asciinums  ;eax holds base address
    mov ecx, 0          ;ecx is index register
getNextElement:
    mov [eax+ecx], al   ;copy value from asciinums into an 8-bit register
    cmp al, target      ;compare the 8-bit register to target value
    je  targetlocation  ;jump if equal to the found label
    inc ecx             ;increment index register
    cmp ecx, 10         ;compare index register to decimal 10
    jne getNextElement  ;if index register not equal to 10 go to getNextElement

This is the website I used to compile. Any help would be greatly appreciated.

https://www.tutorialspoint.com/compile_assembly_online.php

Body:
Assuming that you're writing code for x86 architecture the problem is je instruction in getNextElement. je instruction is a short jump, it expects relative address as a parameter only and it can't be used to make indirect jumps. Here you can look at the difference between je and jmp instructions:

http://x86.renejeschke.de/html/file_module_x86_id_146.html

http://x86.renejeschke.de/html/file_module_x86_id_147.html

Added:

mov [eax+ecx], al   ;copy value from asciinums into an 8-bit register

Here you're moving al into memory and comment says the opposite. Fix it, use je found and try again.

Added:

And another one:
mov [eax+ecx], al   ;copy value from asciinums into an 8-bit register
here you're ruining eax register by loading data into al. On the next loop you'll fetch garbage from memory.

Checked, after fixing all mentioned mistakes it works perfectly.

;;;;;;;;;;;;;;;;;;;;    MACRO DEFINITIONS   ;;;;;;;;;;;;;;;;;;;;
; A macro with two parameters
; Implements the write system call
    %macro writestring 2
        mov eax, 4  ;sys_write system call number
        mov ebx, 1  ;file descriptor std_out
        mov ecx, %1 ;message to write from parameter 1
        mov edx, %2 ;message length from parameter 2
        int 0x80
    %endmacro
; A macro with two parameters
; Implements the sys_read call
    %macro read_string 2
        mov eax, 3  ;sys_write system call number
        mov ebx, 2  ;file descriptor std_in
        mov ecx, %1 ;variable/array to hold data, pass by reference in param 1
        mov edx, %2 ;number of bytes to read passed by value in param 2
        int 0x80
    %endmacro

;;;;;;;;;;;;;;;;;;;;    DATA SEGMENT    ;;;;;;;;;;;;;;;;;;;;
section .data
msg1 db 'Here are the elements: '
lenmsg1 equ $-msg1
msg2 db 'Enter a number to search for: '
lenmsg2 equ $-msg2
msg3 db 'The target value was found at index '
lenmsg3 equ $-msg3
msg4 db 'The target value was NOT found...',0x0a, 0x0d
lenmsg4 equ $-msg4
asciinums db '7','3','2','1','0','5','6','4','8','9'
lenasciinums equ $-asciinums
crlf db 0x0d, 0x0a
lencrlf equ $ - crlf
target db 0x00
targetlocation db 0x30

section .text
    global _start
_start:
    writestring msg1, lenmsg1
    writestring asciinums, lenasciinums
    writestring crlf, lencrlf
    writestring msg2, lenmsg2
    read_string target, 1
    writestring crlf, lencrlf
    mov eax, asciinums  ;eax holds base address
    mov ecx, 0          ;ecx is index register
getNextElement:
    mov bl, [eax+ecx]   ;copy value from asciinums into an 8-bit register
    cmp bl, [target]    ;compare the 8-bit register to target value
    je  found           ;jump if equal to the found label
    inc ecx             ;increment index register
    cmp ecx, 10         ;compare index register to decimal 10
    jne getNextElement  ;if index register not equal to 10 go to getNextElement

    writestring msg4, lenmsg4
    jmp terminate
found:
    add [targetlocation], ecx
    writestring msg3, lenmsg3
    writestring targetlocation, 1
    writestring crlf, lencrlf
terminate:
    mov eax, 1          ;terminate program
    int 0x80


答:
Use flexbox to fix your problem.
Wrap the container fieldset using display: flex, Set the flex-direction as column. Wrap the children inside a div and set the flex-grow property for the span element as 1.

Using flexbox will take care of responsiveness.

Refer CSS Flexbox

fieldset {
  display: flex;
  flex-direction: column;
}

div {
  display: flex;
  margin: 10px;
}

span {
  flex: 1;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><fieldset>
  <legend>Billing Information</legend>
  <div><span>Card Number: </span><input type="text"> </div>
  <div><span>Expiration Month:</span> <input type="number"></div>
  <div><span> Expiration Year:</span> <input type="number"></div>
  <div><span>Name on Card:</span> <input type="text"> </div>
  <div><span>Address:</span> <input type="text"> </div>
  <div><span>City:</span> <input type="text"></div>
  <div><span>State: </span><input type="text"></div>
  <div><span>Country:</span> <input type="text"></div>
  <div><span>ZIP Code:</span> <input type="number"></div>
</fieldset></code>```

Title: Align right side of a group of labels

Body:
I'm making an HTML page with a list of fields for filling out billing info.
Since the labels are in-line, their width is determined by the text contained in them, thus making them different widths which makes the input boxes unaligned. This makes a very ugly, unorganized look.

<fieldset>
    <legend>Billing Information</legend>

    Card Number: <input type="text">

    Expiration Month: <input type="number">

    Expiration Year: <input type="number">

    Name on Card: <input type="text">

    Address: <input type="text">

    City: <input type="text">

    State: <input type="text">

    Country: <input type="text">

    ZIP Code: <input type="number">

</fieldset>

What do I need to do to my HTML code to align the right side of the labels and the left side of the input boxes?

Body:
Use flexbox to fix your problem.
Wrap the container fieldset using display: flex, Set the flex-direction as column. Wrap the children inside a div and set the flex-grow property for the span element as 1.

Using flexbox will take care of responsiveness.

Refer CSS Flexbox

fieldset {
  display: flex;
  flex-direction: column;
}

div {
  display: flex;
  margin: 10px;
}

span {
  flex: 1;
}

<fieldset>
  <legend>Billing Information</legend>
  <div><span>Card Number: </span><input type="text"> </div>
  <div><span>Expiration Month:</span> <input type="number"></div>
  <div><span> Expiration Year:</span> <input type="number"></div>
  <div><span>Name on Card:</span> <input type="text"> </div>
  <div><span>Address:</span> <input type="text"> </div>
  <div><span>City:</span> <input type="text"></div>
  <div><span>State: </span><input type="text"></div>
  <div><span>Country:</span> <input type="text"></div>
  <div><span>ZIP Code:</span> <input type="number"></div>
</fieldset>


问:
Why does the delete method not free up memory for a widget in Tkinter?
In Tkinter I have a large block of code that updates and clears a ScrolledText widget. I noticed during testing however that there was a memory leak regarding this, and after narrowing it down the simplest way to replicate this behavior is:

```<code>import tkinter
import tkinter.scrolledtext
def meme(box_text):
    while True:
        box_text.insert("end", "meme")
        box_text.delete(1.0, "end")
window_main = tkinter.Tk()
box_text = tkinter.scrolledtext.ScrolledText(window_main)
button = tkinter.Button(window_main, command=lambda: meme(box_text))
box_text.pack()
button.pack()
window_main.mainloop()
</code>```

Can anyone explain what I'm doing wrong? I don't understand nor see the problem with this in relation to memory. If I comment out the insert, with only the delete, there's no memory issue so the loop itself is not to blame as far as I can tell, only the insert.

答: I found the culprit. For the Text widget by default "maxundo" is set to 0, and thus Tkinter keeps a log of everything inserted into it. Setting this to 1 solved the problem. Edit: undo=False works better.

Body:
In Tkinter I have a large block of code that updates and clears a ScrolledText widget. I noticed during testing however that there was a memory leak regarding this, and after narrowing it down the simplest way to replicate this behavior is:

import tkinter
import tkinter.scrolledtext
def meme(box_text):
    while True:
        box_text.insert("end", "meme")
        box_text.delete(1.0, "end")
window_main = tkinter.Tk()
box_text = tkinter.scrolledtext.ScrolledText(window_main)
button = tkinter.Button(window_main, command=lambda: meme(box_text))
box_text.pack()
button.pack()
window_main.mainloop()

Can anyone explain what I'm doing wrong? I don't understand nor see the problem with this in relation to memory. If I comment out the insert, with only the delete, there's no memory issue so the loop itself is not to blame as far as I can tell, only the insert.


问:
The Active Record will auto generate name
I study a e-book of Ruby on Rails:
If I create a Active Record below:

```<code>class Product < ApplicationRecord
end
</code>```

Rails Will execute the below code to generate a table:

```<code>CREATE TABLE products (
   id int(11) NOT NULL auto_increment,
   name varchar(255),
   PRIMARY KEY  (id)
);
</code>```

There I have a question, I can understand auto generate the major key, but why how to understand the:

```<code>name varchar(255),
</code>```

If the name field is auto generated? and if yes, why it is necessary?

答:
No,the sql statement to create the table 'products' is not from your model file(product.rb), but from migrate files.

Where you run a Rails rake command: rake g model product name:sring,
it will not only create a model file(product.rb) for you, but also a migrate file in "db/migrate/" folder, naming like "xxxxxx_create_products.rb". Open this file and you will see lines like:

```<code>def change
    create_table :products do |t|
      t.string :name
    end
end
</code>```

That's how Rails knows what columns you want to have in your "products" talbe, and what type they should be.
And this table will not be created, until you run this command: rake db:migrate.

Body:
I study a e-book of Ruby on Rails:
If I create a Active Record below:

class Product < ApplicationRecord
end

Rails Will execute the below code to generate a table:

CREATE TABLE products (
   id int(11) NOT NULL auto_increment,
   name varchar(255),
   PRIMARY KEY  (id)
);

There I have a question, I can understand auto generate the major key, but why how to understand the:

name varchar(255),

If the name field is auto generated? and if yes, why it is necessary?

Body:
No,the sql statement to create the table 'products' is not from your model file(product.rb), but from migrate files.

Where you run a Rails rake command: rake g model product name:sring,
it will not only create a model file(product.rb) for you, but also a migrate file in "db/migrate/" folder, naming like "xxxxxx_create_products.rb". Open this file and you will see lines like:

def change
    create_table :products do |t|
      t.string :name
    end
end

That's how Rails knows what columns you want to have in your "products" talbe, and what type they should be.
And this table will not be created, until you run this command: rake db:migrate.


问:
Kurento - WebRTC does not work on linux virtual machine azure server
I implement Kurento on my local, it works ok.
When I deploy it on linux vm azure server, kurento does not work.
I know that Kurento just works with UDP default, if want it works on TCP, I have to config turn server for kurento. After config turn server of google for kurento, but it still does not work.
And then i try to change Azure to UDP, but I just found down the guider for window vm, it is config on endpoint.
Who knows how to resolve this problem, make kurento work on azure server, please give me your ideas.</p>

答:
First off, Azure does not allow UDP traffic.

On TCP, since you get no error, it sems like the problem is with the network. Assuming that you are trying to tx/rx data from Azure to a server/client outside of Azure, make sure you create/map the proper ports from the Azure public IP endpoint to your VM. You can do this from the Azure portal. Even if the port is open on the VM, you still need to map ports from the public IP to the VM; sort of like port forwarding in a home router.

I hope this helps!


问:
Simultaneous requests in JMeter
Assume I have two users in Thread Group and want them to fire two requests simultaneously. User 1 - HTTP Request A and User 2 - HTTP Request B.

Any ideas how to implement that ?

答:
Just add Synchronizing Timer to your Thread Group and set Number of Simulated Users to Group by to 2 like:

The Synchronizing Timer will pause the first thread until second one is ready to execute the HTTP Request sampler so both threads will be run simultaneously. See Using the JMeter Synchronizing Timer article for more details.

Title: Simultaneous requests in JMeter


问:
Why does SoundPlayer intermittently hang on playback?
I have a WPF application in which I'm using SoundPlayer to play several short sounds such as keyboard clicks. Sometimes, seemingly at random, the sounds will stop playing. When I navigate away from the page the sounds will then play all at once in one screeching playback.

My question is, are there any obvious reasons as to why this would happen?

I've tried several things but because I can't consistently reproduce the issue it's hard to find the cause. The sounds are used throughout the application, so I load them in app.xaml.cs into an application scoped static collection. I call SoundPlayer.Load() to ensure they're loaded into memory straight away.

Like I said, this never stops working completely. The play backs seem to pile up until navigating to another page where they all play at once.

One other thing that may have an impact is that I am displaying a webcam feed in the application. The webcam feed is loaded using the DirectShow.NET library. I'm not sure if loading graphs can have any adverse effect on the playback of sound.

答:
I suppose the web cam is updating a UI element which will cause the UI thread to be pretty busy, in that case you probably do not want to use SoundPlayer.PlaySync() or SoundPlayer.Load which both block the current thread.

Instead try SoundPlayer.LoadAsync() and SoundPlayer.Play() which use a separate thread.


问:
Timer.scheduledTimer is not working in swift 3
My timer is not working...can anyone help me?

I use timer to convert to next page if user login success, but timer is not work and no error message...

```<code>do {
                        if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
                            // Print out dictionary
                            print("convertedJsonIntoDict=\(convertedJsonIntoDict)")
                            print("convertedJsonIntoDict.長度=\(convertedJsonIntoDict.count)")
                            // Get value by key
                            if convertedJsonIntoDict.count > 1{
                                let cc_account = convertedJsonIntoDict["Account"] as! String
                                self.NPaccount = cc_account
                                print("工號=\(self.NPaccount)")
                                let cc_account_2 = convertedJsonIntoDict["Account2"] as! String
                                self.Account = cc_account_2
                                print("帳號=\(self.Account)")
                                let cname = convertedJsonIntoDict["CName"] as! String
                                self.Name = cname
                                print("姓名=\(self.Name)")
                                self.Member.account = self.Account
                                self.Member.password = self.PasswordTextvield.text!
                                self.Member.npaccount = self.NPaccount
                                self.Member.name = self.Name
                                self.Member.uuid = self.UUID
                                self.Member.creatdate = self.now
                                print("Saving data to context...")
                                appDelegate.saveContext()
                                self.segueflag = true
                                EZLoadingActivity.hide(true, animated: true)
                                _ = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.nextBtn(sender:)), userInfo: nil, repeats: false)
                            }else{
                                self.segueflag = false
                                print("segueflag...\(self.segueflag)")
                                if !self.segueflag{
                                    print("無此帳號資料...")
                                    EZLoadingActivity.hide(false, animated: true)
                                    //self.AccoubtTextvield.text = ""
                                    //self.PasswordTextvield.text = ""
                                }
                            }
                        }
                        else{
                            print("here")
                        }
                    } catch let error as NSError {
                        print(error.localizedDescription)
                    }

@IBAction func nextBtn(sender: AnyObject) {
        print("--------Go to next page!--------")
        if members.count == 0{
            SCLAlertView().showError("請先登入~~!!",subTitle:"")
            return
        }
        if !segueflag{
            SCLAlertView().showError("登入的帳號或密碼有誤~~!!",subTitle:"")
            return
        }
        self.performSegue(withIdentifier: "login", sender: self)
    }
</code>```

Can any one tell me possible answer. Thank you in advance....

答:
Timer method is change for ios10. If you are checking in ios10 you can use following code.

```<code>   let systemVersion = UIDevice.current.systemVersion

        if Int(systemVersion)! >= 10 {
            _ = Timer.scheduledTimer(withTimeInterval: 1.5,
                                         repeats: false) {
                                            timer in
                                            //Put the code that be called by the timer here.
                                            print("Testing data")
            }
        }else{

            _ = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.nextBtn(sender:)), userInfo: nil, repeats: false)

        }
</code>```

Body:
My timer is not working...can anyone help me?

I use timer to convert to next page if user login success, but timer is not work and no error message...

do {
                        if let convertedJsonIntoDict = try JSONSerialization.jsonObject(with: data, options: []) as? NSDictionary {
                            // Print out dictionary
                            print("convertedJsonIntoDict=\(convertedJsonIntoDict)")
                            print("convertedJsonIntoDict.長度=\(convertedJsonIntoDict.count)")
                            // Get value by key
                            if convertedJsonIntoDict.count > 1{
                                let cc_account = convertedJsonIntoDict["Account"] as! String
                                self.NPaccount = cc_account
                                print("工號=\(self.NPaccount)")
                                let cc_account_2 = convertedJsonIntoDict["Account2"] as! String
                                self.Account = cc_account_2
                                print("帳號=\(self.Account)")
                                let cname = convertedJsonIntoDict["CName"] as! String
                                self.Name = cname
                                print("姓名=\(self.Name)")
                                self.Member.account = self.Account
                                self.Member.password = self.PasswordTextvield.text!
                                self.Member.npaccount = self.NPaccount
                                self.Member.name = self.Name
                                self.Member.uuid = self.UUID
                                self.Member.creatdate = self.now
                                print("Saving data to context...")
                                appDelegate.saveContext()
                                self.segueflag = true
                                EZLoadingActivity.hide(true, animated: true)
                                _ = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.nextBtn(sender:)), userInfo: nil, repeats: false)
                            }else{
                                self.segueflag = false
                                print("segueflag...\(self.segueflag)")
                                if !self.segueflag{
                                    print("無此帳號資料...")
                                    EZLoadingActivity.hide(false, animated: true)
                                    //self.AccoubtTextvield.text = ""
                                    //self.PasswordTextvield.text = ""
                                }
                            }
                        }
                        else{
                            print("here")
                        }
                    } catch let error as NSError {
                        print(error.localizedDescription)
                    }

@IBAction func nextBtn(sender: AnyObject) {
        print("--------Go to next page!--------")
        if members.count == 0{
            SCLAlertView().showError("請先登入~~!!",subTitle:"")
            return
        }
        if !segueflag{
            SCLAlertView().showError("登入的帳號或密碼有誤~~!!",subTitle:"")
            return
        }
        self.performSegue(withIdentifier: "login", sender: self)
    }

Can any one tell me possible answer. Thank you in advance....

Body:
Timer method is change for ios10. If you are checking in ios10 you can use following code.

   let systemVersion = UIDevice.current.systemVersion

        if Int(systemVersion)! >= 10 {
            _ = Timer.scheduledTimer(withTimeInterval: 1.5,
                                         repeats: false) {
                                            timer in
                                            //Put the code that be called by the timer here.
                                            print("Testing data")
            }
        }else{

            _ = Timer.scheduledTimer(timeInterval: 1.5, target: self, selector: #selector(self.nextBtn(sender:)), userInfo: nil, repeats: false)

        }


问:
Simple validation for  element.
I have a table which consists of data from MYSQL, and whenever I make changes in an element in table, my database will be updated by ajax.
This is my javascript code to send the data in editable row.

```<code>        function saveToDatabase(editableObj,column,id) {
        $(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
        $("#tabs-1").load(location.href + " #tabs-1");
            $.ajax({
                url: "saveedit.php",
                type: "POST",
                data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
                success: function(data){
                    $(editableObj).css("background","#FDFDFD");
                }
           });
    }
</code>```

After the function above, saveedit.php will deal with updating the database and it's functional.

Then, this is my table in html and these table elements are editable.

```<code>        <?php
            $result = FUNCTION_TO_RETRIEVE_DATA_FROM_DB;
            foreach($result as $k=>$v){
        ?>
        <tr>
            <td><?php echo $k+1; ?></td>
            <td contenteditable="true" onBlur="saveToDatabase(this, 'memberID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["memberID"]; ?></td>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'surname', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["surname"]; ?></td>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'forename', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["forename"]; ?></td>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'address', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["address"]; ?></td>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'gradeID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["gradeID"]; ?></td>
        </tr>
        <?php
            }
        ?>
</code>```

This code is working, but the question I would like to ask is, how can I validate the data entered by the user into this  element? For example, what if I would like to check the initial column, memberID, cannot be longer than 6 characters, or if it is required or not. What I am trying to do is to validate entered data before sending it using AJAX but now but I have no idea how validation can be done in the table element.

答:
Before calling the saveToDatabase() function put the desired validation on the entered  value like:

```<code>var newVal = editableObj.innerHTML;
// Your validation on newVal, if validation successful call the saveToDatabase() function
// Otherwise show an error message and do nothing
</code>```

Title: Simple validation for <td contenteditable="true"> element.

Body:
I have a table which consists of data from MYSQL, and whenever I make changes in an element in table, my database will be updated by ajax.
This is my javascript code to send the data in editable row.

        function saveToDatabase(editableObj,column,id) {
        $(editableObj).css("background","#FFF url(images/loaderIcon.gif) no-repeat right");
        $("#tabs-1").load(location.href + " #tabs-1");
            $.ajax({
                url: "saveedit.php",
                type: "POST",
                data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id,
                success: function(data){
                    $(editableObj).css("background","#FDFDFD");
                }
           });
    }

After the function above, saveedit.php will deal with updating the database and it's functional.

Then, this is my table in html and these table elements are editable.

        <?php
            $result = FUNCTION_TO_RETRIEVE_DATA_FROM_DB;
            foreach($result as $k=>$v){
        ?>

            <?php echo $k+1; ?>
            <td contenteditable="true" onBlur="saveToDatabase(this, 'memberID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["memberID"]; ?>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'surname', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["surname"]; ?>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'forename', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["forename"]; ?>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'address', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["address"]; ?>

            <td contenteditable="true" onBlur="saveToDatabase(this, 'gradeID', '<?php echo $result[$k]["memberID"]; ?>')"><?php echo $result[$k]["gradeID"]; ?>

        <?php
            }
        ?>

This code is working, but the question I would like to ask is, how can I validate the data entered by the user into this  element? For example, what if I would like to check the initial column, memberID, cannot be longer than 6 characters, or if it is required or not. What I am trying to do is to validate entered data before sending it using AJAX but now but I have no idea how validation can be done in the table element.

Body:
Before calling the saveToDatabase() function put the desired validation on the entered  value like:

var newVal = editableObj.innerHTML;
// Your validation on newVal, if validation successful call the saveToDatabase() function
// Otherwise show an error message and do nothing


问:
About iOS IPv6 network with ionic framework
Yesterday, I submit my app for review, but I got a message from apple.

Apps are reviewed on an IPv6 network. Please ensure that your app supports IPv6 networks, as IPv6 compatibility is required.

For additional information about supporting IPv6 Networks, please refer to Supporting iPv6 DNS64/NAT64 Networks.

For a networking overview, see About Networking.

My app is used ionic framework, how can I fix this problem.

I already used domain to access my server, but this problem still exist.

答:
No need to make changes in your app code.

You have to check on API server have to support IPv6 Network.

Please find details -- http://www.internetsociety.org/deploy360/blog/2016/05/starting-june-1-apple-requires-all-ios-apps-to-work-in-ipv6-only-networks/?gclid=CK6K9ZfWgNMCFUoXaAodkuoGhw


问:
HTML to CSS (from inspect element)
I am trying to find the CSS code to place in my wordpress backend to float my page element in the center. I have figured out how to float center, but not how to convert the HTML into CSS.
please help

答:
I belive what you're looking for is:</p>

```<code>margin: 0 auto;
</code>```

Title: HTML to CSS (from inspect element)

Body:
I belive what you're looking for is:

margin: 0 auto;


问:
Get return of the method from Action.Invoke
I am trying to implement small console-like commands to ASP .Net Core App. I have a class which stores names and method that should be run:

```<code>public class ActionCenter
{
    public string ActionName { get; set; }
    public Action ActionStart { get; set; }
}
</code>```

And I have a list List<ActionCenter> Actions where I store all the commands and methods associated with them. To run method I can do Actions[0].ActionStart.Invoke, but I do not have return of the method. I tried Task<object> but cannot convert System.Action to System.Func<object>. Is there a way to have return from methods designed this way if not what is the right way?

答:
As it is stated at the documentation an Action:

Encapsulates a method that has no parameters and does not return a
  value.

```<code>public delegate void Action()
</code>```

That being said you cannot achieve that you want with an action. On the other hand, a Func<TResult>:

Encapsulates a method that has no parameters and returns a value of
  the type specified by the TResult parameter.

So in your case you need a Func rather than an Action. If we say that you expect your method to return always an int, you should have a Func<int> etc. Furthremore, Funcs as Actions can get a list of parameters, if your method is going to have any. So for instance, if your have a method that takes two parameters of type int and returns another int, the signarture of your Func, it would be Func<int,int,int>.

Body:
I am trying to implement small console-like commands to ASP .Net Core App. I have a class which stores names and method that should be run:

public class ActionCenter
{
    public string ActionName { get; set; }
    public Action ActionStart { get; set; }
}

And I have a list List<ActionCenter> Actions where I store all the commands and methods associated with them. To run method I can do Actions[0].ActionStart.Invoke, but I do not have return of the method. I tried Task<object> but cannot convert System.Action to System.Func<object>. Is there a way to have return from methods designed this way if not what is the right way?

Body:
As it is stated at the documentation an Action:

Encapsulates a method that has no parameters and does not return a
  value.

public delegate void Action()

That being said you cannot achieve that you want with an action. On the other hand, a Func<TResult>:

Encapsulates a method that has no parameters and returns a value of
  the type specified by the TResult parameter.

So in your case you need a Func rather than an Action. If we say that you expect your method to return always an int, you should have a Func<int> etc. Furthremore, Funcs as Actions can get a list of parameters, if your method is going to have any. So for instance, if your have a method that takes two parameters of type int and returns another int, the signarture of your Func, it would be Func<int,int,int>.


问:
Rails: Load content text file in public after change content.
I have a file text in public folder, url same like "public/text/index.html"

index.html

```<code><html>
  <body>
    <p> hello </p>
  </body>
</html>
</code>```

When I change content this file to:

```<code><html>
  <body>
    <p> hello World</p>
  </body>
</html>
</code>```

When i display this file on browser (url: "localhost:3000/text/index.html"), It display old content.

When i clear cache on brower, it load new content. I think cause is due to cache.
How to load new content without delete on brower?

答:
What you need islivereload.

When the files change, it will auto detect, reload the server, and reload the html in browser.

Check https://github.com/guard/guard-livereload and https://gist.github.com/maxivak/6a23fc7ffe7fea00a5e2

Body:
I have a file text in public folder, url same like "public/text/index.html"

index.html

 hello

When I change content this file to:

 hello World

When i display this file on browser (url: "localhost:3000/text/index.html"), It display old content.

When i clear cache on brower, it load new content. I think cause is due to cache.
How to load new content without delete on brower?


问:
variable null, even without being called
I'm attempting to use JavaScript to add rows to a table. I created an anonymous function iterate that iterates id names, and that works fine. The problem is somewhere in my class.

```<code>class CreateTable{
      constructor(text) {
    this.text = text
  }

  makeTableRow(){
    let self = this;
    let row = document.createElement('tr');
    for (let i = 0; i < 1; i++) {
      let el = document.createElement('td');
      el.setAttribute('id', iterate(i));
      row.appendChild(el);
    }
    let en = document.getElementById('id1');
    console.log(en);
    en.innerHTML = self.text;
    return row;
  }
}
</code>```

I adapted this class from something that already works, with some tweaks. The en variable is returning a typeError:en is null, and I can't figure it out. What I want to do is create two empty td elements with callable ids, and then add text to the first element immediately. What is the actual problem that is going on here?

答:
The document.getElementById() function returns null if there is no element with the specified ID in the DOM. The elements that you create in the loop have not been added to the DOM, they're appended to a tr that isn't in the DOM either (it's just returned from your function without having been appended to anything).

Just add the required text directly at the time you create the element:

```<code>makeTableRow(){
    let self = this;
    let row = document.createElement('tr');
    for (let i = 0; i < 1; i++) {
      let el = document.createElement('td');
      el.setAttribute('id', iterate(i));
      if (i === 0)                 // for first element
        el.innerHTML = self.text;  // set the content
      row.appendChild(el);
    }
    return row;
}
</code>```

Incidentally, you say you want to create two td elements, but your loop only runs for one iteration. The for condition should be i < 2 if you want it to run twice.

Body:
I'm attempting to use JavaScript to add rows to a table. I created an anonymous function iterate that iterates id names, and that works fine. The problem is somewhere in my class.

class CreateTable{
      constructor(text) {
    this.text = text
  }

  makeTableRow(){
    let self = this;
    let row = document.createElement('tr');
    for (let i = 0; i < 1; i++) {
      let el = document.createElement('td');
      el.setAttribute('id', iterate(i));
      row.appendChild(el);
    }
    let en = document.getElementById('id1');
    console.log(en);
    en.innerHTML = self.text;
    return row;
  }
}

I adapted this class from something that already works, with some tweaks. The en variable is returning a typeError:en is null, and I can't figure it out. What I want to do is create two empty td elements with callable ids, and then add text to the first element immediately. What is the actual problem that is going on here?

Body:
The document.getElementById() function returns null if there is no element with the specified ID in the DOM. The elements that you create in the loop have not been added to the DOM, they're appended to a tr that isn't in the DOM either (it's just returned from your function without having been appended to anything).

Just add the required text directly at the time you create the element:

makeTableRow(){
    let self = this;
    let row = document.createElement('tr');
    for (let i = 0; i < 1; i++) {
      let el = document.createElement('td');
      el.setAttribute('id', iterate(i));
      if (i === 0)                 // for first element
        el.innerHTML = self.text;  // set the content
      row.appendChild(el);
    }
    return row;
}

Incidentally, you say you want to create two td elements, but your loop only runs for one iteration. The for condition should be i < 2 if you want it to run twice.