问:
Position of least significant bit that is set
I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4.

A trivial implementation is this:

```<code>unsigned GetLowestBitPos(unsigned value)
{
   assert(value != 0); // handled separately

   unsigned pos = 0;
   while (!(value & 1))
   {
      value >>= 1;
      ++pos;
   }
   return pos;
}
</code>```

Any ideas how to squeeze some cycles out of it?

(Note: this question is for people that enjoy such things, not for people to tell me xyzoptimization is evil.)

[edit]  Thanks everyone for the ideas! I've learnt a few other things, too. Cool!

答:
This is in regards of @Anton Tykhyy answer

Here is my C++11 constexpr implementation doing away with casts and removing a warning on VC++17 by truncating a 64bit result to 32 bits:

```<code>constexpr uint32_t DeBruijnSequence[32] =
{
    0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
    31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
constexpr uint32_t ffs ( uint32_t value )
{
    return  DeBruijnSequence[
        (( ( value & ( -static_cast<int32_t>(value) ) ) * 0x077CB531ULL ) & 0xFFFFFFFF)
            >> 27];
}
</code>```

To get around the issue of 0x1 and 0x0 both returning 0 you can do:

```<code>constexpr uint32_t ffs ( uint32_t value )
{
    return (!value) ? 32 : DeBruijnSequence[
        (( ( value & ( -static_cast<int32_t>(value) ) ) * 0x077CB531ULL ) & 0xFFFFFFFF)
            >> 27];
}
</code>```

but if the compiler can't or won't preprocess the call it will add a couple of cycles to the calculation.

Finally, if interested, here's a list of static asserts to check that the code does what is intended to:

```<code>static_assert (ffs(0x1) == 0, "Find First Bit Set Failure.");
static_assert (ffs(0x2) == 1, "Find First Bit Set Failure.");
static_assert (ffs(0x4) == 2, "Find First Bit Set Failure.");
static_assert (ffs(0x8) == 3, "Find First Bit Set Failure.");
static_assert (ffs(0x10) == 4, "Find First Bit Set Failure.");
static_assert (ffs(0x20) == 5, "Find First Bit Set Failure.");
static_assert (ffs(0x40) == 6, "Find First Bit Set Failure.");
static_assert (ffs(0x80) == 7, "Find First Bit Set Failure.");
static_assert (ffs(0x100) == 8, "Find First Bit Set Failure.");
static_assert (ffs(0x200) == 9, "Find First Bit Set Failure.");
static_assert (ffs(0x400) == 10, "Find First Bit Set Failure.");
static_assert (ffs(0x800) == 11, "Find First Bit Set Failure.");
static_assert (ffs(0x1000) == 12, "Find First Bit Set Failure.");
static_assert (ffs(0x2000) == 13, "Find First Bit Set Failure.");
static_assert (ffs(0x4000) == 14, "Find First Bit Set Failure.");
static_assert (ffs(0x8000) == 15, "Find First Bit Set Failure.");
static_assert (ffs(0x10000) == 16, "Find First Bit Set Failure.");
static_assert (ffs(0x20000) == 17, "Find First Bit Set Failure.");
static_assert (ffs(0x40000) == 18, "Find First Bit Set Failure.");
static_assert (ffs(0x80000) == 19, "Find First Bit Set Failure.");
static_assert (ffs(0x100000) == 20, "Find First Bit Set Failure.");
static_assert (ffs(0x200000) == 21, "Find First Bit Set Failure.");
static_assert (ffs(0x400000) == 22, "Find First Bit Set Failure.");
static_assert (ffs(0x800000) == 23, "Find First Bit Set Failure.");
static_assert (ffs(0x1000000) == 24, "Find First Bit Set Failure.");
static_assert (ffs(0x2000000) == 25, "Find First Bit Set Failure.");
static_assert (ffs(0x4000000) == 26, "Find First Bit Set Failure.");
static_assert (ffs(0x8000000) == 27, "Find First Bit Set Failure.");
static_assert (ffs(0x10000000) == 28, "Find First Bit Set Failure.");
static_assert (ffs(0x20000000) == 29, "Find First Bit Set Failure.");
static_assert (ffs(0x40000000) == 30, "Find First Bit Set Failure.");
static_assert (ffs(0x80000000) == 31, "Find First Bit Set Failure.");
</code>```

ContentLicense: CC BY-SA 2.5

Body:
I am looking for an efficient way to determine the position of the least significant bit that is set in an integer, e.g. for 0x0FF0 it would be 4.

A trivial implementation is this:

unsigned GetLowestBitPos(unsigned value)
{
   assert(value != 0); // handled separately

   unsigned pos = 0;
   while (!(value & 1))
   {
      value >>= 1;
      ++pos;
   }
   return pos;
}

Any ideas how to squeeze some cycles out of it?

(Note: this question is for people that enjoy such things, not for people to tell me xyzoptimization is evil.)

[edit]  Thanks everyone for the ideas! I've learnt a few other things, too. Cool!

Body:
This is in regards of @Anton Tykhyy answer

Here is my C++11 constexpr implementation doing away with casts and removing a warning on VC++17 by truncating a 64bit result to 32 bits:

constexpr uint32_t DeBruijnSequence[32] =
{
    0, 1, 28, 2, 29, 14, 24, 3, 30, 22, 20, 15, 25, 17, 4, 8,
    31, 27, 13, 23, 21, 19, 16, 7, 26, 12, 18, 6, 11, 5, 10, 9
};
constexpr uint32_t ffs ( uint32_t value )
{
    return  DeBruijnSequence[
        (( ( value & ( -static_cast<int32_t>(value) ) ) * 0x077CB531ULL ) & 0xFFFFFFFF)
            >> 27];
}

To get around the issue of 0x1 and 0x0 both returning 0 you can do:

constexpr uint32_t ffs ( uint32_t value )
{
    return (!value) ? 32 : DeBruijnSequence[
        (( ( value & ( -static_cast<int32_t>(value) ) ) * 0x077CB531ULL ) & 0xFFFFFFFF)
            >> 27];
}

but if the compiler can't or won't preprocess the call it will add a couple of cycles to the calculation.

Finally, if interested, here's a list of static asserts to check that the code does what is intended to:

static_assert (ffs(0x1) == 0, "Find First Bit Set Failure.");
static_assert (ffs(0x2) == 1, "Find First Bit Set Failure.");
static_assert (ffs(0x4) == 2, "Find First Bit Set Failure.");
static_assert (ffs(0x8) == 3, "Find First Bit Set Failure.");
static_assert (ffs(0x10) == 4, "Find First Bit Set Failure.");
static_assert (ffs(0x20) == 5, "Find First Bit Set Failure.");
static_assert (ffs(0x40) == 6, "Find First Bit Set Failure.");
static_assert (ffs(0x80) == 7, "Find First Bit Set Failure.");
static_assert (ffs(0x100) == 8, "Find First Bit Set Failure.");
static_assert (ffs(0x200) == 9, "Find First Bit Set Failure.");
static_assert (ffs(0x400) == 10, "Find First Bit Set Failure.");
static_assert (ffs(0x800) == 11, "Find First Bit Set Failure.");
static_assert (ffs(0x1000) == 12, "Find First Bit Set Failure.");
static_assert (ffs(0x2000) == 13, "Find First Bit Set Failure.");
static_assert (ffs(0x4000) == 14, "Find First Bit Set Failure.");
static_assert (ffs(0x8000) == 15, "Find First Bit Set Failure.");
static_assert (ffs(0x10000) == 16, "Find First Bit Set Failure.");
static_assert (ffs(0x20000) == 17, "Find First Bit Set Failure.");
static_assert (ffs(0x40000) == 18, "Find First Bit Set Failure.");
static_assert (ffs(0x80000) == 19, "Find First Bit Set Failure.");
static_assert (ffs(0x100000) == 20, "Find First Bit Set Failure.");
static_assert (ffs(0x200000) == 21, "Find First Bit Set Failure.");
static_assert (ffs(0x400000) == 22, "Find First Bit Set Failure.");
static_assert (ffs(0x800000) == 23, "Find First Bit Set Failure.");
static_assert (ffs(0x1000000) == 24, "Find First Bit Set Failure.");
static_assert (ffs(0x2000000) == 25, "Find First Bit Set Failure.");
static_assert (ffs(0x4000000) == 26, "Find First Bit Set Failure.");
static_assert (ffs(0x8000000) == 27, "Find First Bit Set Failure.");
static_assert (ffs(0x10000000) == 28, "Find First Bit Set Failure.");
static_assert (ffs(0x20000000) == 29, "Find First Bit Set Failure.");
static_assert (ffs(0x40000000) == 30, "Find First Bit Set Failure.");
static_assert (ffs(0x80000000) == 31, "Find First Bit Set Failure.");


来源: stackexchange

问:
C# - Splitting the string when there are 3 chars and adding the values to the dictionary
I have a string like this:

```<code>var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";
</code>```

It's dynamically created, so this one is just for the sake of example. Numbers represent how many portions are ordered. I need to split it to dictionary by the name of food as a key and count how many portions are ordered which would be a value.

I've tried this for spliting the string, first by '\n' then by ' - ':

```<code>count = totalOrders.Split('\n').ToDictionary(item => item.Split(" - ")[0], item => int.Parse(item.Split(" - ")[1]));
</code>```

but I get an error "cannot convert from string to char. I had to use double quotes, because " - " this has 3 chars (2 spaces and a dash) and it's not recognized as a char.

Also, I think the problem will be when I start adding food, because it will report that keys won't be unique, considering that food appears more than once. How to solve this?

