问:
Why isn't the enclosing class included in the generic parameters for inner class constructors?
```<code>import java.lang.reflect.*;
import java.util.Arrays;

class Test {
    class Inner {
        public <T> Inner(T arg) {}
    }

    public static void main(String[] args) {
        Constructor<?> constructor = Test.Inner.class.getConstructors( )[0];
        System.out.println(
            "Regular parameters: " +
            Arrays.toString(constructor.getParameterTypes()) +
            "\nGeneric parameters: " +
            Arrays.toString(constructor.getGenericParameterTypes())
        );
    }
}
</code>```

Running this prints the following.

Regular parameters: [class Test, class java.lang.Object]

  Generic parameters: [T]

My understanding of Java inner classes (i.e. non-static) is that their constructors implicitly have a parameter for their enclosing class. So, to get an instance of Inner, you call its constructor like so.

```<code>Test.Inner foo = new Test().new Inner(new Object());
</code>```

And what actually happens is that the instance of Test is passed to the constructor for Inner (along with any other arguments), where it's assigned to an implicit instance field.

Examining the nullary constructor for Inner bears this out, as calling getParameterTypes returns an array containing the Class objects representing Test and Object (the erasure of T).

However, since the constructor is generic, calling getGenericParameterTypes instead returns an array containing only the type variable T. The implicit parameter for the enclosing class is missing.

This only seems to happen when the inner class constructor declares a type variable. Why does it do that? Is it a bug?

答: It's been reported as a bug: http://bugs.sun.com/view_bug.do?bug_id=5087240</p>

ContentLicense: CC BY-SA 4.0

Body:
import java.lang.reflect.*;
import java.util.Arrays;

class Test {
    class Inner {
        public <T> Inner(T arg) {}
    }

    public static void main(String[] args) {
        Constructor<?> constructor = Test.Inner.class.getConstructors( )[0];
        System.out.println(
            "Regular parameters: " +
            Arrays.toString(constructor.getParameterTypes()) +
            "\nGeneric parameters: " +
            Arrays.toString(constructor.getGenericParameterTypes())
        );
    }
}

Running this prints the following.

Regular parameters: [class Test, class java.lang.Object]

  Generic parameters: [T]

My understanding of Java inner classes (i.e. non-static) is that their constructors implicitly have a parameter for their enclosing class. So, to get an instance of Inner, you call its constructor like so.

Test.Inner foo = new Test().new Inner(new Object());

And what actually happens is that the instance of Test is passed to the constructor for Inner (along with any other arguments), where it's assigned to an implicit instance field.

Examining the nullary constructor for Inner bears this out, as calling getParameterTypes returns an array containing the Class objects representing Test and Object (the erasure of T).

However, since the constructor is generic, calling getGenericParameterTypes instead returns an array containing only the type variable T. The implicit parameter for the enclosing class is missing.

This only seems to happen when the inner class constructor declares a type variable. Why does it do that? Is it a bug?


来源: stackexchange

问:
Function that changes singular French nouns into plurals doesn't work properly (regex)
I am currently reading "Dive Into Python" and in Chapter 6 the author has defined a function using regex that changes singular English nouns to plural ones.
Here it is:

```<code>def plural(noun):
        if re.search('[sxz]$', noun):
             return re.sub('$', 'es', noun)
        elif re.search('[^aeioudgkprt]h$', noun):
            return re.sub('$', 'es', noun)
        elif re.search('[^aeiou]y$', noun):
            return re.sub('y$', 'ies', noun)
        else:
            return noun + 's'
</code>```

I decided to write a function that changes singular French nouns to plural ones. This is what it looks like:

```<code>def plural(noun):
    if re.search('[sxz]$', noun):
        return re.sub('$', '', noun)
    elif re.search(r'''au$|al$|ail$|
                [^\bbijou\b| # exceptions
                \bcaillou\b|
                \bchou\b|
                \bgenou\b|
                \bhibou\b|
                \bjoujou\b|
                \bpou\b]''', noun, re.VERBOSE):
        return re.sub('au$|al$|ail$', 'aux', noun)
    elif re.search(r'''\bbijou\b|
                   \bcaillou\b|
                   \bchou\b|
                   \bgenou\b|
                   \bhibou\b|
                   \bjoujou\b|
                   \bpou\b''', noun, re.VERBOSE):
        return re.sub('ou$', 'oux', noun)
    elif re.search('eu$', noun):
        return re.sub('$', 'eux', noun)
    elif re.search('eau$', noun):
        return re.sub('$', 'eaux', noun)
    elif re.search('ou$', noun):
        return re.sub('ou$', 'ous', noun)
    else:
        return noun + 's'
</code>```

It works for the most part, but! for some reason if a noun (for example: fleur) just needs to be added "s" (the "else" statement), it doesn't work... It just returns 'fleur', but should return 'fleurs'.
I run the code in the visualizer and this is where the problem is:

```<code>      elif re.search(r'''au$|al$|ail$|
            [^\bbijou\b|
            \bcaillou\b|
            \bchou\b|
            \bgenou\b|
            \bhibou\b|
            \bjoujou\b|
            \bpou\b]''', noun, re.VERBOSE):
</code>```

When I delete "[^\bbijou\b|
                \bcaillou\b|
                \bchou\b|
                \bgenou\b|
                \bhibou\b|
                \bjoujou\b|
                \bpou\b]" then the "else" part works. I just want to understand what exactly the problem is and how to fix it.

答:
```<code>^\bbijou\b
</code>```

just means: Anything that ^ does not match either \b (backslash), b i j o or u

and therefor matches fleur.

Do you mean: \bbijou\b ?

ContentLicense: CC BY-SA 3.0

Body:
I am currently reading "Dive Into Python" and in Chapter 6 the author has defined a function using regex that changes singular English nouns to plural ones.
Here it is:

def plural(noun):
        if re.search('[sxz]$', noun):
             return re.sub('$', 'es', noun)
        elif re.search('[^aeioudgkprt]h$', noun):
            return re.sub('$', 'es', noun)
        elif re.search('[^aeiou]y$', noun):
            return re.sub('y$', 'ies', noun)
        else:
            return noun + 's'

I decided to write a function that changes singular French nouns to plural ones. This is what it looks like:

def plural(noun):
    if re.search('[sxz]$', noun):
        return re.sub('$', '', noun)
    elif re.search(r'''au$|al$|ail$|
                [^\bbijou\b| # exceptions
                \bcaillou\b|
                \bchou\b|
                \bgenou\b|
                \bhibou\b|
                \bjoujou\b|
                \bpou\b]''', noun, re.VERBOSE):
        return re.sub('au$|al$|ail$', 'aux', noun)
    elif re.search(r'''\bbijou\b|
                   \bcaillou\b|
                   \bchou\b|
                   \bgenou\b|
                   \bhibou\b|
                   \bjoujou\b|
                   \bpou\b''', noun, re.VERBOSE):
        return re.sub('ou$', 'oux', noun)
    elif re.search('eu$', noun):
        return re.sub('$', 'eux', noun)
    elif re.search('eau$', noun):
        return re.sub('$', 'eaux', noun)
    elif re.search('ou$', noun):
        return re.sub('ou$', 'ous', noun)
    else:
        return noun + 's'

It works for the most part, but! for some reason if a noun (for example: fleur) just needs to be added "s" (the "else" statement), it doesn't work... It just returns 'fleur', but should return 'fleurs'.
I run the code in the visualizer and this is where the problem is:

      elif re.search(r'''au$|al$|ail$|
            [^\bbijou\b|
            \bcaillou\b|
            \bchou\b|
            \bgenou\b|
            \bhibou\b|
            \bjoujou\b|
            \bpou\b]''', noun, re.VERBOSE):

When I delete "[^\bbijou\b|
                \bcaillou\b|
                \bchou\b|
                \bgenou\b|
                \bhibou\b|
                \bjoujou\b|
                \bpou\b]" then the "else" part works. I just want to understand what exactly the problem is and how to fix it.

Body:
^\bbijou\b

just means: Anything that ^ does not match either \b (backslash), b i j o or u

and therefor matches fleur.

Do you mean: \bbijou\b ?


问:
Hi, How to auto execute a php action page on every day at given time, i.e i want to execute a php script at 10:00 am everyday (In windows).?
How to auto execute a php action page on every day at given time, i.e i want to execute a php script at 10:00 am everyday (In windows).?
I want to take the given time from the database and the n i want to execute the php script at the specified time taken from the DB</p>

答:
You will have to use cronjob if you want to execute specific php script, but if you just want to run a mysql 'job', you could use mysql event feature, which allows you to run mysql jobs at scheduled times.

Discussion which one to use: Cronjob or MySQL event?

Here's the manual: https://dev.mysql.com/doc/refman/5.7/en/events-overview.html

And here is a simple example: https://www.sitepoint.com/how-to-create-mysql-events/

On windows 7 you could setup a Task Scheduler task:

Have Administrator rights

Start->Control Panel->System and Security->Administrative Tools->Task Scheduler

Action->Create Basic Task->Type a name and Click Next

Finish the wizard as you like


问:
Running GUI apps on docker container with a MacBookPro host
I have been trying to follow the instructions on https://learning-continuous-deployment.github.io/docker/images/dockerfile/2015/04/22/docker-gui-osx/ about running GUI apps in a docker container inside a MacBookPro host (using Docker tools).

I created a simple docker container using Fedora 23 and with firefox installed.

I try to run firefox and after about a minute I get the following error:

```<code>Unable to init server: Broadway display type not supported: 192.168.57.3:0
Error: cannot open display: 192.168.57.3:0
</code>```

Does anyone have a clue what the error means and/or how to fix it?

答:
On a Mac you may find the following steps useful:

Install XQuartz

Open it, goto preferences > Security and check the option to allow connections from network clients

Reboot

Start XQuartz (from the applications folder or with open -a XQuartz)

Allow incoming connections from your ip with xhost + $IP (see note 1)

Run firefox in your docker container (see note 2)

Note 1: Here's a neat trick toget your ip address:

```<code>export IP=$(ifconfig en0 | grep inet | awk '$1=="inet" {print $2}')
</code>```

Note 2: And an example docker run command to start firefox

```<code>docker run -it -e DISPLAY=$IP:0 -v /tmp/.X11-unix:/tmp/.X11-unix <image> firefox
</code>```

Body:
I have been trying to follow the instructions on https://learning-continuous-deployment.github.io/docker/images/dockerfile/2015/04/22/docker-gui-osx/ about running GUI apps in a docker container inside a MacBookPro host (using Docker tools).

I created a simple docker container using Fedora 23 and with firefox installed.

I try to run firefox and after about a minute I get the following error:

Unable to init server: Broadway display type not supported: 192.168.57.3:0
Error: cannot open display: 192.168.57.3:0

Does anyone have a clue what the error means and/or how to fix it?

Body:
On a Mac you may find the following steps useful:

Install XQuartz

Open it, goto preferences > Security and check the option to allow connections from network clients

Reboot

Start XQuartz (from the applications folder or with open -a XQuartz)

Allow incoming connections from your ip with xhost + $IP (see note 1)

Run firefox in your docker container (see note 2)

Note 1: Here's a neat trick toget your ip address:

export IP=$(ifconfig en0 | grep inet | awk '$1=="inet" {print $2}')

Note 2: And an example docker run command to start firefox

docker run -it -e DISPLAY=$IP:0 -v /tmp/.X11-unix:/tmp/.X11-unix <image> firefox


问:
How can I do mod without a mod operator?
This scripting language doesn't have a % or Mod(). I do have a Fix() that chops off the decimal part of a number. I only need positive results, so don't get too robust.</p>

答:
If someone arrives later, here are some more actual algorithms (with errors...read carefully)

https://eprint.iacr.org/2014/755.pdf

