问:
Sum data from array by parameters php
This is the array that I get from a query:

```<code>Array (
       [0] => Array (
                     [0] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ADELE
                                    [GOLD] => 160
                                    [NORMAL] => 0
                                    [TOTAL] => 160
                                  )
                     [1] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ALESSO
                                    [GOLD] => 1320
                                    [NORMAL] => 550
                                    [TOTAL] => 1870
                                  )
                     [2] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ANASTACIA
                                    [GOLD] => 440
                                    [NORMAL] => 150
                                    [TOTAL] => 590
                                   )
                     [3] => Array (
                                    [PRODUCT] => ROSE1
                                    [VARIETY] => ANASTACIA1
                                    [GOLD] => 420
                                    [NORMAL] => 120
                                    [TOTAL] => 540
                                   )
                     [4] => Array (
                                    [PRODUCT] => ROSE1
                                    [VARIETY] => ANASTACIA1
                                    [GOLD] => 440
                                    [NORMAL] => 100
                                    [TOTAL] => 540
                                   )
                     [5] => Array (
                                    [PRODUCT] => ROSE2
                                    [VARIETY] => ANASTACIA2
                                    [GOLD] => 640
                                    [NORMAL] => 0
                                    [TOTAL] => 640
                                   )
                     [6] => Array (
                                    [PRODUCT] => ROSE2
                                    [VARIETY] => ANASTACIA2
                                    [GOLD] => 440
                                    [NORMAL] => 440
                                    [TOTAL] => 880
                                   )
                    )

     )
)
</code>```

The keys GOLD and NORMAL can be differents, depend of the query, but I would like to sum the total from GOLD, NORMAL and TOTAL by PRODUCT, something like this, you can omit VARIETY:

```<code>Array(
      [0] => Array(
                   [PRODUCT] => ROSE
                   [GOLD]    => 1920
                   [NORMAL]  => 700
                   [TOTAL]   => 2620
                  )
      [1] => Array(
                   [PRODUCT] => ROSE1
                   [GOLD]    => 860
                   [NORMAL]  => 220
                   [TOTAL]   => 1080
                  )
      [2] => Array(
                   [PRODUCT] => ROSE2
                   [GOLD]    => 1080
                   [NORMAL]  => 440
                   [TOTAL]   => 1520
                  )
)
</code>```

I have tried somenthing like this:
$harvest is the array with the data

```<code>//This get the array_keys from the data
$arrayThead = array();
for ($i=0; $i < count($harvest) ; $i++) {
   array_push($arrayThead, array_keys($harvest[$i][0]));
}

$arrayfoot= array();

foreach ($harvest as $key => $value) {
  foreach ($value as $harv) {
     foreach ($arrayThead as $key => $values) {
        foreach ($values as $th) {
           if($th != 'PRODUCT' && $th != 'VARIETY'){
               $arrayfoot[$th] += $harv[$th];
           }
        }
     }
  }
}
</code>```

But at this point it totalizes the data with all the PRODUCTS in general:

```<code>Array (
        [GOLD] => 3850
        [NORMAL] => 1360
        [TOTAL] => 5220
      )
</code>```

UPDATED

This is the mysql query:

```<code>SELECT pr_products.product AS PRODUCT,
            pr_varieties.variety AS VARIETY,
            FORMAT(SUM(IF(pr_grades.grade='GOLD',pf_harvest.quantity,0)),0) AS GOLD,
            SUM(IF(pr_grades.grade='NORMAL',pf_harvest.quantity,0)) AS NORMAL,
            SUM(pf_harvest.quantity) AS TOTAL
FROM pf_harvest
INNER JOIN pf_performance ON pf_performance.id = pf_harvest.id_performance
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pr_grades ON pr_grades.id = pf_harvest.id_grade
WHERE pf_performance.status = 100
AND pf_harvest.id_tenant = 1
AND pf_harvest.date = CURDATE()
GROUP BY pf_harvest.id_product, pf_harvest.id_variety
ORDER BY pf_harvest.id_product, pr_varieties.variety, pf_harvest.id_grade
</code>```

How can I add the data to arm an array as in the example I have explained?
Thanks!

答:
```<code>    <?php
    $array = Array (
        0 => Array (
            0 => Array (
                'PRODUCT' => 'ROSE',
                'VARIETY' => 'ADELE',
                'GOLD' => 160,
                'NORMAL' => 0,
                'TOTAL' => 160
            ),
            1 => Array (
                'PRODUCT' => 'ROSE',
                'VARIETY' => 'ALESSO',
                'GOLD' => 1320,
                'NORMAL' => 550,
                'TOTAL' => 1870
            ),
            2 => Array (
                'PRODUCT' => 'ROSE',
                'VARIETY' => 'ANASTACIA',
                'GOLD' => 440,
                'NORMAL' => 150,
                'TOTAL' => 590
            ),
            3 => Array (
                'PRODUCT' => 'ROSE1',
                'VARIETY' => 'ANASTACIA1',
                'GOLD' => 420,
                'NORMAL' => 120,
                'TOTAL' => 540
            ),
            4 => Array (
                'PRODUCT' => 'ROSE1',
                'VARIETY' => 'ANASTACIA1',
                'GOLD' => 440,
                'NORMAL' => 100,
                'TOTAL' => 540,
            ),
            5 => Array (
                'PRODUCT' => 'ROSE2',
                'VARIETY' => 'ANASTACIA2',
                'GOLD' => 640,
                'NORMAL' => 0,
                'TOTAL' => 640,
            ),
            6 => Array (
                'PRODUCT' => 'ROSE2',
                'VARIETY' => 'ANASTACIA2',
                'GOLD' => 440,
                'NORMAL' => 440,
                'TOTAL' => 880,
            )
        )
    );

    $totalByProduct = array();

    foreach ($array as $items) {
        foreach ($items as $item) {
            if(!key_exists($item['PRODUCT'], $totalByProduct)){
                $totalByProduct[$item['PRODUCT']] = $item;
                continue;
            }
            $totalByProduct[$item['PRODUCT']]['GOLD'] += $item['GOLD'];
            $totalByProduct[$item['PRODUCT']]['NORMAL'] += $item['NORMAL'];
            $totalByProduct[$item['PRODUCT']]['TOTAL'] += $item['TOTAL'];
        }
    }
    var_dump($totalByProduct);
?>
</code>```

Title: Sum data from array by parameters php

Body:
This is the array that I get from a query:

Array (
       [0] => Array (
                     [0] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ADELE
                                    [GOLD] => 160
                                    [NORMAL] => 0
                                    [TOTAL] => 160
                                  )
                     [1] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ALESSO
                                    [GOLD] => 1320
                                    [NORMAL] => 550
                                    [TOTAL] => 1870
                                  )
                     [2] => Array (
                                    [PRODUCT] => ROSE
                                    [VARIETY] => ANASTACIA
                                    [GOLD] => 440
                                    [NORMAL] => 150
                                    [TOTAL] => 590
                                   )
                     [3] => Array (
                                    [PRODUCT] => ROSE1
                                    [VARIETY] => ANASTACIA1
                                    [GOLD] => 420
                                    [NORMAL] => 120
                                    [TOTAL] => 540
                                   )
                     [4] => Array (
                                    [PRODUCT] => ROSE1
                                    [VARIETY] => ANASTACIA1
                                    [GOLD] => 440
                                    [NORMAL] => 100
                                    [TOTAL] => 540
                                   )
                     [5] => Array (
                                    [PRODUCT] => ROSE2
                                    [VARIETY] => ANASTACIA2
                                    [GOLD] => 640
                                    [NORMAL] => 0
                                    [TOTAL] => 640
                                   )
                     [6] => Array (
                                    [PRODUCT] => ROSE2
                                    [VARIETY] => ANASTACIA2
                                    [GOLD] => 440
                                    [NORMAL] => 440
                                    [TOTAL] => 880
                                   )
                    )

     )
)

The keys GOLD and NORMAL can be differents, depend of the query, but I would like to sum the total from GOLD, NORMAL and TOTAL by PRODUCT, something like this, you can omit VARIETY:

Array(
      [0] => Array(
                   [PRODUCT] => ROSE
                   [GOLD]    => 1920
                   [NORMAL]  => 700
                   [TOTAL]   => 2620
                  )
      [1] => Array(
                   [PRODUCT] => ROSE1
                   [GOLD]    => 860
                   [NORMAL]  => 220
                   [TOTAL]   => 1080
                  )
      [2] => Array(
                   [PRODUCT] => ROSE2
                   [GOLD]    => 1080
                   [NORMAL]  => 440
                   [TOTAL]   => 1520
                  )
)

I have tried somenthing like this:
$harvest is the array with the data

//This get the array_keys from the data
$arrayThead = array();
for ($i=0; $i < count($harvest) ; $i++) {
   array_push($arrayThead, array_keys($harvest[$i][0]));
}

$arrayfoot= array();

foreach ($harvest as $key => $value) {
  foreach ($value as $harv) {
     foreach ($arrayThead as $key => $values) {
        foreach ($values as $th) {
           if($th != 'PRODUCT' && $th != 'VARIETY'){
               $arrayfoot[$th] += $harv[$th];
           }
        }
     }
  }
}

But at this point it totalizes the data with all the PRODUCTS in general:

Array (
        [GOLD] => 3850
        [NORMAL] => 1360
        [TOTAL] => 5220
      )

UPDATED

This is the mysql query:

SELECT pr_products.product AS PRODUCT,
            pr_varieties.variety AS VARIETY,
            FORMAT(SUM(IF(pr_grades.grade='GOLD',pf_harvest.quantity,0)),0) AS GOLD,
            SUM(IF(pr_grades.grade='NORMAL',pf_harvest.quantity,0)) AS NORMAL,
            SUM(pf_harvest.quantity) AS TOTAL
