text:
Q: How to access different element of each node in the linked-list I Have a linked-list of n nodes and each nodes holds more than one element. I am trying to write a method that allows me to search for a node and another method that allows me to search for an element inside the node. I cant figure out how am I suppose to access the inside elements of the nodes of linked list. So I guess what I really want to know is that how do you refer/access each individual element with a node of a linked-list?
Trying to create a program that allows the creation of a linked-list where the number of nodes within that linked-list is user dependent. The list should allow searching for nodes and elements and should also be sorted.
    package nodelist;

    public class NodeList {

public int nodeid;
public int nodestate;
public int x_cord;
public int y_cord;
public int direction;

public NodeList next;

public NodeList(int nodeid, int nodestate, int x_cord, int y_cord, int direction){
    this.nodeid = nodeid;
    this.nodestate = nodestate;
    this.x_cord = x_cord;
    this.y_cord = y_cord;
    this.direction = direction;
}

public void display(){
    System.out.println("nodeid: "+nodeid + " state: " +nodestate+ " x: " +x_cord+ " y: " +y_cord+ " direction: " +direction);
}

//@Override
public String toString(){
    return String.valueOf(this.nodeid); // Needed to convert int nodeid to string for printing
}

public static void main(String[] args) {
    // TODO code application logic here
    LinkList theLinkedList = new LinkList();

        // Insert Link and add a reference to the book Link added just prior
        // to the field next
        System.out.println("Enter the number of nodes to deploy");
                    int nodecount = 5;
                    int nodeid = 5000;
                    for(int i=0; i<nodecount;i++){
                        theLinkedList.insertFirstLink(nodeid, 0,0,0,0);

                        nodeid++;
                    }
                    /*
        theLinkedList.insertFirstLink("5000", 0,0,0,0);
        theLinkedList.insertFirstLink("5001", 1,1,1,1);
        theLinkedList.insertFirstLink("5002", 2,2,2,2);
        theLinkedList.insertFirstLink("5003", 3,3,3,3);
        */
        theLinkedList.display();

        System.out.println("Value of first in LinkedList " + theLinkedList.firstLink + "\n");

        // Removes the last Link entered

        theLinkedList.removeFirst();

        theLinkedList.display();

        //System.out.println(theLinkedList.find("The Lord of the Rings").bookName + " Was Found");

        //theLinkedList.removeNodeList("A Tale of Two Cities");

        System.out.println("\nA Tale of Two Cities Removed\n");

        theLinkedList.display();

}

    }

    public class LinkList {
// Reference to first Link in list
    // The last Link added to the LinkedList

    public NodeList firstLink;

    LinkList(){

        // Here to show the first Link always starts as null

        firstLink = null;

    }

    // Returns true if LinkList is empty

    public boolean isEmpty(){

        return(firstLink == null);

    }

    public void insertFirstLink(int nodeid, int nodestate, int x_cord, int y_cord, int direction){

        NodeList newLink = new NodeList(nodeid, nodestate, x_cord, y_cord, direction);

        // Connects the firstLink field to the new Link

        newLink.next = firstLink;

        firstLink = newLink;

    }

    public NodeList removeFirst(){

        NodeList linkReference = firstLink;

        if(!isEmpty()){

            // Removes the Link from the List

            firstLink = firstLink.next;

        } else {

            System.out.println("Empty LinkedList");

        }

        return linkReference;

    }

            public NodeList removeNodeList(){

        NodeList linkReference = firstLink;

        if(!isEmpty()){

            // Removes the Link from the List

            firstLink = firstLink.next;

        } else {

            System.out.println("Empty LinkedList");

        }

        return linkReference;

    }

    public void display(){

        NodeList theLink = firstLink;

        // Start at the reference stored in firstLink and
        // keep getting the references stored in next for
        // every Link until next returns null

        while(theLink != null){

            theLink.display();

            System.out.println("Next Link: " + theLink.next);

            theLink = theLink.next;

            System.out.println();

        }
      }
    }

A: You can only do this if you have same number of element in list of a node.
As single node use struct which is declared only once so it's memory has been already decided. So you can't increase the size of node at run-time.
Below i have mentioned C++ code.
struct Node{
int list[5];
Node *node;
}

A: Simply you can do this.
Point temp node to head node and then Iterate temp.
System.out.println(temp.your_element_name);


text:
Q: Finding indices in Python lists efficiently (in comparison to MATLAB) I have got difficulties to find an efficient solution to find indices in Python lists. All the solutions I have tested so far are slower than the 'find' function in MATLAB. I have only just started to use Python (therefore, I am not very experienced).
In MATLAB I would use the following:
a = linspace(0, 1000, 1000); % monotonically increasing vector
b = 1000 * rand(1, 100); % 100 points I want to find in a
for i = 1 : numel(b)
    indices(i) = find(b(i) <= a, 1); % find the first index where b(i) <= a
end

If I use MATLAB's arrayfun() I can speed this process up a little bit.
In Python I tried several possibilities. I used
for i in xrange(0, len(b)):
   tmp = numpy.where(b[i] <= a)
   indices.append(tmp[0][0])

which takes a lot of time, especially if a is quite big.
If b is sorted than I can use
for i in xrange(0, len(b)):
    if(b[curr_idx] <= a[i]):
        indices.append(i)
        curr_idx += 1
    if(curr_idx >= len(b)):
        return indices
        break

This is much quicker than the numpy.where() solution because I only have to search through the list a once, but this is still slower than the MATLAB solution.
Could anyone suggest a better / more efficient solution?
Thanks in advance.

A: Try numpy.searchsorted:
>> a = np.array([0, 1, 2, 3, 4, 5, 6, 7])
>> b = np.array([1, 2, 4, 3, 1, 0, 2, 9])
% sorting b "into" a
>> np.searchsorted(a, b, side='right')-1
array([1, 2, 4, 3, 1, 0, 2, 9])

You might have to apply a little special treatment for values in b, that are outside the range of a - such as the 9 in the above example.
Despite that, this should be faster than any loop-based method.
As an aside:
Similarly, histc in MATLAB will be much faster than the loop.
EDIT:
If you want the get the index where b is closest to a, you should be able to use the same code, simply with a modified a:
>> a_mod = 0.5*(a[:-1] + a[1:]) % take the centers between the elements in a
>> np.searchsorted(a_mod, np.array([0.9, 2.1, 4.2, 2.9, 1.1]), side='right')
array([1, 2, 4, 3, 1])

Note that you can drop the -1 since a_mod has one element less than a.

A: With numpy only for number generation (not for vectorization):
import numpy as np
a = np.linspace(0, 1000, 1000)
b = 1000 * np.random.rand(100)
indices = [next(i for i, ai in enumerate(a) if bi <= ai) for bi in b]

This works if a.max() >= b.max() as in the example, otherwise will raise a StopIteration, and it's still slow (although this one doesn't make every possible comparison like in b(i) <= a).
If you need the indices as an array instead of a list, use np.array(indices) after that. If you need some optimization, you can sort b and keep only one enumerate(a), peeking instead of taking the last element.
You can also try without numpy on pypy:
def igen(a, b):
    iterb = iter(b)
    bi = next(iterb)
    for i, ai in enumerate(a):
        while bi <= ai:
            yield i
            bi = next(iterb)
    i += 1 # Last bi are bigger than all ai
    yield i
    for unused in iterb:
        yield i

from random import random
a = (i * 1000. / 999. for i in xrange(43032500))
b = sorted(random() * 1000 for unused in xrange(3848))
indices = list(igen(a, b))

This one is based on generators using that idea, and b should be sorted. This will return len(a) when bi > ai for all ai.
For testing, I'm using:
setup = """
from random import random

def igen(a, b):
    iterb = iter(b)
    bi = next(iterb)
    for i, ai in enumerate(a):
        while bi <= ai:
            yield i
            bi = next(iterb)
    i += 1 # Last bi are bigger than all ai
    yield i
    for unused in iterb:
        yield i
"""

program = """
a = (i * 1000. / 999. for i in xrange(43032500))
b = sorted(random() * 1000 for unused in xrange(3848))
indices = list(igen(a, b))
"""

# Python 2 and 3 compatibility
import sys
if sys.version_info.major == 3:
    program = program.replace("xrange", "range")

# Time it! =)
from timeit import timeit
print(timeit(program, setup, number=5000))

That means I'm running 5 thousand times that algorithm in each environment. The resulting time is the SUM of all trials (program) duration (not the mean value):

*

*On CPython 3.4.0 result was 11.491293527011294 (seconds)

*On CPython 2.7.6 result was 9.39319992065 (seconds)

*On Pypy 2.2.1 result was 3.31203603745 (seconds)

More specific version messages:

*

*Python 3.4.0 (default, Apr 11 2014, 13:05:11) [GCC 4.8.2] on linux

*Python 2.7.6 (default, Mar 22 2014, 22:59:56) [GCC 4.8.2] on linux2

*Python 2.7.3 (2.2.1+dfsg-1, Nov 28 2013, 05:13:10) [PyPy 2.2.1 with GCC 4.8.2] on linux2

Now the same with the "two ifs" version adapted (code below) had the results:

*

*On CPython 3.4.0 result was 13.03860338096274 (seconds)

*On CPython 2.7.6 result was 10.7371659279 (seconds)

*On Pypy 2.2.1 result was 2.88891601562 (seconds)

Pypy found a way to optimize your version but still have one difference, I've tested this one calculating "a" just once, while my version calculated "a" 5000 times. The code I've run was:
setup = """
from random import random
a = [i * 1000. / 999. for i in xrange(43032500)]
"""

program = """
b = sorted(random() * 1000 for unused in xrange(3848))
curr_idx = 0
indices = []
for i in xrange(len(a)): # Why not for i, ai in enumerate(a)?
    if b[curr_idx] <= a[i]:
        indices.append(i)
        curr_idx += 1
    if curr_idx >= len(b):
        break
"""

# Python 2 and 3 compatibility
import sys
if sys.version_info.major == 3:
    setup = setup.replace("xrange", "range")
    program = program.replace("xrange", "range")

# Time it! =)
from timeit import timeit
print(timeit(program, setup, number=5000))

Another version would just put the a assignment to the program instead of keeping it on the setup, doing so the Pypy time goes to 2102.06863689 (yeah, more than 35 minutes). Storing things on a huge list is really slow. Changing the program beginning to:
a = (i * 1000. / 999. for i in xrange(43032500)) # A generator expression
[...]
for i, ai in enumerate(a):
    if b[curr_idx] <= ai:
    [...]

Brings us back to 3.11599397659 seconds with Pypy. On this version, a is created 5000 times, but never stored on a list. On the other hand, the igen version "hardcoded" outside of the function worked on 3.17516112328 seconds, in which setup just imported random and program was:
a = (i * 1000. / 999. for i in xrange(43032500))
b = sorted(random() * 1000 for unused in xrange(3848))
indices = []
iterb = iter(b)
try:
    bi = next(iterb)
    for i, ai in enumerate(a):
        while bi <= ai:
            indices.append(i)
            bi = next(iterb)