EDIT:

When I try this:

```<code>string[] countOrders = totalOrders.Split('\n');
string[] parts1 = countOrders.Split(new string[] { " - " }, StringSplitOptions.None);
</code>```

I get error at .Split

```<code>'string[]' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'string[]' could be found
</code>```

and if I try this "string countOrders =" (so without []) I get

```<code>Cannot implicitly convert type 'string[]' to 'string'
</code>```

I don't understand how am I suppose to split the string by '\n' and then to split it by " - ", when it gives me errors in both cases?

答:
You have two questions.

Question 1:

How to split by multiple characters is answered here: https://stackoverflow.com/a/1254596/2654498. Code below is directly from there.

```<code>string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" },StringSplitOptions.None);
</code>```

Question 2:

You will need to check the dictionary to see if the Food already exists as a key. If it does, then you need to simply update the value of that food. If it doesn't exist as a key, add it as a new item to your dictionary.

```<code>if (!foodDict.ContainsKey(food))
{
     foodDict.Add(food, qty);
}
else
{
     foodDict[food] += qty;
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a string like this:

var totalOrders = "Beans - 1\nMeat balls - 1\nBrown bread - 2\nBeans - 2\nBanana slice - 1\nSteak with rice - 1\nBrown bread - 1\n";

It's dynamically created, so this one is just for the sake of example. Numbers represent how many portions are ordered. I need to split it to dictionary by the name of food as a key and count how many portions are ordered which would be a value.

I've tried this for spliting the string, first by '\n' then by ' - ':

count = totalOrders.Split('\n').ToDictionary(item => item.Split(" - ")[0], item => int.Parse(item.Split(" - ")[1]));

but I get an error "cannot convert from string to char. I had to use double quotes, because " - " this has 3 chars (2 spaces and a dash) and it's not recognized as a char.

Also, I think the problem will be when I start adding food, because it will report that keys won't be unique, considering that food appears more than once. How to solve this?

EDIT:

When I try this:

string[] countOrders = totalOrders.Split('\n');
string[] parts1 = countOrders.Split(new string[] { " - " }, StringSplitOptions.None);

I get error at .Split

'string[]' does not contain a definition for 'Split' and no extension method 'Split' accepting a first argument of type 'string[]' could be found

and if I try this "string countOrders =" (so without []) I get

Cannot implicitly convert type 'string[]' to 'string'

I don't understand how am I suppose to split the string by '\n' and then to split it by " - ", when it gives me errors in both cases?

Body:
You have two questions.

Question 1:

How to split by multiple characters is answered here: https://stackoverflow.com/a/1254596/2654498. Code below is directly from there.

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Split(new string[] { "][" },StringSplitOptions.None);

Question 2:

You will need to check the dictionary to see if the Food already exists as a key. If it does, then you need to simply update the value of that food. If it doesn't exist as a key, add it as a new item to your dictionary.

if (!foodDict.ContainsKey(food))
{
     foodDict.Add(food, qty);
}
else
{
     foodDict[food] += qty;
}


问:
Assign CSS To A
 Element
I am wanting to add CSS to a DIV element so I can align it to the right and have a form directly to the left of it. I am working on making a hacked version of 2048. My HTML code is:

```<code>    <div id="completetwentyfourtyeightgame" align="right">
        <div class="container">
            <div class="heading">
                <div class="scores-container">
                    <div class="score-container">0</div>
                    <div class="best-container">0</div>
                </div>
                <div class="above-game">
                    <a class="restart-button">New Game</a>
                </div>
            </div>
            <div class="game-container">
                <div class="game-message">
                    <p></p>
                    <div class="lower">
                        <a class="keep-playing-button">Keep going</a>
                        <a class="retry-button">Try again</a>
                    </div>
                </div>
                <div class="grid-container">
                    <div class="grid-row">
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                    </div>
                    <div class="grid-row">
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                    </div>
                    <div class="grid-row">
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                    </div>
                    <div class="grid-row">
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                        <div class="grid-cell"></div>
                    </div>
                </div>
                <div class="tile-container"></div>
            </div>
        </div>
    </div>

        <div align="left">
        <form id="inputs">
            <table border="1">
                <tr>
                    <th>Tile Value 1</th>
                </tr>
                <tr>
                    <th>
                        <input type="text" id="tilevalueone" value="2">
                    </th>
                </tr>
                <tr>
                    <th>Tile Value 2</th>
                </tr>
                <tr>
                    <th>
                        <input type="text" id="tilevaluetwo" value="4">
                    </th>
                </tr>
                <tr>
                    <th>Starting Score</th>
                </tr>
                <tr>
                    <th>
                        <input type="text" id="score" value="0">
                    </th>
                </tr>
                <tr>
                    <th>Tile Value To Win</th>
                </tr>
                <tr>
                    <th>
                        <input type="text" id="winpoints" value="2048">
                    </th>
                </tr>
            </table>
        </form>
    </div>
</code>```

My css is:

```<code>.completetwentyfourtyeightgame{
position: absolute;
right: 0px;
}
</code>```

What is wrong with the code? Is it in my HTML or in my CSS? Here is a screenshot of what the code is doing:

Instead of the table being directly on the left and the game on the right, the table stays below the game.
After changing the . to a # in the css, this happens

I am not wanting the game to be on the edge if the website and the table to be right next to the left border of the game. Also, is there a way to make javascript reload the game to apply the values without reloading the page itself?

答:
Should be:

#completetwentyfourtyeightgamein your CSS.

You have it as .completetwentyfourtyeightgame

This is because with a . starting it, that is for denoting a new CSS class. To target something with an id - as you have it declared in your HTML - you need to use a #

Title: Assign CSS To A <div> Element

Body:
I am wanting to add CSS to a DIV element so I can align it to the right and have a form directly to the left of it. I am working on making a hacked version of 2048. My HTML code is:

0

0

                    New Game

                        Keep going
                        Try again

        <form id="inputs">

                    Tile Value 1

                        <input type="text" id="tilevalueone" value="2">

                    Tile Value 2

                        <input type="text" id="tilevaluetwo" value="4">

                    Starting Score

                        <input type="text" id="score" value="0">

                    Tile Value To Win

                        <input type="text" id="winpoints" value="2048">

        </form>

My css is:

.completetwentyfourtyeightgame{
position: absolute;
right: 0px;
}

What is wrong with the code? Is it in my HTML or in my CSS? Here is a screenshot of what the code is doing:

Instead of the table being directly on the left and the game on the right, the table stays below the game.
After changing the . to a # in the css, this happens

I am not wanting the game to be on the edge if the website and the table to be right next to the left border of the game. Also, is there a way to make javascript reload the game to apply the values without reloading the page itself?


问:
PHP how to get the last item count in "showing # of # items" on a page
I am making a products page and beside my pagination I want to show the item counts per page.

So something like "Showing 1 - 10 products".

I figured out how to calculate the first item number, but I am stuck with figuring out the last # of items on the page.

So assuming I have 10 items per page and 35 items in total the first page would show "1 - 10" the next page would show "11 - 20"  and  the next "21 - 30" and the last page would show "31 - 35".

```<code><?php
//connect to the database
include_once ('includes/connect_to_mysql.php');
    $category = urldecode ($_GET["cat"]); // get category for the current page from the URL
    $page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
    $limit = 10;
    $startpoint = ($page * $limit) - $limit;
    $statement = "products WHERE active = 1 AND category = '$category'";
?>
<header>
    <div class="paging">
        Page:   <?php
        $sql = "SELECT * FROM products WHERE active = 1 AND category = '$category'";
        $rs_result = mysql_query($sql); //run the query
        $total_records = mysql_num_rows($rs_result);  //count number of records
        $num_rec_per_page = 10; //number of records per page
        $total_pages = ceil($total_records / $num_rec_per_page);

        for ($i=1; $i<=$total_pages; $i++) {
            echo '<a href="categories.php?cat='.urlencode($category).'&page='.$i.'">'.$i.'</a>  |  ';
            };

        $first = ($page * $limit) - $limit +1;
        $last = 'NOT SURE WHAT TO PUT HERE';
?>
    </div>
    <form action="#" >
    <select onchange="javascript:addSort();" name="sortBy" id="sortBy">
        <option value="">Default</option>
        <option value="PriceHiLo">Price (High to Low)</option>
        <option value="PriceLoHi">Price (Low to High)</option>
        <option value="pID">Most Recent</option>
    </select>   Showing <?php echo $first?> - <?php echo $last?> of <?php echo $total_records?> Product(s)
    </form>
