text:
Q: having issues with getline(cin) to array This code is part of an assignment I am working on but I can't figure out why the getline keeps returning a "no instance of overloaded function" error. I included the relevant code here and the line is towards the bottom. Any help getting "name" in to animals[i].d would be appreciated as I'm sure it's something simple. Thank you.
#include <iostream> // provides access to cin and cout
#include  <array>// provides access to std:array
#include <string> // required for getline

//--end of #include files-----------
//----------------------------------

using namespace std;
//----------------------------------

//**begin global constants**********
const int arraySize = 4; // **there is a subtle bug here (needs "const")
enum MyEnum // Needs to be before the struct that uses it
{
    Dog, Cat, Fish, Squirrel
};

struct MyStruct
{
    int a;
    float b;
    string c;
    MyEnum d;
};

//--end of global constants---------
//----------------------------------

//**begin main program**************
int main()
{
    // Initialization
    char myCString[arraySize] = { 0 };
    char myOtherCString[] = { "Yet another string" };
    int myInt[4] = { 27, 39, 0, 42 };
    string myString;
    MyStruct aStruct = { 4,3.5,"Dog", Dog};
    int x;
    int * pX;
    pX = &x;
    array <MyStruct, arraySize> Animals;
    // Storing values in uninitialized variables
    myCString[0] = 'A';
    myString = "A third string";
    x = 4;
    for (int i = 0; i<arraySize; i++)
    {
        Animals[i].a = rand() % 10;
        Animals[i].b = rand() % 100 / 100.0;
        Animals[i].c = MyEnum(rand() % 4);
        cout << "Enter a name: ";
        getline(cin, Animals[i].d);
    }

A: The second argument to std::string::getline() needs to be a std::string, but you're giving it a MyEnum instead.
If you want to read a std::string and store a MyEnum you need to have a lookup table to convert from one to the other.
EDIT: Actually you've just got c and d wrong way round, haven't you?
You want to assign a random number to d, and the string you read with getline() to c.

A: You using wrong parametters of function getline. MyEnum is not string. Use on of this:
istream& getline (istream&  is, string& str, char delim);
istream& getline (istream&& is, string& str, char delim);
istream& getline (istream&  is, string& str);
istream& getline (istream&& is, string& str);


text:
Q: Testing a c++ class for features I have a set of classes that describe a set of logical boxes that can hold things and do things to them. I have
struct IBox // all boxes do these
{
    ....
}

struct IBoxCanDoX // the power to do X
{
    void x();
}

struct IBoxCanDoY // the power to do Y
{
    void y();
}

I wonder what is the 'best' or maybe its just 'favorite' idiom for a client of these classes to deal with these optional capabilities
a)
    if(typeid(box) == typeid(IBoxCanDoX))
    {
         IBoxCanDoX *ix = static_cast<IBoxCanDoX*>(box);
         ix->x();
    }

b)
   IBoxCanDoX *ix = dynamic_cast<IBoxCanDoX*>(box);
    if(ix)
    {
         ix->x();
    }

c)
if(box->canDoX())
{
    IBoxCanDoX *ix = static_cast<IBoxCanDoX*>(box);
    ix->x();
}

d)  different class struct now
struct IBox
{
    void x();
    void y();
}
...
box->x(); /// ignored by implementations that dont do x

e) same  except
box->x() // 'not implemented' exception thrown

f) explicit test function
if(box->canDoX())
{
   box->x();
}

I am sure there are others too.
EDIT:
Just to make the use case clearer
I am exposing this stuff to end users via interactive ui. They can type 'make box do X'. I need to know if box can do x. Or I need to disable the 'make current box do X' command
EDIT2: Thx to all answerers
as Noah Roberts pointed out (a) doesnt work (explains some of my issues !).
I ended up doing (b) and a slight variant
   template<class T>
    T* GetCurrentBox()
    {
       if (!current_box)
          throw "current box not set";
       T* ret = dynamic_cast<T*>(current_box);
       if(!ret)
          throw "current box doesnt support requested operation";
       return ret;
    }
    ...
    IBoxCanDoX *ix = GetCurrentBox<IBoxCanDoX>();
    ix->x();

and let the UI plumbing deal nicely with the exceptions (I am not really throwing naked strings).
I also intend to explore Visitor

A: I suggest the Visitor pattern for double-dispatch problems like this in C++:
class IVisitor
{
public:
    virtual void Visit(IBoxCanDoX *pBox) = 0;
    virtual void Visit(IBoxCanDoY *pBox) = 0;
    virtual void Visit(IBox* pBox) = 0;
};

class IBox // all boxes do these
{
public:
    virtual void Accept(IVisitor *pVisitor)
    {
        pVisitor->Visit(this);
    }
};

class BoxCanDoY : public IBox
{
public:
    virtual void Accept(IVisitor *pVisitor)
    {
        pVisitor->Visit(this);
    }
};
class TestVisitor : public IVisitor
{
public:
    // override visit methods to do tests for each type.
};

void Main()
{
    BoxCanDoY y;
    TestVisitor v;
    y.Accept(&v);
}

A: Of the options you've given, I'd say that b or d are "best".  However, the need to do a lot of this sort of thing is often indicative of a poor design, or of a design that would be better implemented in a dynamically typed language rather than in C++.

A: A and B require run time type identification(RTTI) and might be slower if you are doing a lot checks. Personally I don't like the solutions of "canDoX" methods, if situations like this arise the design probably needs an upgrade because you are exposing information that is not relevant to the class.
If you only need to execute X or Y, depending on the class, I would go for a virtual method in IBox which get overridden in subclasses.
class IBox{
   virtual void doThing();
}
class IBoxCanDoX: public IBox{
   void doThing() {  doX(); }
   void doX();
}
class IBoxCanDoY: public IBox{
   void doThing() {  doY(); }
   void doY();
}

box->doThing();

If that solution is not applicable or you need more complex logic, then look at the Visitor design pattern. But keep in mind that the visitor pattern is not very flexible when you add new classes regularly or methods change/are added/are removed (but that also goes true for your proposed alternatives).

A: If you are using the 'I' prefix to mean "interface" as it would mean in Java, which would be done with abstract bases in C++, then your first option will fail to work....so that one's out.  I have used it for some things though.
Don't do 'd', it will pollute your hierarchy.  Keep your interfaces clean, you'll be glad you did.  Thus a Vehicle class doesn't have a pedal() function because only some vehicles can pedal.  If a client needs the pedal() function then it really does need to know about those classes that can.
Stay way clear of 'e' for the same reason as 'd' PLUS that it violates the Liskov Substitution Principle.  If a client needs to check that a class responds to pedal() before calling it so that it doesn't explode then the best way to do that is to attempt casting to an object that has that function.  'f' is just the same thing with the check.
'c' is superfluous.  If you have your hierarchy set up the way it should be then casting to ICanDoX is sufficient to check if x can do X().
Thus 'b' becomes your answer from the options given.  However, as Gladfelter demonstrates, there are options you haven't considered in your post.
Edit note:  I did not notice that 'c' used a static_cast rather than dynamic.  As I mention in an answer about that, the dynamic_cast version is cleaner and should be preferred unless specific situations dictate otherwise.  It's similar to the following options in that it pollutes the base interface.
Edit 2: I should note that in regard to 'a', I have used it but I don't use types statically like you have in your post.  Any time I've used typeid to split flow based on type it has always been based on something that is registered during runtime.  For example, opening the correct dialog to edit some object of unknown type: the dialog governors are registered with a factory based on the type they edit.  This keeps me from having to change any of the flow control code when I add/remove/change objects.  I generally wouldn't use this option under different circumstances.

A: If you are trying to call either of these classes actions from contingent parts of code, you I would suggest you wrap that code in a template function and name each class's methods the same way to implement duck typing, thus your client code would look like this.
template<class box>
void box_do_xory(box BOX){
    BOX.xory();
}

A: There is no general answer to your question. Everything depends. I can say only that:
- don't use a), use b) instead
- b) is nice, requires least code, no need for dummy methods, but dynamic_cast is a little slow
- c) is similar to b) but it is faster (no dynamic_cast) and requires more memory
- e) has no sense, you still need to discover if you can call the method so the exception is not thrown
- d) is better then f) (less code to write)
- d) e) and f) produce more garbage code then others, but are faster and less memory consuming