There are actually two main kind of reduction formulae: Barett and Montgomery. The paper from eprint repeat both in different versions (algorithms 1-3) and give an "improved" version in algorithm 4.

Overview

I give now an overview of the 4. algorithm:

1.) Compute "A*B" and Store the whole product in "C" that C and the modulus $p$ is the input for that algorithm.

2.) Compute the bit-length of $p$, say: the function "Width(p)" returns exactly that value.

3.) Split the input $C$ into N "blocks" of size "Width(p)" and store each in G. Start in G[0] = lsb(p) and end in G[N-1] = msb(p). (The description is really faulty of the paper)

4.) Start the while loop:
Set N=N-1 (to reach the last element)
precompute $b:=2^{Width(p)} \bmod p$

```<code>while N>0 do:
    T = G[N]
    for(i=0; i<Width(p); i++) do: //Note: that counter doesn't matter, it limits the loop)
        T = T << 1 //leftshift  by 1 bit
        while is_set( bit( T, Width(p) ) ) do // (N+1)-th bit of T is 1
            unset( bit( T, Width(p) ) ) // unset the (N+1)-th bit of T (==0)
            T += b
        endwhile
    endfor
    G[N-1] += T
    while is_set( bit( G[N-1], Width(p) ) ) do
        unset( bit( G[N-1], Width(p) ) )
        G[N-1] += b
    endwhile
    N -= 1
endwhile
</code>```

That does alot. Not we only need to recursivly reduce G[0]:

```<code>while G[0] > p do
    G[0] -= p
endwhile
return G[0]// = C mod p
</code>```

The other three algorithms are well defined, but this lacks some information or present it really wrong. But it works for any size ;)

Body:
If someone arrives later, here are some more actual algorithms (with errors...read carefully)

https://eprint.iacr.org/2014/755.pdf

There are actually two main kind of reduction formulae: Barett and Montgomery. The paper from eprint repeat both in different versions (algorithms 1-3) and give an "improved" version in algorithm 4.

Overview

I give now an overview of the 4. algorithm:

1.) Compute "A*B" and Store the whole product in "C" that C and the modulus $p$ is the input for that algorithm.

2.) Compute the bit-length of $p$, say: the function "Width(p)" returns exactly that value.

3.) Split the input $C$ into N "blocks" of size "Width(p)" and store each in G. Start in G[0] = lsb(p) and end in G[N-1] = msb(p). (The description is really faulty of the paper)

4.) Start the while loop:
Set N=N-1 (to reach the last element)
precompute $b:=2^{Width(p)} \bmod p$

while N>0 do:
    T = G[N]
    for(i=0; i<Width(p); i++) do: //Note: that counter doesn't matter, it limits the loop)
        T = T << 1 //leftshift  by 1 bit
        while is_set( bit( T, Width(p) ) ) do // (N+1)-th bit of T is 1
            unset( bit( T, Width(p) ) ) // unset the (N+1)-th bit of T (==0)
            T += b
        endwhile
    endfor
    G[N-1] += T
    while is_set( bit( G[N-1], Width(p) ) ) do
        unset( bit( G[N-1], Width(p) ) )
        G[N-1] += b
    endwhile
    N -= 1
endwhile

That does alot. Not we only need to recursivly reduce G[0]:

while G[0] > p do
    G[0] -= p
endwhile
return G[0]// = C mod p

The other three algorithms are well defined, but this lacks some information or present it really wrong. But it works for any size ;)


问:
DIV won't bottom?
My blog has popup divs and the divs should bottom but they don't :( The bottom will bottom but the content will stay up so the div just stretches.</p>

答:
It works fine in Firefox but not in Chrome.
I checked the jquery code and I could make it work with two changes:

1) animate the bottom css attribute insead of top

2) remove the 'px' at the end of the expression assigned to bottom/top navigation.
The changed script would be:

```<code>$(function () {
        $('.bubbleInfo').each(function () {
            var distance = 10;
            var time = 250;
            var hideDelay = 500;
            var hideDelayTimer = null;
            var beingShown = false;
            var shown = false;
            var trigger = $('.trigger', this);
            var info = $('.popup', this).css('opacity', 0);
            $([trigger.get(0), info.get(0)]).mouseover(function () {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                if (beingShown || shown) {
                    // don't trigger the animation again
                    return;
                } else {
                    // reset position of info box
                    beingShown = true;
                    info.css({
                        display: 'block'
                    }).animate({
                        bottom: '-=' + distance,
                        opacity: 1
                    }, time, 'swing', function() {
                        beingShown = false;
                        shown = true;
                    });
                }
                return false;
            }).mouseout(function () {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                hideDelayTimer = setTimeout(function () {
                    hideDelayTimer = null;
                    info.animate({
                        bottom: '-=' + distance,
                        opacity: 0
                    }, time, 'swing', function () {
                        shown = false;
                        info.css('display', 'none');
                    });
                }, hideDelay);
                return false;
            });
        });
    });
</code>```

P.S: I verified this and it works in Chrome and FF now.

ContentLicense: CC BY-SA 2.5

Title: DIV won't bottom?

Body:
It works fine in Firefox but not in Chrome.
I checked the jquery code and I could make it work with two changes:

1) animate the bottom css attribute insead of top

2) remove the 'px' at the end of the expression assigned to bottom/top navigation.
The changed script would be:

$(function () {
        $('.bubbleInfo').each(function () {
            var distance = 10;
            var time = 250;
            var hideDelay = 500;
            var hideDelayTimer = null;
            var beingShown = false;
            var shown = false;
            var trigger = $('.trigger', this);
            var info = $('.popup', this).css('opacity', 0);
            $([trigger.get(0), info.get(0)]).mouseover(function () {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                if (beingShown || shown) {
                    // don't trigger the animation again
                    return;
                } else {
                    // reset position of info box
                    beingShown = true;
                    info.css({
                        display: 'block'
                    }).animate({
                        bottom: '-=' + distance,
                        opacity: 1
                    }, time, 'swing', function() {
                        beingShown = false;
                        shown = true;
                    });
                }
                return false;
            }).mouseout(function () {
                if (hideDelayTimer) clearTimeout(hideDelayTimer);
                hideDelayTimer = setTimeout(function () {
                    hideDelayTimer = null;
                    info.animate({
                        bottom: '-=' + distance,
                        opacity: 0
                    }, time, 'swing', function () {
                        shown = false;
                        info.css('display', 'none');
                    });
                }, hideDelay);
                return false;
            });
        });
    });

P.S: I verified this and it works in Chrome and FF now.


问:
Non-scalar literals and querying in SPARQL
Assume the runtime context here is Apache jena 3.4 and the ARQ query engine.
Consider the following triples:

```<code>:lib1  :makes   "Butter"
:lib2  :makes   "Bread"
</code>```

It is straightforward to ask for the :makes property of lib1 and lib2 in a variety of ways, and a literal String is returned.  OK, great.
I wish, however, to externally manage a set of other attributes as a hashmap, e.g. (and this is not legal RDF):

```<code>:lib1  :attrs   {a:1, b:"hello", c:false}
</code>```

This is because I want to keep the attrs grouped in the persistor backing the jena runtime and not exploded out into this:

```<code>:lib1  :attrs_a  1
:lib1  :attrs_b  "hello"
:lib1  :attrs_c  false
</code>```

or:

```<code>:lib1  :attrs::a  1
:lib1  :attrs::b  "hello"
:lib1  :attrs::c  false
</code>```

I can certainly do some additional manipulation of the data coming out of the persistor.   A thing that springs to mind is subProperty:

```<code>:attrs   rdf:type   rdf:Property
:a       rdfs:subPropertyOf  :attrs
:b       rdfs:subPropertyOf  :attrs
:c       rdfs:subPropertyOf  :attrs
</code>```

and later

```<code>?resolveSubject ?p ?resolveObject .
?p rdfs:subPropertyOf+ :attrs
</code>```

can be used to dynamically grab all the subProperties.  This works, although it is mildly irritating that the "parent" property attrs is also returned in the query; would like to see that go away without FILTER or some such.

The Question: Are there other best practice / practical tips+tricks around dealing with this sort of grouped, dynamic data?  Or does it quickly boil down to how to turn them into subproperties?

答:
A map like {a:1, b:"hello", c:false} isn't a particular complicated structure, and it's easy to represent in RDF.  It's an object that has three entries, and each entry associates a key with a value.  So, to approximate

```<code>:lib1  :attrs   {a:1, b:"hello", c:false}
</code>```

you can simply do:

```<code>:lib1 :attrs [ :hasEntry [ :key "a"; :value 1 ] ,
                         [ :key "b"; :value "hello" ] ,
                         [ :key "c"; :value false ] ] .
</code>```

Sure, it looks a little more verbose, but you've captured the whole structure of the triples are particularly complicated, especially if you're emitting these programmatically.

These also allow fairly easy query using SPARQL.  E.g., to ask for libraries and their "c" attributes, we can use a query like:

```<code>select ?lib ?value {
  ?lib :attrs/:hasEntry [ :key "c"; :value ?value ]
}
</code>```

Body:
Assume the runtime context here is Apache jena 3.4 and the ARQ query engine.
Consider the following triples:

:lib1  :makes   "Butter"
:lib2  :makes   "Bread"

It is straightforward to ask for the :makes property of lib1 and lib2 in a variety of ways, and a literal String is returned.  OK, great.
I wish, however, to externally manage a set of other attributes as a hashmap, e.g. (and this is not legal RDF):

:lib1  :attrs   {a:1, b:"hello", c:false}

This is because I want to keep the attrs grouped in the persistor backing the jena runtime and not exploded out into this:

:lib1  :attrs_a  1
:lib1  :attrs_b  "hello"
:lib1  :attrs_c  false

or:

:lib1  :attrs::a  1
:lib1  :attrs::b  "hello"
:lib1  :attrs::c  false

I can certainly do some additional manipulation of the data coming out of the persistor.   A thing that springs to mind is subProperty:

:attrs   rdf:type   rdf:Property
:a       rdfs:subPropertyOf  :attrs
:b       rdfs:subPropertyOf  :attrs
:c       rdfs:subPropertyOf  :attrs

and later

?resolveSubject ?p ?resolveObject .
?p rdfs:subPropertyOf+ :attrs

can be used to dynamically grab all the subProperties.  This works, although it is mildly irritating that the "parent" property attrs is also returned in the query; would like to see that go away without FILTER or some such.

The Question: Are there other best practice / practical tips+tricks around dealing with this sort of grouped, dynamic data?  Or does it quickly boil down to how to turn them into subproperties?

Body:
A map like {a:1, b:"hello", c:false} isn't a particular complicated structure, and it's easy to represent in RDF.  It's an object that has three entries, and each entry associates a key with a value.  So, to approximate

:lib1  :attrs   {a:1, b:"hello", c:false}

you can simply do:

:lib1 :attrs [ :hasEntry [ :key "a"; :value 1 ] ,
                         [ :key "b"; :value "hello" ] ,
                         [ :key "c"; :value false ] ] .

Sure, it looks a little more verbose, but you've captured the whole structure of the triples are particularly complicated, especially if you're emitting these programmatically.

These also allow fairly easy query using SPARQL.  E.g., to ask for libraries and their "c" attributes, we can use a query like:

select ?lib ?value {
  ?lib :attrs/:hasEntry [ :key "c"; :value ?value ]
}


问:
Listing all cycles in a really large directed graph
I want to ask whether it is possible to list all cycle in a really large directed graph. The size of the graph is around 600 node and around 7000 edges.

I have tried naive dfs algorithm and multi threaded it using python process. I set it to use 10 processes. The problem is, I still can not finish the program. It takes too long. I noticed that it listed many duplicates cycles. For example, I found a cycle consists of 200 nodes. It means it computes same cycle 200*200 times! I believe it is useless because it is all the same cycle.

I have tried Johnson algorithm but my 64GB RAM can not handle it. It said it runs out of memory.

