text:
Q: Clojure Successive Powers How would a programmer go along to yield successive powers of two starting at 1 up to a limit?
I saw the documentation http://clojuredocs.org/clojure_core/1.2.0/clojure.core/iterate but still need help. Thanks.

A: Separate the task into two steps.
IF you first create a lazy infinite (no need to decide in advance the maximum power you'll need) sequence of powers of 2, you can subsequently slice and dice it any way you choose
(def powers-of-2 (iterate (partial *' 2) 2))
To get the first n powers
(take 5 powers-of-2)
To get the powers less than 70
(take-while (partial > 70) powers-of-2)
Added:
Actually I prefer the more general form:
(defn powers-of [n] (iterate (partial *' n) n))
(take 5 (powers-of 2))
As well as being more general, unless you have efficiency concerns, by calling the higher order function each time for a new lazy sequence you avoid holding on to the head and allow the memory to be garbage collected.

A: You can use for form:
(def powers (for [x (range)]
                 (java.lang.Math/pow 2 x)))

(take 10 powers)
(1.0 2.0 4.0 8.0 16.0 32.0 64.0 128.0 256.0 512.0)

A: Here is one way:
(defn powers-of-two
  [n]
  (map ; we are mapping over a sequence
    (comp int #(Math/pow 2 %)) ; a composition of two functions
                               ; Math/pow returns doubles so int is used to make them into integers
    (range 1 (inc n)))) ; a sequence from 1 to 10

(powers-of-two 15) ;=> (2 4 8 16 32 64 128 256 512 1024 2048 4096 8192 16384 32768)

A: There are two ways to interpret "limit", and from your question it is not sure which one you mean.
Also, you say "starting at 1 up to a limit". Do you mean "start at 0^2 (which is 1) up to a limit", or "start at 1^2 (which is 2)"? In the examples below I'm assuming you want to start with 0^2. If you want to start with 1^2, replace (range) with (drop 1 (range)) in the code below.
In the first interpretation, "limit" means "give me a sequence of n elements, where the elements are the successive powers of two". Ankur and others showed how to do that:
;; return the sequence (0^2, 1^2, 2^2 ... 149^2)
(take 150 (for [x (range)] (java.lang.Math/pow 2 x)))
; => (1.0 2.0 4.0 8.0 ..... 7.1362384635297994E44)

;; this is functionally equivalent:
(for [x (range 150)] (java.lang.Math/pow 2 x))

The other interpretation is "give me a sequence of successive powers of two that are smaller than the limit". You could do that with the following:
;; return the sequence (0^2, 1^2, 2^2 ... 2^7)
(for [x (range) :let [r (Math/pow 2 x)] :while (< r 150)] r)
; => (2.0 4.0 8.0 16.0 32.0 64.0 128.0)


text:
Q: gst-launch return value What will be the return value of gst-launch application? Will it return '0' on success and non-negative number (ERROR CODE) on failure? Where can I fild list of all possible error codes of gst-launch.

A: On Linux the exit status code of last command is stored in variable $?. Typically it's 0 for success and non-zero for failure.
gst-launch v4l2src num-buffers=1 ! xvimagesink
echo $?

shows
0

while something erroneous like
gst-launch junk
echo $?

shows
1

A: Looking at the code, all ok is 0, not able to make sense of the pipeline is 1 (like already stated), and not being able to start or stop the pipeline is -1, and that's it. (gst-launch is meant as a prototyping-tool, and for real use of it, you need to use code, hence the not very comprehensive error-codes.)

redpajama_set_name: RedPajamaStackExchange


text:
Q: Once authenticated the HTTP 1.1 Authorization header is sent with every request to every resource within domain I am encountering a situation whereby an http 1.1 authorization header is sent to every resource under a given domain even though the initial 401 Authentication response by which the authorization information is requested contains a realm associated with a specific resource on the server.
I understand from the http 1.1 spec that a browser can pre-emptively send the Authorization header to a resource for which it already has authenticated.

A client MAY preemptively send the
     corresponding Authorization header with requests for resources in
     that space without receipt of another challenge from the server.
  http://www.ietf.org/rfc/rfc2617.txt

However, it would appear the browser is pre-empting every resource under the domain with the Authorization header.
I have experienced this behaviour for the domain and resources in question whilst using Opera 11.1, IE[7,8], Firefox 3.x which leaves me feeling confident (although not 100%) this is not a browser bug.
It is worth mentioning that the server presents the resource associated with the realm in question as virtual managed by the 'Alias' directive under Apache 2.0 thus for protected resource '/x' the apache configuration is:
Alias /x "/absolute/linux/filesystem/path"

<Directory "/absolute/linux/filesystem/path">
...
AuthName     "y"
AuthType Basic
...
</Directory>

I have one completely unsupported theory where the issue is related to the fact that '/x' is presented by apache as a virtual resource. I wonder if somehow this ends up mapping the realm to '/' instead of '/x'. I draw this conclusion from the fact that the browser is pre-empting the Authorization header to every resource.
I would be grateful if someone could point me in the right direction as it's likley I have mis-configured something in my setup.
In the interests of brevity I have omitted certain information (e.g. module versions et al) if required please ask and I will be more than happy to provide.
Thanks for reading.
Chris

A: Answered on Apache user mailing list here: http://httpd.markmail.org/search/?q=HTTP%201.1%20Authentication#query:HTTP%201.1%20Authentication+page:1+mid:vrkhnxuhynchdmp5+state:results


text:
Q: Is there a way to disable Ctlr+Z (or "undo") in a specific sheet in Google Sheets? I have a script that creates an additional sheet in my file called "Changelog" which tracks changes from another sheet (but same file) called "Source". It appends a new row with information specified in the script, however, if I were to undo something in the source sheet, it also undoes and removes the appended row in the Changelog sheet, which is not the ideal behavior.
Is there a way to disable Ctrl+Z in just my Changelog sheet? Or should I just make my script create a separate Google Sheet file altogether and make that my Changelog? I'm trying to avoid the latter because I want to have that information easily accessible to the users using the source file without having to refer to two separate files. Protecting the sheet also does not make it immune to when I undo something in the source file.
Would love to hear your thoughts!

A: No way to disable feature like Undo.
Spreadsheet is not a good instrument to use it as a add-only log. If you already logging events through Google Apps Script, I recommend you to use console.log(...) instead, because it is faster than SpreadSheet updating and data is logged to Logging service.
It can contain much more data and it can filter and search faster.
Resources:

*

*Class console documentation


text:
Q: Flash AS3, is text anti-aliasing controlled by code? Is text anti-aliasing controlled by code, or is it embedded? What I want to do is take a swf file that someone else has made, find all of the text in the swf file and change all of the anti-aliasing modes from animation to readability. Does it work that way in as3? I honestly haven't tried any anti-aliasing in code yet.

A: you can set the antiAliasType of a textfield to 'advanced', which gives you fine control over sharpness and thickness.  however, the fonts must be embedded (inclusive: the textfield must have embedFonts set to true, the TextFormat objects must have font properties exactly equal to the fontName of the embedded font, and the fonts must be already compiled).  so technically 'is it possible?' - yes.  is it likely to work the way you want it to?  no, unless you plan on working with a swiff that you know is using embedded fonts already.  then you'll need to grab all the textfields from the loaded swiff (you could use something like this: http://upshots.org/?p=107, then use array.filter to get back only TextField objects), then apply your logic.
EDIT: adding code sample
// assuming you're using the DisplayList class linked above
var request:URLRequest = new URLRequest("textfields.swf");
var loader:Loader = new Loader();
loader.contentLoaderInfo.addEventListener(Event.COMPLETE, completeHandler, false, 0, true);
loader.load(request);

function completeHandler(event:Event):void{

    var content:DisplayObjectContainer = event.target.loader.content as DisplayObjectContainer;
    addChild(content);

    var children:Array = new DisplayList(content);
    children = children.filter(function(item:Object, index:int, array:Array):Boolean {
        return item is TextField;
    });
    children.forEach(function(item:Object, index:int, array:Array):void {
        var textfield:TextField = item as TextField;
        textfield.antiAliasType = AntiAliasType.ADVANCED;
        textfield.sharpness = 100;
        textfield.thickness = 100;
    });
}

just ran a quick test - works as described.


text:
Q: We should be able to reply to comments and answers I want to be able to reply to comments and answers directly, instead of having to comment again.
For example, if someone has already answered under a user's answer then I have to write @user. I should just be able to click reply and it adds that for me.

A: You use comments to reply to answers... as well as other comments. That's basically how comments work already. I'm not sure what you're getting at otherwise.
If you're talking about threaded comments, no, that's just going to overcomplicate things.

A: Stack Overflow is not a forum. Our job is to ask questions and provide answers to those questions. That's why comments are small, compact, and ignorable, while questions and answers are big and important. You should avoid attempting to have a long discussion with people. If you're not asking a question, asking for clarification on a question, answering a question, or trying to improve an answer to a question, then your commentary is not needed.
You can effectively reply to a comment using @ notation, where you say @<person-name>, where <person-name> is the ID of the person you are talking to. And to "reply" to an answer, you comment on it.
Both of these require having commenting privileges. If you don't have that, then go earn some rep.


text:
Q: applying a function for cell elements in MATLAB I have neighh1 that is 1 by 10 cell
neighh1 =
Columns 1 through 6
[5x1 double]    [3x1 double]    [3x1 double]    [7x1 double]    [4x1 double]    [5x1 double]

Columns 7 through 10
[4x1 double]    [4x1 double]    [3x1 double]    [4x1 double]

I want to take two cells of neighh1 , for example neighh1{1} & neighh1{3}
neighh1{1}=
2
 4
 7
 8
10
neighh1{3}=
5
 6
 9
I have the matrix N that is a 2-dimentional array that contains 0 & 1,
Then I want to check if N(i,j) == 1 or not . Where i & j are the elements of neighh1{1} & neighh1{3}
so if N(4,7)== 1 I want to save 4 & 7 in a new matrix

A: Based on your comments you are simply looking for a way to access the contents of a cell.
I think you are looking for something like  this:
for t=1:numel(neighh1{1})
  for k = 1:numel(neigh1{3})
    N(neighh1{1}(t),neigh1{3}(k))
  end
end

If you want to add the values to a matrix directly in the loop, you could do this:
M=[];
for t=1:numel(neighh1{1})
  for k = 1:numel(neigh1{3})
      x = neighh1{1}(t);
      y = neigh1{3}(k);
    if N(x,y)
      M(end+1,:) = [x y];
    end
  end
end

A: If you want to index N with all combinations of the two vectors contained in the two cells:
[ii jj] = ndgrid(neighh1{1}, neighh1{3}.')
result = N(sub2ind(size(N), ii,jj));

See ndgrid and sub2ind for reference.

A: Well this is possible, easiest if you wanted to apply it for all elements, though. The trick is, you use a subset of that cell and apply the function to all elements of that via cellfun
cellfun(@length, neighh([1, 3]))

It returns the Vector [5, 3].

A: A = {[1:4].',[1:3].',[4:7].',[1:7].'}
A =
    [4x1 double]    [3x1 double]    [4x1 double]    [7x1 double]

To execute a function on all elements, you can use cellfun straight forward like this:
B = cellfun(@sin, A, 'uni', 0);

You can after this use the cells you want using regular indexing.
If you really want to execute a function only on cells 2 and 3, you may do:
B = cellfun(@sin, A([2, 3]), 'uni', 0);


text:
Q: JPA Query.getResultsList failing on table with composite key Windows 7
Java 8
Spring 4
Hibernate 5
MySql 5
I have a MySql table "person" defined with a composite primary key
CREATE TABLE person (
  id BIGINT(12) UNSIGNED NOT NULL,
  revision BIGINT(12) UNSIGNED NOT NULL,
  // omitted
  PRIMARY KEY ( id, revision);

my ApplicationContext.xml
  <!-- omitted  -->
  <bean id="compositeKey"  class="com.myProject.models.CompositeKey" />
  <bean id="personDao"     class="com.myProject.models.dao.impl.hibernate.PersonDaoImplHibernate" />

Class CompositeKey.java
@Embeddable
public class CompositeKey implements java.io.Serializable
{
    @GeneratedValue
    @Column( name="id", nullable=false)
    private Long id;

    @Column( name="revision", nullable=false)
    private Long revision;

    //constructors
    public CompositeKey() {
    //  this.id = id;    commented out due to being a generated value on the sql side
        this.revision = 0;
    }

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((id == null) ? 0 : id.hashCode());
        result = prime * result + ((revision == null) ? 0 : revision.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj) return true;
        if ( !( obj instanceof CompositeKey)) return false;
        CompositeKey that = ( CompositeKey) obj;
        return Objects.equals(getId(), that.getId()) && Objects.equals(getRevision(), that.getRevision());
    }

}

Class Person.java
@Entity
@Table( name="person")
public class Person implements java.io.Serializable
{
    @EmbeddedId
    private CompositeKey compositeKey;

    // omitted

    //constructors
    public Person() {}

    // getters and setters omitted

    @Override
    public int hashCode() {
        final int prime = 31;
        int result = 1;
        result = prime * result + ((compositeKey == null) ? 0 : compositeKey.hashCode());
        return result;
    }

    @Override
    public boolean equals(Object obj) {
        if (this == obj)
            return true;
        if (obj == null)
            return false;
        if (getClass() != obj.getClass())
            return false;
        Person other = (Person) obj;
        if (address == null) {
            if (other.address != null)
                return false;
        } else if (!address.equals(other.address))
            return false;
        if (birthDate == null) {
            if (other.birthDate != null)
                return false;
        } else if (!birthDate.equals(other.birthDate))
            return false;
        // omitted
        return true;
    }

}

Class PersonDaoImplHibernate.java
@Transactional
public class PersonDaoImplHibernate implements PersonDao
{
    @PersistenceContext( unitName="pu2")
    private EntityManager em;  //injected from bean

    public void setEm( EntityManager em) {
        this.em = em;
    }

    @SuppressWarnings("unchecked")
    public List<Person> getAll() {

        List<Person> results = null;

        String sqlcmd = " SELECT p FROM Person p";
        javax.persistence.Query query = em.createQuery( sqlcmd);
        results =  query.getResultList();  // <<<---- fails on this line

        return results;
    }

}

and at long last this line in my standalone non-webapp testing program:
results =  query.getResultList();

throws the dreaded
Exception in thread "main" javax.persistence.PersistenceException: org.hibernate.WrongClassException: Object [id=CompositeKey [id=0, revision=0]] was not of the specified subclass [com.myProject.models.Person] : Discriminator:
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:149)
    at org.hibernate.internal.ExceptionConverterImpl.convert(ExceptionConverterImpl.java:157)
    at org.hibernate.query.internal.AbstractProducedQuery.list(AbstractProducedQuery.java:1515)
    at org.hibernate.query.Query.getResultList(Query.java:146)
    at com.myProject.models.dao.impl.hibernate.PersonDaoImplHibernate.getAll(PersonDaoImplHibernate.java:43)
    at com.myProject.models.dao.impl.hibernate.PersonDaoImplHibernate$$FastClassBySpringCGLIB$$d0bde1e6.invoke(<generated>)
    at org.springframework.cglib.proxy.MethodProxy.invoke(MethodProxy.java:204)
    at org.springframework.aop.framework.CglibAopProxy$CglibMethodInvocation.invokeJoinpoint(CglibAopProxy.java:736)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:157)
    at org.springframework.transaction.interceptor.TransactionInterceptor$1.proceedWithInvocation(TransactionInterceptor.java:99)
    at org.springframework.transaction.interceptor.TransactionAspectSupport.invokeWithinTransaction(TransactionAspectSupport.java:282)
    at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:96)
    at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:179)
    at org.springframework.aop.framework.CglibAopProxy$DynamicAdvisedInterceptor.intercept(CglibAopProxy.java:671)
    at com.myProject.models.dao.impl.hibernate.PersonDaoImplHibernate$$EnhancerBySpringCGLIB$$e6f5d088.getAll(<generated>)
    at TestQueries.testPersonGetAll(TestQueries.java:47)
    at TestQueries.main(TestQueries.java:74)

Note that there doesn't seem to be any Discriminator at all - do I explicitly need to set one, and if so what would it be?
The examples on composite keys and @Embeddable and @EmbeddedId do not mention discriminators.
TIA,
code_warrior

A: Problem solved...turns out not to be an issue with out with how @Embeddable and @EmbeddedId at all, but rather having hibernate.hbm2ddl.auto=update had at some point changed the structure of my table.
I prefer to create my own tables manually then build the Java class to match.
DROPing the reCREATEing the table and removing the hbm2ddl statement from my applicationContext.xml  did the trick.
Along the way I learned that javax.persistence.TypedQuery will make sure getResultsList() returns a list of proper class objects. I've updated the code as appropriate.
Thanks to all,
code_warrior


text:
Q: Problem with .env file setting for docker-compose.yml file
I try to set variables in my `docker-compose.yml` file in a separate `PORTAL_ENVIRONMENT.env` file
I don't know, what I am doing wrong.
I have this output:
WARNING: The POSTGRES_DB variable is not set. Defaulting to a blank string.
WARNING: The POSTGRES_USER variable is not set. Defaulting to a blank string.
WARNING: The POSTGRES_PASSWORD variable is not set. Defaulting to a blank string.
WARNING: The HOST variable is not set. Defaulting to a blank string.
WARNING: The PORT2 variable is not set. Defaulting to a blank string.
WARNING: The PORT3 variable is not set. Defaulting to a blank string.
WARNING: The PORT1 variable is not set. Defaulting to a blank string.

docker-compose.yml looks like this:
  client_app:
    env_file:
      - PORTAL_ENVIRONMENT.env
    image: 'client:latest'
    build:
      context: ./
    container_name: client
    depends_on:
      - db
    environment:
      - SPRING_DATASOURCE_URL=jdbc:postgresql://db:5432/${POSTGRES_DB}
      - SPRING_DATASOURCE_USERNAME=${POSTGRES_USER}
      - SPRING_DATASOURCE_PASSWORD=${POSTGRES_PASSWORD}
      - SPRING_JPA_HIBERNATE_DDL_AUTO=update
      - HOST_NAME=${HOST}
      - CREDIT_POST=${PORT1}
      - PRODUCT_POST=${PORT3}
    ports:
      - ${PORT2}:8080

(there are 3 separate modules,every looks almost the same)
PORTAL_ENVIRONMENT.env looks like this:
HOST=localhost

PORT1=8089
PORT2=8090
PORT3=8091

POSTGRES_DB=create_credit
POSTGRES_USER=user
POSTGRES_PASSWORD=pass123

I run it with:
sudo docker-compose up --force-recreate --build

A: When specifying your service's environment, you want those environment variables (HOST, POSTGRES_DB, etc) to be accessible to docker-compose at the time that it parses your docker-compose file. To do that, you should put them in a file called just .env. (Alternatively, if they are set in your shell environment at the time you run docker-compose, that is okay too, but you probably want to be keeping them in a .env file.)
Instead, you're trying to use env_file: in the docker-compose file. That specifies that the service that uses the env_file should look in that file and then update its own environment with that information. env_file is like environment:, but it looks at a file. It's just for the container to use, and docker-compose can't use it to set up how to run the container.
If you'd like to also pass variables from a .env file into a container, you can do something like one of these:
environment:
 - MY_VARIABLE=${VARIABLE_IN_MY_ENV_FILE}
 - MY_VARIABLE_SAFER=${VARIABLE_IN_MY_ENV_FILE:?err}

(the ?err will cause the startup to fail if the environment variable is not set, which is a nice trick.)
If you want the .env file used by docker-compose to not be named .env (maybe you are fond of the name you already have for some reason), docker-compose also has its own --env-file command-line option which you can use to specify the path of the .env file to use.
If you're still curious or confused you could also check out the docker-compose Environment Variables documentation page - that one talks about both environment-setting for docker-compose and for containers, all in the same webpage.

A: Also make sure you are running docker-compose up in the correct folder where your YML File is, and that you have your .env file in the correct path in relation to your YML file


text:
Q: Why is the Gogh Terminal theme not working correctly? I'm running Ubuntu Gnome, and I installed the Terminal theme Gogh. However, while the background color has changed, the color of commands didn't. Why not?

A: You can write colors configuration in .bashrc file. There are several places to set the colors (for example, there is dircolors, in /usr/bin/ binary file to set the colors for dir, setvtegb file to set the virtual terminal colors etc.). You can also create your own .dircolors file in your home directory.
For the terminal, it has its own color config files. For ls, it has its own color config file, for any other component, which requires color profiles, they each have their own color config files. So, you need to dig more into it from your own operating system.
To dig more into it, do type
apropos "terminal colors" //apropos - search the whatis database for strings


text:
Q: How to animate a sequence of maps in postscript format? I'm working on the Atlantic ocean for my research and I need to create an animation of movement of few islands in the Atlantic from their past locations to their present locations that moved due to plate tectonics. Input will be a postscript file of that region.

Are there any tools which can do this task?

A: My usual method is to use the convert utility from either ImageMagick or GraphicsMagick to convert a sequence of still images from a variety of formats, including PostScript, and output a variety of other formats, such as an animated GIF or MNG.
For example, from a directory with several PostScript files, make an animated GIF with 0.2 seconds between each frame:
$ convert -delay 20 map*.ps map.gif

ImageMagick's version has many more options, such as -layers method, which can be used to control how a GIF animation is constructed. There are also plenty of options to control how the PostScript files are converted too. You may want to pre-process each PostScript still files into individual .png frames if this step is complicated.
Also, make sure your file names are sequenced correctly, like map0001.ps, map0002.ps, ..., map0365.ps, otherwise you might have odd jumps of frames.


text:
Q: Converge of Integral of Bounded Differentiable Function I am told that $h$ is a bounded differentiable function on $[0,\infty)$ with $h(0)=0$. I wish to show that
$$\int_0^\infty{\left|h\left(\dfrac{1}{x^2}\right)\right|\,dx} < \infty~.$$
I know that, because $h$ is differentiable at $0$, $\displaystyle\lim_{x\to 0^+}{\dfrac{h(x)}{x}} = h^\prime(0)$. I'm assuming this is leading me to use dominated convergence, but am not sure how to proceed.


text:
Q: Only one occurence of the symbol in string - regexp I have a string like that:
var x = _something_ somethingelse _whatever_

I'd like to match by regular expressions only something and whatever words (because they are located between two underscore characters directly). Rest word is between underscore characters by accident - I don't need it.
The regular expression I use is matches all of them. How to fixed that? My curent regexp:
/_(.*)_/gm

A: You could search for a word boundary and then for underscore.

var x = '_something_ somethingelse _whatever_ foo_bar _foo_2';

console.log(x.match(/\b_[^_]+_\b/g));


text:
Q: TYPO3 - Link to external URL redirect I'm using TYPO3 v6.2 and inside the footer I have links to my social networks :

As you can see, it is "Link to external URL".
Problem: TYPO3 creates new URL www.mycompany.com/twitter and then redirects to www.twitter.com/mycompany with a 303. How to avoid this behavior?

A: In 6.2 you need to do the immediate rendering in the menu by yourself:
For each page with type "external URL" (doktype == 3) you need to do a special handling.
NO {
    :
    your default configuration
    :
    // special handling for 'external URL'
    doNotLinkIt = 1
    doNotLinkIt.if {
        equals.field = doktype
        value = 3
    }
    stdWrap.cObject = TEXT
    stdWrap.cObject {
        if {
            equals.field = doktype
            value = 3
        }
        field = navtitle // title
        typolink {
            parameter.field = url
            extTarget.field = target
        }
    }
}

If you also want special handling for shortcuts you better use a CASE object with key.field = doktype
NO {
    :
    std handling (wrap)
    :

    // don't do the std link:
    doNotLinkIt = 1
    // but link it yourself:
    stdWrap.cObject = CASE
    stdWrap.cObject {
        key.field = doktype

        // normal pages:
        default = TEXT
        default {
            field = navtitle // title
            typolink.parameter.field = uid
        }

        // shortcut
        4 < .default
        4.typolink.parameter.field = shortcut

        // external url
        3 < .default
        3.typolink.parameter.field = url
        3.typolink.extTarget.field = target
    }
}

A: The behaviour has changed in TYPO3 7: Breaking: #62812 - Resolve URLs to "Link to external URL"-pages directly

The behaviour of pages with the type "Link to External URL" has changed for menus. Those pages link now directly to the provided url instead of linking the internal page with a redirect afterwards.

I assume that is what was intended in the question.


text:
Q: fsck is taking a lot of time?(buffer I/O error) I had a irregular powercut 4-5 times in a row within an hour. My ubuntu suddenly went into busy box mode and showed there are errors on /dev/sda5.
I then tried:
fsck /dev/sda5 -y
It has taken a lot of time more than an hour and still forcing rewrite. It seems that a lot of blocks are being repaired.
Can someone describe what is going on or suggest any fix?

A: Alas, what has probably happened is that you had the head hit the hard drive, or something similar.
Your best bet is probably to replace /dev/sda altogether.  Note that the errors may not be restricted to sda5, but may get all your partitions.
(I had this happen recently to a 5 terabyte drive.  Painful.)
In my experience, the "rewrite" option doesn't help.  And if you say no, fsck just terminates.  I would recommend mounting all the partition read-only and copying the data to other media (i.e. the new drive I'm recommending you acquire).
It is possible to do a "bad block scan" using the e2fsck option -c.  On the other hand, it isn't supposed to be needed on a modern hard disk.

A: The short answer: always run fsck after a abrupt shutdown, reboot, or disconnection of a drive. What causes serious damage to the filesystem structure is continuing to use it once it's already slightly damaged.
Long answer…
On its own "a long time" does not necessarily indicate a physical problem with the drive.
But it might, depending on what exactly you mean by a lot of blocks are being repaired: unreadable blocks being remapped indicates a potential drive fault, but blocks being cross-linked into multiple files is just a logical error with the filesystem. (Serious loss of data, but not cause to throw away the drive.)
I recently had to run fsck on a 5TiB drive connected via a USB-2 interface on an older machine, and even with no sector errors, it still took a very long time.
I ran strace to see why fsck.ext4 was so slow, and the answer was obvious: it was issuing a separate pread syscall for each 4KiB block - effectively, one for each of the 10M in-use inodes.
I went to bed after waiting for more than an hour, and it had completed successfully when I got up the next morning; somewhere between 1 and 9 hours after it started.
In my case I trusted that it wasn't a drive problem because (a) there had been a recent hard reboot, (b) the only reported errors were the free inode and free block counts being lower than they should have been, and (c) I'd been merging duplicate files when the reboot occurred — essentially, just deleting lots of stuff, and changing existing directory entries.
Fortunately I hadn't written new stuff as well, so there were no cross-linked files.


text:
Q: Difference between clone and deepClone I'm having a hard time visualising the difference between shallow clone and deep clone in apex, for example
Account acct = [SELECT Id, Name, Rating, ParentId FROM Account WHERE Id = '0010O00001qEu5cQAC'][0];

//specifying false for isDeepClone parameter
Account acctDeepClone = acct.clone(false,false);
acctDeepClone.Name = 'DeepClone2';

update acct;

Changing the account name of the shallow clone and then updating the original does nothing to the original, the original name remains.
Also, I cannot update acctDeepClone because it doesn't have an Id field.
If I change my code to the following
Account acct = [SELECT Id, Name, Rating, ParentId FROM Account WHERE Id = '0010O00001qEu5cQAC'][0];

//specifying true for isDeepClone parameter
Account acctDeepClone = acct.clone(false,true);
acctDeepClone.Name = 'DeepClone2';

update acct;

I see the exact same behaviour as in the first snippet, the original account is never updated, and I cannot update the cloned version.
Can someone please show a concrete example (no theory) of how these two really look like?

A: It affects the referenced objects.
If you have a lookup / master detail and you touch the info there and update afterwards, you will see the difference.
In the example below, if you play with false or true you will see that the Parent account is modified or not (respectively)
// Preparation of Hierarchy
Account a1 = new Account(Name = 'Acc 1');
insert a1;

Account a11 = new Account(Name = 'Acc 1.1', ParentId = a1.Id);
insert a11;

// fetch child 1
a11 = [SELECT Name, parent.Name FROM Account WHERE Id = :a11.Id];

// clone it to create a12
Account a12 = a11.clone(false,true);

// touch parent on clone
a12.parent.Name = 'Acc 1 FROM 2';

// update parent info from original child
// if you put true, it will keep 'Acc 1'
// if you put false it will have 'Acc 1 FROM 2'
update a11.parent;


text:
Q: Javascript regex to check for at least 3 carets in a string I am requesting assistance with a regular expression to show that there are at least 3 carets in a string. I've tried using /\^/ but that only finds if the caret exists one time.
Example Data:
KEYWORD^HOSTNAME^MESSAGE^NUMBERS

A: This expression should work:
(.*\^.*){3}

Example in javascript:
var str = "KEYWORD^HOSTNAME^MESSAGE^NUMBERS";
var patt = new RegExp(/(.*\^.*){3}/);
var res = patt.test(str);
console.log(res);


text:
Q: problema ao converter texto para minúsculo Galera criei uma função que converto o texto para minúsculo dentro do input, o problema e que quando informo um input com value, e tendo alterar algo o cursor pula para o final. Alguém sabe como resolver isso?
Meu código:

// Converte minusculas em maiusculas
function up(lstr) {
    var str = lstr.value;
    lstr.value = str.toUpperCase();
}
<input OnKeyUp='up(this)' type='text' class='form_campos form_campos_simples' id='inputNormal' name='historico' value="TESTANDO O TEXTO">

A: Não precisa usar função, usa assim direto no input:
onkeyUP="this.value = this.value.toUpperCase()"

Usando Ajax, permite edição em qualquer parte do campo sem pular o cursor:

$(document).ready( function() {
  $("#NOME_DO_SEU_INPUT").on('input', function(){

    // armazena posição corrente
    var start = this.selectionStart,
        end = this.selectionEnd;

    this.value = this.value.toUpperCase();

    // restaura posição armazenada anteriormente.
    this.setSelectionRange(start, end);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input id="NOME_DO_SEU_INPUT" />

Adaptação daqui

A: Bom com a ajuda do diego chegou a seguinte solução:

$(document).ready( function() {
  $('input').on('input', function(){

    // Armazena posição corrente do cursor
    var start = this.selectionStart,
        end = this.selectionEnd;

    this.value = this.value.toUpperCase();

    // Restaura posição armazenada anteriormente.
    this.setSelectionRange(start, end);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<input nome="campo1">
<input nome="campo2">
<input nome="campo3">
<input nome="campo4">
<input nome="campo5">
<input nome="campo6">
<input nome="campo7">

Obrigado pela ajuda.


text:
Q: Count of Rownumber before a particular value Suppose I have the following table. I want to count the number of wins before the first loss and I want to order by day. So before first loss on 4th Jan, there were 3 wins on 1st, 2nd and 3rd I should get 3. I used a case statement within rownumber (), but didn't work
Day Score
2-Jan   Win
1-Jan   Win
4-Jan   Lose
3-Jan   Win
5-Jan   Lose
6-Jan   Win

Desired Output
Day   Count(wins)
Day 3-Jan 3

A: You can do this with a subquery in the where clause:
select max(date), count(*)
from t
where t.score = 'Win' and
      t.date < (select min(t2.date) from t t2 where t2.score = 'Lose');


text:
Q: using tr command to read permission Following commands have been executed by me
[root@gblabvl31 Aakash]# cat > file1.txt
-rwx
[root@gblabvl31 Aakash]# cat file1.txt |tr '[-rwx]' '[0421]' > file2.txt
[root@gblabvl31 Aakash]# cat file2.txt
-]]]

I could not understand why the expected output which is
0421

is not achieved

A: tr is a little special and expects its parameters to already be character classes, thus
$ echo '-rwx' | tr -- '-rwx' '0421'
0421

yields the expected result.

A: Get rid of the character class:
$ tr -- '-rwx' '0421' <<<'-rwx'
0421


text:
Q: Designing a MongoDB solution? I'm a RDBMS guy that has a project that I believe will work really well in a MongoDB system.  For different reasons that I think is irrelevant for the questions at hand.
Anyway, my system will be something like the following:

Properties Available
  Houses
    House A
      123 Pine Street
    House B
      456 Main Street

Realtors
  Sale
    Leads
      Properties
        House A
          123 Pine Street
      People Involved
        Moe Howard
        Larry Fine
        Shemp Howard
    Budgets
      Operating Budget Items
        $200 rentals
        $400 supplies

As you can see, I have two collections.  One ("Properties Available") will be generated at different times from different sources and will be shared across any number of users.  Most of the content will be static and not change often.
The other collection is "Realtors".
Now, in my old RDBMS world, I would create tables for Leads, People, Budgets, etc.
However, I think keeping all of the information in one giant "record" would be better.  A "Sale" record would be worked on for a while (weeks perhaps) and then closed.  To me, keeping everything inside that one record is awesome.  Especially since there will be wildly generic and dynamic information stored inside such as websites, notes, photos, etc.
Am I approaching this with the right mind-set?  It's hard for me to let go of the relational model.
Thanks for any suggestions and tips.

A: One can't answer yes or no that this is the best design for your data.  You've described the items you want to store, but not how you intend to query it.
The relational model is great for designing storage that has minimal redundancy, and supports the widest range of queries.
The document-oriented model is great for optimizing specific queries.  But you need to know in advance what types of queries you need to be most efficient.
See TANSTAAFL.


text:
Q: Amended code to retrieve dual signature information from PE executable in Windows? I've been struggling for awhile to amend this code sample from Microsoft that shows (somewhat outdated) way how to retrieve a code signature information from an executable file. It works but it doesn't retrieve information if a binary file is dual-signed.
So I did some research and tried to rewrite it to make it recognize dual-signatures that are present in many modern executables in Windows. Unfortunately there are very few (nebulous) suggestion available (1), (2), such as those to use UnauthenticatedAttributes and szOID_NESTED_SIGNATURE (whatever that means) but only to retrieve a time stamp.
So I attempted to rewrite that Microsoft code, and here's what I got:
(To build it simply copy it into Visual Studio console project & change the .exe file path. The code that deals with dual-signatures is in the PrintDualSignatureInfo() function.)
#include "stdafx.h"

//SOURCE:
//      https://support.microsoft.com/en-us/help/323809/how-to-get-information-from-authenticode-signed-executables
//

#include <windows.h>
#include <wincrypt.h>
#include <wintrust.h>
#include <stdio.h>
#include <tchar.h>
#include <atlconv.h>

#pragma comment(lib, "crypt32.lib")

#define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)

typedef struct {
    LPWSTR lpszProgramName;
    LPWSTR lpszPublisherLink;
    LPWSTR lpszMoreInfoLink;
} SPROG_PUBLISHERINFO, *PSPROG_PUBLISHERINFO;

BOOL GetProgAndPublisherInfo(PCMSG_SIGNER_INFO pSignerInfo,
                             PSPROG_PUBLISHERINFO Info);
BOOL GetDateOfTimeStamp(PCMSG_SIGNER_INFO pSignerInfo, SYSTEMTIME *st);
BOOL PrintCertificateInfo(PCCERT_CONTEXT pCertContext);
BOOL GetTimeStampSignerInfo(PCMSG_SIGNER_INFO pSignerInfo,
                            PCMSG_SIGNER_INFO *pCounterSignerInfo);
void PrintSignatureAlgorithm(CRYPT_ALGORITHM_IDENTIFIER* pSigAlgo);
void PrintDualSignatureInfo(PCMSG_SIGNER_INFO pSignerInfo);
void PrintCertificateInfo(HCERTSTORE hStore, PCMSG_SIGNER_INFO pSignerInfo, LPCTSTR pStrCertName);

int main()
{
     WCHAR szFileName[MAX_PATH];
    HCERTSTORE hStore = NULL;
    HCRYPTMSG hMsg = NULL;
    BOOL fResult;
    DWORD dwEncoding, dwContentType, dwFormatType;
    PCMSG_SIGNER_INFO pSignerInfo = NULL;
    DWORD dwSignerInfo;
    SPROG_PUBLISHERINFO ProgPubInfo;

    ZeroMemory(&ProgPubInfo, sizeof(ProgPubInfo));
    __try
    {
        LPCTSTR pExePath = L"C:\\Users\\UserName\\Downloads\\procmon.exe";  //works
        //pExePath = L"C:\\Users\\UserName\\Downloads\\putty.exe";      //doesnt work

        lstrcpynW(szFileName, pExePath, MAX_PATH);

        // Get message handle and store handle from the signed file.
        fResult = CryptQueryObject(CERT_QUERY_OBJECT_FILE,
                                   szFileName,
                                   CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
                                   CERT_QUERY_FORMAT_FLAG_BINARY,
                                   0,
                                   &dwEncoding,
                                   &dwContentType,
                                   &dwFormatType,
                                   &hStore,
                                   &hMsg,
                                   NULL);
        if (!fResult)
        {
            _tprintf(_T("CryptQueryObject failed with %x\n"), GetLastError());
            __leave;
        }

        // Get signer information size.
        fResult = CryptMsgGetParam(hMsg,
                                   CMSG_SIGNER_INFO_PARAM,
                                   0,
                                   NULL,
                                   &dwSignerInfo);
        if (!fResult)
        {
            _tprintf(_T("CryptMsgGetParam failed with %x\n"), GetLastError());
            __leave;
        }

        // Allocate memory for signer information.
        pSignerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwSignerInfo);
        if (!pSignerInfo)
        {
            _tprintf(_T("Unable to allocate memory for Signer Info.\n"));
            __leave;
        }

        // Get Signer Information.
        fResult = CryptMsgGetParam(hMsg,
                                   CMSG_SIGNER_INFO_PARAM,
                                   0,
                                   (PVOID)pSignerInfo,
                                   &dwSignerInfo);
        if (!fResult)
        {
            _tprintf(_T("CryptMsgGetParam failed with %x\n"), GetLastError());
            __leave;
        }

        // Get program name and publisher information from
        // signer info structure.
        if (GetProgAndPublisherInfo(pSignerInfo, &ProgPubInfo))
        {
            if (ProgPubInfo.lpszProgramName != NULL)
            {
                wprintf(L"Program Name : %s\n",
                    ProgPubInfo.lpszProgramName);
            }

            if (ProgPubInfo.lpszPublisherLink != NULL)
            {
                wprintf(L"Publisher Link : %s\n",
                    ProgPubInfo.lpszPublisherLink);
            }

            if (ProgPubInfo.lpszMoreInfoLink != NULL)
            {
                wprintf(L"MoreInfo Link : %s\n",
                    ProgPubInfo.lpszMoreInfoLink);
            }
        }

        _tprintf(_T("\n"));

        // Print Signer certificate information.
        PrintCertificateInfo(hStore, pSignerInfo, L"Signer Certificate");

        //Look for dual signature
        PrintDualSignatureInfo(pSignerInfo);

    }
    __finally
    {
        // Clean up.
        if (ProgPubInfo.lpszProgramName != NULL)
            LocalFree(ProgPubInfo.lpszProgramName);
        if (ProgPubInfo.lpszPublisherLink != NULL)
            LocalFree(ProgPubInfo.lpszPublisherLink);
        if (ProgPubInfo.lpszMoreInfoLink != NULL)
            LocalFree(ProgPubInfo.lpszMoreInfoLink);

        if (pSignerInfo != NULL) LocalFree(pSignerInfo);
        if (hStore != NULL) CertCloseStore(hStore, 0);
        if (hMsg != NULL) CryptMsgClose(hMsg);
    }
    return 0;
}

void PrintCertificateInfo(HCERTSTORE hStore, PCMSG_SIGNER_INFO pSignerInfo, LPCTSTR pStrCertName)
{

    if(hStore &&
        pSignerInfo)
    {
        PCCERT_CONTEXT pCertContext = NULL;
        CERT_INFO CertInfo = {0};
        PCMSG_SIGNER_INFO pCounterSignerInfo = NULL;
        SYSTEMTIME st;

        __try
        {
            // Search for the signer certificate in the temporary
            // certificate store.
            CertInfo.Issuer = pSignerInfo->Issuer;
            CertInfo.SerialNumber = pSignerInfo->SerialNumber;

            pCertContext = CertFindCertificateInStore(hStore,
                                                      ENCODING,
                                                      0,
                                                      CERT_FIND_SUBJECT_CERT,
                                                      (PVOID)&CertInfo,
                                                      NULL);
            if (!pCertContext)
            {
                _tprintf(_T("CertFindCertificateInStore failed with %x\n"),
                    GetLastError());
                __leave;
            }

            // Print Signer certificate information.
            _tprintf(L"%s:\n\n", pStrCertName);     //(_T("Signer Certificate:\n\n"));
            PrintCertificateInfo(pCertContext);
            _tprintf(_T("\n"));

            // Get the timestamp certificate signerinfo structure.
            if (GetTimeStampSignerInfo(pSignerInfo, &pCounterSignerInfo))
            {
                // Search for Timestamp certificate in the temporary
                // certificate store.
                CertInfo.Issuer = pCounterSignerInfo->Issuer;
                CertInfo.SerialNumber = pCounterSignerInfo->SerialNumber;

                pCertContext = CertFindCertificateInStore(hStore,
                                                    ENCODING,
                                                    0,
                                                    CERT_FIND_SUBJECT_CERT,
                                                    (PVOID)&CertInfo,
                                                    NULL);
                if (!pCertContext)
                {
                    _tprintf(_T("CertFindCertificateInStore failed with %x\n"),
                        GetLastError());
                    __leave;
                }

                // Print timestamp certificate information.
                _tprintf(_T("TimeStamp Certificate:\n\n"));
                PrintCertificateInfo(pCertContext);
                _tprintf(_T("\n"));

                // Find Date of timestamp.
                if (GetDateOfTimeStamp(pCounterSignerInfo, &st))
                {
                    _tprintf(_T("Date of TimeStamp : %02d/%02d/%04d %02d:%02d\n"),
                                                st.wMonth,
                                                st.wDay,
                                                st.wYear,
                                                st.wHour,
                                                st.wMinute);
                }
                _tprintf(_T("\n"));
            }

        }
        __finally
        {
            if (pCounterSignerInfo != NULL)
                LocalFree(pCounterSignerInfo);

            if (pCertContext != NULL)
                CertFreeCertificateContext(pCertContext);
        }
    }

}

void PrintDualSignatureInfo(PCMSG_SIGNER_INFO pSignerInfo)
{
    if(pSignerInfo)
    {

        for(DWORD a = 0; a < pSignerInfo->UnauthAttrs.cAttr; a++)
        {
            if(pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId &&
                lstrcmpiA(pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId, szOID_NESTED_SIGNATURE) == 0)
            {
                HCRYPTMSG hMsg = ::CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, 0, NULL, NULL, NULL);
                if(hMsg)
                {
                    if(::CryptMsgUpdate(hMsg,
                        pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData,
                        pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData,
                        TRUE))
                    {
                        DWORD dwSignerInfo = 0;
                        ::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
                        if(dwSignerInfo != 0)
                        {
                            PCMSG_SIGNER_INFO pSignerInfo2 = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwSignerInfo];
                            if(pSignerInfo2)
                            {
                                if(::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM,
                                    0, (PVOID)pSignerInfo2, &dwSignerInfo))
                                {
                                    CRYPT_DATA_BLOB p7Data;
                                    p7Data.cbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData;
                                    p7Data.pbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData;

                                    HCERTSTORE hStore = ::CertOpenStore(CERT_STORE_PROV_PKCS7, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, NULL, 0, &p7Data);
                                    if(hStore)
                                    {
                                        // Print Signer certificate information.
                                        PrintCertificateInfo(hStore, pSignerInfo2, L"Dual Signer Certificate");

                                        //Close
                                        ::CertCloseStore(hStore, CERT_CLOSE_STORE_FORCE_FLAG);
                                    }
                                }

                                //Free mem
                                delete[] pSignerInfo2;
                                pSignerInfo2 = NULL;
                            }
                        }
                    }

                    //Close message
                    ::CryptMsgClose(hMsg);
                }

            }
        }

    }

}

void PrintSignatureAlgorithm(CRYPT_ALGORITHM_IDENTIFIER* pSigAlgo)
{
    if(pSigAlgo &&
        pSigAlgo->pszObjId)
    {
        PCCRYPT_OID_INFO pCOI = ::CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, pSigAlgo->pszObjId, 0);
        if(pCOI &&
            pCOI->pwszName)
        {
            _tprintf(L"%s", pCOI->pwszName);
        }
        else
        {
            USES_CONVERSION;
            _tprintf(L"%s",  A2W(pSigAlgo->pszObjId));
        }
    }
}

BOOL PrintCertificateInfo(PCCERT_CONTEXT pCertContext)
{
    BOOL fReturn = FALSE;
    LPTSTR szName = NULL;
    DWORD dwData;

    __try
    {
        // Print Serial Number.
        _tprintf(_T("Serial Number: "));
        dwData = pCertContext->pCertInfo->SerialNumber.cbData;
        for (DWORD n = 0; n < dwData; n++)
        {
            _tprintf(_T("%02x "),
              pCertContext->pCertInfo->SerialNumber.pbData[dwData - (n + 1)]);
        }
        _tprintf(_T("\n"));

        //Hashing algoriths
        _tprintf(L"Signature Algorithm: ");
        PrintSignatureAlgorithm(&pCertContext->pCertInfo->SignatureAlgorithm);
        _tprintf(_T("\n"));

        // Get Issuer name size.
        if (!(dwData = CertGetNameString(pCertContext,
                                         CERT_NAME_SIMPLE_DISPLAY_TYPE,
                                         CERT_NAME_ISSUER_FLAG,
                                         NULL,
                                         NULL,
                                         0)))
        {
            _tprintf(_T("CertGetNameString failed.\n"));
            __leave;
        }

        // Allocate memory for Issuer name.
        szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
        if (!szName)
        {
            _tprintf(_T("Unable to allocate memory for issuer name.\n"));
            __leave;
        }

        // Get Issuer name.
        if (!(CertGetNameString(pCertContext,
                                CERT_NAME_SIMPLE_DISPLAY_TYPE,
                                CERT_NAME_ISSUER_FLAG,
                                NULL,
                                szName,
                                dwData)))
        {
            _tprintf(_T("CertGetNameString failed.\n"));
            __leave;
        }

        // print Issuer name.
        _tprintf(_T("Issuer Name: %s\n"), szName);
        LocalFree(szName);
        szName = NULL;

        // Get Subject name size.
        if (!(dwData = CertGetNameString(pCertContext,
                                         CERT_NAME_SIMPLE_DISPLAY_TYPE,
                                         0,
                                         NULL,
                                         NULL,
                                         0)))
        {
            _tprintf(_T("CertGetNameString failed.\n"));
            __leave;
        }

        // Allocate memory for subject name.
        szName = (LPTSTR)LocalAlloc(LPTR, dwData * sizeof(TCHAR));
        if (!szName)
        {
            _tprintf(_T("Unable to allocate memory for subject name.\n"));
            __leave;
        }

        // Get subject name.
        if (!(CertGetNameString(pCertContext,
                                CERT_NAME_SIMPLE_DISPLAY_TYPE,
                                0,
                                NULL,
                                szName,
                                dwData)))
        {
            _tprintf(_T("CertGetNameString failed.\n"));
            __leave;
        }

        // Print Subject Name.
        _tprintf(_T("Subject Name: %s\n"), szName);

        fReturn = TRUE;
    }
    __finally
    {
        if (szName != NULL) LocalFree(szName);
    }

    return fReturn;
}

LPWSTR AllocateAndCopyWideString(LPCWSTR inputString)
{
    LPWSTR outputString = NULL;

    outputString = (LPWSTR)LocalAlloc(LPTR,
        (wcslen(inputString) + 1) * sizeof(WCHAR));
    if (outputString != NULL)
    {
        lstrcpyW(outputString, inputString);
    }
    return outputString;
}

BOOL GetProgAndPublisherInfo(PCMSG_SIGNER_INFO pSignerInfo,
                             PSPROG_PUBLISHERINFO Info)
{
    BOOL fReturn = FALSE;
    PSPC_SP_OPUS_INFO OpusInfo = NULL;
    DWORD dwData;
    BOOL fResult;

    __try
    {
        // Loop through authenticated attributes and find
        // SPC_SP_OPUS_INFO_OBJID OID.
        for (DWORD n = 0; n < pSignerInfo->AuthAttrs.cAttr; n++)
        {
            if (lstrcmpA(SPC_SP_OPUS_INFO_OBJID,
                        pSignerInfo->AuthAttrs.rgAttr[n].pszObjId) == 0)
            {
                // Get Size of SPC_SP_OPUS_INFO structure.
                fResult = CryptDecodeObject(ENCODING,
                            SPC_SP_OPUS_INFO_OBJID,
                            pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].pbData,
                            pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].cbData,
                            0,
                            NULL,
                            &dwData);
                if (!fResult)
                {
                    _tprintf(_T("CryptDecodeObject failed with %x\n"),
                        GetLastError());
                    __leave;
                }

                // Allocate memory for SPC_SP_OPUS_INFO structure.
                OpusInfo = (PSPC_SP_OPUS_INFO)LocalAlloc(LPTR, dwData);
                if (!OpusInfo)
                {
                    _tprintf(_T("Unable to allocate memory for Publisher Info.\n"));
                    __leave;
                }

                // Decode and get SPC_SP_OPUS_INFO structure.
                fResult = CryptDecodeObject(ENCODING,
                            SPC_SP_OPUS_INFO_OBJID,
                            pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].pbData,
                            pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].cbData,
                            0,
                            OpusInfo,
                            &dwData);
                if (!fResult)
                {
                    _tprintf(_T("CryptDecodeObject failed with %x\n"),
                        GetLastError());
                    __leave;
                }

                // Fill in Program Name if present.
                if (OpusInfo->pwszProgramName)
                {
                    Info->lpszProgramName =
                        AllocateAndCopyWideString(OpusInfo->pwszProgramName);
                }
                else
                    Info->lpszProgramName = NULL;

                // Fill in Publisher Information if present.
                if (OpusInfo->pPublisherInfo)
                {

                    switch (OpusInfo->pPublisherInfo->dwLinkChoice)
                    {
                        case SPC_URL_LINK_CHOICE:
                            Info->lpszPublisherLink =
                                AllocateAndCopyWideString(OpusInfo->pPublisherInfo->pwszUrl);
                            break;

                        case SPC_FILE_LINK_CHOICE:
                            Info->lpszPublisherLink =
                                AllocateAndCopyWideString(OpusInfo->pPublisherInfo->pwszFile);
                            break;

                        default:
                            Info->lpszPublisherLink = NULL;
                            break;
                    }
                }
                else
                {
                    Info->lpszPublisherLink = NULL;
                }

                // Fill in More Info if present.
                if (OpusInfo->pMoreInfo)
                {
                    switch (OpusInfo->pMoreInfo->dwLinkChoice)
                    {
                        case SPC_URL_LINK_CHOICE:
                            Info->lpszMoreInfoLink =
                                AllocateAndCopyWideString(OpusInfo->pMoreInfo->pwszUrl);
                            break;

                        case SPC_FILE_LINK_CHOICE:
                            Info->lpszMoreInfoLink =
                                AllocateAndCopyWideString(OpusInfo->pMoreInfo->pwszFile);
                            break;

                        default:
                            Info->lpszMoreInfoLink = NULL;
                            break;
                    }
                }
                else
                {
                    Info->lpszMoreInfoLink = NULL;
                }

                fReturn = TRUE;

                break; // Break from for loop.
            } // lstrcmp SPC_SP_OPUS_INFO_OBJID
        } // for
    }
    __finally
    {
        if (OpusInfo != NULL) LocalFree(OpusInfo);
    }

    return fReturn;
}

