问:
my result in email just display "resource id#7"
I need to send my code result to the mail.
If I write html code, its all displayed in my email, but if I write php code- its not displayed.

In my browser it works, but in my email it just displays "resource id#7".

```<code><?php

include_once("include.php");
include_once("p_bulan.php");
require_once('class.phpmailer.php');

$runSQL = "select a.id_client, a.nama_cpw, ifnull(a.tlp_mobile_cpw,'belum-diinput')tlp_mobile_cpw, ifnull(a.nama_cpp,'belum-diinput')nama_cpp, ifnull(a.tlp_mobile_cpp,'belum-diinput')tlp_mobile_cpp, a.tgl_rencana, b.tgl_janjiawal, b.tgl_janjiakhir, b.barang, b.keterangan, ifnull(c.nama,'-')nama
 from client a
 left join jadwal_fitting_new b on a.id_client=b.id_client
 left join pegawai c on a.id_pegawai=c.id_pegawai
 where a.id_client=b.id_client and b.tgl_janjiakhir BETWEEN '$tanggal' AND '$tanggal2'
order by id_client desc";

$mail  = new PHPMailer(); // defaults to using php "mail()"

$mail->IsSendmail(); // telling the class to use SendMail transport

$body  =

$res=mysql_query($runSQL);
//echo $runSQL;
while($rec=mysql_fetch_array($res))
{

    $ccc++;
    if ($ccc%2 > 0){ $color='#EBEFFA'; }else{ $color='#D7E0F4'; };
echo "<table><tr bgcolor=$color onmouseover=bgColor=\'#FDD0D8\' onmouseout=bgColor=\'$color\' valign=top>
    <td align='center'>".($ccc)."</td>

          <td align=center> $rec[nama_cpw] </td>
          <td align=center> $rec[tlp_mobile_cpw]</td>
          <td align=center> $rec[nama_cpp] </td>
          <td align=center> $rec[tlp_mobile_cpp] </td>
          <td align=center> $rec[tgl_rencana] </td>
          <td align=center> $rec[tgl_janjiawal] </td>
          <td align=center> $rec[tgl_janjiakhir] </td>
          <td> $rec[barang] </td>
          <td> $rec[keterangan] </td>
          <td> $rec[nama]</td>

</tr>";
}
echo "<tr bgcolor=$color onmouseover=bgColor=\'#FDD0D8\' onmouseout=bgColor=\'$color\' valign=top>

</tr>
</table>
</font>
</table></br>

<table align='center' width='1002' height='79' border='0'>
  <tr align='center' >
    <td height='23'>Dibuat oleh,</td>
    <td>Diperikasa oleh,</td>
  </tr>
  <tr>
    <td height='23'> </td>
    <td> </td>
    <td> </td>
    <td> </td>
  </tr>
  <tr align='center'>
    <td height='23'>(Admin Fitting)</td>
    <td>(KaBag. Gudang)</td>
  </tr>
</table>";

  $mail->AddReplyTo('admin@alfin.com', 'admin');
  $mail->AddAddress('alfin@gmail.com', 'zalfinm');
  $mail->SetFrom('admin@alfin.com', 'admin');
  $mail->AddReplyTo('admin@alfin.com', 'admin');
  $mail->Subject = 'test';
  $mail->AltBody = 'ini isi email'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML($body);

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

?>

   please help me
</code>```

答:
HTML code will be displayed if the content type header, is valid

```<code>'Content-type: text/html;'
</code>```

but the php code will not be displayed in the mail, you can try to put it in a string and add this before and after the php string

```<code>```

    // your code

```
</code>```

Body:
I need to send my code result to the mail.
If I write html code, its all displayed in my email, but if I write php code- its not displayed.

In my browser it works, but in my email it just displays "resource id#7".

<?php

include_once("include.php");
include_once("p_bulan.php");
require_once('class.phpmailer.php');

$runSQL = "select a.id_client, a.nama_cpw, ifnull(a.tlp_mobile_cpw,'belum-diinput')tlp_mobile_cpw, ifnull(a.nama_cpp,'belum-diinput')nama_cpp, ifnull(a.tlp_mobile_cpp,'belum-diinput')tlp_mobile_cpp, a.tgl_rencana, b.tgl_janjiawal, b.tgl_janjiakhir, b.barang, b.keterangan, ifnull(c.nama,'-')nama
 from client a
 left join jadwal_fitting_new b on a.id_client=b.id_client
 left join pegawai c on a.id_pegawai=c.id_pegawai
 where a.id_client=b.id_client and b.tgl_janjiakhir BETWEEN '$tanggal' AND '$tanggal2'
order by id_client desc";

$mail  = new PHPMailer(); // defaults to using php "mail()"

$mail->IsSendmail(); // telling the class to use SendMail transport

$body  =

$res=mysql_query($runSQL);
//echo $runSQL;
while($rec=mysql_fetch_array($res))
{

    $ccc++;
    if ($ccc%2 > 0){ $color='#EBEFFA'; }else{ $color='#D7E0F4'; };
echo "

    ".($ccc)."

           $rec[nama_cpw]
           $rec[tlp_mobile_cpw]
           $rec[nama_cpp]
           $rec[tlp_mobile_cpp]
           $rec[tgl_rencana]
           $rec[tgl_janjiawal]
           $rec[tgl_janjiakhir]
           $rec[barang]
           $rec[keterangan]
           $rec[nama]

";
}
echo "

    Dibuat oleh,
    Diperikasa oleh,

    (Admin Fitting)
    (KaBag. Gudang)

";

  $mail->AddReplyTo('admin@alfin.com', 'admin');
  $mail->AddAddress('alfin@gmail.com', 'zalfinm');
  $mail->SetFrom('admin@alfin.com', 'admin');
  $mail->AddReplyTo('admin@alfin.com', 'admin');
  $mail->Subject = 'test';
  $mail->AltBody = 'ini isi email'; // optional - MsgHTML will create an alternate automatically
  $mail->MsgHTML($body);

if(!$mail->Send()) {
  echo "Mailer Error: " . $mail->ErrorInfo;
} else {
  echo "Message sent!";
}

?>

   please help me

Body:
HTML code will be displayed if the content type header, is valid

'Content-type: text/html;'

but the php code will not be displayed in the mail, you can try to put it in a string and add this before and after the php string

<pre>
  <code>

    // your code

  </code>
</pre>


来源: stackexchange

问:
associative array total value count
Check array print_r() view bellow. I want to get total of only "amount" value. And output should not in array. It should be a simple integer value. So result should be 4+3+9= 16      </p>

```<code>Array
    (
        [0] => Array
            (
                [id] => 15
                [portfolio_id] => 1
                [stock_id] => 1
                [amount] => 4
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:04:30
                [updated_at] => 2017-04-02 09:04:30
            )

        [1] => Array
            (
                [id] => 14
                [portfolio_id] => 1
                [stock_id] => 3
                [amount] => 3
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:40
                [updated_at] => 2017-04-02 09:03:40
            )

        [2] => Array
            (
                [id] => 13
                [portfolio_id] => 1
                [stock_id] => 4
                [amount] => 9
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:36
                [updated_at] => 2017-04-02 09:03:36
            )

    )
</code>```

答:
Try this one :

```<code>function sum($carry, $item)// summing on amount column of the inner array $item
{
    $carry += $item["amount"];
    return $carry;
}
echo "Amount sum : ".array_reduce($a, "sum");// output : 59
</code>```

Example :

```<code><?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 4/2/2017
 * Time: 11:17 AM
 */

  $array = array
     (
        array("name"=>"Volvo","amount"=>22,"id"=>18),
        array("name"=>"BMW","amount"=>15,"id"=>13),
        array("name"=>"Saab","amount"=>5,"id"=>2),
        array("name"=>"Land Rover","amount"=>17,"id"=>15)
     );

    function sum($carry, $item)
    {
        $carry += $item["amount"];
        return $carry;
    }
    echo "Amount sum : " .array_reduce($array, "sum");// output : 59
</code>```

Good  luck.

ContentLicense: CC BY-SA 3.0

Title: associative array total value count

Body:
Check array print_r() view bellow. I want to get total of only "amount" value. And output should not in array. It should be a simple integer value. So result should be 4+3+9= 16

Array
    (
        [0] => Array
            (
                [id] => 15
                [portfolio_id] => 1
                [stock_id] => 1
                [amount] => 4
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:04:30
                [updated_at] => 2017-04-02 09:04:30
            )

        [1] => Array
            (
                [id] => 14
                [portfolio_id] => 1
                [stock_id] => 3
                [amount] => 3
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:40
                [updated_at] => 2017-04-02 09:03:40
            )

        [2] => Array
            (
                [id] => 13
                [portfolio_id] => 1
                [stock_id] => 4
                [amount] => 9
                [date] => 04/02/2017
                [created_at] => 2017-04-02 09:03:36
                [updated_at] => 2017-04-02 09:03:36
            )

    )

Body:
Try this one :

function sum($carry, $item)// summing on amount column of the inner array $item
{
    $carry += $item["amount"];
    return $carry;
}
echo "Amount sum : ".array_reduce($a, "sum");// output : 59

Example :

<?php
/**
 * Created by PhpStorm.
 * User: lenovo
 * Date: 4/2/2017
 * Time: 11:17 AM
 */

  $array = array
     (
        array("name"=>"Volvo","amount"=>22,"id"=>18),
        array("name"=>"BMW","amount"=>15,"id"=>13),
        array("name"=>"Saab","amount"=>5,"id"=>2),
        array("name"=>"Land Rover","amount"=>17,"id"=>15)
     );

    function sum($carry, $item)
    {
        $carry += $item["amount"];
        return $carry;
    }
    echo "Amount sum : " .array_reduce($array, "sum");// output : 59