Other things that I have done is to list whether a cycle exixts between 2 nodes.

I detect if node A can reach node C and node C can reach node A, it means there is at least a cycle that involves A and C. This algorithm is quite fast and I can list there are around 600,000 possibilities although I know there are many duplicates too. For example if A can reach B, B can reach C, and C can reach A, it means there is a cycle between A and C and B and C.

What should I do?

答: There would be perfect algorithms for your problem of course, but you could prune some processing by finding a Strongly Connected Component of your graph. There is no chance for a node of a SCC to form a cycle with a node of another SCC. So you can then run your current algorithm for different SCCs separately which could save a lot of processing and traversing.</p>


问:
jQuery animate on previously appended div
I'm trying to animate a div that I previously appended, but the animation doesn't happen, even though the complete function is executed.

Here is a very simple example:

EDIT: I corrected the typo in my jsFiddle and the problem is still there, but thank you for pointing it out.

HTML:

```<code><button id="test">
    Go
</button>
<div class="elements">
</div>
</code>```

JS:

```<code>$('#test').click(function(){
  $("<div class='element-test'><img src='https://image.flaticon.com/icons/png/128/148/148836.png' style='position:absolute; z-index:40; top:400px; left:200px; width:2%;'></div>")
  .appendTo('.elements').animate({top:'100px', left:'400px'}, 500, function(){
      $('.element-test').fadeOut(200);
    });
});
</code>```

I wrote a jsFiddle showing the problem.

In my application, I would need to animate this with % positions, and I thought that was the problem in the beginning. However, changing it to pixel positions or even pure int numbers in the animate parameters doesn't solve it.

At the beginning, I was using .append() and then animate(). The idea of using appendTo().animate() comes from there.

