问:
How to get values from input types using this.refs in reactjs?
Not able to get values of input type using this.refs...
how to get that values from input type</p>

```<code>   export class BusinessDetailsForm extends Component {
      submitForm(data) {
        console.log(this.refs.googleInput.value)
        }
      }
      reder() {
        return(
          <form onSubmit={this.submitForm}>
            <Field type="text"
              name="location"
              component={GoogleAutoComplete}
              id="addressSearchBoxField"
              ref="googleInput"
            />
          </form>
        )
      }
    }
</code>```

答:
You should avoid ref="googleInput" as it is now considered legacy. You should instead declare

```<code>ref={(googleInput) => { this.googleInput = googleInput }}
</code>```

Inside of your handler, you can use this.googleInput to reference the element.

Then inside of your submitForm function, you can obtain the text value with
this.googleInput._getText()

String refs are legacy
https://facebook.github.io/react/docs/refs-and-the-dom.html

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

Edit

From React 16.3, the format for creating refs are:

```<code>class Component extends React.Component
{
        constructor()
        {
            this.googleInput = React.createRef();
        }

        render()
        {
            return
            (
                <div ref={this.googleInput}>
                    {/* Details */}
                </div>
            );
        }
    }
</code>```

Body:
Not able to get values of input type using this.refs...
how to get that values from input type

   export class BusinessDetailsForm extends Component {
      submitForm(data) {
        console.log(this.refs.googleInput.value)
        }
      }
      reder() {
        return(
          <form onSubmit={this.submitForm}>
            <Field type="text"
              name="location"
              component={GoogleAutoComplete}
              id="addressSearchBoxField"
              ref="googleInput"
            />
          </form>
        )
      }
    }

Body:
You should avoid ref="googleInput" as it is now considered legacy. You should instead declare

ref={(googleInput) => { this.googleInput = googleInput }}

Inside of your handler, you can use this.googleInput to reference the element.

Then inside of your submitForm function, you can obtain the text value with
this.googleInput._getText()

String refs are legacy
https://facebook.github.io/react/docs/refs-and-the-dom.html

If you worked with React before, you might be familiar with an older API where the ref attribute is a string, like "textInput", and the DOM node is accessed as this.refs.textInput. We advise against it because string refs have some issues, are considered legacy, and are likely to be removed in one of the future releases. If you're currently using this.refs.textInput to access refs, we recommend the callback pattern instead.

Edit

From React 16.3, the format for creating refs are:

class Component extends React.Component
{
        constructor()
        {
            this.googleInput = React.createRef();
        }

        render()
        {
            return
            (
                <div ref={this.googleInput}>
                    {/* Details */}
                </div>
            );
        }
    }


来源: stackexchange

问:
Sending mail with Rails 3 in development environment
I'm sure this has been asked a million times before but I can't find anything that works for me so I'm asking again!

I just need a way of sending emails using ActionMailer in rails 3.  I have followed numerous tutorials including the Railscasts tutorial on the new ActionMailer and I can see the mails being generated but I don't receive them.

I have tried a bunch of different ways but they generally amount to configuring the following settings

```<code>ActionMailer::Base.delivery_method = :smtp

ActionMailer::Base.smtp_settings = {
  :address              => "smtp.gmail.com",
  :port                 => "587",
  :domain               => "gmail.com",
  :user_name            => "xxx@gmail.com",
  :password             => "yyy",
  :authentication       => "plain",
  :enable_starttls_auto => true
}
</code>```

I have tried the above code (with valid gmail details of course) in my config/environment.rb, config/environments/development.rb and currently have it in its own initialiser config/initialisers/setup_mail.rb

I have also tried with a few different smtp servers including Gmail and Sendgrid, adjusting the smtp settings accordingly but still nothing.  I can see the mail in the terminal and the development log and that's it.

Does anyone know of any other gotcha's that I may have missed that need to be setup for ActionMailer to work?  Failing that is there a way of getting more information about why the mails aren't being sent? I have

```<code>config.action_mailer.raise_delivery_errors = true
</code>```

set in my config/development.rb but the development log still just shows the same as I see in the terminal.

For what it's worth, I am developing on a Ubuntu 10.04 laptop just in case there's any specific setup needed for that.

Many thanks

答:
I have the following in config/environments/development.rb

```<code>config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true
</code>```

The actual mail-configuration, config.actionmailer.* i have placed in config\application.rb.

Hope this helps :)

ContentLicense: CC BY-SA 2.5

Body:
I'm sure this has been asked a million times before but I can't find anything that works for me so I'm asking again!

I just need a way of sending emails using ActionMailer in rails 3.  I have followed numerous tutorials including the Railscasts tutorial on the new ActionMailer and I can see the mails being generated but I don't receive them.

I have tried a bunch of different ways but they generally amount to configuring the following settings

ActionMailer::Base.delivery_method = :smtp

ActionMailer::Base.smtp_settings = {
  :address              => "smtp.gmail.com",
  :port                 => "587",
  :domain               => "gmail.com",
  :user_name            => "xxx@gmail.com",
  :password             => "yyy",
  :authentication       => "plain",
  :enable_starttls_auto => true
}

I have tried the above code (with valid gmail details of course) in my config/environment.rb, config/environments/development.rb and currently have it in its own initialiser config/initialisers/setup_mail.rb

I have also tried with a few different smtp servers including Gmail and Sendgrid, adjusting the smtp settings accordingly but still nothing.  I can see the mail in the terminal and the development log and that's it.

Does anyone know of any other gotcha's that I may have missed that need to be setup for ActionMailer to work?  Failing that is there a way of getting more information about why the mails aren't being sent? I have

config.action_mailer.raise_delivery_errors = true

set in my config/development.rb but the development log still just shows the same as I see in the terminal.

For what it's worth, I am developing on a Ubuntu 10.04 laptop just in case there's any specific setup needed for that.

Many thanks

Body:
I have the following in config/environments/development.rb

config.action_mailer.raise_delivery_errors = true
config.action_mailer.perform_deliveries = true

The actual mail-configuration, config.actionmailer.* i have placed in config\application.rb.

Hope this helps :)


问:
Bind an event on a jquery generated element
My code is like this:

$('.flag-icon-dz').click(function() {
  var lang = 'Arab';
  var $frame = $('.goog-te-menu-frame:first');
  if (!$frame.size()) {
    console.log("Error: Could not find Google translate frame.");
    return false;
  }
  $frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
  $("li.ql-item.linkid188546").after("

").fadeIn(500);
  $('li.ql-item.linkid188546').fadeOut(500);
  return false;
});

$('.closegoogle').click(function() {
  $('.skiptranslate').contents().find('.goog-close-link > img').click();
  $('li.ql-item.linkid18854777').fadeOut('fast').remove();
  $('li.ql-item.linkid188546').fadeIn(500);
});
```

<p>The first function works great, but the second doesn't. I realize that if I copy/paste the second function in the console <strong>after</strong> the first one, it works too. </p>

<p>I tried a few solutions (callback / setTimeout / jquery deferred / jquery .when method...) I didn't try promise but I don't think I have to in my context. Maybe I didn't write these solutions good enough. </p>

<p>I finally try to put my event (click) directly the <code>.before()</code> which create my new element like this : </p>

<pre class="lang-js prettyprint-override"><code>$('.flag-icon-dz').click(function() {
  var lang = 'Arab';
  var $frame = $('.goog-te-menu-frame:first');
  if (!$frame.size()) {
    console.log("Error: Could not find Google translate frame.");
    return false;
  }
  $frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
  $("li.ql-item.linkid188546").after("<li class='ql-item linkid18854777 closegoogle'><i class='icon closegoogle ls-lang-frr' aria-hidden='true'></i></li>").fadeIn(500).click(function() {
    $('.skiptranslate').contents().find('.goog-close-link > img').click();
    $('li.ql-item.linkid18854777').fadeOut('fast').remove();
    $('li.ql-item.linkid188546').fadeIn(500);
  });
  $('li.ql-item.linkid188546').fadeOut(500);
  return false;
});
</code>```

But it doesn't work either.

Thanks for the help.

EDIT :

I finally found a kind of solution for my second click event (which isn't the best solution but i works) :

window.setInterval(function(){$('.closegoogle').on("click",function(){
$('.skiptranslate').contents().find('.goog-close-link > img').click();
  $('li.ql-item.linkid18854777').fadeOut('fast').remove();
  $('li.ql-item.linkid188546').fadeIn(500);
}); }, 1000);
```

Thanks.

答:
You need to use a delegated bind as the element does not exist before you try your binding:

```<code>$('#parent-element-of-closegoogle').on('click', '.closegoogle', function() {
  $('.skiptranslate').contents().find('.goog-close-link > img').click();
  $('li.ql-item.linkid18854777').fadeOut('fast').remove();
  $('li.ql-item.linkid188546').fadeIn(500);
});
</code>```

Please note that the #parent-element-of-closegoogle needs to be an element that already exists when you do the binding - this can be $(document) if you hjave no other element to bind to

ContentLicense: CC BY-SA 3.0

Body:
My code is like this:

$('.flag-icon-dz').click(function() {
  var lang = 'Arab';
  var $frame = $('.goog-te-menu-frame:first');
  if (!$frame.size()) {
    console.log("Error: Could not find Google translate frame.");
    return false;
  }
  $frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
  $("li.ql-item.linkid188546").after("

").fadeIn(500);
  $('li.ql-item.linkid188546').fadeOut(500);
  return false;
});

$('.closegoogle').click(function() {
  $('.skiptranslate').contents().find('.goog-close-link > img').click();
  $('li.ql-item.linkid18854777').fadeOut('fast').remove();
  $('li.ql-item.linkid188546').fadeIn(500);
});

The first function works great, but the second doesn't. I realize that if I copy/paste the second function in the console after the first one, it works too.

I tried a few solutions (callback / setTimeout / jquery deferred / jquery .when method...) I didn't try promise but I don't think I have to in my context. Maybe I didn't write these solutions good enough.

I finally try to put my event (click) directly the .before() which create my new element like this :

$('.flag-icon-dz').click(function() {
  var lang = 'Arab';
  var $frame = $('.goog-te-menu-frame:first');
  if (!$frame.size()) {
    console.log("Error: Could not find Google translate frame.");
    return false;
  }
  $frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
  $("li.ql-item.linkid188546").after("

").fadeIn(500).click(function() {
    $('.skiptranslate').contents().find('.goog-close-link > img').click();
    $('li.ql-item.linkid18854777').fadeOut('fast').remove();
    $('li.ql-item.linkid188546').fadeIn(500);
  });
  $('li.ql-item.linkid188546').fadeOut(500);
  return false;
});

But it doesn't work either.

Thanks for the help.

EDIT :

I finally found a kind of solution for my second click event (which isn't the best solution but i works) :

window.setInterval(function(){$('.closegoogle').on("click",function(){
$('.skiptranslate').contents().find('.goog-close-link > img').click();
  $('li.ql-item.linkid18854777').fadeOut('fast').remove();
  $('li.ql-item.linkid188546').fadeIn(500);
}); }, 1000);

Thanks.

Body:
You need to use a delegated bind as the element does not exist before you try your binding:

$('#parent-element-of-closegoogle').on('click', '.closegoogle', function() {
  $('.skiptranslate').contents().find('.goog-close-link > img').click();
  $('li.ql-item.linkid18854777').fadeOut('fast').remove();
  $('li.ql-item.linkid188546').fadeIn(500);
});

Please note that the #parent-element-of-closegoogle needs to be an element that already exists when you do the binding - this can be $(document) if you hjave no other element to bind to


问:
Recursive Procedure Whose Calls Resemble a Binary Tree in MIPS
I'm working on an assignment and am having difficulty understanding how to properly code the following problem in C.

```<code>int choose(int n, int k){
    if (k == 0) {
        return 1;
    } else if (n == k) {
        return 1;
    } else if (n < k) {
        return 0;
    } else {
        return choose(n-1, k-1) + choose(n-1, k);
    }
}
</code>```

My thoughts were to use three registers for storing the values onto the stack with each call $s0, $s1, $s2, where $s0 will contain the value of updated n; $s1 would maintain the value of k; and $s2 would hold the value of k in the second choose(n-1, k) since that value will only decrease when the parent call changes it.  The reason I chose this is because the value of k isn't subtracted from each call in this one, it should be the same until the parent decrements it in a previous call.

Here is the Choose procedure that I'm trying to do.  Problem is that I'm not getting the correct answer, of course.

```<code>Choose:
    #store current values onto stack
    addi $sp, $sp, -16
    sw $ra, 0($sp)
    sw $s0, 4($sp)
    sw $s1, 8($sp)
    sw $s2, 12($sp)

    #check values meet criteria to add to $v0
    beq $s1, $0, one
    beq $s0, $s1, one
    blt $s0, $s1, zero
    beq $s2, $0, one

    #no branches passed so decrement values of n and k
    subi $s0, $s0, 1
    subi $s1, $s1, 1

    #move values of registers to $a's for argument passing
    move $a0, $s0
    move $a1, $s1

    jal Choose  #call procedure again

    #this is where I'm having my problems
    #not sure how to loop the procedure to get
    #the second half of the equation Choose(n-1,k)
    #which is the reason for the next 2 lines of code
    move $a2, $s2
    jal Choose

    add $v0, $v0, $v1
    j Choose_Exit

#add one to $v1 from branch passed
one:
    addi $v1, $v1, 1
    j Choose_Exit

#branch returns 0
zero:
    addi $v1, $v1, 0
    j Choose_Exit

#return values to caller from stack
Choose_Exit:
    lw $s2, 12($sp)
    lw $s1, 8($sp)
    lw $s0, 4($sp)
    lw $ra, 0($sp)
    addi $sp, $sp, 16
    jr $ra
</code>```

So I'm having a problem understanding how to properly implement this recursive procedure twice to add them together.  I can understand how to create a recursive procedure in MIPS to perform a factorial, since that is always the definition of recursion for any language.  But using recursion with differing arguments and then add them all together is confusing me to no end.

When written out on paper, I understand that this procedure can be represented by a binary tree of parents and children.  The parent being the single function Choose(n,k) and the children being Choose(n-1, k-1) + Choose(n-1, k) and once one of the leaf children branches from the if statement, it passes a digit to the parent who will wait for the other callee portion of the addition to return its value, etc etc etc.

Any help to point me in the correct direction as to what I'm doing wrong with my approach would be great.  I understand the beginning, I understand the end, just need some assistance to help understand the most important part of the middle.

答:
Disclaimer: I rewrite the assembly code WITHOUT checking it.

There are delay-slots to consider so better to make smart use of them and to make them explicit to avoid aggregations of implicit nop instructions after branch instructions.

Reverse the order of calls between choose(n - 1,k - 1) and choose(n - 1,k) for smarter usage of $a0 and $a1 and of the stack.

Restrain stack usage for only calling choose(n - 1,k) and use tail calling for calling choose(n - 1,k - 1).

It makes more sense to stack the value of a0-1 and not a0.

We accumulate everything into $v0 instead of stacking it. We keep $t0 as a local result to add to $v0 because it is cheap while we can discard it by doing direct things with $v0.

As a result, the overall changes should make icache happier with less instructions and dcache happier with less stack space.

The assembly code:

```<code>#@+
#   int
#   choose(int n, int k)
#   {
#
#       if (k == 0)
#           return 1;
#
#       if (n == k)
#           return 1;
#
#       if (n < k)
#           return 0;
#
#       return choose(n - 1,k - 1) + choose(n - 1,k);
#   }
#@-

    .text

# choose -- choose
#
# RETURNS:
#   v0 -- return value
#
# arguments:
#   a0 -- n
#   a1 -- k
#
# registers:
#   t0 -- temp for local result to accumulate into v0
choose:
    j       choose_rec
    addui   $v0, $zr, 0             # initialize $v0 to 0 before calling
choose_rec:
    beqz    $a1,choose_one          # k == 0? if yes, fly
    addui   $t0,$zr,1               # branch delay-slot with $t0 = 1
    beq     $a0,$a1,choose_one      # n == k? if yes, fly
    nop                             # branch delay-slot with $t0 = 1 already done
    blt     $a0,$a1,choose_zero     # n < k? if yes, fly
    addui   $t0,$zr,0               # branch delay-slot with $t0 = 0

    # establish stack frame (preserve ra/a0/a1)
    sub     $sp,$sp,12
    addui   $a0,$a0,-1              # get n - 1 (common to both calls)
    sw      $ra,8($sp)
    sw      $a0,4($sp)
    jal     choose_rec              # choose(n - 1,k)
    sw      $a1,0($sp)

    # restore from stack frame
    lw      $ra,8($sp)
    lw      $a0,4($sp)
    lw      $a1,0($sp)
    add     $sp,$sp,12

    # choose(n - 1,k - 1)
    j       choose_rec              # tail call: jump instead of call
    addi    $a1,$a1,-1              # get k - 1

choose_one:
choose_zero:
    jr      $ra                     # return
    addui   $v0,$v0,$t0             # branch delay-slot with $v0 += $t0
</code>```

Body:
I'm working on an assignment and am having difficulty understanding how to properly code the following problem in C.

int choose(int n, int k){
    if (k == 0) {
        return 1;
    } else if (n == k) {
        return 1;
    } else if (n < k) {
        return 0;
    } else {
        return choose(n-1, k-1) + choose(n-1, k);
    }
}

My thoughts were to use three registers for storing the values onto the stack with each call $s0, $s1, $s2, where $s0 will contain the value of updated n; $s1 would maintain the value of k; and $s2 would hold the value of k in the second choose(n-1, k) since that value will only decrease when the parent call changes it.  The reason I chose this is because the value of k isn't subtracted from each call in this one, it should be the same until the parent decrements it in a previous call.

Here is the Choose procedure that I'm trying to do.  Problem is that I'm not getting the correct answer, of course.

Choose:
    #store current values onto stack
    addi $sp, $sp, -16
    sw $ra, 0($sp)
    sw $s0, 4($sp)
    sw $s1, 8($sp)
    sw $s2, 12($sp)

    #check values meet criteria to add to $v0
    beq $s1, $0, one
    beq $s0, $s1, one
    blt $s0, $s1, zero
    beq $s2, $0, one

    #no branches passed so decrement values of n and k
    subi $s0, $s0, 1
    subi $s1, $s1, 1

    #move values of registers to $a's for argument passing
    move $a0, $s0
    move $a1, $s1

    jal Choose  #call procedure again

    #this is where I'm having my problems
    #not sure how to loop the procedure to get
    #the second half of the equation Choose(n-1,k)
    #which is the reason for the next 2 lines of code
    move $a2, $s2
    jal Choose

    add $v0, $v0, $v1
    j Choose_Exit

#add one to $v1 from branch passed
one:
    addi $v1, $v1, 1
    j Choose_Exit

#branch returns 0
zero:
    addi $v1, $v1, 0
    j Choose_Exit

#return values to caller from stack
Choose_Exit:
    lw $s2, 12($sp)
    lw $s1, 8($sp)
    lw $s0, 4($sp)
    lw $ra, 0($sp)
    addi $sp, $sp, 16
    jr $ra

So I'm having a problem understanding how to properly implement this recursive procedure twice to add them together.  I can understand how to create a recursive procedure in MIPS to perform a factorial, since that is always the definition of recursion for any language.  But using recursion with differing arguments and then add them all together is confusing me to no end.

When written out on paper, I understand that this procedure can be represented by a binary tree of parents and children.  The parent being the single function Choose(n,k) and the children being Choose(n-1, k-1) + Choose(n-1, k) and once one of the leaf children branches from the if statement, it passes a digit to the parent who will wait for the other callee portion of the addition to return its value, etc etc etc.

Any help to point me in the correct direction as to what I'm doing wrong with my approach would be great.  I understand the beginning, I understand the end, just need some assistance to help understand the most important part of the middle.

Body:
Disclaimer: I rewrite the assembly code WITHOUT checking it.

There are delay-slots to consider so better to make smart use of them and to make them explicit to avoid aggregations of implicit nop instructions after branch instructions.

Reverse the order of calls between choose(n - 1,k - 1) and choose(n - 1,k) for smarter usage of $a0 and $a1 and of the stack.

Restrain stack usage for only calling choose(n - 1,k) and use tail calling for calling choose(n - 1,k - 1).

It makes more sense to stack the value of a0-1 and not a0.

We accumulate everything into $v0 instead of stacking it. We keep $t0 as a local result to add to $v0 because it is cheap while we can discard it by doing direct things with $v0.

As a result, the overall changes should make icache happier with less instructions and dcache happier with less stack space.

The assembly code:

#@+
#   int
#   choose(int n, int k)
#   {
#
#       if (k == 0)
#           return 1;
#
#       if (n == k)
#           return 1;
#
#       if (n < k)
#           return 0;
#
#       return choose(n - 1,k - 1) + choose(n - 1,k);
#   }
#@-

    .text

# choose -- choose
#
# RETURNS:
#   v0 -- return value
#
# arguments:
#   a0 -- n
#   a1 -- k
#
# registers:
#   t0 -- temp for local result to accumulate into v0
choose:
    j       choose_rec
    addui   $v0, $zr, 0             # initialize $v0 to 0 before calling
choose_rec:
    beqz    $a1,choose_one          # k == 0? if yes, fly
    addui   $t0,$zr,1               # branch delay-slot with $t0 = 1
    beq     $a0,$a1,choose_one      # n == k? if yes, fly
    nop                             # branch delay-slot with $t0 = 1 already done
    blt     $a0,$a1,choose_zero     # n < k? if yes, fly
    addui   $t0,$zr,0               # branch delay-slot with $t0 = 0

    # establish stack frame (preserve ra/a0/a1)
    sub     $sp,$sp,12
    addui   $a0,$a0,-1              # get n - 1 (common to both calls)
    sw      $ra,8($sp)
    sw      $a0,4($sp)
    jal     choose_rec              # choose(n - 1,k)
    sw      $a1,0($sp)

    # restore from stack frame
    lw      $ra,8($sp)
    lw      $a0,4($sp)
    lw      $a1,0($sp)
    add     $sp,$sp,12

    # choose(n - 1,k - 1)
    j       choose_rec              # tail call: jump instead of call
    addi    $a1,$a1,-1              # get k - 1

choose_one:
choose_zero:
    jr      $ra                     # return
    addui   $v0,$v0,$t0             # branch delay-slot with $v0 += $t0


问:
C# Math 3D Movement x,y,z equation
Hi guy's i got this math equation to movement the enemy x,y,z but i can't seem to replicate the result i want once am done with x,y i wanna create z movement also

So let's say i have a enemy with the movement speed of 1.5 his position is

```<code>Enemy Position: posX > 119.75013, posY > 12.1830482, posZ > 167.700226
</code>```

I want to move him to

```<code>Enemy Final Position: posX > 119.41893, posY > 11.3724937, posZ > 162.9639
</code>```

With these x,y,z result:

```<code>Enemy movement: posX > 119.645088, posY > 11.9535465, posZ > 166.198029
Enemy movement: posX > 119.539749, posY > 11.7193651, posZ > 164.691589
Enemy movement: posX > 119.479477, posY > 11.54633, posZ > 163.829742
</code>```

But the function only prints

```<code>Enemy Movement: posX 119.182753804649, posY 10.7944934646909
</code>```

Note i am not using Unity3D so i need a function that works with out unity3d..

Current function:

```<code>static void Main(string[] args)
{
    double startX = 119.75013;
    double startY = 12.1830482;
    double startZ = 167.700226;

    double x = 119.41893;
    double y = 11.3724937;
    double z = 162.9639;

    double endX = x;
    double endY = y;
    double endZ = y;

    double speed = 1.5f;

    Console.WriteLine($"Enemy Position: posX {startX}, posY {startY}, posZ {startZ}");
    Console.WriteLine($"Enemy Final Position: posX {x}, posY {y}, posZ {z}\n");

    double distance = Math.Sqrt(Math.Pow(endX - startX, 2) + Math.Pow(endY - startY, 2));
    double directionX = (endX - startX) / distance;
    double directionY = (endY - startY) / distance;

    double newlat = startX;
    double newLng = startY;

    while (Math.Sqrt(Math.Pow(newlat - startX, 2) + Math.Pow(newLng - startY, 2)) <= distance)
    {

        newlat += directionX * speed;
        newLng += directionY * speed;

        Console.WriteLine($"Enemy Movement: posX {newlat}, posY {newLng}");
    }

    Console.ReadKey();
}
</code>```

Thank you!

答:
It's quite simple, you use a speed of 1.5, that's your problem.

You compute

```<code>speed = 1.5
Δx = targetx - startx
positionx = startx
while(distance(position,target) <= distance(start,target)){
    positionx += Δx * speed
}
</code>```

At the first iteration, you already speed past the target, you are simply too fast to reach it.

If you want to have 3 positions in between start and target, you need 4 steps, therefore you should set speed to 0.25.

Which means, simply exchange double speed = 1.5f; with double speed = 0.25f;.

That said, I really really recommend that you make sure that you understand perfectly what your code does. That's why I wrote the part with the Δx. You should perfectly understand what Δx is and why it is applied as it is. If you use code without understanding it, and I suspect this, you have no chance to find a bug, should one occur. Or change the way things work. Also, you should really use classes. Your code would look much cleaner, especially if you'd use a class that represents a mathematical vector.

Title: C# Math 3D Movement x,y,z equation

Body:
Hi guy's i got this math equation to movement the enemy x,y,z but i can't seem to replicate the result i want once am done with x,y i wanna create z movement also

So let's say i have a enemy with the movement speed of 1.5 his position is

Enemy Position: posX > 119.75013, posY > 12.1830482, posZ > 167.700226

I want to move him to

Enemy Final Position: posX > 119.41893, posY > 11.3724937, posZ > 162.9639

With these x,y,z result:

Enemy movement: posX > 119.645088, posY > 11.9535465, posZ > 166.198029
Enemy movement: posX > 119.539749, posY > 11.7193651, posZ > 164.691589
Enemy movement: posX > 119.479477, posY > 11.54633, posZ > 163.829742

But the function only prints

Enemy Movement: posX 119.182753804649, posY 10.7944934646909

Note i am not using Unity3D so i need a function that works with out unity3d..

Current function:

static void Main(string[] args)
{
    double startX = 119.75013;
    double startY = 12.1830482;
    double startZ = 167.700226;

    double x = 119.41893;
    double y = 11.3724937;
    double z = 162.9639;

    double endX = x;
    double endY = y;
    double endZ = y;

    double speed = 1.5f;

    Console.WriteLine($"Enemy Position: posX {startX}, posY {startY}, posZ {startZ}");
    Console.WriteLine($"Enemy Final Position: posX {x}, posY {y}, posZ {z}\n");

    double distance = Math.Sqrt(Math.Pow(endX - startX, 2) + Math.Pow(endY - startY, 2));
    double directionX = (endX - startX) / distance;
    double directionY = (endY - startY) / distance;

    double newlat = startX;
    double newLng = startY;

    while (Math.Sqrt(Math.Pow(newlat - startX, 2) + Math.Pow(newLng - startY, 2)) <= distance)
    {

        newlat += directionX * speed;
        newLng += directionY * speed;

        Console.WriteLine($"Enemy Movement: posX {newlat}, posY {newLng}");
    }

    Console.ReadKey();
}

Thank you!

Body:
It's quite simple, you use a speed of 1.5, that's your problem.

You compute

speed = 1.5
Δx = targetx - startx
positionx = startx
while(distance(position,target) <= distance(start,target)){
    positionx += Δx * speed
}

At the first iteration, you already speed past the target, you are simply too fast to reach it.

If you want to have 3 positions in between start and target, you need 4 steps, therefore you should set speed to 0.25.

Which means, simply exchange double speed = 1.5f; with double speed = 0.25f;.

That said, I really really recommend that you make sure that you understand perfectly what your code does. That's why I wrote the part with the Δx. You should perfectly understand what Δx is and why it is applied as it is. If you use code without understanding it, and I suspect this, you have no chance to find a bug, should one occur. Or change the way things work. Also, you should really use classes. Your code would look much cleaner, especially if you'd use a class that represents a mathematical vector.


问:
UpdateModel for Nested Properties in ASP.NET MVC2
I'm currently working my way through the MvcMusicStore tutorial for the second time as a personal project. This time instead of the Entity Framework I'm attempting to use nHibernate and also some IoC using Castle Windsor.

The first hurdle that Ive hit relates to nested classes and model binding. Im able to display a list of albums and then edit them. Im also able to persist changes to database as long as I edit the Title, Price or AlbumArtUrl fields. When I attempt to edit the Artist or Genre fields then the following error occurs.

"The model of type 'MvcMusicStore.Models.Album' could not be updated."

This error occurs on the call to UpdateModel so I'm assuming its something to do with the binding but I'm completely stumped how to proceed. From the searches I've done on StackOverflow and elsewhere this seems to be a common problem but I haven't found a solution so far.

I'm hoping someone can spot what I'm doing wrong here and suggest a solution.

Album

```<code>public class Album
{
    public virtual int AlbumId { get; set; }
    public virtual Artist Artist { get; set; }
    public virtual Genre Genre { get; set; }
    public virtual string Title { get; set; }
    public virtual decimal Price { get; set; }
    public virtual string AlbumArtUrl { get; set; }
}
</code>```

StoreManagerViewModel

```<code>public class StoreManagerViewModel
{
    public Album Album { get; set; }
    public IList<Artist> Artists { get; set; }
    public IList<Genre> Genres { get; set; }
}
</code>```

Edit.aspx

```<code><%@ Page Language="C#" MasterPageFile="/Views/Shared/Site.Master"
   Inherits="System.Web.Mvc.ViewPage<MvcMusicStore.ViewModels.StoreManagerViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Edit - <%: Model.Album.Title %>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

    <h2>Edit Album</h2>

    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>

    <fieldset>
        <legend>Edit Album</legend>
        <%: Html.EditorFor(model => model.Album,
            new { Artists = Model.Artists, Genres = Model.Genres}) %>

        <p>
            <input type="submit" value="Save" />
        </p>
    </fieldset>

    <% } %>

    <div>
        <%: Html.ActionLink("Back to List", "Index") %>
    </div>

</asp:Content>
</code>```

Album.ascx

```<code><%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMusicStore.Models.Album>" %>

<div class="editor-label">
    <%: Html.LabelFor(model => model.Title) %>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.Title) %>
    <%: Html.ValidationMessageFor(model => model.Title) %>