FROM pf_harvest
INNER JOIN pf_performance ON pf_performance.id = pf_harvest.id_performance
INNER JOIN pr_products ON pr_products.id = pf_harvest.id_product
INNER JOIN pr_varieties ON pr_varieties.id = pf_harvest.id_variety
INNER JOIN pr_grades ON pr_grades.id = pf_harvest.id_grade
WHERE pf_performance.status = 100
AND pf_harvest.id_tenant = 1
AND pf_harvest.date = CURDATE()
GROUP BY pf_harvest.id_product, pf_harvest.id_variety
ORDER BY pf_harvest.id_product, pr_varieties.variety, pf_harvest.id_grade

How can I add the data to arm an array as in the example I have explained?
Thanks!


来源: stackexchange

问:
Connect 4 right to left diagonal check
There's probably a very simple solution to this but I can't figure out where I'm doing something wrong. I'm making a small game with android studio that is connect 4. There is a 5x7 matrix of single cells, and 5 imageviews above that when clicked on put a fiche in the right place. Up to this point it's all working fine. When I however have to check if someone won, I thought I could break up the process in 4 main functions: one that check horizontally, one vertically, one diagonally left to right and one diagonally right to left. Now they all work perfectly except the right to left one. I'll post the code below:

```<code>private void checkRightLeftDiagonally() {
    int winCondition = 0;
    boolean goingRight = true;
    int y = 1;
    int i = 4;
    int j = 0;
    while (y < 6 && won == false) {
        while (i > 0 && j < 7 && won == false) {
            if (cells[j][i].getFull() == true && players[playerTurn].getFicheColor() == cells[j][i].getFicheColor()) {
                winCondition++;
                winningCells.add(cells[j][i]);
            } else {
                winCondition = 0;
                winningCells.clear();
            }

            if (winCondition == 4) {
                won = true;
                for (int x = 0; x < 4; x++) {
                    winningCells.get(x).won();
                }
            }
            i--;
            j++;
        }

        if(goingRight == true)
        {
            if(y<=4)
            {
                i=4-y;
                j=0;
                y++;
            }
            else
            {
                goingRight = false;
                y=0;
                i=0;
                j=0+y;
            }
        }

        if(goingRight == false)
        {
            i=0;
            j=0+y;
            y++;
        }

        if(won == false)
        {
            winCondition = 0;
            winningCells.clear();
        }

    }
    if(won == false) {
        winCondition = 0;
        winningCells.clear();
    }

    }
</code>```

And here is one of the arrow imageview code:

```<code>imgArrows[0].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(cells[0][0].getFull() == false && won == false)
            {
                int i = 0;
                while(cells[i][0].getFull() == false)
                {
                    i++;
        if(i>6) break;
                }

        i--;

                cells[i][0].ficheDown(players[playerTurn]);

                checkVertically();
                checkHorizantally();
                checkLeftRightDiagonally();
                checkRightLeftDiagonally();

                playerTurn++;
                if(playerTurn==2)
                {
                    playerTurn = 0;
                }

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

I've also made the cell class, which is here if it could help you

```<code>public class Cell {
private boolean full;
private Player.FicheColor ficheColor;
private ImageView fiche;

public Cell(Player currentPlayer, ImageView img)
{
    full = false;
    ficheColor = currentPlayer.getFicheColor();
    fiche = img;
    img.setAlpha(0f);
}

public void ficheDown(Player currentPlayer)
{
    full = true;
    ficheColor = currentPlayer.getFicheColor();
    switch(ficheColor)
    {
        case red:
            fiche.setImageResource(R.drawable.redfiche);
            break;

        case blue:
            fiche.setImageResource(R.drawable.bluefiche);
            break;

        case green:
            fiche.setImageResource(R.drawable.greenfiche);
            break;

        case white:
            fiche.setImageResource(R.drawable.whitefiche);
            break;

        case black:
            fiche.setImageResource(R.drawable.whitefiche);
            break;
    }
    fiche.setAlpha(1f);

}

public Player.FicheColor getFicheColor()
{
    return ficheColor;
}

public boolean getFull()
{
    return full;
}

public void won(){
    fiche.setColorFilter(Color.GREEN);
}

public void reset()
{
    fiche.clearColorFilter();
}
</code>```

}

Thank a lot, even just for reading

答: In the end the problem was that in the first paragraph of code the int i needed to be set to 4 and that solved it. Thanks to everyone that tried to help me</p>

ContentLicense: CC BY-SA 3.0

Title: Connect 4 right to left diagonal check

Body:
There's probably a very simple solution to this but I can't figure out where I'm doing something wrong. I'm making a small game with android studio that is connect 4. There is a 5x7 matrix of single cells, and 5 imageviews above that when clicked on put a fiche in the right place. Up to this point it's all working fine. When I however have to check if someone won, I thought I could break up the process in 4 main functions: one that check horizontally, one vertically, one diagonally left to right and one diagonally right to left. Now they all work perfectly except the right to left one. I'll post the code below:

private void checkRightLeftDiagonally() {
    int winCondition = 0;
    boolean goingRight = true;
    int y = 1;
    int i = 4;
    int j = 0;
    while (y < 6 && won == false) {
        while (i > 0 && j < 7 && won == false) {
            if (cells[j][i].getFull() == true && players[playerTurn].getFicheColor() == cells[j][i].getFicheColor()) {
                winCondition++;
                winningCells.add(cells[j][i]);
            } else {
                winCondition = 0;
                winningCells.clear();
            }

            if (winCondition == 4) {
                won = true;
                for (int x = 0; x < 4; x++) {
                    winningCells.get(x).won();
                }
            }
            i--;
            j++;
        }

        if(goingRight == true)
        {
            if(y<=4)
            {
                i=4-y;
                j=0;
                y++;
            }
            else
            {
                goingRight = false;
                y=0;
                i=0;
                j=0+y;
            }
        }

        if(goingRight == false)
        {
            i=0;
            j=0+y;
            y++;
        }

        if(won == false)
        {
            winCondition = 0;
            winningCells.clear();
        }

    }
    if(won == false) {
        winCondition = 0;
        winningCells.clear();
    }

    }

And here is one of the arrow imageview code:

imgArrows[0].setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            if(cells[0][0].getFull() == false && won == false)
            {
                int i = 0;
                while(cells[i][0].getFull() == false)
                {
                    i++;
        if(i>6) break;
                }

        i--;

                cells[i][0].ficheDown(players[playerTurn]);

                checkVertically();
                checkHorizantally();
                checkLeftRightDiagonally();
                checkRightLeftDiagonally();

                playerTurn++;
                if(playerTurn==2)
                {
                    playerTurn = 0;
                }

            }
        }
    });

I've also made the cell class, which is here if it could help you

public class Cell {
private boolean full;
private Player.FicheColor ficheColor;
private ImageView fiche;

public Cell(Player currentPlayer, ImageView img)
{
    full = false;
    ficheColor = currentPlayer.getFicheColor();
    fiche = img;
    img.setAlpha(0f);
}

public void ficheDown(Player currentPlayer)
{
    full = true;
    ficheColor = currentPlayer.getFicheColor();
    switch(ficheColor)
    {
        case red:
            fiche.setImageResource(R.drawable.redfiche);
            break;

        case blue:
            fiche.setImageResource(R.drawable.bluefiche);
            break;

        case green:
            fiche.setImageResource(R.drawable.greenfiche);
            break;

        case white:
            fiche.setImageResource(R.drawable.whitefiche);
            break;

        case black:
            fiche.setImageResource(R.drawable.whitefiche);
            break;
    }
    fiche.setAlpha(1f);

}

public Player.FicheColor getFicheColor()
{
    return ficheColor;
}

public boolean getFull()
{
    return full;
}

public void won(){
    fiche.setColorFilter(Color.GREEN);
}

public void reset()
{
    fiche.clearColorFilter();
}

}

Thank a lot, even just for reading


问:
Implement a bootstrap collapse with twig loop
I am trying to implement a bootstrap collapse inside a collapse but it doesn't work very well.

This is my code;

```<code><div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
{% for frame,value in object.getPortHierarchy() %}
    <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="heading-f-{{ frame }}">
            <h4 class="panel-title">
                <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse-f-{{ frame }}" aria-expanded="true" aria-controls="collapse-f-{{ frame }}">
                    Frame #{{ frame }}
                </a>
            </h4>
        </div>
        <div id="collapse-f-{{ frame }}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading-f-{{ frame }}">
            <div class="panel-body">
                <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
                {% for slot,value in value %}
                    <div class="panel panel-default">
                        <div class="panel-heading" role="tab" id="heading-s-{{ slot }}">
                            <h4 class="panel-title">
                                <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse-s-{{ slot }}" aria-expanded="true" aria-controls="collapse-s-{{ slot }}">
                                    Slot #{{ slot }}
                                </a>
                            </h4>
                        </div>
                        <div id="collapse-s-{{ slot }}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading-s-{{ slot }}">
                            <div class="panel-body">
                                {% for port,value in value %}
                                    Port: {{ value }}</br>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                {% endfor %}
                </div>
            </div>
        </div>
    </div>
{% endfor %}
</div>
</code>```

But when clicking on slots inside frames, the frames close as well. I've double checked my IDs and the correct numbers, but the issue still remain

答:
Maybe because you have the same id #accordion , but id should be unique

```<code>{#THE FIRST ID#}    <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
{% for frame,value in object.getPortHierarchy() %}
    <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="heading-f-{{ frame }}">
            <h4 class="panel-title">
                <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse-f-{{ frame }}" aria-expanded="true" aria-controls="collapse-f-{{ frame }}">
                    Frame #{{ frame }}
                </a>
            </h4>
        </div>
        <div id="collapse-f-{{ frame }}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading-f-{{ frame }}">
            <div class="panel-body">
        {#HERE#}        <div class="panel-group" id="accordion-{{frame}}" role="tablist" aria-multiselectable="true">
                {% for slot,value in value %}
                    <div class="panel panel-default">
                        <div class="panel-heading" role="tab" id="heading-s-{{ slot }}">
                            <h4 class="panel-title">
                    {#HERE#}            <a role="button" data-toggle="collapse" data-parent="#accordion-{{frame}}" href="#collapse-s-{{ slot }}" aria-expanded="true" aria-controls="collapse-s-{{ slot }}">
                                    Slot #{{ slot }}
                                </a>
                            </h4>
                        </div>
                        <div id="collapse-s-{{ slot }}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading-s-{{ slot }}">
                            <div class="panel-body">
                                {% for port,value in value %}
                                    Port: {{ value }}</br>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                {% endfor %}
                </div>
            </div>
        </div>
    </div>
{% endfor %}
</div>
</code>```

Body:
I am trying to implement a bootstrap collapse inside a collapse but it doesn't work very well.

This is my code;

{% for frame,value in object.getPortHierarchy() %}

                    Frame #{{ frame }}

                {% for slot,value in value %}

                                    Slot #{{ slot }}

                                {% for port,value in value %}
                                    Port: {{ value }}

                                {% endfor %}

                {% endfor %}

{% endfor %}

But when clicking on slots inside frames, the frames close as well. I've double checked my IDs and the correct numbers, but the issue still remain

Body:
Maybe because you have the same id #accordion , but id should be unique

{#THE FIRST ID#}    <div class="panel-group" id="accordion" role="tablist" aria-multiselectable="true">
{% for frame,value in object.getPortHierarchy() %}
    <div class="panel panel-default">
        <div class="panel-heading" role="tab" id="heading-f-{{ frame }}">
            <h4 class="panel-title">
                <a role="button" data-toggle="collapse" data-parent="#accordion" href="#collapse-f-{{ frame }}" aria-expanded="true" aria-controls="collapse-f-{{ frame }}">
                    Frame #{{ frame }}
                </a>
            </h4>
        </div>
        <div id="collapse-f-{{ frame }}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading-f-{{ frame }}">
            <div class="panel-body">
        {#HERE#}        <div class="panel-group" id="accordion-{{frame}}" role="tablist" aria-multiselectable="true">
                {% for slot,value in value %}
                    <div class="panel panel-default">
                        <div class="panel-heading" role="tab" id="heading-s-{{ slot }}">
                            <h4 class="panel-title">
                    {#HERE#}            <a role="button" data-toggle="collapse" data-parent="#accordion-{{frame}}" href="#collapse-s-{{ slot }}" aria-expanded="true" aria-controls="collapse-s-{{ slot }}">
                                    Slot #{{ slot }}
                                </a>
                            </h4>
                        </div>
                        <div id="collapse-s-{{ slot }}" class="panel-collapse collapse in" role="tabpanel" aria-labelledby="heading-s-{{ slot }}">
                            <div class="panel-body">
                                {% for port,value in value %}
                                    Port: {{ value }}</br>
                                {% endfor %}
                            </div>
                        </div>
                    </div>
                {% endfor %}
                </div>
            </div>
        </div>
    </div>
{% endfor %}
</div>


问:
OSError: no such file or directory on using subprocess.Popen
I am trying to get the duration of a video clip. But it is unable to get the file.
Here is my code:

```<code>import subprocess
import os
def getLength(input_video):
    result = subprocess.Popen('ffprobe -i input_video -show_entries format=duration -v quiet -of csv="p=0"', stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output = result.communicate()
    return output[0]
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
x = (os.path.join(BASE_DIR,'uploads/video.mkv'))
getLength(x)
</code>```

This is the error I am getting:

```<code>Traceback (most recent call last):
  File "/home/aman/Desktop/stream/src/stream/uploads/sadf.py", line 9, in <module>
    getLength(x)
  File "/home/aman/Desktop/stream/src/stream/uploads/sadf.py", line 4, in getLength
    result = subprocess.Popen('ffprobe -i input_video -show_entries format=duration -v quiet -of csv="p=0"', stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[Finished in 0.1s with exit code 1]
[shell_cmd: "python" -u "/home/aman/Desktop/stream/src/stream/uploads/sadf.py"]
[dir: /home/aman/Desktop/stream/src/stream/uploads]
[path: /home/aman/bin:/home/aman/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]
</code>```

答:
You can't run subprocess.Popen as a string like that without add shell=True.

```<code>result = subprocess.Popen('ffprobe -i input_video -show_entries format=duration -v quiet -of csv="p=0"', stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True)
</code>```

If you split the command into a list of args, then you can use the method you used without shell=True.  The non-shell method is generally recommended: When to use Shell=True for Python subprocess module

```<code>result = subprocess.Popen(['ffprobe', '-i', 'input_video', '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv="p=0"'], stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
</code>```

Body:
I am trying to get the duration of a video clip. But it is unable to get the file.
Here is my code:

import subprocess
import os
def getLength(input_video):
    result = subprocess.Popen('ffprobe -i input_video -show_entries format=duration -v quiet -of csv="p=0"', stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
    output = result.communicate()
    return output[0]
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
x = (os.path.join(BASE_DIR,'uploads/video.mkv'))
getLength(x)

This is the error I am getting:

Traceback (most recent call last):
  File "/home/aman/Desktop/stream/src/stream/uploads/sadf.py", line 9, in <module>
    getLength(x)
  File "/home/aman/Desktop/stream/src/stream/uploads/sadf.py", line 4, in getLength
    result = subprocess.Popen('ffprobe -i input_video -show_entries format=duration -v quiet -of csv="p=0"', stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
  File "/usr/lib/python2.7/subprocess.py", line 711, in __init__
    errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1343, in _execute_child
    raise child_exception
OSError: [Errno 2] No such file or directory
[Finished in 0.1s with exit code 1]
[shell_cmd: "python" -u "/home/aman/Desktop/stream/src/stream/uploads/sadf.py"]
[dir: /home/aman/Desktop/stream/src/stream/uploads]
[path: /home/aman/bin:/home/aman/.local/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin]

Body:
You can't run subprocess.Popen as a string like that without add shell=True.

result = subprocess.Popen('ffprobe -i input_video -show_entries format=duration -v quiet -of csv="p=0"', stdout=subprocess.PIPE,stderr=subprocess.STDOUT, shell=True)

If you split the command into a list of args, then you can use the method you used without shell=True.  The non-shell method is generally recommended: When to use Shell=True for Python subprocess module

result = subprocess.Popen(['ffprobe', '-i', 'input_video', '-show_entries', 'format=duration', '-v', 'quiet', '-of', 'csv="p=0"'], stdout=subprocess.PIPE,stderr=subprocess.STDOUT)


问:
Retrieving returned value from fetch inside render()?
I'm having a little trouble, I have JSON data which is being fetched, and then the data is rendered. However within the render I need to perform another fetch as the data I'm trying to render relies on the first JSON.

You can see I'm trying grab the returned value, but it comes as undefined.

So the fetch looks like this:

```<code>getFeaturedImage(thumbnail_json) {
    fetch(thumbnail_json)
      .then((response) => response.json())
      .then((responseData) => {
        return responseData.media_details.sizes.medium.source_url;
      })
      .done();
  }
</code>```

and the renderPost() is:

```<code>renderPosts() {
    contents = this.state.posts.map((post) => {
      let postDate = Moment(post.date).format('LLL');

      if ( post._links['wp:featuredmedia'] ) {
        console.log('has featured image');
        let thumbnail_json = post._links['wp:featuredmedia'][0].href;
        this.getFeaturedImage(thumbnail_json);
        console.log(this.getFeaturedImage(thumbnail_json)); // <----- UNDEFINED?
      } else {
        console.log('no featured image');
      }

      return (
        <View key={post.id} style={ postStyles.postContainer }>
          <Text style={postStyles.postTitle}>
            {post.title.rendered}
          </Text>
          <Text style={postStyles.postDate}>
            {postDate}
          </Text>
          <View style={ postStyles.excerptContainer }>
            <HTMLView stylesheet={htmlStyles}
              value={post.excerpt.rendered}
            />
          </View>
        </View>
      );
    });
    return (
      <ScrollView>
        <View style={baseStyles.container}>
          {contents}
        </View>
      </ScrollView>
    );
  }
</code>```

答:
You can pass a callback function in getFeaturedImage as an argument and call that on success

```<code>mycallback(result) {
    //do what you want with result
}
getFeaturedImage(thumbnail_json, callback) {
    fetch(thumbnail_json)
      .then((response) => response.json())
      .then((responseData) => {
        callback(responseData.media_details.sizes.medium.source_url);
      })
      .done();
  }

renderPosts() {
    contents = this.state.posts.map((post) => {
      let postDate = Moment(post.date).format('LLL');

      if ( post._links['wp:featuredmedia'] ) {
        console.log('has featured image');
        let thumbnail_json = post._links['wp:featuredmedia'][0].href;
        this.getFeaturedImage(thumbnail_json, this.mycallback);
        console.log(this.getFeaturedImage(thumbnail_json)); // <----- UNDEFINED?
      } else {
        console.log('no featured image');
      }

      return (
        <View key={post.id} style={ postStyles.postContainer }>
          <Text style={postStyles.postTitle}>
            {post.title.rendered}
          </Text>
          <Text style={postStyles.postDate}>
            {postDate}
          </Text>
          <View style={ postStyles.excerptContainer }>
            <HTMLView stylesheet={htmlStyles}
              value={post.excerpt.rendered}
            />
          </View>
        </View>
      );
    });
    return (
      <ScrollView>
        <View style={baseStyles.container}>
          {contents}
        </View>
      </ScrollView>
    );
  }
</code>```

Body:
I'm having a little trouble, I have JSON data which is being fetched, and then the data is rendered. However within the render I need to perform another fetch as the data I'm trying to render relies on the first JSON.

You can see I'm trying grab the returned value, but it comes as undefined.

So the fetch looks like this:

getFeaturedImage(thumbnail_json) {
    fetch(thumbnail_json)
      .then((response) => response.json())
      .then((responseData) => {
        return responseData.media_details.sizes.medium.source_url;
      })
      .done();
  }

and the renderPost() is:

renderPosts() {
    contents = this.state.posts.map((post) => {
      let postDate = Moment(post.date).format('LLL');

      if ( post._links['wp:featuredmedia'] ) {
        console.log('has featured image');
        let thumbnail_json = post._links['wp:featuredmedia'][0].href;
        this.getFeaturedImage(thumbnail_json);
        console.log(this.getFeaturedImage(thumbnail_json)); // <----- UNDEFINED?
      } else {
        console.log('no featured image');
      }

      return (
        <View key={post.id} style={ postStyles.postContainer }>
          <Text style={postStyles.postTitle}>
            {post.title.rendered}
          </Text>
          <Text style={postStyles.postDate}>
            {postDate}
          </Text>
          <View style={ postStyles.excerptContainer }>
            <HTMLView stylesheet={htmlStyles}
              value={post.excerpt.rendered}
            />
          </View>
        </View>
      );
    });
    return (
      <ScrollView>
        <View style={baseStyles.container}>
          {contents}
        </View>
      </ScrollView>
    );
  }

Body:
You can pass a callback function in getFeaturedImage as an argument and call that on success

mycallback(result) {
    //do what you want with result
}
getFeaturedImage(thumbnail_json, callback) {
    fetch(thumbnail_json)
      .then((response) => response.json())
      .then((responseData) => {
        callback(responseData.media_details.sizes.medium.source_url);
      })
      .done();
  }

renderPosts() {
    contents = this.state.posts.map((post) => {
      let postDate = Moment(post.date).format('LLL');

      if ( post._links['wp:featuredmedia'] ) {
        console.log('has featured image');
        let thumbnail_json = post._links['wp:featuredmedia'][0].href;
        this.getFeaturedImage(thumbnail_json, this.mycallback);
        console.log(this.getFeaturedImage(thumbnail_json)); // <----- UNDEFINED?
      } else {
        console.log('no featured image');
      }

      return (
        <View key={post.id} style={ postStyles.postContainer }>
          <Text style={postStyles.postTitle}>
            {post.title.rendered}
          </Text>
          <Text style={postStyles.postDate}>
            {postDate}
          </Text>
          <View style={ postStyles.excerptContainer }>
            <HTMLView stylesheet={htmlStyles}
              value={post.excerpt.rendered}
            />
          </View>
        </View>
      );
    });
    return (
      <ScrollView>
        <View style={baseStyles.container}>
          {contents}
        </View>
      </ScrollView>
    );
  }


问:
How to use max function inside IN clause
I need to select max(time) and some some specific hours in single table. i tried something like this. any idea?</p>

```<code>SELECT * FROM ara WHERE date = '2017-03-31' and time in('07:00:00','13:00:00','19:00:00',max(tme)) order by time desc

SELECT * FROM ara WHERE date = '2017-03-31' and (time = '07:00:00' or time = '13:00:00' or time = '19:00:00'or time = max(time)) order by time desc
</code>```

答:
Assuming you're selecting the maximum time from that same ara table, you can do that this way

```<code>SELECT  *
FROM    ara
WHERE   date = '2017-03-31' and
        (
          time in ('07:00:00','13:00:00','19:00:00') OR
          time = (SELECT MAX(time) FROM ara)
        )
ORDER BY time desc
</code>```

Body:
I need to select max(time) and some some specific hours in single table. i tried something like this. any idea?

SELECT * FROM ara WHERE date = '2017-03-31' and time in('07:00:00','13:00:00','19:00:00',max(tme)) order by time desc

SELECT * FROM ara WHERE date = '2017-03-31' and (time = '07:00:00' or time = '13:00:00' or time = '19:00:00'or time = max(time)) order by time desc

Body:
Assuming you're selecting the maximum time from that same ara table, you can do that this way

SELECT  *
FROM    ara
WHERE   date = '2017-03-31' and
        (
          time in ('07:00:00','13:00:00','19:00:00') OR
          time = (SELECT MAX(time) FROM ara)
        )
ORDER BY time desc


问:
How to make a JLabel looks like a tab header of JTabbedPane
Providing the text of the JLabel is "Text",

I want a JLabel object looks like this in Nimbus:

like this in Metal:

i.e. the same as a tab header of a JTabbedPane.
Is it possible?

Thanks.

答:
Absolutely Yes. But not that easy.

Every Swing Component has a UI associated with it, that can be overridden by your own custom UI. You can create a JLabelUI (UI delegate class) and set it yourself, or you could simply override the paint() method of the JLabel (creating your own custom JLabel.

The next step is then to get the source of the UI that you want to copy, and take the paint function from that UI and copy it into your overridden paint method (or UI delegate class).

ContentLicense: CC BY-SA 2.5


问:
JSON encoding not working
Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?

```<code><?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
    $masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
    $r['masp'] =$data['masp'];
    $r['loai'] =$data['loai'];
    $r['hangsx']=$data['hangsx'];
    $r['tensp']=$data['tensp'];
    $r['img']=$data['img'];
    $r['gia']=$data['gia'];
    $r['nx']=$data['nx'];
 }
}
}
print json_encode($data);

?>
</code>```

答:
You are setting your variables wrong.

In every while cycle you get a new $r variable that you want to add to your $data variable.

```<code>$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
    $masp = $_GET['masp'];
    $sql = "SELECT *FROM sanpham WHERE masp='$masp'";
    $result = mysqli_query($conn, $sql);
    $i = 0;
    if ($result) {
        while ($r = mysqli_fetch_assoc($result)) {
            $data[$i]['masp'] = $r['masp'];
            $data[$i]['loai'] = $r['loai'];
            $data[$i]['hangsx'] = $r['hangsx']];
            $data[$i]['tensp'] = $r['tensp'];
            $data[$i]['img'] = $r['img'];
            $data[$i]['gia'] = $r['gia'];
            $data[$i]['nx'] = $r['nx'];
            $i += 1;
        }
    }
}
print json_encode($data);
</code>```

Title: JSON encoding not working

Body:
Here is my code to encode data in JSON format, but it doesn't work. The result is []. Where is my mistake?

<?php
$conn = new mysqli('localhost','root','','project');
$data =array();
if(!empty($_GET['masp'])){
    $masp =$_GET['masp'];
$sql ="SELECT *FROM sanpham WHERE masp='$masp'";
$result = mysqli_query($conn,$sql);
if($result){
while($r = mysqli_fetch_assoc($result)){
    $r['masp'] =$data['masp'];
    $r['loai'] =$data['loai'];
    $r['hangsx']=$data['hangsx'];
    $r['tensp']=$data['tensp'];
    $r['img']=$data['img'];
    $r['gia']=$data['gia'];
    $r['nx']=$data['nx'];
 }
}
}
print json_encode($data);

?>

Body:
You are setting your variables wrong.

In every while cycle you get a new $r variable that you want to add to your $data variable.

$conn = new mysqli('localhost', 'root', '', 'project');
$data = array();
if (!empty($_GET['masp'])) {
    $masp = $_GET['masp'];
    $sql = "SELECT *FROM sanpham WHERE masp='$masp'";
    $result = mysqli_query($conn, $sql);
    $i = 0;
    if ($result) {
        while ($r = mysqli_fetch_assoc($result)) {
            $data[$i]['masp'] = $r['masp'];
            $data[$i]['loai'] = $r['loai'];
            $data[$i]['hangsx'] = $r['hangsx']];
            $data[$i]['tensp'] = $r['tensp'];
            $data[$i]['img'] = $r['img'];
            $data[$i]['gia'] = $r['gia'];
            $data[$i]['nx'] = $r['nx'];
            $i += 1;
        }
    }
}
print json_encode($data);


问:
How to append value to an array keeping old value intact in Javascript?
Google visualization API requires arrays like this:

```<code>var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);
</code>```

I have separately array of columns

```<code>var columns = ['Copper', 'Copper', 'Gold', 'Gold'];
</code>```

for values

```<code>var values = [8.94, 10.49, 19.30, 21.45];
</code>```

and for colors

```<code>var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];
</code>```

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.

答:
Using Array#map.

var columns = ['Copper', 'Copper', 'Gold', 'Gold'],
    values = [8.94, 10.49, 19.30, 21.45],
    styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'],
    res = columns.map((v,i) => [v, values[i], styles[i]]),
    result = [['Element', 'Density', { role: 'style' }], ...res];
    console.log(result);```