Good  luck.


问:
Visual Basic: Force App to Stop
How can I simulate; app has stopped
After I click a button? I'm trying to make my program display that (exactly) after I click a button.</p>

答:
easy way to do this is,

let your app crash in the first place ( cause some sort of exception) take a screenshot from that exact message.

Create a new form called mCrashForm, place a picturebox with the screenshot of that message ( leave out the close Program button.

Create a button in your main Form to open the crashForm with mCrashForm.Show()

Create a Button in mCrashForm which says "Close program" which executes this code snippet when pressed mCrashForm.Close()

Title: Visual Basic: Force App to Stop


问:
cycling star-field animation
I made this star-field animation in javascript. I'm just not sure the best way to make it cycle the same animation from the other side. I like to get the stars to scroll across from one side of the canvas to the other.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x += stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id="myCanvas"></canvas></code>```

答:
To move and repeat use the remainder operator %. Because it returns negative values you have to mess about a little to make sure that the numbers are always positive. Also you want to make sure that the stars only move to the other side of the canvas when they are completely off one side so the modulo value must include the star size 500+2.

Thus star pos x

```<code>x %= 502;  // get remainder could be negative
x += 502;  // ensure it is positive
x %= 502;  // do modulo again
</code>```

How I did it in your example

```<code>// set up
var w = canvas.width;
var h = canvas.height;
const starCount = 2000;
const starSize = 2;
const widthModulo = w + starSize;
const heightModulo = h + starSize;

   // in iteration

    x = ((star.x % widthModulo) + widthModulo) % widthModulo - starSize / 2;
    y = ((star.y % heightModulo) + heightModulo) % heightModulo - starSize / 2;
    // draw the star
    ctx.fillRect(x, y, starSize, starSize);
</code>```

I have changed your code to have the stars go in many directions to show how well this method works. Also have added a few other changes. The main one is using requestAnimationFrame to call the animation function.

var ctx = canvas.getContext("2d");
const stars = [];
var dir = Math.PI;
var w = canvas.width;
var h = canvas.height;
const starCount = 2000;
const starSize = 2;
const widthModulo = w + starSize;
const heightModulo = h + starSize;

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var i;
for (i = 0; i < starCount; i++) {

  // following 4 randoms give a semi bell curve to the random value
  // this is to make more star at lower z values
  var z = (Math.random() + Math.random() +Math.random() +Math.random());
  z = Math.abs(z-2) * 8;
  var col = Math.floor(16 * z);
  stars.push({
    x: getRandomInt(0, w),
    y: getRandomInt(0, h),
    v: z / 6,
    col : "rgb("+col+","+col+","+col+")",
  });
}
stars.sort((a,b)=>a.v - b.v);  // sort from back to front

function animation (timer) {
  var star, dx, dy, x, y, i;

  // set the direction to make stars move in long circles
  dir = (Math.sin(timer / 13289) + 1) * Math.PI ;

  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, w, h);

  // get direction vector
  dx = Math.cos(dir);
  dy = Math.sin(dir);
  for (i = 0; i < starCount; i += 1) {
    star = stars[i];
    ctx.fillStyle = star.col;

    // move the star
    star.x += star.v * dx;
    star.y += star.v * dy;

    // make sure that stars are rendered on the current viewport
    x = ((star.x % widthModulo) + widthModulo) % widthModulo - starSize / 2;
    y = ((star.y % heightModulo) + heightModulo) % heightModulo - starSize / 2;
    // draw the star
    ctx.fillRect(x, y, starSize, starSize);
  }

  requestAnimationFrame(animation);
}
requestAnimationFrame(animation);```
<pre class="snippet-code-html lang-html prettyprint-override"><code><canvas id=canvas width = 500 height = 500></canvas></code>```

Title: cycling star-field animation

Body:
I made this star-field animation in javascript. I'm just not sure the best way to make it cycle the same animation from the other side. I like to get the stars to scroll across from one side of the canvas to the other.

var canvas = document.getElementById("myCanvas");
var ctx = canvas.getContext("2d");
stars = [];
ctx.fillStyle = "#000000";
ctx.fillRect(0, 0, 500, 500);

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

function getSpeed(depth) {
  switch (depth / 2) {
    case 0:
      return 6;
    case 1:
      return 5;
    case 2:
      return 4;
    case 3:
      return 3;
    case 4:
      return 2;
    case 5:
      return 1;
  }
}
var i;
for (i = 0; i < 2000; i++) {
  var star = {
    x: 0,
    y: 0,
    z: 0,
    v: 0
  };
  star.x = getRandomInt(0, 500);
  star.y = getRandomInt(0, 500);
  star.z = getRandomInt(0, 5) * 2;
  star.v = getSpeed(star.z);
  stars.push(star);
}

function animation() {
  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, 500, 500);

  // populates space with stars
  for (i = 0; i < 2000; i++) {
    ctx.fillStyle = "rgb(" + (256 / stars[i].z) + "," + (256 / stars[i].z) + "," + (256 / stars[i].z) + ")";
    ctx.fillRect(stars[i].x, stars[i].y, 2, 2);
    stars[i].x += stars[i].v;
  }

  setTimeout(animation, 33);
}
animation();

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

Body:
To move and repeat use the remainder operator %. Because it returns negative values you have to mess about a little to make sure that the numbers are always positive. Also you want to make sure that the stars only move to the other side of the canvas when they are completely off one side so the modulo value must include the star size 500+2.

Thus star pos x

x %= 502;  // get remainder could be negative
x += 502;  // ensure it is positive
x %= 502;  // do modulo again

How I did it in your example

// set up
var w = canvas.width;
var h = canvas.height;
const starCount = 2000;
const starSize = 2;
const widthModulo = w + starSize;
const heightModulo = h + starSize;

   // in iteration

    x = ((star.x % widthModulo) + widthModulo) % widthModulo - starSize / 2;
    y = ((star.y % heightModulo) + heightModulo) % heightModulo - starSize / 2;
    // draw the star
    ctx.fillRect(x, y, starSize, starSize);

I have changed your code to have the stars go in many directions to show how well this method works. Also have added a few other changes. The main one is using requestAnimationFrame to call the animation function.

var ctx = canvas.getContext("2d");
const stars = [];
var dir = Math.PI;
var w = canvas.width;
var h = canvas.height;
const starCount = 2000;
const starSize = 2;
const widthModulo = w + starSize;
const heightModulo = h + starSize;

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min + 1)) + min;
}

var i;
for (i = 0; i < starCount; i++) {

  // following 4 randoms give a semi bell curve to the random value
  // this is to make more star at lower z values
  var z = (Math.random() + Math.random() +Math.random() +Math.random());
  z = Math.abs(z-2) * 8;
  var col = Math.floor(16 * z);
  stars.push({
    x: getRandomInt(0, w),
    y: getRandomInt(0, h),
    v: z / 6,
    col : "rgb("+col+","+col+","+col+")",
  });
}
stars.sort((a,b)=>a.v - b.v);  // sort from back to front

function animation (timer) {
  var star, dx, dy, x, y, i;

  // set the direction to make stars move in long circles
  dir = (Math.sin(timer / 13289) + 1) * Math.PI ;

  //clears background
  ctx.fillStyle = "#000000";
  ctx.fillRect(0, 0, w, h);

  // get direction vector
  dx = Math.cos(dir);
  dy = Math.sin(dir);
  for (i = 0; i < starCount; i += 1) {
    star = stars[i];
    ctx.fillStyle = star.col;

    // move the star
    star.x += star.v * dx;
    star.y += star.v * dy;

    // make sure that stars are rendered on the current viewport
    x = ((star.x % widthModulo) + widthModulo) % widthModulo - starSize / 2;
    y = ((star.y % heightModulo) + heightModulo) % heightModulo - starSize / 2;
    // draw the star
    ctx.fillRect(x, y, starSize, starSize);
  }

  requestAnimationFrame(animation);
}
requestAnimationFrame(animation);

<canvas id=canvas width = 500 height = 500></canvas>


问:
Verify empty field Selenium C#
I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:

```<code>var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
                Console.WriteLine("This field can not be empty");
            }
</code>```

Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?

Thank you in advance!

答:
For Empty / White space / Null, use following APIs of the string class

string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)

For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits

```<code>string pattern = @"^\d{20}$";
var booleanResult  = Regex.Match(value,pattern).Success
</code>```

Title: Verify empty field Selenium C#

Body:
I am trying to check if a text field is empty and I can't convert bool to string.
I am trying this:

var firstName = driver.FindElement(By.Id("name_3_firstname"));
if (firstName.Equals(" ")) {
                Console.WriteLine("This field can not be empty");
            }

Also, how can I check if certain number field is exactly 20 digits?
Can you help me do this?

Thank you in advance!

Body:
For Empty / White space / Null, use following APIs of the string class

string.IsNullOrEmpty(value) or
string.IsNullOrWhiteSpace(value)

For exact 20 digits, best is to use the Regular expression as follows, this can also be converted to range and combination of digits and characters if required. Current regular expression ensures that beginning, end and all components are digits

string pattern = @"^\d{20}$";
var booleanResult  = Regex.Match(value,pattern).Success


问:
What is the point of using ConcurrentMap.replace in this example
Here's an excerpt from Java Concurrency in Practice:

```<code>public class DelegatingVehicleTracker {

    private final ConcurrentMap<String, Point> locations;
    private final Map<String, Point> unmodifiableMap;

    public DelegatingVehicleTracker(final Map<String, Point> points) {
        this.locations = new ConcurrentHashMap<>(points);
        this.unmodifiableMap = Collections.unmodifiableMap(this.locations);
    }

    public Map<String, Point> getLocations() {
        return unmodifiableMap;
    }

    public Point getLocation(final String id) {
        return locations.get(id);
    }

    public void setLocation(final String id, final int x, final int y) {
        if (null == locations.replace(id, new Point(x, y))) {
            throw new IllegalArgumentException("Invalid vehicle name: " + id);
        }
    }
}
</code>```

My question is about the setLocation method which uses ConcurrentMap.replace. The JavaDoc of this method says that it's equivalent to:

```<code>if (map.containsKey(key)) {
     return map.put(key, value);
} else return null;
</code>```

except that the action is performed atomically.

What could go wrong if we don't use the atomic version. One possibility is that one thread sees that the map contains a given key and before it puts a new value for that key, another thread removes that key-value pair, but since the class in the example does not allow removals, this cannot happen.

Another possibility is that two threads attempt to replace the same key with different values. In that case one thread may not return the correct previous value but in the example we don't care about the previous value, the method setLocation returns void.

So, it seems as though the method could be rewritten without replace. And that is what prompted my question. In a subsequent version of the same class in the book, which almost identical to the one above, the method setLocation does not use replace, just containsKey and I was wondering if this could compromise thread safety.

答:
the method setLocation does not use replace, just containsKey and I
  was wondering if this could compromise thread safety.

It does, you've described it perfectly

What could go wrong if we don't use the atomic version. One
  possibility is that one thread sees that the map contains a given key
  and before it puts a new value for that key, another thread removes
  that key-value pair, but since the class in the example does not allow
  removals, this cannot happen.

That's why the implementation of ConcurrentHashMap.replace locks the node it tries to replace

```<code>/**
     * Implementation for the four public remove/replace methods:
     * Replaces node value with v, conditional upon match of cv if
     * non-null.  If resulting value is null, delete.
     */
    final V replaceNode(Object key, V value, Object cv) {
        int hash = spread(key.hashCode());
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            if (tab == null || (n = tab.length) == 0 ||
                (f = tabAt(tab, i = (n - 1) & hash)) == null)
                break;
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                boolean validated = false;
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        if (fh >= 0) {
                            validated = true;
                            for (Node<K,V> e = f, pred = null;;) {
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    V ev = e.val;
                                    if (cv == null || cv == ev ||
                                        (ev != null && cv.equals(ev))) {
                                        oldVal = ev;
                                        if (value != null)
                                            e.val = value;
                                        else if (pred != null)
                                            pred.next = e.next;
                                        else
                                            setTabAt(tab, i, e.next);
                                    }
                                    break;
                                }
                                pred = e;
                                if ((e = e.next) == null)
                                    break;
                            }
                        }
                        else if (f instanceof TreeBin) {
                            validated = true;
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> r, p;
                            if ((r = t.root) != null &&
                                (p = r.findTreeNode(hash, key, null)) != null) {
                                V pv = p.val;
                                if (cv == null || cv == pv ||
                                    (pv != null && cv.equals(pv))) {
                                    oldVal = pv;
                                    if (value != null)
                                        p.val = value;
                                    else if (t.removeTreeNode(p))
                                        setTabAt(tab, i, untreeify(t.first));
                                }
                            }
                        }
                    }
                }
                if (validated) {
                    if (oldVal != null) {
                        if (value == null)
                            addCount(-1L, -1);
                        return oldVal;
                    }
                    break;
                }
            }
        }
        return null;
    }
</code>```

Body:
Here's an excerpt from Java Concurrency in Practice:

public class DelegatingVehicleTracker {

    private final ConcurrentMap<String, Point> locations;
    private final Map<String, Point> unmodifiableMap;

    public DelegatingVehicleTracker(final Map<String, Point> points) {
        this.locations = new ConcurrentHashMap<>(points);
        this.unmodifiableMap = Collections.unmodifiableMap(this.locations);
    }

    public Map<String, Point> getLocations() {
        return unmodifiableMap;
    }

    public Point getLocation(final String id) {
        return locations.get(id);
    }

    public void setLocation(final String id, final int x, final int y) {
        if (null == locations.replace(id, new Point(x, y))) {
            throw new IllegalArgumentException("Invalid vehicle name: " + id);
        }
    }
}

My question is about the setLocation method which uses ConcurrentMap.replace. The JavaDoc of this method says that it's equivalent to:

if (map.containsKey(key)) {
     return map.put(key, value);
} else return null;

except that the action is performed atomically.

What could go wrong if we don't use the atomic version. One possibility is that one thread sees that the map contains a given key and before it puts a new value for that key, another thread removes that key-value pair, but since the class in the example does not allow removals, this cannot happen.

Another possibility is that two threads attempt to replace the same key with different values. In that case one thread may not return the correct previous value but in the example we don't care about the previous value, the method setLocation returns void.

So, it seems as though the method could be rewritten without replace. And that is what prompted my question. In a subsequent version of the same class in the book, which almost identical to the one above, the method setLocation does not use replace, just containsKey and I was wondering if this could compromise thread safety.

Body:
the method setLocation does not use replace, just containsKey and I
  was wondering if this could compromise thread safety.

It does, you've described it perfectly

What could go wrong if we don't use the atomic version. One
  possibility is that one thread sees that the map contains a given key
  and before it puts a new value for that key, another thread removes
  that key-value pair, but since the class in the example does not allow
  removals, this cannot happen.

That's why the implementation of ConcurrentHashMap.replace locks the node it tries to replace

/**
     * Implementation for the four public remove/replace methods:
     * Replaces node value with v, conditional upon match of cv if
     * non-null.  If resulting value is null, delete.
     */
    final V replaceNode(Object key, V value, Object cv) {
        int hash = spread(key.hashCode());
        for (Node<K,V>[] tab = table;;) {
            Node<K,V> f; int n, i, fh;
            if (tab == null || (n = tab.length) == 0 ||
                (f = tabAt(tab, i = (n - 1) & hash)) == null)
                break;
            else if ((fh = f.hash) == MOVED)
                tab = helpTransfer(tab, f);
            else {
                V oldVal = null;
                boolean validated = false;
                synchronized (f) {
                    if (tabAt(tab, i) == f) {
                        if (fh >= 0) {
                            validated = true;
                            for (Node<K,V> e = f, pred = null;;) {
                                K ek;
                                if (e.hash == hash &&
                                    ((ek = e.key) == key ||
                                     (ek != null && key.equals(ek)))) {
                                    V ev = e.val;
                                    if (cv == null || cv == ev ||
                                        (ev != null && cv.equals(ev))) {
                                        oldVal = ev;
                                        if (value != null)
                                            e.val = value;
                                        else if (pred != null)
                                            pred.next = e.next;
                                        else
                                            setTabAt(tab, i, e.next);
                                    }
                                    break;
                                }
                                pred = e;
                                if ((e = e.next) == null)
                                    break;
                            }
                        }
                        else if (f instanceof TreeBin) {
                            validated = true;
                            TreeBin<K,V> t = (TreeBin<K,V>)f;
                            TreeNode<K,V> r, p;
                            if ((r = t.root) != null &&
                                (p = r.findTreeNode(hash, key, null)) != null) {
                                V pv = p.val;
                                if (cv == null || cv == pv ||
                                    (pv != null && cv.equals(pv))) {
                                    oldVal = pv;
                                    if (value != null)
                                        p.val = value;
                                    else if (t.removeTreeNode(p))
                                        setTabAt(tab, i, untreeify(t.first));
                                }
                            }
                        }
                    }
                }
                if (validated) {
                    if (oldVal != null) {
                        if (value == null)
                            addCount(-1L, -1);
                        return oldVal;
                    }
                    break;
                }
            }
        }
        return null;
    }


问:
Auto hyperlink Jira Issues in Git commits in SourceTree
Jira will automatically scan a git repo and pull in commits that are tagged with a Jira ID (ie QA-244).

Is there a way to display the links to Jira issues from with SourceTree:

答:
To make the commit text in SourceTree link to a GitHub Issue or Bitbucket Issue (standard issue tracker, similar to Jira), where the Issue is in the form "#1234", use this approach:

Open your repository window

Click 'Settings' in the toolbar

Click 'Advanced'

In the 'Commit Text Replacements' section, click 'Add'

For the Replacement Type, select 'Other'

In the 'Regex Pattern' field, enter #(\d+)($|[^a-zA-Z0-9-]) (but see the Note below)

In the 'Replace With' field:

a. On Mac OS X, enter #$1$2 (make sure you include the speech marks)

b. On Windows, enter https://bitbucket.org/your_username/your_project/issue/$1

Click OK twice

Re-select the commit log item which has a mention of the #12345 style issue number. It should now show a clickable hyperlink to the issue, which will open your web browser.

Note: For step 6, you may consider using a regex like #(\d{1,4})($|[^a-zA-Z0-9-]) to prevent matching URLs that have "#numbers" in them, like www.example.com/#123456 - More info here

Sources:

https://confluence.atlassian.com/sourcetreekb/link-to-bitbucket-issue-tracker-from-commits-296911608.html

https://answers.atlassian.com/questions/237742/sourcetree-what-format-is-link-to-url-for-commit-text-links

Apply the same links in JetBrains products