BOOL GetDateOfTimeStamp(PCMSG_SIGNER_INFO pSignerInfo, SYSTEMTIME *st)
{
    BOOL fResult;
    FILETIME lft, ft;
    DWORD dwData;
    BOOL fReturn = FALSE;

    // Loop through authenticated attributes and find
    // szOID_RSA_signingTime OID.
    for (DWORD n = 0; n < pSignerInfo->AuthAttrs.cAttr; n++)
    {
        if (lstrcmpA(szOID_RSA_signingTime,
                    pSignerInfo->AuthAttrs.rgAttr[n].pszObjId) == 0)
        {
            // Decode and get FILETIME structure.
            dwData = sizeof(ft);
            fResult = CryptDecodeObject(ENCODING,
                        szOID_RSA_signingTime,
                        pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].pbData,
                        pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].cbData,
                        0,
                        (PVOID)&ft,
                        &dwData);
            if (!fResult)
            {
                _tprintf(_T("CryptDecodeObject failed with %x\n"),
                    GetLastError());
                break;
            }

            // Convert to local time.
            FileTimeToLocalFileTime(&ft, &lft);
            FileTimeToSystemTime(&lft, st);

            fReturn = TRUE;

            break; // Break from for loop.

        } //lstrcmp szOID_RSA_signingTime
    } // for

    return fReturn;
}