Body:
Google visualization API requires arrays like this:

var data = google.visualization.arrayToDataTable([
         ['Element', 'Density', { role: 'style' }],
         ['Copper', 8.94, '#b87333'],            // RGB value
         ['Copper', 10.49, 'silver'],            // English color name
         ['Gold', 19.30, 'gold'],
         ['Gold', 21.45, 'color: #e5e4e2' ], // CSS-style declaration
      ]);

I have separately array of columns

var columns = ['Copper', 'Copper', 'Gold', 'Gold'];

for values

var values = [8.94, 10.49, 19.30, 21.45];

and for colors

var styles = ['#b87333', 'silver', 'gold', 'color: #e5e4e2'];

Am I really in need to write multilevel loop with multiple conditions to build this array? Or there are simpler ways?

I can't push because arrays should be intact.


问:
How to inject config properties in Spring Boot to Spring Retry annotation?
In spring boot application, I define some config properties in yaml file as below.

```<code>my.app.maxAttempts = 10
my.app.backOffDelay = 500L
</code>```

And an example bean

```<code>@ConfigurationProperties(prefix = "my.app")
public class ConfigProperties {
  private int maxAttempts;
  private long backOffDelay;

  public int getMaxAttempts() {
    return maxAttempts;
  }

  public void setMaxAttempts(int maxAttempts) {
    this.maxAttempts = maxAttempts;
  }

  public void setBackOffDelay(long backOffDelay) {
    this.backOffDelay = backOffDelay;
  }

  public long getBackOffDelay() {
    return backOffDelay;
  }
</code>```

