text:
Q: How to change the colour SVG during Page Render ? First of all I know how to change the color of SVG dynamically. I have used the solution from this question:
jQuery SVG image replacement
But my scenario is different.
On my page I have several icons (SVGs) and there is a color picker. The user can change the of icons using colorpicker.
All works fine.
Now I want to generate the PDF of the whole page with the color of icons selected by the user.
I am using third party PDF generation library that takes my page URL and generates the PDF of that. But the problem is that the color does not get applied to the icons and PDF is generated. I know the cause of this problem because as on document ready I convert all the SVG img tags to actual SVG tags and then apply the color to them chosen by the user. This all happens after the page has rendered.
But the PDF generation library does not wait for this process to complete and generates the PDF before all the SVGs images are converted to SVGs and color is applied to them.
I don't know to first wait for whole process to complete and then generate its PDF.
I have tried caching of the page but that does not help either.
Any help would be highly appreciated.
Thanks

A: I did that.
The solution was to wrap the code in IIFE so that it executes immediately on page load rather than on ready event of the DOM.


text:
Q: How can I show an image in a NSView using an CGImageRef image I want to show an image in NSview or in the NSImageView. In my header file I have
@interface FVView : NSView
{
    NSImageView *imageView;
}
@end

here is what I been trying to do in my implementation file:
- (void)drawRect:(NSRect)dirtyRect
{
    [super drawRect:dirtyRect];

    (Here I get an image called fitsImage........ then I do)

    //Here I make the image
    CGImageRef cgImage = CGImageRetain([fitsImage CGImageScaledToSize:maxSize]);

    NSImage *imageR = [self imageFromCGImageRef:cgImage];
    [imageR lockFocus];

    //Here I have the view context
    CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];

    //Here I set the via dimensions
    CGRect renderRect = CGRectMake(0., 0., maxSize.width, maxSize.height);

    [self.layer renderInContext:ctx];
    [imageR unlockFocus];

    CGContextDrawImage(ctx, renderRect, cgImage);
    CGImageRelease(cgImage);
}

I don't get anything in the NSview window when I run the script. No errors at all I just can't see what I'm doing wrong. My Xcode version in 5.1.1
I'm trying to learn how to manipulate CGImageRef and view it in a window or nsview.
Thank you.

A: I'm not quite sure what exactly your setup is. Drawing an image in a custom view is a separate thing from using an NSImageView. Also, a custom view that may (or may not) be layer-backed is different from a layer-hosting view.
You have a lot of the right elements, but they're all mixed up together. In no case do you have to lock focus on an NSImage. That's for drawing into an NSImage. Also, a custom view that subclasses from NSView doesn't have to call super in its -drawRect:. NSView doesn't draw anything.
To draw an image in a custom view, try:
- (void) drawRect:(NSRect)dirtyRect
{
    CGImageRef cgImage = /* ... */;
    NSSize maxSize = /* ... */;
    CGContextRef ctx = (CGContextRef)[[NSGraphicsContext currentContext] graphicsPort];
    CGRect renderRect = CGRectMake(0., 0., maxSize.width, maxSize.height);
    CGContextDrawImage(ctx, renderRect, cgImage);
    CGImageRelease(cgImage);
}

If you have an NSImageView, then you don't need a custom view or any drawing method or code. Just do the following at the point where you obtain the image or the information necessary to generate it:
NSImageView* imageView = /* ... */; // Often an outlet to a view in a NIB rather than a local variable.
CGImageRef cgImage = /* ... */;
NSImage* image = [[NSImage alloc] initWithCGImage:cgImage size:/* ... */];
imageView.image = image;
CGImageRelease(cgImage);

If you're working with a layer-hosting view, you just need to set the CGImage as the layer's content. Again, you do this whenever you obtain the image or the information necessary to generate it. It's not in -drawRect:.
CALayer* layer = /* ... */; // Perhaps someView.layer
CGImageRef cgImage = /* ... */;
layer.contents = (__bridge id)cgImage;
CGImageRelease(cgImage);

redpajama_set_name: RedPajamaStackExchange


text:
Q: Apply background color to parent table th only I have a table structure, where I can't access jsp file to add class files. I have to manage it through CSS. In this case, I need to apply background color for first table all th's. Not to nested table th's. How can we do this with CSS? Example : http://jsfiddle.net/qdDnJ/

A: As per i understand may you can write like this:
tr th{
    background:red;
}
tr table th{
    background:none;
}

Check this http://jsfiddle.net/qdDnJ/2/

A: Distinguish first table's th from the second table's th.
Edited after comment:
See here, http://jsfiddle.net/qdDnJ/25/
I have assumed that div is parent container of first table.
You can replace it with table's parent.
e.g. If body is parent, css should be,
    body > table > tbody > tr > th {
      background-color:red;
    }

A: You could do this:
table th:first-child {
    background: red;
}
table table th:first-child {
    background: none;
}

I would just give the outer table a class and use this:
table.class-name th:first-child {
    background: red;
}

A: The simplest way I know is to use the child selector
#yourtableId > tbody > tr > th { background: red; }

Demo

A: Every body tried many things to achieve the target as per the question.
but as per the HTML we can just write the following css and avoid child th to get background-color..
in this solution we do not need any id and class or any thing accept the .gap class. Even if this class is not there we can apply the css.
check the demo
HERE is the CSS with .gap class
table th {background-color:red;}
table td.gap tr th {background:none;}

HERE is the CSS without .gap class
table th {background-color:red;}
table td tr th {background:none;}


text:
Q: Simple username and password application in Python I'm trying to build a simple login and password application using a dictionary. It works fine except the part where it checks if the login matches the password (in the bottom where it says "Login successful!").
If I were to create login 'a' and password 'b', and then create login 'b' and password 'a', it would log me in if I tried to log in with login 'a' and password 'a'. It just checks if those characters exist somewhere in the dictionary, but not if they are a pair.
Any suggestions how to fix this?
users = {}
status = ""

while status != "q":
    status = raw_input("Are you a registered user? y/n? Press q to quit: ")

    if status == "n": #create new login
         createLogin = raw_input("Create login name: ")

         if createLogin in users: # check if login name exist in the dictionary
             print "Login name already exist!\n"
         else:
             createPassw = raw_input("Create password: ")
             users[createLogin] = createPassw # add login and password
             print("\nUser created!\n")

    elif status == "y": #login the user
        login = raw_input("Enter login name: ")

        if login in users:
           passw = raw_input("Enter password: ")
           print

           if login in users and passw in users: # login matches password
               print "Login successful!\n"

        else:
            print
            print("User doesn't exist!\n")

Edit
Now that this is working, I'm trying to divide the application to three functions, for readability purposes. It works, except that I get infinite loop.
Any suggestions why?
users = {}
status = ""

def displayMenu():
    status = raw_input("Are you a registered user? y/n? Press q to quit: ")
    if status == "y":
        oldUser()
    elif status == "n":
        newUser()

def newUser():
    createLogin = raw_input("Create login name: ")

    if createLogin in users: # check if login name exists
        print "\nLogin name already exist!\n"
    else:
        createPassw = raw_input("Create password: ")
        users[createLogin] = createPassw # add login and password
        print("\nUser created!\n")

def oldUser():
    login = raw_input("Enter login name: ")
    passw = raw_input("Enter password: ")

    # check if user exists and login matches password
    if login in users and users[login] == passw:
        print "\nLogin successful!\n"
    else:
        print "\nUser doesn't exist or wrong password!\n"

while status != "q":
    displayMenu()

A: Right now you are checking if the given password, passw, matches any keys in users (not right). You need to see if the password entered matches that particular user's password. Since you have already checked if the username exists in the dictionary's keys you don't have to check again, so try something like:
if passw == users[login]:
    print "Login successful!\n"

EDIT:
For your updated code, I'm going to assume by "infinite loop" you mean that you cannot use q to exit the program. It's because when you're inside displayMenu, you save user input in a local variable named status. This local variable does not refer to the same status where you are checking,
while status != "q":

In other words, you are using the variable status in two different scopes (changing the inner scope does not change the outer).
There are many ways to fix this, one of which would be changing,
while status != "q":
    status = displayMenu()

And adding a return statement at the end of displayMenu like so,
return status

By doing this, you are saving the new value of status from local scope of displayMenu to global scope of your script so that the while loop can work properly.
Another way would be to add this line to the beginning of displayMenu,
global status

This tells Python that status within displayMenu refers to the global scoped status variable and not a new local scoped one.

A: change
if login in users and passw in users: # login matches password

to
if users[login] == passw: # login matches password

Besides, you should not tell the hackers that "User doesn't exist!". A better solution is to tell a generall reason like: "User doesn't exist or password error!"

A: Please encrypt you passwords in database if you go put this online.
Good work.
import md5
import sys
# i already made an md5 hash of the password: PASSWORD
password = "319f4d26e3c536b5dd871bb2c52e3178"
def checkPassword():
    for key in range(3):
        #get the key
        p = raw_input("Enter the password >>")
        #make an md5 object
        mdpass = md5.new(p)
        #hexdigest returns a string of the encrypted password
        if mdpass.hexdigest() == password:
            #password correct
            return True
        else:
            print 'wrong password, try again'
    print 'you have failed'
    return False

def main():
    if checkPassword():
        print "Your in"
        #continue to do stuff

    else:
        sys.exit()
if __name__ == '__main__':
    main()

A: usrname = raw_input('username   :     ')
if usrname == 'username' :
    print 'Now type password '

else :
    print 'please try another user name .this user name is incorrect'

pasword = raw_input ('password     :    ')
if pasword  == 'password' :
    print ' accesses granted '
    print ' accesses granted '
    print ' accesses granted '
    print ' accesses granted '
    print 'this service is temporarily unavailable'

else :
    print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
    print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
    print 'INTRUDER ALERT !!!!' , 'SYSTEM LOCKED'
    exit()

A: This is a very simple one based on the one earlier for a single user with improved grammar and bug fixes:
print("Steam Security Software ©")
print("-------------------------")
print("<<<<<<<<<Welcome>>>>>>>>>")
username = input("Username:")
if username == "username" :
    print ("Now type password")

else :
    print ("please try another user name. This user name is incorrect")

password = input ("Password:")
if password  == "password" :
    print ("ACCESS  GRANTED")
    print ("<<Welcome Admin>>")
    #continue for thins like opening webpages or hidden files for access

else :
    print ("INTRUDER ALERT !!!!" , "SYSTEM LOCKED")
    exit()


text:
Q: How to generate QR code together with the image in a center how I can generate QR code in react js or node js?
Maybe you know a library or package for generating QR code together with the image in a center?)
Example

A: This function will create qrcode with a logo at centre.
const qrcode= require('qrcode');

const getQRcodeImage = async () => {
    try {
        let canvas=await qrcode.toCanvas(`my sample text`);

        //adding a log at center
        const imgDim={width:30,height:30}; //logo dimention
        var context = canvas.getContext('2d');
        var imageObj = new Image();
        imageObj.src = './images/logo.png';
        imageObj.onload = function() {
          context.drawImage(imageObj,
          canvas.width / 2 - imgDim.width / 2,
          canvas.height / 2 - imgDim.height / 2,imgDim.width,imgDim.height);
        };
        return canvas;
    }catch (e) {
        console.error(e);
        return "";
    }
}