You can also have the same links in IntelliJ IDEA, Android Studio, PyCharm, etc, when viewing the "Version Control" tab for Git history:

IDE -> Preferences -> Search for "Issue Navigation" -> Add -> Enter regular the same expression and hyperlink. More info here.

Body:
To make the commit text in SourceTree link to a GitHub Issue or Bitbucket Issue (standard issue tracker, similar to Jira), where the Issue is in the form "#1234", use this approach:

Open your repository window

Click 'Settings' in the toolbar

Click 'Advanced'

In the 'Commit Text Replacements' section, click 'Add'

For the Replacement Type, select 'Other'

In the 'Regex Pattern' field, enter #(\d+)($|[^a-zA-Z0-9-]) (but see the Note below)

In the 'Replace With' field:

a. On Mac OS X, enter <a href="https://bitbucket.org/your_username/your_project/issue/$1/">#$1</a>$2 (make sure you include the speech marks)

b. On Windows, enter https://bitbucket.org/your_username/your_project/issue/$1

Click OK twice

Re-select the commit log item which has a mention of the #12345 style issue number. It should now show a clickable hyperlink to the issue, which will open your web browser.

Note: For step 6, you may consider using a regex like #(\d{1,4})($|[^a-zA-Z0-9-]) to prevent matching URLs that have "#numbers" in them, like www.example.com/#123456 - More info here

Sources:

https://confluence.atlassian.com/sourcetreekb/link-to-bitbucket-issue-tracker-from-commits-296911608.html

https://answers.atlassian.com/questions/237742/sourcetree-what-format-is-link-to-url-for-commit-text-links

Apply the same links in JetBrains products

You can also have the same links in IntelliJ IDEA, Android Studio, PyCharm, etc, when viewing the "Version Control" tab for Git history:

IDE -> Preferences -> Search for "Issue Navigation" -> Add -> Enter regular the same expression and hyperlink. More info here.

ContentLicense: CC BY-SA 4.0


问:
Libgdx android icon not being applied
I made a game and now I want to change the icon, so I replaced the icons on res/drawable (with the same file name). But when I run the game on my android phone it still installs with the default libgdx icon and not my own icon. Then I tried to change the icon names and also making changes in my manifest file.

```<code><application
        android:allowBackup="true"
        android:icon="@drawable/loh_icon" //loh_icon.png is my icon name
        android:label="@string/app_name"
        android:theme="@style/GdxTheme" >
</code>```

Still the same problem, how can my game still have the default libgdx icon? I deleted those icons and replaced them. I also invalidated my intellij caches and restarted.

答:
If you look in your android/res folder, you'll see 5 different directories starting with drawable. The part after the dash is the screen density.

Inside each folder there is a file called ic_launcher.png with a size for each screen density. This is why by default, you'll find this in your manifest: @drawable/ic_launcher. You'll need to make different resolutions for different densities, and replace them.

You can use this online tool to automatically do it for you: Android Asset Studio.
Make your icon and click the download link. Open the ZIP file, and extract it to your res folder.

You can delete the drawable folders. Go into your manifest, and set your icon to: @mipmap/ic_launcher

Title: Libgdx android icon not being applied

Body:
I made a game and now I want to change the icon, so I replaced the icons on res/drawable (with the same file name). But when I run the game on my android phone it still installs with the default libgdx icon and not my own icon. Then I tried to change the icon names and also making changes in my manifest file.

<application
        android:allowBackup="true"
        android:icon="@drawable/loh_icon" //loh_icon.png is my icon name
        android:label="@string/app_name"
        android:theme="@style/GdxTheme" >

Still the same problem, how can my game still have the default libgdx icon? I deleted those icons and replaced them. I also invalidated my intellij caches and restarted.


问:
Dynamics CRM Plugin-For a input publication value, search for subscription, if found add it to the contact on create/update
The below code seems to work when a contact is created, for input value publication it searches and associates an existing subscription. But the same code wont work for update of a contact. Any opinions as to why this may be happening in my plugin?

if (!String.IsNullOrEmpty(publication))
{
    //Query for existing Publication
    var publicationQuery = new QueryByAttribute("msdynhcp_publicationnewsletter");
    //publicationQuery.ColumnSet.AllColumns = true;
    publicationQuery.Attributes.AddRange("msdynhcp_publicationname");
    publicationQuery.Values.AddRange(publication);
    publicationQuery.TopCount = 1;

    //Call Query
    EntityCollection publicationIds = organizationService.RetrieveMultiple(publicationQuery);

    if (publicationIds.Entities.Count > 0)
    {
        //Query for existing subscription
        var subscriptionQuery = new QueryExpression("msdynhcp_subscription");

        var linkedContact = new LinkEntity("msdynhcp_subscription", "contact", "msdynhcp_contactlookup", "contact" + "id", JoinOperator.Inner);
        linkedContact.LinkCriteria = new FilterExpression(LogicalOperator.And);
        linkedContact.LinkCriteria.AddCondition("contact" + "id", ConditionOperator.Equal, ContactId);
        subscriptionQuery.LinkEntities.Add(linkedContact);

        var linkedPublication = new LinkEntity("msdynhcp_subscription", "msdynhcp_publicationnewsletter", "msdynhcp_publicationlookup", "msdynhcp_publicationnewsletter" + "id", JoinOperator.Inner);
        linkedPublication.LinkCriteria = new FilterExpression(LogicalOperator.And);
        linkedPublication.LinkCriteria.AddCondition("msdynhcp_publicationnewsletter" + "id", ConditionOperator.Equal, publicationIds[0].Id);
        subscriptionQuery.LinkEntities.Add(linkedContact);

        subscriptionQuery.TopCount = 1;

        //Call Query
        EntityCollection subscriptionIDs = organizationService.RetrieveMultiple(subscriptionQuery);

        if (subscriptionIDs.Entities.Count == 0)
        {
            //New Subscription
            var crmSubscription = new Entity("msdynhcp_subscription");
            crmSubscription["msdynhcp_utcdatetimestamp"] = DateTime.UtcNow;
            crmSubscription["msdynhcp_enabledactive"] = true;

            //Call Create
            var id = organizationService.Create(crmSubscription);

            //Call Associate
            organizationService.Associate("msdynhcp_subscription", id, new Relationship("msdynhcp_contact_new_subscription_contactlookup"),
                new EntityReferenceCollection(new List<EntityReference>() { new EntityReference("contact", new Guid(ContactId)) }));
            //Call Associate
            organizationService.Associate("msdynhcp_subscription", id, new Relationship("msdynhcp_new_publicationnewsletter_new_subscription_publicationlookup"),
                new EntityReferenceCollection(new List<EntityReference>() { new EntityReference("msdynhcp_publicationnewsletter", publicationIds.Entities[0].Id) }));
        }
    }
}
```

答: You did not post the whole plugin logic but if it works on create and does not work on update then most likely, you are expecting in your plugin an attribute that is simply not there. When you create an entity, you have to fill all the required fields (at least if you do that on the web form) and all this attributes are there in your Target in InputParameters of the plugin. But when you are updating entity, only the attributes that are modified are in the Target from InputParameters (and of course some standard attributes like modifiedon, modifiedby etc.). So, most likely, your plugin checks if some attribute is null (this first check for publication looks suspicious, but I can't tell if that's it, as it's not the full code. To be sure that the attribute is there, get it from PostImage/PreImage not Target (see: https://msdn.microsoft.com/en-us/library/gg309673.aspx#Anchor_5)


问:
AngularJS filtering ng-repeat on an array
I'm learning Angular. The below code dynamically shows/hides rows of a table based on a <select multiple> control.

The code works but I wonder if there is a way to convert the expression in data-ng-if to a filter expression without creating a custom filter. Also not sure which is a better approach performancewise.

```<code><select id="psgs" data-ng-model="ctrl.showSubGroups"
   ng-options="item.id as item.name group by item.productGroup.name for item in ctrl.productSubGroupList"
   multiple>
</select>

<tr
   data-ng-if="ctrl.showSubGroups.indexOf(product.productSubGroup.id) > -1"
   data-ng-repeat="product in ctrl.productList | filter: ??? | orderBy: ctrl.seq">
   ...
</tr>
</code>```

答:
You can achieve that using custom filter and it's better approach as compared to having ng-if on each iteration. You shouldn't be repeating the loop for those which are not going to be rendered.

Here's how. In your HTML, use customFilter (which is a custom filter function we created) like this:

```<code><tr
   data-ng-repeat="product in ctrl.productList | filter: ctrl.customFilter | orderBy: ctrl.seq">
   ...
</tr>
</code>```

Now, in your controller, you can have customFilter function like this:

```<code>ctrl.customFilter = function(product) {
  return ctrl.showSubGroups.indexOf(product.productSubGroup.id) > -1
}
</code>```

Here's a simple working example with sample data

Body:
I'm learning Angular. The below code dynamically shows/hides rows of a table based on a <select multiple> control.

The code works but I wonder if there is a way to convert the expression in data-ng-if to a filter expression without creating a custom filter. Also not sure which is a better approach performancewise.

<select id="psgs" data-ng-model="ctrl.showSubGroups"
   ng-options="item.id as item.name group by item.productGroup.name for item in ctrl.productSubGroupList"
   multiple>
</select>

 -1"
   data-ng-repeat="product in ctrl.productList | filter: ??? | orderBy: ctrl.seq">
   ...

Body:
You can achieve that using custom filter and it's better approach as compared to having ng-if on each iteration. You shouldn't be repeating the loop for those which are not going to be rendered.

Here's how. In your HTML, use customFilter (which is a custom filter function we created) like this:

<tr
   data-ng-repeat="product in ctrl.productList | filter: ctrl.customFilter | orderBy: ctrl.seq">
   ...
</tr>

Now, in your controller, you can have customFilter function like this:

ctrl.customFilter = function(product) {
  return ctrl.showSubGroups.indexOf(product.productSubGroup.id) > -1
}

Here's a simple working example with sample data


问:
Serializing and Deserializing Raw Json String using Jackson
I am using Jackson Fasterxml version 2.8.0 to serialize and deserialize json as follows:

```<code>public static byte[] serializeData(Object object){
   final ObjectMapper mapper = new ObjectMapper();
   return mapper.writeValueAsBytes(object);
}