except StopIteration:
    pass
else:
    i += 1 # Last bi are bigger than all ai
    indices.append(i)
    for unused in iterb:
        indices.append(i)

Anyhow, let A = len(a) and B = len(b), so these are O[A + B.log(B)] algorithms (including @sebastian solution with np.searchsorted). On the other hand, calculating bi <= ai for all pairs (bi, ai) is O[b * a], the Matlab solution should be asymptotically slower unless it does some internal optimization to avoid full comparison making each statement completely lazy (but I don't have Matlab to verify =/). As a need for a comparison, I did this on GNU Octave:
start = time;
a = linspace(0, 1000, 43032500);
b = 1000 * rand(1, 3848);
for i = 1 : numel(b)
    indices(i) = find(b(i) <= a, 1);
end
stop = time;

stop - start

That's one time the process Python did 5000 times, using the original code from this question, and it happened in 203.16 seconds (more than 3 minutes).

Oh, but you're cheating! Put that "start = time;" after the assignment to "a"!

Ok, no one said that, but I've just tried such change. As every b(i) <= a is a vector with size 43032500, it doesn't change much: 202.83 seconds.

And Numpy?!

Numpy also have to store the data. Mostly, it doesn't work with generators (hstack and vstack are exceptions). But we can't be sure which is fasterwithout empirical evidence. Let's run this with Numpy 1.8.1:
setup = """
import numpy as np
a = np.linspace(0., 1000., 43032500) # Don't count this time
"""

program = """
b = 1000 * np.random.rand(3848)
indices = np.searchsorted(a, b, side='right') - 1 # From @sebastian solution
indices[b > a[-1]] = len(a) # Big value correction (my improvement)
"""

# Time it! =)
from timeit import timeit
print(timeit(program, setup, number=5000))

*

*On CPython 2.7, 9.81494688988 seconds

*On CPython 3.4, 9.831143222982064 seconds

And that's it. =)

redpajama_set_name: RedPajamaStackExchange


text:
Q: New transactions during a Sybase "dump database" command I have a Sybase 15.5 database which is backed up every night using the DUMP DATABASE command.  The process takes about 30 minutes.
What happens to the transactions that occur within those 30 minutes?  Are they included in the backup or ignored?

A: Transactions during the dump are included, with the exception of any at the very end of the dump in "phase 3".
From the System Administration Guide: Volume 2, Chapter 11: Developing a Backup and Recovery Plan, Making routine database dumps: dump database:

Users can continue to make
  changes to the database while the dump takes place. This makes it
  convenient to back up databases on a regular basis.
dump database executes in three phases. A progress message informs you
  when each phase completes. When the dump is finished, it reflects all
  changes that were made during its execution, except for those initiated
  during phase 3.

All the data and log pages are dumped including those that are updated during the dump. Here is an example output:
Aug  6 16:32:42 2012: Backup Server: 4.188.1.1: Database mydb: 371587246 kilobytes (100%) DUMPED.
Aug  6 16:33:34 2012: Backup Server: 3.43.1.1: Dump phase number 1 completed.
Aug  6 16:33:34 2012: Backup Server: 3.43.1.1: Dump phase number 2 completed.
Aug  6 16:33:34 2012: Backup Server: 3.43.1.1: Dump phase number 3 completed.
Aug  6 16:33:34 2012: Backup Server: 4.188.1.1: Database mydb: 373878392 kilobytes (100%) DUMPED.
Aug  6 16:33:34 2012: Backup Server: 3.42.1.1: DUMP is complete (database mydb).

See also: http://www.sybaseteam.com/dump-database-t-506.html


text:
Q: Need transistor circuit to supply pulse/gnd signals to optical switch I am a digital designer so anything analog is out of my expertise. I need to control an optical 2x2 switch with the following truth table:

The pulse is in the msec range and the driver current is about 200mA.
Link to data sheet shown below:
https://agiltron.com/PDFs/CL%202x2%202-Stage%20Series%20Switch.pdf
I have an FPGA that can control the transistors but not sure how to arrange them?
Any ideas?
Thanks!

A: Given the specs on the switch I'd go for some small integrated H-bridge circuit, like the one used for small stepper motors. They have (by pure chance!) two full bridges and are trivially driven by logic. As a bonus you have usually many nice protections.
In fact probably these switch have coils inside that moves the actual switch assembly around the optical path, so I think the kind of electrical load is the same. Many, many, manufacturers do these things, they are used, for example, in throttle valve control for engines.


text:
Q: Updating float4 declaration from dx9 to dx11 There's a shader which was given which I'm trying to update to be compatible with the newest Unity 5 (presumably dx11).  I don't understand how float4 basic instantiation from dx9 was working.  Can someone help me understand the following syntax and then provide an equivalent dx11 syntax?
I understand that float4 normally uses x,y,z,w or xyz,y as arguments, but what does did a single float argument do?  Did float4(0.01) make {.01,0,0,0} or does float4(.01) make {.01,.01,.01,.01}?
Original code from the shader:
float4 Multiply19 = float4( 0.01 ) * float4( 0 );

A: It should make a new float4 with all members (xyzw) set to 0.01 and then multiply all that by 0, effectively making Multiply19 a (0, 0, 0, 0) float4.


text:
Q: How do I resolve this syntax error caused by .? The error message I am getting is:

Syntax Error: Token '.' is unexpected, expecting [}] at column 23 of the expression [] starting at [{4}].

The offending html that is causing the issue.

             {[{ data }]}

             <button type="button" class="btn btn-default" ng-click="$ctrl.open({[{ record.KeyNum }]})">Open me!</button>

               <button>Edit</button> <button>Delete</button>

The open function in angularjs:
 angular.module('KeyManager').controller("KeyController",  function( httpFactory, $uibModal) {
  $ctrl = this;
  $ctrl.open = function () {
  var modalInstance = $uibModal.open({
    animation: true,
    ariaLabelledBy: 'modal-title',
    ariaDescribedBy: 'modal-body',
    templateUrl: 'RecordViewer.html',
    controller: 'RecordViewerInstanceCtrl',
    controllerAs: '$ctrl',
    size: "lg",
    resolve: {
      items: function (keyNum) {
          httpFactory.getRecord(keyNum).then(
              function(response) {
                  $ctrl.items = response.data[0];
              },
              function(response) {
                  console.log(response);
                  $ctrl.items = [];
              }
          );
        return $ctrl.items;
      }
    }
  });
});

Also, note that I am doing this in a twig file so start and and end symbols have been changed to "{[{" and "}]}" respectively.
Added Information:
I have tried switching the ng-click directive to
 "$ctrl.open(record.KeyNum)"

but this only prints out the literal string record.KeyNum which is explain here so @smarx comment is the answer.

A: I think you just want $ctrl.open(record.KeyNum).


text:
Q: Tutorial section for Stack Overflow
Possible Duplicate:
Moving a personal technical blog to stackoverflow / serverfault

Many (most?) of the questions I've seen on Stack Overflow are specific to a narrowly-defined problem set, e.g., how-do-I-do-this, what-does-this-error-mean, etc.
Occasionally, a question comes along that is a little bit bigger in scope, such as how do I implement a simple client/server application using sockets or how do I create a Windows service.  Every now and again, I've taken the time to provide a detailed instruction set (see answer to "Easiest language to create a Windows service in") for questions like these.  And when I notice new questions that refer to the same or similar problem, I usually provide a link to the answer I've already given.
Would it be useful to the Stack Overflow community to have a tutorial section under one's profile that allows Stack Overflow participants to provide such tutorials without having to have a question asked?  In my mind, I'm envisioning something like The Code Project but completely hosted within the Stack Overflow environment.

A: I think a link in your profile to your blog would serve the same purpose.  You're also welcome to ask a question then provide the answer on those occasions when you have an answer ready but the question hasn't been asked yet.

A: Let's see ...
StackOverflow, et al, are question and answer sites. They are not a blog engine. In fact, the format doesn't even work particularly well for blog-type entries. They do OK for questions you self-answer, but even that seems to be frowned on (these days) by the communities.
Having a separate tutorial/blog post kind of deal that any of us (even with a minimum required threshold) can post to will dilute the value of the primary mission (Q & A), whilst simultaneously increasing the amount of noise and maintenance on the site. Not to mention the development effort for Jeff & crew (who I'm sure many of us would like to see implement things like tag blacklists first).

In my mind, I'm envisioning something like CodeProject but completely hosted within the SO environment.

That exists already. It's called CodeProject.
Bottom line: The sites work right now because they're laser-focused on specific missions and have a critical mass of users. Adding more to their nice, focused missions will dilute their value, hurt the quality, and take development resources away from more pressing and mission-focused feature requests.


text:
Q: r removing symmetrical elements of a matrix I'm trying to combine two adjacency matrices leaving out the symmetric intersections.
    M1<-matrix(c(0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,0),nrow=5,ncol=5,byrow=T)
    M2<-matrix(c(0,0,0,0,0,1,0,0,0,0,1,0,0,0,0,0,0,0,0,1,0,0,0,0,0),nrow=5,ncol=5,byrow=T)

The question is : how to reach the matrix below which "forgets" ([1,2],[2,1]) and displays only ones and zeros ?
My final result should be :
      [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    1    0    0    0    0
[4,]    1    0    0    0    1
[5,]    0    0    0    0    0

I've tried all sorts of additions and substractions involving t(M2) but there is always something wrong.

A: M = M1+M2
M[M==t(M)]=0
+(M>0)
     [,1] [,2] [,3] [,4] [,5]
[1,]    0    0    0    0    0
[2,]    0    0    0    0    0
[3,]    1    0    0    0    0
[4,]    1    0    0    0    1
[5,]    0    0    0    0    0

A: Thanks to Onyambu. Applying your solution to my MClist of 40 (Mn,Nn) pairs, seems to work in this way:
 AddMC<-lapply(1:40, function(x){
  (MClist[[x]][[1]]+MClist[[x]][[2]])
})

InterMC<-lapply(1:40, function(x){
  AddMC[[x]][AddMC[[x]]==t(AddMC[[x]])]=0
  +(AddMC[[x]]>0)
})


text:
Q: Patching linux kernel fails? From what I understand, I can easily upgrade my kernel by applying patches to it, opposed to recompiling the kernel every time. I'm trying to go from kernel 3.2.51 to 3.2.54 by applying all the patches in between.
I'm trying to patch my 3.2.51 kernel (I downloaded it from www.kernel.org and compiled it myself) to 3.2.52. When I run this command (in the source directory /usr/src/linux-3.2.51):
$ gzip -dc /root/patch-3.2.52.gz | patch -p1

I get this error:
patching file Documentation/HOWTO
Reversed (or previously applied) patch detected!  Assume -R? [n]

Apply anyway? [n]

And it rejects all the changes. Can someone explain what I'm doing wrong?

A: The patch for 3.2.x is presumably between 3.2.0 and 3.2.x, not between 3.2.(x - 1) and 3.2.x.
If you do this often, perhaps it is easier just to follow the relevant git repository.
In any case, you will need to recompile (much) of the kernel anyway.


text:
Q: Android : Error Initilazing the Youtube player I implementing a YouTube player in my app using YouTubeAndroidPlayerApi to play videos I add into my app. It was working all fine till two days back when an error started to show up suddenly. I have been trying to solve this, but have failed. Please help me out.
onCreate
@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.youtube_lightbox);
        final RelativeLayout relativeLayout = (RelativeLayout) findViewById(R.id.relativeLayout_youtube_activity);
        relativeLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                onBackPressed();
            }
        });
        final YouTubePlayerView playerView = (YouTubePlayerView) findViewById(R.id.youTubePlayerView);

        if (savedInstanceState != null) {
            millis = savedInstanceState.getInt(KEY_VIDEO_TIME);
        }

        final Bundle extras = getIntent().getExtras();
        if (extras != null && extras.containsKey(KEY_VIDEO_ID)) {
            mVideoId = extras.getString(KEY_VIDEO_ID);
        } else {
            finish();
        }

        playerView.initialize(API_KEY, this);

    }