答:
$('#test').click(function(){
  var img = $("

");
  $("body").append(img);
  $('img').animate({
    left: '250px',
    opacity: '0.5',
    top: '+=100px',
    left: '+=400px'
  });
  $('img').fadeOut(200)
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="test">
  Go
</button>

<div class="elements"></div></code>```

Body:
I'm trying to animate a div that I previously appended, but the animation doesn't happen, even though the complete function is executed.

Here is a very simple example:

EDIT: I corrected the typo in my jsFiddle and the problem is still there, but thank you for pointing it out.

HTML:

<button id="test">
    Go
</button>

JS:

$('#test').click(function(){
  $("

")
  .appendTo('.elements').animate({top:'100px', left:'400px'}, 500, function(){
      $('.element-test').fadeOut(200);
    });
});

I wrote a jsFiddle showing the problem.

In my application, I would need to animate this with % positions, and I thought that was the problem in the beginning. However, changing it to pixel positions or even pure int numbers in the animate parameters doesn't solve it.

At the beginning, I was using .append() and then animate(). The idea of using appendTo().animate() comes from there.

Body:
$('#test').click(function(){
  var img = $("<div class='element-test'><img src='https://image.flaticon.com/icons/png/128/148/148836.png' style='height:130px;width:130px;position:absolute;'></div>");
  $("body").append(img);
  $('img').animate({
    left: '250px',
    opacity: '0.5',
    top: '+=100px',
    left: '+=400px'
  });
  $('img').fadeOut(200)
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<button id="test">
  Go
</button>

<div class="elements"></div>


问:
representing JSON policy in Go
I would like to Generate this JSON policy:

```<code>{"Statement":[{"Resource":"RESOURCE","Condition":{"DateLessThan":{"AWS:EpochTime":EXPIRES}}}]}
</code>```

The solution I'm showing below produces the following JSON:

```<code>{"Statement":{"Resource":"example.com","Condition":{"DateLessThan":{"AWS:EpochTime":"1234543"}}}}
</code>```

How do I change this so that "Statement": has an array value?

```<code>package main
import (
        "json"
        "fmt"
)

type S struct {
        Statement Statement
}

type Statement struct {
        Resource  string
        Condition Date
}

type Date struct {
        DateLessThan AWS
}

type AWS struct {
        EpochTime string "AWS:EpochTime"
}

func main() {
        expires := "1234543"
        resource := "example.com"
        date := &AWS{EpochTime: expires}
        date2 := &Date{DateLessThan:*date}
        reso := &Statement{Resource: resource, Condition: *date2}
        statement := &S{Statement: *reso}
        result1, _ := json.Marshal(statement)
        fmt.Printf(result1)
}
</code>```

答:
Apply the following changes:

```<code>type S struct {
    Statement []Statement
}
...
    s_array := []Statement{*reso}
    statement := &S{Statement: s_array}
</code>```

Hopefully that should make it clear: you want a slice of Statement objects, rather than just a single Statement.

Title: representing JSON policy in Go

Body:
I would like to Generate this JSON policy:

{"Statement":[{"Resource":"RESOURCE","Condition":{"DateLessThan":{"AWS:EpochTime":EXPIRES}}}]}

The solution I'm showing below produces the following JSON:

{"Statement":{"Resource":"example.com","Condition":{"DateLessThan":{"AWS:EpochTime":"1234543"}}}}

How do I change this so that "Statement": has an array value?

package main
import (
        "json"
        "fmt"
)

type S struct {
        Statement Statement
}

type Statement struct {
        Resource  string
        Condition Date
}

type Date struct {
        DateLessThan AWS
}

type AWS struct {
        EpochTime string "AWS:EpochTime"
}

func main() {
        expires := "1234543"
        resource := "example.com"
        date := &AWS{EpochTime: expires}
        date2 := &Date{DateLessThan:*date}
        reso := &Statement{Resource: resource, Condition: *date2}
        statement := &S{Statement: *reso}
        result1, _ := json.Marshal(statement)
        fmt.Printf(result1)
}

Body:
Apply the following changes:

type S struct {
    Statement []Statement
}
...
    s_array := []Statement{*reso}
    statement := &S{Statement: s_array}

Hopefully that should make it clear: you want a slice of Statement objects, rather than just a single Statement.


问:
CSS image zoom effect breaking thumbnail footer
Im creating a new project where Im using zoom effect with css 3 but in  thumb section at the bottom I have video stats which is moving to the top on mouse hover.

Do you know how to keep the video-stats fixed?

DEMO: https://jsfiddle.net/gazi/dbLcq3cj/

css:

```<code>.video-item {width: 24.6%;display:inline-block;display: -moz-inline-stack;vertical-align: top;zoom: 1;*display: inline;margin-bottom: 10px;padding: 0 5px;}
.video-item {display:inline-block;display: -moz-inline-stack;vertical-align: top;zoom: 1;*display: inline;margin-bottom: 10px;padding: 0 5px;}
.video-item-thumb {display: block;position: relative;height: 154px;padding: 7px;overflow: hidden;}
.video-item .outline {position: relative;border: 1px solid transparent;overflow: hidden;-webkit-backface-visibility: hidden;}
.video-item-thumb {height: 197px !important;}
.video-item:hover .video-item-thumb {-webkit-backface-visibility: hidden;overflow:hidden;height: 197px;}
.video-item-thumb {display: inline-block;}
.video-item-thumb img{width: 100% !important;}
.video-item:hover .video-item-thumb .wrapper {-webkit-transform: scale(1.6);-ms-transform: scale(1.6);transform: scale(1.6);}

/* Featured */
.video-item.featured {width: 33%;height: 280px;}
.video-item.featured.video-item-thumb {height: 197px;}
.video-item.featured:hover .video-item-thumb {height: 210px;}
.video-item.featured:hover .video-item-thumb .wrapper {-webkit-transform: scale(1.5);-ms-transform: scale(1.6);transform: scale(1.6);}

.outline .video-item-thumb {width: 100%;}
.video-item-title,.featured .video-item-title {padding: 0 5px;height: 22px;}
.video-item-title h2,.featured .video-item-title h2 {font-size: 15px;line-height: 22px;height: 22px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;}
.video-item-footer,.featured .video-item-footer {padding: 10px 5px;}
.video-item-footer .video-stats p,.featured .video-item-footer .video-stats p {font-size: 12px;}
.video-item-footer .video-stats p.stat-rating,.featured .video-item-footer .video-stats p.stat-rating {font-size: 18px;}
.video-item-footer .video-stats p.stat-rating .ico,.featured .video-item-footer .video-stats p.stat-rating .ico {font-size: 15px;}
/* Thumbnail Footer */
.video-item-thumb span.ico,.video-item-thumb span.duration {display: block;position: absolute;-webkit-transition: .3s opacity;transition: .3s opacity;}
.video-item-thumb .wrapper {overflow: hidden;max-width: 100%;max-height: 100%;}
.video-item-thumb:hover span.duration {opacity: 0;}
.video-item-thumb span.ico-play {opacity: 0;width: 38px;height: 38px;right: 18px;bottom: 18px;-webkit-border-radius: 38px;-moz-border-radius: 38px;-ms-border-radius: 38px;border-radius: 38px;text-align: center;font-size: 15px;line-height: 38px;}
.video-item-thumb:hover span.ico-play {opacity: 1;}
.video-item-thumb span.ico-hd {left: 13px;bottom: 13px;font-size: 11px;padding: 10px 6px;-webkit-border-radius: 3px;-moz-border-radius: 3px;-ms-border-radius: 3px;border-radius: 3px;}
.video-item-thumb span.duration {right: 13px;bottom: 13px;padding: 6px;font-size: 10px;line-height: 10px;-webkit-border-radius: 3px;-moz-border-radius: 3px;-ms-border-radius: 3px;border-radius: 3px;}
.video-item-title {display: block;padding: 0 7px;height: 40px;text-decoration: none;}
.video-item-title h2 {font-size: 15px;line-height: 18px;font-weight: 400;margin: 0;max-width: 100%;height: 40px;white-space: normal;overflow: hidden;}
.video-item-footer {padding: 15px 7px 10px 7px;border-top: 1px solid transparent;height: 48px;}
.video-item-footer .video-stats .stat {float: left;width: 33%;border-right: 1px solid transparent;}
.video-item-footer .video-stats .stat:last-child {border-right: 0 none;}
.video-item-footer .video-stats p {margin: 0;font-size: 13px;line-height: 22px;height: 22px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;}
.video-item-footer .video-stats p.stat-views {padding-right: 8px;}
.video-item-footer .video-stats p.stat-when {text-align: center;}
.video-item-footer .video-stats p.stat-rating {font-size: 20px;text-align: right;}
.video-item-footer .video-stats p.stat-rating .ico {font-size: 16px;}
.video-item-thumb span.ico,.video-item-thumb span.duration {background: rgba(25,26,34,0.7);color: #fff;}
.video-item-thumb span.ico-play {text-shadow: 1px 1px 5px rgba(0,0,0,0.75);}
.video-item-title {color: #2b2c33}
.video-item-footer {border-color: #d2d2d2;}
.video-item-footer .video-stats .stat {border-color: #3d3d3d;}
/*E RE*/
.video-item:hover .video-item-title,.video-item.featured:hover .video-item-title {height: 0 !important;padding: 0 !important;}
.video-item.featured .video-item-thumb:after {top: 6px;left: 6px;}
.video-item-thumb .site-wrap {position: absolute;top: 0;left: 0;width: 100%;height: 100%;font-size: 0;text-align: center;vertical-align: middle;background-color: rgba(0,0,0,0.3);-moz-opacity: 0;opacity: 0;filter: alpha(opacity=0);}
.video-item-thumb .site-wrap:before {content: '';display: inline-block;height: 100%;vertical-align: middle;}
.video-item-thumb .site-wrap .site-info {display: inline-block;vertical-align: middle;width: 99%;}
.video-item-thumb .site-info .btn-play {display: block;position: relative;margin: 0 auto;width: 36px;height: 36px;-webkit-border-radius: 36px;-moz-border-radius: 36px;-ms-border-radius: 36px;border-radius: 36px;}
.video-item-thumb .site-info .btn-play:before {content: '';display: block;position: absolute;top: 50%;left: 50%;margin-top: -7px;margin-left: -5px;border-left: 10px solid #fff;border-top: 7px solid transparent;border-bottom: 7px solid transparent;}
.video-item-thumb .site-info .site-logo {display: block;margin-top: 10px;width: 100%;height: 64px;background-repeat: no-repeat;background-color: transparent;}
/*ZOOM on HOVER */
.video-item-thumb:before {content: '';display: block;position: absolute;top: 0;left: 0;width: 100%;height: 100%;z-index: 1;}
.video-item-thumb,.video-item-thumb:before,.video-item-thumb .wrapper,.video-item-thumb .site-wrap,.video-item .video-item-title {transition: all 0.3s;}
.video-item .video-item-title {overflow: hidden;}
.video-item:hover .video-item-thumb .wrapper {-webkit-transform: scale(1.35);-ms-transform: scale(1.35);transform: scale(1.35);}
</code>```

I tried with position: absolute and relative but I didnt have luck

答:
The problem is you are setting:

```<code>.video-item:hover .video-item-title, .video-item.featured:hover .video-item-title {
    height: 0 !important;
    padding: 0 !important;
}
</code>```

So on hover you are setting the height of the title to 0. Try do delete that line from your code if this is not you intention.

Edit:

If I got you right you only want to hide the title but keep everything where it is. To achieve this dothe following:

Set a transition to the title:

```<code>.video-item-title h2, .featured .video-item-title h2 {
    transition: all 0.3s;
}
</code>```

and remove:

```<code>.video-item:hover .video-item-title, .video-item.featured:hover .video-item-title {
    height: 0 !important;
    padding: 0 !important;
}
</code>```

instead use:

```<code>.video-item:hover .video-item-title h2, .video-item.featured:hover .video-item-title h2{
    height: 0 !important;
    padding: 0 !important;
}
</code>```

So you only scale down the h2 itself not the whole container.

Body:
Im creating a new project where Im using zoom effect with css 3 but in  thumb section at the bottom I have video stats which is moving to the top on mouse hover.

Do you know how to keep the video-stats fixed?

DEMO: https://jsfiddle.net/gazi/dbLcq3cj/

css:

.video-item {width: 24.6%;display:inline-block;display: -moz-inline-stack;vertical-align: top;zoom: 1;*display: inline;margin-bottom: 10px;padding: 0 5px;}
.video-item {display:inline-block;display: -moz-inline-stack;vertical-align: top;zoom: 1;*display: inline;margin-bottom: 10px;padding: 0 5px;}
.video-item-thumb {display: block;position: relative;height: 154px;padding: 7px;overflow: hidden;}
.video-item .outline {position: relative;border: 1px solid transparent;overflow: hidden;-webkit-backface-visibility: hidden;}
.video-item-thumb {height: 197px !important;}
.video-item:hover .video-item-thumb {-webkit-backface-visibility: hidden;overflow:hidden;height: 197px;}
.video-item-thumb {display: inline-block;}
.video-item-thumb img{width: 100% !important;}
.video-item:hover .video-item-thumb .wrapper {-webkit-transform: scale(1.6);-ms-transform: scale(1.6);transform: scale(1.6);}

/* Featured */
.video-item.featured {width: 33%;height: 280px;}
.video-item.featured.video-item-thumb {height: 197px;}
.video-item.featured:hover .video-item-thumb {height: 210px;}
.video-item.featured:hover .video-item-thumb .wrapper {-webkit-transform: scale(1.5);-ms-transform: scale(1.6);transform: scale(1.6);}

.outline .video-item-thumb {width: 100%;}
.video-item-title,.featured .video-item-title {padding: 0 5px;height: 22px;}
.video-item-title h2,.featured .video-item-title h2 {font-size: 15px;line-height: 22px;height: 22px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;}
.video-item-footer,.featured .video-item-footer {padding: 10px 5px;}
.video-item-footer .video-stats p,.featured .video-item-footer .video-stats p {font-size: 12px;}
.video-item-footer .video-stats p.stat-rating,.featured .video-item-footer .video-stats p.stat-rating {font-size: 18px;}
.video-item-footer .video-stats p.stat-rating .ico,.featured .video-item-footer .video-stats p.stat-rating .ico {font-size: 15px;}
/* Thumbnail Footer */
.video-item-thumb span.ico,.video-item-thumb span.duration {display: block;position: absolute;-webkit-transition: .3s opacity;transition: .3s opacity;}
.video-item-thumb .wrapper {overflow: hidden;max-width: 100%;max-height: 100%;}
.video-item-thumb:hover span.duration {opacity: 0;}
.video-item-thumb span.ico-play {opacity: 0;width: 38px;height: 38px;right: 18px;bottom: 18px;-webkit-border-radius: 38px;-moz-border-radius: 38px;-ms-border-radius: 38px;border-radius: 38px;text-align: center;font-size: 15px;line-height: 38px;}
.video-item-thumb:hover span.ico-play {opacity: 1;}
.video-item-thumb span.ico-hd {left: 13px;bottom: 13px;font-size: 11px;padding: 10px 6px;-webkit-border-radius: 3px;-moz-border-radius: 3px;-ms-border-radius: 3px;border-radius: 3px;}
.video-item-thumb span.duration {right: 13px;bottom: 13px;padding: 6px;font-size: 10px;line-height: 10px;-webkit-border-radius: 3px;-moz-border-radius: 3px;-ms-border-radius: 3px;border-radius: 3px;}
.video-item-title {display: block;padding: 0 7px;height: 40px;text-decoration: none;}
.video-item-title h2 {font-size: 15px;line-height: 18px;font-weight: 400;margin: 0;max-width: 100%;height: 40px;white-space: normal;overflow: hidden;}
.video-item-footer {padding: 15px 7px 10px 7px;border-top: 1px solid transparent;height: 48px;}
.video-item-footer .video-stats .stat {float: left;width: 33%;border-right: 1px solid transparent;}
.video-item-footer .video-stats .stat:last-child {border-right: 0 none;}
.video-item-footer .video-stats p {margin: 0;font-size: 13px;line-height: 22px;height: 22px;white-space: nowrap;text-overflow: ellipsis;overflow: hidden;}
.video-item-footer .video-stats p.stat-views {padding-right: 8px;}
.video-item-footer .video-stats p.stat-when {text-align: center;}
.video-item-footer .video-stats p.stat-rating {font-size: 20px;text-align: right;}
.video-item-footer .video-stats p.stat-rating .ico {font-size: 16px;}
.video-item-thumb span.ico,.video-item-thumb span.duration {background: rgba(25,26,34,0.7);color: #fff;}
.video-item-thumb span.ico-play {text-shadow: 1px 1px 5px rgba(0,0,0,0.75);}
.video-item-title {color: #2b2c33}
.video-item-footer {border-color: #d2d2d2;}
.video-item-footer .video-stats .stat {border-color: #3d3d3d;}
/*E RE*/
.video-item:hover .video-item-title,.video-item.featured:hover .video-item-title {height: 0 !important;padding: 0 !important;}
.video-item.featured .video-item-thumb:after {top: 6px;left: 6px;}
.video-item-thumb .site-wrap {position: absolute;top: 0;left: 0;width: 100%;height: 100%;font-size: 0;text-align: center;vertical-align: middle;background-color: rgba(0,0,0,0.3);-moz-opacity: 0;opacity: 0;filter: alpha(opacity=0);}
.video-item-thumb .site-wrap:before {content: '';display: inline-block;height: 100%;vertical-align: middle;}
.video-item-thumb .site-wrap .site-info {display: inline-block;vertical-align: middle;width: 99%;}
.video-item-thumb .site-info .btn-play {display: block;position: relative;margin: 0 auto;width: 36px;height: 36px;-webkit-border-radius: 36px;-moz-border-radius: 36px;-ms-border-radius: 36px;border-radius: 36px;}
.video-item-thumb .site-info .btn-play:before {content: '';display: block;position: absolute;top: 50%;left: 50%;margin-top: -7px;margin-left: -5px;border-left: 10px solid #fff;border-top: 7px solid transparent;border-bottom: 7px solid transparent;}
.video-item-thumb .site-info .site-logo {display: block;margin-top: 10px;width: 100%;height: 64px;background-repeat: no-repeat;background-color: transparent;}
/*ZOOM on HOVER */
.video-item-thumb:before {content: '';display: block;position: absolute;top: 0;left: 0;width: 100%;height: 100%;z-index: 1;}
.video-item-thumb,.video-item-thumb:before,.video-item-thumb .wrapper,.video-item-thumb .site-wrap,.video-item .video-item-title {transition: all 0.3s;}
.video-item .video-item-title {overflow: hidden;}
.video-item:hover .video-item-thumb .wrapper {-webkit-transform: scale(1.35);-ms-transform: scale(1.35);transform: scale(1.35);}

I tried with position: absolute and relative but I didnt have luck

Body:
The problem is you are setting:

.video-item:hover .video-item-title, .video-item.featured:hover .video-item-title {
    height: 0 !important;
    padding: 0 !important;
}

So on hover you are setting the height of the title to 0. Try do delete that line from your code if this is not you intention.

Edit:

If I got you right you only want to hide the title but keep everything where it is. To achieve this dothe following:

Set a transition to the title:

.video-item-title h2, .featured .video-item-title h2 {
    transition: all 0.3s;
}

and remove:

.video-item:hover .video-item-title, .video-item.featured:hover .video-item-title {
    height: 0 !important;
    padding: 0 !important;
}

instead use:

.video-item:hover .video-item-title h2, .video-item.featured:hover .video-item-title h2{
    height: 0 !important;
    padding: 0 !important;
}

So you only scale down the h2 itself not the whole container.


问:
PayPal - Multiple billing agreements on one purchase possible?
Sorry, if this topic is too unspecific, but actually I did not know where ask else. If this question is not ok, please feel free to close it.

My question is, if it is possible to execute / approve multiple billing agreements from one user at one purchase at paypal?

We created a shop where the user can buy different virtual products for different periods. If a user buys 2 or more products we want to create for each product a billing agreement (i.e. 12 months). If I understand the paypal API correctly, every product (subscription / billing agreement) has to be approved independently.
Is there a way to let the user approve the billing agreement once for all products at all? Or can we create a billing plan with multiple products in it?

Thanks for your help in advance.

答:
According to PayPal, it is not possible to accomplish this using the latest version of the SDKs. It should be possible, however, to accomplish this using the currently-deprecated SOAP version of SDKs. There are several API calls related to the creation of Billing Agreements, but two calls that are required for basic situations: SetExpressCheckout and CreateRecurringPaymentsProfile. All of the supporting documentation for this calls using the SOAP API clearly state that there is a limit of 10 billing agreements per transaction. For example, this is taken from the documentation from CreateRecurringPaymentsProfile:

RecurringPayments | ProfileDetails

(Required) You can include up to 10 recurring payments profiles
    per request. The order of the profile details must match the order
    of the billing agreement details specified in the SetExpressCheckout
    request.

I am in the process of attempting this with the PHP SDK using Express Checkout specifically and I will provide an update on whether I can in fact get this working.

I apologize that this is not as clear an answer as it should be, but the documentation surrounding this question provided by the developers is directly conflicting and IMO there should be some explanation of that here.


问:
Can't pass parameter to ContentView
I have the next code of ContentView:

```<code>     <StackLayout>
        <StackLayout Orientation="Horizontal">
          <Frame
            HeightRequest="{Binding Height}"
            WidthRequest="{Binding Width}"
            CornerRadius="{Binding Radius}"
            Margin="0"
            Padding="0">
            <Label Text="Some text" />
          </Frame>
        </StackLayout>
    </StackLayout>

    public partial class CicrleView : ContentView
    {
        public int XCoord { get; set; }
        public int YCoord { get; set; }
        public int Radius { get; set; }

        private int width;
        public int Width
        {
            get
            {
                return Radius * 2;
            }
            set
            {
                this.width = value;
            }
        }

        private int height;
        public int Height
        {
            get
            {
                return Radius * 2;
            }
            set
            {
                this.height = value;
            }
        }

        public CicrleView()
        {
            InitializeComponent();
        }
    }
</code>```

When I use CircleView and pass parameter "Radius" <local:CicrleView Radius="50" /> nothing will happen (property Radius will not initialize). How can I resolve this problem and initialize Radius property in CircleView?

答:
The value for Radius is set after the CircleView is instantiated - and because there is no property-change notification - it doesn't get propagated to inner Frame.CornerRadius.

In order to resolve this, either create a bindable property for Radius, or ensure PropertyChanged is invoked.

```<code>public int Radius
{
    get { return _radius; }
    set { _radius = value; OnPropertyChanged(nameof(Radius)); }
}
</code>```

Also, make sure to set the parent host view as binding source.

```<code>CornerRadius="{Binding Radius, Source=_parentHost}
</code>```

and, assign x:Name attribute to root tag in CircleView XAML:

```<code><ContentView .... x:Name="_parentHost" ..
</code>```

Title: Can't pass parameter to ContentView

Body:
I have the next code of ContentView:

     <StackLayout>
        <StackLayout Orientation="Horizontal">
          <Frame
            HeightRequest="{Binding Height}"
            WidthRequest="{Binding Width}"
            CornerRadius="{Binding Radius}"
            Margin="0"
            Padding="0">

          </Frame>
        </StackLayout>
    </StackLayout>

    public partial class CicrleView : ContentView
    {
        public int XCoord { get; set; }
        public int YCoord { get; set; }
        public int Radius { get; set; }

        private int width;
        public int Width
        {
            get
            {
                return Radius * 2;
            }
            set
            {
                this.width = value;
            }
        }

        private int height;
        public int Height
        {
            get
            {
                return Radius * 2;
            }
            set
            {
                this.height = value;
            }
        }

        public CicrleView()
        {
            InitializeComponent();
        }
    }

When I use CircleView and pass parameter "Radius" <local:CicrleView Radius="50" /> nothing will happen (property Radius will not initialize). How can I resolve this problem and initialize Radius property in CircleView?

Body:
The value for Radius is set after the CircleView is instantiated - and because there is no property-change notification - it doesn't get propagated to inner Frame.CornerRadius.

In order to resolve this, either create a bindable property for Radius, or ensure PropertyChanged is invoked.

public int Radius
{
    get { return _radius; }
    set { _radius = value; OnPropertyChanged(nameof(Radius)); }
}

Also, make sure to set the parent host view as binding source.

CornerRadius="{Binding Radius, Source=_parentHost}

and, assign x:Name attribute to root tag in CircleView XAML:

<ContentView .... x:Name="_parentHost" ..


问:
How do I display a random phrase from a list when a button is clicked in a web page?
I am creating a web page where someone can visit it. They type a question in a field and click a button, and a response is passed back to them. (Kind of like a magic 8 ball).

What I'm trying to do is set it up something like this:

http://img585.imageshack.us/img585/997/layoutoi.png

I'm still new to hand-coding things - I have a book on HTML/CSS and one on PHP, which lay still unread, so I'll probably need a step-by-step process. (I have a host and everything, so that's already taken care of.) Thanks in advance!

答:
To do it without a page load (i.e. immediately after the button click), you'll have to do it in Javascript (working jsfiddle example here)

```<code><a id="myButton" href="#">
    click here to get random stuff
</a>

<div id="myRandomDiv">
</div>

<script type="text/javascript" charset="utf-8">
    var randomStrings = [
        "hello 1",
        "hello 2",
        "hello 3",
        "hello 4",
        "hello 5",
    ];

    var randomDiv = document.getElementById("myRandomDiv");

    document.getElementById("myButton").addEventListener("click", function() {
          randomIndex = Math.ceil((Math.random()*randomStrings.length-1));
          newText = randomStrings[randomIndex];
          randomDiv.innerHTML = newText;
    });
</script>
</code>```

To do this instead in PHP (which will require a new page load), you could do this:

```<code><?php

$randomThings = array(
    'random thing 1',
    'random thing 2',
    'random thing 3',
    'random thing 4',
    'random thing 5',
    'random thing 6',
    'random thing 7 ',
);

?>

<!-- REST OF YOUR PAGE -->

<?php

echo $randomThings[mt_rand(0,count($randomThings)-1)];

?>

<!-- OTHER STUFF -->
</code>```

First, we create an array ('list') of random things and store it in the variable $randomThings.

Elements in an array can be accessed using $variableName[$index] -- in this case, the indices will simply be 0,1,2,3,4,5,6.

The reason this one-liner (beginning with 'echo') works is, mt_rand is going to return a random number between 0 and 6, so it'll grab a random element from the $randomThings array.  echo will then spit it to the page.

Body:
To do it without a page load (i.e. immediately after the button click), you'll have to do it in Javascript (working jsfiddle example here)

<a id="myButton" href="#">
    click here to get random stuff
</a>

<div id="myRandomDiv">
</div>

<script type="text/javascript" charset="utf-8">
    var randomStrings = [
        "hello 1",
        "hello 2",
        "hello 3",
        "hello 4",
        "hello 5",
    ];

    var randomDiv = document.getElementById("myRandomDiv");

    document.getElementById("myButton").addEventListener("click", function() {
          randomIndex = Math.ceil((Math.random()*randomStrings.length-1));
          newText = randomStrings[randomIndex];
          randomDiv.innerHTML = newText;
    });
</script>

To do this instead in PHP (which will require a new page load), you could do this:

<?php

$randomThings = array(
    'random thing 1',
    'random thing 2',
    'random thing 3',
    'random thing 4',
    'random thing 5',
    'random thing 6',
    'random thing 7 ',
);

?>

<!-- REST OF YOUR PAGE -->

<?php

echo $randomThings[mt_rand(0,count($randomThings)-1)];

?>

<!-- OTHER STUFF -->

First, we create an array ('list') of random things and store it in the variable $randomThings.

Elements in an array can be accessed using $variableName[$index] -- in this case, the indices will simply be 0,1,2,3,4,5,6.

The reason this one-liner (beginning with 'echo') works is, mt_rand is going to return a random number between 0 and 6, so it'll grab a random element from the $randomThings array.  echo will then spit it to the page.


问:
MySQL - Select row if appear more than x times in other table
Lets say I have two tables, Members and Orders with a 1:N relation:

```<code>Members         | Orders
UserID  Name    | OrderID   UserID  Name
111     Peter   | 777       111     Peter
222     Bart    | 888       333     Joe
333     Joe     | 999       111     Peter
444     Andrew  | 101       444     Andrew
                | 102       111     Peter
                | 103       333     Joe
</code>```

I am trying to get the Members ID from the Members table, in case that Member has more than 1 order in the Orders table.

So the result should be...

```<code>Members
UserID  Name
111     Peter
333     Joe
</code>```

...because Peter and Joe both have at least 2 orders in the Orders table.

I have tried to get a result with:

```<code>SELECT
    s.UserID,
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )
</code>```

But that gives me Peter back 3 times, and Joe 2 times; so I get duplicates instead of each UserID once. How can I get the result without duplicates?

答:
Is it this what your looking for?</p>

```<code>SELECT
    s.UserID,
    s.Name
FROM
    Members s
INNER JOIN
    Orders o ON s.UserID = o.UserID
GROUP BY
    s.UserID
HAVING
    COUNT(*) > 5
</code>```

Body:
Lets say I have two tables, Members and Orders with a 1:N relation:

Members         | Orders
UserID  Name    | OrderID   UserID  Name
111     Peter   | 777       111     Peter
222     Bart    | 888       333     Joe
333     Joe     | 999       111     Peter
444     Andrew  | 101       444     Andrew
                | 102       111     Peter
                | 103       333     Joe

I am trying to get the Members ID from the Members table, in case that Member has more than 1 order in the Orders table.

So the result should be...

Members
UserID  Name
111     Peter
333     Joe

...because Peter and Joe both have at least 2 orders in the Orders table.

I have tried to get a result with:

SELECT
    s.UserID,
FROM Members s
    INNER JOIN Orders o
        ON s.UserID = o.UserID
WHERE
    s.UserID IN
    (
        SELECT UserID
        FROM Orders
        GROUP BY UserID
        HAVING COUNT(*) > 5
    )

But that gives me Peter back 3 times, and Joe 2 times; so I get duplicates instead of each UserID once. How can I get the result without duplicates?

Body:
Is it this what your looking for?

SELECT
    s.UserID,
    s.Name
FROM
    Members s
INNER JOIN
    Orders o ON s.UserID = o.UserID
GROUP BY
    s.UserID
HAVING
    COUNT(*) > 5


问:
how handle fcm notification data without need to click on notification popup in android
i used LocalBroadcastManager and pass data through it in onmessagerecieved()

```<code>  if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        Intent i=new Intent("com.taskty.tasktysupplierapp_FCM_MESSAGE");
        String orderid=remoteMessage.getData().get("orderid");
        String placeOfExecution=remoteMessage.getData().get("placeOfExecution");
        i.putExtra("orderid",orderid);
        i.putExtra("placeOfExecution",placeOfExecution);
        LocalBroadcastManager lbm=LocalBroadcastManager.getInstance(this);
        lbm.sendBroadcast(i);

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            handleNow();
        }
    }
</code>```

and then call it in the launcher activity as

```<code>private BroadcastReceiver mhandler=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        String orderid = intent.getStringExtra("orderid");
        Toast.makeText(context, "order id is :"+orderid, Toast.LENGTH_SHORT).show();

    }
};

@Override
protected void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mhandler);
}

@Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(mhandler,new IntentFilter("com.taskty.tasktysupplierapp_FCM_MESSAGE"));
}
</code>```

and register receiver in onCreate() also before setcontentview()

答:
I found the answer by override the following method it works in all cases whether app in background or foreground and you can get data from intent </p>

```<code>  @override
  onhandleIntetn(Intent intent){}