BOOL GetTimeStampSignerInfo(PCMSG_SIGNER_INFO pSignerInfo, PCMSG_SIGNER_INFO *pCounterSignerInfo)
{
    PCCERT_CONTEXT pCertContext = NULL;
    BOOL fReturn = FALSE;
    BOOL fResult;
    DWORD dwSize;

    __try
    {
        *pCounterSignerInfo = NULL;

        // Loop through unathenticated attributes for
        // szOID_RSA_counterSign OID.
        for (DWORD n = 0; n < pSignerInfo->UnauthAttrs.cAttr; n++)
        {
            if (lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId,
                         szOID_RSA_counterSign) == 0)
            {
                // Get size of CMSG_SIGNER_INFO structure.
                fResult = CryptDecodeObject(ENCODING,
                           PKCS7_SIGNER_INFO,
                           pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
                           pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
                           0,
                           NULL,
                           &dwSize);
                if (!fResult)
                {
                    _tprintf(_T("CryptDecodeObject failed with %x\n"),
                        GetLastError());
                    __leave;
                }

                // Allocate memory for CMSG_SIGNER_INFO.
                *pCounterSignerInfo = (PCMSG_SIGNER_INFO)LocalAlloc(LPTR, dwSize);
                if (!*pCounterSignerInfo)
                {
                    _tprintf(_T("Unable to allocate memory for timestamp info.\n"));
                    __leave;
                }

                // Decode and get CMSG_SIGNER_INFO structure
                // for timestamp certificate.
                fResult = CryptDecodeObject(ENCODING,
                           PKCS7_SIGNER_INFO,
                           pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
                           pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
                           0,
                           (PVOID)*pCounterSignerInfo,
                           &dwSize);
                if (!fResult)
                {
                    _tprintf(_T("CryptDecodeObject failed with %x\n"),
                        GetLastError());
                    __leave;
                }

                fReturn = TRUE;

                break; // Break from for loop.
            }
        }
    }
    __finally
    {
        // Clean up.
        if (pCertContext != NULL) CertFreeCertificateContext(pCertContext);
    }

    return fReturn;
}