onInitializationSuccess
  @Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
    mPlayer = youTubePlayer;
    youTubePlayer.setFullscreenControlFlags(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_ORIENTATION);
    youTubePlayer.addFullscreenControlFlag(YouTubePlayer.FULLSCREEN_FLAG_CONTROL_SYSTEM_UI);
    youTubePlayer.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
        @Override
        public void onFullscreen(boolean b) {
            isFullscreen = b;
        }
    });
    if (mVideoId != null && !b) {
        youTubePlayer.loadVideo(mVideoId);
    }

    if (b) {
        youTubePlayer.seekToMillis(millis);
    }

}

Error
E/YouTubeAndroidPlayerAPI: Error creating YouTubePlayerView
  com.google.android.youtube.player.internal.w$a: Exception thrown by invoked constructor in com.google.android.youtube.api.jar.client.RemoteEmbeddedPlayer
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.ac.a(Unknown Source)
                                                                                at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
                                                                                at com.google.android.youtube.player.YouTubePlayerView$1.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r.g(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$c.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$b.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                                                Caused by: java.lang.reflect.InvocationTargetException
                                                                                at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.ac.a(Unknown Source)
                                                                                at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
                                                                                at com.google.android.youtube.player.YouTubePlayerView$1.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r.g(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$c.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$b.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)
                                                                                Caused by: java.lang.IllegalArgumentException: The concrete class implementing IObjectWrapper must have exactly *one* declared private field for the wrapped object.  Preferably, this is an instance of the ObjectWrapper<T> class.
                                                                                at tff.a(SourceFile:76)
                                                                                at com.google.android.youtube.api.jar.client.RemoteEmbeddedPlayer.<init>(SourceFile:147)
                                                                                at java.lang.reflect.Constructor.newInstance(Native Method)
                                                                                at java.lang.reflect.Constructor.newInstance(Constructor.java:288)
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.w.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.ac.a(Unknown Source)
                                                                                at com.google.android.youtube.player.YouTubePlayerView.a(Unknown Source)
                                                                                at com.google.android.youtube.player.YouTubePlayerView$1.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r.g(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$c.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$b.a(Unknown Source)
                                                                                at com.google.android.youtube.player.internal.r$a.handleMessage(Unknown Source)
                                                                                at android.os.Handler.dispatchMessage(Handler.java:102)
                                                                                at android.os.Looper.loop(Looper.java:145)
                                                                                at android.app.ActivityThread.main(ActivityThread.java:5832)
                                                                                at java.lang.reflect.Method.invoke(Native Method)
                                                                                at java.lang.reflect.Method.invoke(Method.java:372)
                                                                                at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1399)
                                                                                at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1194)

Can anyone point out whats the issue. Thanks in advance.

A: Did you have google youtube app on your device?
update youtube app from playstore to the latest,
or you can install it if you dont have.
then run the youtube app,
last step, try run your own app with youtube player again.
tell me if it works.


text:
Q: ImageMagick installation MediaTemple GridServer I've activated the ImageMagick extension as per the KnowledgeBase article
Basically, adding this line to php.ini:
open_basedir = /nfs:/tmp:/usr/local:/etc/apache2/gs-bin:/usr/bin/convert

However, this doesn't seem to work.
This script outputs the version number just fine:
$IM_version=shell_exec("/usr/bin/convert -version");
echo $IM_version;

However, when I try to use the Imagick class I get an error.
try
{
        /*** a new imagick object ***/
        $im = new Imagick();

        /*** Create a red rectangle  ***/
        $im->newImage( 200, 100, "red", "png" );

        /*** write image to disk ***/
        $im->writeImage( '/tmp/rectangle.png' );

        echo 'Image Created';
}
catch(Exception $e)
{
        echo $e->getMessage();
}

Error:
Fatal error: Class 'Imagick' not found in /xxxxxxxxxxxxxxx/html/mt.php on line 8

Any ideas what I'm doing wrong or what the next step for troubleshooting is?
I've contacted MediaTemple support and they just said "sorry but because the script outputs the version number it proves it's installed"

A: Ok, I got this working but it was a bit tricky. Here goes...
First, you'll want to install ImageMagick from source. This step may be optional if you already have access to 'MagickWand-config', but it wasn't in my path. Here were the steps I followed to install it into an alternate directory on the (gs):
Note: As of this post, the latest release was 6.8.9.3.
$ wget http://www.imagemagick.org/download/ImageMagick-6.8.9-3.tar.gz
$ tar xvfz ImageMagick-6.8.9-3.tar.gz
$ cd ImageMagick-6.8.9-3
$ mkdir /home/#####/etc/imagemagick
$ ./configure --prefix=/home/#####/etc/imagemagick
$ make
$ make install

The Imagick PHP class is a PECL extension so we will install it using the provided KB from Media Temple with one change. Here are the steps:
$ export SITEID=`pwd | awk -F\/ '{ print $3 }'`
$ export PHPPATH=`php-stable -i | grep "Configure Command" | perl -pe "s/.*'.\/configure'\s*?'--prefix\=(.*?)'.*/\1/"`
$ mkdir /home/$SITEID/data/lib
$ mkdir /home/$SITEID/data/lib/php/
$ wget http://pecl.php.net/get/imagick && tar zxvf imagick && cd imagick-* && $PHPPATH/bin/phpize

This is where our script deviates from the instructions. We need to specify the path to our ImageMagick install to use 'MagickWand-config'. If this isn't specified, you'll see the following error:

checking ImageMagick MagickWand API configuration program...
  configure: error: not found. Please provide a path to
  MagickWand-config or Wand-config program.

If you've used an alternate location for the source install of ImageMagick, replace the path for '--with-imagick' with that path.
$ ./configure --with-php-config=$PHPPATH/bin/php-config --with-imagick=/home/#####/etc/imagemagick

Resuming the normal instructions:
$ make && cp modules/*.so /home/$SITEID/data/lib/php

Update your php.ini file, which should be located at /home/#####/etc/php.ini and add these 2 lines:

extension_dir=/home/#####/data/lib/php/
extension = imagick.so

Once complete, here is the script I ran:
<?php

$IM_version=shell_exec("/usr/bin/convert -version");
echo $IM_version;

if (!extension_loaded('imagick'))
{
    echo "imagick not installed\n";
}
else
{
    echo "imagick installed\n";
}

try
{
        /*** a new imagick object ***/
        $im = new Imagick();

        /*** Create a red rectangle  ***/
        $im->newImage( 200, 100, "red", "png" );

        /*** write image to disk ***/
        $im->writeImage( '/tmp/rectangle.png' );

        echo 'Image Created';
}
catch(Exception $e)
{
        echo $e->getMessage();
}

Output:
Version: ImageMagick 6.6.0-4 2012-05-03 Q16 http://www.imagemagick.org
Copyright: Copyright (C) 1999-2010 ImageMagick Studio LLC
Features: OpenMP

imagick installed
Image Created


text:
Q: Sum cell values from multiple workbooks with multiple worksheets - Macro
*

*I have 50 workbooks. Each has 3 worksheets.

*I have a value in each of these sheets from cells A1 to N1.