</code>```

Body:
i used LocalBroadcastManager and pass data through it in onmessagerecieved()

  if (remoteMessage.getData().size() > 0) {
        Log.d(TAG, "Message data payload: " + remoteMessage.getData());

        Intent i=new Intent("com.taskty.tasktysupplierapp_FCM_MESSAGE");
        String orderid=remoteMessage.getData().get("orderid");
        String placeOfExecution=remoteMessage.getData().get("placeOfExecution");
        i.putExtra("orderid",orderid);
        i.putExtra("placeOfExecution",placeOfExecution);
        LocalBroadcastManager lbm=LocalBroadcastManager.getInstance(this);
        lbm.sendBroadcast(i);

        if (/* Check if data needs to be processed by long running job */ true) {
            // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
            scheduleJob();
        } else {
            // Handle message within 10 seconds
            handleNow();
        }
    }

and then call it in the launcher activity as

private BroadcastReceiver mhandler=new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

        String orderid = intent.getStringExtra("orderid");
        Toast.makeText(context, "order id is :"+orderid, Toast.LENGTH_SHORT).show();

    }
};

@Override
protected void onPause() {
    super.onPause();
    LocalBroadcastManager.getInstance(this).unregisterReceiver(mhandler);
}

@Override
protected void onResume() {
    super.onResume();
    LocalBroadcastManager.getInstance(this).registerReceiver(mhandler,new IntentFilter("com.taskty.tasktysupplierapp_FCM_MESSAGE"));
}

and register receiver in onCreate() also before setcontentview()

Body:
I found the answer by override the following method it works in all cases whether app in background or foreground and you can get data from intent

  @override
  onhandleIntetn(Intent intent){}


问:
how to send 2 parameter with datatables CI
My controller:

```<code>function json_survey()
{
    header('Content-Type: application/json');
    $this->load->library('Datatables');
    $this->load->helper('datatables_helper');
    $this->datatables->SELECT('id_survey,judul_survey,status_survey,responden,detail_target,judul_kategori,judul_target');
    $this->datatables->add_column('action',tombol_survey('$1','$2'), 'id_survey,status_survey');
    $this->datatables->FROM('survey');

    return print_r($this->datatables->generate('json',''));
}
</code>```

And my Helper for datatables:

```<code>function tombol_survey($id_survey,$status_survey)
{
    $ci = & get_instance();
    $html = '<span class="actions">';
    If($status_survey=='terbit'){
        $html .= '<a href="' . base_url() . 'subscriber/edit/' . $id_survey . '">Tutup</a>';
    }elseif($status_survey=='tertunda'){
        $html .= '<a href="' . base_url() . 'subscriber/edit/' . $id_survey . '">Tambah</a>';
    }else{
        $html .= 'Tutup | ';
    }
    $html .= '<a href="' . base_url() . 'subscriber/delete/' . $id_survey . '">Lihat | </a>';
    $html .= '<a href="' . base_url() . 'subscriber/delete/' . $id_survey . '">Hapus</a>';
    $html .= '</span>';

    return $html;
}
</code>```

This is json not error, but parameter 2nd ($status_survey) not included, so function if always return false.

答:
```<code>function tombol_survey($ids)
    {
        $ci = & get_instance();
        if(!empty($ids)){
            $html = '<span class="actions">';
            if($ids['status_survey']=='terbit'){
                $html .= '<a href="' . base_url() . 'survey/edit/'.$ids['id_survey'].'">Tutup2</a>';
            }else if($ids['status_survey']=='tertunda'){
                $html .= '<a href="' . base_url() . 'pertanyaan/tambah/'.$ids['id_survey'].'">Tambah</a>';
            }else{
                $html .= 'Tutup | ';
            }
            $html .= '<a href="' . base_url() . 'pertanyaan/tambah/' .$ids['id_survey']. '">Tambah</a>';
            $html .= '<a href="' . base_url() . 'pertanyaan/tambah/' .($ids['status_survey']) ? ($ids['status_survey']) : ''. '">Tambah</a>';
            $html .= '</span>';

            return $html;
        }
    }