</header>
</code>```

Any help with figuring out how to calculate $last in the above code would be appreciated. Thank you.

答:
Without if case</p>

```<code>floor(total / perPageSize) + (total % perPageSize)
</code>```

Body:
I am making a products page and beside my pagination I want to show the item counts per page.

So something like "Showing 1 - 10 products".

I figured out how to calculate the first item number, but I am stuck with figuring out the last # of items on the page.

So assuming I have 10 items per page and 35 items in total the first page would show "1 - 10" the next page would show "11 - 20"  and  the next "21 - 30" and the last page would show "31 - 35".

<?php
//connect to the database
include_once ('includes/connect_to_mysql.php');
    $category = urldecode ($_GET["cat"]); // get category for the current page from the URL
    $page = (int) (!isset($_GET["page"]) ? 1 : $_GET["page"]);
    $limit = 10;
    $startpoint = ($page * $limit) - $limit;
    $statement = "products WHERE active = 1 AND category = '$category'";
?>

        Page:   <?php
        $sql = "SELECT * FROM products WHERE active = 1 AND category = '$category'";
        $rs_result = mysql_query($sql); //run the query
        $total_records = mysql_num_rows($rs_result);  //count number of records
        $num_rec_per_page = 10; //number of records per page
        $total_pages = ceil($total_records / $num_rec_per_page);

        for ($i=1; $i<=$total_pages; $i++) {
            echo ''.$i.'  |  ';
            };

        $first = ($page * $limit) - $limit +1;
        $last = 'NOT SURE WHAT TO PUT HERE';
?>

    <form action="#" >
    <select onchange="javascript:addSort();" name="sortBy" id="sortBy">
        <option value="">Default</option>
        <option value="PriceHiLo">Price (High to Low)</option>
        <option value="PriceLoHi">Price (Low to High)</option>
        <option value="pID">Most Recent</option>
    </select>   Showing <?php echo $first?> - <?php echo $last?> of <?php echo $total_records?> Product(s)
    </form>

Any help with figuring out how to calculate $last in the above code would be appreciated. Thank you.

Body:
Without if case

floor(total / perPageSize) + (total % perPageSize)


问:
Remove items of list from another lists with criteria
i have a list of writers.

```<code>public class Writers{
    long WriterID { get;set; }
}
</code>```

Also I have two lists of type Article.

```<code>public class Article{
    long ArticleID { get; set; }
    long WriterID { get; set; }
    //and others
}
</code>```

so the code i have is:

```<code>List<Article> ArticleList = GetList(1);
List<Article> AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();
</code>```

I want to remove those records from ArticleList, AnotherArticleList where WriterID matches from listWriters WriterID. How to do this in LINQ?

答:
I do not really see what is the difficulty you are facing...

Why don't you just filter/remove data from you lists using a simple for loop ?
(Note that a foreach Loop will definitely NOT work if you iterate while editing/changing the iterated object)

```<code>for (int i = ArticleList.Count -1; i >= 0; i--)
{
    for (int j = 0; j < listWriters.Count; j++)
    {
        if (ArticleList[i].WriterId == listWriters[j].WriterID )
            ArticleList.RemoveAt(i);
    }
}
</code>```

The Backward iteration trick solves the "delete items while iterating" paradigm.

Body:
i have a list of writers.

public class Writers{
    long WriterID { get;set; }
}

Also I have two lists of type Article.

public class Article{
    long ArticleID { get; set; }
    long WriterID { get; set; }
    //and others
}

so the code i have is:

List
 ArticleList = GetList(1);
List
 AnotherArticleList = AnotherList(2);
List<Writers> listWriters = GetAllForbiddenWriters();

I want to remove those records from ArticleList, AnotherArticleList where WriterID matches from listWriters WriterID. How to do this in LINQ?

Body:
I do not really see what is the difficulty you are facing...

Why don't you just filter/remove data from you lists using a simple for loop ?
(Note that a foreach Loop will definitely NOT work if you iterate while editing/changing the iterated object)

for (int i = ArticleList.Count -1; i >= 0; i--)
{
    for (int j = 0; j < listWriters.Count; j++)
    {
        if (ArticleList[i].WriterId == listWriters[j].WriterID )
            ArticleList.RemoveAt(i);
    }
}

The Backward iteration trick solves the "delete items while iterating" paradigm.


问:
How to properly center the text?
I'm trying to center the text in the middle of JQM page, vertically and horizontally. Using 1.4.5, default theme.

In my .css I have:

```<code>.splashDiv {
    position: absolute;
    top: 50%;
    height: 50%;
    width: 100%;
    text-align: center;
    padding:0;
}
</code>```

HTML

```<code><div class="splashDiv" data-role="page">
    Please wait...
</div>
</code>```

The result is:

The text is vertically centered only if I remove top: 0 directive in developer tools(although not perfectly centered).

My question is what is the proper way according to JQM architecture to have what I want? I am not looking for quick/dirty workaround, unless there is no other way.

UPDATE

答:
```<code>.splashDiv {
    position: absolute;
    top: 50%;
    width: 100%;
    text-align: center;
    transform: translateY(-50%);
    padding:0;
}
</code>```

Use this it will align your text vertically center.

Title: How to properly center the text?

Body:
I'm trying to center the text in the middle of JQM page, vertically and horizontally. Using 1.4.5, default theme.

In my .css I have:

.splashDiv {
    position: absolute;
    top: 50%;
    height: 50%;
    width: 100%;
    text-align: center;
    padding:0;
}

HTML

    Please wait...

The result is:

The text is vertically centered only if I remove top: 0 directive in developer tools(although not perfectly centered).

My question is what is the proper way according to JQM architecture to have what I want? I am not looking for quick/dirty workaround, unless there is no other way.

UPDATE

Body:
.splashDiv {
    position: absolute;
    top: 50%;
    width: 100%;
    text-align: center;
    transform: translateY(-50%);
    padding:0;
}

Use this it will align your text vertically center.


问:
Getting the id of the last record inserted into a MySQL database
I'm trying to get the id of the last record inserted into a MySQL database using MAX(id).
I can't figure out why my query is not returning any results. Is there something wrong with my PHP?Tthe query works if I try it inside phpmyadmin.

```<code>include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];
</code>```

答:
use an alias for get  the value </p>

```<code>  $sql = "SELECT MAX(id) as max_id FROM tbl_uploads";
  $result = $db_conx->query($sql);
  $row = $result->fetch_assoc();
  echo 'last_id: '.$row['max_id'];
</code>```

Body:
I'm trying to get the id of the last record inserted into a MySQL database using MAX(id).
I can't figure out why my query is not returning any results. Is there something wrong with my PHP?Tthe query works if I try it inside phpmyadmin.

include("db_conx.php"); //Connect to db mysqli
$sql = "SELECT MAX(id) FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];

Body:
use an alias for get  the value

  $sql = "SELECT MAX(id) as max_id FROM tbl_uploads";
  $result = $db_conx->query($sql);
  $row = $result->fetch_assoc();
  echo 'last_id: '.$row['max_id'];


问:
configure pip to get missing package from pypi.python.org
I have local pypi server.

and I set it configuration in

```<code>root@localhost$ cat .pip/pip.conf
[global]
index-url = http://localhost/simple
trusted-host=localhost
</code>```

My pypi server has paste=2.0.2 but one of the app need paste=2.0.3. when I check in https://pypi.python.org/simple/paste/ it has this version.

When I run pip install -r requirements.txt it gives below error.

```<code>Collecting paste==2.0.3 (from -r requirements.txt (line 22))
  1 location(s) to search for versions of paste:
  * http://localhost/simple/paste/
  Getting page http://localhost/simple/paste/
  Resetting dropped connection: localhost
  "GET /simple/paste/ HTTP/1.1" 200 309
  Analyzing links from page http://localhost/simple/paste/
    Found link http://localhost/packages/Paste-2.0.2-py2-none-any.whl#md5=42d3df8ad533457607903a0ca0922825 (from http://localhost/simple/paste/), version: 2.0.2
  Could not find a version that satisfies the requirement paste==2.0.3 (from -r requirements.txt (line 22)) (from versions: 2.0.2)
Cleaning up...
No matching distribution found for paste==2.0.3 (from -r requirements.txt (line 22))
Exception information:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 276, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/local/lib/python2.7/dist-packages/pip/index.py", line 514, in find_requirement
    'No matching distribution found for %s' % req