Usage:
$(document).ready(function () {
    getQRcodeImage().then(res=>{$("#qrcodeAuth").html( res);});
}


text:
Q: Is there a function to check a set of events/random variables are mutually independent? Say, 5 random variables A,B,C,D,E which can take values either 0 or 1.
I have the theoretical population chances for the 32 cases of P(A,B,C,D,E). Obviously they add up to 1.
How to check if A,B,C,D,E are mutually independent.
 0 0 0 1 0   ->   0.039026946
 0 0 0 0 0   ->   0.221152694
 0 0 0 0 1   ->   0.000000000
 0 0 0 1 1   ->   0.000000000
 0 0 1 0 0   ->   0.081381771
 0 0 1 0 1   ->   0.000000000
 0 0 1 1 0   ->   0.014361489
 0 0 1 1 1   ->   0.000000000
 0 1 0 0 0   ->   0.126588070
 0 1 0 0 1   ->   0.000000000
 0 1 0 1 0   ->   0.022339071
 0 1 0 1 1   ->   0.000000000
 0 1 1 0 0   ->   0.046583025
 0 1 1 0 1   ->   0.000000000
 0 1 1 1 0   ->   0.008220534
 0 1 1 1 1   ->   0.000000000
 1 0 0 0 0   ->   0.174007266
 1 0 0 0 1   ->   0.000000000
 1 0 0 1 0   ->   0.030707165
 1 0 0 1 1   ->   0.000000000
 1 0 1 0 0   ->   0.064032769
 1 0 1 0 1   ->   0.000000000
 1 0 1 1 0   ->   0.011299900
 1 0 1 1 1   ->   0.000000000
 1 1 0 0 0   ->   0.099601970
 1 1 0 0 1   ->   0.000000000
 1 1 0 1 0   ->   0.017576818
 1 1 0 1 1   ->   0.000000000
 1 1 1 0 0   ->   0.036652435
 1 1 1 0 1   ->   0.000000000
 1 1 1 1 0   ->   0.006468077
 1 1 1 1 1   ->   0.000000000

A: The multiway chi-square test computes the marginal chances of each variable and compares the given chances to the products of the marginal chances: by definition, the variables are independent if and only if every one of the joint chances equals the product of the marginal chances.  Thus, if we convert this information into the format expected by your statistical software's contingency table independence test, all we need do is verify that the chi-squared statistic is zero.  This is sufficient because the chi-squared statistic is a sum of squares of residuals; when it is zero, every residual must be zero, whence independence holds.

Here is an example in R.  It multiplies all the probabilities by a sufficiently large number to make them all integral, which is what a chi-squared test assumes it will be given (it "thinks" these are counts).
m = matrix(c(0, 0, 0, 1, 0, 0.039026946,
0, 0, 0, 0, 0, 0.221152694,
0, 0, 0, 0, 1, 0,
0, 0, 0, 1, 1, 0,
0, 0, 1, 0, 0, 0.081381771,
0, 0, 1, 0, 1, 0,
0, 0, 1, 1, 0, 0.014361489,
0, 0, 1, 1, 1, 0,
0, 1, 0, 0, 0, 0.12658807,
0, 1, 0, 0, 1, 0,
0, 1, 0, 1, 0, 0.022339071,
0, 1, 0, 1, 1, 0,
0, 1, 1, 0, 0, 0.046583025,
0, 1, 1, 0, 1, 0,
0, 1, 1, 1, 0, 0.008220534,
0, 1, 1, 1, 1, 0,
1, 0, 0, 0, 0, 0.174007266,
1, 0, 0, 0, 1, 0,
1, 0, 0, 1, 0, 0.030707165,
1, 0, 0, 1, 1, 0,
1, 0, 1, 0, 0, 0.064032769,
1, 0, 1, 0, 1, 0,
1, 0, 1, 1, 0, 0.0112999,
1, 0, 1, 1, 1, 0,
1, 1, 0, 0, 0, 0.09960197,
1, 1, 0, 0, 1, 0,
1, 1, 0, 1, 0, 0.017576818,
1, 1, 0, 1, 1, 0,
1, 1, 1, 0, 0, 0.036652435,
1, 1, 1, 0, 1, 0,
1, 1, 1, 1, 0, 0.006468077,
1, 1, 1, 1, 1, 0), nrow=6)

data <- data.frame(t(m))
xt <- xtabs(~ X1+X2+X3+X4+X5, data=data)
xt[1:32] <- data$X6 * 10^8
    summary(xt)$statistic

The output is zero, confirming independence.


text:
Q: java: check if WGS84 point is within a polygon if not get the distance as mentioned in the title I'm searching for a possibillity to check if a given point in wgs84-format is within an given polygon and if not I want to find the shortest distance from that point to the polgon. Maybe there exists any library.
Thank you for the help
Greetings

A: Check out the Java Topology Suite. This has a point in polygon function, and distance functions, among many others. To check if a point is inside a polygon it doesn't really matter what the coordinate system is.
http://www.vividsolutions.com/jts/JTSHome.htm
http://en.wikipedia.org/wiki/JTS_Topology_Suite
If you want to convert from one coordinate system to another, have a look at:
http://en.wikipedia.org/wiki/JTS_Topology_Suite
Both of these libraries (JTS in the guise of the C++ port, GEOS) form part of the very popular Postgis extension to Postgres, if you ever want to move you spatial analysis to a database.

A: You can also use GeoTools (http://www.geotools.org/). They are an excellent open-source Java library for geospatial data.


text:
Q: passing '' as 'this' argument discards qualifiers [-fpermissive] I have this error on my code:
passing 'const Auteur' as 'this' argument discards qualifiers [-fpermissive]

Located on auteur.getNom(), on that line:
cout << titre << ", " << auteur.getNom() << ", en " << langue << endl;

The type of auteur is const Auteur&
Here is the Oeuvre class, where the error is located :
class Oeuvre {
    private:
    string titre;
    const Auteur& auteur;
    string langue;

    public:
    Oeuvre(string titre, const Auteur& auteur, string langue)
    : titre(titre), auteur(auteur), langue(langue) {}
    string getTitre() { return titre; }
    const Auteur& getAuteur() { return auteur; }
    string getLanguage() { return langue; }
    void affiche() {

        cout << titre << ", " << auteur.getNom() << ", en " << langue << endl; // the error is here
    }
    ~Oeuvre() {
        cout << "L'oeuvre \"" << titre << ", " << auteur.getNom() << ", en " << langue << "\" n'est plus disponible." << endl;
    }
    Oeuvre(Oeuvre const&) = delete;
};

And here is the Auteur class, the type of auteur:
class Auteur {
    private:
    string nom;
    bool prime;

    public:
    Auteur(string nom, bool prime = false)
    : nom(nom), prime(prime) {}
    string getNom() { return nom; }
    bool getPrix() { return prime; }
    Auteur(Auteur const&) = delete;
};

A: Why you get this error: Imagine auteur.h just had this
class Auteur {
    private:
    string nom;
    bool prime;

    public:
    Auteur(string nom, bool prime = false)
    : nom(nom), prime(prime){}
    string getNom();
    bool getPrix();
    Auteur(Auteur const&) = delete;
};

and the implementations were in a different file (auteur.cpp). This is a very common thing to do
The compiler doesnt know if getnom will change the Autuer object it is called on. getnom could say:
   string Autuer::getnom(){
       string temp = name;
       name = "";
       return name;
   }

it doesnt know. Then you try to do this
   const Auteur& auteur;
   autuer.getnom();

this cant work because you have said that autuer is const. You know getnom is read only but the compiler doesnt (I know it could do by looking at the .h file in this case , but it doesnt)
So you have to promise the compiler that getnom doesnt change the object its called on
string getNom() const;


text:
Q: How to display a background image larger than the actual div size? I want to display image larger then the actual div size and scroll it inside the div.
The image should be behind the div and part of the image are hide.
To view all the image i should scroll it.
demojsFFidle

#wrapper {
  border: 1px solid black;
  width:80px;
  height;80px;
  margin:10px;
  z-index:4;
}
img {
    border: 1px solid red;
   display: inline-block;
}

many thanks.

A: add overflow: scroll; to your div. This will allow the user to scroll inside of the div to view the background.

A: To display the image behind the div... try using z-index property...and also add a scroll to your css...
something like...
your_css {
z-index:2;
overflow:scroll;
}

might help...

A: You may add overflow:auto; to the #wrapper div.
This way, the scroll bar will be shown only when it is needed.
You may add overflow:hidden; if you do not want to show the scroll bars at all.
JSFiddle : http://jsfiddle.net/BZeLR/30/


text:
Q: Getting an error when exiting program after loading .wav using NAudio I just found NAudio the other day and I've been playing with it.  I have written a simple windows form program that has a load button (loads a specific .wav song), and buttons to play, pause, stop, fade the sound in (my own added functionality using timers and a gradually increasing volume), and fade the sound out.  I also have a trackbar control to handle the volume.  I created a wrapper class to put all the NAudio stuff in, as well as to add-on extra functionality like fade-in/out and event notifications when a sound starts or is paused.
Okay, all said, that works fine.  The program correctly loads, plays, pauses, stops, and fades in and out.  The volume trackbar correctly reflects the volume level of the song being played.  That much works, but I do have two problems.
First, after I click the "Load" button to load the sound in and then do all the playing I want to (or not), when I exit the program I get the following popup error message ("Assertion failed"): "AcmStreamHeader dispose was not called at AcmStreamHeader.Finalize()".  This is one of those "Abort, Retry, Ignore" popups, but after a few seconds it disappears and the project terminates.  (Note: The load functionality creates the DirectSoundOut and calls CreateInputStream... taken directly from the NAudio samples on the site.  It also sets up event handlers for the defined events, but that probably doesn't matter.)
In the class destructor, I make the following calls:
mainOutputStream.Close();
mainOutputStream.Dispose();
waveOutDevice.Dispose();

But I still get the error.  This is the big one, and I'll ask the other question in another thread.  Any idea why this is is happening and how I can stop it?
I am running VS 10 on Windows 7 32-bit.

A: The most likely reason for the error (it's actually just a Debug.Assert - it doesn't occur in release builds of NAudio), is mainOutputStream was assigned to more than one WaveStream and when you changed it, you didn't Dispose the old one. When you exit the app, the Garbage Collector runs and this Debug.Assert fires.
A couple of other points:

*

*There is no need to call mainOutputStream.Close and Dispose. Just call one of them.

*Your cleanup code should not be in a class destructor (finalizer?), but in a Dispose method, for a Form, in the Closing or Closed event handler.

*Edit: Another possible reason is that you derived from WaveStream and in your overriden Dispose method didn't call Dispose on any WaveStreams that are members of class.


text:
Q: Python raise Error proper use Description:
I've read a lot opinions about checking value type in python and most said that you shouldn't check type, but instead use try and except.
I want to make clear few things.
Questions:
When I have method like this:
def set_age(self, age):
    self._age = age

I can't let user pass any types other then int because later in code it can cause some harder to debug bugs.
And according to Python methodology I can't check type.
So how should I do it with try in the proper way?
def set_age(self, age):
    try:
        age = int(age)
    except TypeError:
        raise TypeError('First parameter must be of int type.')
    self._age = age

Or just
def set_age(self, age):
    self._age = int(age)

and let Python raise errors on it's own.
I know it might be silly questions, I just want to make sure.

A: Python will raise an appropriate error if it's not an integer, so there is no need to put your own over the top of it.
Let's step back a bit though, as there are other problems here. getters and setters are really unpythonic - either just use an attribute, or use properties.
In this case, I think you are still thinking in the wrong way. The reason we don't type check in Python is because we shouldn't care what type something is, just if it will work in the given situation. Making everything the type you think it should be as soon as you get it is essentially type checking.
You say it will make it harder to debug, but that's not really the experience most people have. Duck typing is designed to allow anything that can do the job do the job. Converting everything to an int limits your program. The problem isn't here, the problem is with your code that is passing something that doesn't make sense to your class. In my experience, this is actually a really rare thing to do - you don't tend to throw random stuff at classes and see what sticks.
So, my suggestion here is that you use an attribute - just do x.age = ... instead of using set_age() or anything like that. If you really need to have an int (as in, only whole numbers make sense), then use a property and call int() in the setter, leaving the error to propagate to the caller if it happens.

A: One tenet of python is that "its better to ask forgiveness than permission". Many times the exceptions generated by the functions your function calls are sufficient to tell the caller of your function what went wrong.
That being said, in some cases I'll throw a more specific exception where the semantics to the caller don't entirely line up. one example I can think of is where I am examining a json response and I get a "key error" on one element of the dictionary. This typically means whatever request I sent out failed, and I therefore can't find the data I need. I'll in turn throw something more semantically in line with my function like "Query Failed".
Most times though exceptions thrown by called functions "type error" or "io error" should make perfect sense to the caller of my function so I don't bother catching and rethrowing.


text:
Q: How do I href to a file without locking it? I allow users to view a report on my IIS website with:
Check Matching (Regularly through day)

If a user leaves a report open - I am unable to update it.
Is there a flag to add to the above html such that user open a read-only copy?
Or is there another way to ensure multiple users can view the file but still leave it update-able?

A: You can force to you user for download a copy of file.You can use the download  attribute.
Example:
Check Matching (Regularly through day)

OR


text:
Q: Visual studio for some reason says that i don't have netcore installed even tho i do (macos) i wanted to make pong with monogame using C# but VS told me otherwise...

Error: .NET Core 6.0 SDK is required to build this application, and is not installed.
Install the latest update to the .NET Core 6.0 SDK by visiting https://aka.ms/vs/mac/install-netcore6 (Pong)

but it is installed, i just don't understand
i even reinstalled it, but it didn't work
(Yeah, i know, installing .net on mac IS a stupid idea, but i didn't find a way to get monogame running with mono.)
You already know that i just wanted no errors but i got one


text:
Q: Add a row with total in Log Analytics Kusto query I query a request log for a summary of status codes. However I would like to add a row at the end of the results, showing the total number of requests. How do I add such a row?
Current query (simplified)
MyLog
| summarize count() by responseCode

Current result looks like

responseCode
count

200
1000

404
20

500
100

I would like to have the totals like this

responseCode
count

200
1000

404
20

500
100

total
1120

A: you could try this:
MyLog
| summarize c = count() by responseCode
| as hint.materialized=true T
| union (T | summarize c = sum(c) by responseCode = "total")

or this:
MyLog
| summarize c = count() by responseCode
| union (print responseCode = "total", c = toscalar(MyLog | count))

if you want to keep the 'total' row last, you can order the unioned data set. for example:
MyLog
| summarize c = count() by responseCode
| extend _o = 0
| union (
    print responseCode = "total",
          c = toscalar(MyLog | count),
          _o = 1
)
| order by _o asc, c desc
| project-away _o


text:
Q: Error:(17, 21) error: no suitable method found for add(int, ExampleItemFragment) I'm using Android Studio.  I'm trying to develop an app where one fragment holds a list, and tapping an item displays another fragment with details. I built the list, following the tutorial available at: https://www.airpair.com/android/list-fragment-android-studio
I was planning on taking the code apart again after seeing how it ran. However, when I tried to run it (at step 6, where the basic list should be functioning), I got the error:
Error:(17, 21) error: no suitable method found for add(int,ExampleItemFragment)
method FragmentTransaction.add(Fragment,String) is not applicable
(argument mismatch; int cannot be converted to Fragment)
method FragmentTransaction.add(int,Fragment) is not applicable
(argument mismatch; ExampleItemFragment cannot be converted to Fragment)

in
package com.example.brittany.fragmentlistexample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends AppCompatActivity {

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

    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.container, new ExampleItemFragment())
                .commit();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
}

Where & how should I implement this .add() method, or should I do something to the object I'm passing in order to make an inherited .add() accept it? The class ExampleItemFragment already extends Fragment.
ExampleItemFragment's code (mostly untouched from the default code):
package com.example.brittany.fragmentlistexample;

import android.app.Activity;
import android.os.Bundle;
import android.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.TextView;
import android.widget.Toast;

import com.example.brittany.fragmentlistexample.dummy.DummyContent;

import java.util.ArrayList;
import java.util.List;

public class ExampleItemFragment extends Fragment implements AbsListView.OnItemClickListener {
private List exampleListItemList; // at the top of your fragment list

// TODO: Rename parameter arguments, choose names that match
// the fragment initialization parameters, e.g. ARG_ITEM_NUMBER
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";

// TODO: Rename and change types of parameters
private String mParam1;
private String mParam2;

private OnFragmentInteractionListener mListener;

/**
 * The fragment's ListView/GridView.
 */
private AbsListView mListView;

/**
 * The Adapter which will be used to populate the ListView/GridView with
 * Views.
 */
private ListAdapter mAdapter;

// TODO: Rename and change types of parameters
public static ExampleItemFragment newInstance(String param1, String param2) {
    ExampleItemFragment fragment = new ExampleItemFragment();
    Bundle args = new Bundle();
    args.putString(ARG_PARAM1, param1);
    args.putString(ARG_PARAM2, param2);
    fragment.setArguments(args);
    return fragment;
}

/**
 * Mandatory empty constructor for the fragment manager to instantiate the
 * fragment (e.g. upon screen orientation changes).
 */
public ExampleItemFragment() {
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    exampleListItemList = new ArrayList();
    exampleListItemList.add(new ExampleListItem("Example 1"));
    exampleListItemList.add(new ExampleListItem("Example 2"));
    exampleListItemList.add(new ExampleListItem("Example 3"));
    mAdapter = new ExampleListAdapter(getActivity(), exampleListItemList);

    if (getArguments() != null) {
        mParam1 = getArguments().getString(ARG_PARAM1);
        mParam2 = getArguments().getString(ARG_PARAM2);
    }

    // TODO: Change Adapter to display your content
    mAdapter = new ArrayAdapter<DummyContent.DummyItem>(getActivity(),
            android.R.layout.simple_list_item_1, android.R.id.text1, DummyContent.ITEMS);
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_exampleitem, container, false);

    // Set the adapter
    mListView = (AbsListView) view.findViewById(android.R.id.list);
    ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

    // Set OnItemClickListener so we can be notified on item clicks
    mListView.setOnItemClickListener(this);

    return view;
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        mListener = (OnFragmentInteractionListener) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement OnFragmentInteractionListener");
    }
}

@Override
public void onDetach() {
    super.onDetach();
    mListener = null;
}

@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    ExampleListItem item = (ExampleListItem)this.exampleListItemList.get(position);
    Toast.makeText(getActivity(), item.getItemTitle() + " Clicked!"
            , Toast.LENGTH_SHORT).show();
    if (null != mListener) {
        // Notify the active callbacks interface (the activity, if the
        // fragment is attached to one) that an item has been selected.
        mListener.onFragmentInteraction(DummyContent.ITEMS.get(position).id);
    }
}