Unfortunately what I came up with doesn't always work correctly when dealing with dual signatures.
For instance, a working example. If I run it on Sysiternal's ProcMon, that has a dual-signature as we can see from Windows Explorer:

My code correctly retrieves both SHA1 and SHA256 signatures:

But, here's a non-working example. If I run it on some other dual-signed file, say Putty executable, which also has a dual signature:

The code above retrieves the same SHA256 cert twice:

Any idea why?
PS. This doesn't just happen with the Putty's signature. There are other dual-signed executables that exhibit the same behavior.

A: The reason the digest algorithm in your output does not match the digest algorithm shown in file properties is because what you are showing in your output is the digest algorithm of the first certificate in the certificate chain for the signature, not the digest algorithm of the Authenticode signature itself. It's like this:

+-----------+          +-------------------+          +---------+
| Root Cert |  signs   | Intermediate Cert |  signs   | PE Data |
|-----------|=========>|-------------------|=========>|---------|
|  SHA256   |          |      SHA256       |          |  SHA1   |
+-----------+          +-------------------+          +---------+

                                ^                          ^
                                |                          |
                         You are showing                But you
                              this                    want to show
                                                          this

The way Authenticode works is that first the file digest is computed using what is sometimes referred to (by Microsoft) as the "digest algorithm." That digest is then signed with a signing key whose certificate is provided. But that certificate itself is signed by computing its digest with what's referred to as "signature digest" and signing it with a key from a certificate higher up in the certificate chain and so on.
The first certificate in the certificate chain can be obtained with the CertFindCertificateInStore function. You are then supposed to keep invoking CertFindCertificateInStore in a while loop to get the other certificates. What you do in your code is obtain the first certificate in the certificate chain (with CertFindCertificateInStore) and print its signature digest algorithm. What you want to do instead is obtain and print the digest algorithm for the file signature. You can do that with CryptMsgGetParam with the CMSG_SIGNER_INFO_PARAM flag, and you do obtain it, you just don't print it.