public static void main(String [] args) {
  String json = "{ \"id\" : \"user1\" }"; // need to escape or else compiler complains

  byte[] result = serializeData(json);

  final ObjectMapper mapper = new ObjectMapper();
  final JsonNode jsonNode = mapper.readTree(result);

  System.out.println(json);
  System.out.println(jsonNode.toString());
  System.out.println(jsonNode.getNodeType());

  Iterator<String> fields = jsonNode.fieldNames();
  while(fields.hasNext()){
    System.out.println("field - " + fields.next());
  }
}
</code>```

The output was:

```<code>{ "id" : "user1" }
"{ \"id\" : \"user1\" }"
STRING
</code>```

Notice there is no output lines for printing the field names. So, it seems like the JsonNode does not have any properties and for some reason the toString() has escape chars in them. Am I using this library in the wrong manner? Why is that when deserializing the byte array results in a behavior where I can't find the fields I initially added?

Updates

Providing some more context of the application. The app receives the Json as a String input. The code that deserializes the Json is not aware of the model of the Json. It just expects it to be valid Json object so that it can iterate through the various fields in it.

答:
You are mistaking a JSON string to java Object, that is the key issue here.

```<code>  String json = "{ \"id\" : \"user1\" }"; // need to escape or else compiler complains

  byte[] result = serializeData(json);
</code>```

Your String json  is just a String, it does not matter what it's contents are, using mapper.writeValueAsBytes(object) just serializes a String thus resulting in a single JSON Node of type STRING.

To serialize an Object that has a field id of type String, you need to serialize an object with a field named id of type String.

For example :

```<code>public class User {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "User [id=" + id + "]";
    }
}
</code>```

This type User can be serialized to {"id":"User1"} (if the id field is set to "User1").

In the following example you either start from a POJO (User user = new User();) or you start from valid json string (String json = "{ \"id\" : \"user1\" }";).

In the first case you first map the object into json bytes, then you parse those bytes to get a JSONNode (a kind of DOM tree for json ).

In the second case you just parse the bytes to get the node, you don't writeValueAsBytes of the json string, beacause you would just stringify twice thus getting just a value node of STRING type.

```<code>    User user = new User();
    user.setId("user1");

    ObjectMapper mapper = new ObjectMapper();
    byte[] jsonBytes = mapper.writeValueAsBytes(user);

    System.out.println(new String(jsonBytes)); // will print {"id":"user1"}

    JsonNode node = mapper.readTree(jsonBytes);
    Iterator<String> names = node.fieldNames();
    while (names.hasNext()) {
        String name = (String) names.next();
        JsonNodeType type = node.get(name).getNodeType();
        System.out.println(name+":"+type); //will print id:STRING
    }

    // This is not a object to serialize
    // This is a string to parse into a json object
    String json = "{ \"id\" : \"user1\" }";

    JsonNode node2 = mapper.readTree(json.getBytes());
    names = node.fieldNames();
    while (names.hasNext()) {
        String name = (String) names.next();
        JsonNodeType type = node.get(name).getNodeType();
        System.out.println(name+":"+type); //will print id:STRING
    }
</code>```

Body:
I am using Jackson Fasterxml version 2.8.0 to serialize and deserialize json as follows:

public static byte[] serializeData(Object object){
   final ObjectMapper mapper = new ObjectMapper();
   return mapper.writeValueAsBytes(object);
}

public static void main(String [] args) {
  String json = "{ \"id\" : \"user1\" }"; // need to escape or else compiler complains

  byte[] result = serializeData(json);

  final ObjectMapper mapper = new ObjectMapper();
  final JsonNode jsonNode = mapper.readTree(result);

  System.out.println(json);
  System.out.println(jsonNode.toString());
  System.out.println(jsonNode.getNodeType());

  Iterator<String> fields = jsonNode.fieldNames();
  while(fields.hasNext()){
    System.out.println("field - " + fields.next());
  }
}

The output was:

{ "id" : "user1" }
"{ \"id\" : \"user1\" }"
STRING

Notice there is no output lines for printing the field names. So, it seems like the JsonNode does not have any properties and for some reason the toString() has escape chars in them. Am I using this library in the wrong manner? Why is that when deserializing the byte array results in a behavior where I can't find the fields I initially added?

Updates

Providing some more context of the application. The app receives the Json as a String input. The code that deserializes the Json is not aware of the model of the Json. It just expects it to be valid Json object so that it can iterate through the various fields in it.

Body:
You are mistaking a JSON string to java Object, that is the key issue here.

  String json = "{ \"id\" : \"user1\" }"; // need to escape or else compiler complains

  byte[] result = serializeData(json);

Your String json  is just a String, it does not matter what it's contents are, using mapper.writeValueAsBytes(object) just serializes a String thus resulting in a single JSON Node of type STRING.

To serialize an Object that has a field id of type String, you need to serialize an object with a field named id of type String.

For example :

public class User {
    private String id;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    @Override
    public String toString() {
        return "User [id=" + id + "]";
    }
}

This type User can be serialized to {"id":"User1"} (if the id field is set to "User1").

In the following example you either start from a POJO (User user = new User();) or you start from valid json string (String json = "{ \"id\" : \"user1\" }";).

In the first case you first map the object into json bytes, then you parse those bytes to get a JSONNode (a kind of DOM tree for json ).

In the second case you just parse the bytes to get the node, you don't writeValueAsBytes of the json string, beacause you would just stringify twice thus getting just a value node of STRING type.

    User user = new User();
    user.setId("user1");

    ObjectMapper mapper = new ObjectMapper();
    byte[] jsonBytes = mapper.writeValueAsBytes(user);

    System.out.println(new String(jsonBytes)); // will print {"id":"user1"}

    JsonNode node = mapper.readTree(jsonBytes);
    Iterator<String> names = node.fieldNames();
    while (names.hasNext()) {
        String name = (String) names.next();
        JsonNodeType type = node.get(name).getNodeType();
        System.out.println(name+":"+type); //will print id:STRING
    }

    // This is not a object to serialize
    // This is a string to parse into a json object
    String json = "{ \"id\" : \"user1\" }";

    JsonNode node2 = mapper.readTree(json.getBytes());
    names = node.fieldNames();
    while (names.hasNext()) {
        String name = (String) names.next();
        JsonNodeType type = node.get(name).getNodeType();
        System.out.println(name+":"+type); //will print id:STRING
    }


问:
Calculate compass bearing / heading to location in Android
I want to display an arrow at my location on a google map view that displays my direction relative to a destination location (instead of north).

a) I have calculated north using the sensor values from the magnetometer and accelerometer. I know this is correct because it lines up with the compass used on the Google Map view.

b) I have calculated the initial bearing from my location to the destination location by using myLocation.bearingTo(destLocation);

I'm missing the last step; from these two values (a & b) what formula do I use to get the  direction in which the phone is pointing relative to the destination location?

Appreciate any help for an addled mind!

答:
Ok I figured this out. For anyone else trying to do this you need:

a) heading: your heading from the hardware compass. This is in degrees east of magnetic north

b) bearing: the bearing from your location to the destination location.  This is in degrees east of true north.

```<code>myLocation.bearingTo(destLocation);
</code>```

c) declination: the difference between true north and magnetic north

The heading that is returned from the magnetometer + accelermometer is in degrees east of true (magnetic) north (-180 to +180) so you need to get the difference between north and magnetic north for your location.  This difference is variable depending where you are on earth.  You can obtain by using GeomagneticField class.

```<code>GeomagneticField geoField;