*I want to sum up all the values in a single workbook (in 3 worksheets respectively).
(i.e. A1 of sheet1 workbook1 + A1 of sheet1 workbook2 +.....+ A1 of sheet1 workbook50 = A1 of sheet1 MacroWorkbook.

Similarly B1 of sheet1 workbook1 + B1 of sheet1 workbook2 +.....+ B1 of sheet1 workbook50 = B1 of sheet1 MacroWorkbook.
 For 3 sheets and say 50 workbooks.
I would prefer open file location instead of selecting from a directory.

With the help of different forums, I have tried getting the sum from multiple workbooks from sheet1:
Sub SUM_Workbooks()
    Dim FileNameXls As Variant
    Dim i As Integer
    Dim wb As Workbook
    FileNameXls = Application.GetOpenFilename(filefilter:="Excel Files, *.xl*", MultiSelect:=True)
    If Not IsArray(FileNameXls) Then Exit Sub
    Application.ScreenUpdating = False
    For i = LBound(FileNameXls) To UBound(FileNameXls)
        Set wb = Workbooks.Open(FileNameXls(i))
        wb.Sheets(1).Range("A1:N1").Copy
        ThisWorkbook.Sheets(1).Range("A1:N1").PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks:=True, Transpose:=False
        Application.CutCopyMode = False
        wb.Close SaveChanges:=False
        Next i
    Application.ScreenUpdating = True
End Sub

I would want to extend this for 3 sheets. Help would be much appreciated as I'm no expert in VBA. Thanks!

A: If you want to sum values from all workbooks (from each worksheet A1:N1) and paste result in A1:N1 of thisWorkbook, use this one:
Sub SUM_Workbooks()
    Dim FileNameXls, f
    Dim wb As Workbook, i As Integer

    FileNameXls = Application.GetOpenFilename(filefilter:="Excel Files, *.xl*", MultiSelect:=True)

    If Not IsArray(FileNameXls) Then Exit Sub

    Application.ScreenUpdating = False

    For Each f In FileNameXls
        Set wb = Workbooks.Open(f)
        For i = 1 To 3
            wb.Worksheets(i).Range("A1:N1").Copy
            ThisWorkbook.Sheets(i).Range("A1:N1").PasteSpecial Paste:=xlPasteValues, Operation:=xlAdd, SkipBlanks:=True, Transpose:=False
        Next i
        wb.Close SaveChanges:=False
    Next f

    Application.CutCopyMode = False
    Application.ScreenUpdating = True
End Sub


text:
Q: Volume of the intersection of unit hypercube and Lp n-ball What is the $n$-dimensional volume of the intersection of a unit hypercube (side length 1) and an $L_p$ ball with radius $r$, both centered at the origin, with $p > 0$? [This includes the $L_p$ seminorms where $0 < p < 1$].
This question is a generalization of intersection of hypercube and hypersphere. I am wondering if there is an analytical and/or recursive solution similar to the accepted answer there, which is given for the specific case when $p = 2$. The question is also similar to volume of the intersection of two lp balls, which does not have an accepted answer, though my question has different constraints and may be easier to solve analytically.
When $r \geq \frac{1}{2}||\mathbf{1}||_p$, the hypercube will be contained within the $L_p$ ball and the volume $V$ will be 1. When $r \leq \frac{1}{2}$, then the ball will be contained within the hypercube and
$V = 2^n r^n \frac{\Gamma\left(1 + \frac{1}{p}\right)^n}{\Gamma\left( 1 + \frac{n}{p} \right)}$,
where $\Gamma$ is the gamma function, as shown here but scaled by $r^n$ for non-unit balls.
What is the volume when $\frac{1}{2} < r < \frac{1}{2}||\mathbf{1}||_p$?


text:
Q: WSO2 IS as a bridge, email address claim lost I have WSO2 IS set up as a bridge to provide a SAML IdP for our WS-Federation IP.  Upon authenticating, the WS-Federation IP sends a SAML assertion containing various attributes including one with the name of http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress.  WSO2's SAML assertion has all of those attributes exactly as is with the exception that the emailaddress claim is missing.
I am using the default claim mappings, the service provider has Enable Attribute Profile, Include Attributes in the Response Always, and using version 5.3.0, on Windows.

A: I believe I have found the problem.  WSO2 apparently does not like to receive multiple values for an attribute, and, when it does, it only accepts the last value for the attribute.  Also, if the value happens to be blank, WSO2 will remove the item.  In the SAML Assertion from our WS-Federation IP, the email address attribute was being set as:
<Attribute Name="http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress">
    <AttributeValue>email@address</AttributeValue>
    <AttributeValue/>
</Attribute>

Because WSO2 does not appear to support multiple values for attributes, it keeps the last one only, and, because it is blank, it removes the attribute.  When I modified the data of the test user to have two email addresses, the last email address listed was passed through.


text:
Q: How to change a class's content using jQuery Here is the div element on my page:

How can I change a class's content?
So from existing which is: class="jcarousel-next jcarousel-next-horizontal"
to class="jcarousel-next jcarousel-next-horizontal jcarousel-next-
disabled jcarousel-next-disabled-horizontal"
Do I need to completely remove it by using removeClass and then re-add?

A: The addClass function preserves existing classes.

A: no you can just use addClass.  if you add a class that is already there jQuery wont add it again
$('#myelem').addClass('jcarousel-next-disabled jcarousel-next-disabled-horizontal');

A: Try this:
jQuery('#myobj').removeClass('class-to-remove').addClass('class-to-add');

EDIT: multiple classes at once:
jQuery('#myobj').removeClass('class1 class2').addClass('class3 class4');

Also you can toggle classes with toggleClass().
Brg.


text:
Q: Overlap AABB-Arc and AABB-Pie I am looking for a simple algorithm to detect if the area of an aabb overlaps with the area of an arc (closed by the cord) or a pie (closed through the circle's center).
I already found this answer: Intersection of rectangle and circle (or arc)
But it is not quite what I am looking for because I am not interested in the intersection points of the shapes' outlines but just want to know if the areas overlap.
Eg the case that a very small AABB contains only the center of the pie but the AABB's edges do not intersect the pie's circle would not be covered in the linked answer.
Likewise the case that the arc completely contains the the AABB and the AABB's sides do not even intersect the cord would not be covered.
Now before I start reinventing the wheel I would like to ask if there is a known algorithm for such an overlap check.
One example of AABB-Sector:

A: This isn't such an easy problem given the variety of configurations.
You will make the problem simpler by splitting the sector with a cross through the center, so that an horizontal or vertical line will not meet the arc twice, and process the pieces separately.
Then consider one of the pieces and "inflate" it while you "deflate" the rectangle. More precisely, every point of the sector becomes the rectangle originating from it (upper-left corner), while the rectangle shrinks to its lower-right corner.
The shape that you obtain (green area) is a so-called Minkowski sum (aka dilation).
As you see, it has 5 straight edges and a curved one. You can easily predict the shapes for all sector orientations.

Now there is an intersection if the rectangle shrunk to a point lies inside this curvilinear hexagon. You check that the point belongs to the sector using polar coordinates (r < R and Θ' < Θ < Θ"), and you check insideness to the (straight) hexagon by a standard point-in-polygon test.
Similar reasoning works for the circular segment (chord).

This geometric transformation allows to use the "locus" approach, i.e. visualize the solution set as a geometric shape, to support reasoning. Given the nature of the domain (a convex hexagon), we can conclude that in the worst case 4 comparisons (involving linear or quadratic terms) are enough to get the answer by dichotomy !

A: The sector and segment cases are different.
For a segment:

*

*Broadphase: If the AABB of the circle-segment doesn't intersect, then no.

*If the chord intersects (or is within) the AABB the answer is yes. This is line-segment to rectangle test, which I assume you know how to do.

*This leaves only the case where the AABB is within the circle-segment or intersects the arc. For this to be true at least part of one of the four sides must be within the segment (or the whole segment would be contained including the chord, and we would have found that at the previous step).

*therefore treat rectangle as four lines, and for each line

*

*calculate the line segment within the circle by intersection with the circle

*if it exists check that either end of the line is on the inside of the circle-segment by comparing to the chord.

For a sector, you can either treat it as a segment plus a triangle, or:

*

*If the AABB of the circle doesn't intersect, then no.

*If either radial line intersects, then Yes.

*Otherwise treat the rectangle as four line segments, and for each segment:

*

*Calculate the line segment within the circle by intersection with the circle.

*If it exists calculate the sub-segment which is on the correct side of the first radial line.

*if it exists calculate the sub-segment which is on the correct side of the second radial line.


text:
Q: Hibernate generates query without using where cluase I use hibernate and MySQL.
I have a query in MySQL database which looks like:
select
  phones0_.c_id as c_id_1, phones0_.cp_id as cp_id1_2, phones0_.cp_phone as cp_phon1
from
  customer_phone phones0
where
  phones0_.c_id in (select customer0_.c_id from customer customer0_ )

The issue is that there is no where clause in nested select. But I always use restrictions when i do some operations in JpaRepository.
I guess there are some issues in mapping.
Here are the examples of entities:
@Data
@Entity
class Customer {
  @GeneratedValue
  @Id
  @Column(name="c_id")
  Long id;

  @Column(name="c_name")
  private String name;

  @OneToMany( mappedBy = "customer" )
  @Fetch( FetchMode.SUBSELECT )
  private List<CustomerPhone> phones;
}

@Data
@Entity
@Table(name = "customer_phone")
class CustomerPhone {
  @GeneratedValue
  @Id
  @Column(name="cp_id")
  Long id;

  @Column(name="cp_phone")
  private String phone;

  @ManyToOne( fetch = FetchType.LAZY )
  @JoinColumn( name = "id", nullable = false, updatable = false )
  private Customer customer;
}


text:
Q: Temporary method within method? In the method below, there are three conditionals.  I'd like to replace them with a method and pass in the conditional.
Also, the conditional body is nearly repeated.  Is it possible to create a method that exist only locally within MyMethod()?  So the code below reduces to something like this:
//reduced code
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
 return localMethod((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1");
 return localMethod((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true);
 return localMethod((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2");

//...localMethod() defined here...
}

But in the above, only one should return.
//original code
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{

 if(class1Var.SomeBool && !class2Var.SomeBool)
 {
   return new ClassZ
   {
     Property1 = false,
     String1 = "This is string1"
   };
 }

 if(class1Var.SomeBool && !class2Var.IsMatch(class2Var))
 {
   return new ClassZ
   {
     Property1 = true,
   };
 }
 if(class1Var.SomeProperty.HasValue && !class2Var.SomeBool)
 {
   return new ClassZ
   {
     Property1 = false,
     String1 = "This is string2"
   };
 }

}

Basically, I'd like to create a temporary method within a method.

A: You can use Func notation for this.  Funcs encapsulate delegate methods.  Read the documentation of Funcs here.  For a Func with n generic parameters, the first n-1 are the inputs of the method and the last parameter is the return type.  Try something like this:
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
    Func<bool, bool, string, ClassZ> myFunc
             = (predicate, prop1Value, string1Value) =>
                      predicate
                      ? new ClassZ { Property1 = prop1Value, String1 = string1Value }
                      : null;
    return myFunc((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1")
           ?? myFunc((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true)
           ?? myFunc((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2");
}

Here, we instantiate a Func that takes in a bool (the predicate), the parameters to set (the second bool and the string), and returns a ClassZ.
This is also using null coalescing (the ?? notation), which returns the first non-null argument.  Read more about null coalescing here.
The other option is to use Actions, which encapsulate void methods.  Read about Actions here.  You could instantiate a new ClassZ, and then call 3 Actions on it, which conditionally set the variables provided.
public ClassZ MyMethod (Class1 class1Var, Class2 class2Var)
{
     Action<bool, bool, string, ClassZ> myAction
         = (predicate, prop1Value, string1Value, classZInstance) =>
                  if (predicate)
                  {
                      classZIntance.Property1 = prop1Value;
                      classZInstance.String1 = string1Value;
                  }
     var myClassZ = new ClassZ();
     myAction((class1Var.SomeBool && !class2Var.SomeBool), false, "This is string1", myClassZ)
     myAction((class1Var.SomeBool && !class2Var.IsMatch(class2Var)), true, classZ)
     myAction((class1Var.SomeProperty.HasValue && !class2Var.SomeBool), false, "This is string2", myClassZ);
     return myClassZ;
}


text:
Q: What's the default TLS version used by MSOLEDBSQL? I'm asking because Java 7 uses TLS 1.0 by default unless you explicitly stated otherwise in the connection string when using JDBC. I would like to know whether this is also the case with MSOLEDBSQL.

A: This is not client library-specific.

Note that the cipher suite for TLS/SSL and the authentication mechanism for SSPI and federated authentication are negotiated outside the influence of TDS in [RFC2246] and [RFC6101].

TDS - 1.7 Versioning and Capability Negotiation
The important thing is that the cypher used is acceptable to both the client and the server.  So even if the client supports TLS 1.0, the server doesn't.


text:
Q: When synchronizing my report with Teamleader I get a itgensql001 error for a custom field When synching my Teamleader report in Invantive Control I get the following error:
Unknown identifier 'cpyd.c_5_contactpersoon'.

Screenshot of error

Part of the query:
select pjtd.pjt_title          pjt_title
,      cpyd.c_5_contactpersoon customer_contact_person

This is a custom field in Teamleader.
What could be the cause of this error?

A: When you add a custom field in Teamleader, the order of the fields will change.
In order to check which new number is assigned to certain fields, you can execute the following query:
select * from Teamleader.CustomFields.Custom_Fields_All

This will return a list of all the custom fields, with the number that is assigned to them.
For example:

So the custom field 'contactpersoon' will be 6 in this case.
This means the number of the field in the query has to be changed:
cpyd.c_5_contactpersoon > cpyd.c_6_contactpersoon


text:
Q: How to ask an exclusive or question? Not long ago I finished a project for a school assignment. After the assignment was done I left the office of this particular teacher. Just before I wanted to exit through the door I turned around and asked if he preferred the door open or close. The question I asked was "Door open or door closed?". This particular teacher always tries to be funny in a dickish way. He answered "Yes". After some research I found out that apparently the answer yes to an or question is valid, because "or" in a question is like the programmable "or". How would I ask exclusively "or" questions, programmable xor, so to speak.
TLDR: How to ask "Xor" questions in english, A Xor B.

A: Door open or door closed? is not an XOR in the true sense of it as you are only asking for one input (Yes or No) but XOR requires two inputs.
You are asking two questions already, but still only getting a single response. If you simply negate the response and use it as the second input you are still only working with an OR. Yes and No, No and Yes, this doesn't give enough variation to complete the truth table for OR but because the OR outcome of any pair where one complement is true is true, you don't need to complete the true/true=true. This is not the case for XOR
It can be a straight OR question because with a door any amount of openness is open, zero amount of openness is closed. Due to the exclusivity of door openness you can safely ask Door open? meaning do you want the door left open or not, there are only two sensible responses, Yes or No, although Don't care is a possibility (same as Up to you) but that really means you can ignore the result of the question and take no action.
The right way to ask in this case is just to ask

Do you want the door left open?

This doesn't work where there is no exclusivity built into your question, for example Shall I leave the book on the shelf or on the floor? cannot be shortened to Shall I leave the book on the shelf?
So that got me thinking, is it really possible to use XOR in English
Can it really be done as an XOR? ... maybe
This is the XOR truth table (bad format alert), Ix is the inputs, R is the result (binary)
I1=0 I2=0 R=0

I1=1 I2=0 R=1

I1=1 I2=1 R=0

I1=0 I2=1 R=1

Lets define the two inputs as 'Your teachers Reply' and 'the Current state of the door'
Lets define the result as Should you change the state of the door
You ask your teacher Door open or door closed? and he replies with either Yes or No.
Our truth table looks like (worse format alert)
Reply  Current State of the Door  = Should you change the state of the door

No(0)  Closed(0)                  = No(0) (leave the door closed)

Yes(1) Closed(0)                  = Yes(1) (open the door)

Yes(1) Open(1)                    = No(0) (leave the door open)

No(0)  Open(1)                    = Yes(1) (close the door)

While we've managed to somehow squeeze a simple English question into an XOR it's not really a proper case for XOR as we've had to 'invent' one of the inputs and I can't think of any English question or statement that would fall into a proper XOR scenario. The problem is always the two positive inputs that result in a negative.
Another possible XOR method
You ask your teacher Door open or door closed?. Ignoring all replies that include responses other than Yes or No  we can make some assumptions.
If the reply is just No, that means Door open? No, Door closed? No
If the reply is Yes and No, that means Door open? Yes, Door closed? No
If the reply is just Yes that means Door open? Yes, Door closed? Yes
If the reply is No and Yes, that means Door open? No, Door closed? Yes
Fitting that into our truth table
Reply to Door open    Reply to Door closed     Result
No(0)                 No(0)                    (0) Close the door
Yes(1)                No(0)                    (1) Open the door
Yes(1)                Yes(1)                   (0) Close the door
No(0)                 Yes(1)                   (1)Open the door

Again we've had to make something of an assumption, that when the teacher replies with a single response he means that the single response applies to both questions. So it's not at all cut and dried.
After all that I'm beginning to think that the next time you ask your teacher what state he wants his door left in and he answers in a dickish manner, you should find someone in a position of higher authority and tell them he touched you in an inappropriate manner. (Joking)

This could be my next bounty question - find a question that elicits
  two answers and a result that fits in to the XOR truth table.


text:
Q: Как заставить бота работать 24/7 не на компьютере? Я разработал бота (написан на Java для Discord). На данный момент бота запускаю через компилятор на компьютере, но хотел бы, чтобы мой бот работал непрерывно 24/7. Как я понимаю, мне нужен Java-север или что-то другое?
Уверен, данный вопрос актуален еще тем, кто пишет бота для Telegram и vk.com

A: Используйте хостинг. Amazon(для крутых, т.к. не дешево) и т.п. - Digital Ocean(его рекомендуют), Heroku, Hostinger тоже неплох.
Вот хорошая статья(Веб-платформа на Java за 30 минут), как быстро развернуть web-приложение Java на сервере.

A: Для развертывания Java-бота (да и вообще любого другого бота, написанного на других языках) не стоит искать специальный Java-сервер. В данном случае нам понадобится выделенный сервер (dedicated server) или VPS (Virtual Private Server). Web-Hosting - это для хостинга сайтов, а значит нам данный вариант не подходит.
Из моего личного опыта, лучший VPS-провайдер - это Digital Ocean, однако он дорогой и если вы из России, то готовьтесь к тому, что многие запросы на Российские сервера будут недоступны (привет Рос****надзору).
Я бы лучше брал dedicated server. Один из лучших провайдеров выделенных серверов - OVH. Сервера дорогие и поэтому я порекомендовал бы их дочернюю компанию - https://www.kimsufi.com/. Если у вас бот не многозадачен, то за 5-6 евро сервера вам будет сверхдостаточно.
Что же делать после покупки сервера?
Лично я люблю Ubuntu (хотя с ней немало хлопот можно словить) и через командную строку (на сервере) устанавливаете OpenJDK, потом перекидываете по FTP executable jar file (запускаемый Jar-файл). Далее запускаем приложение в фоновом режиме. Если вы просто запустите приложение на сервере и закроете консоль, то программа ваша автоматически завершится.
Как запустить в фоновом режиме приложение?
Создаем файл /etc/systemd/system/myapplication.service
[Unit]
Description= # Place a descriptive application name here
After=syslog.target
After=network.target[Service]
User= # Define a user account that will own our app. Example: root
Type=simple

[Service]
ExecStart=/usr/bin/java -jar # Provide /path/to/file/myapplication.jar
Restart=always
StandardOutput=syslog
StandardError=syslog
SyslogIdentifier= # A short identifier for system journal, f. e. 'myapplication'

[Install]
WantedBy=multi-user.target

sudo systemctl start/stop/restart myapplication
start - запускает бота
stop - останавливает бота
restart - перезапускает бота (можно использовать команду при обновлении jar-файла с ботом)
На этом все


text:
Q: Serverless Mailgun not generating mail Thought I'd dip my toe into Serverless and see if I can generate a function to send a message via Mailgun. My function succesfully runs with the message "Go Serverless v1.0! Your function executed successfully!" but no message is sent via Mailgun:
My handler.js:
'use strict';
var mailgun = require('mailgun-js')({apiKey: 'xxx', domain: 'email.mydomain.co.uk'})

module.exports.hello = async event => {
        var data = {
            from: 'no-reply@email.mydomain.co.uk',
            to: 'me@somewhere.co.uk',
            subject: 'Hello',
            text: 'Testing some Mailgun awesomeness!'
        };

        mailgun.messages().send(data, function (error, body) {
            if(error)
            {
                    console.log(error)
            }
            console.log(body);
        });

        return {
            statusCode: 200,
            body: JSON.stringify('Go Serverless v1.0! Your function executed successfully!')
        };
};

My serverless.yml is very simple:
service: helloworld
provider:
  name: aws
  runtime: nodejs12.x
  region: eu-west-2
functions:
  hello:
    handler: handler.hello
    events:
      - http:
          path: hello
          method: post

I've tested the function with curl and via the UI in AWS but neither provide any debug messages related to mailgun.

A: I suspect that, since the .send() method is asynchronous, your handler does not wait long enough and finishes running before the message is done.
Return a promise (the API of mailgun-js is already producing promises, you just need to return them):
module.exports.hello = event => {
    return mailgun.messages().send({
        from: 'no-reply@email.mydomain.co.uk',
        to: 'me@somewhere.co.uk',
        subject: 'Hello',
        text: 'Testing some Mailgun awesomeness!'
    }).then(msgBody => {
        statusCode: 200,
        body: JSON.stringify({status: 'sent a message!', text: msgBody})
    });
};

when you return an actual promise yourself, the async keyword becomes superfluous. You can rewrite the same thing in async/await style:
module.exports.hello = async event => {
    var msgBody = await mailgun.messages().send({
        from: 'no-reply@email.mydomain.co.uk',
        to: 'me@somewhere.co.uk',
        subject: 'Hello',
        text: 'Testing some Mailgun awesomeness!'
    });

    return {
        statusCode: 200,
        body: JSON.stringify({status: 'sent a message!', text: msgBody})
    };
};


text:
Q: Associativity of logical connectives According to the precedence of logical connectives, operator $\rightarrow$ gets higher precedence than $\leftrightarrow$ operator. But what about associativity of $\rightarrow$ operator?
The implies operator ($\rightarrow$) does not have the associative property. That means that $(p \rightarrow q) \rightarrow r$ is not equivalent to $p \rightarrow (q \rightarrow r)$. Because of that, the question comes op how $p \rightarrow q \rightarrow r$ should be interpreted.
The proposition $p \rightarrow q \rightarrow r$ can be defined in multiple ways that make sense:

*

*$(p \rightarrow q) \rightarrow r$ (left associativity)

*$p \rightarrow (q \rightarrow r)$ (right associativity)

*$(p \rightarrow q) \land (q \rightarrow r)$

Which one of these definitions is used?
I could not locate any book/webpage that mentions about associativity of logical operators in discrete mathematics.
Please also cite the reference (book/reliable webpage) that you use to answer my question (as I'm planning to add this to wikipedia page about 'logical connectives').
Thanks.
PS: I got this question when I saw this problem:
Check if following compound  proposition is tautology or not:
$$ \mathrm{p} \leftrightarrow (\mathrm{q} \wedge \mathrm{r}) \rightarrow \neg\mathrm{r} \rightarrow \neg\mathrm{p}$$

A:
The proposition $p \rightarrow q \rightarrow r$ can be defined in
multiple ways that make sense:

*

*$(p \rightarrow q) \rightarrow r$ (left associativity)

*$p \rightarrow (q \rightarrow r)$ (right associativity)

*$(p \rightarrow q) \land (q \rightarrow r)$
Which one of these definitions is used?

In the absence of parentheses, a logician would read $$p \rightarrow q \rightarrow r$$ as $$p \rightarrow (q \rightarrow r);$$ however, in informal logic (including mathematics), $$p \Rightarrow q \Rightarrow r$$ is commonly read as $$(p \Rightarrow q) \;\text{ and }\; (q \Rightarrow r),$$ which isn't logically equivalent to $$p \Rightarrow (q  \Rightarrow r).$$

Similarly, $$p \Leftrightarrow q \Leftrightarrow r$$ is commonly read as $$(p \Leftrightarrow q) \;\text{ and }\; (q \Leftrightarrow r),$$ although a logician would read $$p \leftrightarrow q \leftrightarrow r$$ as $$p \leftrightarrow (q \leftrightarrow r),$$ which isn't logically equivalent to $$(p \leftrightarrow q) \;\text{ and }\; (q \leftrightarrow r).$$

Here's a clear illustration: $$(p \Leftrightarrow q) \;\text{ and }\; (q \Leftrightarrow r)$$ asserts that $p,q,r$ all have the same truth value; however, both $$p \Leftrightarrow ( q \Leftrightarrow r)$$ and $$(p \Leftrightarrow q) \Leftrightarrow r $$ admit this truth assignment: $(p,q,r)=$ (false, false, true).

A: Counter example: Suppose p, q, r are all false. Then (p=>q)=>r is false, and p=>(q=>r) is true.

A: I think $(p \rightarrow q) \land (q \rightarrow r)$ is the most useful interpretation of $p \rightarrow q \rightarrow r$.  It corresponds to natural language when we say something like "A implies B, which implies C".
A related convention is $x \lt y \lt z$ meaning $x \lt y \land y \lt z$.  The same three cases arise when $\lt$ is treated as a function yielding a boolean integer like in many programming languages.

A: When you enter $p \Rightarrow q \Rightarrow r$ in Mathematica (with p \[Implies] q \[Implies] r), it displays $p \Rightarrow (q \Rightarrow r)$.
That makes it plausible that the $\rightarrow$ operator is generally accepted as right-associative.

A: Some logical operators are associative: both $\wedge$ and $\vee$ are associative, as a simple check of truth tables verifies. Likewise, the biconditional $\leftrightarrow$ is associative.
However, the implication $\rightarrow$ is not associative. Compare $(p\rightarrow q)\rightarrow r$ and $p\rightarrow(q\rightarrow r)$. If all of $p$, $q$, and $r$ are false, then $p\rightarrow (q\rightarrow r)$ is true, because the antecedent is false; but $(p\rightarrow q\rightarrow r$ is false, because $r$ is false, but $p\rightarrow q$ is true. They also disagree with $p$ and $r$ are false but $q$ is true: then $p\rightarrow(q\rightarrow r)$ is true because the antecedent is false, but $(p\rightarrow q)$ is true, $r$ false, so $(p\rightarrow q)\rightarrow r$ is false.
Since they take different values at some truth assignments, the two propositions are not equivalent, so $\to$ is not associative.

A: Presumably $p \Rightarrow q \Rightarrow r$ means $(p \Rightarrow q) \Rightarrow r$, since the other option $p \Rightarrow (q \Rightarrow r)$ is equivalent to $(p \land q) \Rightarrow r$. That's similar to the laws of powering $p^{q^r} = p^{\left(q^r\right)}$ since $\left(p^q\right)^r = p^{qr}$.
Best practice is just not to put the reader into a state of ambiguity. Some mathematical writers dislike punctuation, but that's not an excuse for the rest of us to take advantage of it.
Since $\land$ and $\lor$ are associative, there's no ambiguity there, and it makes sense not to put parentheses. Sometimes one even thinks of an expression like $p \land q \land r$ as a conjunction $\land(p,q,r)$.
The latter convention is the case in proof complexity when one is measuring the depth of a formula. If a first-order quantified formula is translated to propositional logic, then $\forall$ will correspond to a conjunction, and $\exists$ to a disjunction; it makes sense not to penalize the formula for the size of the underlying universe.
An even more daring "convention" is having infinite conjunctions/disjunctions - this wouldn't make sense at all for $\Rightarrow$. So your textbook authors are at fault (even though having the $\Leftrightarrow$ bind weakly is a reasonable convention if not overused).

A: What basic principle(s) do you have when doing logic from scratch without any formation rules?  I'll propose one which I think unobjectionable.

*

*Try to keep things as simple as reasonable or make things as simple as reasonable.

When you work or play around with conditionals you probably will want to find the antecedent of the conditional so that you can detach something.  p→(q→r) has a simpler antecedent than (p→q)→r, and consequently given a pseudo-formula it comes as simpler to find an antecedent of some form "p" in your axiom set than to find some form (p→q) in your axiom set to detach something from (p→q)→r.  Consequently, p→(q→r) makes more sense than (p→q)→r.

A: Note that since it's not a binary operator, but a binary relation, associativity does not always yield the same semantics, of reducing composition pairings to a queue. Suppose $p \implies q \implies r.$ But if $r$ is false, $p \implies q$ being true does not imply $r$ is true. Likewise, $p \implies q$ can be false while $p \implies (r \implies q)$ is true, so $(p \implies (q \implies r)) \implies (p \implies q), (q \implies r)$ is not necessarily true. Finally, if $(p \implies q) \implies r$, and $p \implies (q \implies r),$ and $p \equiv F,$ we have no reason to think $q \implies r$, and $p \implies q$ can still be true, which would mean $r$ is true regardless of whether $p \implies r$.


text:
Q: How to finish current animation in Unity3D Animator? I have an animation created in Animator where a part of UI transitions from one side of the screen to another.
How to add an option to immediately finish the animation and put animated object in its final place?
Because animations are created by 3rd party and I don't know the locations upfront, I can't just stop the animation and set position of the object to the final one.
Thanks

A: What you can do is something like this :
yourGameObject.GetComponent<Animation>().GetClip("YOUR_CLIP_NAME").SampleAnimation(yourGameObject, GetComponent<Animation>()["YOUR_CLIP_NAME"].length);
But this will only work if you know your AnimationClip name ahead...
Hope this helps,


text:
Q: Show that $e+\pi$ is not integer. It was suggested Taylor series for that.
$e^1 = \sum_{k=0}^\infty \frac{1}{k!}$
I don't know how to prove the convergence of this series, so I tried to set the upper limit to 5 (I'm doing all this with a very simple calculator, it's basically by hand). Then $e \approx 2.71$
Since $4\arctan(1)= \pi$
$4\arctan(1)=4 \sum_{k=0}^\infty \frac{(-1)^k}{2k+1}$
Again doing a aproximation setting the upper limit to 5, $\pi\approx2.96$ (which I think it's pretty bad, but with my calculator it's the best I could do).
Then $e+\pi \approx 5.67$. But this only proves the approximation that I did is not integer, not the exactly value of $e+\pi$. Is there a way to prove that $e+\pi$ is not integer without relaying on approximations?

A: With your approximations and using Interval arithmetics, you just have to show that $5<e+\pi <6$.

A: With very crude approximations you can show that
$ 5 \lt e +\pi \lt 6$, and the rest follows.
For crudely approximating $\pi$, we can use Taylor series expansion of $\tan^{-1}(x)$  Since it's an alternating series we can bound $\pi$ on both sides.
Since $\frac\pi6 = \tan^{-1}(\frac1{\sqrt{3}})$.
$$ 6(x - \frac{x^3}3) < \pi <6( x - \frac{x^3}3 + \frac{x^5}5) $$
$$ 3.07 < \frac{16 \sqrt 3}9 < \pi < \frac{82 \sqrt 3}{45} < 3.16 $$
For $e$ using the limit definition $\left(1+\frac1n\right)^n$ for two sided bounds:
$$   \left(1+\frac1n\right)^n < e < \left(1+\frac1n\right)^{n+1}$$

A: As @karakfa stated that you can prove $5\lt e+\pi\lt6$ using valid approximations. Better approximations would have been: $3\frac{10}{71}<\pi<3\frac{16}{113}$ for $\pi$ and $$\left(3+\sum_{i=2}^n \frac{-1}{i!(1-1)i}\right)\gt e \gt \sum_{i=0}^n \frac{1}{i!}$$ for $e$ (if $n$ is a finite natural number) as given in following web page: https://en.wikipedia.org/wiki/List_of_representations_of_e
You can set $n=5$ for $n$ in this approximation as you started.
The higher end of the approximation for $\pi$, $\pi \lt 3\frac{16}{113}$, is from  A063674 (https://oeis.org/A063674).

A: On calculating $\pi :$ If $\arctan u +\arctan v  =\arctan 1=\frac {\pi}{4}$ we may estimate $\pi$ using $$\arctan x=x\sum_{n=0}^{\infty}\frac {(-x^2)^n}{2n+1}.$$
If  $|ab|<1$ then $\arctan a + \arctan b =\arctan \frac {a+b}{1-ab}. $
$\frac {\pi}{4}=\arctan 1=\arctan \frac {1}{2}+\arctan \frac {1}{3}.$
$\arctan \frac {1}{2}=\arctan \frac {1}{3}+\arctan \frac {1}{7}.$
Hence $\frac {\pi}{4}=2\arctan \frac {1}{3}+\arctan \frac {1}{7}.$
Another one is $4\arctan \frac {1}{5} =$ $2\arctan \frac {5}{12}=$ $\arctan \frac {120}{119}=$ $\frac {\pi}{4}-\arctan \frac {1}{239}.$


text:
Q: Can not install rails on Ubuntu 14.0.4. Gem install rails error Im trying to install rails on ubuntu. Current version of ruby is 2.2.2 but its returning and error
omer@AK47:~$ gem install rails
ERROR:  While executing gem ... (Gem::RemoteFetcher::FetchError)
    Errno::EHOSTUNREACH: No route to host - connect(2) for "rubygems.global.ssl.fastly.net" port 443 (https://rubygems.org/quick/Marshal.4.8/rails-4.2.1.gemspec.rz)

A: Well, maybe your certificates are out of date? Try to fix them by sudo update-ca-certificates


text:
Q: Setup and Teardown in Typeorm We have setup and teardown in JEST where we can run some code before and after all tests run, things like beforeAll, afterAll, globalSetup etc
Do we have a similar thing in typeorm to run code before and after running the migrations ? I want to run some code before any of my migrations run when I execute npm run migrate:run. I can't find any thing in the docs related to this


text:
Q: Computing regular representations I'm doing a reading of representation theory (not a class) but don't really understand what $GL(\mathbb{F}(G))$ is. We defined $GL(n,\mathbb{C})$ in the usual way (set of matrices with nonzero determinant). But I'm not sure the determinant has a natural generalization for free vector spaces (ie $\mathbb{F}(G)$). Also, because I am not sure about this or what the objects look like in this space, I can't answer this fairly easy question (help appreciated here): Let $\mathbb{Z}_4$ denote the cyclic group of order four, compute the four by four matrices of each of the four elements for the left and right representations.  Actually, I would only like one matrix and a brief explanation of how it was found because I'm certain I can do the rest.  I suspect the matrix for $0$ would be the identity and the matrix for $1 $would have for rows $e_4, e_1, e_2,e_3$ respectively... but I'm not sure precisely why.... because I don't understand what $GL(\mathbb{F}(G))$ is.

A: If I understand the notation correctly, ${\mathbb{F}(G)}$ is simply the free vector space generated by $G$. Explicitly, ${\mathbb{F}(G)}$ is the vector space spanned by elements $[g]$ for $g\in G$: Elements of it are given by sums $\alpha_i[g_1] + \cdots + \alpha_n [g_n]$ for $g_i\in G$ distinct; addition is given by
$$\sum_{g\in G} \alpha_g [g] + \sum_{g\in G} \beta_g [g] = \sum_{g\in G} (\alpha_g + \beta_g)[g];$$
and the action of ${\mathbb{F}}$ is given by $k.[g] = k[g]$. (I'm assuming $G$ is finite here, for simplicity.) Then $\mathbb{F}(G)$ has dimension $\#G$, so its determinant of a homomorphism $\mathbb{F}(G) \to \mathbb{F}(G)$ is defined as for any other vector space over $\mathbb{F}$. (If you're familiar with algebraic number theory, the definition of the norm for a field extension $L/K$ is very similar to the construction here.)
Here's an explicit example. Take $G = {\mathbb{Z}}_4$, and write $G = \{1, x, x^2, x^3\}$ for some generator $x\in G$. We'll use that as our basis of $V = \mathbb{F}(G)$: the vectors $[1], [x], [x^2],$ and $[x^3]$. The left action of $G$ on itself, given by $\rho(g)h = gh$, defines the left representation of $G$: $\rho(g)[h] = [gh]$, and we extend $\rho$ by linearity to get a map $\rho:G \to \text{End}(V)$. This map is invertible, since every element of $G$ is invertible, so we actually get a map $\rho: G \to GL(V)$. For example, $\rho(x)$ is the map that takes $[1]\to [x]$, $[x]\to [x^2]$, $[x^2]\to [x^3]$, and $[x^3] \to [1]$. Over the basis, we've chosen, we wind up with:
$$\rho(x) = \begin{pmatrix}0 & 0 & 0 & 1\\1 & 0 & 0 & 0\\0 & 1 & 0 & 0\\0 & 0 & 1 & 0\end{pmatrix}.$$
Again, this is just the matrix form of an ordinary endomorphism of a 4-dimensional vector space over ${\mathbb{F}}$, and its determinant is entirely analogous to what it would be if the matrix above were just an ordinary element of $GL_4(\mathbb{C})$. You can derive the other $\rho(x^i)$ similarly, or use the fact that $\rho(x^i) = \rho(x)^i$.
In short: ${\mathbb{F}(G)}$ is the vector space spanned by symbols $[g]$ for $g\in G$. (This is just formal notation; I'm not even using the fact that $G$ is a group yet.) The left representation $\rho$ is defined by (linearity and the relation) $\rho(g)[h] = [gh]$. Choose your favorite basis of ${\mathbb{F}(G)}$ (the elements of $G$ listed in a particular order is generally a good choice), and you can write down $\rho$ as a matrix.


text:
Q: facets in ggplot failing to reflect data I'm graphing data from an experiment I ran with multiple participants who repeated the same trial several times. Naturally, I'm using facet_grid() from the ggplot2 package to plot each trial for each participant in its own sub-graph. The graph is beautiful, but it seems to be failing to represent the data I am feeding it. To wit, the x-axis in my graph is categorical, and I have re-ordered the levels using factor(), but while the axes are correct, the data in the plots does not follow the intended ordering. Stranger still, I'm using color to differentiate between values, but the color bindings in the legend seem to be off. So my question is ... what can I do to get the expected behavior?
Here's some sample code (data omitted):
library(ggplot2)

#pulling out variable for color
group <- df$Subvalue

#assigning an order to levels
v <- df$Item
v <- factor(v, levels = c("a", "o", "e", "u", "i", "A"))

p <- ggplot(df, aes(x=v, y=Duration, color=group)) +
    geom_point(shape=1)
p
#adding the facets
p + facet_grid(Repetition ~ Participant)

And here's part of my graph (it didn't come out very well in the pdf-ifying, so just use it to get a gestalt):

A: Maybe this is what you want? You need to leave your data in the dataframe, pulling it out just make things harder to keep in sync (as Hugh mentioned). Also you need to be explicit about what colors you want.
library(ggplot2)

# generate some fake data
n <- 500
iv <- sample(c("a", "o", "e", "u", "i", "A"),n,replace=T)
dv <- rnorm(n,100,50)
sv <- sample(c("group-1","group-2"),n,replace=T)
rv <- sample(1:2,n,replace=T)
pv <- sample(1:14,n,replace=T)
df <- data.frame(Item=iv,Duration=dv,Subvalue=sv,Repetition=rv,Participant=pv)

#assigning an order to levels
df$v <- factor(df$Item, levels = c("a", "o", "e", "u", "i", "A"))

p <- ggplot(df, aes(x=v, y=Duration, color=Subvalue)) +
  geom_point(shape=1) +
  scale_color_manual(values=c("group-1"="red","group-2"="blue")) +
  facet_grid(Repetition ~ Participant)
p

Yielding:


text:
Q: Function log from math.h returns wrong I was getting wrong values from log(), so I wrote this program just for testing:
#include <math.h>
#include <stdio.h>
void main()
{
  printf ("%1f", log(10));
}

This should print "1", but I get "2.302585"
Why is this and how can I fix it?

A: The log function is for the natural logarithm with base e.
It seems you want log10 instead.


text:
Q: DLLs are working on machine and in another not. Same configuration I have a DLL that I need to use in a Java application. This is already made with a Windows 32 bit service pack 3, so the DLL is working. Now I have another machine with the same configuration that needs to use it.
When I'm trying to load the lib in java, the follow error occurs:
Exception in thread "main" java.lang.UnsatisfiedLinkError: ARWAPI32 (This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem. )

When I open the DLL with Dependency Walker in the first machine, no problem occurrs, but when I open the DLL in the machine is not working
Error: The Side-by-Side configuration information for "c:\ARWAPI32.DLL" contains errors. This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem (14001).

What this means? I tried to register the dlls with the command Regsvr32 but the same error is showed.
LoadLibrary("c:\ARWAPI32.DLL") failed - This application has failed to start because the application configuration is incorrect. Reinstalling the application may fix this problem.


text:
Q: How could I install Elasticsearch 1.2.1 with homebrew I need old Elasticsearch for my work. but I couldn't install Elasticsearch 1.2.1 with brew
Development environment
$ brew --version
Homebrew 0.9.5 (git revision 567b; last commit 2015-12-23)

The procedure I tried
I tried the following process
$ brew search elasticsearch
elasticsearch ✔                              homebrew/versions/elasticsearch20
homebrew/versions/elasticsearch17 ✔

There is no elasticsearch10.
So, I tracked down this guidance.
Homebrew install specific version of formula?
And typed this command.
$ brew info elasticsearch
elasticsearch: stable 2.1.1, HEAD
Distributed search & analytics engine
https://www.elastic.co/products/elasticsearch
/usr/local/Cellar/elasticsearch/2.1.1 (52 files, 31M)
  Built from source
From: https://github.com/Homebrew/homebrew/blob/master/Library/Formula/elasticsearch.rb
==> Caveats
Data:    /usr/local/var/elasticsearch/elasticsearch_kent/
Logs:    /usr/local/var/log/elasticsearch/elasticsearch_kent.log
Plugins: /usr/local/Cellar/elasticsearch/2.1.1/libexec/plugins/
Config:  /usr/local/etc/elasticsearch/

To have launchd start elasticsearch at login:
  ln -sfv /usr/local/opt/elasticsearch/*.plist ~/Library/LaunchAgents
Then to load elasticsearch now:
  launchctl load ~/Library/LaunchAgents/homebrew.mxcl.elasticsearch.plist
Or, if you don't want/need launchctl, you can just run:
  elasticsearch

And also typed this command, however couldn't find out a key to installing elasticsearch version 1.2.1
$ brew versions elasticsearch
Error: The `versions` command is no longer supported.
You can use the homebrew-versions tap instead:
  https://github.com/Homebrew/homebrew-versions
Or use `brew log` to browse the git history.

I need some help to bridge myself to installing elasticsearch 1.2.1 with brew.
Could you steer my steps?

A: If you're just trying to do this for local development, then it's probably easier to just download and untar Elasticsearch into a directory.
$ cd /path/to/install/at
$ wget https://download.elastic.co/elasticsearch/elasticsearch/elasticsearch-1.2.1.tar.gz
$ tar -xf elasticsearch-1.2.1.tar.gz
$ cd elasticsearch-1.2.1

Once untarred, you can optionally delete the tarball:
$ rm elasticsearch-1.2.1.tar.gz

From there, it's just a matter of configuring (as desired) and starting Elasticsearch.
$ vi config/elasticsearch.yml
$ bin/elasticsearch

Note: Elasticsearch 1.2.1 is an extremely old version. I strongly recommend that you upgrade to a more recent release to gain reliability and security. For example, ES 1.2.1 uses MVEL scripting, which is bad at best.
For your production scenario (after New Years, of course), you can easily perform a rolling restart from ES 1.2.1 to ES 1.7.4 to gain a lot of features and stability without much risk. If you have dedicated master nodes, then I recommend starting with them first to get a few extra benefits upfront.


text:
Q: Using Landau-Zener formula in closed system I have read arXiv:1001.3322 and the wikipedia page of Landau-Zener formula and I have the following questions.
In a closed system of two-level system:

*

*Does the Landau-Zener formula come from the Landau–Zener approximation only? What other approximation was also made in order for it not to fail?

*Can I apply Landau-Zener formula for a particular portion of the whole quantum annealing time only, but not the whole quantum annealing process, or for negative infinity to positive infinity? Is there a bound of how small the time difference has to be taken?

*I cannot find similar formula for the case of energy level crossing? Why does energy level crossing prohibit us from calculating such probability?


text:
Q: webpack-dev-server - support for POST, PUT, Delete Methods using proxy I am using webpack-dev-server as a proxy to my original API URL to avoid CORS related issues and dynamically pointing to Dev, UAT, Mock server URL based on the environments.
For Mock dev - I prefer to use the JSON from the local file system and it servers its purpose for all the GET request.
How to to add support for 'POST, PUT, DELETE' so that the local JSON can be served directly?
One possible approach may be - Overriding the HTTP Request methods to GET as I am not passing any payload. But I can't find any configuration for that.
Below is the current configuration :
if (IS_MOCK_SERVER) {
    devServer.proxy = {
        '/api': {
            target: 'http://localhost:9090/data',
            secure: false,
            pathRewrite: function(req, options) {
                return req + '.json'
            }
        }
    }
} else {
    devServer.proxy = {
        '/api': {
            target: 'http://dev-server-url.com',
            secure: false
        }
    }
}

I tried digging into the official documents, but didn't get much support on this topic.
The Webpack dev server makes use of http-proxy-middleware to optionally proxy requests to a separate, possibly external, backend server.

A: As the Webpack dev server internally makes use of http-proxy-middleware to optionally proxy requests to other servers.
So, I opened a ticket at : https://github.com/chimurai/http-proxy-middleware/issues/151
Would be looking for a better solution in future.
But for time being, I found one workaround for the requirement/problem by Overriding the HTTP Method in API Util itself before passing it to Webpack-dev-server.
// Convert all the Request Method to Get ***ONLY IF*** MOCK-Server is running
if (process.env.IS_MOCK_SERVER) {
    payload.method = 'get';
}

A: after much tinkering found this setup which i'm using to convert all requests to "GET" using the onProxyReq event in http proxy middleware. i'm using it in context of angular cli proxy setup, but will work same for any webpack dev server instance
onProxyReq: function(proxyReq, req, res) {
    // convert all api requests (POST/PUT/DELETE) to GET so they work in webpack dev server for mocking
    proxyReq.method =  'GET';
}

https://github.com/nodejitsu/node-http-proxy#listening-for-proxy-events


text:
Q: FragmentPagerAdapter getItem error with ListFragment I've looked at quite a lot of code and can't figure this out. http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html
It has to be something simple.
I'm showing most of the code. The error is in the next section.
    public class MainActivity extends FragmentActivity implements
    ActionBar.TabListener {

public static final int TAB_COUNT = 3;
public static InputMethodManager inputManager;

SectionsPagerAdapter mSectionsPagerAdapter;
ViewPager mViewPager;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mSectionsPagerAdapter = new SectionsPagerAdapter(
            getSupportFragmentManager());

    // Set up the action bar.
    final ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(mSectionsPagerAdapter);

    // When swiping between different sections, select the corresponding
    // tab.
    mViewPager
            .setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
                @Override
                public void onPageSelected(int position) {
                    actionBar.setSelectedNavigationItem(position);
                }
            });

    // For each of the sections in the app, add a tab to the action bar.
    for (int i = 0; i < mSectionsPagerAdapter.getCount(); i++) {

        actionBar.addTab(actionBar.newTab()
                .setText(mSectionsPagerAdapter.getPageTitle(i))
                .setTabListener(this));
    }

    // To control keyboard pop-up
    inputManager = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

}
    @Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public void onTabUnselected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
}

@Override
public void onTabSelected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
    // When the given tab is selected, switch to the corresponding page in
    // the ViewPager.
    mViewPager.setCurrentItem(tab.getPosition());
}

@Override
public void onTabReselected(ActionBar.Tab tab,
        FragmentTransaction fragmentTransaction) {
}

This is where my error is.
case 1 of getItem, Type mismatch: Cannot convert from MainActivity.HistoryFragment to Fragment. it is telling me to either change method return type to HistoryFragment or change return type of newInstance() to Fragment. Where I can't do either. Other examples I've seen look almost identical to my code. I have tried with and without passing an argument.
    public class SectionsPagerAdapter extends FragmentPagerAdapter {

    public SectionsPagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int i) {
        switch (i) {
        case 0:
            Fragment tipCalc = new TipCalcFragment();
            return tipCalc;
        case 1:
            // Fragment history = new HistoryFragment();
            return HistoryFragment.newInstance(i); //ERROR HERE
        case 2:
            Fragment stats = new StatsFragment();
            return stats;
        }
        return null;
    }

And my HistoryFragment that extends ListFragment. In the end it won't be pulling from the String[] values but from database resources. I just wanted to setup a structure first and see it/play with the layout.
    public static class HistoryFragment extends ListFragment {
    // public HistoryFragment() {
    // }

    String[] values = new String[] { ... };

    static HistoryFragment newInstance(int num) {
        HistoryFragment history = new HistoryFragment();

        Bundle args = new Bundle();
        args.putInt("num", num);

        history.setArguments(args);

        return history;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.history, container, false);

        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setListAdapter(new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_list_item_1, android.R.id.text1,
                values));
    }
}

A: I figured it out after getting some sleep. I was importing android.app.ListFragment instead of android.support.v4.app.ListFragment

A: I think you will have to typecast to fragment before returning. So try this
Fragment history = HistoryFragment.newInstance(i);
return  history;


text:
Q: Grep out the last matching line of a text file which line contains a given string, and doesn't start with another string I would like to analyze a log file, and grepping for an IP address. Log file looks like:
<date> -> <IP address>

for example:
2016-06-02 11:46:33 +0200 -> 86.171.55.134

So I would like to select the last line which contains a given IP, and the line doesn't start with the today date (2016-06-02), my first attempt unfortunately doesn't work:
tac logfile.txt|grep -P  '^(?<!2016-06-03).*?86.171.55.134'

This way I succeeded to make it work, but I would like to work out a more general way, where I can use .* or .*? instead of 19 points, because sometimes there are more and unknown length data between the two pattern:
tac logfile.txt|grep -aP -m1 '(?<!2016\-06\-03)...................86.171.55.134'

Here 5000 actual line of log data to play with:
http://www.filefactory.com/file/2sdj77aqflxp/5000.txt
Only the IP addresses were faked.

A: ^(?<!2016-06-03).*?86.171.55.134 this regex will never work, lets break it down to understand:
^                # Start of line
 (?<!2016-06-03) # Negative look behind searching for 2016-06-03

Can there be anything before start of line?
You might want to try to change it to a look ahead:
tac logfile.txt | grep -P '^(?!2016-06-03).*?86.171.55.134'

Or with sed:
tac logfile.txt | sed -n '/^2016-06-03/!{/86\.171\.55\.134/p}'

And if you only want the first (last because of tac) match:
tac logfile.txt | sed -n '/^2016-06-03/!{/86\.171\.55\.134/{p;q}}'

A: This will grep for the lines having IP in it, and then remove the lines having todays date. (Generalized way) and head to chop only the first one of it.
tac data |grep  "86.171.55.134" |grep -v "`date +%Y-%m-%d`" |head -1
2016-06-02 11:46:33 +0200 -> 86.171.55.134


text:
Q: How to select columns from a different places of a large data frame Hi I have a pandas data frame with about 85 columns . I want to create a data frame using 2nd column and  30-45 columns. I tried with .iloc but gives me a error. Your advice much appreciated
df.iloc[:,(2,[30:45])]


text:
Q: Is it possible to use DistributedDataParallel with PyTorch Estimator We know that Horovod is suppported. Is there an example script which uses DistributedDataParallel and Pytorch estimator?

A: You should be able to specify nccl or gloo as distributed data parallel backend, in addition to MPI with Horovod. See the distributed_training parameter of PyTorch Estimator.


text:
Q: Do I still need to use data-ng with AngularJS or can I drop the data-? In my application data-ng is used everywhere. Can someone tell me why the data- is needed? I read something about HTML5 validation however if I do not care if it is fully validated or not and if I am using browsers that are IE8 and above then do I still need to use the data- ?

A: data-* is only there to enforce validation - if you don't care, there is nothing wrong with just using ng-* directives.


text:
Q: How do I round a Vector3F to an integer vector? I am currently making a program to build up and knock down blocks. It's simple but fun. I have gotten pretty far but have hit a snag.
So far, I have it so that when I click, it creates a block at the position I am looking at, either on another block or the ground. This is achieved through the use of ray tracing from the camera and creating a block at a Vector3F created from the collision between the ray and the other object. What I can't do is round the Vector3F so that the numbers are all single digit integers. Does anyone know how to achieve this?

A: You can use Math.round():
http://docs.oracle.com/javase/6/docs/api/java/lang/Math.html#round(float)
Examples:1:
// It will round the floats in Vector3F and leave the results as floats
Vector3F vect = new Vector3F(2.3f, 1.114124f, 0f);
vect.x = Math.round(vect.x); // 2f
vect.y = Math.round(vect.x); // 1f
vect.z = Math.round(vect.x); // 0f

2:
// It will round the floats in Vector3F and leave the results as ints
Vector3F vect = new Vector3F(2.3f, 1.114124f, 0f);
int x = Math.round(vect.x);
int y = Math.round(vect.x);
int z = Math.round(vect.x);

There is also more info: How to convert float to int with Java


text:
Q: What happens between a java controller and jsp I have a java controller.In this controller i have a string array("Cities") which consisits of nearly 3000 strings. Now my problem is when i am sending it to the JSP page and trying it to display, it s taking too much time.
My Observations :
1) First i thought database access, from where i am fetching these cities is taking time. But it s not.
2)Second i thought displaying these cities in the dropdown is taking time. But it is not
So i would like to know what is reali happening to the data between a controller and jsp. What process is going on between
 models.put("cities", cities);
 return new  ModelAndView("traning_management", models);

variable cities contains nearly 3000 cities.

A: The ModelAndView constructor is harmless. It stores the view name and copies the provided map entries into a LinkedHashMap (in your case there is only one entry, an array of name strings).


text:
Q: No data received in POST I am trying to upload a file to server. Here is my form code.
<form method="POST" action="<%request.getContextPath();%>/OPMS/webl" enctype="multipart/form-data">

<input type="hidden" name="handler" value="fileupload" />
<input type="hidden" name="user" value="${dev.getUserId()}" />
<input type="file" id="fileLoader" name="files" title="Load File" />
<button type="button" class="btn btn-primary" onClick="openFileChooser();"> Choose File</button>
<button type="submit" class="btn btn-primary"> Upload </button>
</form>

The problem is i can't get data from the attributes. When i check the handler it return null. But if i change method to GET i can view the parameters in the request correctly but get won't work for the type of form enctype used.

A: If you are just looking to get the job done, I recommend Ravishanker Kusuma's Hayageek jQuery File Upload plugin:
http://hayageek.com/docs/jquery-upload-file.php
He breaks down the process into three simple steps, that basically look like this:

    <link href="http://hayageek.github.io/jQuery-Upload-File/uploadfile.min.css" rel="stylesheet">  // (1)

       // (1)

Upload
  // (2)

The final step is to have the PHP file specified in the jQuery code (in this case my_php_processor.php) to receive and process the file:
my_php_processor.php:
<?php
    $output_dir = "uploads/";
    $theFile = $_FILES["myfile"]["name"];
    move_uploaded_file($_FILES["myfile"]["tmp_name"],$output_dir.$fileName);

Note the relationship between myfile in the PHP ($_FILES["myfile"]), and the filename specified in the jQuery code block.