Another way to think about this is in terms of the relationship between MSG_SIGNER_INFO and CERT_INFO. It's not a 1-1 relationship where the information needs to match. It's more like:

+---------------+                  +---------------+
| SIGNER_INFO 1 |                  | SIGNER_INFO 2 |
|---------------|                  |---------------|
|     SHA1      |                  |    SHA256     |
+---------------+                  +---------------+
        |                                  |
        |   +-------------+                |   +-------------+
        +---| CERT_INFO 1 |                +---| CERT_INFO 3 |
            |-------------|                    |-------------|
            |   SHA256    |                    |   SHA256    |
            +-------------+                    +-------------+
                   |                                  |
            +-------------+                    +-------------+
            | CERT_INFO 2 |                    | CERT_INFO 4 |
            |-------------|                    |-------------|
            |    SHA1     |                    |    SHA1     |
            +-------------+                    +-------------+

A: I think I got it to work:

Here's the updated code. Please make sure to check before you use it and post a comment if there are any issues:
#include <new>

#include <windows.h>
#include <wincrypt.h>
#include <wintrust.h>
#include <stdio.h>
#include <tchar.h>
#include <atlconv.h>

#pragma comment(lib, "crypt32.lib")

#define ENCODING (X509_ASN_ENCODING | PKCS_7_ASN_ENCODING)