private final LocationListener locationListener = new LocationListener() {
   public void onLocationChanged(Location location) {
      geoField = new GeomagneticField(
         Double.valueOf(location.getLatitude()).floatValue(),
         Double.valueOf(location.getLongitude()).floatValue(),
         Double.valueOf(location.getAltitude()).floatValue(),
         System.currentTimeMillis()
      );
      ...
   }
}
</code>```

Armed with these you calculate the angle of the arrow to draw on your map to show where you are facing in relation to your destination object rather than true north.

First adjust your heading with the declination:

```<code>heading += geoField.getDeclination();
</code>```

Second, you need to offset the direction in which the phone is facing (heading) from the target destination rather than true north. This is the part that I got stuck on. The heading value returned from the compass gives you a value that describes where magnetic north is (in degrees east of true north) in relation to where the phone is pointing. So e.g. if the value is -10 you know that magnetic north is 10 degrees to your left.  The bearing gives you the angle of your destination in degrees east of true north. So after you've compensated for the declination you can use the formula below to get the desired result:

```<code>heading = myBearing - (myBearing + heading);
</code>```

You'll then want to convert from degrees east of true north (-180 to +180) into normal degrees (0 to 360):

```<code>Math.round(-heading / 360 + 180)
</code>```

ContentLicense: CC BY-SA 2.5

Body:
Ok I figured this out. For anyone else trying to do this you need:

a) heading: your heading from the hardware compass. This is in degrees east of magnetic north

b) bearing: the bearing from your location to the destination location.  This is in degrees east of true north.

myLocation.bearingTo(destLocation);

c) declination: the difference between true north and magnetic north

The heading that is returned from the magnetometer + accelermometer is in degrees east of true (magnetic) north (-180 to +180) so you need to get the difference between north and magnetic north for your location.  This difference is variable depending where you are on earth.  You can obtain by using GeomagneticField class.

GeomagneticField geoField;

private final LocationListener locationListener = new LocationListener() {
   public void onLocationChanged(Location location) {
      geoField = new GeomagneticField(
         Double.valueOf(location.getLatitude()).floatValue(),
         Double.valueOf(location.getLongitude()).floatValue(),
         Double.valueOf(location.getAltitude()).floatValue(),
         System.currentTimeMillis()
      );
      ...
   }
}

Armed with these you calculate the angle of the arrow to draw on your map to show where you are facing in relation to your destination object rather than true north.

First adjust your heading with the declination:

heading += geoField.getDeclination();

Second, you need to offset the direction in which the phone is facing (heading) from the target destination rather than true north. This is the part that I got stuck on. The heading value returned from the compass gives you a value that describes where magnetic north is (in degrees east of true north) in relation to where the phone is pointing. So e.g. if the value is -10 you know that magnetic north is 10 degrees to your left.  The bearing gives you the angle of your destination in degrees east of true north. So after you've compensated for the declination you can use the formula below to get the desired result:

heading = myBearing - (myBearing + heading);

You'll then want to convert from degrees east of true north (-180 to +180) into normal degrees (0 to 360):

Math.round(-heading / 360 + 180)


问:
Unable to remove axis animation from `UIStackView`
I have an UIStackView build in interface builder which changes it's axis property from vertical to horizontal when it's superview rotates from portrait to landscape. The issue is that this results in an animation of it's two arranged subviews, where one of those views overlaps the other view while transitioning to the new position.

In my case I would like to remove only that particular animation and force the view to it's end position right away.

I have tried to remove all animation on from the stackview layer in my VC:

```<code>public override func willTransition(to newCollection: UITraitCollection,
                                    with coordinator: UIViewControllerTransitionCoordinator) {

    coordinator.animate(alongsideTransition: {
        _ in
        // The first subview is `UIStackView`
        self.view.subviews[0].layer.removeAllAnimations()
    })

    super.willTransition(to: newCollection, with: coordinator)
}
</code>```

And I observed the animation keys when the axis property is changed, because that seems to happen somewhere during the transition (set automatically by interface builder). Unfortunately I had no luck with it, because the layer returns nil for animationKeys on the stackview and its subviews/arrangedSubviews.

```<code>class StackView : UIStackView {

    override var axis: UILayoutConstraintAxis {

        didSet { /* here */ }
    }
}
</code>```

答:
That's going to be challenging, I think. There's a nice demo of what it sounds like you're trying to do over here if the axis animation it shows is what you're trying to get rid of, pretty sure that's outside the UIStackView design space.

Pretty sure the best solution to "force the view to it's end position right away" is to in fact have one UIStackView for each axis and move the contents between them on rotation.

You could also try putting a performWithoutAnimation block in your viewWillTransition(to:with:) that calls updateConstraintsIfNeeded on completion? Maybe that would work. I'd go with the two-view idea instead of that though!

Body:
I have an UIStackView build in interface builder which changes it's axis property from vertical to horizontal when it's superview rotates from portrait to landscape. The issue is that this results in an animation of it's two arranged subviews, where one of those views overlaps the other view while transitioning to the new position.

In my case I would like to remove only that particular animation and force the view to it's end position right away.

I have tried to remove all animation on from the stackview layer in my VC:

public override func willTransition(to newCollection: UITraitCollection,
                                    with coordinator: UIViewControllerTransitionCoordinator) {

    coordinator.animate(alongsideTransition: {
        _ in
        // The first subview is `UIStackView`
        self.view.subviews[0].layer.removeAllAnimations()
    })

    super.willTransition(to: newCollection, with: coordinator)
}

And I observed the animation keys when the axis property is changed, because that seems to happen somewhere during the transition (set automatically by interface builder). Unfortunately I had no luck with it, because the layer returns nil for animationKeys on the stackview and its subviews/arrangedSubviews.

class StackView : UIStackView {

    override var axis: UILayoutConstraintAxis {

        didSet { /* here */ }
    }
}


问:
How can I build a hashed region for null column values in Highcharts?
With data: [null, null, 10, 20, 20, 33, 23, 23, 22, 5]

How can i build a hashed region in Highcharts, like displayed to the left of the blue columns, the hashed region would represent a group of null data points?

I had thought to overlay 2 chart types to solve this. Wondering if anyone has a better idea here? Maybe using Renderer or an area line chart?

答:
you can use Plot bands

In chart option add following

Fiddle

```<code>events: {
 load: function () {
 var series_data=this.series[0].data;//this is series data
 for(var i=0;i<series_data.length;i++){
      if(series_data[i].y==null){//find null value in series
         //adds plot band
          this.xAxis[0].addPlotBand({
              from: i-1, //point back
              to: i+1,   //point after
              color: '#c5d8f7',//this color represent null value region
          });
      }
  }

}
}
</code>```

Body:
you can use Plot bands

In chart option add following

Fiddle

events: {
 load: function () {
 var series_data=this.series[0].data;//this is series data
 for(var i=0;i<series_data.length;i++){
      if(series_data[i].y==null){//find null value in series
         //adds plot band
          this.xAxis[0].addPlotBand({
              from: i-1, //point back
              to: i+1,   //point after
              color: '#c5d8f7',//this color represent null value region
          });
      }
  }

}
}


问:
.net Regex to capture groups plus everything else
I am trying to create a .net regex that will capture the whole string into different groups. Capturing the groups is easy but capturing the rest is beyond me.

The [BBCode] markers could happen anywhere in the string, or be the only thing, or not be present at all. There also maybe [ brackets ] in the string.

Having group names would be a bonus.

```<code>class Program
{
    static void Main(string[] args)
    {
        string input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";
        string regexString = @"((\[A=[0-9]+\])|(\[E=[0-9]+\])|(\[V=[0-9]+\]))";
        MatchCollection matches = Regex.Matches(input, regexString);

        foreach (Match match in matches)
        {
            Console.WriteLine(match.Value);
        }
   }
}
</code>```

The result I am after is (one group per line)

thinking [ of using ] BBCode format

[A=16]

and

[E=2]

here

[V=8]

and so on

答:
```<code>    string input = "thinking of[ using BBCode format [A=16] here [E=2] and [V=8] and so on";
    var firstText= Regex.Match(input, @".+?(?=\[A)"); //Match until [A
    Console.WriteLine(firstText); //thinking of[ using BBCode format
    input = Regex.Replace(input, @".+?(?=\[A)", "");
    var AValue = Regex.Match(input, @"\[A=[0-9]+\]"); //Match the value of A
    input = Regex.Replace(input, @"\[A=[0-9]+\] ", "");
    Console.WriteLine(AValue); //[A=16]
    var AText = Regex.Match(input, @".+?(?=\[)"); //Match the text after A
    Console.WriteLine(AText); // here
</code>```

One huge regex is hard to understand, so I would just use some more lines on this. This for example matches the wanted text and then removes it from the input. This way you can capture the groups one by one and it's clear which part of the code captures which text, in case the regex needs to be modified in the future.

Body:
I am trying to create a .net regex that will capture the whole string into different groups. Capturing the groups is easy but capturing the rest is beyond me.

The [BBCode] markers could happen anywhere in the string, or be the only thing, or not be present at all. There also maybe [ brackets ] in the string.

Having group names would be a bonus.

class Program
{
    static void Main(string[] args)
    {
        string input = "thinking [ of using ] BBCode format [A=16] and [E=2] here [V=8] and so on";
        string regexString = @"((\[A=[0-9]+\])|(\[E=[0-9]+\])|(\[V=[0-9]+\]))";
        MatchCollection matches = Regex.Matches(input, regexString);

        foreach (Match match in matches)
        {
            Console.WriteLine(match.Value);
        }
   }
}

The result I am after is (one group per line)

thinking [ of using ] BBCode format

[A=16]

and

[E=2]

here

[V=8]

and so on

Body:
    string input = "thinking of[ using BBCode format [A=16] here [E=2] and [V=8] and so on";
    var firstText= Regex.Match(input, @".+?(?=\[A)"); //Match until [A
    Console.WriteLine(firstText); //thinking of[ using BBCode format
    input = Regex.Replace(input, @".+?(?=\[A)", "");
    var AValue = Regex.Match(input, @"\[A=[0-9]+\]"); //Match the value of A
    input = Regex.Replace(input, @"\[A=[0-9]+\] ", "");
    Console.WriteLine(AValue); //[A=16]
    var AText = Regex.Match(input, @".+?(?=\[)"); //Match the text after A
    Console.WriteLine(AText); // here

One huge regex is hard to understand, so I would just use some more lines on this. This for example matches the wanted text and then removes it from the input. This way you can capture the groups one by one and it's clear which part of the code captures which text, in case the regex needs to be modified in the future.


问:
How to get the value of a custom attribute in angular js
I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.

 then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.

In this case I got undefined in alert($attrs.test)

Full code...

```<code><html>
<script src="angular.min.js"></script>
<body ng-app="myApp">