DistributionNotFound: No matching distribution found for paste==2.0.3 (from -r requirements.txt (line 22))
You are using pip version 9.0.0, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.
</code>```

How can I configure pip.conf, so when specific package with number is not available on local pypi, it will search for pypi.python.org?

答:
You need to set

```<code>[global]
extra-index-url =  https://pypi.python.org
</code>```

in your ~/.pip/pip.conf file per the documentation

Furthermore, you can start you pypi server with the following argument

```<code>  --fallback-url FALLBACK_URL
    for packages not found in the local index, this URL will be used to
    redirect to (default: http://pypi.python.org/simple)
</code>```

Body:
I have local pypi server.

and I set it configuration in

root@localhost$ cat .pip/pip.conf
[global]
index-url = http://localhost/simple
trusted-host=localhost

My pypi server has paste=2.0.2 but one of the app need paste=2.0.3. when I check in https://pypi.python.org/simple/paste/ it has this version.

When I run pip install -r requirements.txt it gives below error.

Collecting paste==2.0.3 (from -r requirements.txt (line 22))
  1 location(s) to search for versions of paste:
  * http://localhost/simple/paste/
  Getting page http://localhost/simple/paste/
  Resetting dropped connection: localhost
  "GET /simple/paste/ HTTP/1.1" 200 309
  Analyzing links from page http://localhost/simple/paste/
    Found link http://localhost/packages/Paste-2.0.2-py2-none-any.whl#md5=42d3df8ad533457607903a0ca0922825 (from http://localhost/simple/paste/), version: 2.0.2
  Could not find a version that satisfies the requirement paste==2.0.3 (from -r requirements.txt (line 22)) (from versions: 2.0.2)
Cleaning up...
No matching distribution found for paste==2.0.3 (from -r requirements.txt (line 22))
Exception information:
Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/pip/basecommand.py", line 215, in main
    status = self.run(options, args)
  File "/usr/local/lib/python2.7/dist-packages/pip/commands/install.py", line 335, in run
    wb.build(autobuilding=True)
  File "/usr/local/lib/python2.7/dist-packages/pip/wheel.py", line 749, in build
    self.requirement_set.prepare_files(self.finder)
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 380, in prepare_files
    ignore_dependencies=self.ignore_dependencies))
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_set.py", line 554, in _prepare_file
    require_hashes
  File "/usr/local/lib/python2.7/dist-packages/pip/req/req_install.py", line 276, in populate_link
    self.link = finder.find_requirement(self, upgrade)
  File "/usr/local/lib/python2.7/dist-packages/pip/index.py", line 514, in find_requirement
    'No matching distribution found for %s' % req
DistributionNotFound: No matching distribution found for paste==2.0.3 (from -r requirements.txt (line 22))
You are using pip version 9.0.0, however version 9.0.1 is available.
You should consider upgrading via the 'pip install --upgrade pip' command.

How can I configure pip.conf, so when specific package with number is not available on local pypi, it will search for pypi.python.org?

Body:
You need to set

[global]
extra-index-url =  https://pypi.python.org

in your ~/.pip/pip.conf file per the documentation

Furthermore, you can start you pypi server with the following argument

  --fallback-url FALLBACK_URL
    for packages not found in the local index, this URL will be used to
    redirect to (default: http://pypi.python.org/simple)


问:
Gradle build is successful, but won't sync
I'm trying to run an old project of mine, so I imported it into Android Studio ( It used this when I originally created it ) and updated the libraries ( It wouldn't run before either )

The problem is, even though the build succeeds ( with only a warning ), I get Gradle project sync failed. and can't run it.

I'm currently running the latest alpha of gradle (2.4.0-alpha3), have tried older versions to see if that was the issue, and also tried to change the dependencies, the version, and the buildtools. I have other working projects from the same SdkVersion, so it's probably not that.

```<code>apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '26-rc1'

    defaultConfig {
        applicationId "com.jediburrell.sof"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 7
        versionName "1.6"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile('com.github.afollestad.material-dialogs:core:0.8.5.4@aar') {
        transitive = true
    }
    compile files('libs/activation.jar')
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.android.support:design:+'
    compile 'com.android.support:cardview-v7:+'
    compile 'com.balysv:material-ripple:1.0.2'
    compile 'com.melnykov:floatingactionbutton:1.3.0'
    compile 'com.squareup.okhttp:okhttp:2.3.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.3.0'
    compile 'org.apache.httpcomponents:httpclient:+'

}
</code>```

As for the warning:

```<code>Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies]
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.3 is ignored for debug as it may be conflicting with the internal version provided by Android.
Information:BUILD SUCCESSFUL
Information:Total time: 1.27 secs
Information:0 errors
Information:1 warning
Information:See complete output in console
</code>```

I have tried to build it without HttpClient. It builds the same

答:
Two Suggestions:

Have you tried the old "Invalidate Caches/Restart IDE" Method? Or Clean Project and Rebuild? Those are my gotos for anomalous build conflicts.

Try replacing the '+' in compile 'org.apache.httpcomponents:httpclient:+' with a static version of the library. Dynamic versioning on your dependencies can cause some serious undefined behavior in your builds, and can even prevent you from building/syncing your project. Here (fairly old, but relevant) is a blog post on the matter.

Body:
I'm trying to run an old project of mine, so I imported it into Android Studio ( It used this when I originally created it ) and updated the libraries ( It wouldn't run before either )

The problem is, even though the build succeeds ( with only a warning ), I get Gradle project sync failed. and can't run it.

I'm currently running the latest alpha of gradle (2.4.0-alpha3), have tried older versions to see if that was the issue, and also tried to change the dependencies, the version, and the buildtools. I have other working projects from the same SdkVersion, so it's probably not that.

apply plugin: 'com.android.application'

android {
    compileSdkVersion 25
    buildToolsVersion '26-rc1'

    defaultConfig {
        applicationId "com.jediburrell.sof"
        minSdkVersion 15
        targetSdkVersion 26
        versionCode 7
        versionName "1.6"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    testCompile 'junit:junit:4.12'
    compile('com.github.afollestad.material-dialogs:core:0.8.5.4@aar') {
        transitive = true
    }
    compile files('libs/activation.jar')
    compile 'com.android.support:appcompat-v7:+'
    compile 'com.android.support:design:+'
    compile 'com.android.support:cardview-v7:+'
    compile 'com.balysv:material-ripple:1.0.2'
    compile 'com.melnykov:floatingactionbutton:1.3.0'
    compile 'com.squareup.okhttp:okhttp:2.3.0'
    compile 'com.squareup.okhttp:okhttp-urlconnection:2.3.0'
    compile 'org.apache.httpcomponents:httpclient:+'

}

As for the warning:

Information:Gradle tasks [:app:generateDebugSources, :app:generateDebugAndroidTestSources, :app:mockableAndroidJar, :app:prepareDebugUnitTestDependencies]
Warning:WARNING: Dependency org.apache.httpcomponents:httpclient:4.5.3 is ignored for debug as it may be conflicting with the internal version provided by Android.
Information:BUILD SUCCESSFUL
Information:Total time: 1.27 secs
Information:0 errors
Information:1 warning
Information:See complete output in console

I have tried to build it without HttpClient. It builds the same


问:
Show fragment with dynamic custom animation
I am new to Android and having difficulty displaying a fragment with animation dynamically.

So far I animate fragment using XML files like below, which is working fine.

```<code>FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
transaction.add(R.id.task_fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();
</code>```

Problem is in XML files, I have to hard coded fromXDelta and toXDelta values etc, but I want these values to be dynamic wherever user clicks on screen. I guess, I may not be able to do this using XML files. Is there any other way?

I tried experimenting with AnimationSet like this:

```<code>final AnimationSet animEnter = new AnimationSet( true );
Animation trans = new TranslateAnimation( 0, 0, 500, 0);
trans.setDuration( 140 );
animEnter.addAnimation( trans );
</code>```

but I don't know how to use AnimationSet with FragmentTransaction.

Any help is appreciated.

答: For dynamic animation you can set setCustomAnimations(0,0) for setting no animation by system and then from next fragment you can set transition object setEnterTransition() in onCreate method of fragment.</p>

Body:
I am new to Android and having difficulty displaying a fragment with animation dynamically.

So far I animate fragment using XML files like below, which is working fine.

FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.setCustomAnimations(R.anim.enter, R.anim.exit, R.anim.pop_enter, R.anim.pop_exit);
transaction.add(R.id.task_fragment_container, fragment);
transaction.addToBackStack(null);
transaction.commit();

Problem is in XML files, I have to hard coded fromXDelta and toXDelta values etc, but I want these values to be dynamic wherever user clicks on screen. I guess, I may not be able to do this using XML files. Is there any other way?

I tried experimenting with AnimationSet like this:

final AnimationSet animEnter = new AnimationSet( true );
Animation trans = new TranslateAnimation( 0, 0, 500, 0);
trans.setDuration( 140 );
animEnter.addAnimation( trans );

but I don't know how to use AnimationSet with FragmentTransaction.

Any help is appreciated.


问:
Is there a way I can write my PHP code for WordPress a bit more optimized? Right now I feel like there could be a better way
So I am writing a template file for WordPress and I feel like I am using too many echo tabs. Just wanted to see if there is something that is better and easier that I am not doing right now. </p>

```<code><h1>Responsive grid layout</h1>
      <dl class="gridtab-1">

        <?php
            $args = array( 'post_type' => 'product', 'posts_per_page' => 5 );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();
              echo '<dt>', the_post_thumbnail('medium'), '</dt>';
              echo '<dd class="entry-content">';

              echo '<div class="bdanzer-container">',
                        '<div class="bdanzer-left">';

                            echo '<p>', the_post_thumbnail('large'), '</p>';

                        echo '</div>';

                echo '<div class="bdanzer-right">';
                    echo '<h1>', the_title() , '</h1>';
                    echo '<p>',the_content(),'</p>';
                echo '</div>';

                echo '<p>', the_category(), '</p>';

              echo '</div>';
              echo '</dd>';

            endwhile;
        ?>

        </dl>
</code>```

答: Use separate class for code and template for view.</p>

Body:
So I am writing a template file for WordPress and I feel like I am using too many echo tabs. Just wanted to see if there is something that is better and easier that I am not doing right now.

Responsive grid layout

        <?php
            $args = array( 'post_type' => 'product', 'posts_per_page' => 5 );
            $loop = new WP_Query( $args );
            while ( $loop->have_posts() ) : $loop->the_post();
              echo '
', the_post_thumbnail('medium'), '
';
              echo '
';

              echo '
',
                        '
';

                            echo '
', the_post_thumbnail('large'), '
';

                        echo '
';

                echo '
';
                    echo '
', the_title() , '
';
                    echo '
',the_content(),'
';
                echo '
';

                echo '
', the_category(), '
';

              echo '
';
              echo '
';

            endwhile;
        ?>


问:
Modifying value before get call
I have a property that is dependent on some other properties, code looks like this:

```<code>        get
        {
            if (this.FuelType == "Benzin")
            {
                if (this.KmPrL >= 18)
                {
                    return 'A';
                }
                else if (this.KmPrL < 18 && this.KmPrL >= 14)
                {
                    return 'B';
                }
                else if (this.KmPrL < 14 && this.KmPrL >= 10)
                {
                    return 'C';
                }
                else
                {
                    return 'D';
                }
            }
        }
</code>```

Now I have another class that overrides this get, and I would like it to use this get call, but with the KmPrL value multiplied by 0.7, but without actually modifying the property KmPrL permanently.
How would I go about doing that?

答:
I would do some refactoring to accomplish this, refactor your usage of this.KmPrL to a virtual method like this:

```<code>protected virtual GetKmPrL() //Or a more descriptive name
{
   return KmPrL
}

...
if (this.FuelType == "Benzin")
        {
            if (GetKmPrL() >= 18)
            {
</code>```

Then your derived class can override it:

```<code>protected override GetKmPrL()
{
   return KmPrL * .7
}
</code>```

Overall your getter property looks a little complicated to start with but by allowing derived classes to override the calculation of your dependent property, you'll get the behavior you are looking for.

Title: Modifying value before get call

Body:
I have a property that is dependent on some other properties, code looks like this:

        get
        {
            if (this.FuelType == "Benzin")
            {
                if (this.KmPrL >= 18)
                {
                    return 'A';
                }
                else if (this.KmPrL < 18 && this.KmPrL >= 14)
                {
                    return 'B';
                }
                else if (this.KmPrL < 14 && this.KmPrL >= 10)
                {
                    return 'C';
                }
                else
                {
                    return 'D';
                }
            }
        }

Now I have another class that overrides this get, and I would like it to use this get call, but with the KmPrL value multiplied by 0.7, but without actually modifying the property KmPrL permanently.
How would I go about doing that?

Body:
I would do some refactoring to accomplish this, refactor your usage of this.KmPrL to a virtual method like this:

protected virtual GetKmPrL() //Or a more descriptive name
{
   return KmPrL
}

...
if (this.FuelType == "Benzin")
        {
            if (GetKmPrL() >= 18)
            {

Then your derived class can override it:

protected override GetKmPrL()
{
   return KmPrL * .7
}

Overall your getter property looks a little complicated to start with but by allowing derived classes to override the calculation of your dependent property, you'll get the behavior you are looking for.


问:
Facebook messenger chat item animation on click
I'm trying to make my list item to be animated after onClick(),Like Facebook messenger. I tried to do this with animateLayoutChanges=true in my list item layout and also my recyclerView's parent layout, but it is not smooth and have some problem, after first click when I want to show hidden fields (setVisibility(VISIBLE)) , it works not bad, but setVisibility(GONE) works not properly, this is what it looks like

And what I'm trying to achieve is this

Any advice how to do that?
this is My custom view

```<code>class MessageItemView : RelativeLayout {

  constructor(context: Context) : super(context)
  constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)

  private var messageTextView: TextView
  private var dateTextView: TextView
  private var itemView: View? = null
  init {
      itemView =  LayoutInflater.from(context)?.inflate(R.layout.live_chat_list_item, this)
      messageTextView = itemView?.findViewById(R.id.live_chat_msg_text_id) as TextView
      dateTextView = itemView?.findViewById(R.id.message_received_date_txt_id) as TextView
  }

 fun setUPViewModelData(message: MessageModel) {
     itemView?.setOnClickListener {
         dateTextView.visibility = if (dateTextView.visibility == View.VISIBLE) View.GONE else View.VISIBLE
         delivered_status_txt_id.visibility = dateTextView.visibility
  }
}
</code>```

And this is xml of this view

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:animateLayoutChanges="true"
    android:orientation="vertical">

<TextView
    android:id="@+id/message_received_date_txt_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:visibility="gone" />

<LinearLayout
    android:id="@+id/message_wrapper_layout_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/message_received_date_txt_id"
    android:orientation="vertical">

    <TextView
        android:id="@+id/live_chat_msg_text_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

<TextView
    android:id="@+id/delivered_status_txt_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/message_wrapper_layout_id"
    android:visibility="gone" />

</RelativeLayout>
</code>```

I don't understand what's wrong in my layout hierarchy or what would be good architecture and also interested in Fb's messenger chat item layout hierarchy... Any eideas?

答:
Remove the animateLayoutChanges from your layout and then use the TransitionManager from the support library:</p>

```<code>fun setUPViewModelData(message: MessageModel) {
     itemView?.setOnClickListener {
         TransitionManager.beginDelayedTransition(recyclerView)
         dateTextView.visibility = if (dateTextView.visibility == View.VISIBLE) View.GONE else View.VISIBLE
         delivered_status_txt_id.visibility = dateTextView.visibility
    }
}
</code>```

Body:
I'm trying to make my list item to be animated after onClick(),Like Facebook messenger. I tried to do this with animateLayoutChanges=true in my list item layout and also my recyclerView's parent layout, but it is not smooth and have some problem, after first click when I want to show hidden fields (setVisibility(VISIBLE)) , it works not bad, but setVisibility(GONE) works not properly, this is what it looks like

And what I'm trying to achieve is this

Any advice how to do that?
this is My custom view

class MessageItemView : RelativeLayout {

  constructor(context: Context) : super(context)
  constructor(context: Context, attributeSet: AttributeSet) : super(context, attributeSet)

  private var messageTextView: TextView
  private var dateTextView: TextView
  private var itemView: View? = null
  init {
      itemView =  LayoutInflater.from(context)?.inflate(R.layout.live_chat_list_item, this)
      messageTextView = itemView?.findViewById(R.id.live_chat_msg_text_id) as TextView
      dateTextView = itemView?.findViewById(R.id.message_received_date_txt_id) as TextView
  }

 fun setUPViewModelData(message: MessageModel) {
     itemView?.setOnClickListener {
         dateTextView.visibility = if (dateTextView.visibility == View.VISIBLE) View.GONE else View.VISIBLE
         delivered_status_txt_id.visibility = dateTextView.visibility
  }
}

And this is xml of this view

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:animateLayoutChanges="true"
    android:orientation="vertical">

<TextView
    android:id="@+id/message_received_date_txt_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_centerHorizontal="true"
    android:visibility="gone" />

<LinearLayout
    android:id="@+id/message_wrapper_layout_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/message_received_date_txt_id"
    android:orientation="vertical">

    <TextView
        android:id="@+id/live_chat_msg_text_id"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"/>

</LinearLayout>

<TextView
    android:id="@+id/delivered_status_txt_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/message_wrapper_layout_id"
    android:visibility="gone" />

</RelativeLayout>

I don't understand what's wrong in my layout hierarchy or what would be good architecture and also interested in Fb's messenger chat item layout hierarchy... Any eideas?

Body:
Remove the animateLayoutChanges from your layout and then use the TransitionManager from the support library:

fun setUPViewModelData(message: MessageModel) {
     itemView?.setOnClickListener {
         TransitionManager.beginDelayedTransition(recyclerView)
         dateTextView.visibility = if (dateTextView.visibility == View.VISIBLE) View.GONE else View.VISIBLE
         delivered_status_txt_id.visibility = dateTextView.visibility
    }
}


问:
C# Sql Command for Insering into a database
I am new to Visual C# programming language and recently i was trying to make a application that is supposed to insert into a local database of users some data but every times my code runs and the insertion works fine the database does not update.This is the code that i am using

```<code>try
{
    cn.Open();
    SqlCommand insert = new SqlCommand();
    insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
    insert.Connection = cn;
    insert.Parameters.AddWithValue("@Nume", register_nume.Text);
    insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
    insert.Parameters.AddWithValue("@Parola", register_password.Text);
    insert.Parameters.AddWithValue("@Email", register_email.Text);
    insert.ExecuteNonQuery();
    SqlDataReader reader = insert.ExecuteReader();
    while (reader.Read()) { }

    MessageBox.Show("Added succesfully");
}
catch (Exception ex)
{
    MessageBox.Show(""+ex);
}
</code>```

I already tried the property Copy to output and it doesn't seems to work.
I am sorry for any grammar mistakes that i made,I would be grateful for any help.

答:
This part of your code is preparing the SQL command that you are running

```<code>cn.Open();
SqlCommand insert = new SqlCommand();
insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
insert.Connection = cn;
insert.Parameters.AddWithValue("@Nume", register_nume.Text);
insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
insert.Parameters.AddWithValue("@Parola", register_password.Text);
insert.Parameters.AddWithValue("@Email", register_email.Text);
</code>```

The SQL command that your code is running, is an INSERT statement, which only adds a new record to your table.

This statement runs the command that you setup earlier:

```<code>insert.ExecuteNonQuery();
</code>```

If I understand correctly, here you are trying to read the data from the table again:

```<code>SqlDataReader reader = insert.ExecuteReader();
while (reader.Read()) { }
</code>```

Problem is, your command is NOT set for reading. To read data, you need to use a SELECT statement. Something like this:

```<code>insert.CommandText = "SELECT Nume,Prenume,Parola,Email from Clienti" ;
</code>```

So, to read the data after executing the insert, you should do this:

```<code>insert.CommandText = "SELECT Nume,Prenume,Parola,Email from Clienti" ;
SqlDataReader reader = insert.ExecuteReader();
while (reader.Read()) { }
</code>```

Body:
I am new to Visual C# programming language and recently i was trying to make a application that is supposed to insert into a local database of users some data but every times my code runs and the insertion works fine the database does not update.This is the code that i am using

try
{
    cn.Open();
    SqlCommand insert = new SqlCommand();
    insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
    insert.Connection = cn;
    insert.Parameters.AddWithValue("@Nume", register_nume.Text);
    insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
    insert.Parameters.AddWithValue("@Parola", register_password.Text);
    insert.Parameters.AddWithValue("@Email", register_email.Text);
    insert.ExecuteNonQuery();
    SqlDataReader reader = insert.ExecuteReader();
    while (reader.Read()) { }

    MessageBox.Show("Added succesfully");
}
catch (Exception ex)
{
    MessageBox.Show(""+ex);
}

I already tried the property Copy to output and it doesn't seems to work.
I am sorry for any grammar mistakes that i made,I would be grateful for any help.

Body:
This part of your code is preparing the SQL command that you are running

cn.Open();
SqlCommand insert = new SqlCommand();
insert.CommandText = "insert into Clienti (Nume,Prenume,Parola,Email) values(@Nume,@Prenume,@Parola,@Email)";
insert.Connection = cn;
insert.Parameters.AddWithValue("@Nume", register_nume.Text);
insert.Parameters.AddWithValue("@Prenume", register_prenume.Text);
insert.Parameters.AddWithValue("@Parola", register_password.Text);
insert.Parameters.AddWithValue("@Email", register_email.Text);

The SQL command that your code is running, is an INSERT statement, which only adds a new record to your table.

This statement runs the command that you setup earlier:

insert.ExecuteNonQuery();

If I understand correctly, here you are trying to read the data from the table again:

SqlDataReader reader = insert.ExecuteReader();
while (reader.Read()) { }

Problem is, your command is NOT set for reading. To read data, you need to use a SELECT statement. Something like this:

insert.CommandText = "SELECT Nume,Prenume,Parola,Email from Clienti" ;

So, to read the data after executing the insert, you should do this:

insert.CommandText = "SELECT Nume,Prenume,Parola,Email from Clienti" ;
SqlDataReader reader = insert.ExecuteReader();
while (reader.Read()) { }


问:
How to compare strings in an "if" statement?
I want to test and see if a variable of type "char" can compare with a regular string like "cheese" for a comparison like:

```<code>#include <stdio.h>

int main()
{
    char favoriteDairyProduct[30];

    scanf("%s",favoriteDairyProduct);

    if(favoriteDairyProduct == "cheese")
    {
        printf("You like cheese too!");
    }
    else
    {
        printf("I like cheese more.");
    }

    return 0;
}
</code>```

(What I actually want to do is much longer than this but this is the main part I'm stuck on.)
So how would one compare two strings in C?

答:
```<code>if(!strcmp(favoriteDairyProduct, "cheese"))
{
    printf("You like cheese too!");
}
else
{
    printf("I like cheese more.");
}
</code>```

Body:
I want to test and see if a variable of type "char" can compare with a regular string like "cheese" for a comparison like:

#include <stdio.h>

int main()
{
    char favoriteDairyProduct[30];

    scanf("%s",favoriteDairyProduct);

    if(favoriteDairyProduct == "cheese")
    {
        printf("You like cheese too!");
    }
    else
    {
        printf("I like cheese more.");
    }

    return 0;
}

(What I actually want to do is much longer than this but this is the main part I'm stuck on.)
So how would one compare two strings in C?


问:
Progress Bar findviewbyid returns null
Help me please it's getting frustrating!

i'm doing a chat application where i'm adding views to a linear layout programmatically each time a user press the send button the code is below:

```<code>public  void appendToMessageHistory(String id,String uname, String messa,String messageType, final String filepath, String DownloadStatus,boolean internet,int type) {

    //TextView tv=new TextView(Messaging.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Width, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 10, 0, 0);

    View v = getLayoutInflater().inflate(R.layout.message_entity, null);

    TextView mess;
    TextView time;
    final ImageView iv;
    final ProgressBar progressBar;
    ImageView statusiv;
    if (friend.userName.equals(uname)) {
        v = getLayoutInflater().inflate(R.layout.message_entity, null);
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_message);
        time = (TextView) v.findViewById(R.id.message_entity_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_imageview);
        statusiv = (ImageView) v.findViewById(R.id.imageView);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_progressbar);
    } else {
        v = getLayoutInflater().inflate(R.layout.message_entity_right, null);
        lp.gravity = Gravity.RIGHT;
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_right_message);
        time = (TextView) v.findViewById(R.id.message_entity_right_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
        statusiv = (ImageView)v.findViewById(R.id.imageViewleft);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
    }

    try {
        progressBar.setId(Integer.parseInt(id));

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (messageType != null) {
        if (messageType.equals(MessageInfo.MESSAGE_TYPE_PIC)) {
            iv.setImageBitmap(ImageHandlet.GetBitmapFromPath(filepath));
            progressBar.setVisibility(View.GONE);
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + filepath), "image/png");
                    startActivity(intent);
                    Log.d("FIlePAth", filepath);
                }
            });

        } else if (messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO)) {
            if (DownloadStatus.equals(LocalStorageHandler.DOWNLOADED)) {
                if(!(friend.userName.equals(uname))) {
                    if (type != 3) {
                        Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                        iv.setImageBitmap(bitTh);
                        progressBar.setVisibility(View.GONE);
                        iv.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                                intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                                startActivity(intent);

                            }
                        });
                    } else {
                        Log.w("Zipping","Progress Bar");
                        progressBar.setVisibility(View.VISIBLE);
                    }
                } else {
                    Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                    iv.setImageBitmap(bitTh);
                    progressBar.setVisibility(View.GONE);
                    iv.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                            intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                            startActivity(intent);

                        }
                    });
                }
            } else if (DownloadStatus.equals(LocalStorageHandler.NotDOWNLOADED)) {
                iv.setTag(id);
                iv.setImageResource(R.drawable.download);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        progressBar.setVisibility(View.VISIBLE);
                        Cursor c = localstoragehandler.getIDnfo(iv.getTag().toString());
                        String filepath = "";
                        //Toast.makeText(getApplication(),iv.getTag().toString()+" iD " +iv.getId(),Toast.LENGTH_SHORT).show();

                        while (c.moveToNext()) {
                            String msg0 = c.getString(0);
                            String msg2 = c.getString(2);
                            String msg3 = c.getString(3);
                            String msg4 = c.getString(4);
                            String msg5 = c.getString(5);
                            String msg6 = c.getString(6);

                            filepath = msg5;

                            Log.d("-----------Vedio-----", "------------------");
                            Log.d("DATABASE---------", msg0);
                            Log.d("DATABASE-------", msg2);
                            Log.d("DATABASE---------", msg3);
                            Log.d("DATABASE-----", msg4 + "");
                            Log.d("DATABASE-------", msg5 + "");
                            Log.d("DATABASE----------", msg6 + "");
                            Log.d("--------END-------", "-------END-----------");

                        }

                        Toast.makeText(getApplicationContext(), filepath.toString() + iv.getTag().toString(), Toast.LENGTH_SHORT).show();

                        DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(filepath, iv.getTag().toString());
                        downloadFileFromURL.execute("");
                    }
                });
            }
        } else {
            iv.setVisibility(View.GONE);
            progressBar.setVisibility(View.GONE);
        }
    }
    if(!(messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO))) {
        if (!internet) {
            statusiv.setImageResource(R.drawable.noconnectionl);
        }
    }
    mess.setText(messa);
    //time.setText(sendt);
    v.setLayoutParams(lp);
    final View lastview = v;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mEssageBox.addView(lastview);

        }
    });
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(View.FOCUS_DOWN);
            messageText.requestFocus();
        }
    });
}
</code>```

and here is the XML of the dialogbox:

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layoutDirection="ltr">

<ImageView
    android:id="@+id/imageViewleft"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/chaticion" />

<RelativeLayout
    android:id="@+id/tests"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#83e3ed"
    android:layoutDirection="rtl"
    android:padding="5dp"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/imageViewleft"
    android:layout_toStartOf="@+id/imageViewleft">

    <TextView
        android:id="@+id/message_entity_right_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="19dp"
        android:layout_marginRight="19dp"
        android:text="Large ffText"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/message_entity_right_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/message_entity_right_message"
        android:paddingRight="10dp"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/message_entity_right_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"

        android:src="@drawable/ic_launcher" />

    <ProgressBar
        android:id="@+id/message_entity_Right_progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"

        android:indeterminate="false"
        android:visibility="invisible" />

</RelativeLayout>
</code>```

And here is the code to send the video message:

```<code>final String message = messageText.getText().toString();
    final Long rowid = localstoragehandler.insert(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED); //insert data into db and get to chat_id
    appendToMessageHistory(rowid + "", imService.getUsername(), message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED, internet,3);// append the video with type 3 to just display the progress
    messageText.setText("Video");
    String newstr = null;
    // intialize the asynctask to upload the video
    class UploadVideo extends AsyncTask<Void, Void, String> {
        ProgressDialog uploading;
        View V;
        UploadVideo(View v){
            V = v;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //          uploading = ProgressDialog.show(Messaging.this, "Uploading File", "Please wait...", false, false);
        }

        @Override
        protected String doInBackground(Void... params) {
            return imService.sendVideoMessage(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, "", ZippedVideoPath);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
         //   RelativeLayout v = (RelativeLayout) V.findViewById(rowid.intValue());
        //    Log.w("Zipping",v.toString());
     //       ProgressBar progressBar1 = (ProgressBar) V.findViewById(R.id.message_entity_Right_progressbar);
      //      Log.w("Zipping",progressBar1.toString());
            //          ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
       //     progressBar1.setVisibility(View.GONE);
        //  Log.d("POST Execute", s + "");

            //textViewResponse.setText(Html.fromHtml("<b>Uploaded at <a href='" + s + "'>" + s + "</a></b>"));
            //textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());
    // here i am preparing the path so when the compress is done to save into.
        }
    }
    if (null != absolute && absolute.length() > 0) {
        int endIndex = absolute.lastIndexOf("/");
        if (endIndex != -1) {
            newstr = absolute.substring(endIndex, absolute.length()); // not forgot to put check if(endIndex != -1)
        }
    }
    Log.w("Zipping", newstr);
    final File videosdir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/videos/");
    if (!videosdir.exists()) {
        videosdir.mkdirs();
    }
    ZippedVideoPath = videosdir.getAbsolutePath() + "/" + newstr;
    Log.w("Zipping", ZippedVideoPath);
    // here i got the ffmpeg library from the net to compress the video and i'm preparing the commands
    String[] complexCommand = {"-y", "-i", absolute, "-strict", "experimental", "-r", "25", "-vcodec", "mpeg4", "-b:a", "150k", "-ab", "48000", "-ac", "2", "-ar", "22050", ZippedVideoPath};
    FFmpeg ffmpeg = FFmpeg.getInstance(getBaseContext());
    try {
        // to execute "ffmpeg -version" command you just need to pass "-version"
        ffmpeg.execute(complexCommand, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
                Log.w("Zipping", "started");
            }

            @Override
            public void onProgress(String message) {
            }

            @Override
            public void onFailure(String message) {
                Log.w("Zipping", message);
            }

            @Override
            public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue());
                Log.w("VideoView",v.toString());
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        Log.w("Zipping", e.toString());
    }
}
</code>```

okay now to the problem when i call the findviewbyid for the progress bar in sendvideomessage ffmpeg onsuccess callback it returns null even though the findviewbyid for the the imageview which is in the same layout it returns the view! so please tell me what is the problem

```<code>public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue()); ;
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar); // this keeps returning null!
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview); // returns the view
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }
</code>```

Thank you!

答:
You're trying to find the view as a child to "v" which seems to be a sibling to the progress bar, not a parent.

Edit: But tbh it's a bit hard to follow the code since you seem to reuse the rowid as the view id. Is this even what you intended?
When adding views programmatically they don't get any id so you'd have a hard time finding views with the rowid as an id. I guess you could use tags and iterate through views to find a tag, but this is a horribly inefficient solution.

(Try finding the view using the view root, or at least one that is actually a parent to the view you're looking for.
Also, don't do this multiple times, save your views as members.)

And furthermore, don't add views dynamically in a linearlayout that grows indefinitely. You will eventually run out of memory. Use a recyclerview and a n adapter to have views created, reused and destroyed as needed while you scroll.

Title: Progress Bar findviewbyid returns null

Body:
Help me please it's getting frustrating!

i'm doing a chat application where i'm adding views to a linear layout programmatically each time a user press the send button the code is below:

public  void appendToMessageHistory(String id,String uname, String messa,String messageType, final String filepath, String DownloadStatus,boolean internet,int type) {

    //TextView tv=new TextView(Messaging.this);
    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(Width, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(0, 10, 0, 0);

    View v = getLayoutInflater().inflate(R.layout.message_entity, null);

    TextView mess;
    TextView time;
    final ImageView iv;
    final ProgressBar progressBar;
    ImageView statusiv;
    if (friend.userName.equals(uname)) {
        v = getLayoutInflater().inflate(R.layout.message_entity, null);
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_message);
        time = (TextView) v.findViewById(R.id.message_entity_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_imageview);
        statusiv = (ImageView) v.findViewById(R.id.imageView);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_progressbar);
    } else {
        v = getLayoutInflater().inflate(R.layout.message_entity_right, null);
        lp.gravity = Gravity.RIGHT;
        v.setId(Integer.parseInt(id));
        mess = (TextView) v.findViewById(R.id.message_entity_right_message);
        time = (TextView) v.findViewById(R.id.message_entity_right_time);
        iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
        statusiv = (ImageView)v.findViewById(R.id.imageViewleft);
        progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
    }

    try {
        progressBar.setId(Integer.parseInt(id));

    } catch (Exception e) {
        e.printStackTrace();
    }

    if (messageType != null) {
        if (messageType.equals(MessageInfo.MESSAGE_TYPE_PIC)) {
            iv.setImageBitmap(ImageHandlet.GetBitmapFromPath(filepath));
            progressBar.setVisibility(View.GONE);
            iv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent();
                    intent.setAction(Intent.ACTION_VIEW);
                    intent.setDataAndType(Uri.parse("file://" + filepath), "image/png");
                    startActivity(intent);
                    Log.d("FIlePAth", filepath);
                }
            });

        } else if (messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO)) {
            if (DownloadStatus.equals(LocalStorageHandler.DOWNLOADED)) {
                if(!(friend.userName.equals(uname))) {
                    if (type != 3) {
                        Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                        iv.setImageBitmap(bitTh);
                        progressBar.setVisibility(View.GONE);
                        iv.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                                intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                                startActivity(intent);

                            }
                        });
                    } else {
                        Log.w("Zipping","Progress Bar");
                        progressBar.setVisibility(View.VISIBLE);
                    }
                } else {
                    Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(filepath, MediaStore.Images.Thumbnails.MINI_KIND);
                    iv.setImageBitmap(bitTh);
                    progressBar.setVisibility(View.GONE);
                    iv.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(filepath));
                            intent.setDataAndType(Uri.parse(filepath), "video/mp4");
                            startActivity(intent);

                        }
                    });
                }
            } else if (DownloadStatus.equals(LocalStorageHandler.NotDOWNLOADED)) {
                iv.setTag(id);
                iv.setImageResource(R.drawable.download);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        progressBar.setVisibility(View.VISIBLE);
                        Cursor c = localstoragehandler.getIDnfo(iv.getTag().toString());
                        String filepath = "";
                        //Toast.makeText(getApplication(),iv.getTag().toString()+" iD " +iv.getId(),Toast.LENGTH_SHORT).show();

                        while (c.moveToNext()) {
                            String msg0 = c.getString(0);
                            String msg2 = c.getString(2);
                            String msg3 = c.getString(3);
                            String msg4 = c.getString(4);
                            String msg5 = c.getString(5);
                            String msg6 = c.getString(6);

                            filepath = msg5;

                            Log.d("-----------Vedio-----", "------------------");
                            Log.d("DATABASE---------", msg0);
                            Log.d("DATABASE-------", msg2);
                            Log.d("DATABASE---------", msg3);
                            Log.d("DATABASE-----", msg4 + "");
                            Log.d("DATABASE-------", msg5 + "");
                            Log.d("DATABASE----------", msg6 + "");
                            Log.d("--------END-------", "-------END-----------");

                        }

                        Toast.makeText(getApplicationContext(), filepath.toString() + iv.getTag().toString(), Toast.LENGTH_SHORT).show();

                        DownloadFileFromURL downloadFileFromURL = new DownloadFileFromURL(filepath, iv.getTag().toString());
                        downloadFileFromURL.execute("");
                    }
                });
            }
        } else {
            iv.setVisibility(View.GONE);
            progressBar.setVisibility(View.GONE);
        }
    }
    if(!(messageType.equals(MessageInfo.MESSAGE_TYPE_VIDEO))) {
        if (!internet) {
            statusiv.setImageResource(R.drawable.noconnectionl);
        }
    }
    mess.setText(messa);
    //time.setText(sendt);
    v.setLayoutParams(lp);
    final View lastview = v;
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            mEssageBox.addView(lastview);

        }
    });
    scrollView.post(new Runnable() {
        @Override
        public void run() {
            scrollView.fullScroll(View.FOCUS_DOWN);
            messageText.requestFocus();
        }
    });
}

and here is the XML of the dialogbox:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="20dp"
android:layoutDirection="ltr">

<ImageView
    android:id="@+id/imageViewleft"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_alignParentRight="true"
    android:layout_alignParentTop="true"
    android:src="@drawable/chaticion" />

<RelativeLayout
    android:id="@+id/tests"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="#83e3ed"
    android:layoutDirection="rtl"
    android:padding="5dp"
    android:layout_alignParentTop="true"
    android:layout_toLeftOf="@+id/imageViewleft"
    android:layout_toStartOf="@+id/imageViewleft">

    <TextView
        android:id="@+id/message_entity_right_message"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_marginEnd="19dp"
        android:layout_marginRight="19dp"
        android:text="Large ffText"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:textIsSelectable="true" />

    <TextView
        android:id="@+id/message_entity_right_time"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/message_entity_right_message"
        android:paddingRight="10dp"
        android:text="Small Text"
        android:textAppearance="?android:attr/textAppearanceMedium" />

    <ImageView
        android:id="@+id/message_entity_right_imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"
        android:adjustViewBounds="true"
        android:scaleType="centerCrop"

        android:src="@drawable/ic_launcher" />

    <ProgressBar
        android:id="@+id/message_entity_Right_progressbar"
        style="?android:attr/progressBarStyleLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="false"
        android:layout_below="@+id/message_entity_right_time"

        android:indeterminate="false"
        android:visibility="invisible" />

</RelativeLayout>

And here is the code to send the video message:

final String message = messageText.getText().toString();
    final Long rowid = localstoragehandler.insert(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED); //insert data into db and get to chat_id
    appendToMessageHistory(rowid + "", imService.getUsername(), message, MessageInfo.MESSAGE_TYPE_VIDEO, ZippedVideoPath, LocalStorageHandler.DOWNLOADED, internet,3);// append the video with type 3 to just display the progress
    messageText.setText("Video");
    String newstr = null;
    // intialize the asynctask to upload the video
    class UploadVideo extends AsyncTask<Void, Void, String> {
        ProgressDialog uploading;
        View V;
        UploadVideo(View v){
            V = v;
        }

        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            //          uploading = ProgressDialog.show(Messaging.this, "Uploading File", "Please wait...", false, false);
        }

        @Override
        protected String doInBackground(Void... params) {
            return imService.sendVideoMessage(imService.getUsername(), friend.userName, message, MessageInfo.MESSAGE_TYPE_VIDEO, "", ZippedVideoPath);
        }

        @Override
        protected void onPostExecute(String s) {
            super.onPostExecute(s);
         //   RelativeLayout v = (RelativeLayout) V.findViewById(rowid.intValue());
        //    Log.w("Zipping",v.toString());
     //       ProgressBar progressBar1 = (ProgressBar) V.findViewById(R.id.message_entity_Right_progressbar);
      //      Log.w("Zipping",progressBar1.toString());
            //          ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
       //     progressBar1.setVisibility(View.GONE);
        //  Log.d("POST Execute", s + "");

            //textViewResponse.setText(Html.fromHtml("Uploaded at " + s + ""));
            //textViewResponse.setMovementMethod(LinkMovementMethod.getInstance());
    // here i am preparing the path so when the compress is done to save into.
        }
    }
    if (null != absolute && absolute.length() > 0) {
        int endIndex = absolute.lastIndexOf("/");
        if (endIndex != -1) {
            newstr = absolute.substring(endIndex, absolute.length()); // not forgot to put check if(endIndex != -1)
        }
    }
    Log.w("Zipping", newstr);
    final File videosdir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/videos/");
    if (!videosdir.exists()) {
        videosdir.mkdirs();
    }
    ZippedVideoPath = videosdir.getAbsolutePath() + "/" + newstr;
    Log.w("Zipping", ZippedVideoPath);
    // here i got the ffmpeg library from the net to compress the video and i'm preparing the commands
    String[] complexCommand = {"-y", "-i", absolute, "-strict", "experimental", "-r", "25", "-vcodec", "mpeg4", "-b:a", "150k", "-ab", "48000", "-ac", "2", "-ar", "22050", ZippedVideoPath};
    FFmpeg ffmpeg = FFmpeg.getInstance(getBaseContext());
    try {
        // to execute "ffmpeg -version" command you just need to pass "-version"
        ffmpeg.execute(complexCommand, new ExecuteBinaryResponseHandler() {

            @Override
            public void onStart() {
                Log.w("Zipping", "started");
            }

            @Override
            public void onProgress(String message) {
            }

            @Override
            public void onFailure(String message) {
                Log.w("Zipping", message);
            }

            @Override
            public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue());
                Log.w("VideoView",v.toString());
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar);
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview);
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

            @Override
            public void onFinish() {
            }
        });
    } catch (FFmpegCommandAlreadyRunningException e) {
        Log.w("Zipping", e.toString());
    }
}

okay now to the problem when i call the findviewbyid for the progress bar in sendvideomessage ffmpeg onsuccess callback it returns null even though the findviewbyid for the the imageview which is in the same layout it returns the view! so please tell me what is the problem

public void onSuccess(String message1) {
                Log.w("Zipping","Success");
                RelativeLayout v = (RelativeLayout) mEssageBox.findViewById(rowid.intValue()); ;
                ProgressBar progressBar = (ProgressBar) v.findViewById(R.id.message_entity_Right_progressbar); // this keeps returning null!
                ImageView iv = (ImageView) v.findViewById(R.id.message_entity_right_imageview); // returns the view
            //  progressBar.setVisibility(View.GONE);
                Bitmap bitTh = ThumbnailUtils.createVideoThumbnail(ZippedVideoPath, MediaStore.Images.Thumbnails.MINI_KIND);
                iv.setImageBitmap(bitTh);
                progressBar.setVisibility(View.GONE);
                iv.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(ZippedVideoPath));
                        intent.setDataAndType(Uri.parse(ZippedVideoPath), "video/mp4");
                        startActivity(intent);

                    }
                });
                UploadVideo uv = new UploadVideo(v);
                uv.execute();
            }

Thank you!


答:
you can use this built in function for get last insert id

```<code>$last_id = mysqli_insert_id($conn);
</code>```

if you want to get max record id from your db and if id this your primary key then you can use this code

```<code>$sql = "SELECT id FROM tbl_uploads order by id desc";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];
</code>```

and if you want to get specific max record then use this code. if id your filed then you can use this code . you use alias for get record

```<code>$sql = "SELECT MAX(id) as max_id FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['max_id'];
</code>```

Title: Getting the id of the last record inserted into a MySQL database

Body:
you can use this built in function for get last insert id

$last_id = mysqli_insert_id($conn);

if you want to get max record id from your db and if id this your primary key then you can use this code

$sql = "SELECT id FROM tbl_uploads order by id desc";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['id'];

and if you want to get specific max record then use this code. if id your filed then you can use this code . you use alias for get record

$sql = "SELECT MAX(id) as max_id FROM tbl_uploads";
$result = $db_conx->query($sql);
$row = $result->fetch_assoc();
echo 'last_id: '.$row['max_id'];


问:
Math to convert seconds since 1970 into date and vice versa
I have seconds since Jan 1 1970 00:00 as an int64 in nanoseconds and I'm trying to convert it into month/day/year/day of week.

It's easy to do this iteratively, I have that working but I want to do it formulaically. I'm looking for the actual math.

答:
BEFORE

```<code>    for (i = 0; i < (years - 1); i++)
    {
        if (LEAPYEAR((epoch + i)))
        countleap++;
    }