/**
 * The default content for this Fragment has a TextView that is shown when
 * the list is empty. If you would like to change the text, call this method
 * to supply the text it should use.
 */
public void setEmptyText(CharSequence emptyText) {
    View emptyView = mListView.getEmptyView();

    if (emptyView instanceof TextView) {
        ((TextView) emptyView).setText(emptyText);
    }
}

/**
 * This interface must be implemented by activities that contain this
 * fragment to allow an interaction in this fragment to be communicated
 * to the activity and potentially other fragments contained in that
 * activity.
 *

 * See the Android Training lesson Communicating with Other Fragments for more information.
 */
public interface OnFragmentInteractionListener {
    // TODO: Update argument type and name
    public void onFragmentInteraction(String id);
}

}

A: You have to import the Fragment from the support library, not from the android.widget. Use import android.support.v4.app.Fragment; in your fragment.


text:
Q: Finding a set of edges to add to a set of graphs to satisfy connectivity constraints I have a set of N undirected, disconnected graphs that share the same M vertices, but have different edges. I also have a set of constraints for each graph of the form "V0 is connected to V1" or "V3 is not connected to V5" etc.
I want to find a set of edges such that adding those edges to every graph causes every graph to satisfy its constraints.
For a simple example, consider, for two given graphs with vertices V0, V1, V2, V3, V4:

*

*a graph G with one edge (V0, V1) and the constraint "V0 is connected to V2"

*a graph H with edge (V1, V3) and the constraints "V2 is connected to V4", "V0 is not connected to V2"

With these given parameters, the problem is satisfiable by adding the edges {(V1, V2), (V3, V4)} to both of the graphs.

After failing to solve the problem with a script, I reached for z3 to help, but I've run into trouble trying to express connectivity. My current solution consists of an unquantified formula with only boolean terms:

*

*ci,j,k for each pair of vertices i, j representing whether they are connected in graph k with added edges from the solution

*gi,j,k for each pair of vertices i, j representing whether the edge between them is given in graph k

*si,j for each pair of vertices i, j representing whether adding an edge between them is part of the solution

and assertions:

*

*gi,j,k if the edge (i, j) is given in graph k

*¬gi,j,k if the edge (i, j) is not given in graph k

*ci,j,k if the graph k requires i and j to be connected

*¬si,j ∧ ¬ci,j,k if the graph k requires i and j to not be connected

*si,j ⇒ ci,j,k for all graphs k

*ci,j,k = si,j ∨ gi,j,k ∨ ((si,z ∨ gi,z,k) ∧ cz,j,k) for all vertices i, j, z and graphs k
The last clause, however, does not seem to work as intended for expressing connectivity and z3 is returning sat but the clearly necessary si,j are false in the resulting model.
Here's the shortest I could manage to make a minimal example of the problem:
from itertools import combinations

from z3 import *

vertices = [0, 1, 2, 3, 4]
edges = [tuple(sorted(edge)) for edge in list(combinations(vertices, 2))]

graphs = {
    "G": [(0, 1)],
    "H": [(1, 3)],
}

facts = Solver()

connected_in_graph = {}
for graph in graphs:
    for edge in edges:
        connected_in_graph[(graph, edge)] = Bool(f"{edge}_conn_in_{graph}")