enum RESULT_FIND_CONTEXT{
    RFC_FOUND_CONTEXT,
    RFC_NO_CONTEXT,
};

enum RESULT_FIND_CERT_STORE{
    RFCS_ERROR = -1,
    RFCS_NONE = 0,
    RFCS_FOUND_ONE = 1,
};

void RetrieveDigitalSignatureInfo(const WCHAR* pFilePath);
void PrintProgramAndPublisherInfo(PCMSG_SIGNER_INFO pSignerInfo);
RESULT_FIND_CONTEXT PrintCertificateInformation(HCERTSTORE hStore, PCMSG_SIGNER_INFO pSignerInfo, LPCTSTR pStrCertDescription, BOOL bIsTimeStamp, FILETIME* pftTimeStampUtc = NULL);
void PrintCertContextDetails(PCCERT_CONTEXT pCertContext, DWORD dwNameOutputType, CRYPT_ALGORITHM_IDENTIFIER* pHashAlgo);
void PrintDigestAlgorithmName(CRYPT_ALGORITHM_IDENTIFIER* pSigAlgo);
BOOL PrintSignerDateTime(FILETIME* pftUtc);
int PrintSignerTimeStampDateTime(PCMSG_SIGNER_INFO pSignerInfo);
RESULT_FIND_CERT_STORE FindCertStoreByIndex(int iIndex, HCERTSTORE& hOutStore, CRYPT_DATA_BLOB* p7Data = NULL);
void PrintDualSignatureInformation(PCMSG_SIGNER_INFO pSignerInfo);
void FindAppropriateStoreAndPrintCertificateInformation(PCMSG_SIGNER_INFO pSignerInfo, CRYPT_DATA_BLOB* p7Data, LPCTSTR pStrCertDescription, BOOL bIsTimeStamp, FILETIME* pftTimeStampUtc = NULL);

int _tmain(int argc, WCHAR* argv[])
{
    LPCTSTR pExePath;

    if(argc <= 1)
    {
        pExePath = L"C:\\Users\\UserName\\Downloads\\procmon.exe";
        //pExePath = L"C:\\Users\\UserName\\Downloads\\putty.exe";
    }
    else
    {
        //Otherwise use first argument from command line
        pExePath = argv[1];
    }

    _tprintf(L"File: %s\n", pExePath);

    RetrieveDigitalSignatureInfo(pExePath);

    return 0;
}

//The following functions were re-written from the following source to be able to
//retrieve dual-signatures from PE binaries:
//
//  https://support.microsoft.com/en-us/help/323809/how-to-get-information-from-authenticode-signed-executables

void RetrieveDigitalSignatureInfo(const WCHAR* pFilePath)
{
    HCERTSTORE hStore = NULL;
    HCRYPTMSG hMsg = NULL;

    if(CryptQueryObject(CERT_QUERY_OBJECT_FILE,
        pFilePath,
        CERT_QUERY_CONTENT_FLAG_PKCS7_SIGNED_EMBED,
        CERT_QUERY_FORMAT_FLAG_BINARY,
        0,
        NULL,
        NULL,
        NULL,
        &hStore,
        &hMsg,
        NULL))
    {
        //We must have at least one signer
        DWORD dwCountSigners = 0;
        DWORD dwcbSz = sizeof(dwCountSigners);
        if(CryptMsgGetParam(hMsg, CMSG_SIGNER_COUNT_PARAM, 0, &dwCountSigners, &dwcbSz))
        {
            if(dwCountSigners != 0)
            {
                //Get Signer Information
                dwcbSz = 0;
                CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwcbSz);
                if(dwcbSz)
                {
                    PCMSG_SIGNER_INFO pSignerInfo = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwcbSz];
                    if(pSignerInfo)
                    {
                        DWORD dwcbSz2 = dwcbSz;
                        if(CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, pSignerInfo, &dwcbSz) &&
                            dwcbSz == dwcbSz2)
                        {
                            //Print program publisher info
                            PrintProgramAndPublisherInfo(pSignerInfo);

                            _tprintf(L"\n");

                            //Print signer certificate info
                            if(PrintCertificateInformation(hStore, pSignerInfo, L"Signer Certificate", FALSE) == RFC_NO_CONTEXT)
                            {
                                _tprintf(L"ERROR: (0x%X) CertFindCertificateInStore(CERT_FIND_SUBJECT_CERT) data failed\n", ::GetLastError());
                            }

                            //Print dual-signature info
                            PrintDualSignatureInformation(pSignerInfo);

                        }
                        else
                            _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(CMSG_SIGNER_INFO_PARAM) data failed\n", ::GetLastError());

                        //Free mem
                        delete[] pSignerInfo;
                        pSignerInfo = NULL;
                    }
                    else
                        _tprintf(L"ERROR: (0x%X) new(PCMSG_SIGNER_INFO) failed\n", ::GetLastError());
                }
                else
                    _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(CMSG_SIGNER_INFO_PARAM) failed\n", ::GetLastError());
            }
            else
                _tprintf(L"ERROR: Must have to least one signer\n");
        }
        else
            _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(CMSG_SIGNER_COUNT_PARAM) failed\n", ::GetLastError());
    }
    else
        _tprintf(L"ERROR: (0x%X) CryptQueryObject(CERT_QUERY_OBJECT_FILE) failed\n", ::GetLastError());

    //Clear up
    if (hStore != NULL)
    {
        CertCloseStore(hStore, 0);
        hStore = NULL;
    }

    if (hMsg != NULL)
    {
        CryptMsgClose(hMsg);
        hMsg = NULL;
    }

}

void PrintProgramAndPublisherInfo(PCMSG_SIGNER_INFO pSignerInfo)
{
    // Loop through authenticated attributes and find SPC_SP_OPUS_INFO_OBJID OID.
    for(DWORD n = 0; n < pSignerInfo->AuthAttrs.cAttr; n++)
    {
        if(pSignerInfo->AuthAttrs.rgAttr[n].pszObjId)
        {
            if(lstrcmpA(pSignerInfo->AuthAttrs.rgAttr[n].pszObjId, SPC_SP_OPUS_INFO_OBJID) == 0)
            {
                // Get Size of SPC_SP_OPUS_INFO structure.
                PSPC_SP_OPUS_INFO pInfo = NULL;
                DWORD dwcbSz = 0;

                if(CryptDecodeObjectEx(ENCODING, SPC_SP_OPUS_INFO_OBJID,
                    pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].pbData,
                    pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].cbData,
                    CRYPT_DECODE_ALLOC_FLAG,
                    NULL,
                    &pInfo, &dwcbSz) &&
                    pInfo &&
                    dwcbSz)
                {

                    if(pInfo->pwszProgramName)
                    {
                        _tprintf(L"Program Name: %s\n", pInfo->pwszProgramName);
                    }

                    if (pInfo->pPublisherInfo)
                    {
                        switch (pInfo->pPublisherInfo->dwLinkChoice)
                        {
                            case SPC_URL_LINK_CHOICE:
                                _tprintf(L"Publisher Link: %s\n", pInfo->pPublisherInfo->pwszUrl);
                                break;
                            case SPC_FILE_LINK_CHOICE:
                                _tprintf(L"Publisher Link: %s\n", pInfo->pPublisherInfo->pwszFile);
                                break;
                        }
                    }

                    if (pInfo->pMoreInfo)
                    {
                        switch (pInfo->pMoreInfo->dwLinkChoice)
                        {
                            case SPC_URL_LINK_CHOICE:
                                _tprintf(L"MoreInfo Link: %s\n", pInfo->pMoreInfo->pwszUrl);
                                break;
                            case SPC_FILE_LINK_CHOICE:
                                _tprintf(L"MoreInfo Link: %s\n", pInfo->pMoreInfo->pwszFile);
                                break;
                        }
                    }
                }
                else
                    _tprintf(L"ERROR: (0x%X) CryptDecodeObjectEx(SPC_SP_OPUS_INFO_OBJID) data failed\n", ::GetLastError());

                if(pInfo)
                {
                    ::LocalFree(pInfo);
                    pInfo = NULL;
                }
            }
        }
    }

}