<div ng-controller="kumar" >
 <button ng-click="check()" test="def">Click</button>
</div>

 <script>
 var app = angular.module("myApp", []);
 app.directive("test", function() {
  return {
    //template : "<h1>Hello</h1>"
  };
});

 app.controller("kumar",function($scope,$attrs){
    $scope.check=function(){
      alert(JSON.stringify($attrs.test));   //getting undefined. I
                      //should get def.
  }
});
</script>

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

答:
You can check it:</p>

```<code><html>
<script src="src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js""></script>
<body ng-app="myApp">

<div ng-controller="kumar" >
 <button ng-click="check()" test="def">Click</button>
</div>

 <script>
 var app = angular.module("myApp", []);
 app.directive("test", function() {
  return {
    //template : "<h1>Hello</h1>"
  };
});

 app.controller("kumar",function($scope,$attrs){
    $scope.check=function(){
    var testa=$scope.test;
      alert(JSON.stringify(testa));   //getting undefined. I
                      //should get def.
  }
});
</script>

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

Body:
I have created a custom attribute called test in angular js. When I write the test attribute just beside the ng-controller keyword i.d.

 then I can access that test from the controller by using alert($attrs.test). But if I write the custom attribute test other than beside of the ng-controller keyword, I can't access that. i.e.

In this case I got undefined in alert($attrs.test)

Full code...

 <button ng-click="check()" test="def">Click</button>

Body:
You can check it:

<html>
<script src="src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js""></script>
<body ng-app="myApp">

<div ng-controller="kumar" >
 <button ng-click="check()" test="def">Click</button>
</div>

 <script>
 var app = angular.module("myApp", []);
 app.directive("test", function() {
  return {
    //template : "<h1>Hello</h1>"
  };
});

 app.controller("kumar",function($scope,$attrs){
    $scope.check=function(){
    var testa=$scope.test;
      alert(JSON.stringify(testa));   //getting undefined. I
                      //should get def.
  }
});
</script>

</body>
</html>


问:
ListView Inside Child TreeViewItem?
Hey guys,
I have a WPF TreeView that has three nodes, I would like the last child (the third node) to contain a ListView populated with my bound data.  The issue that I'm running into is that if I put a ListView in the ItemTemplate of my HierarchicalDataTemplate I get a ListView for each child rather than a single ListView with content. This is expected behavior per the documentation, but I'm looking for a work around (possibly modify the ItemContainerStyle), unfortunately I have virtually no experience with the TreeViewItem's control template, or for that matter much experience with TreeViews in general.

I've looked at the posibility of using a TreeListView but it doesn't fit my use case, nor does binding a separate control and displaying data that way.

Has anyone either already gone through the headache of sandwiching a ListView into a TreeViewItem, or can someone suggest how to modify the ControlTemplate to accomplish this?

Thank you,
Aj

答:
The node that has the Listview should be a different data type than the other two nodes so it can be handled differently by the Treeview.
Also it sounds like the child that contains the list view data should not be in a HierarchicalDataTemplate but a regular DataTemplate one, since it doesn't have other child elements recognized by the Treeview. You can mix and match HierarchicalDataTemplate and regular DataTemplates in a Treeview as you see fit, regular DataTemplates represent "leaf" nodes, they don't have any children.

sample with different data types used in Treeview but still using hierarchical templates:

```<code><HierarchicalDataTemplate DataType="{x:Type FooNormal}" ItemsSource="{Binding TreeviewChildNodeCollection}">
   // do something else here.
</HierarchicalDataTemplate>

<HierarchicalDataTemplate DataType="{x:Type FooList}" ItemsSource="{Binding TreeviewChildNodeCollection}">
  <ListView  ItemsSource="{Binding ListviewChildNodeCollection}">
   //use listview here
  </ListView>
</HierarchicalDataTemplate>
</code>```

Title: ListView Inside Child TreeViewItem?

Body:
The node that has the Listview should be a different data type than the other two nodes so it can be handled differently by the Treeview.
Also it sounds like the child that contains the list view data should not be in a HierarchicalDataTemplate but a regular DataTemplate one, since it doesn't have other child elements recognized by the Treeview. You can mix and match HierarchicalDataTemplate and regular DataTemplates in a Treeview as you see fit, regular DataTemplates represent "leaf" nodes, they don't have any children.

sample with different data types used in Treeview but still using hierarchical templates:

<HierarchicalDataTemplate DataType="{x:Type FooNormal}" ItemsSource="{Binding TreeviewChildNodeCollection}">
   // do something else here.
</HierarchicalDataTemplate>

<HierarchicalDataTemplate DataType="{x:Type FooList}" ItemsSource="{Binding TreeviewChildNodeCollection}">
  <ListView  ItemsSource="{Binding ListviewChildNodeCollection}">
   //use listview here
  </ListView>
</HierarchicalDataTemplate>


问:
save state of togglebutton android
Can anyone tell me why this doesn't work please? I am trying to save the state of the togglebutton, but everytime I close the app and start again, it goes back to off. I want the state to be remembered, so when someone adds something to their favourites, to remember it as being added to favourite.

private String state = "State";

```<code>public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recipe_menu, menu);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(readState());
    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                // The toggle is enabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_black_24dp));
            else
                // The toggle is disabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));

            saveState(isChecked);
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private void saveState(boolean isFavourite) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putBoolean(state, isFavourite).apply();
}
private boolean readState() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return sharedPreferences.getBoolean(state, true);
}
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));
    toggleButton.setChecked(readState());
}
</code>```

答:
```<code>toggleButton.setChecked(sharedPreferences.getBoolean("toggleButton", true));
</code>```

The above line is resetting the state of checkbox. Hence it needs to be removed. Moreover the Strings like "Favourite" and "State" should be defined as constants.In case of spelling mistakes in one or the other line,this can also lead to unexpected results.

Title: save state of togglebutton android

Body:
Can anyone tell me why this doesn't work please? I am trying to save the state of the togglebutton, but everytime I close the app and start again, it goes back to off. I want the state to be remembered, so when someone adds something to their favourites, to remember it as being added to favourite.

private String state = "State";

public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.recipe_menu, menu);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setChecked(readState());
    toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            if (isChecked)
                // The toggle is enabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_black_24dp));
            else
                // The toggle is disabled
                toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));

            saveState(isChecked);
        }
    });
    return super.onCreateOptionsMenu(menu);
}

private void saveState(boolean isFavourite) {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    sharedPreferences.edit().putBoolean(state, isFavourite).apply();
}
private boolean readState() {
    SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
    return sharedPreferences.getBoolean(state, true);
}
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    toggleButton = (ToggleButton) findViewById(R.id.myToggleButton);
    toggleButton.setBackgroundDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.ic_favorite_border_black_24dp));
    toggleButton.setChecked(readState());
}

Body:
toggleButton.setChecked(sharedPreferences.getBoolean("toggleButton", true));

The above line is resetting the state of checkbox. Hence it needs to be removed. Moreover the Strings like "Favourite" and "State" should be defined as constants.In case of spelling mistakes in one or the other line,this can also lead to unexpected results.


问:
No module named 'info' on fresh Python 3 installation
I did a fresh python3 installation on OSX via homebrew:

```<code>brew install python3
</code>```

Then I created a virtual environment for my project and installed scipy and scikits.samplerate:

```<code>virtualenv -p /usr/local/bin/python3 pythen_env
pip install scipy
pip install scikits.samplerate
</code>```

However, when I try to import a function from scikits.samplerate, I get the following error:

```<code>>>> from scikits.samplerate import resample
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/__init__.py", line 4, in <module>
    from info import __doc__