</code>```

LATER:

```<code>    for (i = 0; i < years; i++)
 {
   if (LEAPYEAR((epoch + i)))
    countleap++;
 }
</code>```

After the correction the code worked for me.

Body:
BEFORE

    for (i = 0; i < (years - 1); i++)
    {
        if (LEAPYEAR((epoch + i)))
        countleap++;
    }

LATER:

    for (i = 0; i < years; i++)
 {
   if (LEAPYEAR((epoch + i)))
    countleap++;
 }

After the correction the code worked for me.


问:
Understanding Javascript scope with modules
I am trying to understand how scope works with node modules. I have an IIFE to initialize a LinkedList, which uses Node object for each element.

using IIFE to avoid polluting global scope

After IIFE, where does the Node go? Is there any way I can access Node in require object i.e. test class?

linkedList.js

(function LinkedListInit() {
    module.exports = new LinkedList();

    function LinkedList() {
        this.head;
    }

    // LinkedList Node
    function Node(data, next) {
        this.data = data;
        this.next = next;
    }

    LinkedList.prototype.insert = insert;

    function insert(data) {
        var curr = this.head,
            newNode = new Node(data);

        if (this.head == null) {
            this.head = newNode;
        } else {
            while (curr.next != null) {
                curr = curr.next;
            }
            curr.next = newNode;
        }
        return this;
    }
}());```
</div>
</div>
</p>