How can I inject the values of my.app.maxAttempts and my.app.backOffdelay to Spring Retry annotation? In the example below, I want to replace the value 10 of maxAttempts and 500Lof backoff value with the corresponding references of config properties.

```<code>@Retryable(maxAttempts=10, include=TimeoutException.class, backoff=@Backoff(value = 500L))
</code>```

答:
Staring from spring-retry-1.2.0 we can use configurable properties in @Retryable annotation.

Use "maxAttemptsExpression", Refer the below code for usage,

```<code> @Retryable(maxAttemptsExpression = "#{${my.app.maxAttempts}}",
 backoff = @Backoff(delayExpression = "#{${my.app. backOffDelay}}"))
</code>```

It will not work if you use any version less than 1.2.0.Also you don't require any configurable property classes.

Body:
In spring boot application, I define some config properties in yaml file as below.

my.app.maxAttempts = 10
my.app.backOffDelay = 500L

And an example bean

@ConfigurationProperties(prefix = "my.app")
public class ConfigProperties {
  private int maxAttempts;
  private long backOffDelay;

  public int getMaxAttempts() {
    return maxAttempts;
  }

  public void setMaxAttempts(int maxAttempts) {
    this.maxAttempts = maxAttempts;
  }

  public void setBackOffDelay(long backOffDelay) {
    this.backOffDelay = backOffDelay;
  }

  public long getBackOffDelay() {
    return backOffDelay;
  }

How can I inject the values of my.app.maxAttempts and my.app.backOffdelay to Spring Retry annotation? In the example below, I want to replace the value 10 of maxAttempts and 500Lof backoff value with the corresponding references of config properties.

@Retryable(maxAttempts=10, include=TimeoutException.class, backoff=@Backoff(value = 500L))

Body:
Staring from spring-retry-1.2.0 we can use configurable properties in @Retryable annotation.

Use "maxAttemptsExpression", Refer the below code for usage,

 @Retryable(maxAttemptsExpression = "#{${my.app.maxAttempts}}",
 backoff = @Backoff(delayExpression = "#{${my.app. backOffDelay}}"))

It will not work if you use any version less than 1.2.0.Also you don't require any configurable property classes.


问:
WordPress - Code Snippet plugin
I am working on a new Wordpress blog and it's very important to have code snippets in it.

So to highlight the code snippet I downloaded a Code Snippet plugin from https://wordpress.org/plugins/codesnippet-20/

Now, everything is screwed up. Below is the error when I access the site.

Warning: require_once(geshi.php): failed to open stream:

No such file or directory in /home1/jamburster/public_html/wp-content/plugins/codesnippet-20/codesnippet.php on line 126

```<code>Fatal error: require_once(): Failed opening required 'geshi.php'
(include_path='.:/opt/php56/lib/php:/home1/jamburster/public_html//wp-content/plugins/codesnippet/lib:/home1/jamburster/public_html//wp-content/plugins/codesnippet/lib/PEAR')
in /home1/jamburster/public_html/wp-content/plugins/codesnippet-20/codesnippet.php on line 126
</code>```

Here is what I did.
1. Downloaded the archive from https://wordpress.org/plugins/codesnippet-20/
2. Uploaded the plugin WordPress -> Plugins -> Add Plugin. Browsed the downloaded one and clicked on upload.
3. Activated the plugin.

Can anyone please help.

答:
Ok, so it looks to me like the plugin is having trouble finding a file called geshi.php. I just downloaded the plugin and activated it in my WordPress admin dashboard and I got the same error. So this isn't specific to you. One thing to note is that this plugin is not currently being maintained.

"This plugin hasn’t been updated in over 2 years. It may no longer be maintained or supported and may have compatibility issues when used
  with more recent versions of WordPress."

However, I believe I have a fix for you. Go into your plugin and open the codesnippet.php file. Go to line 126 and replace that line with this:

```<code>require_once('/lib/geshi.php');
</code>```

It looks like the directory structure of the plugin got changed without the necessary changes being made in the code base. I just tried this change on my machine and I am now able to activate the plugin without WordPress crashing. I haven't tried to use it, though.

Title: WordPress - Code Snippet plugin

Body:
I am working on a new Wordpress blog and it's very important to have code snippets in it.

So to highlight the code snippet I downloaded a Code Snippet plugin from https://wordpress.org/plugins/codesnippet-20/

Now, everything is screwed up. Below is the error when I access the site.

Warning: require_once(geshi.php): failed to open stream:

No such file or directory in /home1/jamburster/public_html/wp-content/plugins/codesnippet-20/codesnippet.php on line 126

Fatal error: require_once(): Failed opening required 'geshi.php'
(include_path='.:/opt/php56/lib/php:/home1/jamburster/public_html//wp-content/plugins/codesnippet/lib:/home1/jamburster/public_html//wp-content/plugins/codesnippet/lib/PEAR')
in /home1/jamburster/public_html/wp-content/plugins/codesnippet-20/codesnippet.php on line 126

Here is what I did.
1. Downloaded the archive from https://wordpress.org/plugins/codesnippet-20/
2. Uploaded the plugin WordPress -> Plugins -> Add Plugin. Browsed the downloaded one and clicked on upload.
3. Activated the plugin.

Can anyone please help.

Body:
Ok, so it looks to me like the plugin is having trouble finding a file called geshi.php. I just downloaded the plugin and activated it in my WordPress admin dashboard and I got the same error. So this isn't specific to you. One thing to note is that this plugin is not currently being maintained.

"This plugin hasn’t been updated in over 2 years. It may no longer be maintained or supported and may have compatibility issues when used
  with more recent versions of WordPress."

However, I believe I have a fix for you. Go into your plugin and open the codesnippet.php file. Go to line 126 and replace that line with this:

require_once('/lib/geshi.php');

It looks like the directory structure of the plugin got changed without the necessary changes being made in the code base. I just tried this change on my machine and I am now able to activate the plugin without WordPress crashing. I haven't tried to use it, though.


答: You make mistake. You should swap variable data with r inner loop, but probably than also will works unpropely. write in while loop $data [] = $r; </p>

Title: JSON encoding not working


问:
NoReverseMatch in Django; views and urls are properly defined
I am currently working on a website and I am receiving an error that is driving me up a wall. I have the following url defined in urls.py.

```<code>urlpatterns = [
    url(r'^', views.homeFeed, name='home'),
    url(r'^posts/(?P<uid>[\w+])$', views.discussPostView, name='post')
    ]
</code>```

I then have the following code defining views.discussPostView.

```<code>def discussPostView(request, **kwargs):
    if request.method == 'GET':
        print(kwargs['uid'])
        post = get_object_or_404(DiscussPost, uid=kwargs['uid'])
        return render(request, 'discuss/post.html', {"post": post})
    if request.method == 'POST':
        reply = DiscussReply.objects.create(
            by=request.user,
            content=request.POST['reply'])
        reply.save()
        reply_to = DiscussPost.objects.get(pk=request.POST['post_id'])
        reply_to.replies.add(reply)
        reply_to.save()
        return HttpResponseRedirect(request.get_full_path())
</code>```

However, when I try to create a post on the site or access a post with a certain uid, I receive this error;

```<code>Reverse for 'post' with arguments '()'
and keyword arguments '{u'uid': u'CHacFvE_'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w+])$']
</code>```

I literally have no idea what's wrong with my code. I am a bit rusty on python so I might be missing some obvious pointers, but any pointers in the right direction would be helpful. Thank you!

Full error stack:

```<code>Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/ubuntu/workspace/discuss/views.py", line 15, in homeFeed
    "feeds": [DiscussPost.getFeed(request), DiscussPost.getNewPosts()]})
  File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py", line 67, in render
    template_name, context, request=request, using=using)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 97, in render_to_string
    return template.render(context, request)
  File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py", line 95, in render
    return self.template.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 206, in render
    return self._render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 197, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 173, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 197, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 69, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 326, in render
    return nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 220, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 220, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 513, in render
    six.reraise(*exc_info)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 499, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 600, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 508, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns))
NoReverseMatch: Reverse for 'post' with arguments '()' and keyword arguments '{u'uid': u'-lTmOw__'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w]+)$']
</code>```

答:
What is the valid characters in the Post.uid? Your question has two examples u'CHacFvE_' from the error message and {u'uid': u'-lTmOw__'} in the stack trace.

If you want both underscores and dashes to be valid in uid, you must change the regex.

```<code>^posts/(?P<uid>[-\w]+)$
</code>```

explanation: https://regex101.com/r/1E2WVY/1

Body:
I am currently working on a website and I am receiving an error that is driving me up a wall. I have the following url defined in urls.py.

urlpatterns = [
    url(r'^', views.homeFeed, name='home'),
    url(r'^posts/(?P<uid>[\w+])$', views.discussPostView, name='post')
    ]

I then have the following code defining views.discussPostView.

def discussPostView(request, **kwargs):
    if request.method == 'GET':
        print(kwargs['uid'])
        post = get_object_or_404(DiscussPost, uid=kwargs['uid'])
        return render(request, 'discuss/post.html', {"post": post})
    if request.method == 'POST':
        reply = DiscussReply.objects.create(
            by=request.user,
            content=request.POST['reply'])
        reply.save()
        reply_to = DiscussPost.objects.get(pk=request.POST['post_id'])
        reply_to.replies.add(reply)
        reply_to.save()
        return HttpResponseRedirect(request.get_full_path())

However, when I try to create a post on the site or access a post with a certain uid, I receive this error;

Reverse for 'post' with arguments '()'
and keyword arguments '{u'uid': u'CHacFvE_'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w+])$']

I literally have no idea what's wrong with my code. I am a bit rusty on python so I might be missing some obvious pointers, but any pointers in the right direction would be helpful. Thank you!

Full error stack:

