Q:

Is there any way to tell which way is the next universe?

Is there a observable void outside our universe that can give a clue on how far the next on is? How many universes can surround ours? What does a universes gravity well look like?

A:

Which direction is the next closest universe?

Which direction to the nearest unicorn?

How many universes can surround ours at a time?

We don't know the shape of our universe.  Whether it's infinite or finite.  Whether it's bound or unbound or whether it's part of a theoretical 4 dimensional multiverse or if 3 dimensions are some kind of natural limit.    Without knowing how far our universe extends, or what (if anything) lies beyond it, it's impossible to answer.    You may as well ask how many balls fit into a box, but you don't know the size of the balls or the box?   See the problem?

Do universes redshift from each other?

In order to redshift, something needs to be both visible and have an established frequency, like the hydrogen signature of stars.   Since we've never seen another universe, and we don't even know how to look for one, or if they exist, and without knowing what they're made of.   Asking if they redshift can't be answered for many reasons.
There are alternative universe hypotheses out there, like the multiverse hypothesis and Neil deGrasse Tyson sometimes talks about other (theoretical) universes, but it's all very hand-wavy and there's nothing measurable and without measurement or detection, there's no direction, distance to or number of.
Maybe you should start with an easier one.   Point in the direction of the 4th dimension.  :-)

A:

There is no way to know, if any other "different Universe" exists.
There is also a terminologic problem with it. Universe means, on latinic, something what "contains everything".

If there is no way for the different "Universes" to interact, then how could we know that it exists?
If there is a way to interact. For example, there is another spacetime where somehow we can pass through (or at least can see light or gravitation from it), then how could we call it as a "different Universe"? Then the Universe would be our current spacetime, and that other, together.

But the problem is a hypothetical one, as no alternate Universe were found until now.
We can play with different Universes in some theoretical constructions. For example, the spacetime of a rotating black hole looks like as if it would be some gateway to somewhere, out of our Minkowski-Universe (or to a different point of our current one). Google for Penrose-diagrams and for the topological extensions of the General Relativity, if you would like to play with it more.


Q:

How to communicate "we owe you" vs "you owe us"?

Usually when I log in to check my account at the utilities website, I see something like this:

And I'm usually stumped as I have no idea whether "in debit" means whether I have still outstanding payments to make, or wheter I have paid more money and it's actually the company that ows me money back, and I have to double check the site to be sure whether "in debit" or "in credit" means I'm okay.
Initially I thought that it's because I'm not a native English speaker, but actually on some sites "in debit" means I'm okay, and on others "in credit" means I'm okay, as it doesn't really tell you who is the one that's fine. And also as a non-English speaker you also have to know what debit and credit means before you could potentally understand your statement.
I'm not sure whether using positive vs negative numbers would help, especially since I've also seen them interchanged on different websites (e.g. at some place -5.00€ would mean you have to still pay 5.00€, while on other sites 5.00€ would mean you have to still pay 5.00€)
Would there be a good way of handling this issue, so it's clear to the user that the amount they see is the amount they still owe, or the amount they have been payed more?

A:

The quick and straight forward answer is: just say what you mean.

"You currently owe 39.00"

It speaks the same language as the user and removes the ambiguity.
Small differences in language make a big difference, and can often times mean different things to different people who speak the same language. Perhaps it is a cultural difference in the application of the language, or just two people who live 5-miles away and just interpret the meaning a little different.
Here's an example of an option I recently worked on. Two actions where available:

"Sync device to group"
"Sync group to device"

What's going to happen when I select the first one? Is the 'device' going to inherit the group's settings, or vise-versa?
Here is what we switched it to:

"Push device settings to group"
"Pull group setting to device"

The push/pull concept is understood in the general population, and very well understood within our user base. The small change in language, where we said what we meant, completely removed any misinterpretation of the settings. When asked what the first set of options did, users got it right roughly half the time (geographic boundaries actually played a significant roll in a particular answer's density). When asked what the second set of options did, users got it right 100% of the time.

A:

For consumer websites it's important not to use words (e.g. financial terms) which can be confusing to a broad audience.
If you need to communicate a complex concept like an account balance, you can do so simply but also provide some additional explanatory text in case the user needs clarification:


Q:

NullPointerException in Beginner's Guide To Android Development [chapter 5]

I have been working out of the book "The Beginner's Guide To Android Game Development" by James Cho and everything has been fine until chapter 5. I finished the chapter and everything worked great, but when I tried to run the application it came up with two NullPointerExceptions that I had not even seen before. I double checked my code by comparing it to the downloadable source code and it is exactly the same but I still get the errors.
This is what the console says when I run the application
/usr/lib/jvm/default-java/bin/java -Didea.launcher.port=7543 -Didea.launcher.bin.path=/home/jake/IntelliJ/idea/bin -Dfile.encoding=UTF-8 -classpath /usr/lib/jvm/default-java/jre/lib/jsse.jar:/usr/lib/jvm/default-java/jre/lib/javazic.jar:/usr/lib/jvm/default-java/jre/lib/management-agent.jar:/usr/lib/jvm/default-java/jre/lib/jce.jar:/usr/lib/jvm/default-java/jre/lib/compilefontconfig.jar:/usr/lib/jvm/default-java/jre/lib/rt.jar:/usr/lib/jvm/default-java/jre/lib/resources.jar:/usr/lib/jvm/default-java/jre/lib/rhino.jar:/usr/lib/jvm/default-java/jre/lib/charsets.jar:/usr/lib/jvm/default-java/jre/lib/ext/dnsns.jar:/usr/lib/jvm/default-java/jre/lib/ext/java-atk-wrapper.jar:/usr/lib/jvm/default-java/jre/lib/ext/localedata.jar:/usr/lib/jvm/default-java/jre/lib/ext/pulse-java.jar:/usr/lib/jvm/default-java/jre/lib/ext/zipfs.jar:/usr/lib/jvm/default-java/jre/lib/ext/sunjce_provider.jar:/usr/lib/jvm/default-java/jre/lib/ext/sunpkcs11.jar:/home/jake/Git/LoneBall/out/production/LoneBall:/home/jake/IntelliJ/idea/lib/idea_rt.jar com.intellij.rt.execution.application.AppMain com.jakevw.game.main.GameMain
Loaded Successfully
Entered MenuState
Exception in thread "Game Thread" java.lang.NullPointerException
    at com.jakevw.game.state.PlayState.update(PlayState.java:35)
    at com.jakevw.game.main.Game.run(Game.java:67)
    at java.lang.Thread.run(Thread.java:745)

Process finished with exit code 0

Here is my PlayState class:
package com.jakevw.game.state;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.event.KeyEvent;
import java.awt.event.MouseEvent;

import com.jakevw.game.main.GameMain;
import com.jakevw.game.main.Resources;
import com.jakevw.game.model.Ball;
import com.jakevw.game.model.Paddle;

public class PlayState extends State {
    private Paddle paddleLeft, paddleRight;
    private static final int PADDLE_WIDTH = 15;
    private static final int PADDLE_HEIGHT = 60;

    private Ball ball;
    private static final int BALL_DIAMETER = 20;

    private int playerScore = 0;
    private Font scoreFont;

    @Override
    public void init() {
        paddleLeft = new Paddle(0, 195, PADDLE_WIDTH, PADDLE_HEIGHT);
        paddleRight = new Paddle(785, 195, PADDLE_WIDTH, PADDLE_HEIGHT);
        scoreFont = new Font("SansSerif", Font.BOLD, 25);
        ball = new Ball(300, 200, BALL_DIAMETER, BALL_DIAMETER);
    }

    @Override
    public void update() {
        paddleLeft.update();
        paddleRight.update();
        ball.update();

        if (ballCollides(paddleLeft)) {
            playerScore++;
            ball.onCollideWith(paddleLeft);
            Resources.hit.play();
        } else if (ballCollides(paddleRight)) {
            playerScore++;
            ball.onCollideWith(paddleRight);
            Resources.hit.play();
        } else if (ball.isDead()) {
            playerScore -= 3;
            ball.reset();
        }
    }

    @Override
    public void render(Graphics g) {
        // Draw Background
        g.setColor(Resources.darkBlue);
        g.fillRect(0, 0, GameMain.GAME_WIDTH, GameMain.GAME_HEIGHT);
        g.setColor(Resources.darkRed);
        g.fillRect(GameMain.GAME_WIDTH / 2, 0, GameMain.GAME_WIDTH / 2,
                GameMain.GAME_HEIGHT);
        // Draw Separator Line
        g.drawImage(Resources.line, (GameMain.GAME_WIDTH / 2) - 2, 0, null);

        // Draw Paddles
        g.setColor(Color.white);
        g.fillRect(paddleLeft.getX(), paddleLeft.getY(), paddleLeft.getWidth(),
                paddleLeft.getHeight());
        g.fillRect(paddleRight.getX(), paddleRight.getY(),
                paddleRight.getWidth(), paddleRight.getHeight());

        // Draw Ball
        g.drawRect(ball.getX(), ball.getY(), ball.getWidth(), ball.getHeight());

        // Draw UI
        g.setFont(scoreFont); // Sets scoreFont as current font
        g.drawString("" + playerScore, 350, 40); // Draws String using current
        // font
    }

    @Override
    public void onClick(MouseEvent e) {
        // TODO Auto-generated method stub
    }

    @Override
    public void onKeyPress(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_UP) {
            paddleLeft.accelUp();
            paddleRight.accelDown();
        } else if (e.getKeyCode() == KeyEvent.VK_DOWN) {
            paddleLeft.accelDown();
            paddleRight.accelUp();
        }
    }

    @Override
    public void onKeyRelease(KeyEvent e) {
        if (e.getKeyCode() == KeyEvent.VK_UP
                || e.getKeyCode() == KeyEvent.VK_DOWN) {
            paddleLeft.stop();
            paddleRight.stop();
        }
    }

    private boolean ballCollides(Paddle p) {
        return ball.getRect().intersects(p.getRect());
    }
}

And here is my Game class:
package com.jakevw.game.main;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Graphics;

import javax.swing.JPanel;

import com.jakevw.game.state.LoadState;
import com.jakevw.game.state.State;

import com.jakevw.framework.util.InputHandler;

@SuppressWarnings("serial")

public class Game extends JPanel implements Runnable {
    private int gameWidth;
    private int gameHeight;
    private Image gameImage;

    private volatile State currentState;
    private volatile boolean running;

    private InputHandler inputHandler;

    public Game(int gameWidth, int gameHeight) {
        this.gameWidth = gameWidth;
        this.gameHeight = gameHeight;
        setPreferredSize(new Dimension(gameWidth, gameHeight));
        setBackground(Color.BLACK);
        setFocusable(true);
        requestFocus();

    }

    public void setCurrentState(State newState){
        System.gc();
        currentState = newState;
        newState.init();
        inputHandler.setCurrentState(currentState);
    }

    private void initInput() {
        inputHandler = new InputHandler();
        addKeyListener(inputHandler);
        addMouseListener(inputHandler);
    }

    @Override
    public void addNotify() {
        super.addNotify();
        initInput();
        setCurrentState(new LoadState());
        initGame();
    }