</code>```

i debug, now the param status_survey was included, but function if still return false

Body:
My controller:

function json_survey()
{
    header('Content-Type: application/json');
    $this->load->library('Datatables');
    $this->load->helper('datatables_helper');
    $this->datatables->SELECT('id_survey,judul_survey,status_survey,responden,detail_target,judul_kategori,judul_target');
    $this->datatables->add_column('action',tombol_survey('$1','$2'), 'id_survey,status_survey');
    $this->datatables->FROM('survey');

    return print_r($this->datatables->generate('json',''));
}

And my Helper for datatables:

function tombol_survey($id_survey,$status_survey)
{
    $ci = & get_instance();
    $html = '';
    If($status_survey=='terbit'){
        $html .= 'Tutup';
    }elseif($status_survey=='tertunda'){
        $html .= 'Tambah';
    }else{
        $html .= 'Tutup | ';
    }
    $html .= 'Lihat | ';
    $html .= 'Hapus';
    $html .= '';

    return $html;
}

This is json not error, but parameter 2nd ($status_survey) not included, so function if always return false.

Body:
function tombol_survey($ids)
    {
        $ci = & get_instance();
        if(!empty($ids)){
            $html = '<span class="actions">';
            if($ids['status_survey']=='terbit'){
                $html .= '<a href="' . base_url() . 'survey/edit/'.$ids['id_survey'].'">Tutup2</a>';
            }else if($ids['status_survey']=='tertunda'){
                $html .= '<a href="' . base_url() . 'pertanyaan/tambah/'.$ids['id_survey'].'">Tambah</a>';
            }else{
                $html .= 'Tutup | ';
            }
            $html .= '<a href="' . base_url() . 'pertanyaan/tambah/' .$ids['id_survey']. '">Tambah</a>';
            $html .= '<a href="' . base_url() . 'pertanyaan/tambah/' .($ids['status_survey']) ? ($ids['status_survey']) : ''. '">Tambah</a>';
            $html .= '</span>';

            return $html;
        }
    }

i debug, now the param status_survey was included, but function if still return false


问:
Try to sort a List of Object in C#
I'm trying to sort a c # object list, the object is composed like this: an int num and a string alphabet.
I wish a list like that :

```<code> - element 1 : num : 2 alphabet : A
 - element 2 : num : 1 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B
</code>```

become like that :

```<code> - element 1 : num : 1 alphabet : A
 - element 2 : num : 2 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B
</code>```

I already did that :

```<code>myList.Sort(MyObject p1, MyObject p2) {
  p1.num;
  p2.Type;
  //code but i don't know what
});
</code>```

Does anyone know how to do it? thank you very much

答:
As apparently lexicographic sorting is desired, the list can be sorted using the Linq extension methods OrderBy and ThenBy (which are documented here) as follows.

```<code>myList = MyList.OrderBy(x => x.alphabet).ThenBy(x => x.num).ToList();
</code>```

Title: Try to sort a List of Object in C#

Body:
I'm trying to sort a c # object list, the object is composed like this: an int num and a string alphabet.
I wish a list like that :

 - element 1 : num : 2 alphabet : A
 - element 2 : num : 1 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B

become like that :

 - element 1 : num : 1 alphabet : A
 - element 2 : num : 2 alphabet : A
 - element 3 : num : 1 alphabet : B
 - element 4 : num : 2 alphabet : B
 - element 5 : num : 2 alphabet : B

I already did that :

myList.Sort(MyObject p1, MyObject p2) {
  p1.num;
  p2.Type;
  //code but i don't know what
});

Does anyone know how to do it? thank you very much

Body:
As apparently lexicographic sorting is desired, the list can be sorted using the Linq extension methods OrderBy and ThenBy (which are documented here) as follows.

myList = MyList.OrderBy(x => x.alphabet).ThenBy(x => x.num).ToList();


问:
Sort a dictionary by a custom order
This refers to

Sort a list by a custom order

I will go for a similar example... I have a dictionary containing users

```<code>public class UserInfo
{
    public string Name { get; set; }

    public string Location { get; set; }
}
</code>```

the data:

```<code>private Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>(); // id + user
</code>```

and a list of possible locations

```<code>        private string[] locations = {
            "europe",
            "america",
            "asia",
            "africa"
        };
</code>```

how can I order this dictionary by these locations?

There should be the output

// ... all europeans

// ... all americans

// ... all asians

// ... all africans

when calling

```<code>    Dictionary<string, UserInfo> sortedUsers = ; // Sorting the dict "users" by locations

    foreach (KeyValuePair<string, UserInfo> info in sortedUsers)
    {
        Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
    }
</code>```

答:
You could at first build a sorted list by using IComparer and then create a dictionary from it:</p>

```<code>    void Main()
    {
        var d = GetDictionary();
    }

    Dictionary<string,UserInfo> GetDictionary()
    {
        var l = new List<UserInfo>() {
            new UserInfo("One", "There"),
            new UserInfo("Two", "SomewhereB"),
            new UserInfo("Three", "SomewhereA"),
            new UserInfo("Four", "Here")
        };
        var comp = new UserInfoComparer();
        l.Sort(comp);
        return  l.ToDictionary( e => e.Name);
    }

    public class UserInfo
    {
        public string Name { get; set; }
        public string Location { get; set; }
        public UserInfo(string name, string location)
        {
            Name = name;
            Location = location;
        }
    }
    public class UserInfoComparer: IComparer<UserInfo>{
        public int Compare(UserInfo x, UserInfo y)
        {
            var r = x.Location.CompareTo(y.Location);
            if (r == 0)
            {
                r = x.Name.CompareTo(y.Name);
            }
            return r;
        }
    }
</code>```

Title: Sort a dictionary by a custom order

Body:
This refers to

Sort a list by a custom order

I will go for a similar example... I have a dictionary containing users

public class UserInfo
{
    public string Name { get; set; }

    public string Location { get; set; }
}

the data:

private Dictionary<string, UserInfo> users = new Dictionary<string, UserInfo>(); // id + user

and a list of possible locations

        private string[] locations = {
            "europe",
            "america",
            "asia",
            "africa"
        };

how can I order this dictionary by these locations?

There should be the output

// ... all europeans

// ... all americans

// ... all asians

// ... all africans

when calling

    Dictionary<string, UserInfo> sortedUsers = ; // Sorting the dict "users" by locations

    foreach (KeyValuePair<string, UserInfo> info in sortedUsers)
    {
        Console.WriteLine("L: " + info.Value.Location + " N: " + info.Value.Name);
    }

Body:
You could at first build a sorted list by using IComparer and then create a dictionary from it:

    void Main()
    {
        var d = GetDictionary();
    }

    Dictionary<string,UserInfo> GetDictionary()
    {
        var l = new List<UserInfo>() {
            new UserInfo("One", "There"),
            new UserInfo("Two", "SomewhereB"),
            new UserInfo("Three", "SomewhereA"),
            new UserInfo("Four", "Here")
        };
        var comp = new UserInfoComparer();
        l.Sort(comp);
        return  l.ToDictionary( e => e.Name);
    }

    public class UserInfo
    {
        public string Name { get; set; }
        public string Location { get; set; }
        public UserInfo(string name, string location)
        {
            Name = name;
            Location = location;
        }
    }
    public class UserInfoComparer: IComparer<UserInfo>{
        public int Compare(UserInfo x, UserInfo y)
        {
            var r = x.Location.CompareTo(y.Location);
            if (r == 0)
            {
                r = x.Name.CompareTo(y.Name);
            }
            return r;
        }
    }


问:
Framework recommendation needed on .NET or JAVA for Volunteer computing (internet nodes)
I want client machines on internet who subscribe to my server to donate their idle cpu cycles.(Like SETI@Home)

They would take jobs(work-units) from server to process, and send back results to the server. (This is the most simple description). The framework i need should allow me to define a job/task. Rest of things like communication, job execution/tracking, client binaries update etc. should be managed by framework.

I evaluated Alchemi.NET a bit, but its not actively maintained, seems half-baked.

BOINC has API in C, but i want a .NET or JAVA framework.

I am looking at Manjrasoft's ANEKA , but it seems to work only for LAN clouds.

There must be some such frameworks available. I need expert recommendations!

答:
My recommendation

Work dist:

Have a receiver of requests, that places messages in a message queue, like rabbit mq

Have a host of workers, listening to the same queue, taking work from it and acking it when done.

When done, send a message on another queue, containing an URI to a known location, such as your network drive. The target is your parsed data.

The receiver listens to these "completed" messages. Fetches the data from the URI.

Done.

RabbitMQ comes with great CLR APIs.

The same reasoning works well with Microsoft Azure and their AbbFabric Queue. A plus is that is scales extremely well.

Hot Versioning

http://topshelf-project.com/

It gives a folder where you can drop binaries, which are then run. It manages versioning of these as well as running them as windows services.

Deployment

You can deploy the binaries with robocopy/xcopy and "net use Q: pwd \server\share", "net delete Q:"

Continuous Integration

Teamcity

After working with MsBuild extensively, I would recommend scripting it with psake and running the build with PowerShell. If you get advanced with PowerShell you also have WinRM available to you from your build scripts, which is really smooth.

Use the git/subversion commit number as the 0.0.0.x, x in the previous version number, and you will have automatic versioning that is "shared" across "Debug"/"Production" builds.

The Azure way

Work dist:

Same as above but with AppFabric Queue instead of RabbitMQ.

Hot Versioning

By swapping "Staging" and "Production" instances around, you avoid the downtime.

Deployment

You can either tap into the Azure Tools for Visual Studio's MsBuild tasks as can be read about here or you could use the PowerShell AzureSnapIns with a similar setup as above for Continuous Integration.

Continuous Integration

Same as above.


问:
Use Angular Flex-layout breakpoint aliases in my own scss files
I'd like to use the breakpoint aliases defined in Angular Flex-layout in my own scss files and I don't know what to import. I don't see any .scss nor .css files in my /node_modules/@angular/flex-layout folder.

I hope it's possible, so if you could help me with that ;-)

Thanks

答:
If you want to apply style depending on the size of the screen, flex-layout upgrades the default ngClass & ngStyle directives to make them work this way :

```<code><div [ngClass.sm]="{'fxClass-sm': hasStyle}"></div>
</code>```

or

```<code><div [ngStyle.xs]="{'font-size.px': 10, color: 'blue'}"></div>
</code>```

See this page.

Then you can add classes which can be fetched in you scss.

Body:
If you want to apply style depending on the size of the screen, flex-layout upgrades the default ngClass & ngStyle directives to make them work this way :

<div [ngClass.sm]="{'fxClass-sm': hasStyle}"></div>

or

<div [ngStyle.xs]="{'font-size.px': 10, color: 'blue'}"></div>

See this page.

Then you can add classes which can be fetched in you scss.


问:
Executor app finished with state KILLED exitStatus 143
Hello, I am using Hive 2.3.0 with spark version 2.0.2, When i am trying to run Hive commands on Spark from hive console,
The Job is getting stuck and i have to manually kill it.

Following was the error message in Spark worker Log. Could you please advise if i am doing something wrong.

INFO worker.Worker: Executor app-20171114093447-0000/0 finished with state KILLED exitStatus 143

答: I was able to fix it by configuring correct EventLog directory in Spark.</p>


问:
Enter "\\\" in a string in python
How to insert "\\\" in a string in python. It seems to give Error

SyntaxError: EOL while scanning string literal

答:
Yes because \ means break in Python.

\\ equals \but if you use 3 you are breaking something again.

Title: Enter "\\\" in a string in python


问:
logistic regression using statsmodels error in python
I am trying to implement a logistic regression using statsmodels (I need the summary) and I get this error:

```<code>LinAlgError: Singular matrix
</code>```

My df is numeric and correlated, I deleted the non-numeric and constant features.
I tried to implement regular regression as well as one with l1 penalty (l2 isn't available) because of the correlated features.

I tried to check the matrix rank and got this print:

```<code>print(len(df.columns)) -> 156