Traceback (most recent call last):
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 149, in get_response
    response = self.process_exception_by_middleware(e, request)
  File "/usr/local/lib/python2.7/dist-packages/django/core/handlers/base.py", line 147, in get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "/home/ubuntu/workspace/discuss/views.py", line 15, in homeFeed
    "feeds": [DiscussPost.getFeed(request), DiscussPost.getNewPosts()]})
  File "/usr/local/lib/python2.7/dist-packages/django/shortcuts.py", line 67, in render
    template_name, context, request=request, using=using)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader.py", line 97, in render_to_string
    return template.render(context, request)
  File "/usr/local/lib/python2.7/dist-packages/django/template/backends/django.py", line 95, in render
    return self.template.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 206, in render
    return self._render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 197, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 173, in render
    return compiled_parent._render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 197, in _render
    return self.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/loader_tags.py", line 69, in render
    result = block.nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 326, in render
    return nodelist.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 988, in render
    bit = node.render_annotated(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 220, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 220, in render
    nodelist.append(node.render_annotated(context))
  File "/usr/local/lib/python2.7/dist-packages/django/template/base.py", line 955, in render_annotated
    return self.render(context)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 513, in render
    six.reraise(*exc_info)
  File "/usr/local/lib/python2.7/dist-packages/django/template/defaulttags.py", line 499, in render
    url = reverse(view_name, args=args, kwargs=kwargs, current_app=current_app)
  File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 600, in reverse
    return force_text(iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)))
  File "/usr/local/lib/python2.7/dist-packages/django/core/urlresolvers.py", line 508, in _reverse_with_prefix
    (lookup_view_s, args, kwargs, len(patterns), patterns))
NoReverseMatch: Reverse for 'post' with arguments '()' and keyword arguments '{u'uid': u'-lTmOw__'}' not found. 1 pattern(s) tried: [u'discuss/posts/(?P<uid>[\\w]+)$']

Body:
What is the valid characters in the Post.uid? Your question has two examples u'CHacFvE_' from the error message and {u'uid': u'-lTmOw__'} in the stack trace.

If you want both underscores and dashes to be valid in uid, you must change the regex.

^posts/(?P<uid>[-\w]+)$

explanation: https://regex101.com/r/1E2WVY/1


问:
Getting a specific value from a webpage from scraped HTML
Curerntly using Java to scrape the HTML code from this page http://counter.onlineclock.net/

I want to get the value from the counter, but this is unique for each version of the webpage, that is, if its open in different browsers or for different people it will be a different value.

Because of this, when I scrape the HTML, the value that I am looking for is just blank. I am wondering if there is any way at all for me to get the current value I am looking for.

For example, if I have the counter at 4 I would like to be able to get that value. It does not have to be in java, any language or any way.

答: JSoup is a great library for scraping data out of a web page. There are a lot of good examples of its usage on the web</p>


问:
Values change when printing from dynamicly allocated memory
Ok quick intro. I'm doing a homework on dynamically allocated memory. We need to simulate a CPU using structs and dyn. al. memory. I was testing if my stack functions properly and doesn't overflow. The stack is supposed to be 2 KiB, didn't overflow, but while printing the numbers, few addresses contain other numbers that i didn't put in. Ill just copy it here, and get rid of instruction lists, registers and such, that are not a problem and would make this long.

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

struct cpu {
    struct stack* memory;
};

struct stack {
    int32_t* values;
    int32_t* top;
};

void stackInit(struct stack* stack)
{
    stack->values = malloc(2048);
    stack->top = NULL;
}

void cpuInit (struct cpu* cpu)
{
    stackInit(cpu->memory); //initialize stack
}

void stackPush(struct stack* stack, int32_t value)
{
    if (stack->top == NULL){
        stack->top = stack->values;
        *(stack->top) = value;
    }
    else if (stack->top + sizeof(int32_t) < stack->values + 2048){
        stack->top += sizeof(int32_t);
        *(stack->top) = value;
    }
}

void cpuDebug(const struct cpu* cpu)
{
    int32_t* auxpt = cpu->memory->top;

    if (cpu->memory->top != NULL)
        for (int32_t i = 0; auxpt >= cpu->memory->values; i++){

            printf("Value on the addr %d\n", *auxpt);
            printf("Address of auxpt: %p\n", ( void * )auxpt );
            auxpt -= sizeof(int32_t);
        }

    printf("\n");
}

int main()
{
    struct cpu Cpu;

    cpuInit(&Cpu);

    for (int32_t i = 0; i < 550; i++){
        stackPush(Cpu.memory,i);
    }

    cpuDebug(&Cpu);

    return 0;
}
</code>```

And the output looks like this :

```<code>Value on the addr 133
Address of auxpt: 0x562640529880
Value on the addr 10
Address of auxpt: 0x562640529870
Value on the addr 544108298
Address of auxpt: 0x562640529860
Value on the addr 2016419898
Address of auxpt: 0x562640529850
Value on the addr 1919181889
Address of auxpt: 0x562640529840
Value on the addr 128
Address of auxpt: 0x562640529830
Value on the addr 127
</code>```

Any ideas why is this happening?
Thanks in advance

答:
Your struct cpu has an associated struct stack, but that stack is not part of the struct cpu; the cpu merely holds a pointer to a separate stack.  You never initialize that pointer, nor indeed reserve any memory for the wanted stack.  In particular, your cpuInit() function does not do this, and your stackInit() function depends on it already having been done.

Overall, supposing that each cpu requires only one stack for its lifetime, you would be better off making the stack an integral part of the cpu, so that you don't need to worry about such allocation issues:

```<code>struct cpu {
    struct stack memory;  // not a pointer
};
</code>```

Having done that, you'll need to change the syntax with which you access the stack's members via the cpu, and you'll need to watch out for other semantic differences, but you can always get a pointer to the stack where needed (such as to pass to stackInit()) via the & operator.

Body:
Ok quick intro. I'm doing a homework on dynamically allocated memory. We need to simulate a CPU using structs and dyn. al. memory. I was testing if my stack functions properly and doesn't overflow. The stack is supposed to be 2 KiB, didn't overflow, but while printing the numbers, few addresses contain other numbers that i didn't put in. Ill just copy it here, and get rid of instruction lists, registers and such, that are not a problem and would make this long.

#include <stdlib.h>
#include <stdio.h>
#include <stdint.h>

struct cpu {
    struct stack* memory;
};

struct stack {
    int32_t* values;
    int32_t* top;
};

void stackInit(struct stack* stack)
{
    stack->values = malloc(2048);
    stack->top = NULL;
}

void cpuInit (struct cpu* cpu)
{
    stackInit(cpu->memory); //initialize stack
}

void stackPush(struct stack* stack, int32_t value)
{
    if (stack->top == NULL){
        stack->top = stack->values;
        *(stack->top) = value;
    }
    else if (stack->top + sizeof(int32_t) < stack->values + 2048){
        stack->top += sizeof(int32_t);
        *(stack->top) = value;
    }
}

void cpuDebug(const struct cpu* cpu)
{
    int32_t* auxpt = cpu->memory->top;

    if (cpu->memory->top != NULL)
        for (int32_t i = 0; auxpt >= cpu->memory->values; i++){

            printf("Value on the addr %d\n", *auxpt);
            printf("Address of auxpt: %p\n", ( void * )auxpt );
            auxpt -= sizeof(int32_t);
        }

    printf("\n");
}

int main()
{
    struct cpu Cpu;

    cpuInit(&Cpu);

    for (int32_t i = 0; i < 550; i++){
        stackPush(Cpu.memory,i);
    }

    cpuDebug(&Cpu);

    return 0;
}

And the output looks like this :

Value on the addr 133
Address of auxpt: 0x562640529880
Value on the addr 10
Address of auxpt: 0x562640529870
Value on the addr 544108298
Address of auxpt: 0x562640529860
Value on the addr 2016419898
Address of auxpt: 0x562640529850
Value on the addr 1919181889
Address of auxpt: 0x562640529840
Value on the addr 128
Address of auxpt: 0x562640529830
Value on the addr 127

Any ideas why is this happening?
Thanks in advance

Body:
Your struct cpu has an associated struct stack, but that stack is not part of the struct cpu; the cpu merely holds a pointer to a separate stack.  You never initialize that pointer, nor indeed reserve any memory for the wanted stack.  In particular, your cpuInit() function does not do this, and your stackInit() function depends on it already having been done.

Overall, supposing that each cpu requires only one stack for its lifetime, you would be better off making the stack an integral part of the cpu, so that you don't need to worry about such allocation issues:

struct cpu {
    struct stack memory;  // not a pointer
};

Having done that, you'll need to change the syntax with which you access the stack's members via the cpu, and you'll need to watch out for other semantic differences, but you can always get a pointer to the stack where needed (such as to pass to stackInit()) via the & operator.


问:
How to set java system properties globally on OS X?

Short story

I need a system level way to set the java.awt.headless property to true for all java invocations. That is, using -Djava.awt.headless=true is not an option, since java is being invoked from places I don't have access to (e.g. from within another tool written in Java/C/etc.)

Long story

I'm using a bunch of tools written in Java (specifically Adobe's Air ADT) that rely on AWT classes. When I run these tools on the console they work fine. But when I run them from an SSH session they fail with java.lang.InternalError: Can't connect to window server - not enough permissions. Googling around I found that setting java.awt.headless to true will fix the problem. It doesn't, and that's because ADT itself spawns children Java processes without -Djava.awt.headless=true.

Is there any system-level way to ensure this property is set whenever Java is invoked? Maybe some system awt property file or equivalent?

Worst case scenario I could try replacing /usr/bin/java with a shell script that adds this argument to "$@" but I'm hoping to avoid that. (Update: Just to ensure my theory is right, tried this shell script hack and it does solve the problem. Just hoping for a cleaner solution)

答:
It looks like support for JAVA_TOOL_OPTIONS environment variable was added to the Sun/Oracle JVM at least by Java 6.  It is described in Java 8 documentation.  I haven't tested but it appears to be in the OpenJDK too.  This appears to be a more standardized solution than the other answers here.

I was able to solve the issue I encountered with:

JAVA_TOOL_OPTIONS=-Djava.awt.headless=true ant ...

This successfully propagated the property to Gradle build scripts (./gradlew) called from Ant.  By comparison ant -Djava.awt.headless=true ... did not propagate the property to subprocesses.  Found this solution originally described in a Gradle-related gist on github.


问:
How to access arguments between chained promise
I have the below code:

```<code>vm.testService.getUser(id, name)
.then((resultA) => {
    return vm.testService.getUserInfo(id, name);
})
.then(() => {
    // will process resultA from first .then
});
</code>```

I need to access resultA on the second .then.
Thanks in advance.

答:
One way is to assign the response of the first then to a variable and access that variable in the second then

check the code snippet

let response

vm.testService.getUser(id, name)
  .then((resultA) => {
    response = resultA
    return vm.testService.getUserInfo(id, name);
  })
  .then(() => {
    console.log(response)
    // will process resultA from first .then
  });```