solution_edges = {}
graph_given_edges = {}
for edge in edges:
    edge_in_solution = Bool(f"{edge}_in_solution")
    solution_edges[edge] = edge_in_solution
    for graph in graphs:
        given = Bool(f"{graph}_{edge}_given")
        graph_given_edges[(graph, edge)] = given
        if edge in graphs[graph]:
            facts.append(given)
        else:
            facts.append(Not(given))

facts.append(
    connected_in_graph[("G", (0, 2))],
    connected_in_graph[("H", (2, 4))],
    Not(connected_in_graph[("H", (0, 2))]),
)

for edge in edges:
    for graph in graphs:
        ors = [
            solution_edges[edge],
            graph_given_edges[(graph, edge)],
        ]
        for vertex in vertices:
            if vertex in edge:
                continue
            l_edge = tuple(sorted((edge[0], vertex)))
            r_edge = tuple(sorted((edge[1], vertex)))
            ors.append(
                And(
                    Or(
                        solution_edges[l_edge],
                        graph_given_edges[(graph, l_edge)],
                    ),
                    connected_in_graph[(graph, r_edge)],
                )
            )
        facts.append(connected_in_graph[(graph, edge)] == Or(*ors))

print(facts.check())
model = facts.model()
for edge in edges:
    c = solution_edges[edge]
    if model[c]:
        print(c)

I suppose what I'd actually need to express, rather than that last constraint, is relations:
c2(i, j, k, through) = si,j ∨ gi,j,k ∨ (∃z. z ∉ (ignored ∪ {i, j}) ∧ (si,z ∨ gi,z,k) ∧ c(z, j, k, ignored ∪ {i}))
c(i, j, k) = c2(i, j, k, {})
However, reducing that to just unquantified boolean terms would obviously take somewhere on the order of M! time and space.
Is there a better way of expressing the existence of a path in a graph in SAT/SMT, or perhaps a better way of solving this problem altogether?

Alias's suggestion to use transitive closure seems to be the solution to this, but I seem to have trouble using it properly. My revised code:
from itertools import combinations

from z3 import *

vertices = [0, 1, 2, 3, 4]
edges = [tuple(sorted(edge)) for edge in list(combinations(vertices, 2))]

graphs = {
    "G": [(0, 1)],
    "H": [(1, 3)],
}

facts = Solver()

vs = {}
VertexSort = DeclareSort("VertexSort")
for vertex in vertices:
    vs[vertex] = Const(f"V{vertex}", VertexSort)
facts.add(Distinct(*vs.values()))

given = {}
directly_connected = {}
tc_connected = {}
for graph in graphs:
    given[graph] = Function(
        f"{graph}_given", VertexSort, VertexSort, BoolSort()
    )
    directly_connected[graph] = Function(
        f"directly_connected_{graph}", VertexSort, VertexSort, BoolSort()
    )
    tc_connected[graph] = TransitiveClosure(directly_connected[graph])

in_solution = Function("in_solution", VertexSort, VertexSort, BoolSort())

for edge in edges:
    # commutativity
    facts.add(
        in_solution(vs[edge[0]], vs[edge[1]])
        == in_solution(vs[edge[1]], vs[edge[0]])
    )
    for graph in graphs:
        # commutativity
        facts.add(
            given[graph](vs[edge[0]], vs[edge[1]])
            == given[graph](vs[edge[1]], vs[edge[0]])
        )
        facts.add(
            directly_connected[graph](vs[edge[0]], vs[edge[1]])
            == directly_connected[graph](vs[edge[1]], vs[edge[0]])
        )
        # definition of direct connection
        facts.add(
            directly_connected[graph](vs[edge[0]], vs[edge[1]])
            == Or(
                in_solution(vs[edge[0]], vs[edge[1]]),
                given[graph](vs[edge[0]], vs[edge[1]]),
            ),
        )
        if edge in graphs[graph]:
            facts.add(given[graph](vs[edge[0]], vs[edge[1]]))
        else:
            facts.add(Not(given[graph](vs[edge[0]], vs[edge[1]])))

facts.append(
    tc_connected["G"](vs[0], vs[2]),
    tc_connected["H"](vs[2], vs[4]),
    Not(tc_connected["H"](vs[0], vs[2])),
)

print(facts.check())
model = facts.model()
print(model)
print(f"solution: {model[in_solution]}")

Prints sat but finds the definition in_solution = [else -> False] rather than the solution I'm looking for. What am I doing wrong?

A: As suggested by @alias in this comment, solving the problem was made possible by using transitive closures.
By:

*

*defining relations givenG(v1, v2) and directly_connectedG(v1, v2) for each graph G and a relation in_solution(v1, v2) where v1, v2 are of an enumeration type with constructors for each vertex

*asserting directly_connectedG(v1, v2) = in_solution(v1,
v2) ∨ givenG(v1, v2) for each v1, v2

*declaring a transitive closure TC_connectedG(v1, v2) for each graph G

*asserting constraints in terms of TC_connected
I got the solver to return a correct solution for all of my test cases.
The revised code:
from itertools import combinations

from z3 import *

vertices = [0, 1, 2, 3, 4]
edges = [tuple(sorted(edge)) for edge in list(combinations(vertices, 2))]

graphs = {
    "G": [(0, 1)],
    "H": [(1, 3)],
}

facts = Solver()

VertexSort = Datatype("VertexSort")
for vertex in vertices:
    VertexSort.declare(str(vertex))
VertexSort = VertexSort.create()

vs = {}
for vertex in vertices:
    vs[vertex] = getattr(VertexSort, str(vertex))

given = {}
directly_connected = {}
tc_connected = {}
for graph in graphs:
    given[graph] = Function(
        f"{graph}_given", VertexSort, VertexSort, BoolSort()
    )
    directly_connected[graph] = Function(
        f"directly_connected_{graph}", VertexSort, VertexSort, BoolSort()
    )
    tc_connected[graph] = TransitiveClosure(directly_connected[graph])

in_solution = Function("in_solution", VertexSort, VertexSort, BoolSort())

for edge in edges:
    # commutativity
    facts.add(
        in_solution(vs[edge[0]], vs[edge[1]])
        == in_solution(vs[edge[1]], vs[edge[0]])
    )
    for graph in graphs:
        # commutativity
        facts.add(
            given[graph](vs[edge[0]], vs[edge[1]])
            == given[graph](vs[edge[1]], vs[edge[0]])
        )
        facts.add(
            directly_connected[graph](vs[edge[0]], vs[edge[1]])
            == directly_connected[graph](vs[edge[1]], vs[edge[0]])
        )
        # definition of direct connection
        facts.add(
            directly_connected[graph](vs[edge[0]], vs[edge[1]])
            == Or(
                in_solution(vs[edge[0]], vs[edge[1]]),
                given[graph](vs[edge[0]], vs[edge[1]]),
            ),
        )
        if edge in graphs[graph]:
            facts.add(given[graph](vs[edge[0]], vs[edge[1]]))
        else:
            facts.add(Not(given[graph](vs[edge[0]], vs[edge[1]])))

facts.append(
    tc_connected["G"](vs[0], vs[2]),
    tc_connected["H"](vs[2], vs[4]),
    Not(tc_connected["H"](vs[0], vs[2])),
)

print(facts.check())
model = facts.model()
print(f"solution: {model[in_solution]}")


text:
Q: Send an SMS when an item is purchased in Prestashop I am using Prestashop. I would like to send an SMS when a user purchases an item. Could I use the Mvaayoo SMS integration API? How?
This is my PHP code to send an SMS:
<?php
    $ch = curl_init();
    $user="emailid@example:password;
    $receipientno="9995563285";
    $senderID="TEST SMS";
    $msgtxt="this is test message , test";
    curl_setopt($ch,CURLOPT_URL,  "http://api.mVaayoo.com/mvaayooapi/MessageCompose");
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, "user=$user&senderID=$senderID&receipientno=$receipientno&msgtxt=$msgtxt");
    $buffer = curl_exec($ch);
    if(empty ($buffer))
    { echo " buffer is empty "; }
    else
    { echo $buffer; }
    curl_close($ch);
?>

A: Placing API code for each events like User registration, new order, order status change will be heavy.
You can use any Free SMS Add-on like Spring Edge Prestashop sms add-on which will make your way easy.
Just need to install and configure events from Admin-Area:

*

*SMS on Order confirmation.

*SMS on Order shipment.

*SMS on User Registration.


text:
Q: spring mvc background image not working when url changes I am trying to give background. Image load properly when the url is (in login page)
/jobsspectrum/login

by using in profile page
<body background="resources/images/black.jpg">

But when the url changes the image does not load. eg.
/jobsspectrum/user/profile
because there is /user in the url before the page where i am using image in profile page.

the Error is
message /jobsspectrum/user/resources/images/black.jpg
description The requested resource is not available.

My image is under resources/images
It does not pick the resource when the url is not /jobsspectrum/
My resource handling class is :
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {

    registry.addResourceHandler("/resources/**").addResourceLocations("resources/");
    super.addResourceHandlers(registry);
}

