Can't SSH to a newly created "Ubuntu Server 16.04 LTS" on AWS (with correct key)

Question: I have tried to ssh to a brand new 16.04 EC2 instance but get a "Permission denied (publickey)." I can use the same key to access a new Amazon Linux instance. It looks to me like it's a sshd issue not liking my key but I can't quite work out what I need to do to fix it (Amazon seems to only be able to create 256 bit RSA keys). Any suggestions?
$ ssh -Ai ~/.ssh/my-web.pem email@example.com -vvvv
OpenSSH_7.4p1 Ubuntu-10, OpenSSL 1.0.2g  1 Mar 2016
debug1: Reading configuration data /home/ivan/.ssh/config
debug1: Reading configuration data /etc/ssh/ssh_config
debug1: /etc/ssh/ssh_config line 19: Applying options for *
debug2: resolving "22.214.171.124" port 22
debug2: ssh_connect_direct: needpriv 0
debug1: Connecting to 22.214.171.124 [18.104.22.168] port 22.
debug1: Connection established.
debug1: key_load_public: No such file or directory
debug1: identity file /home/ivan/.ssh/my-web.pem type -1
debug1: key_load_public: No such file or directory
debug1: identity file /home/ivan/.ssh/my-web.pem-cert type -1
debug1: Enabling compatibility mode for protocol 2.0
debug1: Local version string SSH-2.0-OpenSSH_7.4p1 Ubuntu-10
debug1: Remote protocol version 2.0, remote software version OpenSSH_7.2p2 Ubuntu-4ubuntu2.2
debug1: match: OpenSSH_7.2p2 Ubuntu-4ubuntu2.2 pat OpenSSH* compat 0x04000000
debug2: fd 3 setting O_NONBLOCK
debug1: Authenticating to 220.127.116.11:22 as 'ec2-user'
debug3: hostkeys_foreach: reading file "/home/ivan/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/ivan/.ssh/known_hosts:163
debug3: load_hostkeys: loaded 1 keys from 220.127.116.11
debug3: order_hostkeyalgs: prefer hostkeyalgs: email@example.com,email@example.com,firstname.lastname@example.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521
debug3: send packet: type 20
debug1: SSH2_MSG_KEXINIT sent
debug3: receive packet: type 20
debug1: SSH2_MSG_KEXINIT received
debug2: local client KEXINIT proposal
debug2: KEX algorithms: curve25519-sha256,email@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group16-sha512,diffie-hellman-group18-sha512,diffie-hellman-group-exchange-sha1,diffie-hellman-group14-sha256,diffie-hellman-group14-sha1,ext-info-c
debug2: host key algorithms: firstname.lastname@example.com,email@example.com,email@example.com,ecdsa-sha2-nistp256,ecdsa-sha2-nistp384,ecdsa-sha2-nistp521,firstname.lastname@example.com,firstname.lastname@example.com,ssh-ed25519,rsa-sha2-512,rsa-sha2-256,ssh-rsa
debug2: ciphers ctos: email@example.com,aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,firstname.lastname@example.com,aes128-cbc,aes192-cbc,aes256-cbc
debug2: ciphers stoc: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,firstname.lastname@example.com,aes128-cbc,aes192-cbc,aes256-cbc
debug2: MACs ctos: email@example.com,firstname.lastname@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,email@example.com,firstname.lastname@example.com,email@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,firstname.lastname@example.com,zlib
debug2: compression stoc: none,email@example.com,zlib
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug2: peer server KEXINIT proposal
debug2: KEX algorithms: firstname.lastname@example.com,ecdh-sha2-nistp256,ecdh-sha2-nistp384,ecdh-sha2-nistp521,diffie-hellman-group-exchange-sha256,diffie-hellman-group14-sha1
debug2: host key algorithms: ssh-rsa,rsa-sha2-512,rsa-sha2-256,ecdsa-sha2-nistp256,ssh-ed25519
debug2: ciphers ctos: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,firstname.lastname@example.com,email@example.com
debug2: ciphers stoc: firstname.lastname@example.com,aes128-ctr,aes192-ctr,aes256-ctr,email@example.com,email@example.com
debug2: MACs ctos: email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,firstname.lastname@example.com,email@example.com,email@example.com,email@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: MACs stoc: email@example.com,email@example.com,email@example.com,email@example.com,email@example.com,firstname.lastname@example.com,firstname.lastname@example.com,hmac-sha2-256,hmac-sha2-512,hmac-sha1
debug2: compression ctos: none,email@example.com
debug2: compression stoc: none,firstname.lastname@example.com
debug2: languages ctos:
debug2: languages stoc:
debug2: first_kex_follows 0
debug2: reserved 0
debug1: kex: algorithm: firstname.lastname@example.com
debug1: kex: host key algorithm: ecdsa-sha2-nistp256
debug1: kex: server->client cipher: firstname.lastname@example.com MAC: <implicit> compression: none
debug1: kex: client->server cipher: firstname.lastname@example.com MAC: <implicit> compression: none
debug3: send packet: type 30
debug1: expecting SSH2_MSG_KEX_ECDH_REPLY
debug3: receive packet: type 31
debug1: Server host key: ecdsa-sha2-nistp256 SHA256:dECkQyAas8mb3253fWWnbKyA5sKuHZW5f+WQmZcSQEE
debug3: hostkeys_foreach: reading file "/home/ivan/.ssh/known_hosts"
debug3: record_hostkey: found key type ECDSA in file /home/ivan/.ssh/known_hosts:163
debug3: load_hostkeys: loaded 1 keys from 22.214.171.124
debug1: Host '188.8.131.52' is known and matches the ECDSA host key.
debug1: Found key in /home/ivan/.ssh/known_hosts:163
debug3: send packet: type 21
debug2: set_newkeys: mode 1
debug1: rekey after 134217728 blocks
debug1: SSH2_MSG_NEWKEYS sent
debug1: expecting SSH2_MSG_NEWKEYS
debug3: receive packet: type 21
debug1: SSH2_MSG_NEWKEYS received
debug2: set_newkeys: mode 0
debug1: rekey after 134217728 blocks
debug2: key: /home/ivan/.ssh/my-web.pem ((nil)), explicit
debug3: send packet: type 5
debug3: receive packet: type 7
debug1: SSH2_MSG_EXT_INFO received
debug1: kex_input_ext_info: server-sig-algs=<rsa-sha2-256,rsa-sha2-512>
debug3: receive packet: type 6
debug2: service_accept: ssh-userauth
debug1: SSH2_MSG_SERVICE_ACCEPT received
debug3: send packet: type 50
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug3: start over, passed a different list publickey
debug3: preferred gssapi-keyex,gssapi-with-mic,publickey,keyboard-interactive,password
debug3: authmethod_lookup publickey
debug3: remaining preferred: keyboard-interactive,password
debug3: authmethod_is_enabled publickey
debug1: Next authentication method: publickey
debug1: Trying private key: /home/ivan/.ssh/my-web.pem
debug3: sign_and_send_pubkey: RSA SHA256:pLWmaHNdQ+BtGfxIr026FfbI2d2A+MH1khcRR+3QjsQ
debug3: send packet: type 50
debug2: we sent a publickey packet, wait for reply
debug3: receive packet: type 51
debug1: Authentications that can continue: publickey
debug2: we did not send a packet, disable method
debug1: No more authentication methods to try.
Permission denied (publickey).

Answer: Problem is in publickey permission.
Change it to 400 with command
chmod 400 /home/ivan/.ssh/my-web.pem

Try again. Should be working.
Comment: The my-web.pem file has already had chmod run (I can connect to the Amazon Linux instances)
Comment: Before you create instance on AWS you must create key pair. That key pair you are download to your pc. That key, from AWS, must have privilege 0400 and that key is used for auth when you connect to AWS instance. You must use AWS key not your locally generated.
Comment: As stated before I am able to login into an Amazon Linux instance with that same key pair I just can't log into an Ubuntu Linux instance with the key pair. Everything else about the instances (except OS) is the same.
Comment: Try to change key on instance.
Answer: For Ubuntu, in AWS EC2 the default user is ubuntu, so you have to use ubuntu@<ip> not ec2-user@<ip>.
This is the common list that you should have as a quick reference:
ec2-user  # (Amazon Linux, Red Hat Linux, SUSE Linux)
root      # (Red Hat Linux, SUSE Linux)
ubuntu    # (Ubuntu Linux distribution)
fedora    # (Fedora Linux distribution)

Reference: How to SSH to EC2 Instance on AWS (for Beginners)


How to resolve warning: dereferencing type-punned pointer will break strict-aliasing rules

Question:     #define HTON_I32(x) htonl(x)
inline float  __HTON_F32(float  x)
{
    int i = HTON_I32(*((int *)(&x)));
    return (*((float *)(&i)));
}

How to resolve warning dereferencing type-punned pointer will break strict-aliasing rules
in the above code
Comment: You could compile with the -fno-strict-aliasing flag on.  This will remove warnings about strict aliasing problems
Comment: @TonyTheLion: that doesn't resolve the problem, it hides it, and hides other potential problems in the code. Not a good idea.
Comment: @Mat, no, this resolves the problem at an optimization cost.
Comment: @Simon: it does not resolve the problem in case of different alignment requirements for `float` and `int`; this should not be a problem on mainstream architectures, but needlessly writing non-portable code should be frowned upon if reasonable portable alternatives exist...
Answer: Eliminate the type-punning, and replace it with something that isn't fragile in the face of aliasing:
#include <string.h>

inline float __HTON_F32(float x) {
    int i;
    memcpy(&i, &x, sizeof x);
    i = HTON_I32(i);
    memcpy(&x, &i, sizeof x);
    return x;
}

Reasonable optimizing compilers will lower the memcpy calls, and generate equivalent (sometimes better) code to what you get from type-punning.
Another common solution you will see involves unions.  All of these solutions assume that sizeof(int) == sizeof(float).  You may want to add an assert to that effect.
Answer: You can use unions for type-punning, which takes care of possible alignment and aliasing issues (C99:TC3 explicitly mentions that this is indeed legal):
#include <stdint.h>

inline float __HTON_F32(float x) {
    union { float as_float; int32_t as_int; } value = { x };
    value.as_int = HTON_I32(value.as_int);
    return value.as_float;
}

Comment: For anyone who wants the TC3 reference, this is in §220.127.116.11, footnote 82
Comment: ...and footnote 95 of the same section of the C1x April draft ;)
Comment: what does  this exactly do . ? value.as_int = HTON_I32(value.as_int);
Comment: I think the value of value.as_int is  garbage value.
Comment: why we have to assign int varibale HToN_I32(int)
Comment: previously they are doing int i = HTON_I32(*((int *)(&x)));.
Comment: assigning float to int. but now it seems are we assigning int to int with the below code
Comment: value.as_int = HTON_I32(value.as_int);
Comment: @Cristoph How does these unions work, you store as_int and then retrieve as_float? as_float does not contain anything?