    private void initGame() {
        running = true;
        Thread gameThread = new Thread(this, "Game Thread");
        gameThread.start();
    }

    @Override
    public void run() {
        while (running) {
            currentState.update();
            prepareGameImage();
            currentState.render(gameImage.getGraphics());
            repaint();

            try {
                Thread.sleep(14);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.exit(0);
    }

    private void prepareGameImage() {
        if (gameImage == null) {
            gameImage = createImage(gameWidth, gameHeight);
        }
        Graphics g = gameImage.getGraphics();
        g.clearRect(0, 0, gameWidth, gameHeight);
    }

    public void exit() {
        running = false;
    }

    @Override
    protected void paintComponent(Graphics g) {
        super.paintComponent(g);
        if (gameImage == null) {
            return;
        }
        g.drawImage(gameImage, 0, 0, null);
    }
}

If anybody needs to see any other code you could check out my GutHub:
https://github.com/JakeVdub/LoneBall
Hopefully somebody can help me out with this, thank you in advance for spending time helping a beginner like me out!

A:

In your Game class, you should initialize the newState before setting it as the currentState!
public void setCurrentState(State newState) {
    System.gc();
    currentState = newState;
    newState.init();
    inputHandler.setCurrentState(currentState);
}

Should be:
   public void setCurrentState(State newState){
        System.gc();
        newState.init();
        currentState = newState;
        inputHandler.setCurrentState(currentState);
    }

If you have any other issues, please let me know on the book's forum.
jamescho7.com/forum


Q:

Toggling a property with jquery

Trying to make a simple toggle button.
To explain it:

Input has a property of disabled
User presses button disabled becomes false
User presses Save Changes and button becomes disabled again.

Here's my code
$('#password').click(function(){
    if($("#password") === "disabled"){
        $("#password").prop("disabled", false);
    } else if ($("#password").prop("disabled", false)){
        $("#password").prop("disabled", true);
    }
});

Sidenote: I'm using bootstrap

A:

Disabled form elements don't trigger any mouse events, your event handler function will never be called. Even if it was..
A jQuery collection ($("#password")) will never be equal to the string literal "disabled", although it's a truthy value, you've used ===. Regardless, I'm pretty sure you are looking for
if( $('#password').prop('disabled') ) {

The setter version of .prop() returns the original collection, so will always be a truthy value.

To have the <input> enabled by default and have it disabled when your form is submitted (assuming you are using a form..):
$('#myForm').submit(function(){
    $('#password').prop('disabled', true);
});


Q:

newlineCharacterSet returning 5 lines instead of 3

I download a file which contains 3 lines directly under each other,
but my array appears to skip one line for every set.  In my array, tangible results appear in positions: 0, 2, and 4 instead of positions 0,1,  and 2.
Also, will this timeout after a few seconds? I just see an interval, is that the timeout?
    NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
        NSNumber *timeStampObj = [NSNumber numberWithDouble: timeStamp];
        NSURL* url = [NSURL URLWithString:[NSString stringWithFormat:@"http://192.168.1.30/ios/info.php?a=APP1&s=%i",timeStampObj]];
        NSURLRequest* request = [NSURLRequest requestWithURL:url cachePolicy:0 timeoutInterval:5];
        NSURLResponse* response=nil;
        NSError* error=nil;
        NSData* data=[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
        NSString* fileContents = [[[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding] autorelease];
        if ([fileContents length] == 0) return;

        NSArray* allLinedStrings = [fileContents componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];

        if ([allLinedStrings count] == 0) {

        } else {
            NSString* Title = [allLinedStrings objectAtIndex:0];
            NSString* Description = [allLinedStrings objectAtIndex:2];
            NSString* Url = [allLinedStrings objectAtIndex:4];

        }

A:

If the file is reliably separated by "\r\n", then -componentsSeparatedByString: should work for you.
 NSArray* allLinedStrings = [fileContents componentsSeparatedByString:@"\r\n"];


Q:

Evaluating all the notebook calling a package doesn't work whereas evaluating the package "manually", then run the notebook

I have put all the function I use regularly in a package.
At the beginning of my notebook I have a section containing the following stuff.
Quit[]

Off[SixJSymbol::tri]

<< fonctionsGenerales`

When I run my notebook by evaluation > evaluate notebook, all the functions of my package fonctionsGenerales are unknown by my notebook.
But when I execute line by line this first section, and then I execute the rest of the code normally, everything works fine.
Why by doing "evaluate notebook", my notebook seems to not see the functions in my package ?

A:

When you use Evaluate Notebook all expressions in your notebook are added to the evaluation queue. But the Quit[] command by default removes all items from this queue. So nothing gets evaluated.
To change the default behaviour you can use the following command:
SetOptions[$FrontEnd, "ClearEvaluationQueueOnKernelQuit" -> False]

See also:
Self-restarting MathKernel - is it possible in Mathematica?


Q:

Asp.net Identity 2.0 update user

Having a problem with saving user changes to the database, like changing the person's name.  I'm using the IdentityModel that is automatically created in a new VS2013 web project using individual authentication.  Sadly, the template doesn't allow you to change any user information, other than changing roles.  I'm looking around via google, I haven't found much.  Anyone implement updating using the base identity code?
This is the closest thing I found:
Updating user data - Asp.net Identity
I haven't been successful at incorporating default template. I've just started using Identity this week, so it might be my lack of understanding that's the problem.
var updatedUser = new ApplicationUser
            {
                Id = model.UserId,
                UserName = model.UserName,
                CustomerId = model.CustomerId,
                Email = model.EmailAddress,
                FirstName = model.FirstName,
                LastName = model.LastName,
                PhoneNumber = model.PhoneNumber,
            };

...
var result = await UserManager.UpdateAsync(updatedUser);

My UserManager is created like this:
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();

I get the following error in the browser:
Attaching an entity of type 'ApplicationUser' failed because another entity of the same type already has the same primary key value. This can happen when using the 'Attach' method or setting the state of an entity to 'Unchanged' or 'Modified' if any entities in the graph have conflicting key values. This may be because some entities are new and have not yet received database-generated key values. In this case use the 'Add' method or the 'Added' entity state to track the graph and then set the state of non-new entities to 'Unchanged' or 'Modified' as appropriate
Thanks

A:

The problem I had was I creating an ApplicationUser and saved the object to the database.  Since Identity uses Entity Framework under the covers, the entity state of the "updatedUser" object is Added.  So Entity Framework tried to INSERT in to the Identity database, causing the conflict.  So, you have to get the user and update the returned user object for Entity Framework to know that the entity state is Modified.  Here's the working code:
var user = await UserManager.FindByIdAsync(model.UserId);

user.Email = model.EmailAddress;
user.CustomerId = model.CustomerId;
user.FirstName = model.FirstName;
user.PhoneNumber = model.PhoneNumber;
user.LastName = model.LastName;

var result = await UserManager.UpdateAsync(user);


Q:

Is it possible to get a reference to a UIImage when capturing an image with UIImagePicker

Right now I use the following to save a picture to my Photos album
-(void)shootPicture{
     [self.PickerController takePicture];
}

But I want to be able to get a reference to the UIImage rather than save it immediately to my camera roll.
Is there a way to achieve this in IOS?

A:

You can set yourself as a UIImagePickerControllerDelegate and listen for imagePickerController(_:didFinishPickingMediaWithInfo:) You get a Dictionary and get an UIImage by using the key UIImagePickerControllerEditedImage(or originalImage).
https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImagePickerControllerDelegate_Protocol/index.html#//apple_ref/doc/constant_group/Editing_Information_Keys


Q:

How to have checkbox be toggled on "checkbox" column only, so row select don't toggle checkbox

I'm using multiselect: true option on jqGrid setup.
The issue I'm having is when I click on any row, the checkbox get toggled.  How do I limit the toggling of checkbox to "checkbox" column only when clicking on that "checkbox" column.   I don't want the checkbox to be checked/unchecked when I click on 3rd column, 5th column, etc.
Is that possible?

A:

The callback beforeSelectRow allows to define specific rules for selection the row. It should return false to prevent the selection. The checkboxes from multiselect column have CSS class "cbox". Thus the callback
beforeSelectRow: function (rowid, e) {
    return $(e.target).hasClass("cbox");
}

should solve the problem.


Q:

Do I need 'override func didReceiveMemoryWarning() {}' in my project?

I got an error here: override func didReceiveMemoryWarning() {
The error: Method does not override any of its superclass.
The question: Does the code override func didReceiveMemoryWarning() have to be in my project?

A:

No, you don't. Delete it until you have a need for it.
Shocking, I know, because it's recommended and it's in the template. But in all my years of iOS development, I've only actually had something useful to put in there maybe four or five times (and most of those were back in the iPhone 3GS days when memory was more limited). Frankly, for new developers, I'd just leave it out until you're ready to worry about optimizing resource utilization at that level. I think it creates more confusion than it solves. You definitely shouldn't put it in there unless you also perform tests to make sure your memory warning code works.
As Alessandro notes, this method is only applicable for UIViewController subclasses. (For other types, you can observe UIApplicationDidReceiveMemoryWarningNotification.) But you shouldn't just leave it in there because it's part of the template or because someone told you you should have it. If you don't have any meaningful memory to release (and honestly, view controllers seldom should), then you should get rid of the override.


Q:

Plotting curves containing constants using ezplot

I want to plot a function using ezplot, different values of two constants.
like
ezplot('a*x^2+b*y^2=1')

How can I plot it for different values of a and b?
Thanks everyone.

A:

The easy way is:
first define your function with a handler, something like this:
a = 1;
b = 3;
fh = @(x,y) (a*x.^2 + b*y.^2 - 1);

Then easily use ezplot with the function:
ezplot(fh)
axis equal

If you have different values of a, and b, you can use them in a loop (or using vectorized calculation), and feed them to your function, then plot the function, and after a plot use 'hold on' command to keep the previous plot something like this:
for i=1:n
    fh = @(x,y) (a(i)*x.^2 + b(i)*y.^2 - 1);
    ezplot(fh);
    hold on
end

That's it.


Q:

Porque a chamada a um método simples em uma classe dá erro de referência?

Estou começando a estudar C# e estou com o seguinte erro:

CODE: CS0120 DESCRIPTION: An object reference is required for
  the non-static field, method, or property
  'Program.SomarNumeroes(int,int)' CODE: CS0120 DESCRIPTION:
  An object reference is required for the non-static field, method, or
  property 'Program.dizOla()'

namespace metodo_e_funcao
{
    class Program
    {
        public int SomarNumeros(int a, int b)
        {
            int resultado = a + b;
            if (resultado > 10)
            {
                return resultado;
            }
            return 0;
        }

        public void dizOla()
        {
            Console.WriteLine("Ola");
        }

        static void Main(string[] args)
        {
            int resultado = SomarNumeros(10,11);
            Console.WriteLine(resultado);
            dizOla();
        }
    }
}

A:

Parece acessar os métodos de forma direta sem instanciar um objeto é necessário que o método seja estático.
Obviamente métodos estáticos também não podem acessar diretamente membros de instância. O fato do Main() ser estático já impediria o acesso de membros de instância dessa classe se fosse feito.
using System;

namespace metodo_e_funcao {
    public class Program {
        public static int SomarNumeros(int a, int b) {
            int resultado = a + b;
            if (resultado > 10) {
                return resultado;
            }
            return 0;
        }

        public static void dizOla() {
            Console.WriteLine("Ola");
        }

        public static void Main(string[] args) {
            int resultado = SomarNumeros(10, 11);
            Console.WriteLine(resultado);
            dizOla();
        }
    }
}

Veja funcionando no ideone de forma mais simplificada. E no .NET Fiddle. Também coloquei no GitHub para referência futura.
Leia mais sobre o assunto.


Q:

Logical Connectives and Quantifiers

So I have been told that the rule of thumb when symbolizing Existence statements is to use the "and/$\wedge$" logical connective.
$$\exists x (P_x \wedge Q_x)$$
Whereas symbolizing a Universal statement usually uses a "conditional/$\rightarrow$".
$$\forall x(P_x\to Q_x)$$
But when we compound the quantifiers, should we base the main logical connector on the innermost or the outermost quantifier?
$$\forall x \exists y(P_x\wedge Q_y)\text{ or }\forall x \exists y (P_x\to Q_y)$$
If there is no general rule, what is the reasoning behind choosing the correct logical connective for compound statements?

A:

What he is likely referring to is sometimes you will have relations appear informally inside the quantifier, and those are the rules for how it is translated. For instance,
$(\forall x \in I)P(x)$ informally expresses $(\forall x)(x\in I \to P(x))$
and $(\exists x \in I)P(x)$ informally expresses $(\exists x)(x \in I \land P(x))$
EDIT-
In response to your comment, if he/she is referring to the informal notation above the correct way would be something like the following:
$(\forall x \in I)(\exists y >0)(P(x,y))$ would be translated
$(\forall x)\Big((x \in I) \to \exists y\big((y > 0) \land P(x,y)\big)\Big)$
So you use both. Absent this, I don't know which convention he could be referring to because both can be correct depending on what the statement itself is trying to express. There are plenty of times when you want weaker statements. For instance, you generally want the weakest possible assumptions that suffice to prove a given theorem. This allows you to use the theorem more broadly/frequently as the conditions that must be met to employ it are easier to satisfy.


Q:

Detect device aspect ratio

The plugin fullpageScroll allows to deactivate its plugin at a certain point (for mobile sites). so by setting responsive: 750 the plugin is deactivated whenever the browsers width is less then 750px.
I want to extend this by checking the aspect ratio as well. So whenever the $(window).width()/$(window).height() <= 1.32) I want to although deactivate the plugin.
The code that does the check named above goes like this:
function responsive(){
    if(options.responsive){

        var isResponsive = container.hasClass('fp-responsive');
        if ($(window).width() < options.responsive ){
            if(!isResponsive){
                $.fn.fullpage.setAutoScrolling(false, 'internal');
                $('#fp-nav').hide();
                container.addClass('fp-responsive');
            }
        }else if(isResponsive){
            $.fn.fullpage.setAutoScrolling(originals.autoScrolling, 'internal');
            $('#fp-nav').show();
            container.removeClass('fp-responsive');
        }
    }
}

I am not able to implement the second check for the aspect ratio into this code. I appreciate every help or suggestion!

A:

You could do this then implement your function where the console.log is
$( window ).resize(function() {
    if($(window).width()/$(window).height() <= 1.32){
        console.log("Do stuff here")
    }
});


Q:

Has anyone used ServiceLoader together with Guice?

I keep wanting to try this on a larger scale with our app + build system, but higher priorities keep pushing it to the back burner. It seems like a nice way to load Guice modules and avoids the common complaint about "hard coded configuration". Individual configuration properties rarely change on their own, but you will almost always have a set of profiles, usually for different environments (Debug, Production, etc).
ServiceLoader lets you pull a list of all implementations defined as a service for a given type. Putting this together with Guice, you end up with:
import java.util.ServiceLoader;

import com.google.inject.AbstractModule;
import com.google.inject.Module;

public class ModuleLoader<M extends Module> extends AbstractModule {

    private final Class<M> type;

    public ModuleLoader(Class<M> type) {
        this.type = type;
    }

    public static <M extends Module> ModuleLoader<M> of(Class<M> type) {
        return new ModuleLoader<M>(type);
    }

    @Override
    protected void configure() {
        ServiceLoader<M> modules = ServiceLoader.load(type);
        for (Module module : modules) {
            install(module);
        }
    }
}

Usage example (as a dynamic servlet loader in a guice-servlet project):
import com.google.inject.servlet.ServletModule;

public class ServletLoader extends GuiceServletContextListener {
    @Override
    protected final Injector getInjector() {
       return Guice.createInjector(ModuleLoader.of(ServletModule.class);
    }
}

The services (packaged as modules) would be packaged in seperate jar files. Within each one you'd define the class(es) in the meta-data:
Within servlets.jar: META-INF/services/com.google.inject.Module

com.example.webapps.MyServletModuleA
com.example.webapps.MyServletModuleB

Since we use Maven, we think this would be ideal as we could pull in different implementations at runtime via profile dependencies. Is anyone using Guice like this?
If not, feel free to use this example and see how it works for you. (ServiceLoader is only supported in JDK6+)

A:

We're doing almost exactly this at my work.  We're currently stuck in java 5 due to some internal limitations, so we do it a bit differently using Service Provider (due to not having access to ServiceLocator until java 6 like you mentioned), but it essentially works the same.
I remember reading somewhere that this was one of the preferred ways the Guice developers recommended, though they want to leave this open for flexibility.


Q:

Unable to scroll smoothly listView of Images in android 4.1

I am using a listView of images to scroll images, the listView scrolls smoothly on 2.3 but not on phones with OS 4.0+ . All the images are being fetched from R.drawable Please find my code attached
image_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="#A4A4A4"
        android:orientation="horizontal" >

        <ImageView
            android:id="@+id/imageStatus"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            android:adjustViewBounds="true"
            android:scaleType="fitXY" />
    </LinearLayout>

A:

Try SparseArray<E> for getting the better performance of drawable images list.


Q:

Phone number fails my regular expression

I use this ^((\d-\d{3})|(\d{1,3}))\-\d{3}-\d{7}$ regex to validate phone numbers.
However it does not accept the following number which is valid. What is the problem?
Could it have to do with the zeros at the end?
90-312-2488900

A:

Your regexp seems to work properly.
Maybe the problem is in the last space in your example. Try to remove it with string.Trim, or add \s* to your regexp (or even add it between every groups of numbers.


Q:

Index the first and the last n elements of a list

the first n and the last n element of the python list
l=[1,2,3,4,5,6,7,8,9,10]

can be indexed by the expressions
print l[:3]
[1, 2, 3]

and
print l[-3:]
[8, 9, 10]

is there a way to combine both in a single expression, i.e index the first n and the last n elements using one indexing expression?

A:

Just concatenate the results:
l[:3] + l[-3:]

There is no dedicated syntax to combine disjoint slices.

A:

Do you mean like:
l[:3]+l[-3:]

then using variable:
l[:x]+l[-y:]


Q:

why 2 and 4 prints before b prints?

function first() {
  return new Promise(resolve => {
    console.log(2);
    resolve(3);
    console.log(4);
  });
}

async function f() {
  console.log(1);
  let r = await first();
  console.log(r);
  console.log(99);
}

console.log('a');
f();
console.log('b');

In the above code shows the following result:
a
1
2
4
b
3
99

In my understanding, when the compiler hits the await first() function, it pushes the first() function execution to the event queue and pause the execution of f(), continue execution everything after f().So the execution order should be:
a
1
b
2
4
3
99

Apparently, I get it wrong. Can anyone explain to me how this is really working?

A:

I think this is actually happening, please see the comments and numbers
function first() {
  return new Promise(resolve => {
    console.log(2); // 5. Print "2"
    resolve(3); // 6. call resolve(3), meaning it will set the resolveCallback state of Promise with 3.
    console.log(4); // 7. print "4"
  });
}

async function f() {
  console.log(1); // 3. Print "1"
  let r = await first(); // 4. Call the first() method and await the result, control goes to first()
                        // 8. Since first() method updated the state of resolveCallback, it will assign "3" to variable "r"
  console.log(r); // 10. print "3"
  console.log(99); // 11. print "99"
}

console.log('a'); // 1. Start print 'a'
f(); // 2. Since funtion f() is decoreated with async key word it is by default return a promise and control goes to f()
console.log('b'); // 9. Since control release from f() print "b"

Simple terms a Promise allows you to run some code asynchronously and then run other code after it completes and dependent on the result (whether it failed or succeeded).It is created using the constructor pattern.
Signature : function(resolveCallback, rejectCallback)
The constructor returns a Promise object which keeps track of it’s state, and can only be settled once. This means that the resolver and rejector functions together can only receive one call, and the status can’t change from resolved to rejected or vice versa.


Q:

How to register Broadcast of my app to show as an alternative app

I want to register my App which deal as an optional App. like a user want to send SMS, user goes to contact and select a contact there and get option Call or Message. user select Messege. now i want to show my app as optional with default messaging app,like whats app.I searched a lot but did not  get how to do that. please help me, thanks in advance, i am a new learner.

A:

You need to set an action Intent Filter  .
Something like this
<intent-filter>
   <action android:name="android.intent.action.SENDTO" />
     <action android:name="android.intent.action.SEND" />

</intent-filter>

Check out this link you will get some Idea
It works like this
         Intent intent = new Intent();
        intent.setAction(Intent.SEND);
        startActivity(intent);

It will show you list of all the app which can send sms


Q:

how do I find the index inside a recursion

(in c programming)
I have another index question if you don't mind.
I use this function to find the highest number in an array of integers:
int Find_max(int *array,int n){
    if(n==1) return array[0];
    int num1=Find_max(array,n/2);
    int num2=Find_max(array+n/2,n-n/2);
    if(num1>num2) return num1;
    return num2;
}

how do I get the index of the number I found? I'm not allowed to use any kind of loops.

A:

Almost the same code (style retained):
int Find_max_index(int *array,int n){
    if(n==1) return 0;
    int index1=Find_max_index(array,n/2);
    int index2=n/2+Find_max_index(array+n/2,n-n/2);
    if(array[index1]>array[index2]) return index1;
    return index2;
}


Q:

Android Studio, Button onClick

This issue was specific to an older version of ANDROID studio. But is no longer a problem for Android 0.8.1.   I may delete the question completely.
I am still experimenting with Android Studio.  I just upgraded to Version 0.2.13, which I understand had some upgrade issues.  I wrestled through them... but I have an issue with Buttons that I did not have prior to the upgrade.
The Button on Click event is giving me this error in the Properties section.
Error getting value: ContentElementType: FILE; file:HtmlFile:incognito_mode_start_page.html Boolean.TRUE.equals

Prior to this version, I would just type in what I wanted to call my click Handler and there would be no problems.  Now,  I can not even select this field in the Properties inspector.
I have also tried to Manually change the onClick handler... but AS will switch my code back to ""
this is what i have so far...
<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="New Button"
    android:id="@+id/button"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:onClick="<unset>" />

WHAT I HAVE TRIED SO FAR... With no luck
I have also tried restarting AS
I have tried creating a new ACTIVITY, confirming that it has both a class and Layout file.  and working from that...
I have Manually changed the line android:onClick="<unset>" /> to android:onClick="doSomething" />
and added a doSomething function in my code.
/////////////////////////////////////
I just noticed this on startup...  I think this is related...
java.lang.AssertionError: ContentElementType: FILE; file: HtmlFile:incognito_mode_start_page.html
    Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = false
    getTreeElement() = Element(FILE)
    vFile instanceof VirtualFileWithId = true
    StubUpdatingIndex.canHaveStub(vFile) = false: java.lang.AssertionError: ContentElementType: FILE; file: HtmlFile:incognito_mode_start_page.html
    Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = false
    getTreeElement() = Element(FILE)
    vFile instanceof VirtualFileWithId = true
    StubUpdatingIndex.canHaveStub(vFile) = false
java.util.concurrent.ExecutionException: java.lang.AssertionError: ContentElementType: FILE; file: HtmlFile:incognito_mode_start_page.html
    Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = false
    getTreeElement() = Element(FILE)
    vFile instanceof VirtualFileWithId = true
    StubUpdatingIndex.canHaveStub(vFile) = false
    at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
    at java.util.concurrent.FutureTask.get(FutureTask.java:83)
    at com.intellij.concurrency.PrioritizedFutureTask.access$301(PrioritizedFutureTask.java:32)
    at com.intellij.concurrency.PrioritizedFutureTask$1.run(PrioritizedFutureTask.java:79)
    at com.intellij.concurrency.PrioritizedFutureTask.run(PrioritizedFutureTask.java:115)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:680)
Caused by: java.lang.AssertionError: ContentElementType: FILE; file: HtmlFile:incognito_mode_start_page.html
    Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = false
    getTreeElement() = Element(FILE)
    vFile instanceof VirtualFileWithId = true
    StubUpdatingIndex.canHaveStub(vFile) = false
    at com.intellij.psi.impl.source.PsiFileImpl.calcStubTree(PsiFileImpl.java:996)
    at com.intellij.psi.stubs.StubProcessingHelperBase.processStubsInFile(StubProcessingHelperBase.java:47)
    at com.intellij.psi.stubs.StubIndexImpl$2.perform(StubIndexImpl.java:245)
    at com.intellij.psi.stubs.StubIndexImpl$2.perform(StubIndexImpl.java:236)
    at com.intellij.util.indexing.ValueContainer.forEach(ValueContainer.java:60)
    at com.intellij.psi.stubs.StubIndexImpl.process(StubIndexImpl.java:236)
    at com.intellij.psi.stubs.StubIndexImpl.get(StubIndexImpl.java:210)
    at com.intellij.psi.stubs.StubIndex.safeGet(StubIndex.java:73)
    at com.intellij.psi.impl.java.stubs.index.JavaFullClassNameIndex.get(JavaFullClassNameIndex.java:48)
    at com.intellij.psi.impl.file.impl.JavaFileManagerBase.findClasses(JavaFileManagerBase.java:133)
    at com.intellij.psi.impl.JavaPsiFacadeImpl$PsiElementFinderImpl.findClasses(JavaPsiFacadeImpl.java:297)
    at com.intellij.psi.impl.JavaPsiFacadeImpl.findClasses(JavaPsiFacadeImpl.java:147)
    at com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl.resolveClassPreferringMyJar(ClsJavaCodeReferenceElementImpl.java:187)
    at com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl.resolveElement(ClsJavaCodeReferenceElementImpl.java:182)
    at com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl.advancedResolveImpl(ClsJavaCodeReferenceElementImpl.java:103)
    at com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl.access$000(ClsJavaCodeReferenceElementImpl.java:40)
    at com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl$Resolver.resolve(ClsJavaCodeReferenceElementImpl.java:96)
    at com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl$Resolver.resolve(ClsJavaCodeReferenceElementImpl.java:90)
    at com.intellij.psi.impl.source.resolve.ResolveCache$2.compute(ResolveCache.java:106)
    at com.intellij.openapi.util.RecursionManager$2.doPreventingRecursion(RecursionManager.java:110)
    at com.intellij.psi.impl.source.resolve.ResolveCache.resolve(ResolveCache.java:103)
    at com.intellij.psi.impl.source.resolve.ResolveCache.resolveWithCaching(ResolveCache.java:131)
    at com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl.multiResolve(ClsJavaCodeReferenceElementImpl.java:151)
    at com.intellij.psi.impl.compiled.ClsJavaCodeReferenceElementImpl.advancedResolve(ClsJavaCodeReferenceElementImpl.java:141)
    at com.intellij.psi.impl.source.PsiClassReferenceType.resolveGenerics(PsiClassReferenceType.java:140)
    at com.intellij.psi.impl.source.PsiClassReferenceType.resolve(PsiClassReferenceType.java:89)
    at com.intellij.psi.impl.PsiClassImplUtil.resolveClassReferenceList(PsiClassImplUtil.java:905)
    at com.intellij.psi.impl.PsiClassImplUtil.getSupersInner(PsiClassImplUtil.java:776)
    at com.intellij.psi.impl.PsiClassImplUtil.getSupers(PsiClassImplUtil.java:734)
    at com.intellij.psi.impl.compiled.ClsClassImpl.getSupers(ClsClassImpl.java:138)
    at com.intellij.psi.impl.InheritanceImplUtil.isInheritorWithoutCaching(InheritanceImplUtil.java:170)
    at com.intellij.psi.impl.InheritanceImplUtil.isInheritor(InheritanceImplUtil.java:127)
    at com.intellij.psi.impl.InheritanceImplUtil.checkInheritor(InheritanceImplUtil.java:194)
    at com.intellij.psi.impl.InheritanceImplUtil.checkInheritor(InheritanceImplUtil.java:176)
    at com.intellij.psi.impl.InheritanceImplUtil.isInheritorWithoutCaching(InheritanceImplUtil.java:170)
    at com.intellij.psi.impl.InheritanceImplUtil.isInheritor(InheritanceImplUtil.java:127)
    at com.intellij.psi.impl.InheritanceImplUtil.isInheritor(InheritanceImplUtil.java:57)
    at com.intellij.psi.impl.source.PsiClassImpl.isInheritor(PsiClassImpl.java:650)
    at com.intellij.psi.util.InheritanceUtil.isInheritorOrSelf(InheritanceUtil.java:45)
    at com.intellij.psi.impl.ElementPresentationUtil.getClassKindImpl(ElementPresentationUtil.java:135)
    at com.intellij.psi.impl.ElementPresentationUtil.access$000(ElementPresentationUtil.java:36)
    at com.intellij.psi.impl.ElementPresentationUtil$1.compute(ElementPresentationUtil.java:107)
    at com.intellij.psi.impl.PsiCachedValueImpl.doCompute(PsiCachedValueImpl.java:49)
    at com.intellij.util.CachedValueBase.getValueWithLock(CachedValueBase.java:200)
    at com.intellij.psi.impl.PsiCachedValueImpl.getValue(PsiCachedValueImpl.java:38)
    at com.intellij.psi.impl.ElementPresentationUtil.getClassKind(ElementPresentationUtil.java:112)
    at com.intellij.psi.impl.ElementPresentationUtil.getFlags(ElementPresentationUtil.java:51)
    at com.intellij.psi.impl.ElementPresentationUtil.createLayeredIcon(ElementPresentationUtil.java:63)
    at com.intellij.psi.impl.PsiClassImplUtil$2.fun(PsiClassImplUtil.java:323)
    at com.intellij.psi.impl.PsiClassImplUtil$2.fun(PsiClassImplUtil.java:314)
    at com.intellij.ui.IconDeferrerImpl.defer(IconDeferrerImpl.java:77)
    at com.intellij.psi.impl.PsiClassImplUtil.getClassIcon(PsiClassImplUtil.java:342)
    at com.intellij.psi.impl.PsiClassImplUtil.getClassIcon(PsiClassImplUtil.java:329)
    at com.intellij.psi.impl.source.PsiClassImpl.getElementIcon(PsiClassImpl.java:665)
    at com.intellij.psi.impl.ElementBase.computeIconNow(ElementBase.java:136)
    at com.intellij.psi.impl.ElementBase.access$000(ElementBase.java:52)
    at com.intellij.psi.impl.ElementBase$1.fun(ElementBase.java:62)
    at com.intellij.psi.impl.ElementBase$1.fun(ElementBase.java:56)
    at com.intellij.ui.IconDeferrerImpl.defer(IconDeferrerImpl.java:77)
    at com.intellij.psi.impl.ElementBase.computeIcon(ElementBase.java:124)
    at com.intellij.psi.impl.ElementBase.getIcon(ElementBase.java:89)
    at com.intellij.ide.JavaFileIconPatcher.replaceIcon(JavaFileIconPatcher.java:71)
    at com.intellij.ide.JavaFileIconPatcher.patchIcon(JavaFileIconPatcher.java:44)
    at com.intellij.util.IconUtil$1.fun(IconUtil.java:139)
    at com.intellij.util.IconUtil$1.fun(IconUtil.java:121)
    at com.intellij.ui.DeferredIconImpl$2$1.run(DeferredIconImpl.java:103)
    at com.intellij.ui.IconDeferrerImpl.evaluateDeferred(IconDeferrerImpl.java:112)
    at com.intellij.ui.DeferredIconImpl$2$2.run(DeferredIconImpl.java:118)
    at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1171)
    at com.intellij.ui.DeferredIconImpl$2.run(DeferredIconImpl.java:115)
    at com.intellij.concurrency.JobLauncherImpl$2.call(JobLauncherImpl.java:139)
    at com.intellij.concurrency.JobLauncherImpl$2.call(JobLauncherImpl.java:135)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at com.intellij.concurrency.PrioritizedFutureTask.access$101(PrioritizedFutureTask.java:32)
    at com.intellij.concurrency.PrioritizedFutureTask$1.run(PrioritizedFutureTask.java:72)
    ... 4 more

java.lang.AssertionError: ContentElementType: FILE; file: HtmlFile:incognito_mode_start_page.html
    Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = false
    getTreeElement() = Element(FILE)
    vFile instanceof VirtualFileWithId = true
    StubUpdatingIndex.canHaveStub(vFile) = false
    at com.intellij.psi.impl.source.PsiFileImpl.calcStubTree(PsiFileImpl.java:996)
    at com.intellij.psi.stubs.StubProcessingHelperBase.processStubsInFile(StubProcessingHelperBase.java:47)
    at com.intellij.psi.stubs.StubIndexImpl$2.perform(StubIndexImpl.java:245)
    at com.intellij.psi.stubs.StubIndexImpl$2.perform(StubIndexImpl.java:236)
    at com.intellij.util.indexing.ValueContainer.forEach(ValueContainer.java:60)
    at com.intellij.psi.stubs.StubIndexImpl.process(StubIndexImpl.java:236)
    at com.intellij.psi.stubs.StubIndexImpl.get(StubIndexImpl.java:210)
    at com.intellij.psi.stubs.StubIndex.safeGet(StubIndex.java:73)
    at com.intellij.psi.impl.java.stubs.index.JavaSuperClassNameOccurenceIndex.get(JavaSuperClassNameOccurenceIndex.java:49)
    at com.intellij.psi.impl.search.JavaDirectInheritorsSearcher$5.compute(JavaDirectInheritorsSearcher.java:107)
    at com.intellij.psi.impl.search.JavaDirectInheritorsSearcher$5.compute(JavaDirectInheritorsSearcher.java:104)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:939)
    at com.intellij.psi.impl.search.JavaDirectInheritorsSearcher.execute(JavaDirectInheritorsSearcher.java:104)
    at com.intellij.psi.impl.search.JavaDirectInheritorsSearcher.execute(JavaDirectInheritorsSearcher.java:48)
    at com.intellij.util.ExecutorsQuery.processResults(ExecutorsQuery.java:43)
    at com.intellij.util.AbstractQuery.forEach(AbstractQuery.java:77)
    at com.intellij.util.UniqueResultsQuery.process(UniqueResultsQuery.java:66)
    at com.intellij.util.UniqueResultsQuery.forEach(UniqueResultsQuery.java:56)
    at com.intellij.psi.search.searches.ClassInheritorsSearch.processInheritors(ClassInheritorsSearch.java:278)
    at com.intellij.psi.search.searches.ClassInheritorsSearch.access$100(ClassInheritorsSearch.java:46)
    at com.intellij.psi.search.searches.ClassInheritorsSearch$1.execute(ClassInheritorsSearch.java:75)
    at com.intellij.psi.search.searches.ClassInheritorsSearch$1.execute(ClassInheritorsSearch.java:53)
    at com.intellij.util.ExecutorsQuery.processResults(ExecutorsQuery.java:43)
    at com.intellij.util.AbstractQuery.forEach(AbstractQuery.java:77)
    at org.jetbrains.android.facet.AndroidFacet.fillMap(AndroidFacet.java:979)
    at org.jetbrains.android.facet.AndroidFacet.getInitialClassMap(AndroidFacet.java:946)
    at org.jetbrains.android.facet.AndroidFacet.getClassMap(AndroidFacet.java:892)
    at org.jetbrains.android.dom.AndroidDomElementDescriptorProvider.getDescriptor(AndroidDomElementDescriptorProvider.java:62)
    at org.jetbrains.android.dom.AndroidDomElementDescriptorProvider.getDescriptor(AndroidDomElementDescriptorProvider.java:91)
    at com.intellij.psi.impl.source.xml.XmlTagImpl.computeElementDescriptor(XmlTagImpl.java:461)
    at com.intellij.psi.impl.source.xml.XmlTagImpl.getDescriptor(XmlTagImpl.java:446)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.checkTagByDescriptor(XmlHighlightVisitor.java:284)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.checkTag(XmlHighlightVisitor.java:164)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.visitXmlToken(XmlHighlightVisitor.java:128)
    at com.intellij.psi.impl.source.xml.XmlTokenImpl.accept(XmlTokenImpl.java:44)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.visit(XmlHighlightVisitor.java:724)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass$5.run(GeneralHighlightingPass.java:300)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:419)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.access$300(GeneralHighlightingPass.java:65)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass$7.run(GeneralHighlightingPass.java:425)
    at com.intellij.codeInsight.daemon.impl.DefaultHighlightVisitor.analyze(DefaultHighlightVisitor.java:87)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:422)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.access$300(GeneralHighlightingPass.java:65)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass$7.run(GeneralHighlightingPass.java:425)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.analyze(XmlHighlightVisitor.java:734)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:422)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.access$300(GeneralHighlightingPass.java:65)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass$7.run(GeneralHighlightingPass.java:425)
    at com.intellij.codeInsight.daemon.impl.RefCountHolder.analyze(RefCountHolder.java:298)
    at com.intellij.codeInsight.daemon.impl.analysis.HighlightVisitorImpl.analyze(HighlightVisitorImpl.java:163)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:422)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.collectHighlights(GeneralHighlightingPass.java:378)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.collectInformationWithProgress(GeneralHighlightingPass.java:218)
    at com.intellij.codeInsight.daemon.impl.ProgressableTextEditorHighlightingPass.doCollectInformation(ProgressableTextEditorHighlightingPass.java:86)
    at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:61)
    at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass$1$1.run(PassExecutorService.java:357)
    at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1171)
    at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass$1.run(PassExecutorService.java:348)
    at com.intellij.openapi.progress.ProgressManager.executeProcessUnderProgress(ProgressManager.java:209)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:212)
    at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.doRun(PassExecutorService.java:345)
    at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:321)
    at com.intellij.concurrency.JobLauncherImpl$2.call(JobLauncherImpl.java:139)
    at com.intellij.concurrency.JobLauncherImpl$2.call(JobLauncherImpl.java:135)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at com.intellij.concurrency.PrioritizedFutureTask.access$101(PrioritizedFutureTask.java:32)
    at com.intellij.concurrency.PrioritizedFutureTask$1.run(PrioritizedFutureTask.java:72)
    at com.intellij.concurrency.PrioritizedFutureTask.run(PrioritizedFutureTask.java:115)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:680)

-----------------------------------  a second stack of errors....
    ContentElementType: FILE; file: HtmlFile:incognito_mode_start_page.html
    Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = false
    getTreeElement() = Element(FILE)
    vFile instanceof VirtualFileWithId = true
    StubUpdatingIndex.canHaveStub(vFile) = false: ContentElementType: FILE; file: HtmlFile:incognito_mode_start_page.html
    Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = false
    getTreeElement() = Element(FILE)
    vFile instanceof VirtualFileWithId = true
    StubUpdatingIndex.canHaveStub(vFile) = false
java.lang.AssertionError: ContentElementType: FILE; file: HtmlFile:incognito_mode_start_page.html
    Boolean.TRUE.equals(getUserData(BUILDING_STUB)) = false
    getTreeElement() = Element(FILE)
    vFile instanceof VirtualFileWithId = true
    StubUpdatingIndex.canHaveStub(vFile) = false
    at com.intellij.psi.impl.source.PsiFileImpl.calcStubTree(PsiFileImpl.java:996)
    at com.intellij.psi.stubs.StubProcessingHelperBase.processStubsInFile(StubProcessingHelperBase.java:47)
    at com.intellij.psi.stubs.StubIndexImpl$2.perform(StubIndexImpl.java:245)
    at com.intellij.psi.stubs.StubIndexImpl$2.perform(StubIndexImpl.java:236)
    at com.intellij.util.indexing.ValueContainer.forEach(ValueContainer.java:60)
    at com.intellij.psi.stubs.StubIndexImpl.process(StubIndexImpl.java:236)
    at com.intellij.psi.stubs.StubIndexImpl.get(StubIndexImpl.java:210)
    at com.intellij.psi.stubs.StubIndex.safeGet(StubIndex.java:73)
    at com.intellij.psi.impl.java.stubs.index.JavaSuperClassNameOccurenceIndex.get(JavaSuperClassNameOccurenceIndex.java:49)
    at com.intellij.psi.impl.search.JavaDirectInheritorsSearcher$5.compute(JavaDirectInheritorsSearcher.java:107)
    at com.intellij.psi.impl.search.JavaDirectInheritorsSearcher$5.compute(JavaDirectInheritorsSearcher.java:104)
    at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:939)
    at com.intellij.psi.impl.search.JavaDirectInheritorsSearcher.execute(JavaDirectInheritorsSearcher.java:104)
    at com.intellij.psi.impl.search.JavaDirectInheritorsSearcher.execute(JavaDirectInheritorsSearcher.java:48)
    at com.intellij.util.ExecutorsQuery.processResults(ExecutorsQuery.java:43)
    at com.intellij.util.AbstractQuery.forEach(AbstractQuery.java:77)
    at com.intellij.util.UniqueResultsQuery.process(UniqueResultsQuery.java:66)
    at com.intellij.util.UniqueResultsQuery.forEach(UniqueResultsQuery.java:56)
    at com.intellij.psi.search.searches.ClassInheritorsSearch.processInheritors(ClassInheritorsSearch.java:278)
    at com.intellij.psi.search.searches.ClassInheritorsSearch.access$100(ClassInheritorsSearch.java:46)
    at com.intellij.psi.search.searches.ClassInheritorsSearch$1.execute(ClassInheritorsSearch.java:75)
    at com.intellij.psi.search.searches.ClassInheritorsSearch$1.execute(ClassInheritorsSearch.java:53)
    at com.intellij.util.ExecutorsQuery.processResults(ExecutorsQuery.java:43)
    at com.intellij.util.AbstractQuery.forEach(AbstractQuery.java:77)
    at org.jetbrains.android.facet.AndroidFacet.fillMap(AndroidFacet.java:979)
    at org.jetbrains.android.facet.AndroidFacet.getInitialClassMap(AndroidFacet.java:946)
    at org.jetbrains.android.facet.AndroidFacet.getClassMap(AndroidFacet.java:892)
    at org.jetbrains.android.dom.AndroidDomElementDescriptorProvider.getDescriptor(AndroidDomElementDescriptorProvider.java:62)
    at org.jetbrains.android.dom.AndroidDomElementDescriptorProvider.getDescriptor(AndroidDomElementDescriptorProvider.java:91)
    at com.intellij.psi.impl.source.xml.XmlTagImpl.computeElementDescriptor(XmlTagImpl.java:461)
    at com.intellij.psi.impl.source.xml.XmlTagImpl.getDescriptor(XmlTagImpl.java:446)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.checkTagByDescriptor(XmlHighlightVisitor.java:284)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.checkTag(XmlHighlightVisitor.java:164)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.visitXmlToken(XmlHighlightVisitor.java:128)
    at com.intellij.psi.impl.source.xml.XmlTokenImpl.accept(XmlTokenImpl.java:44)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.visit(XmlHighlightVisitor.java:724)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass$5.run(GeneralHighlightingPass.java:300)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:419)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.access$300(GeneralHighlightingPass.java:65)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass$7.run(GeneralHighlightingPass.java:425)
    at com.intellij.codeInsight.daemon.impl.DefaultHighlightVisitor.analyze(DefaultHighlightVisitor.java:87)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:422)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.access$300(GeneralHighlightingPass.java:65)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass$7.run(GeneralHighlightingPass.java:425)
    at com.intellij.codeInsight.daemon.impl.analysis.XmlHighlightVisitor.analyze(XmlHighlightVisitor.java:734)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:422)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.access$300(GeneralHighlightingPass.java:65)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass$7.run(GeneralHighlightingPass.java:425)
    at com.intellij.codeInsight.daemon.impl.RefCountHolder.analyze(RefCountHolder.java:298)
    at com.intellij.codeInsight.daemon.impl.analysis.HighlightVisitorImpl.analyze(HighlightVisitorImpl.java:163)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.analyzeByVisitors(GeneralHighlightingPass.java:422)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.collectHighlights(GeneralHighlightingPass.java:378)
    at com.intellij.codeInsight.daemon.impl.GeneralHighlightingPass.collectInformationWithProgress(GeneralHighlightingPass.java:218)
    at com.intellij.codeInsight.daemon.impl.ProgressableTextEditorHighlightingPass.doCollectInformation(ProgressableTextEditorHighlightingPass.java:86)
    at com.intellij.codeHighlighting.TextEditorHighlightingPass.collectInformation(TextEditorHighlightingPass.java:61)
    at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass$1$1.run(PassExecutorService.java:357)
    at com.intellij.openapi.application.impl.ApplicationImpl.tryRunReadAction(ApplicationImpl.java:1171)
    at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass$1.run(PassExecutorService.java:348)
    at com.intellij.openapi.progress.ProgressManager.executeProcessUnderProgress(ProgressManager.java:209)
    at com.intellij.openapi.progress.impl.ProgressManagerImpl.executeProcessUnderProgress(ProgressManagerImpl.java:212)
    at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.doRun(PassExecutorService.java:345)
    at com.intellij.codeInsight.daemon.impl.PassExecutorService$ScheduledPass.run(PassExecutorService.java:321)
    at com.intellij.concurrency.JobLauncherImpl$2.call(JobLauncherImpl.java:139)
    at com.intellij.concurrency.JobLauncherImpl$2.call(JobLauncherImpl.java:135)
    at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
    at java.util.concurrent.FutureTask.run(FutureTask.java:138)
    at com.intellij.concurrency.PrioritizedFutureTask.access$101(PrioritizedFutureTask.java:32)
    at com.intellij.concurrency.PrioritizedFutureTask$1.run(PrioritizedFutureTask.java:72)
    at com.intellij.concurrency.PrioritizedFutureTask.run(PrioritizedFutureTask.java:115)
    at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:895)
    at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:918)
    at java.lang.Thread.run(Thread.java:680)

A:

I had the same issue, after googling around I found the answer to be simply Invalidating the cache and then restarting Android Studio. File > Invalidate Cache / Restart. Then from the dialog choose "Invalidate and restart"


Q:

Bluefish Turns Belly-Up

Earlier this afternoon I was using Bluefish Editor on Ubuntu 14.04 LTS with no problem. After installing this afternoon's kernel patch (3.13.0-76-generic), even before rebooting, Bluefish will no longer launch. The first twice I saw the "Applicaton has crashed" alert; now I don't even see that. The only trace I can find is a single-line entry in syslog:

kernel: [ 2947.945466] traps: bluefish[10388] trap int3 ip:7feb062cec13 sp:7fff52a723b0 error:0

I have reinstalled, then removed and reinstalled; what else should I try? I'm working with Bluefish 2.2.5 on Ubuntu 14.04LTS.

A:

Corrupted local files
In many cases, when removing/reinstalling does not work, corrupted local files are the cause. Often these local files are in a hidden folder (starting with a dot) in your home directory.
In the case of Bluefish, just remove the folder ~/.bluefish. That should work :)


Q:

AssertionError: 302 != 200

I tried to create a test in my tests.py
class TaskViewTests(TestCase):
    def test_task_view_with_no_task(self):
        """
        If no task exist, an appropriate message should be displayed.
        """
        userName = 'esutek'
        response = self.client.get(reverse('actuser:task',args=(userName,)))
        self.assertEqual(response.status_code, 200)
        self.assertContains(response, "No task are available.")
        self.assertQuerysetEqual(response.context['taskList'], [])

However it gives me this error message.
I don't have any clue why this happened. I just followed the tutorial.
actuser:task
views.py
def task(request, userName):
    """ User task list in actInbox
    """

    user = ActuserViewModel()
    user.get_task_list(userName)

    return render(request, 'actuser/task.html', {
                'userName': userName,
                'taskList': user.taskList,
                'dateToday': user.dateToday,
           })

viewmodels.py
def get_task_list(self, userName):
    self.taskList = Task.objects.filter(executor = userName, parent_task_id=EMPTY_UUID).order_by('due_date')
    #get date now with this format 05/11
    self.dateToday = datetime.date.today()

Actually I got 2 urls...
this is from the project
url(r'^(?P<userName>[0-9a-zA-Z--]+)/', include('actuser.urls', namespace="actuser")),

and this one is from actuser.urls
url(r'^task/$', views.task, name='task'),

A:

HTTP 302 means that you are redirected to some other URL. You can do a redirect intentionally if you use a RedirectView for example, or accidentally if you forget to write slash at the end of the request URL and you have APPEND_SLASH enabled (in that case, you get HTTP 301 instead of 302).
You need a slash at the end:
url(r'^(?P<userName>[0-9a-zA-Z-]+)/task/$', ...


Q:

Python: literally "printing" a function

For reasons I won't get into, I need some way to literally print a function.
I know when you run print on a function object you get some complicated <010101045 function> output. So to my understanding perhaps the only way to do this is run some kind of python notepad module. Then I could devise an algorithm to write a line of text to match each function line so as to get a printed function.
If anyone knows some other way to achieve this, please do tell because I am sure doing it this way is incredibly complicated. If however this is the only way, if someone could walk me through the basic steps to doing so that would also be greatly appreciated.
It occurred to me also that it would be interesting to be able to have the syntax of the printed function be saved in python format so that I could literally just import it directly into a program if I wanted. Yes, I realize this is getting really complicated, but again, a general walk through would be really cool if anyone knows how to do this.
If anyone has gotten as far as automating the aforementioned process to the point where a program could modify an imported module from inside of the program importing it, now that would really cool.
(In an ideal case of course the modified version would be saved under a different name and be imported as well as the previous version and handled at that point within the program doing the importing)
I guess at this point I'm just curious about the basic commands for importing, saving, and modifying of files from within a python program.
All insight is appreciated,
Thanks,
PS: if you are wondering why I want to do all of this, it should be obvious, if not it would take a while to explain.

A:

Use inspect.getsource:
def a():
    pass

import inspect
print inspect.getsource(a)

Of course, this only works if you have access to the original source.
If you don't have the original source, the most you could get is the byte code (see dis.dis).
EDIT: The Python interactive shell is one example where inspect does not have access to the source.


Q:

How can I change my username, profile, and other settings on the Android mobile application?

Can anyone offer me some help on how to change my username and other settings using the android cellphone application?

A:

It doesn't seem to be possible to edit user profiles from within the Android app. The Meta Stack Exchange page that introduced it does not mention it, and the feature request Ability to update profile from the StackExchange Android App has been open since October 2013.
It's unclear what you mean by 'settings'. On the desktop site, going to your profile > Edit Profile & Settings > Preferences, there are what would normally be considered 'settings' for the site - there's really no chance of those being editable from the Android app.
On the other hand, if you click the menu button (upper left hand on the app) and scroll to the bottom, there is a Settings button that allows you to control the notification settings (on/off, vibrate on/off, notification sound, quiet hours), but that's about it.
And to emphasize a bit - if you have questions about the network-wide functioning of the engine, and particularly with specialized topics like the Android and iOS apps, the mother meta at Meta Stack Exchange is a much better place to ask.


Q:

Proving an oblique asymptote

$$\lim_{x\to +\infty} (\ln (e^{2x}-e^x+1) -2x)$$
It must be equal to zero, I tried L'hopital's rule after taking $2x$ common, but I got an answer of infinity.
Can you help me solve it please?

A:

\begin{align*}
\lim_{x \to +\infty} e^{\ln(e^{2x} - e^x + 1) - 2x} &= \lim_{x \to \infty} \frac{e^{\ln(e^{2x} - e^x + 1)}}{e^{2x}} \\
&= \lim_{x \to \infty} \frac{e^{2x} - e^x + 1}{e^{2x}} \\
&= \lim_{x \to \infty} (1 - e^{-x} + e^{-2x}) \\
&= 1
\end{align*}
Therefore, $\lim_{x \to +\infty} (\ln(e^{2x} - e^x + 1) - 2x) = \ln(1) = 0$.


Q:

How to see if RichTextBox value appeared on the UI

I have a LongListSelector and use inside it a RichTextBox
<DataTemplate>
    <Grid>
        <RichTextBox>
            <Paragraph>
                <Run Text="{Binding Description}"/>
            </Paragraph>
        </RichTextBox>
    </Grid>
</DataTemplate>

because of a long list of data, there is a delay in appearing RichTextBox's data. everything is loaded but texts appear later.
No problem with a delay, but It gets annoying when I try to scroll to a particular item in LongListSelector by its .ScrollTo method. In the Loaded event handler of the form or the LLS (no difference) I call ScrollTo but its execution finishes and scrolls to the item before appearing the text of RichTextBox on the screen, So after appearing the text, it gets longer, and it is not on the right item any more.
I thought of a delay in executing the ScrollTo method, to let everything appear in the screen, but since my app is not multithread, I couldn't end up with a successful sleep or timer.
How can I solve this? How can I wait until RichTextBox's loading finished?
(It's a WP8 app)

A:

You could try using LayoutUpdated(), the last time it fires the content is loaded.


Q:

Reading a non-standard text file in Python

I am trying to read a file with following table. But currently when I try to do it my way, it sees all the values as strings, and I need the values as integers, floats, and lists.
0  1  [5]    [1,3]  1  -1    0    [5]
1  1  [4,5]  [0,2]  2  -1    3    [2]
2  1  [4]    [1,3]  2  0     3    [1]
3  1  []     [0,2]  1  0     0    []
4  0  []     [1,2]  3  -0.5  4.5  []
5  0  []     [0,1]  3  -1.5  1.5  [0]

This is my code:
regions =[]
with open('country.txt', 'r') as fh:
    data = fh.readlines()
for i in data[1:-1]:
    row = []
    for s in i.split():
        row.append(s)
    regions.append(row)
print(regions)

A:

You can use row.append(ast.literal_eval(s)) or row.append(json.loads(s)) as a simple way to parse numbers and lists.


Q:

Markers hidden by axis

Some data I have to plot have coordinates such as (20,0), (10,0), etc... Basically some of the points belong to the x-axis.
The problem is, these points are hidden by the axis; i.e. the markers are behind the line and therefore cannot be seen properly.
Here is an example of my figure: http://i.stack.imgur.com/FNcob.png
Does anybody have an idea to solve this problem? I am running out of idea...
Thanks.
Viktor

A:

Matplotlib "snaps" plot limits to "whole" (factors of 2, 5, 10, 100, etc) numbers, by default.  This often means that your data may wind up on the boundary of the plot.
ax.margins allows you to add a padding factor before this autoscaling for the plot is calculated.  It's a quick way to avoid the problem of points on the plot boundary.
As a quick example of the problem:
import matplotlib.pyplot as plt

x, y = [0, 10, 20], [10, 0, 0]
fig, ax = plt.subplots()
ax.plot(x, y, 'ko')
plt.show()

And an easy solution:
import matplotlib.pyplot as plt

x, y = [0, 10, 20], [10, 0, 0]
fig, ax = plt.subplots()
ax.plot(x, y, 'ko')

# Pad by 5% of the data range before autoscaling:
ax.margins(0.05)

plt.show()


Q:

Local variable unused in a using statement

When implementing a using block for the benefit of dispose, such as
using (var window = new DialogWindow(Dialogs.MyDialogType))
{
    //Some action here
}

I get an obvious resharper / visual studio warning that the local variable window is never used, since it is not mentioned in the using body.
This is technically correct, is there a way to declare variables like this that aren't explicitly used in the using body, but who's dispose method will get called once the using statement terminates?
Call me a sucker for neatness but I do not like having the gray warnings popping up all over the place.

A:

Just leave it out if you're not using it.  The below is perfectly valid:
using (new DialogWindow(Dialogs.MyDialogType))
{
    //Some action here
}

We use this quite often in our infrastructure as we use IDisposable to log entry/exit from blocks of code, so we can just do:
using (_log.Enter("some block")) {

}

There's no variable being assigned to, but the using will dispose of the object as normal.

A:

If you don't use variable it is enough to do the following
//unused variable will not give warning
using (new DialogWindow(Dialogs.MyDialogType))
{
   //Some action here
}


Q:

Image slideshow in R Shiny

I am still learning R and thus would request the experts in this platform to help me out.
I am trying to create a slideshow of .jpg images in a panel in Shiny. The below code when I run in RStudio gives me the slideshow in the Plot window of RStudio.
folder <- "D:/Photos/Foreign Trips/2014_07_08_USA_Irvine/JulyAugust/"
file_list <- list.files(path=folder, pattern="*.jpg", full.names = TRUE)
for (j in 1:30) {
        myJPG <- stack(file_list[[j]])
        plotRGB(myJPG)
}

But, when I try to put the same code in server.R and try to call through ui.R, I don't get the slideshow or any image getting displayed. I am getting a blank page when I click on the tab "Photo Slides". I tried using renderUI, renderImage and renderPlot but none works.
ui.R
tabPanel("Photo Slides",
plotOutput("trvImg")
),

server.R
output$trvImg <- renderPlot({
folder <- "D:/Photos/Foreign Trips/2014_07_08_USA_Irvine/JulyAugust/"
file_list <- list.files(path=folder, pattern="*.jpg", full.names = TRUE)
for (j in 1:30) {
myJPG <- stack(file_list[[j]])
plotRGB(myJPG)
}

As a learner, I am sure I'm going wrong somewhere and thus seek your help.
Thanks

A:

Another solution, with the slickR package (based on the slick javascript library).
library(shiny)
library(slickR)

ui <- fluidPage(
   sidebarLayout(
      sidebarPanel(
        ####
      ),

      mainPanel(
         slickROutput("slickr", width="500px")
      )
   )
)

server <- function(input, output) {

  output$slickr <- renderSlickR({
    imgs <- list.files("D:/Photos/Foreign Trips/2014_07_08_USA_Irvine/JulyAugust/", pattern=".png", full.names = TRUE)
    slickR(imgs)
  })

}

# Run the application
shinyApp(ui = ui, server = server)

A:

library(shiny)

imgs <- list.files("D:/Photos/Foreign Trips/2014_07_08_USA_Irvine/JulyAugust/", pattern=".png", full.names = TRUE)

ui <- fluidPage(

  titlePanel("Slideshow"),

  sidebarLayout(
    sidebarPanel(
      actionButton("previous", "Previous"),
      actionButton("next", "Next")
    ),

    mainPanel(
      imageOutput("image")
    )
  )
)

server <- function(input, output, session) {

  index <- reactiveVal(1)

  observeEvent(input[["previous"]], {
    index(max(index()-1, 1))
  })
  observeEvent(input[["next"]], {
    index(min(index()+1, length(imgs)))
  })

  output$image <- renderImage({
    x <- imgs[index()]
    list(src = x, alt = "alternate text")
  }, deleteFile = FALSE)
}

# Run the application
shinyApp(ui = ui, server = server)

If you want the buttons below the image, you can do:
  sidebarLayout(
    sidebarPanel(
      # actionButton("previous", "Previous"),
      # actionButton("next", "Next")
    ),

    mainPanel(
      imageOutput("image"),
      fluidRow(
        column(1, offset=1, actionButton("previous", "Previous")),
        column(1, offset=1, actionButton("next", "Next"))
      )
    )
  )


Q:

Drawing the quadratic equation curve in c#

I am very new to c# System Draw so please do help me on my code. i am trying to plot the quadratic equation curve and is using the "for" loop in order to dot 10 coordinates for the curve. i have tested out this code many times and nothing ever appears when i start the code. Also whenever i run the code, i get the message ArgumentException was Unhandled, Parameter is not valid with the code "  g.DrawCurve(aPen, Points);" highlighted. please help me on this problem i have spent many days trying to fix.
{
    public Form1()
    {
        InitializeComponent();
    }

    protected override void OnPaint(PaintEventArgs e)
    {

        float a = 10, b = 30, c = 10;
        double x1, x2, delta, cx1, cx2, y1, y2;
        int icx1, iy1, icx2, iy2;
        delta = (b * b) - (4 * a * c);
        x1 = ((b * (-1)) + Math.Sqrt(delta)) / (2 * a);
        x2 = ((b * (-1)) - Math.Sqrt(delta)) / (2 * a);
        for (int i = (-10); i <= 10; i = i + 1)
        {
            cx1 = i * x1;
            cx2 = i * x2;
            y1 = (cx1 * cx1 * a) + (cx1 * b) + c;
            y2 = (cx2 * cx2 * a) + (cx2 * b) + c;
            icx1 = Convert.ToInt32(cx1);
            iy1 = Convert.ToInt32(y1);
            icx2 = Convert.ToInt32(cx2);
            iy2 = Convert.ToInt32(y2);

            Graphics g = e.Graphics;
            Pen aPen = new Pen(Color.Blue, 1);
            Point point1 = new Point(icx1, iy1);
            Point point2 = new Point(icx2, iy2);
            Point[] Points = { point1,point2 };
            g.DrawCurve(aPen, Points);
            aPen.Dispose();
            g.Dispose();

        }

A:

The key problem is that the code disposes the Graphics object. On the second iteration the Graphics object has been disposed and the call to DrawCurve will fail.
And as mentioned in the comments, the DrawCurve method expects 3 points in the array. See under Remarks on the MSDN Page for DrawCurve
All other Dispose calls for the Pen should be reduced as much as possible to prevent re-creating so many pens.
As for the graph: I am not entirely sure what you are trying to do but if you are trying to draw a parabola, you should not solve the quadric equation but instead put the x value in the equation.
Pseudo code:
for x = -10 to 10 step 3

    if SavePoint == null

        x1 = x
        y1 = a * x1 * x1 + b * x1 + c

        point1 = TransformToLocalCoordinates(x1, y1)

    Else

        point1 = SavePoint

    End if

    x2 = x + 1
    y2 = a * x2 * x2 + b * x2 + c

    point2 = TransformToLocalCoordinates(x2, y2)

    x3 = x + 2
    y3 = a * x3 * x3 + b * x3 + c

    point3 = TransformToLocalCoordinates(x3, y3)

    DrawCurve point1, point2, point3

    SavePoint = point3

next


Q:

Get time between two times on night to morning

I have a table that stores schedules by initial hour to end hour, some structure like
| SCHEDULE_NAME | START_HOUR    | END_HOUR  |
| ------------- | ------------- | --------- |
| Morning Shift | 8:00          | 10:00     |
| Evening Shift | 13:00         | 17:00     |
| Night Shit    | 22:00         | 2:00      |

So I have to validate if an hour is between the start and end hours, I have a table with all hours as date that runs to this type of validation in a function
DECLARE @HOUR time = '9:00'
IF @HOUR BETWEEN @START_HOUR AND @END_HOUR
SELECT 'IS BETWEEN'
ELSE
SELECT 'IS NOT'

So it works fine on schedules where start hour and end hour are one after the other (the first two cases), but on the third case, an overnight schedule, it fails as it considers the end hour lower than the hour, like this case
DECLARE @HOUR time = '1:00'
-- Here START_HOUR is '22:00' AND END_HOUR is '2:00'
IF @HOUR BETWEEN @START_HOUR AND @END_HOUR
SELECT 'IS BETWEEN'
ELSE
SELECT 'IS NOT'

So it returns IS NOT but it should be considered that it is between that schedule
Just in case, no schedules end and start hour can be the same, and I'm using SQL Server 2014

A:

I see a design problem them. As @insilenzio said on his comment you should be saving the data as DateTime, not Time.
However you could cast the data to datetime before doing the comparison, setting the end_date greatter than star_date, and ensuring the hour to check is on the same day that end_date.
For example, taking your last example:
Change hour to : '2016-01-02 09:00:00'
Change star_hour to: '2016-01-01 22:00:00'
Change end_hour to: '2016-01-02 02:00:00'

Then your code will work with no problems. As I said, you mus ensure that @HOUR is on the same day that @END_HOUR. If not it will not operate correctly for obviously reasons.
As an example code you could use in SQL Server 2012 and greater: (maybe you will have to correct the sintax, but it's close to work)
DECLARE @HOUR Datetime = '2016-01-02 01:00:00'
IF @HOUR BETWEEN (cast('2016-01-01' as datetime) + cast(@START_HOUR as datetime)) AND (cast('2016-01-02' as datetime) + cast(@END_HOUR as datetime))
SELECT 'IS BETWEEN'
ELSE
SELECT 'IS NOT'


Q:

CMake: Extracting tar gives an error without a message

I'd like to download a tar file and extract it in ${CMAKE_BINARY_DIR}. All my attempts have failed, and I keep getting a non-zero return value. The following is an MCVE:
cmake_minimum_required(VERSION 3.0)

set(QRCODE_LIB_URL "https://fukuchi.org/works/qrencode/qrencode-3.4.4.tar.bz2")
set(QRCODE_LIB_DOWNLOAD_TARGET "${CMAKE_BINARY_DIR}/qrencode.tar.bz")
file(DOWNLOAD ${QRCODE_LIB_URL} ${QRCODE_LIB_DOWNLOAD_TARGET} SHOW_PROGRESS)
execute_process(
    COMMAND "${CMAKE_COMMAND} -E tar xvz ${QRCODE_LIB_DOWNLOAD_TARGET}"
    WORKING_DIRECTORY ${CMAKE_BINARY_DIR}
    OUTPUT_VARIABLE QRCODE_EXTRACT_OUTPUT
    ERROR_VARIABLE QRCODE_EXTRACT_OUTPUT
    RESULT_VARIABLE QRCODE_EXTRACT_RETURN_VALUE
    )

if (NOT QRCODE_EXTRACT_RETURN_VALUE EQUAL 0)
    message(FATAL_ERROR "Error: ${QRCODE_EXTRACT_OUTPUT}")
endif()

project(cmakeTarTest)
add_executable(${PROJECT_NAME} "main.cpp") # this can be removed

The most problematic part is that the error doesn't show any message, which I don't understand. I've been using this same recipe (with execute_process) for a while to run many scripts, including python scripts. Apparently there's something different here I can't catch.

A:

I figured out the solution. The command should be like this:
COMMAND "${CMAKE_COMMAND}" "-E" "tar" "xvz" "${QRCODE_LIB_DOWNLOAD_TARGET}"

The hint from Tsyvarev's comment made me realize it.
EDIT: I still don't understand why the error variable was empty.


Q:

jQuery setTimeout with overlay on submit

I have a form that uses a jQTools overlay and jQuery .ajax submission routine. I would like the overlay to close once the success/error message has been displayed. How would I incorporate a setTimeout into this (only after success/error msg has been displayed) the ID of the overlay is "#overlayForm"
    $.ajax({
        type: $(form).attr('method'),
        url: form.action,
        data: dataString,
        clearForm: true,
        success: function (data) {
            if (data == "Mail sent") {
                $("#formWrap, #supportHdln").hide();
                $("#thankYou").html('
Thank You | We have received your request.

A Customer Service Representative from Kinetick will contact you shortly
').fadeIn("slow");

            } else {
                $("#formWrap, #supportHdln").hide();
                $("#error").html('
Uh Oh | We have encountered an error in your submission.

 Please check that all required form fields were filled out, if that does not resolve the issue, please email us here.
').fadeIn("slow");
            }
        }
    });
    return false;
}

A:

The simplest thing I suppose is an anonymous function:
setTimeout(function(){$("#overlayForm").hide();},1000);

I have looked at the documentation of Jquery Tools, I think you must talk about this:
http://flowplayer.org/tools/overlay/index.html
They talk about "close()".
Then it would be:
$("#overlayForm").close();


Q:

If $A$ is an $n×n$ orthogonal matrix with $\text{det}(A)=1$ and $n$ odd, then show that $\text{det}(I-A)=0$.

Primarily, here $A$ can be either real or complex matrix and as $A$ is orthogonal, hence all the eigenvalues of $A$ are of the form $e^{i\Delta}$ for $i^2=-1$ and real $\Delta$.
I tried to show it by induction but I couldn't prove for the $n=2$ case that $1$ is an eigenvalue of $A$. Can someone please provide me with a short hint?

A:

Every $n \times n$ orthogonal matrix $M$ with determinant $1$ defines an orientation-preserving rotation on the $n-1$ sphere $S^{n-1} \subset \mathbb{R}^n$, and this rotation has a fixed point at $x$ iff $x$ is an eigenvector of $M$ with eigenvalue $1$. The problem statement is thus a consequence of the well-known topological fact that every diffeomorphism from an even-dimensional sphere to itself of degree different to $-1$ has a fixed point.


Q:

In MS Azure AD, I am trying to configure the SSO, but SSO option is not showing up under the selected Enterprise Application

I am configuring the Azure Active Directory as SSO Authentication Provider for Salesforce. I have already Registered the Application in Azure. When I try to configure SSO in Azure for the registered application but I am not able to see Single sign on option under Manage for the aplication. Please help.

A:

Thank you for responding. Actually it is more of a subscription issue. I am not able to add the add the 'New application' under Enterprise Application option. Once I get that solved then I will try your solution. Thanks again.


Q:

why the code using :eq("+e+")?

$(function(){
    $(".nav ul li").each(function(e){
        $(this).mouseover(function(){
            $(".subnav .left div:not(:eq("+e+"))").hide();
            $(".subnav .left div").eq(e).show();
        })
    })
})

what's div:not(:eq("+e+"))")meaning in the above code? i don't know why it use two + in the parenthesis? could i use div:not(:eq(e))") to instead of it? thank you.

A:

In JavaScript, + is used to add two things together.
In this case, it's adding strings.
This:
".subnav .left div:not(:eq("+e+"))"

Means adding three strings to become one:

.subnav .left div:not(:eq(
e
))

The final result is the value of e added to the jQuery selector, e being the index of the currently iterated element.
The outcome of this whole thing in simple words is: when mouse is over specific list item, hide all <div> elements under .subnav .left except the <div> in same index as the hovered list item.
Edit: You can avoid the messy code and dump the + by having such code instead:
$(".subnav .left div").not(function(index) {
    return (index === e);
}).hide();

More lines, but also more elegant as you show the logic inside a function, not a string.


Q:

Loading a ViewController from Swift Framework

I am creating a Swift framework which has ABC.Storyboard and one ViewController. I have referenced all the UIView to MyViewController which is also present in Framework.
When I add this framework to my app and try to load this MyViewController , I get  setValue:forUndefinedKey:]: this class is not key value coding-compliant for the key myImageView error.

A:

Hitesh,
This happens only when your storyboard has stale information about the IBOutlets of its views.
How it happened?
You must be having an ImageView in your Storyboard's ViewController (MyViewController). Sometime during your development of the framework you have dragged an IBOutlet to the owner class (lets say MyViewController.swift) with the name myImageView
Later at somepoint you must have deleted the property named myImageView from your ownerClass (MyViewController.swift) and forgot to remove the reference from the storyboard to that property.
What Happens?
Your Storyboard's ViewController is still under the assumption that there is a property named myImageView in its ownerClass and it is an IBOutlet for its component ImageView.
So when the view is loaded it looks for that property when property not found it throws you error that this class is  not coding-compliant for the key myImageView because it failed to locate property named myImageView.
Solution
Open your storyboard select the MyViewController go to Connection inspector (click the last option on the right side which will show you the IBOutlets for each component in the ViewController) select your ImageView you will find something like this,

Click on the small 'x' symbol infront of the (myImageView) - (x MyViewController) to unlink it from the deleted property reference :) Clean the build and re run :)
Ta daaa problem solved :) happy coding :)


Q:

C Executable does not run on linux Mint

I am running Linux Mint 17.1 Rebecca xfce edition.
I installed libc6-dev and successfully compiled a C program.
My .out does not execute when I double click the file, nor when I right click and select execute. I have actually looked for an answer to this but all answers I found were so specific that it did not answer my question.
Also I have recently migrated from Windows. Just want you to know I am not quite Linux Savvy. I am also new to programming.

A:

You haven't provided much information on the nature of the program itself. So I'm going to assume it is a console program. On Windows, running a console program from say, a file manager will cause a console window to appear. However, on Linux this will cause the program to run 'in the background' (ie. it will not create a console window). The answer is to run the program through a terminal.
$ cd /directory/of/executable
$ ./executable_name


Q:

Containerized web app on iIS

Is there a way to deploy a containerized say .net core web app to IIS on a web server and use things like docker swarm and a virtual load balancer.
Am I looking at this all wrong? Would IIS even factor here?

A:

If you want to go down this path, IIS does run in a (Windows) container, however most web apps I’ve seen uses Kestrel as the application web server (I.e. the default netcore images) and some kind of reverse proxy in front (Nginx, HAproxy) to handle things like load balancing, SSL termination and serving of static content.
I think the use case for IIS (though I haven’t used it so I may be wrong here) is to serve legacy ASP.net applications in a containerized environment.
See:
https://hub.docker.com/r/microsoft/iis/


Q:

akka aws ec2 connection refused

I have a client/server software working perfectly fine in local but I can't figure out why, it does'nt work when I set up the server on a remote aws ec2 instance. When the client tries to connect I got the following error :
    [08/03/2016 12:47:36.231] [ClientSystem1213-akka.remote.default-remote-dispatcher-6] [akka.tcp://ClientSystem1213@127.0.0.1:2555/system/endpointManager/reliableEndpointWriter-akka.tcp%3A%2F%2FSolarServerSystem%4052.59.106.25%3A2552-0/endpointWriter] AssociationError [akka.tcp://ClientSystem1213@127.0.0.1:2555] -> [akka.tcp://SolarServerSystem@52.59.106.25:2552]: Error [Association failed with [akka.tcp://SolarServerSystem@52.59.106.25:2552]] [
akka.remote.EndpointAssociationException: Association failed with [akka.tcp://SolarServerSystem@52.59.106.25:2552]
Caused by: akka.remote.transport.netty.NettyTransportExceptionNoStack: Connection refused: /52.59.106.25:2552
]

Running netstat -tnlp on the server gives the following :
Proto Recv-Q Send-Q Local Address               Foreign Address             State       PID/Program name
tcp        0      0 ::ffff:127.0.0.1:2552       :::*                        LISTEN      4516/java

The aws ec2 security group inbound and outbound are open for all trafic (all protocol - all port).
The akka conf common to client and server is
akka {

  actor {
    provider = "akka.remote.RemoteActorRefProvider"
  }

  remote {
    enabled-transports = ["akka.remote.netty.tcp"]
    netty.tcp {
      hostname = "127.0.0.1"
      send-buffer-size = 5000000b
      receive-buffer-size = 5000000b
      maximum-frame-size = 2500000b
    }

    watch-failure-detector {
      threshold = 100
      acceptable-heartbeat-pause = 20 s
    }
    transport-failure-detector {
      heartbeat-interval = 4 s
      acceptable-heartbeat-pause = 20 s
    }
  }

}

(I copy paste de failure and buffer part from Amazon AWS EC2 ports: connection refused)
The server only part of the conf is :
include "common"

akka {
  remote.netty.tcp.port = 2552
}

The client part is :
include "common"
include "javafx-swing-dispatch"

akka {
  remote.netty.tcp.port = 2555
  remote {
    log-config-on-start = on
    log-sent-messages = on
    log-received-messages = on
  }
}

javafx-swing-dispatch.conf being :
javafx-dispatcher {
  type = "Dispatcher"
  executor = "akka.dispatch.gui.JavaFXEventThreadExecutorServiceConfigurator"
  throughput = 1
}

swing-dispatcher {
  type = "Dispatcher"
  executor = "akka.dispatch.gui.SwingEventThreadExecutorServiceConfigurator"
  throughput = 1
}

(taken from https://gist.github.com/mucaho/8973013)
Any clues where the problem comes from ?

A:

It was actually an akka configuration problem. An aws ec2 instance has a public and a private ip. The public ip is visible in the aws console on the running instance screen. The private ip is visible on the bottom part of the same screen in the description tab (and by default in the instance prompt).
These two different addresses have to be informed to the akka configuration as follow :
akka.remote.netty.tcp {
     hostname = "XX.XX.XX.XX"      # external/public (logical) hostname
     port = 2555                   # external/public (logical) port

     bind-hostname = "192.168.0.4" # internal/private (bind) hostname
     bind-port = 2555              # internal/private (bind) port
}


Q:

Check if a record is selected from a dataPointGrid

I have a dataPointGrid and I want to check if a record from it is being selected (mouse clicked on)

Data point grid above. I want to check if a folder (record) is being selected.
Is there a method that does this?

A:

Add ListGrid#addSelectionChangedHandler() on list grid that is called when (row-based) selection changes within this grid. Note this method fires for each record for which selection is modified - so when a user clicks inside a grid this method will typically fire twice (once for the old record being deselected, and once for the new record being selected).
Look at the ListGrid#setSelectionType() as well that defines a listGrid's clickable-selection behavior (MULTIPLE, SINGLE, SIMPLE or NONE)