<h2>linkedListTest.js</h2>

```var linkedList = require('../../js/ds/linkedList');
// Test cases for linkedList.insert(val); works fine.

// Can I access Node here?
```

答:
Generally, any functions and variables defined in your ES6 module are module scoped, i.e. your IIFE is not necessary in this case. Node or insert will not be accessible from outside the module unless they are explicitly exported via module.exports.

With that in mind, unit tests won't be able to simply access the implementation details either. If you want to test Node separately, the cleanest way would likely to move it to a separate module and import it into LinkedList:

```<code>// Node.js
function Node(data, next) {
    this.data = data;
    this.next = next;
}

module.exports = Node;

// LinkedList.js
var Node = require('./Node');

function LinkedList() {
    this.head;
}
LinkedList.prototype.insert = function(data) {
    var curr = this.head,
        newNode = new Node(data);

    if (this.head == null) {
        this.head = newNode;
    } else {
        while (curr.next != null) {
            curr = curr.next;
        }
        curr.next = newNode;
    }
    return this;
}

module.exports = LinkedList;

// NodeTest.js
var Node = require('./Node');

var node = new Node('foo');
// ...

// LinkedListTest.js
var LinkedList = require('./LinkedList');

var linkedList = new LinkedList();
linkedList.insert('foo');
// ...
</code>```