</div>

<div class="editor-label">
    <%: Html.LabelFor(model => model.Price) %>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.Price, String.Format("{0:F}", Model.Price)) %>
    <%: Html.ValidationMessageFor(model => model.Price) %>
</div>

<div class="editor-label">
    <%: Html.LabelFor(model => model.AlbumArtUrl) %>
</div>
<div class="editor-field">
    <%: Html.TextBoxFor(model => model.AlbumArtUrl) %>
    <%: Html.ValidationMessageFor(model => model.AlbumArtUrl) %>
</div>

<div class="editor-label">
    <%: Html.LabelFor(model => model.Artist)%>
</div>
<div class="editor-field">
    <%: Html.DropDownListFor(model => model.Artist, new SelectList(ViewData["Artists"] as IEnumerable, "ArtistId", "Name", Model.Artist))%>
</div>

<div class="editor-label">
    <%: Html.LabelFor(model => model.Genre)%>
</div>
<div class="editor-field">
    <%: Html.DropDownListFor(model => model.Genre, new SelectList(ViewData["Genres"] as IEnumerable, "GenreId", "Name", Model.Genre))%>
</div>
</code>```

StoreManagerController

```<code>    public ActionResult Edit(int id)
    {
        var viewModel = new StoreManagerViewModel
        {
            Album = AlbumRepository.GetById(id),
            Genres = GenreRepository.GetAll().ToList(),
            Artists = ArtistRepository.GetAll().ToList(),
        };

        return View(viewModel);
    }

    [HttpPost, UnitOfWork]
    public ActionResult Edit(int id, FormCollection formValues)
    {
        var album = AlbumRepository.GetById(id);

        try
        {
            UpdateModel(album, "Album");
            AlbumRepository.SaveOrUpdate(album);

            return RedirectToAction("Index");
        }
        catch
        {
            var viewModel = new StoreManagerViewModel
            {
                Album = album,
                Genres = GenreRepository.GetAll().ToList(),
                Artists = ArtistRepository.GetAll().ToList(),
            };

            return View(viewModel);
        }
    }
</code>```

UPDATE 1:

If I breakpoint at UpdateModel and look at ValueProvider.GetValue("Album.Artist"), I can see the updated ArtistId. This suggests to me Ive completely misunderstood how this should work.

Should I really be letting UpdateModel handle the properties it can like so:

```<code>UpdateModel(album, "Album", new string[] { "Title", "Price", "AlbumArtUrl" });
</code>```

And then manually updating the Artist and Genre properties by fetching the objects myself based on the ArtistId, GenreId in the ValueProvider?

UPDATE 2

A fix of sorts?

Album.ascx

```<code><div class="editor-label">
    <%: Html.LabelFor(model => model.Artist)%>