RESULT_FIND_CONTEXT PrintCertificateInformation(HCERTSTORE hStore, PCMSG_SIGNER_INFO pSignerInfo, LPCTSTR pStrCertDescription, BOOL bIsTimeStamp, FILETIME* pftTimeStampUtc)
{
    CERT_INFO ci = {0};
    ci.Issuer = pSignerInfo->Issuer;
    ci.SerialNumber = pSignerInfo->SerialNumber;

    PCCERT_CONTEXT pCertContext = NULL;

    DWORD dwcbSz;

    int c = 0;
    for(;; c++)
    {
        //Enumerate and look for needed cert context
        pCertContext = CertFindCertificateInStore(hStore,
            ENCODING, 0, CERT_FIND_SUBJECT_CERT,
            (PVOID)&ci, pCertContext);

        if(!pCertContext)
        {
            break;
        }

        if(!c)
        {
            //Print Signer certificate information.
            _tprintf(L"%s:\n", pStrCertDescription);
            if(!bIsTimeStamp)
            {
                _tprintf(L"----------------\n");
            }

            _tprintf(L"\n");
        }

        //In case of a timestamp
        if(bIsTimeStamp)
        {
            //Print time stamp
            if(!pftTimeStampUtc)
            {
                //Retrieve and print it
                if(PrintSignerTimeStampDateTime(pSignerInfo) == 0)
                {
                    _tprintf(L"ERROR: (0x%X) Failed to retrieve date/time for TimeStamp\n", ::GetLastError());
                }
            }
            else
            {
                //We have a time-stamp already
                if(!PrintSignerDateTime(pftTimeStampUtc))
                {
                    _tprintf(L"ERROR: (0x%X) Time conversion failed from %I64x\n", ::GetLastError(), *(ULONGLONG*)pftTimeStampUtc);
                }
            }
        }

        //Print subject name, issuer name, serial, signature algorithm
        PrintCertContextDetails(pCertContext,
            CERT_NAME_SIMPLE_DISPLAY_TYPE,      //Or use CERT_NAME_RDN_TYPE for a more detailed output
            &pSignerInfo->HashAlgorithm);
        volatile static char pmsgDoNotCopyAsIs[] =
            "Please read & verify this code before you "
            "copy-and-paste it into your production project! "
            "https://stackoverflow.com/q/50976612/3170929 "
            "{438EE426-7131-4498-8AF7-9DDCB2508F0C}";
        srand(rand()^pmsgDoNotCopyAsIs[0]);

        _tprintf(L"\n");

        #ifndef szOID_RFC3161_counterSign
        #define szOID_RFC3161_counterSign           "1.3.6.1.4.1.311.3.3.1"
        #endif

        if(!bIsTimeStamp)
        {
            //Get time stamp certificate(s)
            //Loop through unathenticated attributes and look for specific OIDs
            for (DWORD n = 0; n < pSignerInfo->UnauthAttrs.cAttr; n++)
            {
                if(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId)
                {
                    if(lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId, szOID_RSA_counterSign) == 0)
                    {
                        //This is a legacy signature standard
                        PCMSG_SIGNER_INFO pCounterSignerInfo = NULL;
                        dwcbSz = 0;

                        if(CryptDecodeObjectEx(ENCODING, PKCS7_SIGNER_INFO,
                            pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].pbData,
                            pSignerInfo->UnauthAttrs.rgAttr[n].rgValue[0].cbData,
                            CRYPT_DECODE_ALLOC_FLAG,
                            NULL,
                            &pCounterSignerInfo, &dwcbSz) &&
                            pCounterSignerInfo &&
                            dwcbSz)
                        {
                            //Got one signature
                            if(PrintCertificateInformation(hStore, pCounterSignerInfo, L"TimeStamp Certificate", TRUE) == RFC_NO_CONTEXT)
                            {
                                _tprintf(L"ERROR: (0x%X) CertFindCertificateInStore(CERT_FIND_SUBJECT_CERT) data failed\n", ::GetLastError());
                            }

                        }
                        else
                        {
                            _tprintf(L"ERROR: (0x%X) CryptDecodeObjectEx(PKCS7_SIGNER_INFO) failed\n", ::GetLastError());
                        }

                        //Free mem
                        if(pCounterSignerInfo)
                        {
                            ::LocalFree(pCounterSignerInfo);
                            pCounterSignerInfo = NULL;
                        }
                    }
                    else if(lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[n].pszObjId, szOID_RFC3161_counterSign) == 0)
                    {
                        //Using an RFC3161 time stamp
                        if(pSignerInfo->UnauthAttrs.rgAttr[n].cValue != 0)
                        {
                            HCRYPTMSG hMsg = ::CryptMsgOpenToDecode(ENCODING, 0, 0, NULL, NULL, NULL);
                            if(hMsg)
                            {
                                if(::CryptMsgUpdate(hMsg,
                                    pSignerInfo->UnauthAttrs.rgAttr[n].rgValue->pbData,
                                    pSignerInfo->UnauthAttrs.rgAttr[n].rgValue->cbData,
                                    TRUE))
                                {
                                    dwcbSz = 0;
                                    ::CryptMsgGetParam(hMsg, CMSG_CONTENT_PARAM, 0, NULL, &dwcbSz);
                                    if(dwcbSz != 0)
                                    {
                                        BYTE* pCntData = new (std::nothrow) BYTE[dwcbSz];
                                        if(pCntData)
                                        {
                                            if(::CryptMsgGetParam(hMsg, CMSG_CONTENT_PARAM, 0, pCntData, &dwcbSz))
                                            {

                                                //Retrieve time stamp
                                                FILETIME ftUtc = {0};

                                                void* pTmData = NULL;
                                                DWORD dwcbTmDataSz = 0;

                                                struct Microsoft_forgot_to_document_me{
                                                    void* something_0[9];
                                                    FILETIME ftUtc;
                                                };

                                                #ifndef TIMESTAMP_INFO
                                                #define TIMESTAMP_INFO                     ((LPCSTR) 80)
                                                #endif

                                                if(CryptDecodeObjectEx(ENCODING,    //X509_ASN_ENCODING,
                                                    TIMESTAMP_INFO,
                                                    pCntData,
                                                    dwcbSz,
                                                    CRYPT_DECODE_ALLOC_FLAG,
                                                    NULL,
                                                    &pTmData, &dwcbTmDataSz) &&
                                                    pTmData &&
                                                    dwcbTmDataSz >= sizeof(Microsoft_forgot_to_document_me))
                                                {
                                                    ftUtc = ((Microsoft_forgot_to_document_me*)pTmData)->ftUtc;
                                                }
                                                else
                                                    _tprintf(L"ERROR: (0x%X) CryptDecodeObjectEx(RFC3161/TIMESTAMP_INFO) data failed\n", ::GetLastError());

                                                if(pTmData)
                                                {
                                                    ::LocalFree(pTmData);
                                                    pTmData = NULL;
                                                }

                                                //Try to get signer info
                                                dwcbSz = 0;
                                                ::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwcbSz);
                                                if(dwcbSz != 0)
                                                {
                                                    CMSG_SIGNER_INFO* pTmSignerData = (CMSG_SIGNER_INFO*)new (std::nothrow) BYTE[dwcbSz];
                                                    if(pTmSignerData)
                                                    {
                                                        if(::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, pTmSignerData, &dwcbSz))
                                                        {
                                                            CRYPT_DATA_BLOB c7Data;
                                                            c7Data.pbData = pSignerInfo->UnauthAttrs.rgAttr[n].rgValue->pbData;
                                                            c7Data.cbData = pSignerInfo->UnauthAttrs.rgAttr[n].rgValue->cbData;

                                                            //Try to locate the appropriate store
                                                            FindAppropriateStoreAndPrintCertificateInformation(pTmSignerData, &c7Data, L"TimeStamp Certificate", TRUE, &ftUtc);
                                                        }
                                                        else
                                                            _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(RFC3161/CMSG_SIGNER_INFO_PARAM) data failed\n", ::GetLastError());

                                                        //Free mem
                                                        delete[] pTmSignerData;
                                                        pTmSignerData = NULL;
                                                    }
                                                    else
                                                        _tprintf(L"ERROR: (0x%X) new(RFC3161) failed\n", ::GetLastError());
                                                }
                                                else
                                                    _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(RFC3161/CMSG_SIGNER_INFO_PARAM) failed\n", ::GetLastError());

                                            }
                                            else
                                                _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(RFC3161/CMSG_CONTENT_PARAM) data failed\n", ::GetLastError());

                                            //Free mem
                                            delete[] pCntData;
                                            pCntData = NULL;
                                        }
                                        else
                                            _tprintf(L"ERROR: (0x%X) new(RFC3161) failed\n", ::GetLastError());
                                    }
                                    else
                                        _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(RFC3161/CMSG_CONTENT_PARAM) failed\n", ::GetLastError());
                                }
                                else
                                    _tprintf(L"ERROR: (0x%X) CryptMsgUpdate(RFC3161) failed\n", ::GetLastError());

                                //Free handle
                                ::CryptMsgClose(hMsg);
                                hMsg = NULL;
                            }
                            else
                                _tprintf(L"ERROR: (0x%X) CryptMsgOpenToDecode(ENCODING) failed\n", ::GetLastError());
                        }

                    }
                }
            }
        }

    }

    //Free
    if(pCertContext)
    {
        CertFreeCertificateContext(pCertContext);
        pCertContext = NULL;
    }

    return c != 0 ? RFC_FOUND_CONTEXT : RFC_NO_CONTEXT;
}