Body:
I am trying to understand how scope works with node modules. I have an IIFE to initialize a LinkedList, which uses Node object for each element.

using IIFE to avoid polluting global scope

After IIFE, where does the Node go? Is there any way I can access Node in require object i.e. test class?

linkedList.js

(function LinkedListInit() {
    module.exports = new LinkedList();

    function LinkedList() {
        this.head;
    }

    // LinkedList Node
    function Node(data, next) {
        this.data = data;
        this.next = next;
    }

    LinkedList.prototype.insert = insert;

    function insert(data) {
        var curr = this.head,
            newNode = new Node(data);

        if (this.head == null) {
            this.head = newNode;
        } else {
            while (curr.next != null) {
                curr = curr.next;
            }
            curr.next = newNode;
        }
        return this;
    }
}());

linkedListTest.js

var linkedList = require('../../js/ds/linkedList');
// Test cases for linkedList.insert(val); works fine.

// Can I access Node here?

Body:
Generally, any functions and variables defined in your ES6 module are module scoped, i.e. your IIFE is not necessary in this case. Node or insert will not be accessible from outside the module unless they are explicitly exported via module.exports.

With that in mind, unit tests won't be able to simply access the implementation details either. If you want to test Node separately, the cleanest way would likely to move it to a separate module and import it into LinkedList:

// Node.js
function Node(data, next) {
    this.data = data;
    this.next = next;
}

module.exports = Node;

// LinkedList.js
var Node = require('./Node');

function LinkedList() {
    this.head;
}
LinkedList.prototype.insert = function(data) {
    var curr = this.head,
        newNode = new Node(data);

    if (this.head == null) {
        this.head = newNode;
    } else {
        while (curr.next != null) {
            curr = curr.next;
        }
        curr.next = newNode;
    }
    return this;
}

module.exports = LinkedList;

// NodeTest.js
var Node = require('./Node');

var node = new Node('foo');
// ...

// LinkedListTest.js
var LinkedList = require('./LinkedList');

var linkedList = new LinkedList();
linkedList.insert('foo');
// ...