I simple words the image is picked only in the front pages and when the user logins my url changes from /jobsspectrum/ to /jobsspectrum/user/** and the resource image part is not loaded properly.

A: Use absolute paths instead of relative ones.
With the JSTL:
<body background="<c:url value='/resources/images/black.jpg' />">

Or, without the JSTL:
<body background="${pageContext.request.contextPath}/resources/images/black.jpg">


text:
Q: How to accomplish SQL Server 2012+2014 high availability Maybe I'm searching for the wrong thing, but I can't see how I can do this.
I have two servers:

*

*Server A (has SQL Server 2012 installed)

*Server B (has SQL Server 2014 installed)

Server A provides an API via IIS. The code both inserts and gets data from the database depending on the API call.
Server B does exactly the same for its local database.
I would like to have it so that the two databases are consistent copies of each other. I do believe this is what HA accomplishes.
So a load balancer, for example, might direct API calls to A sometimes, and B sometimes, but the data needs to be consistent either way.
I found some documentation on HA for SQL Server 2012, but not on how to do this for a mixed environment of 2012 and 2014.
Any help or pointers to documentation would be great! Thanks.

A:
how to do this for a mixed environment of 2012 and 2014.

Doing HA in a mixed environment is a recipe for disaster because during disaster once you failover from lower (2012) to higher (2014) version, you cannot failback.
Since you are using Enterprise edition of SQL Server, you can leverage AlwaysON technology wherein you can configure writes occurring on Primary and reads on the secondary configured as readable secondary.
Thinking a bit more on what you mean by mixed, I presume that transactional replication would be much better from sql server 2014 as publisher and 2012 acting as subscriber.
The performance would be dependent on how big is the database, if you are replicating only the tables that you need or the entire database, the latency between the two servers as well as the amount of transactions that are occurring on your publisher.
Note that if you go with T-Rep, doing schema changes will require a new snapshot. Also there will be a distribution database created as a part of setting up T-Rep.


text:
Q: Java NullPointerException on serialization of TableModel when associated JTable is on visible JFrame A NullPointerException is thrown when trying to serialize a TableModel object while the associated JTable object is visible in a JFrame. I created a minimal, reproducible Example and will also include the Stack-Trace.
The Nullpointer is described like this:
Cannot invoke "javax.swing.JTable.getColumnModel()"
because "this.table" is null

But why is this method called anyway? I am serializing the Model, not the JTable.
When not using a JFrame, it works fine.
I hope someone can help. I am using AdoptOpenJDK14 (14.0.2.12-hotspot)
Here is the minimal, reproducible Example:
Serialization.java (Entrypoint of the Program)
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;

import javax.swing.JFrame;
import javax.swing.JTable;
import javax.swing.WindowConstants;

public class Serialization {

    public static void main(String[] args) throws Exception {

        MyAbstractModel model = new MyAbstractModel();
        JTable table = new JTable(model);

        // After creating the frame, putting in the table and setting it to visible the exception will be thrown when trying to serialize below
        JFrame frame = new JFrame();
        frame.add(table);
        frame.setSize(300,300);
        frame.setLocationRelativeTo(null);
        frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
        frame.setVisible(true);

        ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("some.dat"));
        oos.writeObject(model);
        oos.close();

    }
}

MyAbstractModel.java (The Model to Serialize)
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.swing.table.AbstractTableModel;

public class MyAbstractModel extends AbstractTableModel {

    private List<String> list = new ArrayList<>();

    public MyAbstractModel(){
        list = Collections.synchronizedList(new ArrayList<>());
        list.add("Test1");
        list.add("Test2");
        list.add("Test3");
        list.add("Test4");
    }

    @Override
    public int getRowCount() {
        return 10;
    }

    @Override
    public int getColumnCount() {
        return 3;
    }

    @Override
    public Object getValueAt(int rowIndex, int columnIndex) {
        return rowIndex + "-" + columnIndex;
    }

    @Override
    public String getColumnName(int column) {
        return "Column " + column;
    }

    @Override
    public Class<?> getColumnClass(int columnIndex) {
        return String.class;
    }

    @Override
    public boolean isCellEditable(int rowIndex, int columnIndex) {
        return false;
    }

    @Override
    public void setValueAt(Object aValue, int rowIndex, int columnIndex) {
        // TODO
    }
}

Some.java (Just a Serializable Test Object)
import java.io.Serializable;

public class Some implements Serializable {

    private static final long serialVersionUID = 1L;

    public final int num;
    public final String name;
    transient int ignoreNum;

    public Some(int num, String name, int ignoreNum) {
        this.num = num;
        this.name = name;
        this.ignoreNum = ignoreNum;
    }

    @Override
    public String toString() {
        return "Some{" +
                "num=" + num +
                ", name='" + name + '\'' +
                ", ignoreNum=" + ignoreNum +
                '}';
    }

}

This is the Stacktrace I got.

Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "javax.swing.JTable.getColumnModel()"
because "this.table" is null
at java.desktop/javax.swing.plaf.basic.BasicTableUI.getPreferredSize(BasicTableUI.java:1768)
at java.desktop/javax.swing.JComponent.getPreferredSize(JComponent.java:1680)
at java.desktop/javax.swing.JTable.setWidthsFromPreferredWidths(JTable.java:3205)
at java.desktop/javax.swing.JTable.doLayout(JTable.java:3117)
at java.desktop/java.awt.Container.validateTree(Container.java:1722)
at java.desktop/java.awt.Container.validateTree(Container.java:1731)
at java.desktop/java.awt.Container.validateTree(Container.java:1731)
at java.desktop/java.awt.Container.validateTree(Container.java:1731)
at java.desktop/java.awt.Container.validateTree(Container.java:1731)
at java.desktop/java.awt.Container.validate(Container.java:1657)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2762)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4844)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)
Exception in thread "AWT-EventQueue-0" java.lang.NullPointerException: Cannot invoke "javax.swing.JTable.getColumnModel()" because "this.table" is null
at java.desktop/javax.swing.plaf.basic.BasicTableUI.getPreferredSize(BasicTableUI.java:1768)
at java.desktop/javax.swing.JComponent.getPreferredSize(JComponent.java:1680)
at java.desktop/javax.swing.JTable.setWidthsFromPreferredWidths(JTable.java:3205)
at java.desktop/javax.swing.JTable.doLayout(JTable.java:3117)
at java.desktop/java.awt.Container.validateTree(Container.java:1722)
at java.desktop/java.awt.Container.validateTree(Container.java:1731)
at java.desktop/java.awt.Container.validateTree(Container.java:1731)
at java.desktop/java.awt.Container.validateTree(Container.java:1731)
at java.desktop/java.awt.Container.validateTree(Container.java:1731)
at java.desktop/java.awt.Container.validate(Container.java:1657)
at java.desktop/java.awt.Window.dispatchEventImpl(Window.java:2762)
at java.desktop/java.awt.Component.dispatchEvent(Component.java:4844)
at java.desktop/java.awt.EventQueue.dispatchEventImpl(EventQueue.java:772)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:721)
at java.desktop/java.awt.EventQueue$4.run(EventQueue.java:715)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:95)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:745)
at java.desktop/java.awt.EventQueue$5.run(EventQueue.java:743)
at java.base/java.security.AccessController.doPrivileged(AccessController.java:391)
at java.base/java.security.ProtectionDomain$JavaSecurityAccessImpl.doIntersectionPrivilege(ProtectionDomain.java:85)
at java.desktop/java.awt.EventQueue.dispatchEvent(EventQueue.java:742)
at java.desktop/java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:203)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:124)
at java.desktop/java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:113)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:109)
at java.desktop/java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.desktop/java.awt.EventDispatchThread.run(EventDispatchThread.java:90)


text:
Q: What's wrong with my string reversal function? (C#) char[] a = { 'o', 'r', 'a', 'n', 'g', 'e' };

for (int i = 0; i < a.Length/2; i++)
{
  a[i] = (char)(((uint)a[i])|((uint)a[a.Length-(i+1)]));
  a[a.Length-(i+1)] = (char)(((uint)a[i])^((uint)a[a.Length-(i+1)]));
  a[i] = (char)(((uint)a[i])^((uint)a[a.Length-(i+1)]));
}

I know how to implement this using standard .NET functionality and temp vars. I am just curious what specifically I am doing wrong in the above example that causes it not to work when the following works fine:
int a = 5;
int b = 10;

a = a | b;
b = a ^ b;
a = a ^ b;

Isn't the above string version just a series of those?

A: Hehe, there's no such thing as an OR/XOR/XOR swap - it should be a "triple xor" swap.
int a = 8, b = 10;
a ^= b;
b ^= a;
a ^= b;

I don't see why you want to use it (aside from the novelty value)

A: The reason it's not working is that you're using a bad example. You can't swap two values by using OR then XOR then XOR. It only worked in your example because 5 and 10 have no bits in common, so the first OR doesn't destroy any information:
a = 0101 #5
b = 1010 #10
# step 1 (OR into a)
a = 1111
b = 1010
# step 2 (XOR into b)
a = 1111
b = 0101
# step 3 (XOR into a)
a = 1010 #10
b = 0101 #5

But it won't work if they have any bits in common - let's try with 13 and 10:
a = 1101 #13
b = 1010 #10
# step 1 (OR into a)
a = 1111
b = 1010
# step 2 (XOR into b)
a = 1111
b = 0101
# step 3 (XOR into a)
a = 1010 #10
b = 0101 #5

Note that we now have the values 5 and 10 still, even though we started with 13 and 10. What you're looking for is a thrice-XOR swap:
a = 1101 #13
b = 1010 #10
# step 1 (XOR into a)
a = 0111
b = 1010
# step 2 (XOR into b)
a = 0111
b = 1101
# step 3 (XOR into a)
a = 1010 # 10
b = 1101 #13

A: It's destructive (because of the bitwise OR).  Why not use a temporary variable in your loop instead of the exclusive ORs:
int tmp = a[i];
a[i] = a[a.Length-(i+1)];
a[a.Length-(i+1)] = tmp;

In answer to your second part, what you were doing in binary is:
a = 0101;
b = 1010;
a = 0101 | 1010 === 1111;
...

When you OR the two values together, you destroy the original numbers.  It works with 5 & 10 because none of the bits are common between the two numbers.  When you do this with the following:
a = 0110;  // 6 (base ten)
b = 1010;  // 10 (base ten)
a = a | b; // this is now 1110, or 14 (base ten)

You can not recover 6 and 10 again, because OR was an irreversible operation.  Exclusive-OR is reversible.

A: Sorry if this is not the point of your question, but how about just:
 char[] a = { 'o', 'r', 'a', 'n', 'g', 'e' };
 a = Array.Reverse(a)

Am I missing something?

A: Others have already pointed out the correct solution using XOR operations... This isn't exactly an answer, but I thought I'd point you that the Interlocked.Exchange method is very suitable for this sort of task. (It performs the swap as an atomic operation and therefore works across threads, though that seems irrelevant here.) Nonetheless, I would almost always consider it the simplest/most elegant solution for swapping two variables.
Here's an example of how to use it with the code you posted.
char[] a = { 'o', 'r', 'a', 'n', 'g', 'e' };

for (int i = 0; i < a.Length/2; i++)
{
    a[a.Length-(i+1)] = Interlocked.Exchange(ref a[a.Length-(i+1)], a[i]);
}

Hope that helps, even if it isn't specifically an answer to your question...

A: List<char> characters = new List<char>();

characters.AddRange("string".ToCharArray());

characters.Reverse();

string reversed = new string(characters.ToArray());


text:
Q: Monitoring BATTERY_CHANGED with BroadcastReceiver and displaying with level-list not working Hello everyone I've been stick with this problem, and I can't see my mistake. I had used  before basicly for having different drawable bind to a specific level, nevertheless I am trying to use it within a BroadcastReceiver wich monitor battery changes, the problem is that I don't get any UI update when I called the setImageLevel change?
The Broadcast Receiver goes like this
public class BatteryReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        Log.d(LOG, "Fired Changed");
        int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, 0);
        int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, 100);

        int percent = (level * 100) / scale;

        imageBattery = (ImageView) findViewById(R.id.imageBatery);
        imageBattery.setImageLevel(percent);
        Log.d(LOG, "On UI running I am");

        // imageBattery.getDrawable().mutate();
        // imageBattery.invalidate();

        // Log.d(LOG,"DRawable: "+((LevelListDrawable)imageBattery.getDrawable()).getCurrent());

    }

}

The Log gets displayed but it does not change my ImageView if you can point me out in the right direction, or you have any insight on this issue?
Little bit of more info
Here is my Registration and unregistration both on the same activity as the BroadcastReceiver
@Override
public void onResume() {
    super.onResume();
    IntentFilter filter = new IntentFilter();
    filter.addAction("android.intent.action.BATTERY_CHANGED");
    registerReceiver(receiver, filter);
}

@Override
public void onPause() {
    super.onPause();
    unregisterReceiver(receiver);
}

How do I instatiate the ImageView Drawable:
<ImageView
            android:id="@+id/imageBatery"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:src="@drawable/battery_status" />

And also battery_status.xml is a drawable (I removed some of the drawable item because you get the idea I have from 0-100)

<item
    android:drawable="@drawable/stat_sys_battery_100"
    android:maxLevel="100"/>

<item
    android:drawable="@drawable/stat_sys_battery_90"
    android:maxLevel="90"/>

<item
    android:drawable="@drawable/stat_sys_battery_80"
    android:maxLevel="80"/>

A: Do You have your BroadcastReceiver inlined in Your Activity? If so, use 'MyActivity.this.runOnUiThread()` method to change Your views.

A: your problem is in images
LevelListDrawable doesn't append new image when level changed, it just shows the image for level you've set
try differen images and you'll see what I mean

A: try this in your onCreate:
    imageBattery = (ImageView) findViewById(R.id.imageBatery);
    for (int i = 0; i < 10; i++) {
        imageBattery.setImageLevel(i * 10);
    }

is smth changed ?


text:
Q: Help with a summatory. Given $B=\{e_1,\dots,e_n\}$ a basis of a K-vector space $V$, and $f$ the only endomorphism such that
$f(e_i)=\begin{cases} e_1-e_2, & \mbox{if } i=1 \\ -e_{i-1}+e_i-e_{i+1}, & \mbox{if } 2 \le i \le n-1 \\ -e_{n-1}+e_n, & \mbox{if } i=n \end{cases} $
I have to prove that f is invertible iff $n \equiv 0,1\mod 3$.
If that's the case, show that
$f^{-1}(e_1)=\begin{cases} e_1+\sum_{k=1}^m (-1)^k(e_{3k}+e_{3k+1}) & \mbox{if } n=3m+1 \\ \sum_{k=1}^m (-1)^k(e_{3k-1}+e_{3k}) & \mbox{if } 2 \le i \le n-1 \end{cases}$
I've already proved that f is bijective iff $n \equiv 0,1 \mod3$, and now I'm proving the second part, with the case $n=3m+1$. Here's what I do.
Supose that $n=3m+1$. Using the definition of f:
$f(e_1+\sum_{k=1}^m (-1)^k(e_{3k}+e_{3k+1}))=\\
=f(e_1)+\sum_{k=1}^{m-1}(-1)^kf(e_{3k}+e_{3k+1})+(-1)^mf(e_{3m})+(-1)^mf(e_{3m+1})\\
=e_1-e_2+\sum_{k=1}^{m-1}(-1)^k(-e_{3k_1}-e_{3k+2})+(-1)^m(-e_{3m-1})$
From here I don't know how to continue.

A: Note that a lot of terms cancel due to the alternating sign:
$$
\sum_{k=1}^{m-1} (-1)^k( -e_{3k-1} - e_{3k+2} ) = e_2 - (-1)^{m-1} e_{3m-1}
= e_2 +(-1)^me_{3m-1}.
$$
Then
$$
f(e_1 + \sum(\dots)) = e_1.
$$


text:
Q: #if check (preprocessor macro) to differentiate between iPhone and iPad Is there a build preprocessor macro I can check, with #if or #ifdef to determine if my current Xcode project is being built for iPhone or iPad?
EDIT
As several answers have pointed out, often apps are universal, and the same binary can run on both devices. Conditional behavior between these very similar devices should be solved at runtime rather than compile time.

A: NSString *deviceType = [UIDevice currentDevice].model;

if([deviceType isEqualToString:@"iPhone"]) {
    //iPhone
}
else if([deviceType isEqualToString:@"iPod touch"]) {
    //iPod Touch
}
else {
    //iPad
}

You cannot, as far as I am concerned, use #if or #ifdef to do this but, it is supported because Obj-C is a strict superset of C.
Related:
Determine device (iPhone, iPod Touch) with iPhone SDK

A: There is no way to determine whether your app is built for iPhone or iPad. Preprocessor #if directives are resolved during build. Once your app is built and flagged as Universal, it has to run correctly on both devices. During building nobody knows where it will be installed later and one build can be installed on both.
However you may want to do one of these:

*

*Detect device model during runtime.
To do this, use [[UIDevice currentDevice] model] and compare to iPhone, iPod touch or iPad strings. This will return you correct device even when running in compatibility mode on iPad (for iPhone-only apps). This can be usefull for usage analytics.

*Detect user interface idiom during runtime.
This is what everyone checks for, when providing different content for iPhone and iPad. Use [[UIDevice currentDevice] userInterfaceIdiom] and compare to UIUserInterfaceIdiomPhone or UIUserInterfaceIdiomPad. You may want to make convenience methods like this:
@implementation UIDevice (UserInterfaceIdiom)

- (BOOL)iPhone {
    return (self.userInterfaceIdiom == UIUserInterfaceIdiomPhone);
}
+ (BOOL)iPhone {
    return [[UIDevice currentDevice] iPhone];
}

- (BOOL)iPad {
    return (self.userInterfaceIdiom == UIUserInterfaceIdiomPad);
}
+ (BOOL)iPad {
    return [[UIDevice currentDevice] iPad];
}

@end

Then you can use:
if ([[UIDevice currentDevice] iPhone]) { }
// or
if ([UIDevice iPhone]) { }
// or
if (UIDevice.iPhone) { }

A: Some ideas in the comment section of this blog
http://greensopinion.blogspot.com/2010/04/from-iphone-to-ipad-creating-universal.html
Mostly using
UI_USER_INTERFACE_IDIOM()

Such as:
#ifdef UI_USER_INTERFACE_IDIOM()
  #define IS_IPAD() (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad)
#else
  #define IS_IPAD() (false)
#endif

A: Updation for swift:
Couldn't use preprocessor. Make global function as
func IS_IPAD() -> Bool {
( return (UIDevice.respondsToSelector(Selector("userInterfaceIdiom"))) && (UIDevice.currentDevice().userInterfaceIdiom == UIUserInterfaceIdiom.Pad) )}

A: I use the following code for AppleTV 4 because UIUserInterfaceIdiomUnspecified, doesn't seem to work, nor can I find any other enums:
#ifdef TARGET_OS_IOS
CGSize result = [[UIScreen mainScreen] bounds].size;
    if(result.width == 1920) {
        NSLog(@"tvOS");
    }
#endif

I used to use this for iPad and such before the dark times, before the empire- OB1, hah good night.  But you can use this similar technique for other screen sizes you know of.


text:
Q: Microsoft Test Manager cannot install test agent on these machines I am trying to create a new environment using microsoft test manager. Unfortuntely I get the following error:
Microsoft Test Manager cannot install test agent on these machines. Possible causes:
- Machines are not running or they are not available on the network
- The File and Printer Sharing exception is not enabled on the machines.
Controller is up and running , the user and password is correct. Firewall is disabled. File and Printer sharing exception too.
I do not know what is going on. How could it be solved? Do not know how to go further with this.

A: Try running MTM as  Administrator. Also check the article on MSDN
https://social.msdn.microsoft.com/Forums/vstudio/en-US/a790f8d3-489d-4fd6-9204-2fb1f7e21b50/microsoft-test-manager-cannot-install-test-agent-on-these-machines?forum=vsmantest&tduid=(bbfad4796548274f6ccbc9c1b7d15461)(256380)(2459594)(XdSn0e3h3.k-lkj0MqSQojhOnvvQ2ym5yA)()


text:
Q: How to add an item to a list in python and save it My program is set up so I can add items to the lists from terminal but whenever I do this for example myFile.append('hello') it keeps it there but when I exit terminal and do it again 'hello' is deleted. Please help. Thank you!
Code
elif userInput in command:
    print("Okay, Initializing new command.\n\n")
    command1 = raw_input("Which command would you like to add?\nKeyword\nLater Versions\n ").lower()
    if command1 == 'keyword':
        print('You selected keyword, to exit press enter')
        command2 = raw_input("Which Keyword would you like to edit? ")
        if command2 == 'calc':
            command3 = raw_input("Which Keyword would you like to add? ")
            calc.append(command3)
            print(calc)

A: Try something like:
with open(myFile, 'a') as f:
    f.write('hello')

You can append to a list with.append but not a file. Instead, you can use the 'a' flag as above to append to the file myFile where myFile is a file path.
Update:
Based on your existing code and what you want to achieve, try this:
...

elif userInput in command:
    print("Okay, Initializing new command.\n\n")
    command1 = raw_input("Which command would you like to add?\nKeyword\nLater Versions\n ").lower()
    if command1 == 'keyword':
        print('You selected keyword, to exit press enter')
        command2 = raw_input("Which Keyword would you like to edit? ")
        if command2 == 'calc':
            command3 = raw_input("Which Keyword would you like to add? ")
            calc = 'path/to/file'
            with open(calc, 'a+') as f:
                f.write(command3 + '\n')
                f.seek(0) #This brings you back to the start of the file, because appending will bring it to the end
                print(f.readlines())

Basically, you are writing to a file, and printing back a list of all the words written to that file. The 'a+' flag will let you open a file for reading and writing. Also, instead of/in addition to printing the "list" with print(f.readlines()), you could assign it to a variable and have an actual python list object for manipulating later, if that is what you want: wordlist = f.readlines().
Also, to improve your fundamental understanding of the issue, you should probably check out this and this.
Update 2
If you need to have a Python list of keywords earlier in your code you could add:
 with open('wordlist.txt', 'a+') as f: #wordlist.txt can be changed to be another file name or a path to a file
     f.seek(0) #opening with `'a+'` because it will create the file if it does not exist,
               # and seeking because `'a+'` moves to the end of the file
     calc = f.readlines()

This will read a list of words from wordlist.txt and save them to an Python list called calc. Now since calc is an actual Python list object, you can use calc.append('whatever'). Later in your code, when you want to save all the keywords back to the persistent "list" (which is actually just a text file with words separated by newline ('\n'), you can do:
with open('wordlist.txt', 'w+') as f:
    for word in calc:
        f.write(word)
    f.seek(0)
    print(f.readlines())

This will overwrite your wordlist file with all the words currently in the calc list, and print out all the values to the console.
This is as good as I can do without really understanding how your program is supposed to work or writing it myself. Try to improve your understanding of Python file I/O; it is not so complicated with some practice, and will serve you well in the future for simple persistent data. I would also suggest going through a Python tutorial like this one on Codecademy to improve your general understanding of how Python works. I don't mean that as an insult; I did this tutorial myself a while ago, and it really helped me to create a good foundation of Python fundamentals. It also includes a lesson on file I/O. Good luck!


text:
Q: El archivo PHP no encuentra una clase, pero la clase está definida Tengo un archivo php llamado "purchase.controller.php" en el cual, dentro de una función llamada 'ctrCash' de la clase 'Purchases', paso variables a una función llamada 'ctrNewCashPurchase' de la clase 'CartController' que he definido. pero cuando ejecuto el proyecto, recibo el mensaje:

"Fatal error : Uncaught Error: Class 'CartModel' not found in ... "

Si hago un var_dump dentro de la función ctrNewCashPurchase, me doy cuenta de que estoy ingresando esa función, pero me dice que no reconoce 'CartModel' y no entiendo por qué.
Comparto el código del archivo "purchase.controller.php":
class CartController{

    static public function ctrNewCashPurchase($datos){

        $tabla = "compras";

        $respuesta = CartModel::mdlNewCashPurchase($tabla, $datos);

        if($respuesta == "ok"){

            $tabla = "comentarios";
            ModeloUsuarios::mdlIngresoComentarios($tabla, $datos);

        }

        return $respuesta;

    }

}

class Purchases {

    public function ctrCash (&$arrayCompleto, &$usuario, &$direccion1, &$direccion2, &$dia, &$hora, &$email, &$telefono, &$sesion){

        if(isset($usuario)){

             //Here I create an array
             for($i = 0; $i < count($arrayCompleto); $i++){

               $datos = array("idUsuario"=> $sesion,
                              "idProducto"=> $arrayCompleto[$i]["idProducto"],
                              "metodo"=> "Efectivo",
                              "email"=> $email,
                              "direccion"=> $direccion1,
                              "detalleDireccion"=> $direccion2,
                              "diaEnvio"=> $dia,
                              "horaEnvio"=> $hora,
                              "telefono"=> $telefono,
                              "pais"=> "ARG");

                }

             $respuesta = CartController::ctrNewCashPurchase($datos);

          }

     }

}

Comparto el código del archivo "purchase.model.php", donde defino la clase CartModel:
class CartModel{

    static public function mdlNewCashPurchase($tabla, $datos){

        $stmt = Conexion::conectar()->prepare("INSERT INTO $tabla (id_usuario, id_producto, metodo, email, direccion, pais, detalleDireccion, diaEnvio, horaEnvio, telefono) VALUES (:id_usuario, :id_producto, :metodo, :email, :direccion, :pais, :detalleDireccion, :diaEnvio, :horaEnvio, :telefono)");

        $stmt->bindParam(":id_usuario", $datos["idUsuario"], PDO::PARAM_INT);
        $stmt->bindParam(":id_producto", $datos["idProducto"], PDO::PARAM_INT);
        $stmt->bindParam(":metodo", $datos["metodo"], PDO::PARAM_STR);
        $stmt->bindParam(":email", $datos["email"], PDO::PARAM_STR);
        $stmt->bindParam(":direccion", $datos["direccion"], PDO::PARAM_STR);
        $stmt->bindParam(":pais", $datos["pais"], PDO::PARAM_STR);
        $stmt->bindParam(":detalleDireccion", $datos["detalleDireccion"], PDO::PARAM_STR);
        $stmt->bindParam(":diaEnvio", $datos["diaEnvio"], PDO::PARAM_STR);
        $stmt->bindParam(":horaEnvio", $datos["horaEnvio"], PDO::PARAM_STR);
        $stmt->bindParam(":telefono", $datos["telefono"], PDO::PARAM_INT);

        if($stmt->execute()){

            return "ok";

        }else{

            return "error";

        }

        $stmt->close();

        $tmt =null;
    }

}

Y agrego este otro archivo llamado 'aux.php' en caso de que influya en algo en el error que me causa. Aquí muestro cómo envío los parámetros de 'purchase.controller.php' dentro de la función 'ctrCash'
    if(isset($_POST['usuario'])){

    require ('purchases.controller.php');

    $arrayCompleto = json_decode($_POST['arrayCompleto'], true);

$usuario = $_POST['usuario'];
$direccion1 = $_POST['direccion1'];
$direccion2 = $_POST['direccion2'];
$dia = $_POST['dia'];
$hora = $_POST['hora'];
$email = $_POST['email'];
$telefono = $_POST['telefono'];
$sesion = $_POST['sesion'];

 $payments = new Purchases();
$payments -> ctrCash($arrayCompleto, $usuario, $direccion1, $direccion2, $dia, $hora, $email, $telefono, $sesion);

    }

A: El archivo "shopping.controller.php" tiene esta línea:
require ('purchases.controller.php');

Que como sabrás incluye y evalúa el archivo especificado.
Pero en la clase "purchase.controller.php" no has incluido el archivo "purchase.model.php".
require ('purchases.model.php');


text:
Q: Android Service with AlarmManager Advice Currently I have an app that is setup in two sections, the activity portion adds tasks and task completion times to a database and then I have a service that runs in the background polling the database and handling the task when the task completion time is reached.
Currently my service is using a private inner class that extends thread and I am making use of thread.sleep to re-run the task handling methods.  This inner class is called from the onStartCommand() in the service class. the thread.sleep is set to either 15 minutes or if the task will need to be handled before that it will sleep until the time this task needs to be handled.  At this point everything is working correctly however I have a few issues that I am running into.

*

*The service needs to run at specific times that are always changing depending on when the task needs to be completed even when the phone goes to sleep.

*I need to make sure that there is as little impact on battery as possible.
Now through research I found that with the use of alarm manager I can start this service only when I need to, which is great, however because I would be constantly changing the time intervals based on when certain tasks had to be handled I'm not sure this would be the right course of action.
I've also read about wakelocks which I really don't want to have to use unless I absolutely need to.
I am more or less looking for advice on how I should structure the service in my app and how it handles these tasks.

A:
Now through research I found that with the use of alarm manager I can start this service only when I need to, which is great, however because I would be constantly changing the time intervals based on when certain tasks had to be handled I'm not sure this would be the right course of action.

AlarmManager is definitely the correct solution. Keeping a service alive all of the time, mostly watching the clock tick, is embarrassingly wasteful of RAM.
You will not "be constantly changing the time intervals", because you will only have one alarm event, set to whenever the next task is to occur. That will be a one-shot alarm, not a recurring alarm. When the event occurs, in addition to doing the work, you schedule the next event. The only edge case is if the user adds a task that is to be completed sooner than the formerly-soonest task, in which case you will need to cancel and reschedule that alarm event.

I've also read about wakelocks which I really don't want to have to use unless I absolutely need to.

You do not have a choice, with your current or an AlarmManager implementation, if you want to make sure that you can do your periodic work without interruption. The goal is to only have an active WakeLock during the actual pulse of work, and to release the WakeLock and shut down the service when that pulse of work is completed. You can see an implementation of this pattern in WakefulIntentService.


text:
Q: custom field value date convert to unix timestamp problems For some reason, I'm having difficulty converting a date value stored in a meta field to a unix timestamp (and back again). If I save the date as a string it all works fine, but if I convert it to a timestamp using strtotime it won't save the value.
My working code looks like this:
<?php

add_action( 'add_meta_boxes', 'rs_add_date' );
function rs_add_date() {
    add_meta_box( 'rs_add_date', 'Date', 'rs_add_date_create_meta_box', 'concerts', 'normal', 'high' );
}
function rs_add_date_create_meta_box( $post ) {
    $date = get_post_meta($post->ID, 'rs_date', true);
    echo 'Choose a date for the event';
    wp_nonce_field( plugin_basename(__FILE__), 'rs_date_nonce');
?>

Date (dd/mm/yyyy) <input type="text" name="rs-date" id="rs-date" value="<?php echo $date; ?>">

<?php
}

// Save the new meta

add_action('save_post', 'rs_date_save_meta');
function rs_date_save_meta( $post_id ) {

    if(!wp_verify_nonce( $_POST['rs_date_nonce'], plugin_basename(__FILE__) ) )
        return;
    if(!current_user_can('edit_posts') )
        return;
    $date = $_POST['rs-date'];
    update_post_meta($post_id, 'rs_date', $date);
}
?>

But if I change it to the following it won't work:
<?php
add_action( 'add_meta_boxes', 'rs_add_date' );
function rs_add_date() {
    add_meta_box( 'rs_add_date', 'Date', 'rs_add_date_create_meta_box', 'concerts', 'normal', 'high' );
}
function rs_add_date_create_meta_box( $post ) {
    $date = get_post_meta($post->ID, 'rs_date', true);
    $date = time("d/m/Y", $date);
    echo 'Choose a date for the event';
    wp_nonce_field( plugin_basename(__FILE__), 'rs_date_nonce');
?>

Date (dd/mm/yyyy) <input type="text" name="rs-date" id="rs-date" value="<?php echo $date; ?>">

<?php
}

// Save the new meta

add_action('save_post', 'rs_date_save_meta');
function rs_date_save_meta( $post_id ) {

    if(!wp_verify_nonce( $_POST['rs_date_nonce'], plugin_basename(__FILE__) ) )
        return;
    if(!current_user_can('edit_posts') )
        return;
    $date = $_POST['rs-date'];
    $date = strtotime($date);
    update_post_meta($post_id, 'rs_date', $date);
}
?>

Scratching my head here! Cheers

A: Looking at http://www.php.net/manual/en/datetime.formats.date.php I dont think strtotime will convert a DD/MM/YYYY to time correctly.
However it can do MM/DD/YYYY or YYYY/MM/DD.
Try using the date format of YYYY/MM/DD
Or if thats not to your liking then you can use the same date format but you will have to, on save, split up the date and convert it to unix datestamp a diff way. You could use:
$date = "dd/mm/yyyy";
$date = explode("/", $date);
$date = mktime(0, 0, 0, (int)$date[1], (int)$date[0], (int)$date[2]);


text:
Q: R: multiplot for plotLearnerPrediction ggplot objects of MLR firing errors in RStudio The article here demonstrates the MLR package. The plotLearnerPrediction function returns an ggplot object by this. I tried the multiplot function provided for ggplot2 objects below but my RStudio crashes with it. I am able to plot things without RStudio

so
How can I plot many plotLearnerPrediction objects in the same picture side-by-side in RStudio?
library(mlr)

# Multiple plot function here failing with p1,p2,p3,... in RStudio
# but I am able to run this thing without RStudio.
# http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/

learners = list( makeLearner("classif.svm", kernel = "linear"),
                 makeLearner("classif.svm", kernel = "polynomial"),
                 makeLearner("classif.svm", kernel = "radial"),
                 "classif.qda",
                 "classif.randomForest",
                 "classif.knn" )

p1<-plotLearnerPrediction(learner = learners[[1]], task = iris.task)
p2<-plotLearnerPrediction(learner = learners[[2]], task = iris.task)
p3<-plotLearnerPrediction(learner = learners[[3]], task = iris.task)
p4<-plotLearnerPrediction(learner = learners[[4]], task = iris.task)
#p5<-plotLearnerPrediction(learner = learners[[5]], task = iris.task)
#p6<-plotLearnerPrediction(learner = learners[[6]], task = iris.task)

#multiplot(p1, p2, p3, p4, p5, p6, cols=2) #failing in Rstudio
#multiplot(p1, p2, p3, p4, cols=1) #failing in Rstudio but not without it

RStudio version
> version
               _
platform       x86_64-apple-darwin15.6.0
arch           x86_64
os             darwin15.6.0
system         x86_64, darwin15.6.0
status
major          3
minor          4.1
year           2017
month          06
day            30
svn rev        72865
language       R
version.string R version 3.4.1 (2017-06-30)
nickname       Single Candle

R on the command line
$ R --version
R version 3.4.1 (2017-06-30) -- "Single Candle"
Copyright (C) 2017 The R Foundation for Statistical Computing
Platform: x86_64-apple-darwin15.6.0 (64-bit)

A: You can use library gridExtra:
    require(gridExtra)
    library(gridExtra)
    p1 <- plotLearnerPrediction(learner = learners[[1]], task = iris.task)
    ...
    p4 <- plotLearnerPrediction(learner = learners[[4]], task = iris.task)
    grid.arrange(p1, p2, p3, p4, ncol = 2, now = 2)


text:
Q: How do I know exact extension of a Word document in Java I have a program which copies a word file (docx/doc) as follows:
A source file which is doc/docx is first copied to a temporary raw file where the extension is lost. Now the contents of this temporary raw file are to be copied to a file with suitable extension(doc/docx). Since, nothing is known at this point about the original file, it is required here to derive extension of the source Word Document from its contents.
   InputStream in = new FileInputStream ( src );
   OutputStream out = new FileOutputStream ( dst );
    byte [] buf = new byte [1024];
    int len;
    while ( ( len = in.read ( buf ) ) > 0 ) {
        out.write ( buf, 0, len );
    }

Destination dst is a raw file without any extension (say, 'sample-file'), which I can't change. The sourcesrc may be a 'doc' or a 'docx' type.
Now, as an output, I need to copy the contents of dst to a Word Document with proper format as of src(this 'proper format' is important here, otherwise the document is rendered useless). Since dst doesn't have any extension, I cannot find the file format by just looking at the name. Is there a way, I can retrieve the file extension from file contents? Hopefully, Word document must have some meta-data containing this information.

A: http://www.forensicswiki.org/wiki/Word_Document_%28DOC%29
This link details lots of different file types. It describes the headers of both DOC and DOCX files, so you should be able to parse the files and determine what kind they are.
Looking at the link, .doc files are OLE Compound Files, the file should have the following binary header:
d0 cf 11 e0 a1 b1 1a e1

In constrast, .docx files will have the binary signature:
50 4b

Also, DOCX files are in ZIP format, in which the first two bytes are the letters PK (after ZIP's creator, Phil Katz).
Hope this helps!

A: If you read the DOCX files contents in binary format the first two characters will be "PK". You can use the same to identify if its a DOCX file or not.


text:
Q: Получить расстояние между центром и краем объекта Мне нужно получить расстояние между краем и центром объекта.
Рисунок который показывает чего я хочу:

A: Размер объекта напрямую зависит от 2х вещей - от самой mesh'ы и его transform'а. Чтобы получить этот размер, нужно найти его AABB (англ. Axis Aligned Bounding Box).
В конкретно Unity его можно получить двумя способами:

*

*Mesh.bounds

*Renderer.bounds
Первый возвращает AABB без трансформации матрицей transform'а, что нам совершенно не подходит, а вот второй возвращает уже измененный AABB.

// AABB
Bounds bounds = GetComponent<Renderer>().bounds;
// Размеры по всем трем осям
Vector3 extents = bounds.extents;

Debug.Log(extents);

extents - это и есть искомое расстояние от центра объекта до его краев по всем осям, если брать конкретно этот вопрос, то расстояние от центра до правого/левого края будет extents.x.


text:
Q: Keep my form when echoing For some reason whenever this script get's execited to the point where it is suppose to echo out "IT WORKED!", the message displays but the form that is suppose to be above it disapears.
My Code:
<?php

    $message    = $_REQUEST['message'];
    $email      = $_REQUEST['email'];
    $times      = $_REQUEST['times'];
    $subject    = $_REQUEST['subject'];
    $to         = $_REQUEST['to'];

    for ($i=1; $i<=$times; $i++) {
        mail( "$to", "$subject", $message, "From:" . rand() . "@$email" ) ;
    }

?>

    <form method="POST" id="email">

Email Bomber

        <fieldset id="inputs">
            <input name="times" type="text" placeholder="How Many Emails" autofocus required>
            <input name="email" type="text" placeholder="Email Suffix" autofocus required>
            <input name="to" type="email" placeholder="Who Do You Want To Email" autofocus required>
            <input name="subject" type="text" placeholder="Email Subject" autofocus required>
            <textarea name="message" placeholder="The Email Message" rows="15" cols="40"></textarea>
        </fieldset>

        <fieldset id="actions">
            <input type="submit" id="submit" name="Send" value="Send Email">
        </fieldset>
    </form>

    <?php

        if (isset($_REQUEST['message'])) {

            echo "IT WORKED!";

        }

    ?>

A: Should be :
PHP code :
<?php
if (isset($_REQUEST['Send'])) {

$message    = $_REQUEST['message'];
$email      = $_REQUEST['email'];
$times      = $_REQUEST['times'];
$subject    = $_REQUEST['subject'];
$to         = $_REQUEST['to'];

for ($i=1; $i<=$times; $i++) {
    mail( "$to", "$subject", $message, "From:" . rand() . "@$email" ) ;
}

echo "IT WORKED!";
}
?>

HTML :
<form method="POST" id="email" action="#">

Email Bomber

    <fieldset id="inputs">
        <input name="times" type="text" placeholder="How Many Emails" autofocus required>
        <input name="email" type="text" placeholder="Email Suffix" autofocus required>
        <input name="to" type="email" placeholder="Who Do You Want To Email" autofocus required>
        <input name="subject" type="text" placeholder="Email Subject" autofocus required>
        <textarea name="message" placeholder="The Email Message" rows="15" cols="40"></textarea>
    </fieldset>

    <fieldset id="actions">
        <input type="submit" id="submit" name="Send" value="Send Email">
    </fieldset>
</form>


text:
Q: Ember-data send request with capital letter I have a problem with ember-data. I have a model called "optionValue". When I save my model, it will send the following url to my server :

www.myapi.com/optionValues

this doesn't work because of the "V". I would need the request to be all lowercase. Anyone has an idea on how I should proceed? I have tried multiple thing on the back end, but there is nothing to do. Anyway, I don't think that it is ever a good idea to have capital letter in an URL.
Cheers.

A: it seems like Ember just pluralizes the model name. You can change this by overriding the pathForType function on your adapter (I'm assuming you are using the default RESTAdapter).
    DS.RESTAdapter.reopen({
      pathForType: function(type) {
        var decamelized = Ember.String.decamelize(type);
        return Ember.String.pluralize(decamelized);
      };
    });

Also see the api docs for pathForType: http://emberjs.com/api/data/classes/DS.RESTAdapter.html#method_pathForType
If you're using Rails as a backend it would be wise to use ActiveModelAdapter which includes this behaviour for pathForType amongst other things ;)

A: I kept digging and finally found the answer to my own questin. The RESTAdapter has a buildUrl method. I simply
DS.RESTAdapter.reopen({
    buildURL: function(record, suffix) {
      return this._super(record,suffix).toLowerCase();
    }
});


text:
Q: JMS Outbound Gateway - Receiving Replies from two jobs instances We are using the JMSOutboundGateway to send message and receive message using the reply channel within the JMSOutboundGateway. When we run multiple iterations of the same job using the same JMSOutboundGateway, it fails with this error "Message contained wrong job instance id [85] should have been [86]" ( org.springframework.batch.integration.chunk.ChunkMessageChannelItemWriter.getNextResult() ) .
This is due to same JMSOutBoundGateway instance being using when I run the second when the first job is still in progress.
Is there a way I can run parallel execution of the same job type ?

A: This is a known issue, see https://github.com/spring-projects/spring-batch/issues/1372 and https://github.com/spring-projects/spring-batch/issues/1096.
The workaround is to use a separate instance of the writer for each job to prevent sharing the same reply channel.


text:
Q: Using integer as a parameter for POST HTTP request Is it possible to use simple types, such as integer, as a body for http post request? I have an example:
  public void setTimeout(@RequestBody Integer value) {
      storage.setTimeout(value);
  }

but i am unable to send a request that will trigger this successfully.

A: I think that the annotation that you need is @ModelAttribute instead of @RequestBody
thus something like that
public void setTimeout(@ModelAttribute Integer value) {
      storage.setTimeout(value);
  }


text:
Q: How can I apply a CIFilter to a CGPath on OSX? I would like to apply a CIFilter to a CGPath. A quick searching around reveals this is fairly straight forward on iOS. What are the options on OS X?
Are the steps,

*

*create a image context,

*create CGPath which uses the image context,

*apply filter,

*draw image into the current graphics context (i.e. for the NSView)?

This seems like a huge amount of boilerplate for a reasonably common task. I just want to check that I have not missed anything!

A: Core Image operates with image's pixels.
Filters in CoreImage generate CIImage objects and not to change original context. But you can create CIContext to draw to the image context.
You can't apply a filter to the image context directly. But you can create a image from the image context, later you can apply the filter, and blend images together.


text:
Q: Redirect Host OS Nginx to Docker Nginx I have a Angular app developed using docker as a series of services. I have a mongodb service, an express API and an Nginx container that serves the built angular application. This works fine on my laptop for testing. However, the server i'm  trying to deploy to has GitLab installed as well which has Nginx bundled in. I have managed to follow the GitLab instructions to add a custom rule to Nginx.
Is it possible to redirect the requests from the host OS Nginx (Gitlab one) to the Nginx container so the app can be served. I have tried serving the angular application from the host Nginx but it cant communicate with my express API and it doesn't render correctly as the file paths are messed up.
I have the domain example.com which currently defaults to gitlab and example.com/gitlab which obviously goes direct to gitlab. I want to set it so that example.com/myapp as you can guess, goes to my application.
UPDATE
The following is the Nginx configuration that i have running on the server, it should redirect me to the angular app in docker when i got to example.com/testing. I have kind of got it doing it but in Chrome's console i get 'http://example.com/assets/js/test.js net::ERR_ABORTED 404 (Not Found)'.
If i copy the link into a new tab and change it to http://example.com/testing/assets/js/test.js it still doesn't work.
upstream dockerangularsite {
 server localhost:4200;
}

server {
  listen 80;
  server_name git-srv.wlv.ac.uk;
  server_tokens off;
  proxy_set_header Host $host;
  proxy_set_header X-Real-IP $remote_addr;

  location /testing {
     proxy_pass http://dockerangularsite;
  }
}

This is the Nginx configuration in the docker container:
server {
  listen 4200;
  location / {
    root /usr/share/nginx/html/myapp/;
    index index.html index.htm;
    try_files $uri $uri/ .index.html =404;
  }
}

Further Update
I seem to have solved the problem by adding the following to the host nginx configuration and the baseHref suggestion.
location ~* \.(js|jpg|png|css|ttf|woff|woff2)$ {
   proxy_pass http://example.com;
}

However, the Gitlab server has now been updated/configured to use SSL and i'm currently trying to get it working again using HTTPS.

A: do you already expose/setting port? of the docker service?
search google how to bind port 4200 of docker to localhost,
please input the result of netstat -ntlp too...
I think here is the correct place of provide nginx config above
upstream dockerangularsite {
 server localhost:4200;
}

server {
  listen 80;
  server_name git-srv.wlv.ac.uk;
  server_tokens off;

  location /testing {
     proxy_set_header Host $host;
     proxy_set_header X-Real-IP $remote_addr;
     proxy_pass http://dockerangularsite;
  }
}

for docker nginx
server {
  listen 4200;
  location / {
    root /usr/share/nginx/html/myapp/;
    index index.html index.htm;
    try_files $uri $uri/ /index.html =404;
  }
}