ModuleNotFoundError: No module named 'info'
</code>```

Info happens to be the first module from the package itself that is imported in __init__.py.

Strangely, the module info.py exists in /my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/:

```<code>ls /my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/
__init__.py    setup.py        tests        __pycache__
info.py        setuphelp.py    version.py
</code>```

The error also happens when I try the same without virtualenv, as well as for other packages. How could I start to debug this issue?

答:
The problem seems to be that the package scikits.samplerate does not support Python 3.X (see issue). However, there is a fork which supports Python 3.X. You can install it via

```<code>$ pip install git+https://github.com/gregorias/samplerate.git
</code>```

As always: people can make anything they like in repositories. I did not check which changes gregorias made.

Body:
I did a fresh python3 installation on OSX via homebrew:

brew install python3

Then I created a virtual environment for my project and installed scipy and scikits.samplerate:

virtualenv -p /usr/local/bin/python3 pythen_env
pip install scipy
pip install scikits.samplerate

However, when I try to import a function from scikits.samplerate, I get the following error:

>>> from scikits.samplerate import resample
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/__init__.py", line 4, in <module>
    from info import __doc__
ModuleNotFoundError: No module named 'info'

Info happens to be the first module from the package itself that is imported in __init__.py.

Strangely, the module info.py exists in /my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/:

ls /my/project/path/pythen_env/lib/python3.6/site-packages/scikits/samplerate/
__init__.py    setup.py        tests        __pycache__
info.py        setuphelp.py    version.py

The error also happens when I try the same without virtualenv, as well as for other packages. How could I start to debug this issue?

Body:
The problem seems to be that the package scikits.samplerate does not support Python 3.X (see issue). However, there is a fork which supports Python 3.X. You can install it via

$ pip install git+https://github.com/gregorias/samplerate.git

As always: people can make anything they like in repositories. I did not check which changes gregorias made.


问:
Docker Jenkins images login error
I'm new to docker, i trying to use jenkins on docker. So I pull jenkins image with this command

```<code>docker pull jenkins
</code>```

Jenkins installed without any error. After that i started jenkins image like the document said. https://hub.docker.com/r/_/jenkins/

```<code>docker run -p 8080:8080 -p 50000:50000 -v /your/home:/var/jenkins_home jenkins
</code>```

So I tried to login http://localhost:8080/ but I got login error. And its said go to https://wiki.jenkins-ci.org/display/JENKINS/Logging for check. I checked and I need to open  /var/log/jenkins/jenkins.log file to generated admin password.
I tried to reach that filed with bash. I didn't get the file.

How can I reach the file ? How to reach my generated password or jenkins files on docker etc.

Thank you.

答:
The password was saved to /var/jenkins_home/secrets/initialAdminPassword.

You can use

```<code>docker exec <container> cat /var/jenkins_home/secrets/initialAdminPassword
</code>```

where <container> is your container id or name.

Title: Docker Jenkins images login error

Body:
I'm new to docker, i trying to use jenkins on docker. So I pull jenkins image with this command

docker pull jenkins

Jenkins installed without any error. After that i started jenkins image like the document said. https://hub.docker.com/r/_/jenkins/

docker run -p 8080:8080 -p 50000:50000 -v /your/home:/var/jenkins_home jenkins

So I tried to login http://localhost:8080/ but I got login error. And its said go to https://wiki.jenkins-ci.org/display/JENKINS/Logging for check. I checked and I need to open  /var/log/jenkins/jenkins.log file to generated admin password.
I tried to reach that filed with bash. I didn't get the file.

How can I reach the file ? How to reach my generated password or jenkins files on docker etc.

Thank you.

Body:
The password was saved to /var/jenkins_home/secrets/initialAdminPassword.

You can use

docker exec <container> cat /var/jenkins_home/secrets/initialAdminPassword

where <container> is your container id or name.


问:
i wrote this c programme for bubble sorting. it does fine, but is it truly bubble sorting logic?
this programme i wrote as an alternative way for bubble logic.it is working fine. but is it truly bubble logic programme or not

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

int main()
{
  int data[5], i, steps, temp, j, k;
  int n = 5;

  for (i = 0; i < n; ++i) {
    printf("%d. Enter element: ", i + 1);
    scanf("%d", &data[i]);
  }

  for (k = 0; k < n; k++) {
    for (j = 0; j < n; j++) {
      for (steps = 0 + j; steps <= j; steps++) {
        printf("%d\n\n", steps);

        if (data[steps] > data[steps + 1]) {
          temp = data[steps];
          data[steps] = data[steps + 1];
          data[steps + 1] = temp;
        }
      }
    }
  }

  printf("In ascending order: ");
  for (i = 0; i < n; ++i) printf("%d  ", data[i]);
  getch();
}
</code>```

any ideas?

答:
Although bubble sort is a very inefficient sorting method, the "best" algorithm I found is (in pseudo code):</p>

```<code>  sort (A, n)       // bubble sort array A[0..n-1]

    k= n-1;         // k holds position of last interchange. All higher elements are sorted.
    while (k > 0)
    {
        l= 0;
        for (j=0; j < k; j++)
        {
            if (A[j] > A[j+1])
            {
                tmp   = A[j];
                A[j]  = A[j+1];
                A[j+1]= tmp;
                l= j;
            }
        }
        k= l;
    }
</code>```

Body:
this programme i wrote as an alternative way for bubble logic.it is working fine. but is it truly bubble logic programme or not

#include <conio.h>
#include <stdio.h>

int main()
{
  int data[5], i, steps, temp, j, k;
  int n = 5;

  for (i = 0; i < n; ++i) {
    printf("%d. Enter element: ", i + 1);
    scanf("%d", &data[i]);
  }

  for (k = 0; k < n; k++) {
    for (j = 0; j < n; j++) {
      for (steps = 0 + j; steps <= j; steps++) {
        printf("%d\n\n", steps);

        if (data[steps] > data[steps + 1]) {
          temp = data[steps];
          data[steps] = data[steps + 1];
          data[steps + 1] = temp;
        }
      }
    }
  }

  printf("In ascending order: ");
  for (i = 0; i < n; ++i) printf("%d  ", data[i]);
  getch();
}

any ideas?

Body:
Although bubble sort is a very inefficient sorting method, the "best" algorithm I found is (in pseudo code):

  sort (A, n)       // bubble sort array A[0..n-1]

    k= n-1;         // k holds position of last interchange. All higher elements are sorted.
    while (k > 0)
    {
        l= 0;
        for (j=0; j < k; j++)
        {
            if (A[j] > A[j+1])
            {
                tmp   = A[j];
                A[j]  = A[j+1];
                A[j+1]= tmp;
                l= j;
            }
        }
        k= l;
    }


答:
Try the below code if it helps,</p>

```<code><?php
$update_list = $db->query('select * from `update` where home = 1 order by category desc, id desc LIMIT 0, 10');
$currentcategory = false;
foreach($update_list as $field => $value) {
  if($currentcategory != $value['category']) {
    if($currentcategory != false) {
      echo '<br>';
    }
    echo $value['category'].' - ';
    $currentcategory = $value['category'];
  }
  else {
    echo ' > ';
  }
  if($value['link'] != '') {
    echo '<a href="'.$value['link'].'" class="new5_text">'.$value['name'].'</a> - ';
  }
  if($value['singers'] != '') {
    echo '['.$value['singers'].']';
  }
} ?>
</code>```

Title: Not getting expected results through foreach loop

Body:
I have following table structure

    Updates
    +----------------------------------------------------------------------------+
    |    Id |    name    |    category    |     link    |    artist    |   home   |
    +---------------------------------------------------------------------------+
    |     1 |   song_1   |     single     |    ####     |   artist_1   |       1  |
    +-------+------------+----------------+-------------+--------------+
    |     2 |   song_2   |   bollywood    |    ####     |   artist_2   |       1  |
    +-------+------------+----------------+-------------+--------------+
    |     3 |   song_3   |     single     |    ####     |   artist_3   |       1  |
    +-------+------------+----------------+-------------+--------------+
    |     4 |   song_4   |   bollywood    |    ####     |   artist_4   |       1  |
    +------------------------------------------------------------------+

My code for fetch results.

    <?php $update_list = $db->query('select * from `update` where home = 1 order by id desc LIMIT 0, 10');
    foreach($update_list as $field => $value)
    {
    print_r($value['category']' - ');
    if($value['link'] != '') { print_r(''.$value['name'].' - - ');
     }
    if($value['singers'] != '') {
    print_r('['.$value['singers'].']');
    } ?>

I'm getting following results

    single - song_1- [artist_1]
    bollywood - song_2 - [artist_2]
    single - song_3 - [artist_3]
    bollywood - song_4 - [artist_4]

I want results like this, by above single  query.

    single - song_1 - [artist_1] > song_3 - [artist_3]
    bollywood - song_2 - [artist_2] > song_4 - [artist_4]

Can't figure out how to code it.
Help me please, suggest me a way which php function to use here.

Body:
Try the below code if it helps,

<?php
$update_list = $db->query('select * from `update` where home = 1 order by category desc, id desc LIMIT 0, 10');
$currentcategory = false;
foreach($update_list as $field => $value) {
  if($currentcategory != $value['category']) {
    if($currentcategory != false) {
      echo '<br>';
    }
    echo $value['category'].' - ';
    $currentcategory = $value['category'];
  }
  else {
    echo ' > ';
  }
  if($value['link'] != '') {
    echo '<a href="'.$value['link'].'" class="new5_text">'.$value['name'].'</a> - ';
  }
  if($value['singers'] != '') {
    echo '['.$value['singers'].']';
  }
} ?>


问:
Git, merge two remote branches
I created second branch -> git checkout -b branch2
After it, created any file, add, commit and push to branch2.

Now I checkout to master branch. How can I added new_file from branch2 to master branch? Any merge option -> your branch is up to date.

答:
There is not much information about your problem. However,

You can use git pull origin branch2 while you are on master. This will pull all the updates on branch2 to master.

Here origin is your remote. In case of confusion, consider using gitk, which is a very handy tool to visually represent the git repository.

Title: Git, merge two remote branches


问:
Subnet Address with FLSM Method?
I'm web programmer and i'm not familiar with networking , i have this next question i have searched many articles on the internet but it was not helpful and i found difficulties with understanding subnetting .. i preach it anyone who can help me to solve this question :)

The question is :

You have been allocated a class B network address: 165.10.0.0/16

```<code>Departments   Number of employees
D1                   800
D2                   200
D3                    50
D4                   1600
D5                   210
D6                    60
D7                    60
D8                    36
D9                    210
</code>```

How to distribute this addresses over the departments with FLSM Method ?

答:
Host bits will be 11... Means each n/w will have 2^11 hosts
N/w bits will be 21... Means there will be (16-11) ie 5.. ie 2^5 n/w ie 32 n/w
SM = 255.255.248.0</p>

Title: Subnet Address with FLSM Method?

Body:
I'm web programmer and i'm not familiar with networking , i have this next question i have searched many articles on the internet but it was not helpful and i found difficulties with understanding subnetting .. i preach it anyone who can help me to solve this question :)

The question is :

You have been allocated a class B network address: 165.10.0.0/16

Departments   Number of employees
D1                   800
D2                   200
D3                    50
D4                   1600
D5                   210
D6                    60
D7                    60
D8                    36
D9                    210

How to distribute this addresses over the departments with FLSM Method ?