print(np.linalg.matrix_rank(df.values)) -> 151
</code>```

How do I know which features are a problem and why?

my code:

```<code>logit = sm.Logit(y,X)

result = logit.fit_regularized(trim_mode='auto', alpha=0,maxiter=150)

print(result.summary())
</code>```

Update:

after removing highly correlated features I get:

```<code>  len(df.columns) =  np.linalg.matrix_rank(df.values)
</code>```

but still the same error. (even if I set a low correlation threshold).

I tried to change the solver as well.

答:
As suggested in the comments, if two features are exactly correlated the model won't run. The easiest way to check this if you have a pandas dataframe with a small number of columns is to call the .corr() method on your dataframe - in this case df.corr(), and check if any pair of features have correlation =1.

You should really think about why some features are perfectly correlated though.

Body:
I am trying to implement a logistic regression using statsmodels (I need the summary) and I get this error:

LinAlgError: Singular matrix

My df is numeric and correlated, I deleted the non-numeric and constant features.
I tried to implement regular regression as well as one with l1 penalty (l2 isn't available) because of the correlated features.

I tried to check the matrix rank and got this print:

print(len(df.columns)) -> 156

print(np.linalg.matrix_rank(df.values)) -> 151

How do I know which features are a problem and why?

my code:

logit = sm.Logit(y,X)

result = logit.fit_regularized(trim_mode='auto', alpha=0,maxiter=150)

print(result.summary())

Update:

after removing highly correlated features I get:

  len(df.columns) =  np.linalg.matrix_rank(df.values)

but still the same error. (even if I set a low correlation threshold).

I tried to change the solver as well.


问:
Hive : join 2 tables and select different columns in single query
I have two tables in hive say Table A and Table B. Basically i want to join both of them and want to select the different column based on some condition in single query .

Table A:

```<code>empid;name;sal;dept

1;'X';100;IT

2;'Y';100;IT

3;'Z';100;ADMIN
</code>```

Table B:

```<code>empid;name;address

1;'X';A

2;'Y';B

3;'Z';C
</code>```

Desired output:

```<code>When Dept='IT'
select empid,name,address from Table A join Table B on (A.empid=B.empid)

When Dept='ADMIN'
select empid,address from Table A join Table B on (A.empid=B.empid)
</code>```

Can someone please help me with the approach?

答:
If you are looking for a single query, the output has to be in the same structure.
I assume you don't want to show the name of the ADMIN due to some security reasons.

If so, you could do the below instead. Admin's names will be shown as 'Name not available'. Hope this helps. If not, please tell us the reason behind your question.

```<code>SELECT ta.empid,
       CASE WHEN ta.dept = 'IT' THEN ta.name
            WHEN ta.dept = 'ADMIN' THEN 'Name not available'
       END AS name,
       tb.address
  FROM tableA ta,
       tableB tb
WHERE ta.empid = tb.empid;
</code>```

Body:
I have two tables in hive say Table A and Table B. Basically i want to join both of them and want to select the different column based on some condition in single query .

Table A:

empid;name;sal;dept

1;'X';100;IT

2;'Y';100;IT

3;'Z';100;ADMIN

Table B:

empid;name;address

1;'X';A

2;'Y';B

3;'Z';C

Desired output:

When Dept='IT'
select empid,name,address from Table A join Table B on (A.empid=B.empid)

When Dept='ADMIN'
select empid,address from Table A join Table B on (A.empid=B.empid)

Can someone please help me with the approach?

Body:
If you are looking for a single query, the output has to be in the same structure.
I assume you don't want to show the name of the ADMIN due to some security reasons.

If so, you could do the below instead. Admin's names will be shown as 'Name not available'. Hope this helps. If not, please tell us the reason behind your question.

SELECT ta.empid,
       CASE WHEN ta.dept = 'IT' THEN ta.name
            WHEN ta.dept = 'ADMIN' THEN 'Name not available'
       END AS name,
       tb.address
  FROM tableA ta,
       tableB tb
WHERE ta.empid = tb.empid;


问:
Multiple versions of jQuery in Django admin template
Without specifying anything, the Django 1.2.4 admin templates include jQuery 1.4.2. I just downloaded the jQuery UI framework, which came with 1.4.4. Thus, I would like to use the UI framework with 1.4.4. However, I'm not sure how to remove it from the Django admin templates. What am I supposed to do in this situation?</p>

```<code>class FooAdmin(admin.ModelAdmin):

    class Media:
        # this will cause both jQuery 1.4.2 and 1.4.4 to be included. Not sure if that's a problem or not.
        js = ("js/foo.js", "js/lib/jquery-1.4.4.min.js", "js/lib/jquery-ui-1.8.8.custom.min.js")

admin.site.register(Foo, FooAdmin)
</code>```

答:
You can override _media property from ModelAdmin

Here is _media form actual django code.

```<code>class FooAdmin(admin.ModelAdmin):
    def _media(self):
        from django.conf import settings

        js = ['js/core.js', 'js/admin/RelatedObjectLookups.js',
              'js/jquery.min.js', 'js/jquery.init.js']
        if self.actions is not None:
            js.extend(['js/actions.min.js'])
        if self.prepopulated_fields:
            js.append('js/urlify.js')
            js.append('js/prepopulate.min.js')
        if self.opts.get_ordered_objects():
            js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js'])

        return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js])
    media = property(_media)
</code>```

But maybe there is a better solution

Body:
Without specifying anything, the Django 1.2.4 admin templates include jQuery 1.4.2. I just downloaded the jQuery UI framework, which came with 1.4.4. Thus, I would like to use the UI framework with 1.4.4. However, I'm not sure how to remove it from the Django admin templates. What am I supposed to do in this situation?

class FooAdmin(admin.ModelAdmin):

    class Media:
        # this will cause both jQuery 1.4.2 and 1.4.4 to be included. Not sure if that's a problem or not.
        js = ("js/foo.js", "js/lib/jquery-1.4.4.min.js", "js/lib/jquery-ui-1.8.8.custom.min.js")

admin.site.register(Foo, FooAdmin)

Body:
You can override _media property from ModelAdmin

Here is _media form actual django code.

class FooAdmin(admin.ModelAdmin):
    def _media(self):
        from django.conf import settings

        js = ['js/core.js', 'js/admin/RelatedObjectLookups.js',
              'js/jquery.min.js', 'js/jquery.init.js']
        if self.actions is not None:
            js.extend(['js/actions.min.js'])
        if self.prepopulated_fields:
            js.append('js/urlify.js')
            js.append('js/prepopulate.min.js')
        if self.opts.get_ordered_objects():
            js.extend(['js/getElementsBySelector.js', 'js/dom-drag.js' , 'js/admin/ordering.js'])

        return forms.Media(js=['%s%s' % (settings.ADMIN_MEDIA_PREFIX, url) for url in js])
    media = property(_media)

But maybe there is a better solution


问:
How to declare an ImageView in a class?
I have an InsertStampActivity witch contains 3 EditText and an ImageView received from phone's gallery.
I need to create a class with those 3 editText and the image.

Here is my class:

```<code>public class Timbru {
    private int year;
    private String country;
    private float value;    }
</code>```

I have also implement construtor, getters and setters for each parameter.

My question is how to implement the imageView in my class for further operations?

答:
You could declare your image in your class as a String.

```<code>public class Timbru {
   private int year;
   private String country;
   private float value;
   private String image;
}
</code>```

Then, in your activity, convert the ImageView to a String like this:

```<code>Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.yourImage);
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();

String imageToStoreInYourClass = Base64.encodeToString(image, 0);
</code>```

And then you can also convert from the String to Bitmap back like this:

```<code>byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);
</code>```

Title: How to declare an ImageView in a class?

Body:
I have an InsertStampActivity witch contains 3 EditText and an ImageView received from phone's gallery.
I need to create a class with those 3 editText and the image.

Here is my class:

public class Timbru {
    private int year;
    private String country;
    private float value;    }

I have also implement construtor, getters and setters for each parameter.

My question is how to implement the imageView in my class for further operations?

Body:
You could declare your image in your class as a String.

public class Timbru {
   private int year;
   private String country;
   private float value;
   private String image;
}

Then, in your activity, convert the ImageView to a String like this:

Bitmap bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.yourImage);
ByteArrayOutputStream stream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] image=stream.toByteArray();

String imageToStoreInYourClass = Base64.encodeToString(image, 0);

And then you can also convert from the String to Bitmap back like this:

byte[] decodedString = Base64.decode(encodedImage, Base64.DEFAULT);
Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);


答:
Calculate the total orders for each product

Pair each product with every one else

Join the pair with orders to find which orders have both products

join all together to have COUNT(A&B) and COUNT(A)

SQL DEMO

```<code>WITH products as (
    SELECT [OtherLangDescription], COUNT(*) as orders_total
    FROM Orders
    GROUP BY [OtherLangDescription]
), correlation as (
    SELECT p1.[OtherLangDescription] as p1,
           p1.orders_total as total1,
           p2.[OtherLangDescription] as p2,
           p2.orders_total as total2
    FROM products p1
    CROSS JOIN products p2
), dual_products as (
    SELECT p1, p2, COUNT (o1.OrderID) as pair_orders_total
    FROM correlation c
    JOIN orders o1
      ON c.p1 = o1.[OtherLangDescription]
    JOIN orders o2
      ON c.p2 = o2.[OtherLangDescription]
     AND o1.orderID = o2.orderID
    GROUP BY p1, p2
)
SELECT c.*,
       d.pair_orders_total,
       d.pair_orders_total * 1.0 / c.total1 as correlation