Interleaving Strings LCS

Question: Hi I was trying to solve the interleaving strings problem.Here is the detailed explanation of the problem. https://practice.geeksforgeeks.org/problems/interleaved-strings/1
I was trying using lcs but it was not passing leetcode cases. Here is my Code:-
(I am taking lcs from start and end)
class Solution {
public boolean isInterLeave(String a, String b, String c) {

           StringBuffer s=new StringBuffer();
            StringBuffer s1=new StringBuffer();
              StringBuffer s2=new StringBuffer();
            StringBuffer s4=new StringBuffer();

       int m=a.length();
        int n=c.length();
        int q=b.length();
        if(n!=m+q){
            return false;
        }

          LinkedHashSet<Integer> res2=  new LinkedHashSet<Integer>();
         res2= lcs(a,c,m,n);
          LinkedHashSet<Integer> res4=  new LinkedHashSet<Integer>();
         res4= lcs(b,c,q,n);
          for(int i=0;i<n;i++){
              if(res2.contains(i)==false){
                  s.append(c.charAt(i));
              }
          }
          for(int i=0;i<n;i++){
              if(res4.contains(i)==false){
                  s1.append(c.charAt(i));
              }
          }
           LinkedHashSet<Integer> res5=  new LinkedHashSet<Integer>();
         res5= LCS(a,c,m,n);
          for(int i=0;i<n;i++){
              if(res5.contains(i)==false){
                  s2.append(c.charAt(i));
              }
          } LinkedHashSet<Integer> res6=  new LinkedHashSet<Integer>();
         res6= LCS(b,c,q,n);
          for(int i=0;i<n;i++){
              if(res6.contains(i)==false){
                  s4.append(c.charAt(i));
              }
          }
          String z=s.toString();
           String u=s1.toString();
           String v=s2.toString();
           String w=s4.toString();

          if( (b.equals(z)==true || a.equals(u)==true) || ( b.equals(v)==true || a.equals(w)==true)){
              return true;
          }

         else{
             return false;
         }
    }
        public static LinkedHashSet<Integer> lcs(String X, String Y, int m, int n)
    {
        int[][] L = new int[m+1][n+1];

        // Following steps build L[m+1][n+1] in bottom up fashion. Note
        // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
        for (int i=0; i<=m; i++)
        {
            for (int j=0; j<=n; j++)
            {
                if (i == 0 || j == 0)
                    L[i][j] = 0;
                else if (X.charAt(i-1) == Y.charAt(j-1))
                    L[i][j] = L[i-1][j-1] + 1;
                else
                    L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
            }
        }

        // Following code is used to print LCS

        // Create a character array to store the lcs string

 LinkedHashSet<Integer> linkedset =
                           new LinkedHashSet<Integer>();
        // Start from the right-most-bottom-most corner and
        // one by one store characters in lcs[]
        int i=1;
      int j=1;
        while (i <= m && j <= n)
        {
            // If current character in X[] and Y are same, then
            // current character is part of LCS
            if (X.charAt(i-1) == Y.charAt(j-1))
            {
                // Put current character in result

                linkedset.add(j-1);
                // reduce values of i, j and index
                i++;
                j++;

            }

            // If not same, then find the larger of two and
            // go in the direction of larger value
            else if (L[i-1][j] > L[i][j-1])
                i++;
            else
                j++;
        }

      return linkedset;

    }
        public static LinkedHashSet<Integer> LCS(String X, String Y, int m, int n)
    {
        int[][] L = new int[m+1][n+1];

        // Following steps build L[m+1][n+1] in bottom up fashion. Note
        // that L[i][j] contains length of LCS of X[0..i-1] and Y[0..j-1]
        for (int i=0; i<=m; i++)
        {
            for (int j=0; j<=n; j++)
            {
                if (i == 0 || j == 0)
                    L[i][j] = 0;
                else if (X.charAt(i-1) == Y.charAt(j-1))
                    L[i][j] = L[i-1][j-1] + 1;
                else
                    L[i][j] = Math.max(L[i-1][j], L[i][j-1]);
            }
        }

        // Following code is used to print LCS

        // Create a character array to store the lcs string

 LinkedHashSet<Integer> linkedset =
                           new LinkedHashSet<Integer>();
        // Start from the right-most-bottom-most corner and
        // one by one store characters in lcs[]
     int i = m;
        int j = n;
        while (i > 0 && j > 0)
        {
            // If current character in X[] and Y are same, then
            // current character is part of LCS
            if (X.charAt(i-1) == Y.charAt(j-1))
            {
                // Put current character in result
                linkedset.add(j-1);

                // reduce values of i, j and index
                i--;
                j--;

            }

            // If not same, then find the larger of two and
            // go in the direction of larger value
            else if (L[i-1][j] > L[i][j-1])
                i--;
            else
                j--;
        }
         return linkedset;

    }
}

Can anyone suggest an LCS approach to this problem?.My code is not passing the following test case
"cacabcbaccbbcbb" -String A
"acaaccaacbbbabbacc"-String B
"accacaabcbacaccacacbbbbcbabbbbacc"-String C
Comment: DP approach will be easier in this one.  Have you tried that too?
Answer: This will be the LCS+DP approach. Try it out:
class Solution {
    public boolean isInterleave(String s1, String s2, String s3) {
    int m = s1.length(), n = s2.length();
    if (n + m != s3.length()) return false;
    if (s3.length() == 0) return true;

    boolean[][] dp = new boolean[m+1][n+1];
    dp[0][0] = true;
    for (int i = 0; i <= m; i++) {
        if (s1.substring(0, i).equals(s3.substring(0, i)))
            dp[i][0] = true;
        else
            dp[i][0] = false;
    }
    for (int j = 0; j <= n; j++) {
        if (s2.substring(0, j).equals(s3.substring(0, j)))
            dp[0][j] = true;
        else
            dp[0][j] = false;
    }
    for (int i = 1; i <= m; i++) {
        for (int j = 1; j <= n; j++) {
            dp[i][j] = (dp[i-1][j] && s1.charAt(i-1) == s3.charAt(i+j-1))
                    || (dp[i][j-1] && s2.charAt(j-1) == s3.charAt(i+j-1));
        }
    }
    return dp[m][n];
 }
}

Comment: Ya I should have filled dp in this way. Anyways, thanks man for the response.
Comment: @Rocky - if you find this is helpful, please click this and upvote it?  Any other questions about it is welcome.
Comment: Can't vote for some weird stack overflow Policy. But thanks for your response

Interleaving Strings LCS


What is this stucco-like finish called?

Question: The chimney is a wide column in the middle of the living room. The finish on this chimney sort of evokes brick, but I don't think it is. It reminds me of stucco, but it isn't that either. The house was built in 1975.
I'm trying to determine what it is so I can answer the following questions:

Can I remove the bumpy finish, make the indoor surfaces of the chimney smooth, and paint it?
What's usually behind this kind of finish on a chimney? Brick? Drywall?
If I wanted to screw a pull-down flatscreen mount above the fireplace, how would I anchor it?

Close-up of the material:

Picture of the room for context:
Comment: I would call it - very hard to duplicate.
Comment: This is an image on google images for stucco -https://www.google.com/search?q=stucco+images&tbm=isch&tbo=u&source=univ&sa=X&ei=yMn_UZLeAYmC8gSV1YHQCw&ved=0CE4QsAQ&biw=1366&bih=643#facrc=_&imgdii=_&imgrc=MIVVVR4Gl7HtZM%3A%3BRNPA_nxuCPLxsM%3Bhttp%253A%252F%252Fthumbs.dreamstime.com%252Fz%252Flight-gray-stucco-texture-19237395.jpg%3Bhttp%253A%252F%252Fwww.dreamstime.com%252Froyalty-free-stock-photo-light-gray-stucco-texture-image19237395%3B800%3B532. Yours is obviously more regular and deeper but looks to be basically the same.
Comment: That's a great-looking room.
Comment: is the texture hard, or soft.  if it is soft, i would think it is plaster, but if it is hard, depending on how hard, i would guess cement(highly unlikely though) or something similar.
Comment: you can find a small unnoticeable place on the wall(where a stud would probably be, and drill a tiny hole(careful on bit selection) in it to find out what is behind the top layer.  if wood starts coming out it is probably some weird material on the surface, if you only see a concrete like powder, you know it is brick.
Comment: I'm really curious as to what that set up is...is that a wood fireplace on the left and a gas one on the right? (FWIW, I like the texture)
Comment: If that's a working fireplace, then it's most likely brick underneath.
Answer: 1) Yes.  It would probably be easier and more cost efficient to simply cover it (drywall, paneling) or fill it in with more stucco (requires more skill).
2) Brick or block.
3) Purchase a TV mounting kit suitable for your make/model TV and use masonry anchors (http://www.doityourself.com/stry/h2anchorconcrete) to mount it.
Good luck!

What is this stucco-like finish called?


How do I convert RFC822 to a python datetime object?

Question: I know how to do this the other way around... it would be:
>>> dt.rfc822()
'Sun, 09 Mar 1997 13:45:00 -0500'

Answer:
In [1]: import rfc822     # This only works for python 2 series

In [2]: rfc822.parsedate_tz('Sun, 09 Mar 1997 13:45:00 -0500')
Out[2]: (1997, 3, 9, 13, 45, 0, 0, 1, 0, -18000)

in python3 parsedate_tz has moved to email.utils

>>> import email.utils   # this works on Python2.5 and up
>>> email.utils.parsedate_tz('Sun, 09 Mar 1997 13:45:00 -0500')
(1997, 3, 9, 13, 45, 0, 0, 1, -1, -18000)

Comment: The above technique does not return `datetime`, rather a `tuple`. The complete code is `datetime.datetime.fromtimestamp( email.utils.mktime_tz(email.utils.parsedate_tz( rfcdate )), pytz.utc )`. Ref: http://parand.com/say/index.php/2008/02/11/parsing-and-normalizing-dates-with-timezones-in-python/
Comment: Continuation on @AppleGrew comment: Or by using rfc822 module `datetime.datetime.fromtimestamp(rfc822.mktime_tz(rfc822.parsedate_tz(rfc822String)))`
Comment: In python 3, try email.utils.parsedate_to_datetime.
Comment: You can simplify slightly; there's an `utcfromtimestamp` method for dates in UTC: `datetime.datetime.utcfromtimestamp(email.utils.mktime_tz(email.utils.parsedate_tz(rfcdate)))`
Comment: @ThomasAhle, the `rfc822` module predated RFC2822. Turns out it's not a great idea to name the module after the RFC :) This was fixed in Python3. The current one is actually RFC5322
Comment: I thought rf822 was deprecated?
Comment: Thanks, fixed it. There is no deprecation warning even in 2.6 :(
Comment: Email utils appears to be RFC2822. is that the same as 822?
Comment: The `rfc822` module was deprecated already in Python 2.3; the [documentation](https://docs.python.org/2/library/rfc822.html) points you to [`email`](https://docs.python.org/2/library/email.html) package instead, which was introduced in Python 2.2.
Answer: As of python 3.3 there is email.utils.parsedate_to_datetime(date)
>>> from email.utils import parsedate_to_datetime
>>> datestr = 'Sun, 09 Mar 1997 13:45:00 -0500'
>>> parsedate_to_datetime(datestr)
datetime.datetime(1997, 3, 9, 13, 45, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))

Answer: If you strip off the time zone, you can do it like this:
datetime.datetime.strptime('Sun, 09 Mar 1997 13:45:00', '%a, %d %b %Y %H:%M:%S')

Comment: This doesn't appear to have timezones
Comment: He specifically asked how to do it for rfc822 date/time. Since rfc822 includes the timezone, you're answer doesn't solve it. Even worse, it actually returns a different time, depending on the timezone the code was run in, and the timezone the string was generated in (which in web-applications may vary greatly).


Spring MVC returns 404 in production for some requests but works fine in all other envs

Question: We have the following combination in our application.

Spring mvc + tiles as view resolver + controller mapping (Request mapping)
Docker to run our application
Splunk to check the logs (developers dont have access to login to the server and check the logs)

We are trying to hit the following URL in Production which gives 404 in the network tab but it works fine in all other envs (there was one request which was successful in production using the same URL). All other URLs are working fine in production.

https://host:port/context_name/assignUpdate.do

Here is the code for the same.
web.xml
<servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:/spring/dispatcher-servlet.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>

dispatcher-servlet.xml
<mvc:default-servlet-handler />
    <context:annotation-config />
    <aop:aspectj-autoproxy />
    <context:component-scan base-package="we have correct package mentioned here" />

SomeController.java
@Controller
    public class SomeController {
    @RequestMapping(value = "assignUpdate", method = RequestMethod.POST)
        public ModelAndView assignCampaignUpdate(formparam form, HttpSession session){
        method body
    }
 }

Points to be considered

How about adding @ModelAttribute before formparam (not sure that will make any difference)
formparam has a member var which is a List of some other class which has all primitives (the volume of some other class goes huge around 1.2K in production whereas in the other envs it will be around 50) - also tried this one by bringing down the search to one item in UI and sent the request. din work

Any help here
Request Headers

Accept: /
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.9
Connection: keep-alive
Content-Length: 993
Content-Type: application/x-www-form-urlencoded; charset=UTF-8

Only log which i could get
[logtype=access] x_client_ip="ip" date="[09/Aug/2018:07:27:09 -0400]" http_status="404" content_length=0 referer="https://localhost:port/context_name/mainpage.do" user_agent="Mozilla/5.0 (Windows NT 6.1; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/68.0.3440.106 Safari/537.36" method=POST uri="/context_name/assignUpdate.do" query="" protocol=HTTP/1.1 durationms=55 fsreqid=- srcip=10.42.247.20
Comment: can anyone answer this ? please let me know, if there is any more information required
Answer: After spinning my head for long time, i finally got the solution for the above problem.
The exception was IndexoutofBounds. In the request body, we are passing object with index more than 256. Since spring framework supports collection limit of 0 - 255 as index in the request body object, dispatcher servlet throws indexoutofbounds exception and returns 404 as status code for that request. To overcome this issue, we need to override the default collection limit of 256 which is provided by spring framework.
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;

    @InitBinder
        public void initBinder(WebDataBinder dataBinder) {
            dataBinder.setAutoGrowCollectionLimit(600);
        }

For more information, refer https://dzone.com/articles/spring-initbinder-for-handling-large-list-of-java


Event click show the selected data with FullCalendar function

Question: I have a problem for event click show the selected data with FullCalendar function in the popup modal. I just can show the start date data in the popup modal.
Below is my sample coding:

<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

<link rel="stylesheet" href="https://firstname.lastname@example.com/main.css">

        <button type="button" class="close" data-dismiss="modal">×</button>

Add Event

                Event:

                    <input class="form-control" id="title" name="title" placeholder="Event" type="text" value="">

                Color:

                <select class="form-control" id="color" name="color" placeholder="Color" type="text" value="">
                <option value="#FF0000">Red</option>
                <option value="#800000">Maroon</option>
                <option value="#FFFF00">Yellow</option>
                <option value="#008000">Green</option>
                <option value="#00FF00">Light Green</option>
                <option value="#00FFFF">Aqua</option>
                <option value="#0000FF">Blue</option>
                <option value="#000080">Navy</option>
                <option value="#FF00FF">Fuchsia</option>
                <option value="#800080">Purple</option>
                </select>

            <input type="hidden" id="startTime"/>
            <input type="hidden" id="endTime"/>

            When:

        <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
        <button type="submit" class="btn btn-primary" id="submitButton">Save</button>

            <button type="button" class="close" data-dismiss="modal">×</button>

Event Details

        <input id="eventID"/>

            <button class="btn" data-dismiss="modal" aria-hidden="true">Cancel</button>
            <button type="submit" class="btn btn-danger" id="deleteButton">Delete</button>

Now my result when I've clicked 2021-04-01 All Day Event like below the picture:

Actually, I want the expected result like below the picture:

Hope someone can guide me on how to solve it. Thanks.
Answer: It error because you select wrong elements, eventClick should be like
       eventClick:  function(arg) {
             $('#modalBody > #title').text(arg.event.title);
             $('#modalWhen').text(arg.event.start);
             $('.modal-content > #eventID').val(arg.event._def.defId);
             $('#calendarModal').modal();
         },
        editable: true,
        dayMaxEvents: true,
        events: arrays //pass array here
      });


Can't understand the Importance sampling GGX

Question: I've read many articles relating to importance sampling of GGX. However, I still feel confused.
The formula of GGX is :

And many article says we should use this formula to sample:

In the formula, theta is the angle between the normal and the halfvector. So what the formula shows is how to sample a angle between normal and halfvector? But, in the article https://schuttejoe.github.io/post/ggximportancesamplingpart1/
it says "To importance sample D(ω^m) we will use the inverse of the CDF of D(ω^m) to generate a microfacet normal ω^m. If you are familar with using GGX in game rendering this can be thought of as creating a half vector in tangent space." How is theta related to microfacet normal? How can I sample a Li based on the theta?
Answer: In microfacet BRDFs, the half-vector is the same as the microfacet normal. The half-vector is exactly the required normal for a microfacet to reflect light from the incident ray to the outgoing ray, by the law of reflection. So, for given incident and outgoing directions, only those microfacets whose normals are aligned with the half-vector are "active".
Conversely, when importance-sampling a microfacet distribution, we wish to select a random microfacet normal, then reflect the incident ray through this normal to produce the outgoing ray. The incident and outgoing rays will then have the chosen microfacet normal as their half-vector.
For an isotropic BRDF, you will sample theta from the inverse CDF, and you must also sample phi, the azimuth angle about the normal, uniformly between 0 and 2π; then convert those into a unit vector using the usual spherical coordinates (as mentioned in the linked blog post), combined with a tangent-to-world transformation. For an anisotropic BRDF, both theta and phi would be supplied by sampling an inverse CDF.
Comment: But theta is the angle between the half-vector and normal right?  How can we use theta as a microfacet normal directly? Do we need to compute half-vector based on theta?
Comment: @TIANLUNZHU Yes, compute half-vector based on theta (and phi) using the spherical coordinates transformation.


Prove: in geometric sequence ($0\ <\ r\ <\ 1$) the ratio between a term and the sum of all following terms doesn't depend on the location of that term

Question: Another question from my math finals, this time we were working with a geometric sequence. We were asked several questions about a specific sequence, but then the last question was this: prove that in every geometric sequence in which the common ratio $r$ is defined in $0<r<1$, the ratio between a certain term and the sum of all following terms does not depend on the location of that term within the sequence.
My initial approach was to take the sequence in which the first term is $1$ and the common ratio is $\frac{1}{2}$, so the sequence is: $$1, \frac{1}{2}, \frac{1}{4}, \frac{1}{8}, \frac{1}{16},...$$
I checked what happens with the first term: $$\frac{a_1}{\frac{a_2}{1-r}}=\frac{1}{\frac{\frac{1}{2}}{1-\frac{1}{2}}}=1$$
Then proceeded to try the second term: $$\frac{a_2}{\frac{a_3}{1-r}}=\frac{\frac{1}{2}}{\frac{\frac{1}{4}}{1-\frac{1}{2}}}=1$$
And the third term: $$\frac{a_3}{\frac{a_4}{1-r}}=\frac{\frac{1}{4}}{\frac{\frac{1}{8}}{1-\frac{1}{2}}}=1$$
Obviously this shows that it's true for the first three terms, but when trying to find the "general term equation," I got: $$\frac{a_n}{\frac{a_{n+1}}{1-r}}=a_n\left(\frac{1-r}{a_{n+1}}\right)=\frac{a_n\left(1-r\right)}{a_{n+1}}=\frac{1}{r}\left(1-r\right)=\frac{1}{r}-1=\frac{1-r}{r}$$
Does this mean it's true and I proved it? If not then how do I go on from here?
Comment: Yes - your final line is the sort of thing you were expected to produce
Comment: Note $\frac{a_{n+1}}{a_n}=r$ so you can speed up the calculations.
Comment: @zwim you're right, I'll edit it right away
Answer: Yes, indeed you proved it in the final calculation,for the simple reason that your final expression has no dependence on $n$ the position of a certain term
As a side note, I'm assuming this is a highschool final exam, so you aren't expected to be proficient in rigorous proof writing, but  your statement "obviously this shows that it is true" is not true at all, you only proved 3 specific cases of infinitely many, you might have noticed that the dependence of the position cancels out somehow, but this was an intuitive realization and without making it explicit, you won't be able to convince other mathematicians of your result unless they too have the same intuition, and as problems get more complicated and less and less people have the precise knowledge you have, this becomes problematic because perhaps no one has the same intuition, and even more likely, perhaps the intuition is wrong
To find a way to formalise your idea, read up about "proof by induction"
Comment: Yeah, I meant to write true for the first 3 terms. I fixed it now. Would I be able to prove this using induction?
Comment: I think it should be possible, but probably also an overkill
Comment: Gotcha, thanks for the help
Answer: I've found that the answer $$\frac{a_n}{\frac{a_{n+1}}{1-r}}=\frac{1-r}{r}$$ is indeed correct and proves that it's true, because you can plug in the said common ratio $r = \frac{1}{2}$ and it would be equal to $1$, just like it was in every specific term I tried.


I'm very skeptical about installing Ubuntu over my existing Windows 7 OS. As a first time user I have no experience with any Linux Software