</div>
<div class="editor-field">
    <%: Html.DropDownListFor(model => model.Artist, new SelectList(ViewData["Artists"] as IEnumerable, "ArtistId", "Name", Model.Artist.ArtistId))%>
</div>

<div class="editor-label">
    <%: Html.LabelFor(model => model.Genre)%>
</div>
<div class="editor-field">
    <%: Html.DropDownListFor(model => model.Genre, new SelectList(ViewData["Genres"] as IEnumerable, "GenreId", "Name", Model.Genre.GenreId))%>
</div>
</code>```

StoreManagerController

```<code>UpdateModel(album, "Album", new string[] { "Title", "Price", "AlbumArtUrl" });
album.Artist = ArtistRepository.GetById(Int32.Parse(formValues["Album.Artist"]));
album.Genre = GenreRepository.GetById(Int32.Parse(formValues["Album.Genre"]));
AlbumRepository.SaveOrUpdate(album);
</code>```

This works, I dont know if its how this sort of thing should be done or not. Would appreciate someone putting me right if its not?

答:
You have to provide your logic in UpdateModel()

Also if you have strongly typed view, you can use your model as a controller parameter instead FormCollection. Also it is a good practice to exclude id of edited album.

```<code>ActionResult Edit([Bind(Exclude = "AlbumId")]Album album)
</code>```

And you'll get in album all fields from your form for editing.

About your code:

Now I see in your code that you get by id current album in your db

```<code> var album = AlbumRepository.GetById(id);
</code>```

and then try to do some actions with it, and it is not clear how you bind information from view.

Body:
I'm currently working my way through the MvcMusicStore tutorial for the second time as a personal project. This time instead of the Entity Framework I'm attempting to use nHibernate and also some IoC using Castle Windsor.

The first hurdle that Ive hit relates to nested classes and model binding. Im able to display a list of albums and then edit them. Im also able to persist changes to database as long as I edit the Title, Price or AlbumArtUrl fields. When I attempt to edit the Artist or Genre fields then the following error occurs.

"The model of type 'MvcMusicStore.Models.Album' could not be updated."

This error occurs on the call to UpdateModel so I'm assuming its something to do with the binding but I'm completely stumped how to proceed. From the searches I've done on StackOverflow and elsewhere this seems to be a common problem but I haven't found a solution so far.

I'm hoping someone can spot what I'm doing wrong here and suggest a solution.

Album

public class Album
{
    public virtual int AlbumId { get; set; }
    public virtual Artist Artist { get; set; }
    public virtual Genre Genre { get; set; }
    public virtual string Title { get; set; }
    public virtual decimal Price { get; set; }
    public virtual string AlbumArtUrl { get; set; }
}

StoreManagerViewModel

public class StoreManagerViewModel
{
    public Album Album { get; set; }
    public IList<Artist> Artists { get; set; }
    public IList<Genre> Genres { get; set; }
}

Edit.aspx

<%@ Page Language="C#" MasterPageFile="/Views/Shared/Site.Master"
   Inherits="System.Web.Mvc.ViewPage<MvcMusicStore.ViewModels.StoreManagerViewModel>" %>

<asp:Content ID="Content1" ContentPlaceHolderID="TitleContent" runat="server">
    Edit - <%: Model.Album.Title %>
</asp:Content>

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">

Edit Album

    <% using (Html.BeginForm()) {%>
        <%: Html.ValidationSummary(true) %>

    <fieldset>
        <legend>Edit Album</legend>
        <%: Html.EditorFor(model => model.Album,
            new { Artists = Model.Artists, Genres = Model.Genres}) %>

            <input type="submit" value="Save" />

    </fieldset>

    <% } %>

        <%: Html.ActionLink("Back to List", "Index") %>

</asp:Content>

Album.ascx

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<MvcMusicStore.Models.Album>" %>

    <%: Html.LabelFor(model => model.Title) %>

    <%: Html.TextBoxFor(model => model.Title) %>
    <%: Html.ValidationMessageFor(model => model.Title) %>

    <%: Html.LabelFor(model => model.Price) %>

    <%: Html.TextBoxFor(model => model.Price, String.Format("{0:F}", Model.Price)) %>
    <%: Html.ValidationMessageFor(model => model.Price) %>

    <%: Html.LabelFor(model => model.AlbumArtUrl) %>

    <%: Html.TextBoxFor(model => model.AlbumArtUrl) %>
    <%: Html.ValidationMessageFor(model => model.AlbumArtUrl) %>

    <%: Html.LabelFor(model => model.Artist)%>

    <%: Html.DropDownListFor(model => model.Artist, new SelectList(ViewData["Artists"] as IEnumerable, "ArtistId", "Name", Model.Artist))%>

    <%: Html.LabelFor(model => model.Genre)%>

    <%: Html.DropDownListFor(model => model.Genre, new SelectList(ViewData["Genres"] as IEnumerable, "GenreId", "Name", Model.Genre))%>

StoreManagerController

    public ActionResult Edit(int id)
    {
        var viewModel = new StoreManagerViewModel
        {
            Album = AlbumRepository.GetById(id),
            Genres = GenreRepository.GetAll().ToList(),
            Artists = ArtistRepository.GetAll().ToList(),
        };

        return View(viewModel);
    }

    [HttpPost, UnitOfWork]
    public ActionResult Edit(int id, FormCollection formValues)
    {
        var album = AlbumRepository.GetById(id);

        try
        {
            UpdateModel(album, "Album");
            AlbumRepository.SaveOrUpdate(album);

            return RedirectToAction("Index");
        }
        catch
        {
            var viewModel = new StoreManagerViewModel
            {
                Album = album,
                Genres = GenreRepository.GetAll().ToList(),
                Artists = ArtistRepository.GetAll().ToList(),
            };

            return View(viewModel);
        }
    }

UPDATE 1:

If I breakpoint at UpdateModel and look at ValueProvider.GetValue("Album.Artist"), I can see the updated ArtistId. This suggests to me Ive completely misunderstood how this should work.

Should I really be letting UpdateModel handle the properties it can like so:

UpdateModel(album, "Album", new string[] { "Title", "Price", "AlbumArtUrl" });

And then manually updating the Artist and Genre properties by fetching the objects myself based on the ArtistId, GenreId in the ValueProvider?

UPDATE 2

A fix of sorts?

Album.ascx

    <%: Html.LabelFor(model => model.Artist)%>

    <%: Html.DropDownListFor(model => model.Artist, new SelectList(ViewData["Artists"] as IEnumerable, "ArtistId", "Name", Model.Artist.ArtistId))%>

    <%: Html.LabelFor(model => model.Genre)%>

    <%: Html.DropDownListFor(model => model.Genre, new SelectList(ViewData["Genres"] as IEnumerable, "GenreId", "Name", Model.Genre.GenreId))%>

StoreManagerController

UpdateModel(album, "Album", new string[] { "Title", "Price", "AlbumArtUrl" });
album.Artist = ArtistRepository.GetById(Int32.Parse(formValues["Album.Artist"]));
album.Genre = GenreRepository.GetById(Int32.Parse(formValues["Album.Genre"]));
AlbumRepository.SaveOrUpdate(album);

This works, I dont know if its how this sort of thing should be done or not. Would appreciate someone putting me right if its not?

Body:
You have to provide your logic in UpdateModel()

Also if you have strongly typed view, you can use your model as a controller parameter instead FormCollection. Also it is a good practice to exclude id of edited album.

ActionResult Edit([Bind(Exclude = "AlbumId")]Album album)

And you'll get in album all fields from your form for editing.

About your code:

Now I see in your code that you get by id current album in your db

 var album = AlbumRepository.GetById(id);

and then try to do some actions with it, and it is not clear how you bind information from view.


问:
Stopping the agent: Reason = sig.kill in cloudstack kvm agent
I work with cloudstack4.9.2.0, have add a kvm host, the agent has started but it always crashed with log message:

```<code>[cloud.agent.Agent] (AgentShutdownThread:null) (logid:) Stopping the agent: Reason = sig.kill
</code>```

and there is no more useful error message.
But when I use dmesg, I see these:

```<code>[18343.770338] libvirtd[5320]: segfault at 7fd34826c313 ip 00007fd34826c313 sp 00007fd343deacf0 error 14 in libnss_sss.so.2[7fd349a0f000+8000]

[18493.759889] libvirtd[10687]: segfault at 7f2d3ad17313 ip 00007f2d3ad17313 sp 00007f2d5016bcf0 error 14

[18642.749523] libvirtd[16073]: segfault at 7f098e654313 ip 00007f098e654313 sp 00007f09a4114cf0 error 14 in libnss_sss.so.2[7f098fdf7000+8000]

[18792.739096] libvirtd[21469]: segfault at 7f374ed17313 ip 00007f374ed17313 sp 00007f374e8dccf0 error 14

[18926.729704] libvirtd[26724]: segfault at 7fbaf62a9313 ip 00007fbaf62a9313 sp 00007fbaf5e6ecf0 error 14
</code>```

does anyone know what is going on?

答:
Looks like agent is being killed for some reason.
Can you check if Kvm host is able to access 8250 port of cloudstack server ?</p>

Body:
I work with cloudstack4.9.2.0, have add a kvm host, the agent has started but it always crashed with log message:

[cloud.agent.Agent] (AgentShutdownThread:null) (logid:) Stopping the agent: Reason = sig.kill

and there is no more useful error message.
But when I use dmesg, I see these:

[18343.770338] libvirtd[5320]: segfault at 7fd34826c313 ip 00007fd34826c313 sp 00007fd343deacf0 error 14 in libnss_sss.so.2[7fd349a0f000+8000]

[18493.759889] libvirtd[10687]: segfault at 7f2d3ad17313 ip 00007f2d3ad17313 sp 00007f2d5016bcf0 error 14

[18642.749523] libvirtd[16073]: segfault at 7f098e654313 ip 00007f098e654313 sp 00007f09a4114cf0 error 14 in libnss_sss.so.2[7f098fdf7000+8000]

[18792.739096] libvirtd[21469]: segfault at 7f374ed17313 ip 00007f374ed17313 sp 00007f374e8dccf0 error 14

[18926.729704] libvirtd[26724]: segfault at 7fbaf62a9313 ip 00007fbaf62a9313 sp 00007fbaf5e6ecf0 error 14

does anyone know what is going on?


问:
Add links to chrome apps tab
(not sure which StackExchange community to use for this question)

I would like to add some web links to the chrome://apps/ tab. Is this possible?

Currently I have this:

Which I can reorganize a bit, but I do not know how to add my own links to this configuration.

答:
just drag the link to the app page
See here</p>

Title: Add links to chrome apps tab


问:
Why is my class not responding to this CSS class?
I've been linked a stylesheet

```<code><link rel="stylesheet" href="../www.assistans.tv/css/joncss.css" type="text/css"/>
</code>```

The css is:

```<code>.meravsnitt {
        font-color: #FFF;
        }
</code>```

and the html class is:

```<code><span class="meravsnitt">Se fler avsnitt</span>
</code>```

I am new to CSS and HTML i am working on this website right now:
http://109.74.0.128/~app/assistanstv/assistanstv/www.assistans.tv/index.html

答:
change css property name font-color to color

```<code>.meravsnitt {
        color: #FFF;
        }