Body:
I have the below code:

vm.testService.getUser(id, name)
.then((resultA) => {
    return vm.testService.getUserInfo(id, name);
})
.then(() => {
    // will process resultA from first .then
});

I need to access resultA on the second .then.
Thanks in advance.


问:
Trying to do a calculation with data from a date and the data from the day before
I have made a report in which i have grouped by day.

I am trying to calculate the fuel consumption per plant expressed in liters per hour.

To do this you take the

```<code>[LitersIssued]Today/[Hourmeter]Today-[Hourmeter]Yesterday
</code>```

How would i get the value of Hourmeter for Yesterday(or the last date when the plant ran)

Example of Table:

答:
Something like this will work:

```<code>[LitersIssued]/([Hourmeter]-DLookup("Hourmeter","[YourTableName]","PlantNumber=" & [PlantNumber] & " AND Dates=#" & FormatDateTime(DateAdd("d",-1,[Dates]),2) & "#")))))
</code>```

Not the most efficient way to do it and probably needs some null values and division by zero protection but pretty straightforward and can be included in an Access SQL statement.

Body:
I have made a report in which i have grouped by day.

I am trying to calculate the fuel consumption per plant expressed in liters per hour.

To do this you take the

[LitersIssued]Today/[Hourmeter]Today-[Hourmeter]Yesterday

How would i get the value of Hourmeter for Yesterday(or the last date when the plant ran)

Example of Table:

Body:
Something like this will work:

[LitersIssued]/([Hourmeter]-DLookup("Hourmeter","[YourTableName]","PlantNumber=" & [PlantNumber] & " AND Dates=#" & FormatDateTime(DateAdd("d",-1,[Dates]),2) & "#")))))

Not the most efficient way to do it and probably needs some null values and division by zero protection but pretty straightforward and can be included in an Access SQL statement.


问:
Datagridview filter with numbers saved as string
I have a datagrid filled that shows yahoo finance data. The data is loaded via a csv. The datagrid has columns with text and numbers. All data, text and numbers, are shown in string. Now I want to filter one a column that has numbers by the size of the number.

For example: the column has the numbers 1, 2, 3, 4, 5, 6
Now I just want to see all numbers bigger then 3.

Is there any function or posibility to filter numbers that are saved as string? If yes how can i update the datagrid that it only shows me the row with the nubers after filtering?

答:
```<code>while ((item = stream_reader.ReadLine()) != null)
        {
            myArr = item.Split(',');
            if (a == 1)
            {
                for (int i = 1; i < myArr.Length; i++)
                {
                    if (i != 5)
                    {
                        string var;
                        string zahl;
                        var = myArr[i];
                        zahl = stringToDoubleToString(var);
                        myArr[i] = zahl;
                    }
                }
            }
            a = 1;
            dataset.Tables["FinData"].Rows.Add(myArr);
</code>```


问:
Each subtree sum in a binary tree in O(N) time and O(1) space?
Given a binary tree, I want to return the maximum sum subtree's root.

Maximum Subtree: A subtree of the tree, whose sum of all its nodes is greater than that of the any other sub tree.

Edit: Node value is an integer.

I can do the following which takes O(n^2).

Calculate the sum of all nodes in the left subtree

Calculate the sum of all nodes in the right subtree

If sum of left subtree and right subtree and value of the root is greater than the current maximum sum, root is stored in the result

call this function recursively , with left subtree as root

call this function recursively , with right subtree as root.
This will take O(n^2).

I can change it to a bottom up approach and use a hashmap to store the node to sum mapping which will make it O(N) but it will take O(N) space.

Is there any approach/method, that is O(N) time and O(1) space ?

答:
That's almost your solution, but takes O(n) and O(h) memory. You just visit each node only once.</p>

```<code>calculateSum(vertex):
    if not vertex:
        return 0
    sum = calculateSum(left) + calculateSum(right) + vertex.value
    if (sum > max)
        max = sum
    return sum
</code>```

Body:
That's almost your solution, but takes O(n) and O(h) memory. You just visit each node only once.

calculateSum(vertex):
    if not vertex:
        return 0
    sum = calculateSum(left) + calculateSum(right) + vertex.value
    if (sum > max)
        max = sum
    return sum


问:
Estimote Beacon Android SDK
I'm developing an Android app that uses the Estimote SDK available on GitHub.

But I'm still not able to use my Android device (5.0.1) as advertiser to be discovered by other devices that use the Estimote app. I've tried to use QuickBeacon by Radius Networks, Inc. but it showed a message saying that my OS on my device does not support Bluetooth LE advertising.

Please can you help me with that?

答:
Not all Android devices supports BLE advertisement, you can check it using this callback. Also you can simulate Estimote's iBeacon (or any other beacons) using simple Linux command from Bluez lib:

```<code>  UUID="B9 40 7F 30 F5 F8 46 6E AF F9 25 55 6B 57 FE 6D"
    MAJOR="00 01"
    MINOR="00 02"
</code>```

sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 $UUID $MAJOR $MINOR C82.

Title: Estimote Beacon Android SDK

Body:
Not all Android devices supports BLE advertisement, you can check it using this callback. Also you can simulate Estimote's iBeacon (or any other beacons) using simple Linux command from Bluez lib:

  UUID="B9 40 7F 30 F5 F8 46 6E AF F9 25 55 6B 57 FE 6D"
    MAJOR="00 01"
    MINOR="00 02"

sudo hcitool -i hci0 cmd 0x08 0x0008 1E 02 01 1A 1A FF 4C 00 02 15 $UUID $MAJOR $MINOR C82.


答:
Yes, you can do it in O(n) with O(h) space if you calculate the sum on the fly. while iterating the tree. (In here, h is the maximal height of the tree, which is the size of the recursion stack).

Pseudo code:

```<code>TreeSum(v):
  if (v == null):
    return 0
  v_sum = TreeSum(v.left) + TreeSum(v.right) + v.value
  # max_sum is some global space variable holding the max_sum.
  # you hold only once such variable.
  if v_sum > max_sum:
    max_sum = v_sum
  return v_sum
</code>```

When you are done, max_value hold the value of the maximal such sum.

If you also need the node itself, hold an extra variable which is a pointer to the relevant node, and is modified together with max_sum.

The idea is to do a post order traversal on the tree. First calculate the sum of each subtree, and only then - calculate the value of the root.

While calculating the sum of each subtree, also modify max_sum when you find a new "best" subtree.

Title: Each subtree sum in a binary tree in O(N) time and O(1) space?

Body:
Given a binary tree, I want to return the maximum sum subtree's root.

Maximum Subtree: A subtree of the tree, whose sum of all its nodes is greater than that of the any other sub tree.

Edit: Node value is an integer.

I can do the following which takes O(n^2).

Calculate the sum of all nodes in the left subtree

Calculate the sum of all nodes in the right subtree

If sum of left subtree and right subtree and value of the root is greater than the current maximum sum, root is stored in the result

call this function recursively , with left subtree as root

call this function recursively , with right subtree as root.
This will take O(n^2).

I can change it to a bottom up approach and use a hashmap to store the node to sum mapping which will make it O(N) but it will take O(N) space.

Is there any approach/method, that is O(N) time and O(1) space ?

Body:
Yes, you can do it in O(n) with O(h) space if you calculate the sum on the fly. while iterating the tree. (In here, h is the maximal height of the tree, which is the size of the recursion stack).

Pseudo code:

TreeSum(v):
  if (v == null):
    return 0
  v_sum = TreeSum(v.left) + TreeSum(v.right) + v.value
  # max_sum is some global space variable holding the max_sum.
  # you hold only once such variable.
  if v_sum > max_sum:
    max_sum = v_sum
  return v_sum

When you are done, max_value hold the value of the maximal such sum.

If you also need the node itself, hold an extra variable which is a pointer to the relevant node, and is modified together with max_sum.

The idea is to do a post order traversal on the tree. First calculate the sum of each subtree, and only then - calculate the value of the root.

While calculating the sum of each subtree, also modify max_sum when you find a new "best" subtree.


问:
c++ save and load game with pointers in structs
I know I can use:

```<code>MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));
</code>```

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?

答:
Boost has a serialization library, with built in support for deep pointer save and restore, and proper serialization of pointers to shared data.

It's a rather extensive library, but you don't need to write that much code to start using it in your own projects. Well worth the learning effort for anything but the simplest serialization requirements in my opinion.

Body:
I know I can use:

MyGame  game; // the game object
//

ofstream out("mygame.bin", ios::binary);
out.write((char *)&game, sizeof(MyGame));

to save and load the game, but what if I have pointers inside MyGame structure? will the pointers just be saved but not the data it points to?

and: how to solve this?


问:
Fastest way to compare 2 lists objects
I allow a user to download some data to csv. They can then edit some columns and then upload it back. I need a speed efficient way to compare certain columns between like objects to see what changed.