Question: Okay, so I am very nervous about wanting to install Ubuntu onto my PC, I don't want to potentially delete my current Windows 7 OS, and as a first time user I have no experience whatsoever with Linux.
I Urge the Ubuntu Community to assist me in this matter as I do not want to make any mistakes that may potentially jeopardize my system.
I have a 64-bit version of windows 7 if that helps with the answer to this question.
Thank you.
Comment: So ...before you do anything you make a backup and have no worries?
Comment: You should at a minimum boot the live ubuntu desktop and ensure your hardware is working. Most people either dual boot or learn Ubuntu in a virtual machine, ie wubi, dual boot, or VirtualBox.
Comment: Yes, backup. And before installing Ubuntu as dual boot make sure you defragmented thoroughly your hard disk.
Answer: You could always install it into your existing windows partition using WUBI, or you could install it into a VirtualBox, that way, you are still running your comfortable windows environment, but can just click over to Ubuntu at will.
Answer: No need to install just use a Live USB image :) And when you are ready to install you can also dual boot.
Here is a link for you to follow on how to create a usb stick:
http://www.ubuntu.com/download/help/create-a-usb-stick-on-windows


Do I need to download the client again?

Question: I have read here that Guild Wars 2 client is available.
I have pre-purchased the game, and I have been participating on the beta weekend events, so I have already downloaded a client from them.
However, I'm not sure if the client for the final release is different from the one for the BWEs.
Will I need to download it all again? (I hope not, it's like 16GB)
Answer: You can continue to use the beta client after the launch. You do not need to download again. However it should be noted that some people have reported improvements in the games performance with a fresh install, this is purely anecdotal and does not hold true for everyone.
If you prefer to have the game 'installed' properly, you can download the installer, run it, and once it begins downloading the game again click cancel. You can then copy the .dat file from your current beta install into the new game folder. This should prevent the need to install the game while giving you things such as a start menu folder e.t.c. I have not found any evidence that this will increase the performance of the game client. This also only applies to those you downloaded the very first BWE client, which used a different launcher style and simply downloaded the files to whatever directory the installer was located in.

Do I need to download the client again?


Is there any difference between 'static transients' and 'transient Type aField' declaration for GORM?

Question: Let us consider two Grails domain example classes.
1st class:
class Person {

    String name
    Integer counter = 0

    static transients = ['counter']
}

2nd class:
class Vehicle {

    String name
    transient Integer counter = 0
}

Will there be any difference in GORM persistence or domain class behaviour for the Integer counter field between classes Person and Vehicle?
EDIT: I know that Person class is the good way to do it as referenced by Grails docs. However I would prefer the Vehicle class way as it seems to be more obvious and easier not to overlook when reading a code.
Answer: The two mechanisms define different kinds of "transience". static transients defines bean properties that should not be mapped to the database by Hibernate, whereas the transient keyword denotes a field that should not be saved by the Java object serialization mechanism (e.g. when using webflow). They both have their uses in different situations.
Comment: Yup, this is true. I was kind of aware about that, but when a property is put in static transients list, then it's not serialized either (for example when 'as XML' casting used). So it was behaviour similar to transient keyword.
I have also checked now, that transient Integer counter is exported to the DB schema anyway, so indeed those two have nothing common between.
Anyway, your answer is fair enough, thanks!


Square tube or C-channel for gate frame

Question: I will built a frame for a wood gate like the one below (but mine will slide in a track instead of hang on hinges).

I was thinking on using C-channel instead of tubing for the frame, since it will make it easier to screw the planks to the frame and the screws will be semi-hidden. Also, the c-channel is thicker per weight, so easier to weld with stick eletrodes.
I never saw a gate frame using C-channel, are there any problems using it for that? Apart from the looks on the inside, will tubing provide any real advantage (considering similar weight materials)?
Comment: I'm no expert, but if it is the same strength, as long as it is stainless steel (or properly painted) you should be fine!
Answer: Square tube (or I-beam) is a trifle stronger than C-channel/C-beam. You may not need that additional strength, depending on exactly what you're building. C-channel is a bit lighter, which may not matter for your application.
(I'm using square-tube aluminum for the bike trailer I'm modifying. C-channel would probably have been fine for this application, but the weight and price differences were insignificant so I went for overkill.)
Answer: The major advantage of c-channel is that you can actually paint all of the surfaces so rust is manageable. With tubular, you can't protect the inside from rust and corrosion. I would use c-channel for that reason alone.
Comment: I understand that (I failed to mention it though in my post). I was (am) a bit worried about using it because I actually never saw a gate using c-channel. I think it might be because of the looks of it, but I'm not sure.
Comment: You'll want the slot pointing downwards as not to collect water

Square tube or C-channel for gate frame


2sxc - How can users View and Edit their own Drafts?

Question: Here is the scenario. At a large organization, all the users login to their Intranet and they are in a Staff (DNN) Role. We are building a 2sxc app to handle a very basic Classifieds Listing so the users can offer/sell items to each other.
For the staff, we have a Manage My Items view, its the only module on the page. Any logged in user in the Staff role can View (DNN permissions) the page. We got it working as expected so that the user can View approved (.IsPublished) items and also Add an item as a Draft (!.IsPublished).
The problem is, after the users add their item, they cannot see them. We cannot figure out how to show the Draft items at all in the View.
After the staff user adds a draft item, an admin can see:

and in the View

But when logged in as Staff role, the View only shows:

I've tried a number of things with Permissions on both the Content Type and the View. I experimented with GetDraft(), but that appears to serve a purpose in another scenario.
The code to get the list of items looks like this:
@{
  var items = AsList(App.Data["Items"])
    // .Where(i => i.IsPublished == false)
  ;
}

What do I need to do so that non-Admins can also view the Drafts (.IsPublished == false) items?
Note that if I upgrade the role's page (DNN) permissions from View to Edit, the draft items appear, but that defeats the purpose (in this scenario).
So again, this is not a public facing page, we are using the 2sxc UI to add a content item. If I am a logged in staff user and I add an item to sell in the Classifieds, I expect a manager will later approve it, but until then, I should be able to able to see my Items (where I am the entity .Owner) that are still in Draft (not approved yet). Thanks in advance!!
2sxc v13.12.1
Update:
Increased the permissions from Create Draft to Edit Draft CRUD and it made no difference, even after a DNN apppool restart.
Answer: Here's some background:
The App has data, and some data is in draft-mode. Internally a draft item actually exists twice - once as the real data, once as draft. All default mechanisms will apply a filter to show only published data to all users, and prefer the drafts for admins.
But this is easy to work around - you just have to get out of the default behavior. I don't know for sure how you're currently accessing the data, but I'll assume it's either

module content (items assigned to module)
query
code accessing the App.Data

All of these behave the default way. But you can change that.
This is basically what a normal query looks like:

Newer queries shorted this to just showing the App DataSource, because it does the same thing - auto-filter.
But you can change it doing it more manually. Add a App Root Cache IAppRoot and use the Draft Stream instead of the Default - then do with it whatever you want - like pass it through an Type Filter to only get the items you want.
it would look a bit like this:


messed up with mount and naming a partition - delete a folder in file system

Question: I have a partition /dev/sda8 which I want to name it "Documents" and automount.
Because I have a long time to use these commands ,I messed up a little (not that I am familiar).
I used gparted and gave a label "Documents" for the partition.
Then , I don't remember exact the order of the commands I used ,but sth like:
sudo mount -L Documents /dev/sda8
sudo mkdir /dev/sda8
sudo mkdir -p /dev/sda8
sudo mount /dev/sda8 /Documents

I added to fstab

UUID=16b7ad55-aea9-49ed-8be9-0bbf1cb23c2e
  /Documents    ext4    #defaults   02

The result now  is  that

I don't have a device named 'Documents'
I have a folder named 'Documents' in my file system (where /etc , /bin...etc lies)

How can I correct these?
-----------UPDATE--------------------------------------------------
I tried to umount (from the above commands) and now I have the device "Documents" but I still have a folder 'Documents' in file system which is empty and is 10GB!  How to delete that?
Thanks!
Answer: I did :
sudo umount /dev/sda8/ /Documents
sudo umount Documents /dev/sda8/
sudo umount -L Documents /dev/sda8/

and suddenly the device "Documents" appeared!
As for the 'Documents' folder inside my file system that was my mistake.
I chekced the properites and it showed the space of the entire file system.My mistake.
Also, for details you can check here.
I want to thank Eliah Kagan  for his help.


Using a charcoal BBQ, how far should I be away from the house?

Question: Are there any guidelines or rules anywhere?
Comment: Voting to close as not related to DIY or home improvement. Preparing a section of wall to accommodate a nearby bbq would be fine IMO, but not general bbq safety tips.
Comment: Of course, rebuilding your deck *after* you've burned it down ... that would be on topic.
Comment: It needs to be known before the slap is put down which determines the position where to put the BBQ :p
Answer: It really depends on the material of your house and the height of the overhang.
In one extreme, if you have a brick house with no overhang you can be almost right up against it.
Vinyl siding and/or 9' overhang is the other extreme. You should probably not be within 10' of vinyl siding.
Somewhere in the middle is wood siding which probably will not burn but you might get paint bubbling if you are within 3'
As a general rule you don't want to be under a 1 story overhang which will hold heat and any sparks in.


How to find orders from repeat/old customers using sql query?

Question: I am using mysql.
I have orders table with column customer_id, order_id, order_date(datetime) now I want to find all orders on Dec 20, 2013, which are from repeat customers( not new customer, i.e. customers has placed some order before as well) in a single query.
Orders table has other typical columns as well not mentioned here. Let me know I can provide more data.
UPDATE: Can we do it without subquery? If yes how? (Just curious)
Answer: select customer_id , order_id, order_date from orders where order_date between
'20/12/2013 00:00:00' and '20/12/2013 23:59:00' AND
customer_id IN (SELECT customer_id FROM orders where order_date < '20/12/2013')

Comment: You should really avoid the use of `BETWEEN` when [dealing with date/time/timestamp values](https://sqlblog.org/2011/10/19/what-do-between-and-the-devil-have-in-common) (yes, I'm aware that MySQL doesn't have the exact same issues as SQL Server - it more has to do with consistency).  Among other things, `BETWEEN` should be avoided any time the value is a measurement (which logically have some amount of error), or are potentially "imprecise"; this essentially excludes everything but integer counts, which then shouldn't use it for consistency reasons.
Comment: if the question is for sql just change the query
Comment: Nice, Serves the purpose. But is there also a way to get results without subquery? Would that be faster? Any performance tip?
Comment: I don't think this query is correct. It assumes that repeat orders can only come from customers who ordered before Dec 20, 2013. I think this query would fail to pull same day repeat customers i.e. customer who order twice or more on the same day.
Answer: Assuming that order_id is the primary key in the table orders and customer_id is a foreign key, you can use the following query with self join to pull the list of all order_id corresponding to repeat customers:
select order_id, customer_id
from orders a, orders b
where a.customer_id = b.customer_id
and order_date = '20131220'

Answer: Now check this query
 SELECT * FROM `orders` WHERE DATE='20/12/2013' AND customer_id IN (SELECT customer_id FROM yearly_sales WHERE DATE < '20/12/2013' )

Comment: That doesn't answer his question at all.
Comment: Well this does not check if customer is old/new.


What's special about a "rare" expedition?

Question: Sometimes if I look at the world map I see sparkly expeditions marked as "Rare". While sometimes these have slightly tougher-than-usual monsters, I haven't noticed the rewards being any different. I still get the same type and number of item rewards and usually end up with yet another velocidrome guild quest.
What's different about "rare" expeditions?
Answer: Rare Expeditions will generate different Guild Quests, as well as have an increased chance of gathering Battered Weapon/Armor from blue mining nodes.
Comment: I think certain monsters only show up on Rare Expeditions, too (e.g. Gore Magala)?
Comment: Are there some guild quests that are exclusive to rare expeditions or is it just an increased chance to get them?


I want multiplication of array elements, where in result I want multiplication of 1st and 2nd, 1st and 3rd and so on

Question: I have an array where a = [2,3,4,5,6].
I want output as multiplication of all array elements as
[2*3,2*4,2*5,2*6, 3*4,3*5,3*6, and so on till 5*6] and output will be in the following format
a = [6,8,10,12,12,15,18.....30]
I have following program - what modification do I need to do
import java.io.*;
import java.util.*;
import java.lang.Math;
class Multipy
{
static void modify(int arr[], int n)
    {

            int prev = arr[0];

        for (int i=0; i<n-1; i++)
        {

            arr[i] = prev * arr[i+1];
        }
    }
    public static void main(String[] args)
    {
        int arr[] = {2,3,4,5,6};
        int n = arr.length;

        modify(arr, n);
        for (int i=0; i<n-1; i++)
        System.out.print(arr[i]+" ");
    }
}

Comment: you didnt add your program
Comment: Hey I just edited
Comment: So what exactly is wrong with the code you're starting with?
Answer: You should return int array as result.
static int[] modify(int[] array) {
    int length = array.length;
    int[] result = new int[length * (length - 1) / 2];
    int k = 0;
    for (int i = 0; i < length; ++i)
        for (int j = i + 1; j < length; ++j)
            result[k++] = array[i] * array[j];
    return result;
}

And
int[] array = {2, 3, 4, 5, 6};
System.out.println(Arrays.toString(modify(array)));

result
[6, 8, 10, 12, 12, 15, 18, 20, 24, 30]


Mac - Tool to slow down the network for Development testing?

Question: is there a Mac Tool that can simulate a internet connection for local development testing purposes?
I want to test ajax loaders etc, but since it's a local machine it's to fast?
Rails 3 App on a Mac, locally hosted
Thanks
Answer: The SpeedLimit prefpane by mschrag does what you want:
http://mschrag.github.com/
I'm not sure if it works for localhost, but it works great for everything else, and it's incredibly easy to use, so it's definitely worth a try.
Answer: I believe that WaterRoof does what you're looking for. It acts as a frontend for ipfw, a packet filter for FreeBSD, which OS X is based on. NoobProof is a simpler interface for the same system, if you want to try that as well.
http://www.hanynet.com/waterroof/
http://www.hanynet.com/noobproof/
Comment: More specifically, you want to use ipfw's [dummynet](http://info.iet.unipi.it/~luigi/dummynet/) feature -- you can use it to feed packets through "pipes", where each pipe can have limited bandwidth, latency, and even packet loss.  See [this AFP548 article](http://www.afp548.com/article.php?story=20060214081244545) for some examples.
Answer: http://www.charlesproxy.com/ is the best I found for OS X.


How to successfully battle Revered Dragons?

Question: Yesterday I came across a Revered Dragon in Winterhold. This thing was hard and would consistently use its drain vitality shout on me which was, for it, very effective. I died multiple times.
My character is level 63 and uses melee weapons - mostly a one-handed ebony war axe and shield / skirmisher build. Her weapons and armour are all smithed to legendary quality.
This dragon landed just outside Winterhold. Normally when I swing an axe at a dragon it's dead in a few hits, but its health hardly went down. It was like chipping away at a rockface.
I have the Aetherial Crown which 'contains' the Atronach Stone, but apparently magic absorption doesn't do anything to drain vitality. I also have the Necklace of the Firewalker which gives me 70% protection against fire, but that's not that helpful when the dragon keeps switching its attacks.
How does anyone battle these things effectively?
Comment: Do you have a companion that could assist, perhaps one with a bow or who casts spells? Generally a melee character in any game, genre, etc., however powerful, will be outmatched by an enemy that can fly and also cast ranged magic attacks. The same is certainly true for TES games.
Comment: @TylerH hmm well, my character is married to Aela the Huntress. I tend to leave her at home. Maybe I should take her out more. I could give her an enchanted Daedric bow or Auriel's bow. I mean, the latter has been sat in a chest for weeks. Or I could stop being so lazy and level up my archery.
Comment: Ah there is a bug that means she won't use the bows I give her. Oh well. https://gaming.stackexchange.com/questions/56533/will-jordis-the-sword-maiden-ever-use-the-bow-that-i-made-for-her
Comment: @C26 She will still use the bow she has, which will be enough to deal damage and, more importantly, take some of the dragon's attention off of you for a bit. Remember that companions are essential and so only die if hit with a critical strike that would reduce their health to zero, so your Aela will be extra useful.
Comment: Do any of these answer your question? [How to kill a dragon in Skyrim?](https://gaming.stackexchange.com/q/35930/4797), [What are Dragons most vulnerable to?](https://gaming.stackexchange.com/q/35489/4797), [How to kill ancient dragons](https://gaming.stackexchange.com/q/198848/4797),
[Tips on beating Legendary Dragons?](https://gaming.stackexchange.com/q/160776/4797)
Comment: @galacticninja thanks - the only one of those links which discusses Drain Vitality is the last one. You have to remember, being level 63, I've been in a lot of dragon fights, but this one took me by surprise. Anyway, I managed to go to Winterhold last night and kill it by levelling my Archery up to 60, raising my bow damage 50% with enchanted armour and using a legendary-smithed shock-enchanted ebony bow and arrows. The guards helped too, but this is the first time I've needed a ranged weapon in the game. I'll develop my archery skill further.
Comment: As a follow-up, I chiefly only use either Dwarven or Ebony weapons/shields, only for the look. Sure, ebony is less powerful than dragonbone, but it's high enough for me. In spite of this, I'm thinking of switching to Zephyr as a main bow, because Dwarven arrows are a lot easier and cheaper to make [I like to coordinate similar bows with arrows] -  and ebony is 300 gold per ingot. Or maybe the Black Bow of Fate, after I get hold of it.
Comment: Zephyr (or the only other two bows worth using) and any arrows. *Player.setav AttackDamageMult 10* - now arrows do what they should, which is kill anyone who's unaware with one shot, and it doesn't matter what they're made out of. And dragons in like five or six shots.
Answer:
My character is level 63 and uses melee weapons - mostly a one-handed ebony war axe.

Level a ranged ability, preferably archery. When the dragon lands somewhere out of melee range, or is hovering, you ought to have a strategy for hitting it other than "cast Dragonrend and then run over to it." That's too slow.

Destruction can work as well, but it is poorly leveled in vanilla Skyrim. If the expert-level spells aren't strong enough, you may be out of luck.

Upgrade to dragonbone weapons.
Upgrade to dual wielding, and get the perks that make it faster. This greatly increases DPS, and blocking is less useful at higher levels in my experience.
If your equipment is not tempered to Legendary already, go level Smithing:

Complete Unfathomable Depths, get a good night's sleep, activate the Warrior Stone, and then...
Go to Halted Stream Camp outside Whiterun, collect a bunch of iron and the guaranteed Transmute spell tome, then smith a bunch of silver and gold jewelry. You can then enchant and sell it to level enchanting and speech respectively, and you'll also make a decent amount of cash from this process. If you sell to the teachers at the College of Winterhold, you can immediately purchase training services from them, and the money will go back into their inventory. Then you can sell them more stuff.
Go through (your favorite Dwemer ruin), collect all the smeltable items of weight 2 (the heavier ones aren't worth it unless you have lots of extra room in your inventory), chop some firewood, then make a ton of Dwarven arrows (which are weightless).

Enchant your weapons. Don't bother with paralysis, it doesn't work on dragons, but there are quite a few enchantments that give a significant increase over base damage.
Potions and poisons can greatly increase your damage output. Lingering damage poisons can negate healing effects and do a lot of damage overall (assuming you're dealing with a battle that will take a long time anyway).
Have a follower distract the dragon once it's grounded, and attack it from a distance. Make sure they have good gear and a reasonable maximum level. Many followers cap out at 30 or so, and those followers are useless for high-level fights.

I have the aetherium crown which 'contains' the atronach stone, but apparently magic absorption doesn't do anything to drain vitality.

Be at the armor cap (displayed value of 542 with a shield, 567 without a shield, but you must fill all four armor slots). You can do this with smithing alone, but the Lord Stone makes it significantly easier. This only protects against physical damage (e.g. the dragon's bite), but at a high Smithing level, it's so easy to reach that you may as well do it anyway.
A couple of tricks which don't work on Drain Vitality, but do work on most other dragon breath attacks:

Have 85% magic resistance (25% from the Lord Stone, 15% from The Book of Love, and enchant some of your gear for the other 45%).
Have 80% spell absorption (50% from the Atronach Stone, 30% from the Alteration perk).
Have 85% resist  for each of fire, frost, and shock. This stacks with magic resistance. I recommend using potions for this, as you may be running short on enchantment slots and elemental resistance is more situational.

Potions of regenerate health will effectively cancel the most deleterious effect of Drain Vitality. The Argonian racial skill Histskin will completely negate it and then some, but only for 60 seconds per day, so it's probably not a good strategy.
Don't bother with potions of fortify light/heavy armor, you're already at the armor cap.
Level Restoration and learn (better) healing spells (purchase from Colette Marence). Use them.

And finally, the extreme option:

Become a Vampire Lord via Dawnguard. The VL form is ridiculously overpowered, but makes most people turn hostile on sight.
Comment: Pretty comprehensive. This should work for most enemies.
Comment: It's hard to see how this answer can be improved upon. There's a lot of interesting advice there. More importantly - and unexpectedly - there are some good proposals on how to upgrade skills which I wasn't using and how to push my character's overall level further, since she's been stuck on 63 for a few days now. Great post, and one which goes beyond the question asked. Thank you very much.
Comment: I should add that these are skills which can be upgraded whilst remaining in character build. Very useful.
Comment: Also: Spellbreaker. I used it the second time with the Revered Dragon when it was at ground level for melee and it worked like an absolute charm [maybe it is a charm]. You just have to be careful that the dragon doesn't ensnare you in its jaws.
Answer: My way of dealing with things is simple:
Stack up on Magicka potions and dual-cast with the Impact perk of the Destruction school of magic: you will be able to stagger-lock the enemy.
Comment: Might this also work with dual-wielding melee and stocking up on stamina potions?
Comment: Is there a perk that does that ?
Comment: Hmm apparently not. War axes have the best stagger-speed ratio. I wonder if it's possible, if they're both smithed to legendary and one-handed is high enough, to have a similar effect.


Programmatically hide views if it is shown. Show views if it is hidden

Question: My button use code that shows and hides the views:
    public void onClick (View v){

      if (What code you need to enter here to determine hidden views or shown)
      {
          testActivity.setVisibility(View.VISIBLE);
      }
      else
      {
          testActivity.setVisibility(View.GONE);
      }
  }

What code I need to add in the "if()", so that clicking on my button was checked condition. If the activity is hidden, it should be shown, and Vice versa. If the views is shown, hide it.
Comment: See http://steveliles.github.io/is_my_android_app_currently_foreground_or_background.html
Answer: I'm guessing since you are using setVisibility, that you want to check the visibility of a View , not an Activity.
In that case you just use getVisibility()
(I used != cause the visibility could be IINVISIBLE as well, change per your needs) :
public void onClick (View v){

  if (testActivity.getVisibility() != View.VISIBLE)
  {
      testActivity.setVisibility(View.VISIBLE);

  }
  else
  {
      testActivity.setVisibility(View.GONE);
  }
} });

Answer: Don't understand why, but only that removed the answer of a man who has solved my problem. Here is his response, and this code works:
  public void onClick (View v){

  if ((testActivity.getVisibility() == View.VISIBLE))
  {
      testActivity.setVisibility(View.GONE);

  }
  else
  {
      testActivity.setVisibility(View.VISIBLE);

  }


How to run a npm script before executing the build command when deploying my GatsbyJS static site on Netlify?

Question: I have a npm script called clone-or-pull that I want to run (via npm run clone-or-pull) before Netlify runs the build command to deploy my static site built using GatsbyJS?
BTW - since my static site is built using GatsbyJS, the build command Netlify would run by default is gatsby build. However, I would like Netlify to execute npm run clone-or-pull before executing gatbsy build.
So how can I run a npm script before executing the build command when deploying my GatsbyJS static site on Netlify?

FYI - i want to execute npm run clone-or-pull to clone my reusable assets repo, which contains the necessary sass/image/font resources I need for my gatbsyjs static site.
Comment: I think I need to use git subtrees to create a copy of my private repo before sending the deploy. I was trying to avoid subtrees/submodules, but I think this might be the way to go.
Answer: I figured out how to run a custom npm script before executing the build command (gatbsy build in my case) when deploying a site on Netlify. But before I show my solution, here is a snippet of my package.json:
GatsbyJS already created a npm script called build that runs gatsby build command:
package.json:
  "build": "gatsby build",
  "clone-or-pull": "node clone-or-pull-assets.js"

So here is my solution:

create prebuild npm script that executes clone-or-pull npm script
create netlify.toml file that specifies to run npm run build instead of gatsy build (since npm run build will run the prebuild script and then run gatsby build

1. create prebuild npm script in package.json:
  "prebuild": "npm run clone-or-pull",
  "build": "gatsby build",
  "clone-or-pull": "node clone-or-pull-assets.js"

2. create netlify.toml to run build script:
[build]
  command = "npm run build"


I need help with this Minecraft Tellraw command, Issue at column 89

Question: This command is still a work in progress, but I am having issues. It gives me an error message when I click "Check Balance" and the error message says:
Invalid json: Unterminated string at line 1 column 89. I don't know what this means. Here is my command:
/tellraw @p ["",{"text":"Welcome, ","color":"green"},{"selector":"@p","color":"dark_blue","bold":"true"},{"text":". How may I help you? -","color":"green","bold":"false"},{"text":" Check Balance","clickEvent":{"action":"run_command","value":"/tellraw @p [{\"text\":\"You currently have: \",\"color\":\"green\"},{\"score\":{\"name\":\"@p\",\"objective\":\"Money\"},\"color\":\"dark_blue\",\"bold\":\"true\",\"underlined\":\"true\"},{\"text\":\" funds in your account.\",\"color\":\"green\"}]"},"color":"none"}]

Can someone explain why this is so?
Comment: @Shudy I don't think that will work for this code, because it's a Minecraft command and not actual code. I tried it and it gave an error at column one, and that's not the problem he's having.
Comment: I don't know how the Json has to be build for this command, but, if you use some tool like: www.jsonlint.com and paste the json, this will say you if  is correct or not.
Comment: I used jsonlint to parse the JSON-parts of both the exterior command and the `run_command`, and both are fine. I pasted the command to [RegExr](regexr.com) to find missing quotation marks using `("|\\"){1}([a-zA-Z \@\,\?\-._:]*)\1` which matches everything inside either `" "` or `\" \"`, there are none missing.
Answer: run_command has a 100 character limit
After double and triple-checking your quotation marks and brackets, I played around with the run_command itself, and I found that it is subject to the same 100 character limit that chat commands are. The reason for this is that the player is treated as actually having run this command himself (including all permission checks).
This means, that starting with the JSON opening square bracket, only 89 characters are processed, seeing that /tellraw.@p. is 11 characters.
For example
/tellraw @p [{"text":"Check Balance","clickEvent":{"action":"run_command","value":"/tellraw @p [\"........10........20........30.......39.\",{\"score\":{\"name\":\"@p\",\"objective\":\"Money\"}}]"}}]

works. After unescaping the ", the nested command is exactly 100 characters long. On the other hand,
/tellraw @p [{"text":"Check Balance","clickEvent":{"action":"run_command","value":"/tellraw @p [\"........10........20........30........40.\",{\"score\":{\"name\":\"@p\",\"objective\":\"Money\"}}]"}}]

breaks with "End of Input at line 1 column 89", which makes sense considering the closing square bracket is cut off.
Note that the length of the exterior command does not matter at all.
Comment: I have found some workarounds that work by either summoning an ArmorStand and using `execute` on them, or by incrementing a scoreboard objective (either trigger or dummy). Unfortunately, this will always cause the command output to appear, i.e. something like "Set score for player" or "Summon successful", which I personally don't really like.
Answer: It most likely means that you have a string that you haven't ended. So for example, you may have a string that, instead of saying "test", it says "test
When you forgot to close the string it most likely messed up the rest of the code. You have a lot of quotations in there, so it only makes sense that you might make that mistake.
Also, make sure all your brackets and square brackets or properly opened and closed.


What is an alternative to a vacuum cleaner for cleaning carpets?

Question: There are reasons we are not interested in a vacuum cleaner at the moment. I'm sure the same applies for other people. Is there an alternative that can get rid of dirt as well as pick up bigger particles?
Comment: Please tell us why you don't want a vacuum.
Comment: If you don't want a vacuum because they exhaust particles, consider either one with a HEPA filter, or a central unit, where the exhaust is usually in a garage or to the outside.
Comment: We really can't give you our best answers unless you know what problem you're trying to solve -- why a vacuum isn't a solution -- since without that our proposed alternatives may run into the same issues.
Comment: If it's an area rug, simply take it outside, hang it over a line/fence/otherwise, and beat the ever living tar (and dirt, crumbs, dead skin and other cruft) out of it. Just like they used to do in "ye olden dayes". If it's wall-to-wall carpeting, that doesn't work so well.
Answer: Use a carpet sweeper.

(source: wikimedia.org)
Bissell sells several models of mechanical manual sweepers -- an invention that's been around in some form since the 1880s. They work, but only to an extent. For deep cleaning you'll have to use a vacuum or roll up your carpet and take it in to the pros.
Comment: I used one of these in the fast food place I worked in years ago.  They work well and they are silent, so they can be used around customers.
Comment: @KeithB, can they be used to do deep cleaning on carpet? I guess not, because some kind of suction like vacuum has to be in place. Please correct me if I am wrong.
Comment: Probably not deep cleaning, and they work best on carpet without a deep pile, like you usually find in commercial settings.
Comment: @KeithB, does it pick up bigger particles like crumbs etc?
Comment: @progtick That it does.  That was the main thing I used it for, picking up crumbs during the day.  We also had a regular vacum that was used after closing.
Comment: That will sweep, but not 'suck' deeper dirt, so aren't really designed for serious cleaning.
Comment: Not downvoting this because it does pick up things off of low ply carpet but this does not clean dirt.   I just bought a grandparent a shark vacuum - she had been using a sweeper - she said in the first weekend that she had to empty the vacuum 12 times.  What is funny is that her house looked immaculate all the time but actually had a half inch of dust.  I do not recommend anyone to use this to "clean" their carpets.  If you use this in your home and only this I really hope nobody there has allergy problems.
Answer: In the "olden days" before there were vacuum cleaners you either swept (which still works to an extent -- tough bristles, short quick strokes are key) or took the carpet up and beat the dust and dirt out with a carpet beater (which also works, as long as your carpet isn't fitted).
Alternatively, there are machines that spray water and shampoo into the carpet and suck up the dirty water -- but these probably come under the heading of a "vacuum cleaner," and so aren't appropriate in your case. Also, they're not very useful for picking up bigger particles.
Beyond those options -- and keeping your carpet clean in the first place (Martha Stewart suggests lots of doormats) -- I don't think that there's another effective way of getting your carpet clean.
Comment: There is anecdotal medical evidence relating carpet cleaning fluids to Kawasaki disease in young children.  And contrary to whatever you saw on "House", this disease is not exclusive to Asians.  My otherwise healthy Caucasian son got it when he was 3.  Treatment is 3 days in the hospital on a Γ-Globulin drip.
Comment: http://www.lpch.org/DiseaseHealthInfo/HealthLibrary/cardiac/kawasaki.html  Ctrl-F for "carpet" -- Evidence is inconclusive.
Answer: The purpose of carpet is two-fold.  First, to make a nice, cushy surface for your delicate feet to tread upon.  Second, as an insulating barrier from the extreme expressions of Maw Nature.   The side-effect of carpet is a trap for disease, dead skin and all, plus an emitter of chemical emissions – a byproduct of materials used in the construction.   The only logical resolution – to the chagrin of carpet manufacturers, is to rip it all out, insulate under the flooring and buy one of those wood floor sweeper-dusters as seen on TV.  Hold out for the "wait, there is more" advertisements, best bang for the buck.
** =====  EDIT ===== **
As zero is a number, "you can't" equally applies to "you cannot clean carpet without a vacuum."
If you've never removed (ripped up and disposed of) carpet and/or padding in a regularly vacuumed environment, you are not qualified to answer, and especially not qualified to down-vote!!   If you have removed carpet then you know, without a doubt, a vacuum of some type is essential to the maintaining a clean and healthy carpeted environment.
In the below diagram, please note the accumulation of dirt between the layers of the carpet, the padding and the flooring.   These particles of dust (http://en.wikipedia.org/wiki/Dust) dead skin (http://www.thenakedscientists.com/HTML/questions/question/1643/) and itsy bitsy creatures such as dust mites (http://en.wikipedia.org/wiki/House_dust_mite) are just some of the components of the yucky stuff labeled "filth and dirt" in the cheap artwork attached to this post.

The OP's question is "There are reasons we are not interested in a vacuum cleaner at the moment. I'm sure the same applies for other people. Is there an alternative that can get rid of dirt as well as pick up bigger particles?"
I propose the following answer :  "no."
Comment: It answers the question precisely, in that there is no answer to the question of thoroughly cleaning a carpet.
Comment: This doesn't answer the question.
Comment: analogous to asking how to bang one's head against a brick wall without it hurting.
Comment: The question is "What is an alternative to a vacuum cleaner for cleaning carpets?"   My answer is "The only logical resolution – to the chagrin of carpet manufacturers, is to rip it all out…" and I stand by the answer.   No vacuum cleaner?  Not a (electric/mechanical) stand-alone, not a central unit, not a shop-vac with a 100ft hose?   I think I'll upvote ChrisF's "took the carpet up and beat it using a carpet beater to knock the dust and dirt out," because it's the only applicable answer.  (Afterwards, I'm heading to my garage-shop to develop a trash bag nanomites can use.)(grin)
Comment: Down voting because it doesn't answer the question. The question is specifically about alternative means to clean carpet, not alternatives to carpet.
Comment: @JoeFromOzarks When editing your post, there's a tool bar above the edit box to add links and photos. Just note that the flickr link wasn't to a photo but a website. You need the direct link to the jpg/gif/png to add a photo with these tools.
Comment: @JoeFromOzarks - I think putting carpet in the wash works right?  I agree with almost everything you said but you can wash carpet.
Comment: I disagree with the belief that dust trapped under a carpet actually matters much until/unless you take the carpet up; it's a legitimate point but I think you're overstating it. Then again, I'm not a believer that floors have to be sanitized, or indeed that much in a house has to be sanitized.
Answer: Lint rollers work on clothes and hard surfaces, and certain products also work on carpets. Consider, for instance, something like this large sticky-tape roller, called the Roll-O-Vac.

For a thorough carpet clean, you'll have to use a plug-in machine or call in the pros.
Comment: Definitely depends on the carpet. Your average loop-pile home carpet will be torn out by the roots, literally, with one of these. They'd be fine for low-pile commercial-grade carpet though.
Answer: Buy carpet squares.  Then take carpet squares outside and beat them.  Then throw them in the wash machine.
Don't know how doable for you this is (but I think I am the only person to actually answer the question fully).  I have seen people get out stains in carpet squares through washing so why not the whole floor...


Is a metal post base needed on a concrete pier?

Question: I'm building a backyard storage shed that will be supported by two 4x6x16' pressure treated rails laying on concrete piers.  The 6" side will be flat against the pier.

At the building supply store I have seen metal 6x6 post bases that seem to be used for attaching a post to concrete:

Since I'm using pressure treated lumber, and the piers stick above the ground a bit, do I really need these?  Can the rails sit directly on the concrete?  I can bolt the rails directly to the piers with wedge anchors.
Answer: You can sit the rails (or beams) right on the piers and level them using shims. That bracket is used for vertical mounting columns.


Too many redirects?

Question: I've used the 'Redirect mapper' tool by Varvy.com, and it's highlighted an issue with my www redirect. I'd like there to be only one redirect, but the tool shows two redirects. See screenshot below.
This is what I'm using in my htaccess file
RewriteEngine On
RewriteBase /
RewriteCond %{HTTPS} off [OR]
RewriteCond %{HTTP_HOST} ^www\. [NC]
RewriteCond %{HTTP_HOST} ^(?:www\.)?(.+)$ [NC]
RewriteRule ^ https://%1%{REQUEST_URI} [L,NE,R=301]

As the screenshot shows, http://www.d3creative.uk 302 redirects to https://www.d3creative.uk/, then 301 redirects to https://d3creative.uk/
I'd like to http://www.d3creative.uk/ to 301 redirect to https://d3creative.uk/, skipping the www redirect.

Any help would be much appreciated!

UPDATE
I use ServerPilot to manage my server, and I've setup SSL using ServerPilot.
I've removed the original RewriteCond and RewriteRule lines from my htaccess file
This clears up the multiple redirects (see screenshot below), but I still need a way to redirect www to non-www
I've contacted ServerPilot support, I'll post back here with any answers.
Comment: The 302 redirection is _not_ caused by those rules you posted. There has to be something else in your configuration. Probably not in a dynamic configuration file (".htaccess"), but in the real http servers host configuration which is the preferred location for such rules anyway.
Answer: Fixed!
Within the ServerPilot control panel there is an option to force a HTTPS redirect. This was conflicting with any redirects I was using in my htaccess file.
Turn 'Redirect to HTTPS' off and use the ruleset below in your htaccess
ServerPilot support kindly provided this ruleset, which works great.
RewriteCond %{HTTP_HOST} ^(www\.)(.*) [NC]
RewriteRule (.*) https://%2%{REQUEST_URI} [R=301,L]
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteRule ^(.*)$ https://%{HTTP_HOST}/$1 [R=301,L]

All versions of my domain now redirect (once) to my preferred version of the domain.

Too many redirects?


Do I need to complete a Subject for it to be garbage collected?

Question: I follow a cleanup pattern in my Angular components that looks like this:
class SomeComponent implements OnInit, OnDestroy {
    private destroy$ = new Subject();

    ngOnInit() {
        service.someStream().takeUntil(this.destroy$).subscribe(doSomething);
    }

    ngOnDestroy() {
        this.destroy$.next(true);
    }
}

This has the benefit of automatically unsubscribing when the component is destroyed.
My question is: Does a reference to destroy$ stick around indefinitely because I haven't called this.destroy$.complete(), or will it get GC'ed when the parent class is collected?
Comment: Even though you're not directly calling `complete()` on the Subject you complete the chain with the `takeUntil` operator which sends the `complete` signal and makes each operator to recursively unsubscribe. So it shouldn't matter whether the `complete` signal comes from the Subject or somewhere further down the chain.
Comment: @paulpdaniels If you have multiple subscriptions you'd have to keep references to each of them and call unsubscribe on each in sequence. By using pattern above you can have a single subject that unsubscribes from them all at once. The result is less, and more readable, code.
Comment: @martin I think your answer is incorrect. For me takeUntil will complete the stream you apply the takeUntil on. Not the one used into the takeUntil. Take a look to the marble diagram : http://reactivex.io/rxjs/class/es6/Observable.js~Observable.html#instance-method-takeUntil Notice that when `z` is emitted, the final stream is closed but the stream containing `z` remains open. So Sean, yes you need to call the next and also the complete.
Comment: The OP is about garbage collecting the `subject`, why are the comments discussing how to garbage collect `subscriptions` ?
Comment: While I'm pretty sure that it will get GC'd when references to the parent class are removed. This pattern seems dubious to me, why are you not simply tracking the subscription and calling `unsubscribe` on it when you close down all your streams?
Comment: @nej_simon, assuming that a component would call `ngOnInit` more than once, which itself sounds strange, this method is still more verbose than creating a new subscription and calling `Subscription#add` followed by `unsubscribe`, and it suffers a possible state inconsistency if the ordering  is incorrect and the `$destroy` call pre-empts the subscription.
Comment: @paulpdaniels Why would it need to call `ngOnInit` multiple times? In the above simplified code example, yes, but actual code may well be dealing with more subscriptions in `ngOnInit`. Explicitly creating a `Subscription` object is another way of doing something similar. I don't see how it's more verbose though nor why it would cause inconsistency. It's actually a pretty common way of doing it - see this post by Ben Lesh for ex. https://medium.com/@benlesh/rxjs-dont-unsubscribe-6753ed4fda87
Comment: @nej_simon The idea is that you only have to unsubscribe _once_ to tear down your pipelines, not that you never call unsubscribe. Note that even the article you linked builds up the subscriptions into a single pipeline which it then tears down in `unmount` with a single `unsubscribe` call. If you have multiple streams you can just compose them with `merge` and you still end up with a single `unsubscribe` to call at the "end of the world".
Answer: If you look at the source for Subject.complete, you'll find the answer:
complete() {
  if (this.closed) {
    throw new ObjectUnsubscribedError();
  }
  this.isStopped = true;
  const { observers } = this;
  const len = observers.length;
  const copy = observers.slice();
  for (let i = 0; i < len; i++) {
    copy[i].complete();
  }
  this.observers.length = 0;
}

Calling complete notifies any observers and then clears the array of observers. Unless you have an observer/subscriber that has a reference to the Subject, there is nothing in the complete implementation that would affect whether or not the Subject could be garbage collected.
RxJS pushes notifications to subscribers. Subscribers don't hold references to the observables; it's the other way around. So, unless you've explicitly created a subscriber that holds a reference to the Subject - via a closure or some other mechanism - there's no need to call complete for garbage-collection purposes.
Comment: The use in `takeUntil` is fine, as the subject's reference to the observer will be removed via the `takeUntil`-initiated unsubscription. It's possible that the observer's reference would prevent the subject from being collected - depending upon what's referencing the observer - but that's a separate issue and is not related to whether or not `complete` is called on the subject.
Comment: Hey @cartant, thank you for your answer. Just so I'm clear, does having my `Subject` in a `takeUntil` count as an observer/subscriber having a reference to it? I assume no, because that subject is unsubscribed from once it emits, but I just want to make sure.
Comment: @cartant, then this is a precaution, not a necessity [take-until-destroy.ts#L26](https://github.com/NetanelBasal/ngx-take-until-destroy/blob/master/src/take-until-destroy.ts#L26), right? *I was just researching the same thing as OP, so please don't consider this as annoyance.*
Comment: So, basically calling subject.complete() clears the list of observers / subscriptions maintained inside the subject, it does not garbage collect the subject itself ?
Comment: "Subscribers don't hold references to the observables" - yes they do, through the Subscription object returned by any call to subscribe on the observable. These objects can prevent a Subject from being garbage collected.
Answer: The original post actually poses two questions:

one in the title "Do I need to complete a Subject for it to be garbage collected?"

The answer to that question is "Yes, sometimes". So normally you should do a complete unless you know for sure it is not necessary. That is because any call to subscribe will return a Subscription object which does refer back to the observable. See, for example, https://www.learnrxjs.io/learn-rxjs/concepts/rxjs-primer#subscription.
(The statement in the answer If you look at the source ... you'll find the answer: "Subscribers don't hold references to the observables..." is misleading. Maybe the subscriber itself does not hold a reference to the Observable - but the returned Subscription object does.)
This reference can stop the Subject being garbage collected - unless complete is called to remove the subscription, or it is  removed in some other way. Which leads to the second question in the post...

the question implicit in the example: "Do I need to call complete on the subject in this example?".

In this particular example it is not necessary to call complete because the subscription to the subject, "destroy$", will have been created - and removed - by the takeUntil call. So if the OP wants to know whether a call to complete is needed in that particular example, the answer is no.


Change html text color without reloading the webview

Question: I'm wondering how can I change the html text color without reloading the webview because with the code I'm using currently, when I scroll down the webview that's holding the html file then click the button that I set to change the html text color, the page jumps again to the beginning of the html file. I think that happens because the webview is being reloaded every time I click the button. What do you thinks guys?
The code I'm using
NSString *myHtmlFile = [[NSBundle mainBundle] pathForResource:htmlName ofType:@"htm"];

NSString* text = [NSString stringWithContentsOfFile:myHtmlFile encoding:NSUTF8StringEncoding error:nil];

[self.myWebView loadHTMLString:[NSString stringWithFormat:@"%@", text] baseURL: nil];

I don't have any experience in javascript so if you can simplify your answer, it would be very helpful.
Comment: post the code of button. is it href or button or submit? does it have # as the URL. then the page will scroll on top
Comment: @Godwin I'm using UISegmentedControl, and there is no code beside the one i mentioned above. Don't know if that helps :)
Comment: Its reloading you web view. You need to make a javascript call from native to change the text then. your js will change the color. link might help you.

http://stackoverflow.com/questions/14334047/how-to-call-javascript-function-in-objective-c
Answer: What I have noticed is that for changing the text color of an already loaded html file, using the following code is better as it doesn't cause the webview to reload. But what worth noting is that this code only worked for me when changing an already loaded html file.
[_myWebView stringByEvaluatingJavaScriptFromString:@"document.getElementsByTagName('body')[0].style.color =\"Black\""];

But when I wanted to change the text color of a new html file (being loaded), the following code worked better for me.
NSString * myHtmlFile = [[NSBundle mainBundle] pathForResource:htmlName ofType:@"htm"];

NSString* text = [NSString stringWithContentsOfFile:htmlFile encoding:NSUTF8StringEncoding error:nil];
NSLog(@"%@",htmlFile);

[self.myWebView loadHTMLString:[NSString stringWithFormat:@"%@", text] baseURL: nil];

Answer: when you add  tag it means webview will treat it as a new page and will reload you can achieve ur task it with javascript or jQuery :)


VIm snipmate  auto completion not working

Question: This is the first time 'm trying snipmate with VIm 7.3 in ubuntu 12.04.
My .vimrc configuration is :
" kill vi compatibility
set nocompatible               " be iMproved

" -------------------------------------
" ---------snipmate--------------------
" -------------------------------------
Bundle "MarcWeber/vim-addon-mw-utils"
Bundle "tomtom/tlib_vim"
Bundle "honza/vim-snippets"

Bundle "garbas/vim-snipmate"
" -------------------------------------
 filetype plugin on

I believe thats all I want followed by :BundleInstall.
The tree structure of my .vim/bundle is
prayag@prayag:~$ tree -d .vim/bundle/
.vim/bundle/
|-- vim-colors-solarized
|   |-- autoload
|   |-- bitmaps
|   |-- colors
|   `-- doc
|-- vim-snipmate
|   |-- after
|   |   `-- plugin
|   |-- autoload
|   |-- doc
|   |-- ftplugin
|   |-- plugin
|   `-- syntax
|-- vim-snippets
|   |-- UltiSnips
|   |-- autoload
|   `-- snippets
|       |-- coffee
|       `-- javascript
`-- vundle
    |-- after
    |   |-- ftplugin
    |   `-- plugin
    |-- autoload
    |   `-- vundle
    |-- doc
    |-- ftplugin
    |-- plugin
    |-- syntax
    `-- test
        `-- files

139 directories

BUT, when I try some java code to test main snippet,
$ vi App.java
main

After pressing <TAB> gives me following result/error
main<Plug>snipMateNextOrTrigger

:verbose imap <Plug>snipMateNextOrTrigger gives me
No mapping found

with finish section commented in plugin/snipMate.vim, :verbose imap <Plug>snipMateNextOrTrigger gives me following information,
i  <Plug>snipMateNextOrTrigger * <C-R>=snipMate#TriggerSnippet()<CR>
        Last set from ~/.vim/bundle/vim-snipmate/plugin/snipMate.vim

and On pressing <TAB>
Error detected while processing /home/prayag/.vim/bundle/vundle/autoload/snipMate.vim:
line   15:
E122: Function <SNR>84_RemoveSnippet already exists, add ! to replace it

Same result/error I get with following configuration in .vimrc,
:imap <C-J> <Plug>snipMateNextOrTrigger
:smap <C-J> <Plug>snipMateNextOrTrigger

Same configuration worked fine for another ubuntu 13.04 machine.
I must be doing something wrong but couldn't figure it out.
References
Vim: snipMate plug-in does not trigger snippet completion
Comment: What do `:verbose map ` and `:verbose set cpo?` tell you?  Check `:version` for the " version", where  is one of Tiny, Small, Big, Huge (I may be missing some).
Comment: @benjifisher Hi, [here's](https://gist.github.com/iPrayag/5330389#comment-1185495) the result of `:verbose map ` etc.
Comment: Sorry, I should have asked about `:imap` instead of `:map`.  Probably it will show `i  snipMateNextOrTrigger`.  What about `:verbose imap snipMateNextOrTrigger`?  It is surprising that the same configuration behaves differently on another machine.  Do you have the same version of snipMate on both?  If not, maybe one is buggy.
Comment: @benjifisher `:verbose imap snipMateNextOrTrigger` gives me `No mapping found`
Comment: That is the problem.  The file https://github.com/garbas/vim-snipmate/blob/master/plugin/snipMate.vim contains the line `inoremap  snipMateNextOrTrigger  =snipMate#TriggerSnippet()`.  Either you do not have that file, it is missing that line, or it is not being `:source`d when vim starts up.  Or maybe the variable `loaded_snips` is defined somewhere else.  Look at the file, check `:scriptnames` right after starting vim, and search for "loaded_snips" in your other startup files.  I guess there are other possibilities, too, like `:imapclear`, but that seems unlikely.
Comment: @benjifisher `:scriptnames` gives me `~/.vim/bundle/vim-snipmate/after/plugin/snipMate.vim` loaded. Unfortunately that doesn't match to that of [github.com/garbas/vim-snipmate/blob/master/plugin/snipMate.vim](https://github.com/garbas/vim-snipmate/blob/master/plugin/snipMate.vim)
Comment: You should have similarly-named files in `after/plugin/` and `plugin/` (both relative to `master/` in the GitHub URL's and relative to `~/.vim/bundle/vim-snipmate/` in your installation).  The "after" version maps `` to something starting with ``, and the non-"after" version maps that to something else; the second map is the one that seems to be missing.
Comment: @benjifisher Fine, there's a `vim` file at `~/.vim/bundle/vim-snipmate/plugin/snipMate.vim` similar to https://github.com/garbas/vim-snipmate/blob/master/plugin/snipMate.vim with a line `inoremap  snipMateNextOrTrigger  =snipMate#TriggerSnippet()` .But [HERE's](https://gist.github.com/iPrayag/5330389/#comment-1188316) my `after/plugin/snipMate.vim`
Comment: I do not see anything wrong with the file in your `after/plugin/` directory, do you?  I gave several things to check 4 comments ago:  now that you know that you have the right file in the `plugin/` directory, check that it is being sourced with `:scriptnames`.  If it is, then either `loaded_snips` is defined somewhere else (easy to test by commenting out the `finish` line in the plugin) or the mapping is being removed later.
Comment: @benjifisher Thanks. After commenting out `finish` line in the plugin threw `Error detected while processing /home/prayag/.vim/bundle/vundle/autoload/snipMate.vim`. I removed this file along with `vim-snipmate` and reinstalled. Working fine. Please post your comments as answer. \,,/
Comment: Hi, @PrayagUpd, what operating system were you using? I think I have encountered exactly the same problem on my Windows 8.2 machine; however, using exactly the same set of packages, and similar vimrc, the `` key should have been working well on my Mac.
Answer: First of all, I suggest that you remove :set nocompatible from your vimrc file.  Vim automatically resets the 'cp' option if it finds a personal vimrc file (not a system vimrc file) on startup, and if you ever :source ~/.vimrc then it can have confusing results.
A complete answer to your question would be a very large troubleshooting flowchart.  That would be a good thing to have, but I am not going to work that hard.  Here is a summary of the conversation we had in the comments to diagnose this problem.

I have snipMate installed, but when I enter "main<Tab>" in Insert mode, I get "main<Plug>snipMateNextOrTrigger".

What do :verbose imap <Tab> and :verbose set cpo? tell you? Check :version for the "<size> version", where <size> is one of Tiny, Small, Big, Huge (I may be missing some).  (The problem may be how <Tab> is mapped, or you may be in compatible mode, or your version of vim may not support maps or may not support the <Tab> notation in maps.)

":verbose imap <Tab>" shows that "<Tab>" is mapped to "<Plug>snipMateNextOrTrigger" in "~/.vim/bundle/vim-snipmate/after/plugin/snipMate.vim", and the other stuff looks right.

How about :verbose imap <Plug>snipMateNextOrTrigger?  (The problem seems to be that <Tab> is mapped to something; that something is supposed to be remapped, but it is not.)

":verbose imap <Plug>snipMateNextOrTrigger" gives me "No mapping found".

That is the problem. The file plugin/snipMate.vim contains the line inoremap <silent> <Plug>snipMateNextOrTrigger  <C-R>=snipMate#TriggerSnippet()<CR>. Either you do not have that file, it is missing that line, or it is not being :sourced when vim starts up. Or maybe the variable loaded_snips is defined somewhere else. Look at the file, check :scriptnames right after starting vim, and search for "loaded_snips" in your other startup files. I guess there are other possibilities, too, like :imapclear, but that seems unlikely.

The file is there, and has the right line.  (At first I looked at "after/plugin/snipMate.vim" instead of "plugin/snipMate.vim".)  I checked ":scriptnames" and it is listed.  I did not check for other files defining "loaded_snips", but I commented out

if exists('loaded_snips') || &cp || version < 700
    finish
endif

and got an error from "snipMate.vim" in another directory.  I removed that file, re-installed snipMate, and now it works.
Comment: Thanks for this answer. For me the problem was that a random, old, unused line from my vimrc was overriding the tab mapping. `:verbose imap ` revealed it, and removing it allowed me to start using