A: I assume that you will not only be working with one object of one type here.
I would lay out the data that you are working with and try to see how you can lay it out in memory in order to do data-driven programming. A good layout in memory should reflect the way that you store the data in your classes and how the classes are layed out in memory. Once you have that basic design structured (shouldn't take more than a napkin), I would begin organizing the objects into lists dependent on the operations that you plan to do on the data. If you plan to do X() on a collection of objects { Y } in the subset X, I would probably make sure to have a static array of Y that I create from the beginning. If you wish to access the entire of X occasionally, that can be arranged by collecting the lists into a dynamic list of pointers (using std::vector or your favorite choice).
I hope that makes sense, but once implemented it gives simple straight solutions that are easy to understand and easy to work with.

A: There is a generic way to test if a class supports a certain concept and then to execute the most  appropriate code. It uses SFINAE hack. This example is inspired by Abrahams and Gurtovoy's "C++ Template Metaprogramming" book. The function doIt will use x method if it is present, otherwise it will use y method. You can extend CanDo structure to test for other methods as well. You can test as many methods as you wish, as long as the overloads of doIt can be resolved uniquely.
#include <iostream>
#include <boost/config.hpp>
#include <boost/utility/enable_if.hpp>

typedef char yes;      // sizeof(yes) == 1
typedef char (&no)[2]; // sizeof(no)  == 2

template<typename T>
struct CanDo {
    template<typename U, void (U::*)()>
    struct ptr_to_mem {};

    template<typename U>
    static yes testX(ptr_to_mem<U, &U::x>*);

    template<typename U>
    static no testX(...);

    BOOST_STATIC_CONSTANT(bool, value = sizeof(testX<T>(0)) == sizeof(yes));
};

struct DoX {
    void x() { std::cout << "doing x...\n"; }
};

struct DoAnotherX {
    void x() { std::cout << "doing another x...\n"; }
};

struct DoY {
    void y() { std::cout << "doing y...\n"; }
};

struct DoAnotherY {
    void y() { std::cout << "doing another y...\n"; }
};

template <typename Action>
typename boost::enable_if<CanDo<Action> >::type
doIt(Action* a) {
    a->x();
}

template <typename Action>
typename boost::disable_if<CanDo<Action> >::type
doIt(Action* a) {
    a->y();
}

int main() {

    DoX         doX;
    DoAnotherX  doAnotherX;
    DoY         doY;
    DoAnotherY  doAnotherY;

    doIt(&doX);
    doIt(&doAnotherX);
    doIt(&doY);
    doIt(&doAnotherY);
}

redpajama_set_name: RedPajamaStackExchange


text:
Q: Varying Vertical Position of Sprite During Movement I have sprites in my iOS application that move across the screen horizontally, both left to right and right to left.  For most of these sprites, a straight line or a well-defined arc is acceptable.  I have some sprites, however, that I would like to have move a little more randomly, specifically varying the vertical position of the sprite as it moves.
In the following code, "y_variant_" is an ivar that specifies the degree of variance that I would like to apply.  It is a smaller value for natural objects like birds or man-made objects like paper airplanes, which should only move a small amount up and down as they fly, but a larger value for natural objects like insects and bees, which have much greater variance.
This is the code that I am currently using (the "update:" method for the sprite):
//  track/vary the object as it moves along its path...
- ( void ) update: ( ccTime ) delta

{

    //  ask director for the window size...
    CGSize const size = [ [ CCDirector sharedDirector ] winSize ];

    //  get the current position of the projectile...
    CGPoint const ptRaw = [ self position ];

    //  create a variant of the vertical position for "intelligent" items...
    CGPoint const pt = ( y_variant_
                       ? ccp( ptRaw.x
                            , ptRaw.y + y_variant_ * (float)( rand( ) % 25 ) * 0.02f - fmodf( ptRaw.x, y_variant_ )
                            )
                       : ptRaw
                       );
    [ self setPosition: pt ];
        :
        :
        :
        //  if we're supposed to stop the projectile on impact (a "brick wall", etc.)...
        if ( fStopProjectile == ObjectImpactActionStop )

            {

            //  object impact, if this is a "smart" projectile (i.e., something with a brain)...
            if ( y_variant_ )

                {

                //  move the projectile around the object...
                CCAction * const move = [ CCMoveTo actionWithDuration: 0.25f
                                                             position: ccpAdd( [ self position ]
                                                                             , ccp( - CS_IMAGE_OBJECT_W
                                                                                , CS_IMAGE_OBJECT_H
                                                                                )
                                                                             )
                                        ];

                [ self runAction: move ];

                }  // end "smart" projectile

            }  //  end projectile impact
        :
        :
        :
    return;

}  //  end update

You'll notice that there's logic involving collision with solid objects: if a solid obstruction (wall, building, etc.) is encountered, the object backs up and moves vertically to avoid the obstacle.
The problem that I'm running into is that the viewed motion is very erratic for the larger values of "y_variant_", and I would like it to appear smoother....
Even if you don't have a solution, any comments as to what can be improved or investigated would be appreciated.
Thanks for your help.
p.s.:  If you're feeling ambitious, one of the suggestions from a user was to have the bee very occasionally loop around backwards and then continue its path.  Once I've fixed the current "bouncing" problem, I'll incorporate that, so please keep that in mind....

A: There's no simple answer to your question. But if you're using Cocos2d, I would look into using actions instead of manually positioning the sprites. So to reiterate, I recommend you look into using actions. But here's a simple example that might help if you stick with manual positioning:
#define kAmountToMovePerFrameInY 10.0 / 60.0

@property float posYCurrentlyMovingTo;
@property SomeSpriteClass *theSpriteMoving;
@property float someXPosition;
@property float nextMoveAmount;

-(void)doStuffDuringUpdate
{

    if (_theSpriteMoving.position.y < labs(_posYCurrentlyMovingTo)) {
        //sprite is still moving to its position

        _theSpriteMoving.position = CGPointMake(_someXPosition, _theSpriteMoving.position.y + _nextMoveAmount);

    }else{
        float variationAmountInY = arc4random_uniform(200) - 100.0;
        _posYCurrentlyMovingTo = variationAmountInY;
        _nextMoveAmount = variationAmountInY * kAmountToMovePerFrameInY;

    }

}


text:
Q: Where is my application binary in Xcode to submit? I've built an app for the App Store (ex-iTunes store).  However, I can't figure out how to submit the app.
Where is the actual binary that I need to submit to the App Store?  What folder does it get built in?

A: You could use XCode and on the left expand "Products".  Highlight your .app and then go up top where it says "Action" drop that down and select "Reveal in Finder"

A: By default, you'll see a build directory inside the directory containing your project.
In that build directory:
<Project Name>.build` contains all the object files created during compilation
and a series of folders with the following naming scheme:
<build setting>-<platform>

You're likely looking for something like "Release-iphoneos".  In that folder you should find the .app package to submit.

A: Look at a path something like this:
"/Users/{user}/Library/Developer/Xcode/DerivedData/{appname-somehash}/Build/Products/Debug-iphoneos/{app-name}.app"
You can run "find" to locate it.


text:
Q: Condition for existence of solution to a power-tower equation. "For two positive number a, b which satisfies the condition $\ln a \ln b <0$. equation $a^{b^{a^{b^x}}}=x$ has only one root if and only if ${\frac{d}{dx}a^{b^x}}_{x=t}\geq-1$, where $a^{b^t}=t$"
It's the last unsolved proposition on my personal reserch.
Please help me prove this, or if it is false, let me know it. You can give a lot of help to this newbie at writing paper, just throwing several hints to him..
== added ==
some pictures to help you understand:
(before picture: $a^{b^{a^{b^x}}}=x$ is equivalent to $a^{b^x}=\log_b{\log_ax}$. and letting $f(x)=a^{b^x}$, it is same with $f(x)=f^{-1}(x)$)
Blue is $f$, red is $f^{-1}$
Graph when $f'(t)\geq-1$

Graph when $f'(t)<-1$

it is SO clear on the graphs. But hard to prove.
Q. Where did you get so far?
A. I've tried many ways. and the best result i got so far is: It is easily proved if I show that $f(f(x))''>0$ for $x<p$, $f(f(x))''=0$ for $x=p$, $f(f(x))''>0$ for $x>p$ for a number p. but... it is also hard.


text:
Q: The remote endpoint could not be called, or the response it returned was invalid. (alexa, aws) I'm currently getting into developing alexa-skills. This is in fact the 1st time I'm trying this and I kinda works out good so far. However, I stumbled upon a problem which seems to be wide-spreaded but I couldn't find an answer how to solve it.
First things first:
I started this skill by following a tutorial. It might be that this tutorial is outdated and therefore this error appears.
I created a skill from the scratch and it works to the part where the LaunchRequest is invoked:

As you can see, I get my response as expected. (works on the test-environment as well as on alexa itself). Now, when try to call an IntentRequest, I just get the error-message:

The remote endpoint could not be called, or the response it returned was invalid.

As I can tell from the picture / request, the correct intent-request is called (in my case getSubscriberCount ) - And this is the point where I have no idea anymore on how to resolve this problem.
To keep things short, this here is the JS-part for the Intent:
case "IntentRequest":
        // Intent Request
        console.log(INTENT REQUEST)
    switch(event.request.intent.name) {
        case "GetSubscriberCount":
            var endpoint = "my url"
            var body = ""
            https.get(endpoint, (response) => {
                response.on('data', (chunk) => { body += chunk })
    response.on('end', () => {
        var data = JSON.parse(body)
        var subscriberCount = data.items[0].statistics.subscriberCount
        context.succeed(
        generateResponse(
            buildSpeechletResponse(`Du hast momentan ${subscriberCount} Abonnenten`, true),
            {}
        )
    )

And this is causing my problems. To test what exactly is wrong, I tried the following:

*

*Called the endpoint in my browser --> Correct output

*Adjusted the "response" to the minimum to see if that works --> didn't work

*Checked several sources related to this error --> didn't help either

I saw some approaches to get rid of this, since this seems to be a common issue, but I got lost. Someone mentioned an environment variable, which I couldn't put my hands on. Another one suggested to run the JSON request manually, which I tried, but leading to the same error.
Hopefully you can help me out here.

A: Assuming you AWS lambda, it might be because you didn't create your response right or your AWS lambda function had a error.


text:
Q: Android NavBar is Black I am learning android. I wanted to implement navigation bar. For Dark theme navbar color is fine but for light theme the navigation bar is still black I wanted it to be white. As highlighted below. I am unable to change it.

Theme Code
    <style name="NoAction" parent="Theme.MaterialComponents.DayNight.NoActionBar.Bridge">
        <item name="colorPrimary">#71C51D</item>
        <item name="colorPrimaryVariant">#2D8A05</item>
        <item name="colorOnPrimary">@color/white</item>
        <!-- Secondary brand color. -->
        <item name="colorSecondary">@color/teal_200</item>
        <item name="colorSecondaryVariant">@color/teal_700</item>
        <item name="colorOnSecondary">@color/white</item>
        <!-- Status bar color. -->
        <item name="android:statusBarColor">?attr/colorPrimaryVariant</item>
        <item name="android:navigationBarColor">@color/black</item>
    </style>

Menu Code
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"

    xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:title="Inbox"
        android:id="@+id/Indbox_menu_main"
        app:showAsAction="always"
        android:icon="@android:drawable/ic_dialog_email"/>
    <item android:title="Sent Item"
        android:id="@+id/Sent_Item_android"
        android:icon="@android:drawable/ic_menu_send"/>
    <item android:title="Help"
        android:icon="@android:drawable/ic_menu_help"
        android:id="@+id/Help_menu"
        />
</menu>

A: You can use android:backgroud property to change the background color of the navbar.


text:
Q: How can I remove short description on the shop page in Woocommerce Shortly, I want to just remove the short description on the shop/archive page. I added two images. it will be helpful for your understanding. I tried many combination but not working on shop page.
I found a code but it was just removed on the product page.
remove_action( 'woocommerce_single_product_summary', 'woocommerce_template_single_excerpt', 20 );

function woocommerce_template_single_excerpt() {
        return;
}

A: Option 1: To remove description entirely place the following action in your child theme functions.php
remove_action('woocommerce_after_shop_loop_item_title','electro_template_loop_product_excerpt', 80 );

Option 2: To override the function place the following function in your child theme functions.php file
function electro_template_loop_product_excerpt() {
    global $post;
    // In case you want to limit description for example or output different content there
    if ( ! is_object( $post ) || ! $post->post_excerpt || $post->post_excerpt ) {
        return;
    }
}


text:
Q: Can't Activate Virtualenv on Powershell I'm trying to learn Django.
To start, I needed to install Python, Django, and Virtualenv. These are all installed with no errors. But now that I want to start a project and run virtualenv, I can't activate it in the powershell.
I used this command to make a virtualenv:
python -m virtualenv venv

Now the tutorial says that I have to activate virtualenv like this:
. \scripts\activate

but it gives me this error:
    . : The term '\scripts\activate' is not recognized as the name of a cmdlet, function, script file, or operable
program. Check the spelling of the name, or if a path was included, verify that the path is correct and try
again.
At line:1 char:3
+ . \scripts\activate
+   ~~~~~~~~~~~~~~~~~
    + CategoryInfo          : ObjectNotFound: (\scripts\activate:String) [], CommandNotFoundException
    + FullyQualifiedErrorId : CommandNotFoundException

What should I do?
I have tried scripts\activate.ps1 but it still is not working.

A: You should to use scripts\activate.ps1 instead of scripts\activate. Find more info here

A: It works perfectly with cmd, and not Powershell.


text:
Q: Convert python pandas dataframe rows or columns into numpy array I have a data frame like this. [from csv file]
       l1  p1 p2 p3 ... p10
    0   ↑  ←---- rows ----→
    1   |  ←---- rows ----→
    2   c  ←---- rows ----→
    3   o  ←---- rows ----→
    .   l  ←---- rows ----→
    .   |  ←---- rows ----→
    9   ↓  ←---- rows ----→

I want to convert l1 column into numpy array like this
[ ←, -, c, o, l, -, →] size : 10

and all the remaining columns into another numpy array like this\
[[ ← - r o w s - →],
 [ ← - r o w s - →],
 [ ← - r o w s - →]]    size: (10, 10)

Also

columns in the data frame are images so how can I further divide my data frame like this
           l1   p1 p2 .... p784
    0       ↑  ←---- rows ----→
    1       |  ←---- rows ----→
    2       c  ←---- rows ----→
    3       o  ←---- rows ----→
    .       l  ←---- rows ----→
    .       |  ←---- rows ----→
    27455   ↓  ←---- rows ----→

After getting the rows array on this data frame
I will have numpy array of size(27455, 784)
How to further split this array into size(27455, 28, 28)
how to do this !!
any other way will also be appreciated !!

A: Try
col=df.l1.to_numpy()

ary=df.drop('l1',axis=1).to_numpy()


text:
Q: Something went wrong when using spring boot with jboss When I used spring-boot with the wildfly, something went wrong.
The following is my application and conf.

*

*pom.xml:
<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.1.RELEASE</version>
</parent>

<dependencies>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
        <exclusions>
            <exclusion>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-starter-tomcat</artifactId>
            </exclusion>
        </exclusions>
    </dependency>

    <dependency>
        <groupId>javax.servlet</groupId>
        <artifactId>servlet-api</artifactId>
        <version>3.0-alpha-1</version>
    </dependency>
</dependencies>

*Main code: Application.java (return JSON data)
@RequestMapping("/")
public Map<String, String> hello() {
    Map<String, String> retMap = new HashMap<String, String>();
    retMap.put("success", "true");
    return retMap;
}

*Wildfly version:
WildFly 8.1.0.Final

*Exception:
2017-02-27 11:53:33,533 ERROR [org.springframework.boot.web.support.ErrorPageFilter] (default task-1) Forwarding to error page from request [/] due to exception [null]: java.lang.NullPointerException
    at java.util.ArrayList.<init>(ArrayList.java:164) [rt.jar:1.7.0_67]
    at io.undertow.servlet.spec.HttpServletResponseImpl.getHeaders(HttpServletResponseImpl.java:248) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]
    at javax.servlet.http.HttpServletResponseWrapper.getHeaders(HttpServletResponseWrapper.java:303) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
    at org.springframework.http.server.ServletServerHttpResponse$ServletResponseHttpHeaders.get(ServletServerHttpResponse.java:161) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.http.server.ServletServerHttpResponse$ServletResponseHttpHeaders.containsKey(ServletServerHttpResponse.java:143) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.addContentDispositionHeader(AbstractMessageConverterMethodProcessor.java:352) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.AbstractMessageConverterMethodProcessor.writeWithMessageConverters(AbstractMessageConverterMethodProcessor.java:230) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestResponseBodyMethodProcessor.handleReturnValue(RequestResponseBodyMethodProcessor.java:174) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.method.support.HandlerMethodReturnValueHandlerComposite.handleReturnValue(HandlerMethodReturnValueHandlerComposite.java:81) [spring-web-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.ServletInvocableHandlerMethod.invokeAndHandle(ServletInvocableHandlerMethod.java:132) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.invokeHandlerMethod(RequestMappingHandlerAdapter.java:827) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter.handleInternal(RequestMappingHandlerAdapter.java:738) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.mvc.method.AbstractHandlerMethodAdapter.handle(AbstractHandlerMethodAdapter.java:85) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:963) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:897) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:970) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:861) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:687) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
    at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:846) [spring-webmvc-4.3.6.RELEASE.jar:4.3.6.RELEASE]
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:790) [jboss-servlet-api_3.1_spec-1.0.0.Final.jar:1.0.0.Final]
    at io.undertow.servlet.handlers.ServletHandler.handleRequest(ServletHandler.java:85) [undertow-servlet-1.0.15.Final.jar:1.0.15.Final]

Can anybody help?


text:
Q: Flutter 3D Cube rotation Transform Matrix (Like Instagram stories) I have a PageView.builder and I am trying to add a custom transition effect just like Instagram's stories. Swift Package which has a gif showing the desired effect Using matrix4 is hard to debug and require lots of math I guess so right now I am getting Gaps and Overlaps between the Left and Right child of the PageView.

The code is taken partially from the tutorial at: custom pageview transitions
PageView.builder(
  controller: controller,
  itemBuilder: (context, position) {
    if (position == currentPageValue.floor()) {
        //page being swiped from
        return Transform(
            transform: _matrix3dSwipeL(position),   //First Matrix ???
            child: _child,
        );
    } else if (position == currentAnimationValue.floor() + 1){
        //page being swiped to
        return Transform(
            transform: _matrix3dSwipeR(position),   //Second Matrix ???
            child: _child,
        );
    } else {
        //off screen page
        return _child;
    }
  },
  itemCount: 10,
)

The Matrix I came up with right now is(does not work!):
Matrix4 _matrix3dSwipeL(int index) {
    double _animationvalue =
        ui.lerpDouble(0.0, math.pi / 2, _currentPageValue - index);
    return Matrix4.identity()
      ..setEntry(3, 2, 0.001)
      ..translate(((_screenSize.width / 2) * math.sin(_animationvalue)), 0.0,
          ((_screenSize.width / 2) * math.sin(_animationvalue)))
      ..rotateY(_animationvalue);
  }

  Matrix4 _matrix3dSwipeR(int index) {
    double _animationvalue =
        ui.lerpDouble(0.0, math.pi / 2, _currentPageValue + 1 - index);
    return Matrix4.identity()
      ..setEntry(3, 2, 0.001)
      ..translate(((-_screenSize.width / 2) * math.cos(_animationvalue)), 0.0,
          ((_screenSize.width / 2) * math.cos(_animationvalue)))
      ..rotateY(-(math.pi / 2) + _animationvalue);
  }

How would we construct the two Transformations for the current and the next page?

A: I've just released a package that has the animation you want. It's called cube_transition.
You can check it : https://pub.dev/packages/cube_transition
Using my package the code is very simple.

import 'package:cube_transition/cube_transition.dart';

const places = [ ...];

class Sample2 extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final height = MediaQuery.of(context).size.height / 2;
    return Scaffold(
      appBar: AppBar(
        title: Text('PageView Cube Transition'),
      ),
      body: Center(
        child: SizedBox(
          height: height,
          child: CubePageView(
            children: places
                .map(
                  (item) =>  Image.network(
                        item.url,
                        height: height,
                        fit: BoxFit.cover,
                      ),
                )
                .toList(),
          ),
        ),
      ),
    );
  }
}

Result


text:
Q: CasperJS' scrollToBottom is not working when populating the complete page from infinite scroll I don't have any idea why scrollToBottom() is not working. I want to keep scrolling to bottom of the page if the current data (from evaluate) is greater than previous data.
PhantomJS 2.0.0
CasperJS 1.1.0-beta3
var casper = require('casper').create({
    verbose: true,
    logLevel: 'info',
    pageSettings: {
        loadImages: false,
        loadPlugins: false,
        userAgent: 'Mozilla/5.0 (Windows NT 6.2; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/29.0.1547.2 Safari/537.36'
    }
});

casper.options.waitTimeout = 60000;
var utils = require('utils');
var hospitals = [];
var prevTotalHospitals = 0;
var currentTotalHospitals = 0;

casper.start('https://www.docdoc.com/').thenClick("#form-submit-btn").then(function() {
    this.wait(5000);
    this.scrollToBottom();
    processPage();
});

casper.on("remote.message", function(msg){
    this.echo("remote> " + msg);
});

casper.on('step.error', function(err) {
    this.die("Step has failed: " + err);
})

casper.on("page.error", function(msg, trace) {
    this.echo("Error: " + msg, "ERROR");
});

casper.on('complete.error', function(err) {
    this.die("Complete callback has failed: " + err);
});

casper.run(function(){
    utils.dump(hospitals);
});

function getCurrentTotalHospitals(){
    var resultsNodeList = document.querySelectorAll("div.results-list div.result");
    return resultsNodeList.length;
}

function getDetails(){
    var details = [];
    var resultsNodeList = document.querySelectorAll("div.results-list div.result");
    console.log("resultsNodeList.length " + resultsNodeList.length);
    for (var i = 0; i < resultsNodeList.length; i++) {
        var detail = {
            "name"          : resultsNodeList[i].querySelector("h2.link").textContent.replace(/\n/g, ''),
            "country"       : resultsNodeList[i].querySelector("h3.country").textContent.replace(/\n/g, ''),
            "specialities"  : resultsNodeList[i].querySelector("div.specialities").textContent.replace(/\n/g, ''),
            "language"      : resultsNodeList[i].querySelector("div.language").textContent.replace(/\n/g, '')
        };
        details.push(detail);
    };

    return JSON.stringify(details);
}

function stopScript() {
    utils.dump(hospitals);
    console.log("Exiting..." + hospitals.length);
    casper.exit();
};

function processPage() {
    currentTotalHospitals = casper.evaluate(getCurrentTotalHospitals);
    console.log(currentTotalHospitals + " <> " + prevTotalHospitals);
    if (currentTotalHospitals > prevTotalHospitals) {
        prevTotalHospitals = currentTotalHospitals;
        hospitals = hospitals.concat(casper.evaluate(getDetails));
        casper.scrollToBottom();
        casper.wait(5000);
        processPage();
    } else {
        stopScript();
    }
}

A: evaluate() is a synchronous function. Since it is used synchronously inside of processPage(), processPage() is also synchronous at the beginning. Later you're using wait() which is asynchronous. The processPage() that comes after wait() is executed immediately.
You can use it in this way:
if (...) {
    ...
    casper.scrollToBottom();
    casper.wait(5000, processPage);
} else {...}

By the way, the same is true for the first wait(). It should be:
this.wait(5000, function(){
    this.scrollToBottom();
    processPage();
});


text:
Q: Enabling and Disabling ListView Item Constantly In my android application, I have an activity that creates a ListView. The ListView contains several items. Every item is associated with a specific condition. If the condition is met, the item should be enabled and clickable. Otherwise, the item should be disabled and non-clickable. To check the conditions constantly, I have a separate thread that keeps checking the condition for every item and updates the item view accordingly. My code is running with no errors, but the behavior of the item does not achieve my need. Sometimes, the item remains non-clickable even though its condition is met. Sometimes, the items are clickable even thought the condition is NOT met. Sometimes, the items behave correctly. Therefore, I believe I am implementing it improperly, which causes such non-deterministic behavior.
Below is part of my Activity:
menu = new ArrayList<String>();

//menu
//Critical Features
menu.add("View Patient Records");
menu.add("Search in File");
menu.add("Search Medicine");
menu.add("Search by Date");
menu.add("Search by Illness");
menu.add("Report");

//Important Features
menu.add("Identify Nearest Emergency");
menu.add("Identify District Emergency");

menu.add("Planning Intervention");
menu.add("Real-time Assistance");

//Useful Features
listView = (ListView) findViewById(R.id.listView1);
listView.setClickable(true);

  ArrayAdapter<String> arrayAdapter =
             new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1, menu);
             listView.setAdapter(arrayAdapter);

             listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

                 public void onItemClick(AdapterView <? > arg0, View view, int position, long id) {
                     // When clicked, show a toast with the TextView text

Below is the part of the thread checking for conditions and updating the view:
            if(! condition)

              {
                mainActivity.getListView().post(new Runnable()
                     {
                         public void run()
                         {
                                View v = mainActivity.getListView().getChildAt(2);
                                v.setEnabled(false);
                                v.setOnClickListener(null);
                         }
                     });

                  }

            if( condition)
            {

        mainActivity.getListView().post(new Runnable()
                     {
                         public void run()
                         {
                                View v = mainActivity.getListView().getChildAt(2);
                                v.setEnabled(true);

                         }
                     });

        }

NOTE: The condition associated with the item depends on battery, network speed, network type.....etc. So the condition changes indeterminately, and the view can change constantly.

A: Try to use  scrolllistener.
listview.setOnScrollListener(new OnScrollListener(){
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
      // TODO Auto-generated method stub
    }
    public void onScrollStateChanged(AbsListView view, int scrollState) {
      // TODO Auto-generated method stub
if(! condition)

              {
                mainActivity.getListView().post(new Runnable()
                     {
                         public void run()
                         {
                                View v = mainActivity.getListView().getChildAt(2);
                                v.setEnabled(false);
                                v.setOnClickListener(null);
                         }
                     });

                  }

            if( condition)
            {

        mainActivity.getListView().post(new Runnable()
                     {
                         public void run()
                         {
                                View v = mainActivity.getListView().getChildAt(2);
                                v.setEnabled(true);

                         }
                     });

        }
}
}

A: This sounds like its to do with the view recycling in android list views.
If your conditions are being updated periodically then you will need to create a custom adapter and have an up to date reference to check against each time getView is called from within your adapter.


text:
Q: Getting error: *****.apk not found I have made one project as a library, while calling that library project to the main project.
I have made an action-bar class and made it a library, while calling it in main project.
I am getting error on Console as Could not find *Actionbar.apk!
While logcat shows as follows:
01-30 13:36:47.595: E/AndroidRuntime(404): FATAL EXCEPTION: main
01-30 13:36:47.595: E/AndroidRuntime(404): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.sos.emergency/com.sos.emergency.SOSHome}: java.lang.NullPointerException
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2663)
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2679)
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.app.ActivityThread.access$2300(ActivityThread.java:125)
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2033)
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.os.Handler.dispatchMessage(Handler.java:99)
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.os.Looper.loop(Looper.java:123)
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.app.ActivityThread.main(ActivityThread.java:4627)
01-30 13:36:47.595: E/AndroidRuntime(404):  at java.lang.reflect.Method.invokeNative(Native Method)
01-30 13:36:47.595: E/AndroidRuntime(404):  at java.lang.reflect.Method.invoke(Method.java:521)
01-30 13:36:47.595: E/AndroidRuntime(404):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
01-30 13:36:47.595: E/AndroidRuntime(404):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
01-30 13:36:47.595: E/AndroidRuntime(404):  at dalvik.system.NativeStart.main(Native Method)
01-30 13:36:47.595: E/AndroidRuntime(404): Caused by: java.lang.NullPointerException
01-30 13:36:47.595: E/AndroidRuntime(404):  at com.sos.emergency.SOSHome.onCreate(SOSHome.java:35)
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
01-30 13:36:47.595: E/AndroidRuntime(404):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2627)
01-30 13:36:47.595: E/AndroidRuntime(404):  ... 11 more

i am working according to the given link
http://thiranjith.wordpress.com/2011/07/15/actionbar-design-pattern-example-for-android/
along with other reference as,
http://developer.android.com/guide/developing/projects/projects-eclipse.html
and
http://developer.android.com/guide/topics/ui/actionbar.html
I have cleaned my project several times, also tried various solution found on net, but could not solve it.
My code snippet where i am getting error,
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.home_screen);

ActionBar = (***_Actionbar) findViewById(R.id.actionBar);
ActionBar.setTitle(R.string.app_name); //getting error here
ActionBar.setHomeLogo(R.drawable.ic_title_home_default);

A: Go to Project-->Properties
Select Android from left-hand side list
Uncheck the "Is Library" checkbox.


text:
Q: Reusing snapshots of Realm databases I have a Realm database being populated with data a number of times each second.  I am viewing the database as plotted MPChartLib data.  My goal is to snap a picture of the database at a particular point in time and reuse that information a bit later.
I am trying a couple of approaches and have reached a stalemate in both.  My first approach is to have a second Realm database that I would populate with the information in the first database on a button click.  My second approach is to export the database to a file and then reopen it later.
In my first approach I build two databases in the onCreateView as shown below.  I'm using mRealm as the dynamically changing Realm and mSRealm as the static one that only changes on button click.
  // Building a Realm instance un-persisted in memory (ie not on disk)
    RealmConfiguration config1 = new RealmConfiguration.Builder(getActivity())
            .name("myDynamic.realm")
            .inMemory()
            .build();
    // Building a Realm instance on disk)
    RealmConfiguration config2 = new RealmConfiguration.Builder(getActivity())
            .name("myStatic.realm")
            .build();
    Log.i(TAG, "delete previous");
    Realm.deleteRealm(config2);
    Realm.deleteRealm(config1); // Clean slate
    Log.i(TAG, "set default configuration");
    Realm.setDefaultConfiguration(config1); // Make this Realm the default
    Log.i(TAG, "define an instance for this");
    mRealm = buildDatabase(config1);
    mSRealm = buildDatabase(config2);

    Log.i(TAG, "build a Listener for database changes");
    realmListener = new RealmChangeListener() {
        @Override
        public void onChange() {
            //        Log.i(TAG, "database changed");
            if (startTime != 0) {
                //        Log.i(TAG, "off to plot");
                setData();
                mChart.invalidate();
            }
        }
    };

    Log.i(TAG, "add Listener  ");
    mRealm.addChangeListener(realmListener);

And the buildDatabase code for each configuration
  public Realm buildDatabase(RealmConfiguration config){

    try {
        Log.i(TAG, "return database since there was not already one ");
        return Realm.getInstance(config);
    } catch (RealmMigrationNeededException e){
        try {
            Log.i(TAG, "deleted database since there was one");
            Realm.deleteRealm(config);
            Log.i(TAG, "return new database since there was one deleted");
            return Realm.getInstance(config);
        } catch (Exception ex){
            Log.i(TAG, "should not ever get here");
            throw ex;
        }
    }
}

When the mRealm database has completed it's transaction I test to see if the recordData flag has been set to true via button push. if so, then I export the database as a file and /or try to update the static database snapshot to the current state of the dynamic one.
   //    Log.i(TAG, "copy element to the database ");
        mRealm.copyToRealm(entry);
        //        Log.i(TAG, " database  has size =  " + results.size());
        mRealm.commitTransaction();

        if (recordData) {
            Log.i(TAG, "record copy to file ");
            exportDatabase(mRealm);
            Log.i(TAG, "record copy to static Database ");
            copyToStaticDatabase(mRealm);
        //    Log.i(TAG, "record to singleton ");
        //    updateDataLab();
            recordData = !recordData;
        }

To export the data to a file I'm using:
    public void exportDatabase(Realm mRealm ) {
    Log.i(TAG, "into export the database to a file ");
    File exportRealmFile = null;
    try {
        // get or create an "export.realm" file
        Log.i(TAG, "get or create file ");
        exportRealmFile = new File(getActivity().getExternalCacheDir(), "export.realm");

        // if "export.realm" already exists, delete
        exportRealmFile.delete();

        // copy current realm to "export.realm"
        try {
            Log.i(TAG, "write copy to file ");
            mRealm.writeCopyTo(exportRealmFile);
        } catch (java.io.IOException e) {
            e.printStackTrace();
        }
    }catch (IOException e) {
            e.printStackTrace();
        }

To copy to the static base I'm using:
  public void copyToStaticDatabase(Realm mRealm ){

    Log.i(TAG, "get query of current state ");
    RealmResults<DataEntry> result2 = mRealm.where(DataEntry.class).findAllSorted("timestamp");
    Log.i(TAG, "delete old and create new static database ");
    Realm mSRealm = buildDatabase(config2);
    Log.i(TAG, "begin repopulating static database ");
    mSRealm.beginTransaction();

    for (int i = 0; i < result2.size(); i++) {
        DataEntry entry = mSRealm.createObject(DataEntry.class);
        entry.setX(result2.get(i).getX());
        entry.setY(result2.get(i).getY());
        entry.setZ(result2.get(i).getZ());
        entry.setTimestamp(result2.get(i).getTimestamp());
        entry.setAccuracy(result2.get(i).getAccuracy());
        entry.setsTimestamp(result2.get(i).getsTimestamp());

        mRealm.copyToRealm(entry);
    }
    Log.i(TAG, "finish static database ");
    mSRealm.commitTransaction();
}

This code dies at the point of creating a new instance of mSRealm since the "begin populating  etc" never gets displayed in the log.  Not sure what I'm doing wrong there.
 Log.i(TAG, "delete old and create new static database ");
    Realm mSRealm = buildDatabase(config2);
    Log.i(TAG, "begin repopulating static database ");

I would like to go to a new fragment and use the static Database.   In the onCreateView in the new fragment I try to create a configuration that points to the static Realm:
    // Building a Realm instance on disk
    RealmConfiguration config = new RealmConfiguration.Builder(getActivity())
            .name("myStatic.realm")
            .build();
    Log.i(TAG, "keep previous");
//    Realm.deleteRealm(config); // Clean slate
    Log.i(TAG, "set default configuration");
    Realm.setDefaultConfiguration(config); // Make this Realm the default
    Log.i(TAG, "define an instance for this");
    mRealm = Realm.getDefaultInstance();

I can't test this however since my code stops at my attempted copy.  For the file approach I've attempted to work through the MigrationExampleActivity that I've rewritten as fragment and included it in my project to test how migrating is performed through version updates.   This will become more important as it will be important to archive the snapshots for long term future reference.
I think this is the way to "reload" a database from a file from what I've read on other questions.  My code again crashes at the point below of getting a new Instance.
@Override
public View onCreateView(LayoutInflater inflater, final ViewGroup container,
                         Bundle savedInstanceState) {

    Log.i(TAG, " in onCreate  View ");
    View view = inflater.inflate(R.layout.activity_realm_basic_example, container, false);

    rootLayout = ((LinearLayout) view.findViewById(R.id.container));
    rootLayout.removeAllViews();
    Log.i(TAG, " get resources of previous database  ");

    copyBundledRealmFile(this.getResources().openRawResource(R.raw.default1), "default1");

    Log.i(TAG, " set up new configuration ");
    RealmConfiguration config1 = new RealmConfiguration.Builder(getActivity())
            .name("default1")
            .schemaVersion(3)
            .migration(new Migration())
            .build();
    Log.i(TAG, " get new instance ");
    realm = Realm.getInstance(config1); // Automatically run migration if needed
    Log.i(TAG, " got new instance ");
    showStatus("Default1");
    showStatus(realm);
    realm.close();

    return view;
}

I've tried to mimic the structure of realmjavamaster in my project but perhaps I have an issue with setting up the raw directory.  I'm not very clear on how to utilize "resident" realms and how to reference re-opening them , getting the correct path and such.
Could be my problem is in the referencing or perhaps I don't know enough details in getting new Instances.  Maybe I'm missing something fundamental.
Any assistance is greatly appreciated.

A: Ok, so I spent some time working through the basics of Realm Databases and now am all set with using multiple realms within one fragment,  saving and retrieving snapshot static realms of my actively varying realm.
My question was based on a somewhat fundamental lack of understanding of the definition of schema for the model classes and ways to migrate to new versions as changes are made to those model classes. Along with some basic misunderstandings of how and where realms are stored.
I have also discovered a huge benefit of using a realm database as a method to pass data between fragments.  I now have a database called "GlobalVariables"  which I can read and write to/from within any fragment in my project. No more fragment args for me!  or passing data between fragments by using "hosting activities".
I just open an instance of GlobalVariables anywhere I want data and done!
In addition, I can store variations of the GlobalVariables as records to allow for custom setups for a particular operation type on my app.
Thanks beender, cmelchior and Realm,  bravo...


text:
Q: How to calculate the Sum of all Values in a Ruby Array I have an array as follows:
a = [1,2,5,8]
I want to calculate the value of all the elements added(or multiplied) together.

A: a.inject{ |sum,x| sum + x }

Or slightly shorter and faster:
a.inject(:+)

For multiplication or whatever else, just change the sign: a.inject(:*)


text:
Q: dl list - can I make the "dt" above the "dl" but also have each dt/dl group inline So I have a dl list something like this:

.title {
  display: inline-block;
  padding-bottom: 20px;
}
dd {
  -moz-margin-start: 0;
  -webkit-margin-start: 0;
  -o-margin-start: 0;
  margin-start: 0;
}

Name:

Box

Member Price

$25

Retail Price

$30

I would like the dt to display above the dd, but also for each dt/dd 'group' to be inline with the next. Is it at all possible to do this without position absolute or another element wraping each dt/dd group (which would break the structure of the dl)
The image attached shows what I am trying to achieve:

A: Because of semantic requirements, I guess you won't change the markup - so I tried fiddling around and here are some hacks.
Hack 1:
Using flexbox,margins and some transforming :

dd,
dt {
  margin: 0;
  display: inline-block;
  vertical-align: middle;
}
dl {
  display: flex;
  flex-direction: column;
  align-items: center;
  width: 100%;
  margin: auto;
  border: 1px solid red;
}
.title {
  transform: translateX(-50%);
}
.title+.title {
  margin-top: -1.1em;
  transform: translateX(50%);
}
.member {
  align-self: flex-start;
}
.retail {
  align-self: flex-end;
  margin-top: -2.2em;
}
.retail+.retail {
  margin-top: initial;
}

Name:

Box

Member Price

$25

Retail Price

$30

Hack 2:
Another option using flexbox wrapping:

dd,
dt {
  margin: 0;
  display: inline-block;
  vertical-align: middle;
}
dl {
  display: flex;
  flex-wrap: wrap;
  align-items: center;
  width: 100%;
  margin: auto;
  border: 1px solid red;
}
.title {
  flex-basis: 50%;
  text-align:right;
}
.title+.title {
  text-align: left;
}
.member {
  text-align:left;
  flex-basis: 100%;
}
.retail {
  text-align:right;
  margin-top: -3.3em;
  flex-basis: 100%;
}
.retail+.retail {
  margin-top: -1.2em;
}

Name:

Box

Member Price

$25

Retail Price

$30

And here is something related that I did sometime back.
Good luck!

A: Here's a way to set it up.  It pulls up the first .retail element using the margin-top being equal to 2 line-heights (I assume your content is short).  And then it moves .member to the left and .retail to the right. (you can use percent widths instead of fixed, if that works better in your page.)

.details {text-align:center; line-height:1.5em;}
dt, dd {display:block; margin:0; padding:0;}
.title {display:inline-block;}
.member + .retail {margin-top:-3em;}
.member {margin-left:-200px;}
.retail {margin-left:200px;}

Name:

Box

Member Price

$25

Retail Price

$30

A: Another flex approach with order, wrap, width and margin:
(Added some colors so you see what selectors are targeting)

dl, dt, dd {
  margin:0;
  padding:0.25em 1em;
  box-sizing:border-box;
}
dl {
  display:flex;
  flex-wrap:wrap;
  width:400px;
  margin:auto;
  background:gray;
}
dt, dd {
  width:50%;
}
.title {
  padding:0.5em 0.1em 1.25em;
}
dl.details > :nth-child(odd) {
  order:0;
  /* see me */color:yellow;
}
dl.details > .member ~ :nth-child(even) {
  order:1;
  /* see me */ background:tomato;
}
dl.details > :nth-child(3n+1),
dl.details > :nth-child(3){
  text-align:right;
  /* see me */ box-shadow:inset 0 0 0 2px turquoise;
}
.retail +.retail,
.member + .member{
  width:35%;/* might need tuning up to 47% */
  margin:auto;
  /*see me */ color:white;
}

Name:

Box

Member Price

$25

Retail Price

$30


text:
Q: How can I create a Kubernetes Secret with Ansible? I'm using an Ansible JMeter Operator to do distributed load testing and am having trouble with creating a Kubernetes secret. The operator I'm modifying is the JMeter one and the additional YAML I'm adding is as below:
- name: InfluxDB Storage Secret
  k8s:
    apiVersion: v1
    kind: Secret
    type: Opaque
    metadata:
      name: azure-storage-account-infxluxdb-secret
      namespace: '{{ meta.namespace }}'
    stringData:
      azurestorageaccountname: 'xxxxxxx'
      azurestorageaccountkey: 'xxxxxxxxxxx'

Is there anything wrong with the YAML definition? I'm modifying the roles/jmeter/tasks/main.yaml of the role to add it into my specific namespace.

A: Here is my example, that works for me, hope it help.
  - name: CREATE MONGOSECRETS SECRET
    kubernetes.core.k8s:
      state: present
      definition:
        apiVersion: v1
        kind: Secret
        type: Opaque
        metadata:
          name: "{{ secret_name }}"
          namespace: "{{ project_name | lower }}"
        data:
          config_data.json: "{{ lookup('template', mongo_conn_templates_path + '/config_data.json' ) | tojson | b64encode }}"


text:
Q: UICollectionView underneath the navigation bar when shown as a page in a UIPageViewController I have an iOS 7 app that has a UIPageViewController. Each page it displays has a UICollectionView that takes up the entire page except for the navigation bar. iOS 7 normally adjusts collection view edge insets so it is positioned below the navigation bar and goes underneath it as you scroll it up.
But when my collection view is displayed in the UIPageViewController, it's edge insets are not being  adjusted because the nav bar is owned by the page view controller, not the page the collection view is on. I have tried to set the edge insets on the collection view, but then it pushes the bottom of the collection view off the screen.
Does anyone know how you are supposed to setup an collection view inside of a page view controller in iOS 7?

A: I had the same problem and out of frustration i ended up doing this:
In the UIPageViewController i added:
[self setEdgesForExtendedLayout:UIRectEdgeAll];

and in the Collection View viewDidLoad:
if ([self respondsToSelector:@selector(topLayoutGuide)]) {
    UIEdgeInsets currentInsets = self.collectionView.contentInset;
    self.collectionView.contentInset = (UIEdgeInsets){
        .top =64,
        .bottom = currentInsets.bottom,
        .left = currentInsets.left,
        .right = currentInsets.right
    };
}

In the storyboard i disabled the all the "Extended Edge" and the "Adjust Scroll View Insets" for both views.
Not exactly an elegant solution but it works.


text:
Q: Shift Reduce Conflict import java_cup.runtime.*;
import java.io.*;
import java.util.*;

/* Preliminaries to set up and use the scanner. */

parser code {:
        SMPLLexer lexer;

      public SMPLParser (SMPLLexer lex) {
            super(lex);
            lexer = lex;
        }

        public void report_error(String message, Object info) {
            System.err.println(message + info);
        }

        public void syntax_error(Symbol cur_token) {
            System.err.print("Line " + lexer.getLine() +
                     " near char " + lexer.getChar() + ": ");
            report_error("Syntax error while reading: ", cur_token);
            System.err.println ("Last token read is " +
                     lexer.getText());
        }

        public void unrecover_syntax_error(Symbol cur_token) {
            System.err.println("Line " + lexer.getLine() +
                        "near char " + lexer.getChar() + ": ");
                         syntax_error(cur_token);
                    }

        :};

/* Terminals (tokens returned by the scanner). */

// special symbols
terminal LBRACKET, RBRACKET, LCBRACKET, RCBRACKET, LPAREN, RPAREN, /* LBRACE, RBRACE, */ SEMI, ASSIGN, COLON, COMMA, EMPTYLIST; /*, DOT, AT; */

// opeartors: base
terminal PAIR, CAR, CDR, LIST, SIZE, SUBSTRING, PROC, CALL, LAZY, LET, BE, DEFINE, PRINT, PRINTLN, READ, READINT;

// operators: equality
terminal PAIREQ, EQV, EQUAL;

// commands: commands
terminal CLEAR, SETBGCOLOR, SETFGCOLOR, PATH, CPATH, PT, CANVAS, RECT, CIRCLE;

// commands: conditional
terminal IF, THEN, ELSE, REPEAT; /* , CASE, WHILE, FOR, TRUE, FALSE; */

// operators: arithmetic
terminal PLUS, MINUS, MUL, DIV, MOD, EXPT;

// operators: relational
terminal LT, GT, EQ, LTEQ, GTEQ, NOTEQ;

//operators: logical
terminal AND, OR, NOT;

// operators:  bitwise
terminal BITAND, BITOR, INVERT;

// terminals with values
terminal Integer INTEGER;
terminal String STRING;
terminal String VAR;
terminal String ID;

/* Non terminals */
// (You're on your own for the IR classes)
non terminal IRProgram program;
non terminal IRCmd statement;
non terminal IRExp expression;
non terminal IRExp arithExp;
non terminal IRExp relExp;
non terminal IRExp logExp;
non terminal IRExp bitExp;
non terminal IRExp term;
non terminal IRExp expt;
non terminal IRExp factor;

non terminal ArrayList statementList;
non terminal IRCmdSeq cmdList;

non terminal ArrayList varList;
non terminal ArrayList expList;
non terminal ArrayList assList;

// non terminal ArrayList sequence;
non terminal empty;

/* Precedence */

precedence left OR;
precedence left AND;
precedence left NOT;
precedence left EQ, GT, LT, LTEQ, GTEQ, NOTEQ;
precedence left BITAND, BITOR;
precedence left PLUS, MINUS;
precedence left MUL, DIV, MOD;
precedence right INVERT;

/* Grammar rules */

start with program;

program ::= statementList:lst SEMI {: RESULT = new IRProgram(lst); :} |
                        statementList:lst {: RESULT = new IRProgram(lst); :} |
                        STRING:str {: RESULT = new IRCmdSeq(lst); :}

;

cmdList ::= statementList:lst {: RESULT = new IRCmdSeq(lst); :};

statementList ::= statementList:lst statement:s {:lst.add(s); RESULT = lst; :} |
                  empty {: RESULT = new ArrayList(); :};

statement ::=

    PAIR statement:s1 statement:s2  {: RESULT = new IRPAIR(s1,s2); :} |

    PAIREQ LPAREN PAIR:p RPAREN {: new IRPAIR(p); :} |

    CAR varList:s1 {: RESULT = new IRCAR(s1); :} |

    CDR varList:s1 {: RESULT = new IRCDR(s1); :} |

    EQV expression:e1 expression:e2  {: RESULT = new IREQV(e1,e2); :} |

    EQUAL expression:e1 expression:e2  {: RESULT = new IREQUAL(e1,e2); :} |

    SUBSTRING STRING:v arithExp:e1 arithExp:e2  {: RESULT = new IRSUBSTR(v,e1,e2); :} |

    SIZE LIST:n {: RESULT = new IRSIZE(n); :} |

    PROC ID:n cmdList:e {: RESULT = new IRPROC(n,e); :} |

    CALL expression:e1 cmdList:body {: RESULT = new IRCALL(e1,body); :} |

    LAZY expression:e1 {: RESULT = new IRLAZY(e1); :} |

  DEFINE ID:pred expression:e1 {: RESULT = new IRDEFINE(pred,e1); :} |

    LIST LPAREN varList:s RPAREN {: RESULT = new IRLIST(s); :} |

    LIST LPAREN LBRACKET varList:s RBRACKET RPAREN {: RESULT = new IRLIST(s); :} |

    LBRACKET varList:s RBRACKET {: RESULT = new IRLIST(s); :} |

    LCBRACKET varList:s RCBRACKET {: RESULT = new IRLIST(s); :} |

    //LBRACKET sequence:s RBRACKET {: RESULT = new IRLIST(s); :} |

    ID:n ASSIGN expression:n {: RESULT = new IRASSIGN(n); :} |

    ID:n ASSIGN expList:n {: RESULT = new IRASSIGN(n); :} |

    LET ID:n BE expression:e {: RESULT = new IRLET(n,e); :} |

    /** Graphic Components **/
  CLEAR {: RESULT = new IRCmdClear(); :} |

    CANVAS LPAREN arithExp:e1 arithExp:e2 RPAREN {: RESULT = new IRCmdCanvas(e1,e2); :} |

    PT LPAREN arithExp:e1 arithExp:e2 RPAREN {: RESULT = new IRCmdPT(e1,e2); :} |

    PATH LPAREN arithExp:e1 arithExp:e2 RPAREN {: RESULT = new IRCmdPath(e1,e2); :} |

    CIRCLE LPAREN arithExp:e1 arithExp:e2 arithExp:e3 RPAREN {: RESULT = new IRCmdCircle(e1,e2,e3); :} |

    CPATH LPAREN arithExp:e1 arithExp:e2 RPAREN {: RESULT = new IRCmdCPath(e1,e2); :} |

    SETFGCOLOR LPAREN arithExp:e1 arithExp:e2 arithExp:e3 RPAREN {: RESULT = new IRCmdSetFG(e1,e2,e3); :} |

    SETBGCOLOR LPAREN arithExp:e1 arithExp:e2 arithExp:e3 RPAREN {: RESULT = new IRCmdSetBG(e1,e2,e3); :} |

    RECT LPAREN arithExp:e1 arithExp:e2 arithExp:e3 RPAREN {: RESULT = new IRCmdRect(e1,e2,e3); :} |

    //conditionals

    IF expression:pred THEN cmdList:cond ELSE cmdList:alt {: RESULT = new IRCmdIf(pred, cond, alt); :} |

    // TODO CASE LBRACE expList RBRACE

    PRINT cmdList:e1 {: RESULT = new IRPRINT(e1); :} |

    PRINTLN cmdList:e1 {: RESULT = new IRPRINTLN(e1); :} |

    READ STRING:n {: RESULT = new IRREAD(n); :} |

    READINT STRING:n {: new IRREADINT(n);:} |

    //iteration
    REPEAT arithExp:count cmdList:body {: RESULT = new IRCmdRepeat(count, body); :} |

    EMPTYLIST {: RESULT = new ArrayList(); :}

    ;

varList ::=
            varList:lst COMMA expression:i COLON PROC:p {: lst.add(new IRVarList(i,p)); RESULT = lst; :} |
            varList:lst COMMA expression:i {: lst.add(i); RESULT = lst; :} |
        empty {: RESULT = new ArrayList(); :};

// list of expressions
expList ::=
            expList:lst COMMA expression:v {: lst.add(v); RESULT = lst; :} |
            expList:lst expression:v {: lst.add(v); RESULT = lst; :} |
        empty {: RESULT = new ArrayList(); :};

/*
sequence ::=
            sequence:s expression:e COMMA {: RESULT = s.add(e); } |
            sequence:s expression:e {: RESULT = s.add(e); } |
            empty {: RESULT = new ArrayList(); :};
*/

/* I'm giving you the expression hierarchy already done. (Am I not nice?) */
expression ::=

        arithExp:ae {: RESULT = ae; :} |
        bitExp:be {: RESULT = be; :} |
        relExp:re {: RESULT = re; :} |
        logExp:le {: RESULT = le; :};

        //relational expressions
relExp ::=

        //relational ops
        arithExp:e1 EQ arithExp:e2 {: RESULT = new IRExpEq(e1, e2); :} |
      arithExp:e1 LT arithExp:e2 {: RESULT = new IRExpLt(e1, e2); :} |
      arithExp:e1 GT arithExp:e2 {: RESULT = new IRExpGt(e1, e2); :} |
      arithExp:e1 LTEQ arithExp:e2 {: RESULT = new IRExpLtEq(e1, e2); :} |
      arithExp:e1 GTEQ arithExp:e2 {: RESULT = new IRExpGtEq(e1, e2); :} |
      arithExp:e1 NOTEQ arithExp:e2 {: RESULT = new IRExpNotEq(e1, e2); :}
      ;

logExp  ::=

        //logical ops
      arithExp:e1 AND arithExp:e2 {: RESULT = new IRExpAnd(e1, e2); :} |
      arithExp:e1 OR arithExp:e2 {: RESULT = new IRExpOr(e1, e2); :} |
      arithExp:e1 NOT arithExp:e2 {: RESULT = new IRExpNot(e1, e2); :}
        ;

bitExp ::=

        //bitwise ops
      arithExp:e1 BITAND arithExp:e2 {: RESULT = new IRExpBitAnd(e1, e2); :} |
      arithExp:e1 BITOR arithExp:e2 {: RESULT = new IRExpBitOr(e1, e2); :} |
      arithExp:e1 INVERT arithExp:e2 {: RESULT = new IRExpIvert(e1, e2); :}
        ;

         //arithmetic expressions
arithExp ::=

        arithExp:e PLUS term:t {: RESULT = new IRExpAdd(e, t); :} |
        arithExp:e MINUS term:t {: RESULT = new IRExpSub(e, t); :} |
        term:t {: RESULT = t; :}

        ;

term ::=

     term:t MUL expt:x {: RESULT = new IRExpMul(t, x); :} |
     term:t MOD expt:x {: RESULT = new IRExpMod(t, x); :} |
     term:t DIV expt:x {: RESULT = new IRExpDiv(t, x); :} |
     expt:x {: RESULT = x; :}

    ;

expt ::=
    expt:x EXPT factor:f {: RESULT = new IRExpExpt(x, f); :} |
    factor:f {: RESULT = f; :}

    ;

factor ::=
    INTEGER:n {: RESULT = new IRExpConst(n.intValue()); :} |
    VAR:var {: RESULT = new IRExpVar(var); :} |
    STRING:n {: RESULT = new IRExpString(n); :} |
    LPAREN arithExp:e RPAREN {: RESULT = e; :}
    // LBRACE arithExp:e RBRACE {: RESULT = e :}
        ;

empty ::=;

Getting some shift/reduce conflict when trying to sort out this grammar for a simple language i'm trying to build :-(. Can anyone guide me in the right light plz?

A: "Some shift/reduce conflict"?  I get 38 S/R conflicts and then a too-many-warnings error.
Perhaps I should just analyze the first one.
> Warning : *** Shift/Reduce conflict
> found in state #106   between cmdList
> ::= statementList (*)    and
> statement ::= (*) LBRACKET varList
> RBRACKET    under symbol LBRACKET
> Resolved in favor of shifting.

So, it looks like a statement could possibly be followed by [something], so the parser doesn't know whether to keep parsing (shift) or reduce the (as it happens, fractional) statement that it already has.
This is a good example of how shift/reduce conflicts in LALR(1) parsers are not necessarily errors. Usually, you want to do the shift and so the default action is perfectly reasonable and the conflict is just an obvious and meaningless purely technical ambiguity.
It might be more useful if you were to ask a question more like "my grammar won't parse '...this...', why not?"


text:
Q: Clicking on the button crashes the TK window import time
from tkinter import *

import pyautogui

root = Tk()
root.geometry('400x200')

def button_command():
    text = int (entry1.get())

    time.sleep(3)

    pyautogui.keyDown("w")
    time.sleep(text)
    pyautogui.keyUp("w")

    return None

entry1 = Entry(root, width= 20)
entry1.pack()

Button(root,text="Button", command=button_command).pack()

root.mainloop()

A: Your button code is odd, I think it's best practice this way:
button = Button(root, text='Button', command=lambda: button_command())
button.pack()
That's how I use them and it's always worked seamlessly.


text:
Q: What event and code in visual basic when the header in datagridview is clicked then all cell in that column will highlighted? I have this datagridview that when the cells in quantity column are highlighted, the sum of that quantity is displayed by Total.Text. Now, my question is, what are the proper code and event that if I click the header "quantity", it will select all cell in that column, and it will sum and displays the total sum of that quantity in that column
This is my code then I highlighted some cells in column 4 (quantity) and it will sum and displays by Total.Text:
 Private Sub AllmatDataGridView_MouseUp(sender As Object, e As MouseEventArgs) Handles AllmatDataGridView.MouseUp

    Dim dblTotal As Double = 0

    Try
        For Each cell As DataGridViewCell In AllmatDataGridView.SelectedCells
            If cell.ColumnIndex = 4 Then
                dblTotal += Double.Parse(cell.Value.ToString)
            End If
        Next
    Catch ex As Exception
    End Try

    If dblTotal <> 0 Then
        Total.Text = "Selected Total: " & dblTotal.ToString("n")
    Else
        Total.Text = ""
    End If

End Sub

If I click the header "quantity", I want it to select all cell in that column, and it will sum and displays the total sum of that quantity in that column.

A: I'd just attach to the SelectionChanged event and then sum everything that could reasonably be parsed as a decimal
Private Sub DataGridView1X_SelectionChanged(sender As Object, e As EventArgs) Handles DataGridViewX.SelectionChanged
    SumLabel.Text = "" & DataGridViewX.SelectedCells.Cast(Of DataGridViewCell).Sum(AddressOf AsDecimal)
End Sub

Shared Function AsDecimal(arg As DataGridViewCell) As Decimal
    Decimal.TryParse(arg.Value, AsDecimal)
End Function

Your user can flexibly select anything ; a full column, a row, a rectangle, a single cell, random cells all over the place, and any that are numeric will be added to the total


text:
Q: How does qsort work? Can someone explain what this sort algorithm does? I can't follow the logic, and it uses recursion. It seems strange to take the middle term and swap it with the first (8th line from top). Also, in the first iteration, ++last = i, so the call to swap is wasted.
The code sets last = left, i = left + 1, and then calls swap() with ++last. This makes last equal i!
/* qsort: sort v[left]...v[right] into increasing order */
void qsort(int v[], int left, int right)
{
    int i, last;

    if (left >= right) /* do nothing if array contains */
        return; /* fewer than two elements */

    swap(v, left, (left + right)/2); /* move partition elem */
    last = left;                     /* to v[0] */

    for (i = left + 1; i <= right; i++) /* partition */
        if (v[i] < v[left])
            swap(v, ++last, i);
    swap(v, left, last); /* restore partition elem */
    qsort(v, left, last-1);
    qsort(v, last+1, right);
}

/* swap: interchange v[i] and v[j] */
void swap(int v[], int i, int j)
{
    int temp;
    temp = v[i];
    v[i] = v[j];
    v[j] = temp;
}

A: The comments in code are quite explaining. At the beginning, a 'partition' element is selected and moved to the beginning of the array so that the subsequent swaps don't touch it. Then all remaining elements are partially sorted so this 'partition' element can be inserted into its final place in the sorted array, and this is what the last swap does (just before calling recursion for the parts to the left and to the right to the partition element).
For the algorithm's details, read about Quick sort.


text:
Q: Ordinary Double Point Characterization I'm reading Qing Liu's Algebraic Geometry and Arithmetic Curves in an attempt to understand Artin-Winters' proof of Deligne-Mumford's semi-stable reduction theorem. I'm having a bit of trouble understanding the algebraic characterization of ordinary double points. In particular, letting $X$ be a reduced curve over an algebraically closed field $k$, and letting $\pi:X'\to X$ be the normalization morphism, we call a closed point $x\in X$ an ordinary double point if $\pi^{-1}(x)$ consists of 2 points, and we have$$\dim_k\left(\mathcal{O}'_{X,x}/\mathcal{O}_{X,x}\right) = [k(x):k] = 1$$where $\mathcal{O}'_{X,x}$ is the integral closure of $\mathcal{O}_{X,x}$ in $\operatorname{Frac}(\mathcal{O}_{X,x})$. I'm having trouble understanding what the dimension of the quotient $\mathcal{O}'_{X,x}/\mathcal{O}_{X,x}$ as a $k$-vector space means (geometrically, say) and, in particular, what it means for it to be 1. Any help is appreciated! Thank you!

A: The dimension of $\mathcal{O}_{X,x}'/\mathcal{O}_{X,x}$ is "how many" extra functions you need to be able to tell the germs of $X'$ through the two points $x_1,x_2$ on the normalization living above $x$ apart. As the normalization map is given by some undue gluing of subvarieties and tangent spaces, it measures how much stuff got glued together. In the case of an ordinary double point, the answer is that two points got glued together but none of their tangent directions - the function that gets added to form the integral closure is one which distinguishes the points $x_1$ and $x_2$.
It may also be helpful to hear a little bit about other better definition of a node (aka ordinary double point). Vakil and the Stacks Project define a node (at least in the algebraically closed case) to be a singular point on a curve which has $\mathcal{O}_{X,x}^\wedge\cong k[[x,y]]/(xy)$ as topological rings. In my opinion, this is much clearer to understand. It turns out that your definition in terms of the number of preimages and $\delta=\dim \mathcal{O}_{X,x}'/\mathcal{O}_{X,x}$ is equivalent to this - the main ingredient is Stacks 0C3W saying that it doesn't matter where we compute $\delta$ - the local ring, the strict henselization, or the completion will all give the same result.


text:
Q: Service principal name changes in kerberos Not sure what is happening since there are multiple moving parts here.
We have a cloudera cluster for hdfs, hadoop, impala, hbase.  We also have an F5 loadbalancer in front of all our impala servers.  We are trying to secure the servers/cluster with Kerberos.  My colleague has setup Kerberos using MIT KDC.  This setup works fine when we query impala directly to the server but not when we go thru an F5 load balancer.
We've run kinit to get a ticket for a pre-created keytab file.
kinit -k -t /blah/keytabs/first.last.keytab first.last

When I run klist, it shows all these tickets:
$ klist
Ticket cache: FILE:/tmp/krb5cc_14377
Default principal: first.last@MADEUPNAME

Valid starting     Expires            Service principal
08/23/17 11:32:02  08/24/17 11:32:02  krbtgt/MADEUPNAME@MADEUPNAME
    renew until 08/23/17 11:32:02
08/23/17 11:33:39  08/24/17 11:32:02  impala/hslave32101.company.com@MADEUPNAME
    renew until 08/23/17 11:32:02

When I run my impala-shell command, it works fine:
$ impala-shell -i hslave32101.company.com:21000 -k -q "select 1"
Starting Impala Shell using Kerberos authentication
Using service name 'impala'
Connected to hslave32101.company.com:21000
Server version: impalad version 2.7.0-cdh5.9.2 RELEASE (build 2f7871169d894fab16f8a2fb99f2e34f0df8763d)
Query: select 1
Query submitted at: 2017-08-23 13:08:34 (Coordinator: http://hslave32101.company.com:25000)
Query progress can be monitored at: http://hslave32101.company.com:25000/query_plan?query_id=4940ca8ca2f267c5:5eeb29af00000000
+---+
| 1 |
+---+
| 1 |
+---+
Fetched 1 row(s) in 0.01s

However, when I run my command thru the F5 loadbalancer, it doesn't work because the ticket it's looking for doesn't match what's in klist because it replaced part of it for some reason.
impala-shell -i bdaudit.company.com:21000 -d bigdata -k -q "select 1"
Starting Impala Shell using Kerberos authentication
Using service name 'impala'
Error connecting: TTransportException, Could not start SASL: Error in sasl_client_start (-1) SASL(-1): generic failure: GSSAPI Error: Unspecified GSS failure.  Minor code may provide more information (Server krbtgt/COMPANY.COM@MADEUPNAME not found in Kerberos database)
Not connected to Impala, could not execute queries.

The problem is this line here
(Server krbtgt/COMPANY.COM@MADEUPNAME not found in Kerberos database)
Somehow when going thru the F5 VIP, it changes first.last@MADEUPNAME to COMPANY.COM@MADEUPNAME.  Does anyone know why it replaced this part of the ticket?

A: Found the reason from Cloudera's instructions on how to setup Impala with an F5 here and here
Here's the snippet from the PDF:

In Cloudera Manager, navigate to the Impala service, select the Configuration pane, then search for "balancer" to
find the Impala Daemons Load Balancer parameter. The load balancer should be specified in host:port format,
where host is your virtual server's FQDN and port. These values are used by Cloudera Manager and are also passed
to Hue

If the Impala Daemons Load Balancer parameter is specified and Kerberos is enabled, Cloudera Manager adds a
principal for 'impala/<load_balancer_host>@<realm>' to the keytab for all Impala daemons. No additional
configuration is required for Kerberos.


text:
Q: Make ListItem Text Bold but not the List Icon itextsharp I am displaying a list using itextsharp in a pdf file .
Some of the Contents in a List item are being Bold as I asked it in my Question :
Bold some text in Pdf List
Now the problem is if I bold some text of Listitem , the List number is also getting Bold.
For Example :
1.Bold Text
it should be

*

*Bold Text
Here is the Snapshot :

How can I resolve this ?
Here is my Code :
 c1 = new Chunk("Earth Pit.", FontFactory.GetFont(FontFactory.TIMES_BOLD, 10,iTextSharp.text.Font.UNDERLINE));
        c2 = new Chunk(" The existing earth...", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10));
        p_chunk = new Paragraph();
        p_chunk.Add(c1);
        p_chunk.Add(c2);
        lst_terms.Add(new iTextSharp.text.ListItem(p_chunk));

A: This works for me:
Chunk c1 = new Chunk("Earth Pit.", FontFactory.GetFont(FontFactory.TIMES_BOLD, 10,iTextSharp.text.Font.UNDERLINE));
Chunk c2 = new Chunk(" The existing earth...", FontFactory.GetFont(FontFactory.TIMES_ROMAN, 10));
ListItem li = new ListItem("", FontFactory.GetFont(TIMES_ROMAN, 10));
p.Add(c1);
p.Add(c2);
lst_terms.Add(li);

Why are you creating a Paragraph object when you actually need a ListItem?


text:
Q: Add local CSS to Domain Online UIWebView Hi I wan't to add css styles to a UIWebView
CSS Code
<style>body{ background: none; } .sepLine{ display: none; } .wrapper{ width: 320px; }</style>

Code for UIWebView
NSString *fullURL = @"http://parentportal.npsinternational.edu.sg/nps/Dashboard.aspx";
NSURL *url = [NSURL URLWithString:fullURL];
NSURLRequest *requestObj = [NSURLRequest requestWithURL:url];
[webView loadRequest:requestObj];

How do I do this

A: Use the UIWebView delegate method - (void)webViewDidFinishLoad:(UIWebView *)webView to wait for the page to finish loading then inject the CSS using JavaScript with - (NSString *)stringByEvaluatingJavaScriptFromString:(NSString *)script

A: I believe you have to load HTML string, append styles and than load it to web view.
Try this code:
dispatch_async(dispatch_get_main_queue(), ^{
    NSString *fullURL = @"http://parentportal.npsinternational.edu.sg/nps/Dashboard.aspx";
    NSString *style = @"<style> ... </style>";

    NSURL *url = [NSURL URLWithString:fullURL];

    NSError* error = nil;

    //load HTML string
    NSString* html = [NSString stringWithContentsOfURL:url usedEncoding:NSUTF8StringEncoding error:&error];
    if(!error){
        //append style string
        html = [html stringByAppendingString:style];

        //load webview
        [webView loadHTMLString:html baseURL:url];
    }
});

It is only example, you'd better to load string with advanced network tool, e.g AFNetworking


text:
Q: repo gets stuck after downloading I'm using repo to download Android source code (ICS). However, repo gets stuck after downloading about 6.2G data. The last lines of repo's output is:
remote: Counting objects: 249, done
remote: Finding sources: 100% (129/129)
remote: Getting sizes: 100% (144/144)
remote: Compressing objects: 100% (24/24)
remote: Total 129 (delta 69), reused 127 (delta 68)
Receiving objects: 100% (129/129), 15.60 MiB | 2.17 MiB/s, done.
Resolving deltas: 100% (69/69), completed with 46 local objects.
From https://android.googlesource.com/platform/prebuilt
 * [new branch]      ics-factoryrom-2-release -> aosp/ics-factoryrom-2-release
 * [new branch]      ics-mr0    -> aosp/ics-mr0
 * [new branch]      ics-mr0-release -> aosp/ics-mr0-release
 * [new branch]      ics-mr1    -> aosp/ics-mr1
 * [new branch]      ics-mr1-release -> aosp/ics-mr1-release
   367f94c..3929228  master     -> aosp/master
 * [new tag]         android-2.2.3_r1 -> android-2.2.3_r1
 * [new tag]         android-2.2.3_r2 -> android-2.2.3_r2
 * [new tag]         android-4.0.1_r1 -> android-4.0.1_r1
 * [new tag]         android-4.0.1_r1.1 -> android-4.0.1_r1.1
 * [new tag]         android-4.0.1_r1.2 -> android-4.0.1_r1.2
 * [new tag]         android-4.0.2_r1 -> android-4.0.2_r1
 * [new tag]         android-4.0.3_r1 -> android-4.0.3_r1
 * [new tag]         android-cts-2.2_r8 -> android-cts-2.2_r8
 * [new tag]         android-cts-2.3_r10 -> android-cts-2.3_r10
 * [new tag]         android-cts-2.3_r11 -> android-cts-2.3_r11
 * [new tag]         android-cts-4.0_r1 -> android-cts-4.0_r1
 * [new tag]         android-cts-verifier-4.0_r1 -> android-cts-verifier-4.0_r1
 * [new tag]         android-sdk-4.0.3-tools_r1 -> android-sdk-4.0.3-tools_r1
 * [new tag]         android-sdk-4.0.3_r1 -> android-sdk-4.0.3_r1
 * [new tag]         android-sdk-adt_r16.0.1 -> android-sdk-adt_r16.0.1

Then no response for quite a while (>1 hour). Really don't know what has happened. du the folder shows its size doesn't change. No network traffic any more. Should I wait or kill repo and restart? The previous trial was also like this...Looking for an answer, thanks.

A: The solution is simple. Kill it and restart. This does no harm when doing repo sync. The size of the whole repository is more than 6G. I guess the stuck was due to some network problem.

A: I got stuck on the same line! I think that one is systemic:
android-sdk-adt_r16.0.1 -> android-sdk-adt_r16.0.1
After killing the process the following error appeared, even with sync -f :
Fetching projects:   0% (1/262)  fatal: Not a git repository: '/home/rodrigo/open-projects/droid/.repo/projects/bionic.git'
So I simply did a rm over '/home/rodrigo/open-projects/droid/.repo/projects/bionic.git', I know its an Orc solution but worked... code was downloaded.


text:
Q: Is any rational extension of degree 3 of the form $\mathbb{Q}(\sqrt[3]{d})$? If $K/\mathbb{Q}$ is an extension of degree $2$, then necessarily it is of the form $\mathbb{Q}(\sqrt{d})$. So, I am wondering if a similar philosophy holds for extension over $\mathbb{Q}$ of degree 3.

A: Your answer I think should be negative because if, for example, $\theta$ is the real root of $x^3+x+1=0$ then $K=\mathbb Q(\theta)$ is of degree $3$ but $\theta\approx -0.6823$ being such that $\theta^3+\theta+1=0$ is not of the form you asked.

A: $\mathbb{Q}(\sqrt[3]{d})$ is not a Galois extension if $d$ is not a power of $3$. In fact, it is not normal, there exists Galois extensions of degree $3$,therefore they cannot be isomorphic to $\mathbb({Q}\sqrt[3]{d})$.
Finding a Galois extension of $\Bbb Q$ of degree $3$


text:
Q: Wordpress Plugin Custom Post Type Archive Template results in other pages not displaying This is the code I am using to call my archive template, now the knowledgebase section works, the forums work, but all other pages throughout the website are now blank.
function kb_archive_template_function($arhive_template){
    if(is_post_type_archive('knowledgebase')){
      $theme_files = array('/templates/archive-knowledgebase.php');
      $exists_in_theme = locate_template($theme_files, false);
      if($exists_in_theme == ''){
        return plugin_dir_path(__FILE__) . '/templates/archive-knowledgebase.php';
      }
      return $archive_template;
    }

  }

A: You can use this code ,instead of your code
function get_custom_post_type_template( $archive_template ) {
     global $post;

     if ( is_post_type_archive ( 'knowledgebase' ) ) {
          $archive_template = plugin_dir_path(__FILE__) . '/templates/archive-knowledgebase.php';
     }
     return $archive_template;
}

add_filter( 'archive_template', 'get_custom_post_type_template' ) ;

Try that, then let me know the result. Thanks


text:
Q: $\sum_{k=0}^\infty\frac{1}{k+1}\binom{3k+1}{k}\left(\frac{1}{2}\right)^{3k+2}$ converges to $\frac{3-\sqrt{5}}{2}$? I stumble upon the expression
$$
\sum_{k=0}^\infty
\frac{1}{k+1}
\binom{3k+1}{k}
\left( \frac{1}{2} \right)^{3k+2}
$$
and it seems to converge to
$$
\frac{3-\sqrt{5}}{2}
$$
Do they equate ? How to prove that ?
Not sure if it's helpful :
$\frac{1}{k+1}\binom{3k+1}{k} , \; k\ge0$ is the OEIS sequence $A006013$.
I only have fundamental knowledge in combinatorics so I could only check it numerically that the convergence seems to be true . However I wouldn't mind learning new theories   .

A: Some thoughts:
We use the integral representation
$$\binom{3k + 1}{k} = \frac{1}{2\pi}\int_{-\pi}^\pi (1 + 2^{-1}\mathrm{e}^{\mathrm{i}t})^{3k + 1}(2^{-1}\mathrm{e}^{\mathrm{i}t})^{-k}\mathrm{d} t. \tag{1}$$
(Note: Similar to https://functions.wolfram.com/GammaBetaErf/Binomial/07/02/)
We have
\begin{align*}
 &\sum_{k=0}^\infty
 \frac{1}{k+1}
 \binom{3k+1}{k}
 \left( \frac{1}{2} \right)^{3k+2}\\[6pt]
 =\,& \frac{1}{2\pi}\int_{-\pi}^\pi \sum_{k=0}^\infty \frac{1}{k + 1}2^{-(3k + 2)}(1 + 2^{-1}\mathrm{e}^{\mathrm{i}t})^{3k + 1}(2^{-1}\mathrm{e}^{\mathrm{i}t})^{-k}\, \mathrm{d} t\\[6pt]
 =\,& \frac{1}{2\pi}\int_{-\pi}^\pi
 \frac{1 + z}{4}\sum_{k=0}^\infty \frac{1}{k + 1} \left(\frac{(1 + z)^3}{8z}\right)^k\Big\vert_{z = 2^{-1}\mathrm{e}^{\mathrm{i}t}}\, \mathrm{d} t \\[6pt]
 =\,& \frac{1}{2\pi}\int_{-\pi}^\pi
 \frac{-2z}{(1 + z)^2}
 \ln \left(1 - \frac{(1 + z)^3}{8z} \right)\Big\vert_{z = 2^{-1}\mathrm{e}^{\mathrm{i}t}}\,\mathrm{d} t \tag{2}\\[6pt]
 =\,& \frac{3 - \sqrt 5}{2} \tag{3}
\end{align*}
where we have used
$$\sum_{k=0}^\infty \frac{1}{k + 1} a^k = - \frac{\ln(1 - a)}{a}, \quad 0 < |a| < 1$$
and
$\frac{1}{32} \le \frac{(1 - 1/2)^3}{4} \le |\frac{(1 + 2^{-1}\mathrm{e}^{\mathrm{i}t})^3}{8\cdot 2^{-1}\mathrm{e}^{\mathrm{i}t}}| \le \frac{(1 + 1/2)^3}{4} = 27/32 < 1$ in (2).

Proof of the integral representation (1):
Using Cauchy integral formula, we have
$$\Big[(1 + z)^{3k + 1}\Big]^{(k)}(0) = \frac{k!}{2\pi \mathrm{i}}
\oint\limits_{|z| = 1/2} \frac{(1 + z)^{3k + 1}}{z^{k + 1}} \mathrm{d} z$$
which results in (with the substitution $z = 2^{-1}\mathrm{e}^{\mathrm{i} t}$)
$$\binom{3k + 1}{k} = \frac{1}{2\pi \mathrm{i}}
 \oint\limits_{|z| = 1/2} \frac{(1 + z)^{3k + 1}}{z^{k + 1}} \mathrm{d} z
 =
\frac{1}{2\pi \mathrm{i}}
\int_{-\pi}^\pi \frac{(1 + 2^{-1}\mathrm{e}^{\mathrm{i} t})^{3k + 1}}{(2^{-1}\mathrm{e}^{\mathrm{i} t})^{k + 1}} 2^{-1}\mathrm{e}^{\mathrm{i} t} \mathrm{i}\, \mathrm{d} t.$$
The desired result follows.

A: Let
$$S(z)=\sum_{k=0}^\infty {{3k+1}\choose{k}}z^{k}(1-z)^{2k+1}.$$
One has
\begin{align}S(z)&=\sum_{k=0}^\infty {{3k+1}\choose{k}}z^{k}\sum_{l=0}^{2k+1}(-1)^l{{2k+1}\choose{l}}z^l \\
&=\sum_{n=0}^\infty\sum_{k+l=n}(-1)^l{{3k+1}\choose{k}}{{2k+1}\choose{l}}z^n\\
&=\sum_{n=0}^\infty\sum_{k=0}^n(-1)^{n-k}{{3k+1}\choose{k}}{{2k+1}\choose{n-k}}z^n
\end{align}
On the other hand,
$${{3k+1}\choose{k}}{{2k+1}\choose{n-k}}=\frac{(3k+1)!}{k!(2k+1)!} \frac{(2k+1)!}{(n-k)!(3k+1-n)!}={n\choose k}{3k+1\choose n}.$$
Moreover, we have the following combinatorial identity:
$$\sum_{k=0}^n(-1)^{n-k}{n\choose k}{3k+1\choose n}=3^n.$$
One way to verify this identity is to write
$$f(x)=x(1+x^3)^n=\sum_{k=0}^n {n\choose k}x^{3k+1}.$$
and notice that the $n$th derivative of $x(1+x^3)^n$ at $x=-1$ is $-3^nn!$, while the $n$th derivative of $\sum_{k=0}^n {n\choose k}x^{3k+1}$ is $\sum_{k=0}^n n!{3k+1\choose n}{n\choose k}x^{3k+1-n}$.
Combining these, we deduce that
$$S(z)=\sum_{n=0}^\infty 3^nz^n=\frac{1}{1-3z}.$$
Next, let
$$G(u)=\sum_{k=0}^\infty \frac{1}{k+1}{3k+1\choose k}u^{k+1},$$
and $u=z(1-z)^2$. Then
$$\frac{dG}{dz}=\frac{dG}{du}\frac{du}{dz}.$$
Since $dG/du=\sum_{k=0}^\infty {3k+1 \choose k}(z(1-z)^2)^k=\frac{S(z)}{1-z}=\frac{1}{(1-z)(1-3z)}$ and $du/dz=1-4z+3z^2$, we have $\frac{dG}{dz}=1$, and so $G(z)=z$ (note that $G(0)=0$).
We have proved that
$$\sum_{k=0}^\infty \frac{1}{k+1}{3k+1 \choose k}(z(1-z)^2)^{k+1}=z.$$
Finally, let $z=(3-\sqrt{5})/2$, for which $z(1-z)^2=1/8$, to conclude that
$$\sum_{k=0}^\infty \frac{1}{k+1}{3k+1 \choose k}\frac{1}{2^{3k+3}}=\frac{3-\sqrt{5}}{4}.$$

A: The given sum is a specific case of the generating function of the Fuss–Catalan numbers: $$\sum_{k=0}^\infty\frac{n}{mk+n}\binom{mk+n}{k}z^n=F_m(z)^n,$$ where $w=F_m(z)$ is the solution of $w=1+zw^m$ analytic in a neighborhood of $z=0$.
Since $\frac1{k+1}\binom{3k+1}{k}=\frac2{3k+2}\binom{3k+2}{k}$, our sum is $\lambda^2$, where $\lambda=\frac12 F_3\left(\frac18\right)$ satisfies $2\lambda=1+\lambda^3$. The solutions of this equation are $\lambda=1$ and $\lambda=(-1\pm\sqrt5)/2$; the correct one $\color{blue}{\lambda=(\sqrt5-1)/2}$ can be found in a number of ways, e.g. by estimating $F_3(1/8)$ from above. A related fact here is that the radius of convergence of $F_m(z)$ equals $z_m=(m-1)^{m-1}/m^m$, with $F_m(z_m)=m/(m-1)$.
There are numerous proofs of the formula stated at the beginning. A fairly short one (which also generalizes to non-integral values of $m$ and $n$) uses the Lagrange–Bürmann formula which states that, given analytic functions $\phi$ and $\psi$ with $\phi(0)\neq0$, if we let $f(w)=w/\phi(w)$ then, using the "coefficient-of" notation, $$[z^k]\psi\big(f^{-1}(z)\big)=\frac1k[w^{k-1}]\big(\psi'(w)\phi(w)^k\big).$$ We apply it to $\phi(w)=(1+w)^m$ and $\psi(w)=(1+w)^n$.


text:
Q: How can I get the current ID number with INSERT INTO?
Possible Duplicate:
php/MySQL insert row then get 'id'

How can I do get current ID number with INSERT INTO?
mysql_query("INSERT INTO mytable(id,a,b) VALUES(null,3,current ID) ");

mysql_query("
    INSERT INTO tablo(id,a,b)
    VALUES(null,3,this ID number)
            ^            ^
            |            |
            | <Copy ID>  |
            |____________|
");

A: Use mysqli_insert_id(), which returns the auto-generated id used in the last query.
Read "PHP mysql_insert_id() Function" or "mysql_insert_id".
Example:
<?php
$query= "INSERT INTO table_name VALUES ('a','b','c')";
$result = mysql_query($query);
echo "INSERT statement ID is" . mysql_insert_id();
?>

And do read the big red box in the PHP documentation on the mysql_insert_id page, starting with mysqli.
See the PHP Documentation For further reference.

A: Basically you can use the mysqli_insert_id function.
As stated in the PHP manual:

The mysqli_insert_id() function returns the ID generated by a query on a table with a column having the AUTO_INCREMENT attribute. If the last query wasn't an INSERT or UPDATE statement or if the modified table does not have a column with the AUTO_INCREMENT attribute, this function will return zero.

A: You can try to get the next value of the sequence used in the selected table. Please check if MySQL has any function to get this value. If you need to have this number while executing a SQL statement, then using a PHP function is impossible.
Check "Get Auto Increment value with MySQL query".


text:
Q: Cookie strings come back altered after migrating from Laravel 5.7 to 6.x I'm migrating an application from Laravel 5.7 to the current LTS release, 6.18.
One side effect I've noticed is that I now get previously existing cookies back in an altered form. For example, under 5.7:
$deviceId = $request->cookie('deviceId') // sample value '1234'

But under 6.18, when retrieving a cookie set under 5.7:
$deviceId = $request->cookie('deviceId') // now same cookie returns 's:4:"1234"'

And behavior returns to normal for cookies set and retrieved under 6.18:
$deviceId = $request->cookie('deviceId') // once again '1234'

Obviously I can write a little helper to translate the unexpected new-style value to the original value, but I was just wondering if I did something wrong in my migration, or there's some other adjustment I was supposed to make to keep this from happening?


text:
Q: Drawing control to memory (Bitmap) Is it possible to draw a wpf control to memory (Bitmap) without drawing on the screen at all?
I found an example of how to save to Bitmap, but it only works when the window has been drawn in the screen.
BitmapImage bitmap = new BitmapImage();
    RenderTargetBitmap renderTarget =
    new RenderTargetBitmap((int)canvaspad.Width,
    (int)canvaspad.Height,
    96,
    96,
    System.Windows.Media.PixelFormats.Default);
renderTarget.Render(canvaspad);

A: As the control has no parent container, you need to call Measure and Arrange in order to do a proper layout. As layout is done asynchronously (see Remarks in Measure and Arrange), you may also need to call UpdateLayout to force the layout to be updated immediately.
public BitmapSource RenderToBitmap(UIElement element, Size size)
{
    element.Measure(size);
    element.Arrange(new Rect(size));
    element.UpdateLayout();

    var bitmap = new RenderTargetBitmap(
        (int)size.Width, (int)size.Height, 96, 96, PixelFormats.Default);

    bitmap.Render(element);
    return bitmap;
}

In case you have already set the Width and Height of the element you may use that for the size parameter:
var grid = new Grid
{
    Width = 200,
    Height = 200,
    Background = Brushes.Yellow
};

grid.Children.Add(
    new Ellipse
    {
        Width = 100,
        Height = 100,
        Fill = Brushes.Blue
    });

var bitmap = RenderElement(grid, new Size(grid.Width, grid.Height));


text:
Q: Kmeans on a million observations in R - trouble plotting clusters I am trying to perform KMeans clustering on over a million rows with 4 observations, all numeric. I am using the following code:
kmeansdf<-as.data.frame(rbind(train$V3,train$V5,train$V8,train$length))
km<-kmeans(kmeansdf,2)

As it can be seen, I would like to divide my data into two clusters. The object km is getting populated but I am having trouble plotting the results. Here is the code I am using to plot:
plot(kmeansdf,col=km$cluster)

This piece of code gives me the following error:
Error in plot.new() : figure margins too large

I tried researching online but could not find a solution, I tried working on command line as well but still getting the same error (I am using RStudio at the moment)
Any help to resolve the error would be highly appreciated.
TIA.

A: When I run your code on a df with 1e6 rows, I don't get the same error, but the system hangs (interrupted after 10 min). It may be that creating a scatterplot matrix with 1e6 points per frame is just too much.
You might consider taking a random sample:
# all this to create a df with two distinct clusters
set.seed(1)
center.1 <- c(2,2,2,2)
center.2 <- c(-2,-2,-2,-2)
n <- 5e5
f <- function(x){return(data.frame(V1=rnorm(n,mean=x[1]),
                                   V2=rnorm(n,mean=x[2]),
                                   V3=rnorm(n,mean=x[3]),
                                   V4=rnorm(n,mean=x[4])))}
df <- do.call("rbind",lapply(list(center.1,center.2),f))

km <- kmeans(df,2)         # run kmeans on full dataset
df$cluster <- km$cluster   # append cluster column to df

# sample is 10% of population (100,000 rows)
s  <- 1e5
df <- df[sample(nrow(df),s),]
plot(df[,1:4],col=df$cluster)

Running the same thing with a 1% sample (50,000 rows) gives this.