FROM correlation c
JOIN dual_products d
  ON c.p1 = d.p1
 AND c.p2 = d.p2
</code>```

If you save the previous result as table Result the pivot is like this:

SQL DEMO

```<code>DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT ',' + QUOTENAME(p2)
            FROM Results c
            GROUP BY p2
            ORDER BY p2
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT p1, ' + @cols + ' from
            (
                select p1
                    , p2
                    , correlation
                from Results
           ) x
            pivot
            (
                 max(correlation)
                for p2 in (' + @cols + ')
            ) p
            ORDER BY p1'

execute(@query);
</code>```

OUTPUT

Title: Calculating the Count of every pair product for every Order Divided by the number of every product and insert the result in correlation table

Body:
Hello Every one I have a historical data-set of sales and i want to create a query which calculate the correlation between the products by calculating the number of orders which has every pair products and then dividing this number over the number of all orders which Has one of this pair, As Ex ( If i want to calculate the correlation between Product "A" and Product "B" then i will count all orders which has "A" & "B" in the same order and then dividing this count over the orders which has Product "A" only [this will differ if i want to get the correlation between "B" & "A"]).
and i want to store this result in a table of correlation As Shown in the Flowing image

and this is a sample of 300 Row from my data

structure(list(ï..OrderId = c(137413L, 137413L, 137413L, 137413L,
137413L, 137413L, 137413L, 137413L, 137413L, 137413L, 137413L,
137413L, 136729L, 136729L, 136729L, 136729L, 136729L, 136729L,
136729L, 136729L, 136729L, 136729L, 136729L, 136729L, 136729L,
137260L, 137260L, 137260L, 137260L, 137260L, 137260L, 137260L,
137260L, 137260L, 137260L, 137429L, 137429L, 137429L, 137429L,
137429L, 137429L, 137429L, 137429L, 137429L, 137902L, 137902L,
137902L, 137902L, 137902L, 137902L, 137902L, 137974L, 137974L,
138837L, 138837L, 138837L, 138837L, 138837L, 138837L, 139424L,
139424L, 139424L, 139424L, 139424L, 139424L, 139424L, 139424L,
139424L, 139642L, 139642L, 139642L, 139642L, 139642L, 139642L,
139642L, 140676L, 140676L, 140676L, 140676L, 140676L, 140676L,
140938L, 140938L, 140938L, 140938L, 140938L, 140938L, 140938L,
140938L, 140938L, 140938L, 141302L, 141302L, 141302L, 141302L,
141302L, 141302L, 137302L, 137302L, 137302L, 137302L, 138297L,
138297L, 138297L, 138297L, 138297L, 138297L, 138297L, 138297L,
138297L, 138297L, 138297L, 138297L, 138297L, 134444L, 134444L,
134444L, 141134L, 141134L, 141134L, 141134L, 134468L, 134468L,
131965L, 131965L, 131965L, 131965L, 131965L, 131965L, 131965L,
131965L, 131965L, 135722L, 135722L, 135722L, 135722L, 135722L,
135722L, 135722L, 135722L, 135722L, 135722L, 135722L, 135722L,
135722L, 135722L, 139444L, 139444L, 139444L, 139444L, 139444L,
139444L, 131866L, 131866L, 131866L, 131866L, 131866L, 131866L,
131866L, 136078L, 136078L, 136078L, 136078L, 136078L, 136078L,
136078L, 136078L, 136078L, 136078L, 136078L, 136078L, 136078L,
137419L, 137419L, 137419L, 137419L, 137419L, 137419L, 137419L,
137419L, 137419L, 137419L, 137419L, 137419L, 139214L, 139214L,
139214L, 139214L, 139214L, 139214L, 131997L, 131997L, 131997L,
131997L, 139482L, 139482L, 139482L, 139482L, 139482L, 139482L,
139482L, 136066L, 136066L, 136066L, 136066L, 136066L, 136066L,
136066L, 136610L, 136610L, 136610L, 136610L, 136610L, 137352L,
137352L, 137352L, 137352L, 137352L, 137352L, 137352L, 137352L,
133358L, 133358L, 133358L, 134522L, 134522L, 134522L, 134522L,
134522L, 134522L, 134522L, 134522L, 131481L, 131481L, 131481L,
131918L, 131918L, 131918L, 131918L, 135758L, 135758L, 135758L,
135758L, 135678L, 135678L, 135678L, 135678L, 135678L, 135678L,
135678L, 135678L, 135678L, 131986L, 131986L, 131986L, 131986L,
131986L, 131986L, 131986L, 139468L, 139468L, 139468L, 139468L,
139468L, 139468L, 139468L, 139468L, 139468L, 139468L, 139533L,
139533L, 139533L, 139533L, 139533L, 139533L, 139533L, 139533L,
139533L, 131950L, 137540L, 137540L, 137540L, 137540L, 137540L,
137540L, 137540L, 138021L, 138021L, 138021L, 138021L, 138021L,
138021L, 138021L, 138021L, 138021L, 134490L, 134490L, 134490L,
134490L, 134490L), Items = structure(c(29L, 27L, 79L, 35L, 50L,
77L, 32L, 80L, 24L, 60L, 20L, 44L, 46L, 47L, 27L, 68L, 14L, 35L,
22L, 77L, 15L, 73L, 80L, 60L, 42L, 29L, 27L, 68L, 51L, 10L, 35L,
22L, 73L, 62L, 60L, 27L, 51L, 10L, 37L, 35L, 22L, 62L, 80L, 60L,
47L, 68L, 51L, 10L, 22L, 77L, 73L, 51L, 10L, 18L, 47L, 73L, 24L,
60L, 20L, 18L, 29L, 47L, 17L, 35L, 77L, 11L, 73L, 78L, 46L, 18L,
29L, 9L, 17L, 35L, 73L, 46L, 18L, 9L, 17L, 35L, 73L, 18L, 29L,
27L, 22L, 50L, 19L, 73L, 13L, 1L, 7L, 46L, 8L, 80L, 24L, 60L,
61L, 48L, 64L, 10L, 6L, 29L, 47L, 27L, 28L, 10L, 22L, 15L, 73L,
62L, 24L, 60L, 20L, 58L, 66L, 67L, 43L, 38L, 36L, 74L, 70L, 74L,
37L, 74L, 37L, 22L, 77L, 34L, 15L, 73L, 62L, 67L, 46L, 53L, 63L,
57L, 74L, 48L, 27L, 17L, 14L, 15L, 73L, 12L, 67L, 43L, 18L, 29L,
14L, 35L, 32L, 73L, 46L, 18L, 52L, 19L, 62L, 71L, 23L, 14L, 35L,
34L, 19L, 73L, 13L, 43L, 39L, 24L, 75L, 20L, 3L, 41L, 29L, 27L,
68L, 64L, 14L, 35L, 11L, 19L, 15L, 73L, 43L, 45L, 65L, 55L, 67L,
61L, 58L, 40L, 57L, 74L, 31L, 73L, 69L, 65L, 30L, 73L, 56L, 49L,
61L, 74L, 19L, 72L, 13L, 43L, 26L, 41L, 46L, 27L, 68L, 60L, 41L,
74L, 27L, 37L, 14L, 73L, 43L, 60L, 41L, 74L, 32L, 67L, 4L, 29L,
59L, 21L, 25L, 76L, 73L, 43L, 57L, 74L, 62L, 74L, 54L, 33L, 2L,
15L, 73L, 62L, 80L, 59L, 21L, 25L, 27L, 14L, 15L, 73L, 43L, 80L,
57L, 31L, 32L, 19L, 15L, 73L, 72L, 46L, 16L, 18L, 29L, 5L, 14L,
35L, 22L, 73L, 61L, 46L, 18L, 29L, 5L, 14L, 35L, 22L, 73L, 61L,
74L, 46L, 18L, 29L, 27L, 73L, 62L, 43L, 68L, 65L, 64L, 10L, 37L,
17L, 11L, 61L, 70L, 59L, 21L, 25L, 76L, 14L), .Label = c(" Green Beans",
"Apricot", "Arugula", "Arugula old", "Autumn Royal Grape", "Avocado",
"Baladi Cabbage", "Baladi Garlic", "Banati Grape", "Barshomi Figs",
"Black Eggplant", "Broccoli", "Cantaloupe", "Capsicum", "Carrot",
"Cauliflower", "Chili Pepper", "Classic Eggplant", "Cooking Potato",
"Coriander", "Coriander old", "Cucumber", "Deluxe Dried Dates",
"Dill", "Dill old", "Dried Dates", "Flame Grape", "Fons Mango",
"frying Potato", "Gala Apple", "Golden Apple", "Golden Onion",
"Granny Apple", "Grape Leaves", "Green pepper", "Guava", "Hot Pepper",
"Imported Peach", "Japanese Plum", "Lebanese Apple", "Local Apple",
"Local Celery ", "Local Cucumber", "Local Eggplant", "Local Hot Pepper",
"Local Lemon", "Local Pear", "Melon", "Mint", "Molokhia", "Momtaza Owais Mango",
"Morket Tangerine", "Mushroom (200G) old", "Nectarine Peach",
"Nems Watermelon (KG)", "Okra", "Orange For Juice", "Owais Mango",
"Parsle old", "Parsley", "Red Globe Grape", "Red Onion", "Red Radish old",
"Sadeeka Mango", "Sokkary Mango", "Strawberry", "Sugary Peach",
"Superior Grape", "Sweet Potato", "Syrian plum", "Tamr hendi",
"Taro", "Tomato", "Watermelon ( per KG)", "White Cabbage", "White Cabbage Old",
"White Eggplant ", "Zaghlol Dates", "Zebdaya Mango", "Zucchini"
), class = "factor")), .Names = c("ï..OrderId", "Items"), class = "data.frame", row.names = c(NA,
-300L))

Body:
Calculate the total orders for each product

Pair each product with every one else

Join the pair with orders to find which orders have both products

join all together to have COUNT(A&B) and COUNT(A)

SQL DEMO

WITH products as (
    SELECT [OtherLangDescription], COUNT(*) as orders_total
    FROM Orders
    GROUP BY [OtherLangDescription]
), correlation as (
    SELECT p1.[OtherLangDescription] as p1,
           p1.orders_total as total1,
           p2.[OtherLangDescription] as p2,
           p2.orders_total as total2
    FROM products p1
    CROSS JOIN products p2
), dual_products as (
    SELECT p1, p2, COUNT (o1.OrderID) as pair_orders_total
    FROM correlation c
    JOIN orders o1
      ON c.p1 = o1.[OtherLangDescription]
    JOIN orders o2
      ON c.p2 = o2.[OtherLangDescription]
     AND o1.orderID = o2.orderID
    GROUP BY p1, p2
)
SELECT c.*,
       d.pair_orders_total,
       d.pair_orders_total * 1.0 / c.total1 as correlation
FROM correlation c
JOIN dual_products d
  ON c.p1 = d.p1
 AND c.p2 = d.p2

If you save the previous result as table Result the pivot is like this:

SQL DEMO

DECLARE @cols AS NVARCHAR(MAX),
    @query  AS NVARCHAR(MAX);

SET @cols = STUFF((SELECT ',' + QUOTENAME(p2)
            FROM Results c
            GROUP BY p2
            ORDER BY p2
            FOR XML PATH(''), TYPE
            ).value('.', 'NVARCHAR(MAX)')
        ,1,1,'')

set @query = 'SELECT p1, ' + @cols + ' from
            (
                select p1
                    , p2
                    , correlation
                from Results
           ) x
            pivot
            (
                 max(correlation)
                for p2 in (' + @cols + ')
            ) p
            ORDER BY p1'

execute(@query);

OUTPUT