Currently I pull the original data from the DB and make it a list so it's all in memory. There is about 100k items so it's not that bad. That part takes less than a second. Then I load in the csv file and put it to list. Both lists have the same class type.

Then I loop over the csv data (as they probably removed some rows which they didn't change but they could still have changed a lot of rows). For each row in the csv list I query the list that came from the DB to find that object. Now I have the csv object and the object from the database as the same structure. Then I run it through a custom object compare function that looks at certain columns to see if anything changed.

If something did change I have to validate what they entered is a valid value by query another reference list for that column. If it's not valid I write it out to an exceptions list. At the end if there are no exceptions I save to db. If there are exceptions I don't save anything and I show them the list of errors.

The detail compare provides a list of columns and the old vs new values that changed. I need this to query the reference list to make sure the new value is valid before I make the change. It's fairly inefficient but it gives great detail to the user about what may be an issue with an upload which is very valuable.

This is very slow. I'm looking for ways to speed it up while still being able to give the user detailed information about why it may have failed so they can correct it.

```<code>// get all the new records from the csv
            var newData = csv.GetRecords<MyTable>().ToArray();

            // select all data from database to list
            var origData = ctx.MyTable.Select(s => s).ToList();

            // look for any changes in the new data and update the database. note we are looping over the new data so if they removed some data from the csv file it just won't loop over those and they won't change
            foreach (var d in newData)
            {
                // find data so we can compare between new (csv) and current (from db) to see what possibly changed
                var oData = (from o in origData
                             where o.id == d.id
                             select o).FirstOrDefault();

                // only the columns in the updatableColumns list are compared
                var diff = d.DetailedCompare(oData, comparableColumns.ToList());
                if (diff.Count > 0)
                {
                    // even though there are differences between the csv record and db record doesn't mean what the user input is valid. only existing ref data is valid and needs to be checked before a change is made
                    bool changed = false;

                    // make a copy of this original data and we'll check after if we actually were able to make a change to it (was the value provided valid)
                    var data = CopyRecord(oData);

                    // update this record's data fields that have changed with the new data
                    foreach (var v in diff)
                    {
                        // special check for setting a value to NULL as its always valid to do this but wouldn't show up in ref data to pass the next check below
                        if (v.valA == null)
                        {
                            oData.GetType().GetProperty(v.Prop).SetValue(oData, v.valA);
                            oData.UpdatedBy = user;
                            oData.UpdatedDate = DateTime.Now;
                            changed = true;
                        }
                        // validate that the value for this column is in the ref table before allowing an update. note exception if not so we can tell the user
                        else if (refData[v.Prop].Where(a => a.value == v.valA.ToString()).FirstOrDefault() != null)
                        {
                            // update the current objects values with the new objects value as it changed and is a valid value based on the ref data defined for that column
                            oData.GetType().GetProperty(v.Prop).SetValue(oData, v.valA);
                            oData.UpdatedBy = user;
                            oData.UpdatedDate = DateTime.Now;
                            changed = true;
                        }
                        else
                        {
                            // the value provided isn't valid for this column so note this to tell the user
                            exceptions.Add(string.Format("Error: ID: {0}, Value: '{1}' is not valid for column [{2}]. Add the reference data if needed and re-import.", d.id, v.valA, v.Prop));
                        }
                    }

                    // we only need to reattach and save off changes IF we actually changed something to a valid ref value and we had no exceptions for this record
                    if (changed && exceptions.Count == 0)
                    {
                        // because our current object was in memory we will reattached it to EF so we can mark it as changed and SaveChanges() will write it back to the DB
                        ctx.MyTable.Attach(oData);
                        ctx.Entry(oData).State = EntityState.Modified;

                        // add a history record for the change to this product
                        CreateHistoryRecord(data, user);
                    }
                }
            }

            // wait until the very end before making DB changed. we don't save anything if there are exceptions or nothing changed
            if (exceptions.Count == 0)
            {
                ctx.SaveChanges();
            }
</code>```

答: One thing to consider is having asynchronous compares and or asynchronous if (diff,Count > 0) at least the latter assuming that there are a few random changes why wait for all the copying and reflection. Put it in a seperatge function and have run parallel.

Title: Fastest way to compare 2 lists objects

Body:
I allow a user to download some data to csv. They can then edit some columns and then upload it back. I need a speed efficient way to compare certain columns between like objects to see what changed.

Currently I pull the original data from the DB and make it a list so it's all in memory. There is about 100k items so it's not that bad. That part takes less than a second. Then I load in the csv file and put it to list. Both lists have the same class type.

Then I loop over the csv data (as they probably removed some rows which they didn't change but they could still have changed a lot of rows). For each row in the csv list I query the list that came from the DB to find that object. Now I have the csv object and the object from the database as the same structure. Then I run it through a custom object compare function that looks at certain columns to see if anything changed.

If something did change I have to validate what they entered is a valid value by query another reference list for that column. If it's not valid I write it out to an exceptions list. At the end if there are no exceptions I save to db. If there are exceptions I don't save anything and I show them the list of errors.

The detail compare provides a list of columns and the old vs new values that changed. I need this to query the reference list to make sure the new value is valid before I make the change. It's fairly inefficient but it gives great detail to the user about what may be an issue with an upload which is very valuable.

This is very slow. I'm looking for ways to speed it up while still being able to give the user detailed information about why it may have failed so they can correct it.

// get all the new records from the csv
            var newData = csv.GetRecords<MyTable>().ToArray();

            // select all data from database to list
            var origData = ctx.MyTable.Select(s => s).ToList();

            // look for any changes in the new data and update the database. note we are looping over the new data so if they removed some data from the csv file it just won't loop over those and they won't change
            foreach (var d in newData)
            {
                // find data so we can compare between new (csv) and current (from db) to see what possibly changed
                var oData = (from o in origData
                             where o.id == d.id
                             select o).FirstOrDefault();

                // only the columns in the updatableColumns list are compared
                var diff = d.DetailedCompare(oData, comparableColumns.ToList());
                if (diff.Count > 0)
                {
                    // even though there are differences between the csv record and db record doesn't mean what the user input is valid. only existing ref data is valid and needs to be checked before a change is made
                    bool changed = false;

                    // make a copy of this original data and we'll check after if we actually were able to make a change to it (was the value provided valid)
                    var data = CopyRecord(oData);

                    // update this record's data fields that have changed with the new data
                    foreach (var v in diff)
                    {
                        // special check for setting a value to NULL as its always valid to do this but wouldn't show up in ref data to pass the next check below
                        if (v.valA == null)
                        {
                            oData.GetType().GetProperty(v.Prop).SetValue(oData, v.valA);
                            oData.UpdatedBy = user;
                            oData.UpdatedDate = DateTime.Now;
                            changed = true;
                        }
                        // validate that the value for this column is in the ref table before allowing an update. note exception if not so we can tell the user
                        else if (refData[v.Prop].Where(a => a.value == v.valA.ToString()).FirstOrDefault() != null)
                        {
                            // update the current objects values with the new objects value as it changed and is a valid value based on the ref data defined for that column
                            oData.GetType().GetProperty(v.Prop).SetValue(oData, v.valA);
                            oData.UpdatedBy = user;
                            oData.UpdatedDate = DateTime.Now;
                            changed = true;
                        }
                        else
                        {
                            // the value provided isn't valid for this column so note this to tell the user
                            exceptions.Add(string.Format("Error: ID: {0}, Value: '{1}' is not valid for column [{2}]. Add the reference data if needed and re-import.", d.id, v.valA, v.Prop));
                        }
                    }

                    // we only need to reattach and save off changes IF we actually changed something to a valid ref value and we had no exceptions for this record
                    if (changed && exceptions.Count == 0)
                    {
                        // because our current object was in memory we will reattached it to EF so we can mark it as changed and SaveChanges() will write it back to the DB
                        ctx.MyTable.Attach(oData);
                        ctx.Entry(oData).State = EntityState.Modified;

                        // add a history record for the change to this product
                        CreateHistoryRecord(data, user);
                    }
                }
            }

            // wait until the very end before making DB changed. we don't save anything if there are exceptions or nothing changed
            if (exceptions.Count == 0)
            {
                ctx.SaveChanges();
            }


问:
Swift 3 - device tokens are now being parsed as '32BYTES'
I just updated from Xcode 7 to the 8 GM and amidst the Swift 3 compatibility issues I noticed that my device tokens have stopped working. They now only read '32BYTES'.

```<code>    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print(deviceToken) // Prints '32BYTES'
    print(String(data: deviceToken , encoding: .utf8)) // Prints nil
}
</code>```

Before the update I was able to simply send the NSData to my server, but now I'm having a hard time actually parsing the token.

What am I missing here?

Edit: I just testing converting back to NSData and I'm seeing the expected results. So now I'm just confused about the new Data type.

```<code>    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print(deviceToken) // Prints '32BYTES'
    print(String(data: deviceToken , encoding: .utf8)) // Prints nil

    let d = NSData(data: deviceToken)
    print(d) // Prints my device token
}
</code>```

答:
```<code>func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

    let token = deviceToken.map({ String(format: "%02.2hhx", $0)}).joined()
     print("TOKEN: " + token)

}
</code>```

Body:
I just updated from Xcode 7 to the 8 GM and amidst the Swift 3 compatibility issues I noticed that my device tokens have stopped working. They now only read '32BYTES'.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print(deviceToken) // Prints '32BYTES'
    print(String(data: deviceToken , encoding: .utf8)) // Prints nil
}

Before the update I was able to simply send the NSData to my server, but now I'm having a hard time actually parsing the token.

What am I missing here?

Edit: I just testing converting back to NSData and I'm seeing the expected results. So now I'm just confused about the new Data type.

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data)
{
    print(deviceToken) // Prints '32BYTES'
    print(String(data: deviceToken , encoding: .utf8)) // Prints nil

    let d = NSData(data: deviceToken)
    print(d) // Prints my device token
}