.play_videolist-section-header__icon::before{color:#fff;}
</code>```

Body:
I've been linked a stylesheet

<link rel="stylesheet" href="../www.assistans.tv/css/joncss.css" type="text/css"/>

The css is:

.meravsnitt {
        font-color: #FFF;
        }

and the html class is:

Se fler avsnitt

I am new to CSS and HTML i am working on this website right now:
http://109.74.0.128/~app/assistanstv/assistanstv/www.assistans.tv/index.html

Body:
change css property name font-color to color

.meravsnitt {
        color: #FFF;
        }

.play_videolist-section-header__icon::before{color:#fff;}


问:
Git- How to kill ssh-agent properly on Linux
I am using git on linux, when pushing to gitlab, sometimes it either stuck at:

debug1: Connecting to gitlab.com [52.167.219.168] port 22.

or

debug1: client_input_channel_req: channel 0 rtype keepalive@openssh.com reply 1

debug3: send packet: type 100

Seems restarting linux could solve it, but no body like to reboot machines.
So, I am trying to kill ssh-agent process, then restart it.

But the process is always defunct after kill, and then I can't use git via ssh at all, so is there any way to restart the ssh-agent, or solve the issue described above without restarting the machine?

@Update

The ssh keys that I use include key phrase, which I would input on first use of a ssh key.

The issue usually occurs after I bring the Linux desktop back from sleep, thus the network is reconnected, not sure whether this matters?

Again, does any one knows how to kill or restart a ssh-agent agent, without making it become defunct?

答:
You can try this bash script to terminate the SSH agent:</p>

```<code>#!/bin/bash

## in .bash_profile

SSHAGENT=`which ssh-agent`
SSHAGENTARGS="-s"
if [ -z "$SSH_AUTH_SOCK" -a -x "$SSHAGENT" ]; then
    eval `$SSHAGENT $SSHAGENTARGS`
    trap "kill $SSH_AGENT_PID" 0
fi

## in .logout

if [ ${SSH_AGENT_PID+1} == 1 ]; then
    ssh-add -D
    ssh-agent -k > /dev/null 2>&1
    unset SSH_AGENT_PID
    unset SSH_AUTH_SOCK
fi
</code>```

Body:
You can try this bash script to terminate the SSH agent:

#!/bin/bash

## in .bash_profile

SSHAGENT=`which ssh-agent`
SSHAGENTARGS="-s"
if [ -z "$SSH_AUTH_SOCK" -a -x "$SSHAGENT" ]; then
    eval `$SSHAGENT $SSHAGENTARGS`
    trap "kill $SSH_AGENT_PID" 0
fi

## in .logout

if [ ${SSH_AGENT_PID+1} == 1 ]; then
    ssh-add -D
    ssh-agent -k > /dev/null 2>&1
    unset SSH_AGENT_PID
    unset SSH_AUTH_SOCK
fi


问:
how can use optional url in angular route with ui-router?
I want to define some state with optional url in angular ui-router

how can I do this?

for example

```<code>state('test',{
   url:'/list/:id/color?/:color?'
}
</code>```

in this example the color and :color is optional and state should work whit these urls:

site.com/list/1

site.com/list/color/red

答:
There was an update to the library a few years ago which allowed this functionality:

```<code>$stateProvider.state("foo", {
  url: "/foo/{foo}",
  params: {
    foo: { value: "bar" }
  }
});
</code>```

Adding a default value to foo means that the route above will match
  /foo, /foo/, and /foo/baz. Additionally, when matching /foo or /foo/,
  $stateParams will still be populated with { foo: "bar" }

Body:
I want to define some state with optional url in angular ui-router

how can I do this?

for example

state('test',{
   url:'/list/:id/color?/:color?'
}

in this example the color and :color is optional and state should work whit these urls:

site.com/list/1

site.com/list/color/red

Body:
There was an update to the library a few years ago which allowed this functionality:

$stateProvider.state("foo", {
  url: "/foo/{foo}",
  params: {
    foo: { value: "bar" }
  }
});

Adding a default value to foo means that the route above will match
  /foo, /foo/, and /foo/baz. Additionally, when matching /foo or /foo/,
  $stateParams will still be populated with { foo: "bar" }


问:
How to declare directive or service i can use like a function in AngularJS expression
I have many functions to convert Datetime format.
I'd like to create a directive or a service to call these functions everywhere in my project.

Here is one of my functions.

```<code>$scope.formatDateTime = function (item) {
    if (item != null) {

        var d = moment().utc();
        if (item instanceof Date)
            d = new moment(item).utc();

        else if (item instanceof moment)
            d = item;

        else
            d = new moment(item, "YYYY-MM-DD HH:mm Z").utc();

        if (d != null) {

            moment.locale($rootScope.language);
            var strReturn = d.format("L LT");
            return strReturn;
        }
    }

    return null;
};
</code>```

My problem is i have to copy my functions in every controller where i need to use them, so i'd like to call a service or directive, i don't really know what exactly, to call these functions like below :

```<code><div>{{formatDateTime(dateToConvert)}}</div>
</code>```

答:
best solution is to create a custom filter

```<code>.filter('dateFilter', function() {
    return function(item) {
        if (item != null) {
            var d = moment().utc();
            if (item instanceof Date)
                d = new moment(item).utc();
            else if (item instanceof moment)
                d = item;
            else
                d = new moment(item, "YYYY-MM-DD HH:mm Z").utc();
            if (d != null) {
                moment.locale($rootScope.language);
                var strReturn = d.format("L LT");
                return strReturn;
            }
        }
        return null;
    }
})
</code>```

in the html, call like this

```<code><div>{{dateToConvert | dateFilter}}</div>
</code>```

Body:
I have many functions to convert Datetime format.
I'd like to create a directive or a service to call these functions everywhere in my project.

Here is one of my functions.

$scope.formatDateTime = function (item) {
    if (item != null) {

        var d = moment().utc();
        if (item instanceof Date)
            d = new moment(item).utc();

        else if (item instanceof moment)
            d = item;

        else
            d = new moment(item, "YYYY-MM-DD HH:mm Z").utc();

        if (d != null) {

            moment.locale($rootScope.language);
            var strReturn = d.format("L LT");
            return strReturn;
        }
    }

    return null;
};

My problem is i have to copy my functions in every controller where i need to use them, so i'd like to call a service or directive, i don't really know what exactly, to call these functions like below :

{{formatDateTime(dateToConvert)}}

Body:
best solution is to create a custom filter

.filter('dateFilter', function() {
    return function(item) {
        if (item != null) {
            var d = moment().utc();
            if (item instanceof Date)
                d = new moment(item).utc();
            else if (item instanceof moment)
                d = item;
            else
                d = new moment(item, "YYYY-MM-DD HH:mm Z").utc();
            if (d != null) {
                moment.locale($rootScope.language);
                var strReturn = d.format("L LT");
                return strReturn;
            }
        }
        return null;
    }
})

in the html, call like this

<div>{{dateToConvert | dateFilter}}</div>


问:
Saving uploaded image in database with relative path in asp.net mvc
I want to upload an image and after uploading, I have to save the path of the image but it only saves the physical path in the database

"C:\Oumaima\GMAOProject\GMAOProject\Images\Lighthouse.jpg".

What I want is to save it as a relative path in the database.

"~\Images\Lighthouse.jpg"

This is the code in controller:

var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images"), fileName);
file.SaveAs(path);
```

Thank you

答: Just save "~/Images/"+fileName. Server.Mappath will give you the physical path</p>

ContentLicense: CC BY-SA 4.0

Body:
I want to upload an image and after uploading, I have to save the path of the image but it only saves the physical path in the database

"C:\Oumaima\GMAOProject\GMAOProject\Images\Lighthouse.jpg".

What I want is to save it as a relative path in the database.

"~\Images\Lighthouse.jpg"

This is the code in controller:

var fileName = Path.GetFileName(file.FileName);
var path = Path.Combine(Server.MapPath("~/Images"), fileName);
file.SaveAs(path);

Thank you


问:
yammer authentication using JS SDK in ionic 2/cordova
I need to authenticate a user using Yammer before posting comments from my ionic 2 app. i am using yammer js sdk for this. its working in browser fine. its opening login popup and closing. when i try running the same in mobile its opening the inappbrowser and showing about:blank at the bottom. not redirecting from there.

i am calling the sdk this way:

```<code>yam.platform.login((loginResp)=>{

  console.log("loginResp:"+JSON.stringify(loginResp));
});
</code>```

i have included the js sdk this way:

```<code><script data-app-id="appid" src="external/yammer_js_sdk.js"></script>
</code>```

because of the above login call its opening the inappbrowser but stuck there.
can somebody help me?

答:
If you notice in Browser, login opens as a pop up window. Which is not possible in Ionic/Cordova app. Check the logs by connecting the simulator/device and you would notice

"{adfs redirection URL} in a frame because it set 'X-Frame-Options' to 'DENY'."

Check another post from StackOverFlow which talks about the error @ How to set 'X-Frame-Options' on iframe?

Try using User Impersonation i.e, Pre-Auth @ Microsoft Blog

Which talks about
1. Generating Verified Admin Developer Token for Yammer
2. Fetch UserID using Email ID.
3. Fetch User Access Token using Impersonation.
4. Set AuthToken using yam.platform.setAuthToken({token}) - This avoid per user login.

Weigh your requirements and you may use this approach.

Body:
I need to authenticate a user using Yammer before posting comments from my ionic 2 app. i am using yammer js sdk for this. its working in browser fine. its opening login popup and closing. when i try running the same in mobile its opening the inappbrowser and showing about:blank at the bottom. not redirecting from there.

i am calling the sdk this way:

yam.platform.login((loginResp)=>{

  console.log("loginResp:"+JSON.stringify(loginResp));
});

i have included the js sdk this way:

because of the above login call its opening the inappbrowser but stuck there.
can somebody help me?


问:
How to query making matching pairs of columns in rails?
I have a movies table in the database with separate columns (integers) for month and year of release date.

I want to get all the movies with the release date from 09/2016 till 02/2017.

This query won't work because of other unwanted results:

```<code>Movie.where(month: [09, 10, 11, 12, 1, 2], year: [2016, 2017])
</code>```

How do I query making pairs of month & year?

答:
Storing dates in that way is a very poor design decision (if you don't also store an actual date value).

So, either do data migration and create a date column which will be trivial to query, or do a big-ass conditional query:

```<code>SELECT movies.*
FROM movies
WHERE month = 9 AND year = 2016 OR
  month = 10 AND year = 2016 OR
  ...
  month = 2 AND year = 2017
</code>```

To build this query in activerecord, you can use this answer (rails-5 specific).

Body:
I have a movies table in the database with separate columns (integers) for month and year of release date.

I want to get all the movies with the release date from 09/2016 till 02/2017.

This query won't work because of other unwanted results:

Movie.where(month: [09, 10, 11, 12, 1, 2], year: [2016, 2017])

How do I query making pairs of month & year?

Body:
Storing dates in that way is a very poor design decision (if you don't also store an actual date value).

So, either do data migration and create a date column which will be trivial to query, or do a big-ass conditional query:

SELECT movies.*
FROM movies
WHERE month = 9 AND year = 2016 OR
  month = 10 AND year = 2016 OR
  ...
  month = 2 AND year = 2017

To build this query in activerecord, you can use this answer (rails-5 specific).


问:
How do i find the selected id and name of radiobutton list
How do I find the selected id of radiobutton in list.

Here is the radiobutton:

```<code><input name="1" id="1" type="radio">
</code>```

Radiobutton are dynamics.

Here is the dynamic radio button list.

```<code><div class="row">
  <div class="form-group">
      <div class="col-md-12">
          <label>1. Here is the question??</label>
          <div class="icheck-list">
              <label class="icheck-list" id="1">

                  <input name="1" id="1" type="radio">Strongly Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="2">
                  <input name="1" id="2" type="radio">Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="3">
                  <input name="1" id="3" type="radio">Neither Agree or Disagree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="4">
                  <input name="1" id="4" type="radio">Agree
                  <span></span>
              </label>
          </div>
          <div class="icheck-list">
              <label class="icheck-list" id="5">
                  <input name="1" id="5" type="radio">Strongly Agree
                  <span></span>
              </label>
          </div>
      </div>
  </div>
</div>
</code>```

There is 5 possible answers for a question.

I am using mvc 4.

For next question the i.e. for question 2.

The answer radiobutton is just like

```<code><input name="2" id="11" type="radio">Strongly Disagree
</code>```

So how do I find the selected radio button id and name???

here is the html i am using in view page.

```<code>        <div class="tab-pane active" id="tab1">

                                        @foreach (var items in Model.ParentList)
                                        {
                                            <div class="row">

                                                <div class="form-group">

                                                    <div class="col-md-12">

                                                        <label>@items.QuestionText</label>

                                                        @foreach (var ch in Model.ChildList)
                                                        {
                                                            if (items.QuestionId == ch.QuestionId)
                                                            {

                                                                <div class="icheck-list">
                                                                    <label class="icheck-list" id="@ch.AnswerId">
                                                                        @*<input type="checkbox"> @Html.DisplayFor(model => model.Answers[j].AnswerText)*@
                                                                        <input name="@ch.QuestionId" id="@ch.AnswerId" type="radio">@ch.AnswerText
                                                                        <span></span>
                                                                    </label> </div>
 }

                                                        }
 </div>
</div>
 }
</div>
</code>```

there is total 10 questions and each questions having 5 multiple choice answers.
so Model.ParentList i got total 10 questions with id
in Model.ChildList i got 50 answers.
so how do i bind and got the selected radio button value??

答:
This piece of code will return the value of the checked radio button in jQuery:

```<code>$('input[name=<name of radio>]:checked').val();
</code>```

In your case with a radio named '1' it would be:

```<code>$('input[name=1]:checked').val();
</code>```

I hope I have understood the question correctly, and that this might be of use for you.

Body:
How do I find the selected id of radiobutton in list.

Here is the radiobutton:

<input name="1" id="1" type="radio">

Radiobutton are dynamics.

Here is the dynamic radio button list.

          1. Here is the question??

                  <input name="1" id="1" type="radio">Strongly Disagree

                  <input name="1" id="2" type="radio">Disagree

                  <input name="1" id="3" type="radio">Neither Agree or Disagree

                  <input name="1" id="4" type="radio">Agree

                  <input name="1" id="5" type="radio">Strongly Agree

There is 5 possible answers for a question.

I am using mvc 4.

For next question the i.e. for question 2.

The answer radiobutton is just like

<input name="2" id="11" type="radio">Strongly Disagree

So how do I find the selected radio button id and name???

here is the html i am using in view page.

                                        @foreach (var items in Model.ParentList)
                                        {

                                                        @items.QuestionText

                                                        @foreach (var ch in Model.ChildList)
                                                        {
                                                            if (items.QuestionId == ch.QuestionId)
                                                            {

                                                                        @*<input type="checkbox"> @Html.DisplayFor(model => model.Answers[j].AnswerText)*@
                                                                        <input name="@ch.QuestionId" id="@ch.AnswerId" type="radio">@ch.AnswerText

 }

                                                        }

 }

there is total 10 questions and each questions having 5 multiple choice answers.
so Model.ParentList i got total 10 questions with id
in Model.ChildList i got 50 answers.
so how do i bind and got the selected radio button value??

Body:
This piece of code will return the value of the checked radio button in jQuery:

$('input[name=<name of radio>]:checked').val();

In your case with a radio named '1' it would be:

$('input[name=1]:checked').val();

I hope I have understood the question correctly, and that this might be of use for you.


问:
concatenate a string/character n number of times in xpath
I am using a mapping node in my messageflow and there is a part where i need to
conatenate a string/character n times in xpath function.
Is there any way to do this with some
xpath expression or xpath build function (or both) ?
for example: concatenate '~' 17 times. </p>

答:
Easy in XPath 2.0:

```<code>string-join(for $i in 1 to 17 return '~', '')
</code>```

Easier still in XPath 3.0:

```<code>string-join((1 to 17)!'~')
</code>```

In XPath 1.0 your best bet is probably to initialize a variable $tildes with 100 (or however many) tildes, and then use

```<code>substring($tildes, 1, 17)
</code>```

Body:
Easy in XPath 2.0:

string-join(for $i in 1 to 17 return '~', '')

Easier still in XPath 3.0:

string-join((1 to 17)!'~')

In XPath 1.0 your best bet is probably to initialize a variable $tildes with 100 (or however many) tildes, and then use

substring($tildes, 1, 17)


问:
c(++) union Data structure
I'm programming for a µC, i have following data Structure:

```<code>typedef struct
{
  RF12Head head;

  typedef union
  {
    uint8_t raw[40];

    typedef struct
    {
      node_id nodeId;
      uint8_t hierachyDepth;
    } MessageNodeFound;
  } data;

} RF12Message;
</code>```

A RF12Message contains a header an an data part.
Now i want to have different message formats.

I want to be able to do something like this:

```<code>RF12Message msg;

memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly

//or indirectly:

msg.data.MessageNodeFound.nodeId = 3;
msg.data.MessageNodeFound.hierachyDepth = 2;
</code>```

but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why?

thank you!

答:
You have too many typedefs in your code.
Try this:

http://codepad.org/frysgQte

Title: c(++) union Data structure

Body:
I'm programming for a µC, i have following data Structure:

typedef struct
{
  RF12Head head;

  typedef union
  {
    uint8_t raw[40];

    typedef struct
    {
      node_id nodeId;
      uint8_t hierachyDepth;
    } MessageNodeFound;
  } data;

} RF12Message;

A RF12Message contains a header an an data part.
Now i want to have different message formats.

I want to be able to do something like this:

RF12Message msg;

memset(&msg.data.raw, 0xEF, sizeof(msg.data.raw)); // fill in directly

//or indirectly:

msg.data.MessageNodeFound.nodeId = 3;
msg.data.MessageNodeFound.hierachyDepth = 2;

but the compiler aways throws an error: "invalid use of 'RF12Message::data'", why?

thank you!


问:
Append objects to Javascript array
I need the values for the below TDs in a JavaScript array that I can loop through in another part of my code later on:

```<code>    <table>
        <tr><td class="drdsclient">DSCDS201020101</td></tr>
        <tr class="drcheck">
            <td>Maximum online generations:</td>
            <td class="maxonlval notopborder">30</td>
            <td class="maxonlnotes notopborder">notes</td>
        </tr>
        <tr class="drcheck">
            <td>Default Retention Rule set:</td>
            <td class="defretruleval notopborder">No default Retention rule set</td>
            <td class="defretrulenotes notopborder">notes</td>
        </tr>
        <tr class="drcheck">
            <td>Default Backup Schedule set:</td>
            <td class="defschedval notopborder">No default Schedule set</td>
            <td class="defschednotes notopborder">notes</td>
        </tr>

        <tr class="drcheck"> <td class="drdsclient">DSCDS901999102</td></tr>
        <tr class="drcheck">
            <td>Maximum online generations:</td>
            <td class="maxonlval notopborder">29</td>
            <td class="maxonlnotes notopborder">notes</td>
        </tr>
        <tr class="drcheck">
            <td>Default Retention Rule set:</td>
            <td class="defretruleval notopborder">30 days</td>
            <td class="defretnotes notopborder">notes</td>
        </tr>
        <tr class="drcheck">
            <td>Default Backup Schedule set:</td>
            <td class="defschedval notopborder">Monday to Friday @ 21:00</td>
            <td class="defschednotes notopborder">notes</td>
        </tr>
    </table>
</code>```

Tried the below JS code:

```<code>var array = $('.drdsclient').map(function() {
  var $client = $(this);
  var $rows = $client.closest('tr').nextUntil('tr:has(.drdsclient)');

  var obj = {
    drdsc: $client.text()
  };

  $rows.each(function() {
    obj['maxonlval'] = $('.drcheck').find('td.maxonlval').text();
    obj['defretruleval'] = $('.drcheck').find('td.defretruleval').text();
    obj['defschedval'] = $('.drcheck').find('td.defschedval').text();
  });

  return obj;
}).get();
</code>```

But objects are duplicated:

```<code>[0]
    [drdsc] => "DSCDS201020101"
    [maxonlval] => "3029"
    [defretruleval] => "No default Retention rule set30 days"
    [defschedval] => "No default Schedule setMonday to Friday @ 21:00"
[1]
    [drdsc] => "DSCDS901999102"
    [maxonlval] => "3029"
    [defretruleval] => "No default Retention rule set30 days"
    [defschedval] => "No default Schedule setMonday to Friday @ 21:00"
</code>```

Ideally if I can have something like below:

```<code>[0]
    [drdsc] => "DSCDS201020101"
    [maxonlval] => "30"
    [defretruleval] => "No default Retention rule set"
    [defschedval] => "No default Schedule set"
[1]
    [drdsc] => "DSCDS901999102"
    [maxonlval] => "29"
    [defretruleval] => "30 days"
    [defschedval] => "Monday to Friday @ 21:00"
</code>```

答:
Maybe replace this part

```<code>  $rows.each(function() {
    obj['maxonlval'] = $('.drcheck').find('td.maxonlval').text();
    obj['defretruleval'] = $('.drcheck').find('td.defretruleval').text();
    obj['defschedval'] = $('.drcheck').find('td.defschedval').text();
  });
</code>```

with

```<code>obj['maxonlval'] = $rows.find('td.maxonlval').text();
obj['defretruleval'] = $rows.find('td.defretruleval').text();
obj['defschedval'] = $rows.find('td.defschedval').text();
</code>```

Note no loop over $rows

Title: Append objects to Javascript array

Body:
I need the values for the below TDs in a JavaScript array that I can loop through in another part of my code later on:

DSCDS201020101

            Maximum online generations:
            30
            notes

            Default Retention Rule set:
            No default Retention rule set
            notes

            Default Backup Schedule set:
            No default Schedule set
            notes

 DSCDS901999102

            Maximum online generations:
            29
            notes

            Default Retention Rule set:
            30 days
            notes

            Default Backup Schedule set:
            Monday to Friday @ 21:00
            notes

Tried the below JS code:

var array = $('.drdsclient').map(function() {
  var $client = $(this);
  var $rows = $client.closest('tr').nextUntil('tr:has(.drdsclient)');

  var obj = {
    drdsc: $client.text()
  };

  $rows.each(function() {
    obj['maxonlval'] = $('.drcheck').find('td.maxonlval').text();
    obj['defretruleval'] = $('.drcheck').find('td.defretruleval').text();
    obj['defschedval'] = $('.drcheck').find('td.defschedval').text();
  });

  return obj;
}).get();

But objects are duplicated:

[0]
    [drdsc] => "DSCDS201020101"
    [maxonlval] => "3029"
    [defretruleval] => "No default Retention rule set30 days"
    [defschedval] => "No default Schedule setMonday to Friday @ 21:00"
[1]
    [drdsc] => "DSCDS901999102"
    [maxonlval] => "3029"
    [defretruleval] => "No default Retention rule set30 days"
    [defschedval] => "No default Schedule setMonday to Friday @ 21:00"

Ideally if I can have something like below:

[0]
    [drdsc] => "DSCDS201020101"
    [maxonlval] => "30"
    [defretruleval] => "No default Retention rule set"
    [defschedval] => "No default Schedule set"
[1]
    [drdsc] => "DSCDS901999102"
    [maxonlval] => "29"
    [defretruleval] => "30 days"
    [defschedval] => "Monday to Friday @ 21:00"

Body:
Maybe replace this part

  $rows.each(function() {
    obj['maxonlval'] = $('.drcheck').find('td.maxonlval').text();
    obj['defretruleval'] = $('.drcheck').find('td.defretruleval').text();
    obj['defschedval'] = $('.drcheck').find('td.defschedval').text();
  });

with

obj['maxonlval'] = $rows.find('td.maxonlval').text();
obj['defretruleval'] = $rows.find('td.defretruleval').text();
obj['defschedval'] = $rows.find('td.defschedval').text();

Note no loop over $rows


问:
redirecting page after login in codeigniter
I am quite newbie to codeigniter, I have login system to start with on site, and have 2 scenario:

If user is already logged in, and if clicks on url from other site(different domain), then it will redirect to given link.

If user is not logged in and click on link from other domain then he will first redirect to login page and then he will redirect again to clicked link.

now my first case works but not second, I tried setting a url in session like,

```<code>$array['login_redirect'] = current_url();

$this->session->set_userdata($array);
</code>```

which is giving me correct url

but after login, session data shows login page url as value for login_redirect.

答:
You need to add condition to set current url.

for Example:

```<code>$current_url = current_url();
$login_url = 'www.test.com/login';   // Login url of current website

if($current_url != $login_url){
   $array['login_redirect'] = $current_url;
   $this->session->set_userdata($array);

}
</code>```

Body:
I am quite newbie to codeigniter, I have login system to start with on site, and have 2 scenario:

If user is already logged in, and if clicks on url from other site(different domain), then it will redirect to given link.

If user is not logged in and click on link from other domain then he will first redirect to login page and then he will redirect again to clicked link.

now my first case works but not second, I tried setting a url in session like,

$array['login_redirect'] = current_url();

$this->session->set_userdata($array);

which is giving me correct url

but after login, session data shows login page url as value for login_redirect.

Body:
You need to add condition to set current url.

for Example:

$current_url = current_url();
$login_url = 'www.test.com/login';   // Login url of current website

if($current_url != $login_url){
   $array['login_redirect'] = $current_url;
   $this->session->set_userdata($array);

}


问:
Import JSZip in Angular 2 project
I am having troubles while importing the JSZip library in my Angular 2 project.
I followed the following steps in order to change the project configuration:

1 - Install JSZip using NPM

```<code>npm install jszip --save
</code>```

2 - Change systemjs.config.js as follows

```<code>var map = {
    ...
    'jszip':                      'node_modules/jszip/dist/jszip.min.js'
};
</code>```

3 - Import the dependency within the component that requires it

```<code>import JSZip from 'jszip';
</code>```

Then, I tried using the main JSZip constructor to attach some files, but I am getting a web error stating that the constructor is not defined. Besides, the Typescript editor I am using is not able to find the definition for it.

Did I miss something?

Thank you.

答:
For those who want to know how it ended, the problem was in the import.
The following is the correct import:

```<code>import * as JSZip from 'jszip';
</code>```

Then, it is used as follows:

```<code>let zipFile: JSZip = new JSZip();
</code>```

Title: Import JSZip in Angular 2 project

Body:
I am having troubles while importing the JSZip library in my Angular 2 project.
I followed the following steps in order to change the project configuration:

1 - Install JSZip using NPM

npm install jszip --save

2 - Change systemjs.config.js as follows

var map = {
    ...
    'jszip':                      'node_modules/jszip/dist/jszip.min.js'
};

3 - Import the dependency within the component that requires it

import JSZip from 'jszip';

Then, I tried using the main JSZip constructor to attach some files, but I am getting a web error stating that the constructor is not defined. Besides, the Typescript editor I am using is not able to find the definition for it.

Did I miss something?

Thank you.

Body:
For those who want to know how it ended, the problem was in the import.
The following is the correct import:

import * as JSZip from 'jszip';

Then, it is used as follows:

let zipFile: JSZip = new JSZip();


问:
How to read 8-bit PNG image as 8-bit PNG image only?
I have a 8-bit PNG image (See the attachment). But when I read it using Image.FromFile method, the pixel format comes as 32-bit. Due to this I am unable to modify the palette.

Please help me.

See below for the code I am using to read the file and update the palette.

```<code>    public static Image GetPreviewImage()
    {
        Bitmap updatedImage = null;
        try
        {
            // Reads the colors as a byte array
            byte[] paletteBytes = FetchColorPallette();

            updatedImage = Image.FromFile(@"C:\Screen-SaverBouncing.png");

            ColorPalette colorPalette = updatedImage.Palette;

            int j = 0;
            if (colorPalette.Entries.Length > 0)
            {
                for (int i = 0; i < paletteBytes.Length / 4; i++)
                {
                    Byte AValue = Convert.ToByte(paletteBytes[j]);
                    Byte RValue = Convert.ToByte(paletteBytes[j + 1]);
                    Byte GValue = Convert.ToByte(paletteBytes[j + 2]);
                    Byte BValue = Convert.ToByte(paletteBytes[j + 3]);
                    j += 4;

                    colorPalette.Entries[i] = Color.FromArgb(AValue, RValue, GValue, BValue);
                }
                updatedImage.Palette = colorPalette; ;
            }

            return updatedImage;
        }
        catch
        {
            throw;
        }
    }
</code>```

答:
I had this problem too, and it seems that any paletted png image that contains transparency can't be loaded as being paletted by the .Net framework, despite the fact the .Net functions can perfectly write such a file. In contrast, it has no problems with this if the file is in gif format.

Transparency in png works by adding an optional "tRNS" chunk in the header, to specify the alpha of each palette entry. The .Net classes read and apply this correctly, so I don't really understand why they insist on converting the image to 32 bit afterwards. What's more, the bug always happens when the transparency chunk is present, even if it marks all colours as fully opaque.

The structure of the png format is fairly simple; after the identifying bytes, each chunk is 4 bytes of the content size, then 4 ASCII characters for the chunk id, then the chunk content itself, and finally a 4-byte chunk CRC value.

Given this structure, the solution is fairly simple:

Read the file into a byte array.

Ensure it is a paletted png file by analysing the header.

Find the "tRNS" chunk by jumping from chunk header to chunk header.

Read the alpha values from the chunk.

Make a new byte array containing the image data, but with the "tRNS" chunk cut out.

Create the Bitmap object using a MemoryStream created from the adjusted byte data, resulting in the correct 8-bit image.

Fix the color palette using the extracted alpha data.

If you do the checks and fallbacks right you can just load any image with this function, and if it happens to identify as paletted png with transparency info it'll perform the fix.

My code:

```<code>/// <summary>
/// Image loading toolset class which corrects the bug that prevents paletted PNG images with transparency from being loaded as paletted.
/// </summary>
public class BitmapLoader
{
    private static Byte[] PNG_IDENTIFIER = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};

    /// <summary>
    /// Loads an image, checks if it is a PNG containing palette transparency, and if so, ensures it loads correctly.
    /// The theory can be found at http://www.libpng.org/pub/png/book/chapter08.html
    /// </summary>
    /// <param name="filename">Filename to load</param>
    /// <returns>The loaded image</returns>
    public static Bitmap LoadBitmap(String filename)
    {
        Byte[] data = File.ReadAllBytes(filename);
        return LoadBitmap(data);
    }

    /// <summary>
    /// Loads an image, checks if it is a PNG containing palette transparency, and if so, ensures it loads correctly.
    /// The theory can be found at http://www.libpng.org/pub/png/book/chapter08.html
    /// </summary>
    /// <param name="data">File data to load</param>
    /// <returns>The loaded image</returns>
    public static Bitmap LoadBitmap(Byte[] data)
    {
        Byte[] transparencyData = null;
        if (data.Length > PNG_IDENTIFIER.Length)
        {
            // Check if the image is a PNG.
            Byte[] compareData = new Byte[PNG_IDENTIFIER.Length];
            Array.Copy(data, compareData, PNG_IDENTIFIER.Length);
            if (PNG_IDENTIFIER.SequenceEqual(compareData))
            {
                // Check if it contains a palette.
                // I'm sure it can be looked up in the header somehow, but meh.
                Int32 plteOffset = FindChunk(data, "PLTE");
                if (plteOffset != -1)
                {
                    // Check if it contains a palette transparency chunk.
                    Int32 trnsOffset = FindChunk(data, "tRNS");
                    if (trnsOffset != -1)
                    {
                        // Get chunk
                        Int32 trnsLength = GetChunkDataLength(data, trnsOffset);
                        transparencyData = new Byte[trnsLength];
                        Array.Copy(data, trnsOffset + 8, transparencyData, 0, trnsLength);
                        // filter out the palette alpha chunk, make new data array
                        Byte[] data2 = new Byte[data.Length - (trnsLength + 12)];
                        Array.Copy(data, 0, data2, 0, trnsOffset);
                        Int32 trnsEnd = trnsOffset + trnsLength + 12;
                        Array.Copy(data, trnsEnd, data2, trnsOffset, data.Length - trnsEnd);
                        data = data2;
                    }
                }
            }
        }
        Bitmap loadedImage;
        using (MemoryStream ms = new MemoryStream(data))
        using (Bitmap tmp = new Bitmap(ms))
            loadedImage = ImageUtils.CloneImage(tmp);
        ColorPalette pal = loadedImage.Palette;
        if (pal.Entries.Length == 0 || transparencyData == null)
            return loadedImage;
        for (Int32 i = 0; i < pal.Entries.Length; i++)
        {
            if (i >= transparencyData.Length)
                break;
            Color col = pal.Entries[i];
            pal.Entries[i] = Color.FromArgb(transparencyData[i], col.R, col.G, col.B);
        }
        loadedImage.Palette = pal;
        return loadedImage;
    }

    /// <summary>
    /// Finds the start of a png chunk. This assumes the image is already identified as PNG.
    /// It does not go over the first 8 bytes, but starts at the start of the header chunk.
    /// </summary>
    /// <param name="data">The bytes of the png image</param>
    /// <param name="chunkName">The name of the chunk to find.</param>
    /// <returns>The index of the start of the png chunk, or -1 if the chunk was not found.</returns>
    private static Int32 FindChunk(Byte[] data, String chunkName)
    {
        if (chunkName.Length != 4 )
            throw new ArgumentException("Chunk must be 4 characters!", "chunkName");
        Byte[] chunkNamebytes = Encoding.ASCII.GetBytes(chunkName);
        if (chunkNamebytes.Length != 4)
            throw new ArgumentException("Chunk must be 4 characters!", "chunkName");
        Int32 offset = PNG_IDENTIFIER.Length;
        Int32 end = data.Length;
        Byte[] testBytes = new Byte[4];
        // continue until either the end is reached, or there is not enough space behind it for reading a new chunk
        while (offset + 12 <= end)
        {
            Array.Copy(data, offset + 4, testBytes, 0, 4);
            // Alternative for more visual debugging:
            //String currentChunk = Encoding.ASCII.GetString(testBytes);
            //if (chunkName.Equals(currentChunk))
            //    return offset;
            if (chunkNamebytes.SequenceEqual(testBytes))
                return offset;
            Int32 chunkLength = GetChunkDataLength(data, offset);
            // chunk size + chunk header + chunk checksum = 12 bytes.
            offset += 12 + chunkLength;
        }
        return -1;
    }

    private static Int32 GetChunkDataLength(Byte[] data, Int32 offset)
    {
        if (offset + 4 > data.Length)
            throw new IndexOutOfRangeException("Bad chunk size in png image.");
        // Don't want to use BitConverter; then you have to check platform endianness and all that mess.
        Int32 length = data[offset + 3] + (data[offset + 2] << 8) + (data[offset + 1] << 16) + (data[offset] << 24);
        if (length < 0)
            throw new IndexOutOfRangeException("Bad chunk size in png image.");
        return length;
    }
}
</code>```

The mentioned ImageUtils.CloneImage is, as far as I know, the only 100% safe way of loading a bitmap and unlinking it from any backing resources like a file or stream. It can be found here.

Alternatively, you can just create the image from MemoryStream and leave the MemoryStream open. Apparently, for a stream that refers to a simple array rather than to an external resource, this gives no problems for garbage collection despite the IDisposable stream being left open. It's a bit less neat and clean, but a lot simpler. The code for the creation of loadedImage then simply becomes:

```<code>MemoryStream ms = new MemoryStream(data)
Bitmap loadedImage = new Bitmap(ms);
</code>```

Body:
I have a 8-bit PNG image (See the attachment). But when I read it using Image.FromFile method, the pixel format comes as 32-bit. Due to this I am unable to modify the palette.

Please help me.

See below for the code I am using to read the file and update the palette.

    public static Image GetPreviewImage()
    {
        Bitmap updatedImage = null;
        try
        {
            // Reads the colors as a byte array
            byte[] paletteBytes = FetchColorPallette();

            updatedImage = Image.FromFile(@"C:\Screen-SaverBouncing.png");

            ColorPalette colorPalette = updatedImage.Palette;

            int j = 0;
            if (colorPalette.Entries.Length > 0)
            {
                for (int i = 0; i < paletteBytes.Length / 4; i++)
                {
                    Byte AValue = Convert.ToByte(paletteBytes[j]);
                    Byte RValue = Convert.ToByte(paletteBytes[j + 1]);
                    Byte GValue = Convert.ToByte(paletteBytes[j + 2]);
                    Byte BValue = Convert.ToByte(paletteBytes[j + 3]);
                    j += 4;

                    colorPalette.Entries[i] = Color.FromArgb(AValue, RValue, GValue, BValue);
                }
                updatedImage.Palette = colorPalette; ;
            }

            return updatedImage;
        }
        catch
        {
            throw;
        }
    }

Body:
I had this problem too, and it seems that any paletted png image that contains transparency can't be loaded as being paletted by the .Net framework, despite the fact the .Net functions can perfectly write such a file. In contrast, it has no problems with this if the file is in gif format.

Transparency in png works by adding an optional "tRNS" chunk in the header, to specify the alpha of each palette entry. The .Net classes read and apply this correctly, so I don't really understand why they insist on converting the image to 32 bit afterwards. What's more, the bug always happens when the transparency chunk is present, even if it marks all colours as fully opaque.

The structure of the png format is fairly simple; after the identifying bytes, each chunk is 4 bytes of the content size, then 4 ASCII characters for the chunk id, then the chunk content itself, and finally a 4-byte chunk CRC value.

Given this structure, the solution is fairly simple:

Read the file into a byte array.

Ensure it is a paletted png file by analysing the header.

Find the "tRNS" chunk by jumping from chunk header to chunk header.

Read the alpha values from the chunk.

Make a new byte array containing the image data, but with the "tRNS" chunk cut out.

Create the Bitmap object using a MemoryStream created from the adjusted byte data, resulting in the correct 8-bit image.

Fix the color palette using the extracted alpha data.

If you do the checks and fallbacks right you can just load any image with this function, and if it happens to identify as paletted png with transparency info it'll perform the fix.

My code:

/// <summary>
/// Image loading toolset class which corrects the bug that prevents paletted PNG images with transparency from being loaded as paletted.
/// </summary>
public class BitmapLoader
{
    private static Byte[] PNG_IDENTIFIER = {0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A};

    /// <summary>
    /// Loads an image, checks if it is a PNG containing palette transparency, and if so, ensures it loads correctly.
    /// The theory can be found at http://www.libpng.org/pub/png/book/chapter08.html
    /// </summary>
    /// <param name="filename">Filename to load</param>
    /// <returns>The loaded image</returns>
    public static Bitmap LoadBitmap(String filename)
    {
        Byte[] data = File.ReadAllBytes(filename);
        return LoadBitmap(data);
    }

    /// <summary>
    /// Loads an image, checks if it is a PNG containing palette transparency, and if so, ensures it loads correctly.
    /// The theory can be found at http://www.libpng.org/pub/png/book/chapter08.html
    /// </summary>
    /// <param name="data">File data to load</param>
    /// <returns>The loaded image</returns>
    public static Bitmap LoadBitmap(Byte[] data)
    {
        Byte[] transparencyData = null;
        if (data.Length > PNG_IDENTIFIER.Length)
        {
            // Check if the image is a PNG.
            Byte[] compareData = new Byte[PNG_IDENTIFIER.Length];
            Array.Copy(data, compareData, PNG_IDENTIFIER.Length);
            if (PNG_IDENTIFIER.SequenceEqual(compareData))
            {
                // Check if it contains a palette.
                // I'm sure it can be looked up in the header somehow, but meh.
                Int32 plteOffset = FindChunk(data, "PLTE");
                if (plteOffset != -1)
                {
                    // Check if it contains a palette transparency chunk.
                    Int32 trnsOffset = FindChunk(data, "tRNS");
                    if (trnsOffset != -1)
                    {
                        // Get chunk
                        Int32 trnsLength = GetChunkDataLength(data, trnsOffset);
                        transparencyData = new Byte[trnsLength];
                        Array.Copy(data, trnsOffset + 8, transparencyData, 0, trnsLength);
                        // filter out the palette alpha chunk, make new data array
                        Byte[] data2 = new Byte[data.Length - (trnsLength + 12)];
                        Array.Copy(data, 0, data2, 0, trnsOffset);
                        Int32 trnsEnd = trnsOffset + trnsLength + 12;
                        Array.Copy(data, trnsEnd, data2, trnsOffset, data.Length - trnsEnd);
                        data = data2;
                    }
                }
            }
        }
        Bitmap loadedImage;
        using (MemoryStream ms = new MemoryStream(data))
        using (Bitmap tmp = new Bitmap(ms))
            loadedImage = ImageUtils.CloneImage(tmp);
        ColorPalette pal = loadedImage.Palette;
        if (pal.Entries.Length == 0 || transparencyData == null)
            return loadedImage;
        for (Int32 i = 0; i < pal.Entries.Length; i++)
        {
            if (i >= transparencyData.Length)
                break;
            Color col = pal.Entries[i];
            pal.Entries[i] = Color.FromArgb(transparencyData[i], col.R, col.G, col.B);
        }
        loadedImage.Palette = pal;
        return loadedImage;
    }

    /// <summary>
    /// Finds the start of a png chunk. This assumes the image is already identified as PNG.
    /// It does not go over the first 8 bytes, but starts at the start of the header chunk.
    /// </summary>
    /// <param name="data">The bytes of the png image</param>
    /// <param name="chunkName">The name of the chunk to find.</param>
    /// <returns>The index of the start of the png chunk, or -1 if the chunk was not found.</returns>
    private static Int32 FindChunk(Byte[] data, String chunkName)
    {
        if (chunkName.Length != 4 )
            throw new ArgumentException("Chunk must be 4 characters!", "chunkName");
        Byte[] chunkNamebytes = Encoding.ASCII.GetBytes(chunkName);
        if (chunkNamebytes.Length != 4)
            throw new ArgumentException("Chunk must be 4 characters!", "chunkName");
        Int32 offset = PNG_IDENTIFIER.Length;
        Int32 end = data.Length;
        Byte[] testBytes = new Byte[4];
        // continue until either the end is reached, or there is not enough space behind it for reading a new chunk
        while (offset + 12 <= end)
        {
            Array.Copy(data, offset + 4, testBytes, 0, 4);
            // Alternative for more visual debugging:
            //String currentChunk = Encoding.ASCII.GetString(testBytes);
            //if (chunkName.Equals(currentChunk))
            //    return offset;
            if (chunkNamebytes.SequenceEqual(testBytes))
                return offset;
            Int32 chunkLength = GetChunkDataLength(data, offset);
            // chunk size + chunk header + chunk checksum = 12 bytes.
            offset += 12 + chunkLength;
        }
        return -1;
    }

    private static Int32 GetChunkDataLength(Byte[] data, Int32 offset)
    {
        if (offset + 4 > data.Length)
            throw new IndexOutOfRangeException("Bad chunk size in png image.");
        // Don't want to use BitConverter; then you have to check platform endianness and all that mess.
        Int32 length = data[offset + 3] + (data[offset + 2] << 8) + (data[offset + 1] << 16) + (data[offset] << 24);
        if (length < 0)
            throw new IndexOutOfRangeException("Bad chunk size in png image.");
        return length;
    }
}

The mentioned ImageUtils.CloneImage is, as far as I know, the only 100% safe way of loading a bitmap and unlinking it from any backing resources like a file or stream. It can be found here.

Alternatively, you can just create the image from MemoryStream and leave the MemoryStream open. Apparently, for a stream that refers to a simple array rather than to an external resource, this gives no problems for garbage collection despite the IDisposable stream being left open. It's a bit less neat and clean, but a lot simpler. The code for the creation of loadedImage then simply becomes:

MemoryStream ms = new MemoryStream(data)
Bitmap loadedImage = new Bitmap(ms);