void PrintCertContextDetails(PCCERT_CONTEXT pCertContext, DWORD dwNameOutputType, CRYPT_ALGORITHM_IDENTIFIER* pHashAlgo)
{
    //'dwNameOutputType' = one of: CERT_NAME_SIMPLE_DISPLAY_TYPE, CERT_NAME_RDN_TYPE, etc. see CertGetNameString()
    DWORD dwcbSz;
    WCHAR* pBuff;

   //Get subject name.
    dwcbSz = CertGetNameString(pCertContext, dwNameOutputType, 0, NULL, NULL, 0);
    if(dwcbSz != 0)
    {
        pBuff = new (std::nothrow) WCHAR[dwcbSz];
        if(pBuff)
        {
            if(CertGetNameString(pCertContext, dwNameOutputType, 0, NULL, pBuff, dwcbSz) == dwcbSz)
            {
                _tprintf(L"Subject: %s\n", pBuff);
            }
            else
                _tprintf(L"ERROR: (0x%X) CertGetNameString(subject) data failed\n", ::GetLastError());

            //Free mem
            delete[] pBuff;
            pBuff = NULL;
        }
        else
            _tprintf(L"ERROR: (0x%X) new CertGetNameString(subject) data failed\n", ::GetLastError());
    }
    else
        _tprintf(L"ERROR: (0x%X) CertGetNameString(subject) failed\n", ::GetLastError());

    //Issuer
    dwcbSz = CertGetNameString(pCertContext, dwNameOutputType, CERT_NAME_ISSUER_FLAG, NULL, NULL, 0);
    if(dwcbSz != 0)
    {
        pBuff = new (std::nothrow) WCHAR[dwcbSz];
        if(pBuff)
        {
            if(CertGetNameString(pCertContext, dwNameOutputType, CERT_NAME_ISSUER_FLAG, NULL, pBuff, dwcbSz) == dwcbSz)
            {
                _tprintf(L"Issuer: %s\n", pBuff);
            }
            else
                _tprintf(L"ERROR: (0x%X) CertGetNameString(issuer) data failed\n", ::GetLastError());

            //Free mem
            delete[] pBuff;
            pBuff = NULL;
        }
        else
            _tprintf(L"ERROR: (0x%X) new CertGetNameString(issuer) data failed\n", ::GetLastError());
    }
    else
        _tprintf(L"ERROR: (0x%X) CertGetNameString(issuer) failed\n", ::GetLastError());

    //Print Serial Number.
    _tprintf(_T("Serial Number: "));
    dwcbSz = pCertContext->pCertInfo->SerialNumber.cbData;
    for (DWORD n = 0; n < dwcbSz; n++)
    {
        _tprintf(_T("%02x"), pCertContext->pCertInfo->SerialNumber.pbData[dwcbSz - (n + 1)]);
    }
    _tprintf(_T("\n"));

    //Digest algorithm
    _tprintf(L"Digest Algorithm: ");
    PrintDigestAlgorithmName(pHashAlgo);
    _tprintf(_T("\n"));

}

void PrintDigestAlgorithmName(CRYPT_ALGORITHM_IDENTIFIER* pSigAlgo)
{
    if(pSigAlgo &&
        pSigAlgo->pszObjId)
    {
        PCCRYPT_OID_INFO pCOI = CryptFindOIDInfo(CRYPT_OID_INFO_OID_KEY, pSigAlgo->pszObjId, 0);
        if(pCOI &&
            pCOI->pwszName)
        {
            _tprintf(L"%s", pCOI->pwszName);
        }
        else
        {
            USES_CONVERSION;
            _tprintf(L"%s",  A2W(pSigAlgo->pszObjId));
        }
    }
}

BOOL PrintSignerDateTime(FILETIME* pftUtc)
{
    BOOL bRes = FALSE;

    if(pftUtc)
    {
        //Convert to local time
        FILETIME ftLoc = {0};
        SYSTEMTIME stLoc = {0};

        if(FileTimeToLocalFileTime(pftUtc, &ftLoc) &&
            FileTimeToSystemTime(&ftLoc, &stLoc))
        {
            _tprintf(L"Date of TimeStamp : %02d/%02d/%04d %02d:%02d:%02d\n",
                stLoc.wMonth,
                stLoc.wDay,
                stLoc.wYear,
                stLoc.wHour,
                stLoc.wMinute,
                stLoc.wSecond);

            bRes = TRUE;
        }
    }
    else
        ::SetLastError(ERROR_INVALID_PARAMETER);

    return bRes;
}

int PrintSignerTimeStampDateTime(PCMSG_SIGNER_INFO pSignerInfo)
{
    int nCountTimeStamps = 0;

    //Loop through authenticated attributes
    for (DWORD n = 0; n < pSignerInfo->AuthAttrs.cAttr; n++)
    {
        if (pSignerInfo->AuthAttrs.rgAttr[n].pszObjId &&
            lstrcmpA(pSignerInfo->AuthAttrs.rgAttr[n].pszObjId, szOID_RSA_signingTime) == 0)
        {
            // Decode and get FILETIME structure.
            FILETIME ftUtc = {0};
            DWORD dwData = sizeof(ftUtc);

            if(CryptDecodeObject(ENCODING, PKCS_UTC_TIME,
                pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].pbData,
                pSignerInfo->AuthAttrs.rgAttr[n].rgValue[0].cbData,
                0,
                (PVOID)&ftUtc, &dwData))
            {
                //Got time stamp
                nCountTimeStamps++;

                //And print it
                if(!PrintSignerDateTime(&ftUtc))
                {
                    _tprintf(L"ERROR: (0x%X) Time conversion failed from %I64x\n", ::GetLastError(), *(ULONGLONG*)&ftUtc);
                }
            }
            else
            {
                _tprintf(L"ERROR: (0x%X) CryptDecodeObject(PKCS_UTC_TIME) failed\n", ::GetLastError());
            }
        }
    }

    return nCountTimeStamps;
}

RESULT_FIND_CERT_STORE FindCertStoreByIndex(int iIndex, HCERTSTORE& hOutStore, CRYPT_DATA_BLOB* p7Data)
{
    //'hOutStore' = receives cert store handle. If not NULL, make sure to release it by calling CertCloseStore(hStore, CERT_CLOSE_STORE_FORCE_FLAG);
    //'p7Data' = used with index 0 only
    hOutStore = NULL;

    switch (iIndex)
    {
    case 0:
        hOutStore = CertOpenStore(CERT_STORE_PROV_PKCS7, X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, NULL, 0, p7Data);
        break;

    case 1:
        hOutStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
            CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_READONLY_FLAG | 0x10000,      // flags = 0x18001
            "ROOT");
        break;
    case 2:
        hOutStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
            CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_READONLY_FLAG | 0x10000,      // flags = 0x18001
            "TRUST");
        break;
    case 3:
        hOutStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
            CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_READONLY_FLAG | 0x10000,      // flags = 0x18001
            "CA");
        break;
    case 4:
        hOutStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
            CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_READONLY_FLAG | 0x10000,      // flags = 0x18001
            "MY");
        break;
    case 5:
        hOutStore = CertOpenStore(CERT_STORE_PROV_SYSTEM_A, 0, 0,
            CERT_STORE_NO_CRYPT_RELEASE_FLAG | CERT_STORE_READONLY_FLAG | 0x20000,      // flags = 0x28001
            "SPC");
        break;

    default:
        return RFCS_NONE;
    }

    return hOutStore ? RFCS_FOUND_ONE : RFCS_ERROR;
}

void FindAppropriateStoreAndPrintCertificateInformation(PCMSG_SIGNER_INFO pSignerInfo, CRYPT_DATA_BLOB* p7Data, LPCTSTR pStrCertDescription, BOOL bIsTimeStamp, FILETIME* pftTimeStampUtc)
{
    HCERTSTORE hStore = NULL;

    //Try to locate the appropriate store
    for(int i = 0;; i++)
    {
        if(hStore)
        {
            CertCloseStore(hStore, CERT_CLOSE_STORE_FORCE_FLAG);
            hStore = NULL;
        }

        RESULT_FIND_CERT_STORE resFnd = FindCertStoreByIndex(i, hStore, p7Data);
        if(resFnd == RFCS_FOUND_ONE)
        {
            //Try to retrieve info
            if(PrintCertificateInformation(hStore, pSignerInfo, pStrCertDescription, bIsTimeStamp, pftTimeStampUtc) == RFC_FOUND_CONTEXT)
            {
                //All done
                break;
            }
        }
        else
        {
            //Stop the seatch
            if(resFnd == RFCS_NONE)
            {
                //No context
                _tprintf(L"ERROR: (0x%X) CertOpenStore(no_context) failed\n", ::GetLastError());
            }
            else
            {
                //Error
                _tprintf(L"ERROR: (0x%X) CertOpenStore(%i) data failed\n", ::GetLastError(), i);
            }

            break;
        }
    }

    if(hStore)
    {
        ::CertCloseStore(hStore, CERT_CLOSE_STORE_FORCE_FLAG);
        hStore = NULL;
    }

}

void PrintDualSignatureInformation(PCMSG_SIGNER_INFO pSignerInfo)
{
    //Loop through unauthenticated attributes
    for(DWORD a = 0; a < pSignerInfo->UnauthAttrs.cAttr; a++)
    {
        #ifndef szOID_NESTED_SIGNATURE
        #define szOID_NESTED_SIGNATURE              "1.3.6.1.4.1.311.2.4.1"
        #endif

        //We need szOID_NESTED_SIGNATURE att
        if(pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId &&
            lstrcmpA(pSignerInfo->UnauthAttrs.rgAttr[a].pszObjId, szOID_NESTED_SIGNATURE) == 0)
        {
            HCRYPTMSG hMsg = ::CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING, 0, 0, NULL, NULL, NULL);
            if(hMsg)
            {
                if(::CryptMsgUpdate(hMsg,
                    pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData,
                    pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData,
                    TRUE))
                {
                    DWORD dwSignerInfo = 0;
                    ::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM, 0, NULL, &dwSignerInfo);
                    if(dwSignerInfo != 0)
                    {
                        PCMSG_SIGNER_INFO pSignerInfo2 = (PCMSG_SIGNER_INFO)new (std::nothrow) BYTE[dwSignerInfo];
                        if(pSignerInfo2)
                        {
                            if(::CryptMsgGetParam(hMsg, CMSG_SIGNER_INFO_PARAM,
                                0, (PVOID)pSignerInfo2, &dwSignerInfo))
                            {
                                CRYPT_DATA_BLOB c7Data;
                                c7Data.cbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->cbData;
                                c7Data.pbData = pSignerInfo->UnauthAttrs.rgAttr[a].rgValue->pbData;

                                //Try to locate the appropriate store & print from it
                                FindAppropriateStoreAndPrintCertificateInformation(pSignerInfo2, &c7Data, L"Dual Signer Certificate", FALSE);
                            }
                            else
                                _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(CMSG_SIGNER_INFO_PARAM) data failed\n", ::GetLastError());

                            //Free mem
                            delete[] pSignerInfo2;
                            pSignerInfo2 = NULL;
                        }
                        else
                            _tprintf(L"ERROR: (0x%X) new(PCMSG_SIGNER_INFO) failed\n", ::GetLastError());
                    }
                    else
                        _tprintf(L"ERROR: (0x%X) CryptMsgGetParam(CMSG_SIGNER_INFO_PARAM) failed\n", ::GetLastError());
                }
                else
                    _tprintf(L"ERROR: (0x%X) CryptMsgUpdate(dual-sig) failed\n", ::GetLastError());

                //Close message
                ::CryptMsgClose(hMsg);
            }
            else
                _tprintf(L"ERROR: (0x%X) CryptMsgOpenToDecode(X509_ASN_ENCODING | PKCS_7_ASN_ENCODING) failed\n", ::GetLastError());
        }
    }
}


text:
Q: Is this query safe from sql inject? This code looks fairly parameterized to me. I'm assuming this code is safe from a drop database command. Am I incorrect? Is there a better way to build queries with vb?
fname = A
lname = B
name = AB

SQL = "INSERT into [mydb].[db].[Table Name] (FName,LName,Name)"
SQL = SQL & "Values ('" & fname & "','" & lname & "','" & name)

'Execute SQL statement.
dbConn.Execute(SQL)