Q:

Overloading assignement operators in the "Shader" class

I need to overload assignement in one of my opengl based classes : problem is that this case is not so simple, because it uses Opengl "objects" : so copying class attributes is not enough. So what would be the correct way to overload the =, and copy constructor methods ? Here is my code :
Shader.h :
#pragma once

#include <GL/glew.h>
#include <map>
#include <string>
#include "alpha/LogManager.h"
#include "alpha/Component.h"
#include "alpha/Exceptions.h"
#include <glm/glm.hpp>
#include <glm/gtc/type_ptr.hpp>

#define NUM_SHADER_TYPES 3
#define NO_UNIFORM -1

class Shader : public Component
{
public:
    Shader();
    virtual ~Shader();

    void loadFromText(GLenum type, const std::string& src);
    void loadFromFile(GLenum type, const char* fileName);
    void loadFromPreCompiledText(GLenum type, const std::string& src){}
    void loadFromPreCompiledFile(GLenum type, const char* fileName){}
    void CreateAndLink();
    GLuint GetObject() const;
    ///accesses elements : shaders/uniforms;
    GLuint GetAttribLocation(const char* attrib);
    GLuint GetUniformLocation(const char* unif);
    void UpdateUniformMatrix4f(const char* unif, const glm::mat4& val, GLboolean inverse = false);
    void UpdateUniformMatrix3f(const char* unif, const glm::mat3& val, GLboolean inverse = false);
    void UpdateUniformMatrix2f(const char* unif, const glm::mat2& val, GLboolean inverse = false);
    void Bind() const override;
    void UnBind() const override;
    void Dispose() override;

    ///MEMBER FUNCTION GENERATORS
    #define __ALPHA_SHADER_PROGRAM_UNIFORM_DECLERATION(OGL_TYPE, TYPE_SUFFIX)\
        void UpdateUniform1##TYPE_SUFFIX(const GLchar* name, OGL_TYPE v0); \
        void UpdateUniform2##TYPE_SUFFIX(const GLchar* name, OGL_TYPE v0, OGL_TYPE v1); \
        void UpdateUniform3##TYPE_SUFFIX(const GLchar* name, OGL_TYPE v0, OGL_TYPE v1, OGL_TYPE v2); \
        void UpdateUniform4##TYPE_SUFFIX(const GLchar* name, OGL_TYPE v0, OGL_TYPE v1, OGL_TYPE v2, OGL_TYPE v3); \
        void UpdateUniform1##TYPE_SUFFIX##v(const GLchar* name, const OGL_TYPE* v, GLsizei count = 1);\
        void UpdateUniform2##TYPE_SUFFIX##v(const GLchar* name, const OGL_TYPE* v, GLsizei count = 1);\
        void UpdateUniform3##TYPE_SUFFIX##v(const GLchar* name, const OGL_TYPE* v, GLsizei count = 1);\
        void UpdateUniform4##TYPE_SUFFIX##v(const GLchar* name, const OGL_TYPE* v, GLsizei count = 1);

    ///Implement Methods
    __ALPHA_SHADER_PROGRAM_UNIFORM_DECLERATION(GLfloat, f);
    __ALPHA_SHADER_PROGRAM_UNIFORM_DECLERATION(GLdouble, d);
    __ALPHA_SHADER_PROGRAM_UNIFORM_DECLERATION(GLint, i);
    __ALPHA_SHADER_PROGRAM_UNIFORM_DECLERATION(GLuint, ui);

    ///undef macro
    #undef __ALPHA_SHADER_PROGRAM_UNIFORM_DECLERATION(OGL_TYPE, TYPE_SUFFIX)

    Shader& operator=(const Shader& other) = delete;
    Shader(const Shader& shader) = delete;

private:
    enum ShaderType{
        VERTEX_SHADER,
        FRAGMENT_SHADER,
        GEOMETRY_SHADER
    };
    int m_numShaders;
    GLuint m_object;
    bool _hasCreated;
    bool _hasDisposed;
    GLuint _shaders[NUM_SHADER_TYPES]; /// VERTEX, FRAGMENT, GEOMETRY
    std::map<std::string, GLuint> _attribList;
    std::map<std::string, GLuint> _unifLocationList;
    std::map<std::string, bool> _registeredUnifs;
};

Shader.cpp
#include "alpha/Shader.h"
#include "alpha/LogManager.h"
#include <fstream>
#include <assert.h>

#define GL_NULL 0

Shader::Shader()
    : m_numShaders(0), m_object(0), _hasCreated(false), _hasDisposed(false)
{
    _shaders[VERTEX_SHADER] = 0;
    _shaders[FRAGMENT_SHADER] = 0;
    _shaders[GEOMETRY_SHADER] = 0;
    _attribList.clear();
    _unifLocationList.clear();
}

Shader::~Shader(){
    Dispose();
}

void Shader::loadFromText(GLenum type, const std::string& text){
    try
    {
        switch (type)
        {
            case GL_VERTEX_SHADER:
                if(glIsShader(_shaders[VERTEX_SHADER]) == GL_TRUE)
                    throw TypeRegisteredTwiceException();
                break;
            case GL_FRAGMENT_SHADER:
                if(glIsShader(_shaders[FRAGMENT_SHADER]) == GL_TRUE)
                    throw TypeRegisteredTwiceException();
                break;
            case GL_GEOMETRY_SHADER:
                if(glIsShader(_shaders[GEOMETRY_SHADER]) == GL_TRUE  )
                    throw TypeRegisteredTwiceException();
                break;
            default:
                throw UnknownTypeException();
                break;
        }

        GLuint shader = glCreateShader(type);
        const char* cstr = text.c_str();
        glShaderSource(shader, 1, &cstr, nullptr);

        ///compile + check shader load status
        GLint status;
        glCompileShader(shader);
        glGetShaderiv(shader, GL_COMPILE_STATUS, &status);

        if(status == GL_FALSE){
            GLint infoLogSize;
            glGetShaderiv(shader, GL_INFO_LOG_LENGTH, &infoLogSize);
            GLchar *infoLog = new GLchar[infoLogSize];
            glGetShaderInfoLog(shader, infoLogSize, nullptr, infoLog);
            LOG_ERROR("Shader", infoLog);
            delete [] infoLog; /// no throw between new and delete !
        }

        if(m_numShaders >= 4)
        {
            throw OutOfBoundsExcpetion();
        }
        _shaders[m_numShaders++]=shader;
    }
    catch(std::exception & e){
        LOG_ERROR_INFO("AN ERROR OCCURED", "\n", e.what() );
        LOG_ERROR("Shader", "IGNORING ADDED SHADER !");
    }
}

void Shader::CreateAndLink(){
    try{
        if(glIsProgram(m_object) == GL_TRUE)
            throw CreatedTwiceException();

        m_object = glCreateProgram();

        ///OK CREATED PROGRAM !
        _hasCreated = true;

        if(_shaders[VERTEX_SHADER] != 0)
            glAttachShader(m_object, _shaders[VERTEX_SHADER]);
        else
            throw NotLoadedException();
        if(_shaders[FRAGMENT_SHADER] != 0)
            glAttachShader(m_object, _shaders[FRAGMENT_SHADER]);
        else
            throw NotLoadedException();
        if(_shaders[GEOMETRY_SHADER] != 0)
            glAttachShader(m_object, _shaders[GEOMETRY_SHADER]);/// OK, not compulsary...

        ///link + check
        GLint status;
        glLinkProgram(m_object);
        glGetProgramiv(m_object, GL_LINK_STATUS, &status);
        if(status == GL_FALSE){
            GLint infoLogSize;
            glGetProgramiv(m_object, GL_INFO_LOG_LENGTH, &infoLogSize);
            GLchar *infoLog = new GLchar[infoLogSize];
            glGetProgramInfoLog(m_object, infoLogSize, nullptr, infoLog);
            delete [] infoLog;
        }

        std::cout << "Shader created : ID = " << m_object << std::endl;

        glDetachShader(m_object, _shaders[VERTEX_SHADER]);
        glDetachShader(m_object, _shaders[FRAGMENT_SHADER]);
        glDetachShader(m_object, _shaders[GEOMETRY_SHADER]);

        glDeleteShader(_shaders[VERTEX_SHADER]);
        glDeleteShader(_shaders[FRAGMENT_SHADER]);
        glDeleteShader(_shaders[GEOMETRY_SHADER]);
    }
    catch(std::exception & e){
         LOG_ERROR_INFO("Shader", "AN ERROR OCCURED\n", e.what() );
         EXIT(1);
    }
}

void Shader::Bind() const{
    glUseProgram(m_object);
}
void Shader::UnBind() const{
    glUseProgram(GL_NULL);
}

GLuint Shader::GetAttribLocation(const char* attrib){
    auto it = _attribList.find(attrib);
    if(it == _attribList.end())
    {
        GLuint loc = glGetAttribLocation(m_object, attrib);
        if(loc == (unsigned)-1)
        {
            LOG_INFO("Shader Warning : Attrib", attrib, "is inactive !");
        }
        it = _attribList.insert({attrib, loc}).first;
    }
    return it->second;
}

GLuint Shader::GetUniformLocation(const char* unif){
    auto it = _unifLocationList.find(unif);
    if(it == _unifLocationList.end())
    {
        GLuint loc = glGetUniformLocation(m_object, unif);
        if(loc == (unsigned)-1)
        {
            LOG_INFO("Shader Warning : Uniform", unif, "is inactive !");
        }
        it = _unifLocationList.insert({unif, loc}).first;
    }
    return it->second;
}

GLuint Shader::GetObject() const{ return m_object; }

void Shader::UpdateUniformMatrix4f(const char* unif, const glm::mat4& val, GLboolean inverse){
    glUniformMatrix4fv(this->GetUniformLocation(unif), 1, inverse, glm::value_ptr(val));
}

void Shader::UpdateUniformMatrix3f(const char* unif, const glm::mat3& val, GLboolean inverse){
    glUniformMatrix3fv(this->GetUniformLocation(unif), 1, inverse, glm::value_ptr(val));
}

void Shader::UpdateUniformMatrix2f(const char* unif, const glm::mat2& val, GLboolean inverse){
    glUniformMatrix2fv(this->GetUniformLocation(unif), 1, inverse, glm::value_ptr(val));
}

#define __ALPHA_SHADER_PROGRAM_UNIFORM_IMPLEMENTATION(OGL_TYPE, TYPE_SUFFIX)\
    void Shader::UpdateUniform1##TYPE_SUFFIX(const GLchar* name, OGL_TYPE v0)\
    { glUniform1 ## TYPE_SUFFIX (this->GetUniformLocation(name), v0); }\
\
    void Shader::UpdateUniform2##TYPE_SUFFIX(const GLchar* name, OGL_TYPE v0, OGL_TYPE v1)\
    { glUniform2 ## TYPE_SUFFIX (this->GetUniformLocation(name), v0, v1); }\
\
    void Shader::UpdateUniform3##TYPE_SUFFIX(const GLchar* name, OGL_TYPE v0, OGL_TYPE v1, OGL_TYPE v2)\
    { glUniform3 ## TYPE_SUFFIX (this->GetUniformLocation(name), v0, v1, v2); }\
\
    void Shader::UpdateUniform4##TYPE_SUFFIX(const GLchar* name, OGL_TYPE v0, OGL_TYPE v1, OGL_TYPE v2, OGL_TYPE v3)\
    { glUniform4 ## TYPE_SUFFIX (this->GetUniformLocation(name), v0, v1, v2, v3); }\
\
    void Shader::UpdateUniform1##TYPE_SUFFIX##v(const GLchar* name, const OGL_TYPE* v, GLsizei count) /** sizei=1 by default */\
    { glUniform1 ## TYPE_SUFFIX ## v (this->GetUniformLocation(name), count, v); }\
\
    void Shader::UpdateUniform2##TYPE_SUFFIX##v(const GLchar* name, const OGL_TYPE* v, GLsizei count) /** sizei=1 by default */\
    { glUniform2 ## TYPE_SUFFIX ## v (this->GetUniformLocation(name), count, v); }\
\
    void Shader::UpdateUniform3##TYPE_SUFFIX##v(const GLchar* name, const OGL_TYPE* v, GLsizei count) /** sizei=1 by default */\
    { glUniform3 ## TYPE_SUFFIX ## v (this->GetUniformLocation(name), count, v); }\
\
    void Shader::UpdateUniform4##TYPE_SUFFIX##v(const GLchar* name, const OGL_TYPE* v, GLsizei count) /** sizei=1 by default */\
    { glUniform4 ## TYPE_SUFFIX ## v (this->GetUniformLocation(name), count, v); }\

__ALPHA_SHADER_PROGRAM_UNIFORM_IMPLEMENTATION(GLfloat, f);
__ALPHA_SHADER_PROGRAM_UNIFORM_IMPLEMENTATION(GLdouble, d);
__ALPHA_SHADER_PROGRAM_UNIFORM_IMPLEMENTATION(GLint, i);
__ALPHA_SHADER_PROGRAM_UNIFORM_IMPLEMENTATION(GLuint, ui);

///undef macro
#undef __ALPHA_SHADER_PROGRAM_UNIFORM_IMPLEMENTATION()

void Shader::loadFromFile(GLenum which, const char* fileName){
    std::ifstream fparser;
    fparser.open(fileName, std::ios_base::in);
    if(fparser){
        ///read + load
        std::string buffer(std::istreambuf_iterator<char>(fparser), (std::istreambuf_iterator<char>()));
        loadFromText(which, buffer);
    }
    else{
        LOG_ERROR_INFO("Shader", "Invalid fileName path", fileName);
    }
}

void Shader::Dispose(){
    if(!_hasDisposed)
    {
        glDeleteProgram(m_object);

        std::cout << "Disposed Shader object : ID was " <<  m_object << std::endl;

        m_object = -1;
        _hasDisposed = true;///no more calls of Dispose() !
    }
}

Edit : I ended up adding a move constructor as you suggested :
Shader::Shader(Shader&& other){
    this->m_object = other.m_object;
    other.m_object = 0;
    this->m_numShaders = other.m_numShaders;
    this->_hasCreated = other._hasCreated;
    this->_hasDisposed = other._hasDisposed;
    for(unsigned i = 0; i < NUM_SHADER_TYPES; ++i)
    {
        this->_shaders[i] = other._shaders[i];
        other._shaders[i] = 0;
    }
    this->_attribList = std::move(other._attribList);
    this->_unifLocationList = std::move(other._unifLocationList);
    this->_unifLocationList = std::move(other._unifLocationList);
}

Thanks for helping :)

A:

I suppose this is an interesting exercise, since copying a shader program is not as simple as copying the GLuint handle. Off the top of my head, I can think of two options:

Shallow copy: implement the handle as a reference counted shared resource (similar to how shared_ptr works). This is the cheaper option, however, I am guessing that this is not what you want, because doing this would mean that a change in one Shader object will affect all the others.
Deep Copy: Delay the glDetachShader() and glDeleteShader() operations until the destructor (or the Dispose() method), and then recompile the shader program in the copy assignment operator. You can do something like this (without error-checking):
Shader(const Shader &other)
{
    DetachAllShaders();
    GLuint shaders[NUM_SHADER_TYPES];
    GLsizei shaderCount;
    glGetAttachedShaders(other.GetObject(), NUM_SHADER_TYPES, &shaderCount, shaders);

    for(auto shader : shaders)
    {
        glAttachShader(m_program, shader);
    }

    if(other.isLinked())
    {
        glLinkProgram(m_program);
    }
}

If I were you, I wouldn't go for it though. I cannot think of a reason why you would need multiple copies of the same shader program. If you are returning it from a function, for example, I would suggest simply implementing a move constructor. Something simple like:
Shader(Shader &&other)
{
    m_object = other.m_object;
    other.m_object = 0;

    _attribList = std::move(other._attribList);
    // ...etc
}

In which case deleting m_object is silently ignored by OpenGL when it is 0.


Q:

Synergy specific entry page

We are linked from the Synergy support pages ( http://synergy-foss.org/support ) as the first port of call for support requests about Synergy.  They currently link to https://superuser.com/questions/tagged/synergy
Quite often people who visit us through that link don't realise that this is a generic site for all super-user style subjects, and not something specific to Synergy.  (See https://superuser.com/questions/264977/cant-get-round-robin-effect-to-work-like-i-use-to-have )
I think it would be very nice if we could have a Synergy specific entry page that tells the user that they are entering the Super User community and that it's not affiliated with Synergy and that they should specify that the question they are asking should mention the fact that they are using Synergy.
Either that or we should request that the Synergy people make it clearer on their site that we are not anything to do with them etc.  At the moment they just say "read the super user faq" and that's it.

A:

As Jeff mentioned, I contacted the Synergy team about this.

Synergy Team,
My name is Rebecca Chernoff and I'm a Community Manager with Stack Exchange, the company behind Super User.  It has come to our attention that there is some confusion with Synergy users on the Super User website.
Based on the Syngery support page, users are asking questions on Super User, unaware that the site is not specifically geared towards Synergy.  One example of this is at https://superuser.com/questions/264977/cant-get-round-robin-effect-to-work-like-i-use-to-have.
The support page lists us as the primary means of support for your users, but does not make it clear that Super User is not a dedicated, official means of support.  Using a Stack Exchange site as an official supprt forum for a product or project is backwards in our eyes.  It doesn't allow the community to organically evolve on our site.  We would much prefer to be equally listed with several other options.
In addition to clarifying the role of Super User, might I kindly suggest removing the bits about "first option", "last option" and simply listing us amongst your mailing list, irc channel, and support ticket system options?  I believe this will result in a better experience for users on both sites.
Thanks,
Rebecca Chernoff
  Community Manager
  Stack Exchange

A:

See my answer at
Is it okay to use Stack Overflow as the support forum for a product or project?

One way is as you saw with Subsonic -- where they simply provide a single link to Stack Overflow among other links of places people can go to discuss Subsonic. I think that's an OK nudge and if you want to seed it with questions yourself, that's fine too.

So I think the community team will be pinging the Synergy folks to ensure they have multiple links of places people can go for support.


Q:

Normalize comma separated foreign key

I have "element" and "authors" tables, where element table can have one or many authors, but tables are not normalized(some folk designed this long ago). eg:
element_id   ...     ...  authors
369561                    319,30,2496,544

DB is large enough, so i need some SQL script which will create and populate join table, for example:
"element_authors"
element_id | author_id
369561       319
369561       30
369561       2496
369561       544

I don't have idea how to write this script, any help?

A:

The general idea is to split the comma separated field into a set using regexp_split_to_table, cast each value to integer, and pair the results up with the element_id from the tuple we got the original comma separated field from.
For PostgreSQL 9.3, you'd write:
INSERT INTO element_authors(element_id, author_id)
SELECT
  element_id,
  CAST (author_id AS integer) AS author_id
FROM
  element,
  LATERAL regexp_split_to_table(nullif(authors, ''), ',') author_id;

or on older PostgreSQL versions I think in this case it's safe to write:
INSERT INTO element_authors(element_id, author_id)
SELECT
  element_id,
  CAST( regexp_split_to_table(nullif(authors, ''), ',') AS integer) AS author_id
FROM
  element;


Q:

How to override magento function?

I have added prefix and telephone field on customer registration page and want to use that value in checkout billing address
So , I have to override magento \app\code\core\Mage\Checkout\Block\Onepage\Billing.php for customer selected prefix and telephone.
I want your help to override this particular functions in local
public function getPrefix() { ... }
Please help me ...

A:

create the folder mage into your app\code\local folder as
\app\code\local\Mage\Checkout\Block\Onepage\Billing.php
and just put the function getPrefix() inside the Billing.php with your modification that will works here


Q:

How to ignore unused XML elements while deserializing a document?

I'm using SimpleXml to (de)serialize POJOs. Now, I have a big XML which has some elements which are not needed. For instance, with this XML:
<Root>
   <Element>Used</Element>
   <Another>Not used</Another>
<Root>

I want to create a POJO which looks like:
@Root
class Root{
    @Element
    private String element;
}

Problem is that I'm getting this Exception:
simpleframework.xml.core.ElementException: Element 'Another' does not have a
match in class blah.blah.Blah at line 1

So... how should I configure the POJO so that I can parse the XML correctly?

A:

Set strict to false within the Root annotation to ignore any XML elements or attributes that do not appear in the class.
@Root(strict=false)

Alternatively, set  strict to false when you read the xml in the serialiser:
Root root = serializer.read(Root.class, source, false);

A:

you can add (required=false) to a single element
@Element(required=false)
private int statusCode;

if you have more elements use
 @Root(strict=false)


Q:

Toy Compiler Symbol Table

I'm creating a compiler (for the Cool language) as a personal project and I'm having trouble designing a symbol table. For context, I'm using a hierarchy of classes as my AST. Here's a small snippet of the AST:
class NodeAST {
public:
  virtual void accept(Visitor&) = 0;
};

class ProgramAST : public NodeAST {
private:
  const std::vector<ClassPtr> vClasses;

public:
  ProgramAST(std::vector<ClassPtr> vClasses);

  auto class_cbegin() const {
    return std::cbegin(vClasses);
  }
  auto class_cend() const {
    return std::cend(vClasses);
  }

  virtual void accept(Visitor& v) override;
};

class ClassAST : public NodeAST {
private:
  const std::string name;
  const std::vector<FeaturePtr> vFeatures;

public:
  ClassAST(std::string name, std::vector<FeaturePtr> vFeatures);

  auto getName() const {
    return name;
  }

  auto feature_cbegin() const {
    return std::cbegin(vFeatures);
  }
  auto feature_cend() const {
    return std::cend(vFeatures);
  }

  virtual void accept(Visitor& v) override;
};

Currently, at the core of my symbol table is a map defined as follows:
std::unordered_map<std::string, NodeAST*> table

It maps the name of a declaration to its corresponding node in the AST. That way, for example, I can fill in the types for the loose identifers using the type that I have set in the AST node.
The problem, however, is that when I query the symbol table for a node, I get back a NodeAST*. Thus, I have to downcast it to ClassAST*, MethodAST* or VarDecAST* etc. to actually use it.
How do I design my symbol table in a way that avoids the need for downcasting?

A:

I don't know the programming language you are implementing, but I don't think it is really likely that you can avoid dynamic casts completely. For example in f(1), f could either be a function or an variable if your language has lambdas. You need to find that out, by looking it up in the symbol table.
If you can absoluteley exclude this possibility, you could in theory create separate symbol tables for each type. But keep in mind that would obviously make it harder to find name conflicts if you need to detect them and may mean that your programming language is harder to extend later. I wouldn't recommend this solution.
Personally I would just add methods like to_class(), to_var(), is_class(), is_var() etc. to your NodeAST class, so that the dynamic cast is encapsulated and not spread around the whole codebase. You could also create a class for your symbol table, so that you can access elements with get_class(), get_var() etc.
If you are concerned about runtime costs of RTTI in C++, you could look at solutions other compilers are using. For LLVM it is described here: http://llvm.org/docs/HowToSetUpLLVMStyleRTTI.html


Q:

TypeError: google.maps.MarkerLabel is not a constructor

I want to customize the color of the label of my marker with Google Maps V3, and searching on the documentation I've found that there's a class named google.maps.MarkerLabel.
Searching on the web I've found some explaes of usage and here's what I've tried to do:
        var marker = new google.maps.Marker ({
            position: new google.maps.LatLng(data.lat, data.lon),
            map: map,
            id: data.id,
            type: data.type,
            type_description: data.type_description,
            name: data.name,
            via: data.via,
            civico: data.civico,
            comune: data.comune,
            cap: data.cap,
            giorno: data.giorno,
            orario: data.orario,
            description: data.description,
            note: data.note,
            label: new google.maps.MarkerLabel({
                text: data.id,
                color: "white"
            }),
            icon: '<cms:link>../resources/images/' + data.markerIcon + '</cms:link>'
        });

The message tells me MarkerLabel is not a costructor. Ok, but where should I call it to make by object id (which is of course a number) coloured white?
Thanks!

A:

a google.maps.MarkerLabel doesn't have a constructor, it is an anonymous object.
Use it like this:
var marker = new google.maps.Marker ({
        position: map.getCenter(),
        map: map,
        label: {
            text: "A", // data.id,
            color: "white"
        }
    });

proof of concept fiddle
code snippet:

function initialize() {
  var map = new google.maps.Map(
    document.getElementById("map_canvas"), {
      center: new google.maps.LatLng(37.4419, -122.1419),
      zoom: 13,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    });
  var marker = new google.maps.Marker({
    position: map.getCenter(), // new google.maps.LatLng(data.lat, data.lon),
    map: map,
    label: {
      text: "A",
      color: "white"
    }
  });
}
google.maps.event.addDomListener(window, "load", initialize);
html,
body,
#map_canvas {
  height: 100%;
  width: 100%;
  margin: 0px;
  padding: 0px
}


Q:

WL.Server.getActiveUser returns Null

I need the ability to get a users login userid/password in a java adapter. After reading lots of articles, the best way seems to be to call
WL.Server.getActiveUser from a javascript function that gets called from the java adapter. So, I added a getIdentity function to the http adapter that authenticates our app. I have verified that getActiveUser works in the authentication function that the login pages calls...
When I call the getIdentity function, getActiveUser returns null using The same authentication realm. I have set the realm in the application_descriptor file. Not sure what else I have to do. Any ideas?
function performAuthentication(username, password) {
       WL.Logger.info("In performAuthentication: username = " + username + " password = " + password + "Time = " + new Date(new Date().getTime()).toLocaleString());

        var invocationData = {
            adapter : 'BluePages',
            procedure : 'authenticate',
            parameters  : [username, password]
        };
        var invocationResult = WL.Server.invokeProcedure(invocationData);

        var fullName = invocationResult.result.fullName;
       if (invocationResult.result.success == false) {
            return {
                authRequired: true,
                loginPassed: false
            };
        }
        else {
            userIdentity = {
                userId: username,
                credentials: password,
                displayName: username,
                attributes: {
                    foo: "bar"
                }
        };

        WL.Server.setActiveUser("AuthRealm", null);
        WL.Server.setActiveUser("AuthRealm", userIdentity);
        var activeUser = WL.Server.getActiveUser("AuthRealm");
        WL.Logger.info("activeUser = " + activeUser);

        if(activeUser && activeUser.userId == username){
            WL.Logger.info("Active userId = " + activeUser.userId + " password = "    + activeUser.credentials);
            WL.Logger.info("User has been logged in!");
            return {
                loginPassed: true,
                authRequired: false,
                fullName: fullName,
                result: invocationResult.result
            };
        }
        else {
            WL.Logger.info("Else Clause...");
            if(activeUser != null)
                WL.Server.setActiveUser("AuthRealm", null);
            WL.Server.setActiveUser("AuthRealm", userIdentity);
        }

         return {
            authRequired: false,
            loginPassed: true,
            fullName: fullName
        };
    }

 }

function getIdentity() {
        WL.Logger.info("AuthAdapter: In getIdentity: Time = " + new Date(new Date().getTime()).toLocaleString());

        WL.Logger.info("AuthAdapter: userIdentity = " + userIdentity);

        var activeUser = WL.Server.getActiveUser("AuthRealm");

        WL.Logger.info("AuthAdapter: getIdentity: getActiveUser returned = " + activeUser);

        if (activeUser) {

                WL.Logger.info("AuthAdapter: getIdentity userId = " + activeUser.userId);

                return {
                    userId: activeUser.userId,
                    credentials: activeUser.credentials,
        };
     }
 }

A:

There could be 2 reasons to get null when using WL.Server.getActiveUser:
1)If no realm is defined on the adapter, the method returns null (active user is unknown)
2)If a realm is defined on the adapter:
If there is no strong identity associated with the user (the user was authenticated in this session or in a previous session), the method returns null.
In your case you said the realm is exist so I suggest to try #2
You can find more information here:
https://www.ibm.com/support/knowledgecenter/SSZH4A_6.0.0/com.ibm.worklight.help.doc/apiref/r_method_wl_server_getactiveuser.html


Q:

Magnific Popup and Bootstrap 3 Modal Call Stack Exceeded

I'm having an interesting issue when combining Boostrap 3 Modal with Magnific Popup. I have a Bootstrap Modal that contains a list of videos, and each video has a view link that opens up a Magnific Popup iframe popup.
Everything worked fine until I played with Magnific Popup's z-index in order to get it to appear on top of the Bootstrap Modal. Problem is, if you try and close the Magnific Popup (or interact with it at all) a stackoverflow error occurs (Maximum call stack exceeded).
Note: Everything works fine if I leave the z-index of the Magnific Popup alone.
Simplified Example: http://codepen.io/craigh/pen/GoWWOK/
Note: codepen suppresses SO errors, so the issue is not as obvious. But on my site, the SO occurs locking the browser up.
I think it has something to do with how clicking outside of a Bootstrap Modal closes the modal, but I changed the modal backdrop to static (forces user to click the x or close button) but no change. Any ideas?

A:

Someone posted the answer to this question in a github issue about this same problem. Commenting out a line of code seems messing it does do the trick and I haven't found any side effects as of now.
Taken from github user RandomArray's response

Line 375 seems to be the problem. I commented it out and the Maximum
  call stack size exceeded error went away.
_document.on('focusin' + EVENT_NS, mfp._onFocusIn);


Q:

Query that returns a list of people born in Paris from DBpedia

I cant figure out how to syntax a query that gets all the people who born in Paris
The results I want to get are:
dbpedia:Sergi_Pàmies
dbpedia:Princess_Eugénie_of_Greece_and_Denmark
dbpedia:Laurent_Fabius
dbpedia:Auguste_Rodin
dbpedia:Manu_Chao
dbpedia:Louis_Antoine_de_Bougainville
dbpedia:Maria_Francisca_of_Savoy
dbpedia:Alexandre_Coste
dbpedia:Jean_le_Rond_d'Alembert
        etc......

The resource page is: http://dbpedia.org/page/Paris

A:

I found the answer for my problem. The query bellow get everyone who born in Paris.
PREFIX dbponto: <http://dbpedia.org/ontology/>
PREFIX dbpedia: <http://dbpedia.org/resource/>
SELECT ?person
WHERE { ?person dbpedia-owl:birthPlace dbpedia:Paris }

Sorry if my question above is not well structured but I am a beginner in programming.


Q:

Implicit parameter in Scalaz

I try to find out why the call ∅ in scalaz.ListW.<^> works
def <^>[B: Zero](f: NonEmptyList[A] => B): B = value match {
  case Nil => ∅
  case h :: t => f(Scalaz.nel(h, t))
}

My minimal theory is:
trait X[T]{
   def y : T
}

object X{
  implicit object IntX extends X[Int]{
    def y = 42
  }
  implicit object StringX extends X[String]{
    def y = "y"
  }
}
trait Xs{
  def ys[T](implicit x : X[T]) = x.y
}

class A extends Xs{
  def z[B](implicit x : X[B]) : B = ys //the call ∅
}

Which produces:
import X._

scala> new A().z[Int]
res0: Int = 42

scala> new A().z[String]
res1: String = y

Is this valid? Can I achieve the same result with fewer steps?

A:

That's all there is to it. You could remove Xs and retain the essence of the example:
object A{
  def ys[T](implicit x : X[T]) = x.y
}
A.ys

The other interesting aspect of the use in Scalaz is that the type argument to ∅ is inferred from the expected type B of the expression.
I recently had to change Zero to be invariant in its type parameter. This actually breaks the infer-ability of this type argument in some cases; you can see this in this example. There are a few related open tickets which will hopefully be solved by the changes on this branch.


Q:

Are "method" and "function" synonyms?

Would saying "Call the printf function" be the same as "Call the printf method"?

A:

These are a different level classifications:
A method is a function (or procedure) associated with object – a concept from Object Oriented Programming.
A function is the logical unit (a piece of reusable code called by name) independent of any objects (those might not even exist in particular language). So the method is a function, but a function exists also in non-OO languages, so the reverse is not true.


Q:

What is the meaning of the dotted lines in Hanon exercise 33?

In The Virtuoso Pianist in 60 exercises exercise 33 (page 44 of the pdf) there are dotted lines with the numeral 8 above and below joining three measures together - what is their meaning?

A:

Ιt means it's supposed to be played an octave higher than indicated. You may also see this as 8va or 8a and 15ma for two octaves. Respectively, 8vb and 15mb is for 1 and 2 octaves lower than indicated.
People use this when they try to avoid adding many lines above the existing ones.
You can also see it on Wikipedia.
8va means all' ottava = at the octave.
Moreover, on some sheets you might see that after the 8va they write loco which means you are supposed to play it at the octave written.


Q:

Delete specific row in CSV file using HTML Table

I have a HTML table and i usePHP.. the data inside the table is came from an CSV file.
I can already add a new data in a new row at the end of file. My problem is, what if i want to delete existing row that is in the middle of the data in the CSV file. How can i do that? By the way i don't use any database here. I just use HTML Table and CSV  file. Below is my code in viewing CSV and adding new data.
View
<?php
                            $row = 1;
                                if (($handle = fopen("bin/pdw_table.csv", "r+")) !== FALSE) {

                        ?>

                                            Field 1
                                            Field 2
                                            Field 3

                                            Field 4
                                            Field 5

                                            Field 6
                                            Field 7
                                            Field 8
                                            Field 9
                                            Field 10
                                            Field 11
                                            Field 12
                                            Field 13

                                            Field 14
                                            Field 15
                                            Field 16

                        <?php
                                        while (($data = fgetcsv($handle, 1000, ',')) !== FALSE) {
                                            $num = count($data);
                        ?>
                                            <tr <?php if($row==0){echo "style='font-weight:bold; background-color:#CCCCCC'";} else {echo "style='background-color:#DDDDDD'";} ?> style="background-color:#DDDDDD">
                        <?php
                                                for ($c=0; $c < $num; $c++) {
                        ?>
                                                <?php echo $data[$c]; ?>
                        <?php
                            }
                        ?>

                        <?php

                                        $row++;
                                        }
                                        fclose($handle);
                        ?>
                                        <form method="post" name="add1" id="add1" action="<?php echo base_url();?>index.php/datacast_ctr/write_csv" autocomplete="off">

                                                <input type="text" name="val1" id="val1"/>
                                                <input type="text" name="val2" id="val2"/>
                                                <input type="text" name="val3" id="val3"/>

                                                <input type="text" name="val4" id="val4"/>
                                                <input type="text" name="val5" id="val5"/>

                                                <input type="text" name="val6" id="val6"/>
                                                <input type="text" name="val7" id="val7"/>
                                                <input type="text" name="val8" id="val8"/>
                                                <input type="text" name="val9" id="val9"/>
                                                <input type="text" name="val10" id="val10"/>
                                                <input type="text" name="val11" id="val11"/>
                                                <input type="text" name="val12" id="val12"/>
                                                <input type="text" name="val13" id="val13"/>

                                                <input type="text" name="val14" id="val14"/>
                                                <input type="text" name="val15" id="val15"/>
                                                <input type="text" name="val16" id="val16"/>

                                        </form>

                        <?php
                            }
                        ?>

CONTROLLER (code for adding new data EOF)
function write_csv()
{
    $R1 = $this->input->post('val1');
    $R2 = $this->input->post('val2');
    $R3 = $this->input->post('val3');
    $H1 = $this->input->post('valh1');
    $R4 = $this->input->post('val4');
    $R5 = $this->input->post('val5');
    $H2 = $this->input->post('valh2');
    $H3= $this->input->post('valh3');
    $R6 = $this->input->post('val6');
    $R7 = $this->input->post('val7');
    $R8 = $this->input->post('val8');
    $R9 = $this->input->post('val9');
    $R10 = $this->input->post('val10');
    $R11 = $this->input->post('val11');
    $R12 = $this->input->post('val12');
    $R13 = $this->input->post('val13');
    $H4 = $this->input->post('valh4');
    $R14 = $this->input->post('val14');
    $R15 = $this->input->post('val15');
    $R16 = $this->input->post('val16');
    $H5 = $this->input->post('valh5');

    $data = $R1.",".$R2.",".$R3.",".$H1.",".$R4.",".$R5.",".$H2.",".$H3.",".$R6.",".$R7.",".$R8.",".$R9.",".$R10.",".$R11.",".$R12.",".$R13.",".$H4.",".$R14.",".$R15.",".$R16;
    $list = array($data);

    $file = fopen("./bin/pdw_table.csv","a+");

    foreach ($list as $line)
    {
        fputcsv($file,explode(',',$line));
    }

    fclose($file);
    redirect('datacast_ctr');
}

A:

AFAIK you can't just delete one line that easy. You have to either open the file, read all lines one after another and put them into the output file except the one you want to delete or use this solution.
If you want to know how to implement this, it depends on the data in your csv file. If you have some sort of unique key you can add another column with a button or anything that calls the delete function passing this key.
EDIT
This is pseudo code as i don't have a php environment here at the moment. But something like
    $filedata = "";
    $line = "";
$f = fopen("<filename>", "c+");
while($line = fgets ($f)){
    if($line != "check here if the line is the one to delete"){
        $data.= $line;
    }
}
ftruncate($f,0);
fputs($f, $data);
fclose($f);


Q:

Ubuntu where to see console.logs

So I am putting my app on a server and I want to see some console logs generated from my nodejs app. Before putting it on the server I saw the output of my console log on my terminal, but where do I find the output for these on Ubuntu? I'm running version 16.04 on Ubuntu

A:

Lifted straight from @SlovyanskiyYehor comment two years ago, but I missed his answer as a comment. Also answered here: Make pm2 log to console.
If you are using pm2 to start your node.js application, you can use:
pm2 logs

or for just a single app running in pm2:
pm2 logs yourAppNameHere


Q:

Calculation by group in one column R

group=c("A","A","B","A","B","C","C","A")
y=c(3,4,5,2,1,4,1,2)
df=data.frame(group,y)

using aggregate, I can get the average by
aggregate(df$y, list(df$group), mean)

But my question is: How to do something like : (y_ij-mean_i)
where mean_i is the average for group i
thank you.

A:

We can use ave
 with(df, y- ave(y, group))


Q:

QT example executables won't run, missing QT5Cored.dll

QT5Cored.dll is on my system @: C:\Qt\5.4\mingw491_32\bin folder
The Analogclock example and other projects will run in the IDE, but can Not be run from the created .exe files. When the EXE is launched the QT5Cored.dll missing error occurs.
QT installed it & doesn’t know where it is?
Removed & reinstalled QT with same results.

Downloaded earler today.
Version: 3.3.1, QT 5.4.1(MSCV 2010, 32 Bit), Built on Feb 20, 2015.
Any suggestions appreciated.
New error after DLL filles added to exe directory.

A:

To run it outside of Qt Creator, you have two choices:

Copy the missing DLLs to the directory where the executable resides. For example if analogclock.exe is in c:\examples, then copy C:\Qt\5.4\mingw491_32\bin\Qt5Cored.dll and other required DLLs to c:\examples. You may need to copy plugins files too.
Add C:\Qt\5.4\mingw491_32\bin to the PATH environment variable.

There are some ways to copy the missing DLLs:
1. Use Windows Deployment Tool (windeployqt.exe) to copy required files

Open Command Prompt in one of the following way:

If you use MSVC as compiler, open the correct Visual Studio Command Prompt. For example for VS2013 32-bit, click Start -> Microsoft Visual Studio 2013 -> Visual Studio Tools -> VS2013 x86 Native Tools Command Prompt. This will open a Command Prompt with the VCINSTALLDIR environment variable correctly set. windeployqt.exe requires this environment variable to copy the correct Visual C++ redistributable executable.
If you use MinGW, just open a Command Prompt.

Add Qt binary path and optionally g++.exe path to PATH environment variable. If your executable is 32-bit, add the 32-bit Qt binary path, eg: c:\Qt\5.4\msvc2013\bin. If your executable is 64-bit, add the 64-bit Qt binary path, eg: c:\Qt\5.4\msvc2013_64\bin. windeployqt.exe will copy DLLs from this directory, so it is important that you don't set 32-bit Qt binary path for a 64-bit executable, vice versa. You need to add g++.exe path too if you use MinGW, windeployqt will copy lib*.dll from there.
; Example path for MSVC 32-bit
PATH=c:\Qt\5.4\msvc2013\bin;%PATH%

; Example path for MinGW 32-bit, g++.exe is in C:\Qt\Tools\mingw491_32\bin
PATH=C:\Qt\5.4\mingw491_32\bin;C:\Qt\Tools\mingw491_32\bin;%PATH%

Run windeployqt.exe with your executable file as argument. Eg:
windeployqt.exe C:\Qt\Examples\Qt-5.4\widgets\richtext\build-calendar-Desktop_Qt_5_4_0_MSVC2013_32bit-Debug\debug\calendar.exe

Check the output for error or warning. The following is an output without error and warning:

2. Manually copy the DLLs
You must copy the correct DLLs (32-bit or 64-bit). Use a tool like Process Explorer to find the correct DLL paths:

Run the application from Qt Creator / Visual Studio.
Open Process Explorer.
In Process Explorer

Click the executable, for example calendar.exe
Press Ctrl+D to show loaded DLLs in the lower panel. The equivalent menu is View -> Lower Panel View -> DLLs
In the lower panel, click the Path column to sort by path.

Copy the DLLs to the directory where the executable resides. For example in the following picture. The DLLs are from C:\Qt\5.4\msvc2013\bin.

If your executable uses something like c:\Qt\5.4\msvc2013\plugins\platforms\qwindowsd.dll. It should be copied too. But copy from the platforms directory, not plugins. Let's say calendar.exe's full path is c:\examples\calendar.exe, then qwindowsd.dll should be copied to c:\examples\platforms\qwindows.dll, not c:\examples\plugins\platforms\qwindows.dll.
You need to copy C++ runtime library too. If you are using mingw, you may need to copy libgcc_s_dw2-1.dll, libstdc++-6.dll. libwinpthread-1.dll etc too. Check in Process Explorer to be sure. If you are using MSVC, you need to deploy the runtime (Eg: msvcp120.dll, msvcr120.dll). At the end, your directory structure is something like this:
c:\examples\calendar.exe
c:\examples\Qt5Cored.dll
c:\examples\Qt5Widgetsd.dll
c:\examples\Qt5Guid.dll
c:\examples\icudt53.dll
c:\examples\icuin53.dll
c:\examples\icuuc53.dll
c:\examples\libgcc_s_dw2-1.dll   (if using mingw)
c:\examples\libstdc++-6.dll      (if using mingw)
c:\examples\libwinpthread-1.dll  (if using mingw)
c:\examples\platforms\qwindowsd.dll

A:

A simple solution for me was just adding the QTDIR C:\Qt\5.4\msvc2017_64\ to your Windows system variables.

In Windows search, type 'env' and press "Edit the system environment variables"
Press "Environment Variables" below
In the System variables list, press "New..."
Add QTDIR as variable name, with value the directory name of the compiler under the Qt directory: C:\Qt\5.4\mingw491_32 in your case


Q:

Counting Methods with Combinatorics Problems (2)

I have a couple of problems with my attempts at them. I was wondering if I could get some verification/help if possible!

A college sent a report saying that 119 students took Calc. I in a Fall Semester. The report says that during the next term, 96 of those students were in Calc. II, 53 of them took Discrete Mathematics, and 39 of them took Physics II. The report also says that 38 of the students took both Calc. II and Discrete Mathematics, 31 of the students took both Discrete Mathematics and Physics II, 32 of the students took both Calc. II and Physics II, and 22 of the students took all three courses. We examine the report and sense an error is present. Why?

119 students total from the Fall semester.
96-Calc II
53-Discrete Mathematics
39-Physics II
38-Calc II and Discrete
31-Discrete and Physics II
32-Calc II and Physics  II
22-Calc II, Discrete, and Physics II
My guess is that if 22 students took all three courses, that would leave a remainder of 74 that are taking Calc II, 31 taking Discrete Math, and 17 taking Physics II which adds up to 122 students. 122>119. Is that the error? Or am I approaching this wrong?

2. We are going to count banana splits: These are ice cream treats that have 3 scoops of ice cream (two or three of the scoops could be the same flavor), three toppings (two or three could be the same flavor), whipped cream (always), a choice of nuts or no nuts, and a choice of a cherry or no cherry, all placed atop two banana halves. If there are 18 different flavors of ice cream and 5 choices of toppings, how many different banana split orders are possible? Note that people do care which toppings end up on which scoops, so the positions of the scoops should be labeled.

So, we have to have 3 scoops of ice cream that have 18 different flavors and they can be repeated  3 toppings that have 5 different kinds and they can be repeated  always whipped cream  nuts or no nuts  and a cherry or no cherry.

I'm going to take a wild shot at this, and I'm probably overthinking it. Order matters and repetition is allowed for the toppings on the scoops. So, we have 18 flavors for our 3 scoops of ice cream. We would use $k^n= 18^3= 5,832$ different scoop & flavor combinations. Same approach with the toppings: $5^3=125$ different combinations.
I attempted to go further with this, but yielded an incredibly high number...so, I'm stopping here. I think I'm doing something wrong. Any suggestions are appreciated very much!

A:

First
Indeed an error is present.
Let's call $A$ the set of students who took Calculus I.
Let $C,D,P$ be three of its subsets. (for Calculus, Discrete and Physics)
(I notate the disjoint union $\sqcup$)
Provided information
$$|A|=119, ~~~~~~ |C|=96, ~~~~~~ |D| = 53, ~~~~~~ |P|=39$$
$$|P\cap C| = 32, ~~~~~~ |P\cap D|=31, ~~~~~~ |C\cap D| = 38, ~~~~~~ |C\cap D\cap P| = 22$$
But
$$\matrix{&P\cap D &= &(P\cap D \cap C) & \sqcup & (P\cap D\cap\bar C)\\
\Rightarrow & |P\cap D| & = & |P\cap D \cap C| & + & |P\cap D\cap\bar C|\\
\Leftrightarrow & |P\cap D| & - & |P\cap D \cap C| & = & |P\cap D\cap\bar C|\\
\Rightarrow & 31 & - & 22 & = & |P\cap D\cap\bar C|\\
\Rightarrow & &&|P\cap D\cap\bar C| & = & 9}$$
With a similar reasoning, we find that $~~|P\cap C\cap \bar D|= 10$
Finally,
$$\matrix{&P&=&(P\cap D \cap C)&\sqcup&(P\cap D \cap \bar C)&\sqcup&(P\cap \bar D \cap C)&\sqcup&(P\cap \bar D \cap \bar C)\\
\Rightarrow & |P| & \geqslant&|P\cap D \cap C|&+&|P\cap D \cap \bar C|&+&|P\cap \bar D \cap C|\\
\Rightarrow & 39 & \geqslant&22&+&9&+&10\\
\Leftrightarrow & 39 & \geqslant & 41}$$
Seems like we got ourselves a contradiction.
Solution
$$|P\cap C \cap D| \leftarrow 24$$
(I verified every possible relation and there is no contradiction)
Second

The choice of scoop flavor is unordered with repetition so the possibilities are $\binom{n+k-1}{k}=\binom{18+3-1}{3}=1140$
The choice of topping is ordered and with repetition, thous $5^3 = 125$ possibilities
Nuts and cherries both multiply by 2

Total
We got a total of 570 000 possible banana splits !!


Q:

UIWebView: Can You Disable Javascript?

You can disable Javascript in both mobile Safari and Cocoa's WebView but I can see no means of doing so in UIWebView.
Am I correct?
I ask in relation to this question regarding obtaining the title of page displayed in an UIWebView using Javascript. I had worried that it would fail if Javascript was disabled but it appears the API does not allow the disabling of Javascript.
If Javascript cannot be deactivated UIWebView,that renders my previous question moot.

A:

There is a way!  Using the Content Security Policy which is partially supported in iOS 5.1 and up, and a custom header:
X-WebKit-CSP: script-src none;

You can tell the UIWebKit to not allow javascript on the page entirely.  (or selectively only allow script from a specific domain, more information in the spec.
To do this from a server you control, you'll have to modify the response headers for the page to include the X-WebKit-CSP header... To do it from pages that are local (plain text or HTML data on device), you'll have to define and register a custom NSURLProtocol for loading your page, and send the header in your crafted NSHTTPURLResponse:
NSDictionary *headers = [NSDictionary dictionaryWithObjectsAndKeys:
                         @"script-src none",@"X-WebKit-CSP",
                         @"text/html",@"Content-type",
                         encoding,@"Content-encoding",
                         nil];
NSHTTPURLResponse *urlResponse = [[NSHTTPURLResponse alloc] initWithURL:self.request.URL
                                                         statusCode:200
                                                        HTTPVersion:@"1.1"
                                                       headerFields:headers];
[self.client URLProtocol:self didReceiveResponse:urlResponse cacheStoragePolicy:NSURLCacheStorageAllowedInMemoryOnly];

A:

There is no public API to disable Javascript. So it is fairly safe to assume that it won't be disabled.


Q:

Redux store: Element type is invalid: expected a string

I am getting an error setting up the store for redux using typescript for the first time.
The error message is as following:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports.
  11 | // tslint:disable-next-line
  12 | const store = configureStore(undefined);
  13 |
> 14 | render(
  15 |   <Provider store={store}>
  16 |     <ConnectedRouter history={createHistory()}>
  17 |       <App />

 import * as React from 'react';
    import {render} from 'react-dom';
    import {ConnectedRouter} from 'react-router-redux';
    import {Provider} from 'react-redux';
    import configureStore from './store/configureStore';
    import createHistory from 'history/createBrowserHistory';

    import App from './App';
    import './styles/styles.css';

    // tslint:disable-next-line
    const store = configureStore(undefined);

    render(
      <Provider store={store}>
        <ConnectedRouter history={createHistory()}>
          <App />
        </ConnectedRouter>
      </Provider>,
      document.getElementById('root') as HTMLElement
    );

My configurestore:
import {createStore} from 'redux';
import rootReducer from '../reducers';

interface WindowModuleHot extends Window {
  module: {
    hot: {
      accept: (path: string, callback: () => void) => void;
    };
  };
}

export default function configureStore(initialState: any) {
  const store = createStore(rootReducer, initialState);
  const hotWindow = window as WindowModuleHot;

  if (hotWindow.module && hotWindow.module.hot) {
    // Enable Webpack hot module replacement for reducers
    hotWindow.module.hot.accept('../reducers', () => {
      const nextReducer = require('../reducers');
      store.replaceReducer(nextReducer);
    });
  }

  return store;
}

A:

ConnectedRouter is for version 5.0 of react-router-redux. Npm currently points to v4.0.8 here.


Q:

How to include existing code/class file when compiling in Java

I am a complete newbie with Java. I use notepad++ to write Java code, and then compile and execute using command line on the Windows Platform
How do I reuse existing code or a class file? For instance, I have written a class in file A.java (with the corresponding compiled class file available) and wish to use that class in B.java. Do I need to specify it in the B.java file (sort of lie c/c++) or using compiler options. What compiler options?

A:

You're looking for the import statement, and the Using Package Members tutorial.

A:

You can use import the A.java class in B.java like this
import A.java;

By doing like this A class will be available in B class.
Java Packages Tutorial


Q:

Removing characters from a string

I have an app in which I parse a .txt file from a URL and spit out the string to the user. I want to remove the first 16 characters of the string. How can I do this?
EDIT- I want to remove 16 characters from the data I receive from my http call.
public void onClick(View src) {
        switch(src.getId()) {
        case R.id.buttonRetrieveMetar:

            InputMethodManager imm = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);

imm.hideSoftInputFromWindow(EditTextAirportCode.getWindowToken(), 0);

            textDisplayMetar.setText ("");

            airportcode = EditTextAirportCode.getText().toString();
            url = urlmetar + airportcode + ".TXT";

            //Added 06-27-11 METAR code
            textDisplayMetar.setText ("");

            try {
                HttpGet httpGet = new HttpGet(url);
                HttpClient httpclient = new DefaultHttpClient();
                // Execute HTTP Get Request
                HttpResponse response = httpclient.execute(httpGet);
                content = response.getEntity().getContent();
                BufferedReader r = new BufferedReader(new
InputStreamReader(content));
                StringBuilder total = new StringBuilder();
                String line;

                while ((line = r.readLine()) != null) {
                    total.append(line);
                }
                textDisplayMetar.append("\n" + total + "\n");
                    } catch (Exception e) {
                //handle the exception !
            }

   break;

Thanks!

A:

You can't modify the string itself, but you can create a substring easily enough:
line = line.substring(16);

The single-parameter overload of substring takes the whole of the rest of the string after the given start index. The two-parameter overload starts at an index specified by the first argument, and ends at an index specified by the second argument (exclusive). So to get the first three characters after "skipping" the first 16, you'd use:
line = line.substring(16, 19);

Note that you don't have to assign back to the same variable - but you need to understand that it doesn't affect the string object that you call it on. So:
String original = "hello world";
String secondPart = original.substring(6);

System.out.println(original); // Still prints hello world
System.out.println(secondPart); // Prints world

EDIT: If you want to remove the first 16 characters of the whole file, you want:
textDisplayMetar.append("\n" + total.toString().substring(16) + "\n");

If you want that on a per-line basis, you want:
while ((line = r.readLine()) != null) {
    total.append(line.substring(16));
}

Note that both of these may require extra validation - if you call substring(16) on a string with less than 16 characters, it will throw an exception.


Q:

Jquery datepicker unavaialble dates

Html

Date: <input id="datepicker" type="text">

"17-2-2015","28-2-2015","01-1-1970","24-3-2015","25-2-2015","25-2-2015","26-2-2015","27-2-2015","21-3-2015"

Javascript here
    var unavilabledates = $('#DesignIdUnavialble').html();
    var availableDates = [unavilabledates];
    //console.log(availableDates);

    function available(date) {
      dmy = date.getDate() + "-" + (date.getMonth()+1) + "-" + date.getFullYear();
      if ($.inArray(dmy, availableDates) !== -1) {
        return [false, "","Available"];
      } else {
        return [true,"","unAvailable"];
      }
    }

//$( "#datepicker" ).datepicker();
$('#datepicker').datepicker({
   beforeShowDay: available,
   dateFormat: "dd-mm-yy",
   onSelect: function (date) {
   }
});

I'm trying to hide the unaviable dates but i cant able to do it..
when im executing this
var availableDates = ["17-2-2015","28-2-2015","01-1-1970","24-3-2015","25-2-2015","25-2-2015","26-2-2015","27-2-2015","21-3-2015"];

its working properly.while im using this
 var unavilabledates = $('#DesignIdUnavialble').html();
 var availableDates = [unavilabledates];

Its not working.. how can i fix this ?
Here is my Fiddle

A:

you need an array for unavailable script but what you do is putting the whole html-string into an array, so the array contains of just 1 string
try that:
 var unavilabledates = $('#DesignIdUnavialble').html();
var availableDates =[];
$(unavilabledates.split(",")).each(function(i, el){console.log(el);availableDates[i] =      el.substring(1, el.length-1)});

EDIT: changed code


Q:

In which case would HTML5 be advantageaous compared to flash?

I have read a few articles, I can't see why one would use html5 instead of flash so any few examples which could show the advantages ?

A:

HTML5 isn't one big blob that, taken as a whole, obsoletes Flash. It's lots of independent developments that browser vendors have been working on, some of which will allow native-HTML browsers to do things that have previously been limited to plugins such as Flash.

The famous one of these is audio/video. Flash was designed for animation and games, but in recent years since Flash added FLV playback, video has become by far the more prevalent use case for Flash (replacing embedded media players, which were always really horrible — good riddance to them). When browsers can do video by themselves, that will take a big bite out of Flash on the web.
Another important feature is <canvas>. This expands the possibilities for games and other simple animations and pixel-level user interaction. Obviously it is far from offering all that Flash can do in the 2D realm, but again, it'll take a bite out of Flash's traditional use cases by offering similar features in an easier-to-deploy environment.

There are also features which browser vendors are implementing that are not actually part of HTML5, but which are seen as part of the same future-browser platform. For example:

ECMAScript Fifth Edition. JavaScript, now 10% less rubbish!
WebSockets. Faster than XMLHttpRequest, more reliable than Flash sockets.
SVG. This has long existed, but without IE support and with relatively poor performance for animations in many browsers. IE9 brings SVG support and promises to make it fast, potentially kicking the other browsers into optimisation action. SVG could offer rich retained-mode graphics in a similar vein to Flash, but with much smoother integration into the web page (instead of being stuck in a box).
CSS3 font embedding and effects will reduce the need for Flash text-replacement hacks.
Potentially, in the future, WebGL or similar for 3D.

and so on. Does all this, taken together, obsolete Flash? No. Not even when most deployed browsers support it all (and that'll be a long time yet). But it doesn't leave very much that only Flash can do.
IMO: in the future Flash will remain popular for drawn animation (thanks to its authoring environment) and games. But in five years it will no longer be what it is today: an essential, integral part of the web.

A:

HTML5-based pages will work on the iPhone and IPad.  Flash will not.  Right now, Flash is supported more broadly that HTML5 except on Apple's mobile platform.  HTML5 support is rapidly becoming ubiquitous so it is certainly a reasonable choice even for non-mobile focused sites.  If you choose HTML5, you may want to implement graceful fall back for clients that do not implement any or all of the HTML5 features you use.


Q:

Assigning some style from the styles-box in CKEditor through JavaScript

How can I simulate user-selection of some style from the styles-box, through JS? I want to put some shortcut buttons that assign some of the popular styles with one click.
EDIT:

I don't care if it'll be in-editor button or outer button.
I don't want css-style assignment; I want CKEditor-style assignment (those of the styles-box).

A:

I haven't used CKEditor, but, I saw your question and thought "That would be fun to figure out."  Well, here is what I figured out:
(yes, I found terrible documentation, but, that's not the point...I will give them props for commenting their code, though.)
///
// function to add buttons that trigger styles to be applied.
//
// editor - CKEDITOR - instance of editor you want command attached to.
// buttonName - String - name of the button
// buttonLabel - String - humane readable name of the button
// commandName - String - name of command, the way to call this command from CKEDITOR.execCommand()
// styleDefinition - StyleDefinition - obj defining the style you would like to apply when this command is called.
///

var addButtonCommand = function( editor, buttonName, buttonLabel, commandName, styleDefiniton )
{
    var style = new CKEDITOR.style( styleDefiniton );
    editor.attachStyleStateChange( style, function( state )
        {
            !editor.readOnly && editor.getCommand( commandName ).setState( state );
        });
    editor.addCommand( commandName, new CKEDITOR.styleCommand( style ) );
    editor.ui.addButton( buttonName,
        {
            label : buttonLabel,

            command : commandName
            //adding an icon here should display the button on the toolbar.
            //icon : "path to img",
        });
};

//Get the editor instance you want to use.  Normally the same as the ID of the textarea CKEditor binds to.
var editor1 = CKEDITOR.instances.editor1;

//If you look at ckeditor/_source/plugins/styles/default.js you will see that this selects the first element.  That list is read into the array 'default'.
var blueTitleStyle = CKEDITOR.stylesSet.registered.default[0];

//Or, you can define the style like this: See http://dev.ckeditor.com/wiki/Components/Styles for more info on style definitions.
var blueTitleStyle = {
    name : 'Blue Title',
    element : 'h3',
    styles : { 'color' : 'Blue' }
};

addButtonCommand(editor1, 'BlueTitle', 'BlueTitle', 'bluetitle', blueTitleStyle);

Here is a Javascript function to aid your click events:
//function used to execute the command.  Only used for calling the command when not calling from a button. (Like an A with an onClick bound to it.)
    //pulled this function right out of the api.html example in the ckeditor/_samples dir.
    function ExecuteCommand( commandName )
    {
        // Get the editor instance that we want to interact with.
        var oEditor = CKEDITOR.instances.editor1;

        // Check the active editing mode.
        if ( oEditor.mode == 'wysiwyg' )
        {
            // Execute the command.
            // http://docs.cksource.com/ckeditor_api/symbols/CKEDITOR.editor.html#execCommand
            oEditor.execCommand( commandName );
        }
        else
        {
            alert( 'You must be in WYSIWYG mode!' );
        }
    }

Now, you can create a link like this:
Set Blue Title

and use a bit of jQuery to spice it up:

I am not 100% sure about the button icon part.  I didn't have an icon to try it with.  But, according to a few posts, it should work fine.  Regardless, the jQuery click binding works.
That should be pretty much it!  I had to do quite a bit of digging around to figure this out, but it certainly is satisfying to see it work!


Q:

Changing game object type: reinstantiating the object, or switching an object state

I work on a strategy game, where the player occasionally has to transform ordinary citizens into the so called "leaders". Leaders are temporary units, which the player can control directly, in order to interact with the other citizens. After some time, the leader gets transformed back to a normal citizen.
My question is if I should stick to the classical OOP approach of keeping citizens and leaders in two separate classes, whereas the leader class extends the citizen class, and every time when I need a leader, I simply re-instantiate the current citizen instance.
I personally dislike this approach, however. I already have a state machine implemented, and am more likely to keep only the citizen class (or rather, human class). Rather, I'd like to keep the citizen/leader separation into two different states. When I need one or the other type, I simply switch the current state.

A:

Most games don't have different classes for different entity types, because it's not very flexible. Your example is a classic case of why this is so! Classical OO with one-class-per-noun is great for toy problems but not so good in the real world.
I'd suggest using the Strategy pattern, and swapping out a behaviour object that encapsulates the key differences between the two types of character, leaving the rest of the entity unchanged.


Q:

What's the best way to store this data structure?

I'm creating a kind of wiki site and have a data structure which consists of a parent entity which has a one to many relationship to a child entity. I'm currently storing this in two tables in the database, with a foreign key relationship from the child entity table to the parent entity table.
I need to version this data structure in my database for the wiki functionality. This would be straight forward if it were just one table, but since it's two it's a bit more tricky. I was thinking of removing the child entity table and storing them as XML data in a field of the parent entity table. I don't need to search by these child entities. Is this a good or bad idea? Are there any better ways to store my data?

A:

I was thinking of removing the child
  entity table and storing them as XML
  data in a field of the parent entity
  table

Every time you change a parent you will create a copy of the children: if the parent data changes a lot, then you will eat up your storage quite quickly.   Also, storing all the child changes within a single parent record will tend to bloat the parent (as having lots of children tends to), which might have implications for the performance of data retrieval.
There are many different ways of storing versioned data, but they fall into two categories:

current version in one store, historical versions in another store
all versions in a single store

Choosing between these approaches depends on what you want to do with the historical versions.  Are they there just for rollback?  Or will users be regularly browsing changes?
A further complication which doesn't always apply but which I think might be pertinent here (because of your suggested solution) is the relationship between parent and child changes: when you show a historical version of the parent do you need to show the appropriate versions of the child?  And vice versa, if you show an old version of a child, do you need to show the appropriate versions of its parent (and siblings)?
The key thing you need to establish is: what are most users going to do most of the time?  Prioritise that.  If the most common use case is look at just the current versions of all records then you should go for separate tables for storing the versions.
If you need to record the child versions which applied to a given parent version then you could introduce an additional framework table (parent_id, parent_version, child_id, child_version).  Maintaining this table is not too onerous when you only have tables for one parent and one child.  Where it gets gnarly is when you have multiple child you need to track.


Q:

Android Studio - EditText.addTextChangedListener not working

I have an application that I had implemented Fragment Pager Adapter for swiping pages using fragment. Then, on the fragment, it have a EditText and a TextView. I want to implement  EditText.addTextChangedListener into the fragment, so at MainActivity.java
package testing.com.testing;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;

import layout.page1;
import layout.page2;

public class MainActivity extends AppCompatActivity {

ViewPager mViewPager;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mViewPager = (ViewPager) findViewById(R.id.pager);
    mViewPager.setAdapter(new SamplePagerAdapter(
            getSupportFragmentManager()));

}

public class SamplePagerAdapter extends FragmentPagerAdapter {

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

    @Override
    public Fragment getItem(int position) {

        if (position == 0) {
            return new page1();
        } else
            return new page2();
    }

    @Override
    public int getCount() {
        return 2;
    }
}

}

My fragment.java
package layout;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.text.Editable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import testing.com.testing.R;

public class page1 extends Fragment {

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.page1, container,
            false);
    return rootView;
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    EditText text;
    TextView textv;
    text = (EditText) getView().findViewById(R.id.p1Name);
    textv = (TextView) getView().findViewById(R.id.textView);

    text.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            textv.setText(s);
        }
    });
}

}

But it doesn't work, I get error on TextWatcher, error: cannot find symbol class TextWatcher, Execution failed for task ':appcompileDebugJavaWithJavac'. Can anyone please help me..

A:

Assuming R.id.p1Name and R.id.textView in your fragment's layout
Inside your fragment in onActivityCreated(...) method get the reference to the edittext and set the addTextChangedListener over there.
@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);

 text = (EditText) getView().findViewById(R.id.p1Name);
 textv = (TextView) getView().findViewById(R.id.textView);

text.addTextChangedListener(new TextWatcher() {
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        textv.setText(s);
    }
});
}


Q:

Skeletal Animation - Caching global bone transforms

Very often I see skeletal animation implemented like this:

On Init - store bone's local transforms and inverse bind pose
On Update - traverse the skeleton tree, multiplying local transforms on the way (and inverse bind pose)

However, it is more efficient to pre-calculate global poses from local transforms and just reassign them at specified time point to constant buffer.
What is the benefit of keeping all those local matrices? Does it have any meaningful application in other systems like physics, collision detection?
People still choose the first scenario and that actually keeps me puzzled.

A:

In a lot of cases animations are blended between to create a pose. In some cases many animations are layered at once, sometimes on only part of the body. Finally inverse kinematics can be applied on top or under animations. The only way for all this to work is if the bones transforms are first calculated in local space.


Q:

Table with name 'X' is not defined

I downloaded the swift and Xamarin.Android version of quick start application (To Do Item) and it worked fine, then I added some additional models like Country and tried to fetch data from both applications and I get the following errors:
iOS Swift Error:
Error: Error Domain=com.Microsoft.MicrosoftAzureMobile.ErrorDomain Code=-1153 "Table 'Country' not found" UserInfo={NSLocalizedDescription=Table 'Country' not found}

Android Xamarin Error:
System.InvalidOperationException: Table with name 'Country' is not defined.
  at Microsoft.WindowsAzure.MobileServices.SQLiteStore.MobileServiceSQLiteStore.GetTable (System.String tableName) [0x00024] in <filename unknown>:0
  at Microsoft.WindowsAzure.MobileServices.SQLiteStore.MobileServiceSQLiteStore.ExecuteQuery (System.String tableName, System.String sql, IDictionary`2 parameters) [0x00000] in <filename unknown>:0
  at Microsoft.WindowsAzure.MobileServices.SQLiteStore.MobileServiceSQLiteStore+<>c__DisplayClass8_0.<ReadAsync>b__0 (System.Threading.Tasks.Task t) [0x00022] in <filename unknown>:0
  at System.Threading.Tasks.ContinuationResultTaskFromTask`1[TResult].InnerInvoke () [0x00027] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/Tasks/TaskContinuation.cs:111
  at System.Threading.Tasks.Task.Execute () [0x00016] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/threading/Tasks/Task.cs:2502
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
  at Microsoft.WindowsAzure.MobileServices.Sync.MobileServiceSyncContext+<ReadAsync>d__25.MoveNext () [0x00179] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
  at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryProvider+<Execute>d__8`1[T].MoveNext () [0x001b8] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
  at Microsoft.WindowsAzure.MobileServices.Query.MobileServiceTableQueryProvider+<Execute>d__7`1[T].MoveNext () [0x000a5] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
  at Microsoft.WindowsAzure.MobileServices.Sync.MobileServiceSyncTable`1+<ToListAsync>d__23[T].MoveNext () [0x00060] in <filename unknown>:0
--- End of stack trace from previous location where exception was thrown ---
  at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw () [0x0000c] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/exceptionservices/exceptionservicescommon.cs:143
  at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (System.Threading.Tasks.Task task) [0x00047] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:187
  at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (System.Threading.Tasks.Task task) [0x0002e] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:156
  at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd (System.Threading.Tasks.Task task) [0x0000b] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:128
  at System.Runtime.CompilerServices.TaskAwaiter`1[TResult].GetResult () [0x00000] in /Users/builder/data/lanes/3415/7db2aac3/source/mono/external/referencesource/mscorlib/system/runtime/compilerservices/TaskAwaiter.cs:357
  at swoup.ToDoActivity+<OnCreate>d__7.MoveNext () [0x001c1] in C:\Users\Developer\Documents\Visual Studio 2015\Projects\SwoupAndroidTest\swoup\ToDoActivity.cs:68

On the browser it returns the expected result https://swoup.azurewebsites.net/tables/country?ZUMO-API-VERSION=2.0.0

A:

The fix was very easy, for Xamarin.Android you only needed to define the table in InitLocalStoreAsync, I suppose it something similar for other languages.
private async Task InitLocalStoreAsync()
{
    // new code to initialize the SQLite store
    string path = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal), localDbFilename);

    if (!File.Exists(path)) {
        File.Create(path).Dispose();
    }

    var store = new MobileServiceSQLiteStore(path);
    store.DefineTable<ToDoItem>();
    store.DefineTable<Country>(); // Here I defining new table

    // Uses the default conflict handler, which fails on conflict
    // To use a different conflict handler, pass a parameter to InitializeAsync. For more details, see http://go.microsoft.com/fwlink/?LinkId=521416
    await client.SyncContext.InitializeAsync(store);
}


Q:

WordPress - Targetting a specific CSS selector on a specific page

There is a CSS selector that I want to target, but only on one specific page.
Normally I would write something like this:
.page-id-70 a{
    text-decoration: underline;
}

But this selector is in a different form, it's inside brackets:
[class*="span"]  {
    margin-left: 82px;
}

Is there a way to target a selector like that on a single page ID?

A:

The best way to do this is to either use Developer Tools (Chrome is usually the best), and right click on the DOM element and select 'Copy CSS Path'.
Although, if this exact path is also on other pages, it may be best to include the class you want to modify within the page itself. For example, in the Wordpress edit, just add <style> .myClass{ styles here } </style> at the top of the edit box.
For example, go to the page that you would like to edit. Make sure you are in the text or html view, not the visual view. Then paste the following at the very top:
<style>
#boxedWrapper > div:nth-child(5) > div.span12.animated.activate.fadeIn {
    margin-left:82px;
}
</style>


Q:

Regular train service from Antananarivo to Antsirabe?

The Madarail website lists two options from Antananarivo to Antsirabe:

La Micheline "Viko-Viko"
Le Trans Lemurie Express

Both options seem to run for weddings and such events, according to the description.
Also, the French Wikivoyage says the line is closed, but I don't know how recent the information is.
Is there any regular train service that individuals can use, more economical than hiring a whole train for yourself?

A:

No, there is only cargo rail service between from Antananarivo to Antsirabe.
The only public transportation options are taxi-brousse and plane.

A:

As of August 2017, there are still no passenger train services from Antananarivo. (For a while, the vintage Micheline did run a tourist trip from Antananarivo at weekends, but it no longer operates any services.) Passenger trains in Madagascar run on at least one day per week on the following routes:

Moramanga to Toamasina (Tamatave)
Moramanga to Ambatondrazaka
Fianarantsoa to Manakara

Each of these journies takes between half a day and one day.

A:

At madarail.mg you can find an overview of current routes.
Antananarivo and Antsirabe are not on it (September 2014).


Q:

JQuery Mobile Tabs

Does anyone know if JQuery Mobile does Tabs that stick to the bottom like the iphone native apps?
Thanks

A:

Yes, they have tabs that stay fixed to the bottom:
http://jquerymobile.com/demos/1.0a4.1/#docs/toolbars/footer-persist-a.html
They behave slightly differently in that they disappear while scrolling and then reappear after the scrolling is finished.

A:

You can also watch the navbar section for more examples:
http://jquerymobile.com/test/docs/toolbars/docs-navbar.html
Example code:

One

Two

Three


Q:

Example of Non-Compact Closed Set contained in Open Set With Special Property

I am looking for an example of an open set $A$ in a metric space $X$ and a closed, non-compact subset $B$ of $A$ such that there is no $\delta > 0$ s.t. $\{x: \textrm{dist}(x,B) < \delta\} \subset A$.
I have tried using the discrete metric and other obvious tricks but have been unable to come up with an example. Any hints would be appreciated.

A:

Let $X= \Bbb R^2.$  Let $A=\{(x, y)~|~ y \gt 0 \}.$  Let $B=\{(x, y)~|x \gt 0 \land xy \geq 1 \}.$
Choose $\delta \gt 0$.  Then $(2\delta, \frac{1}{2\delta}) \in B$, so $(2\delta, -\frac{1}{4\delta}) \notin A$ but $\operatorname{dist}((2\delta, -\frac{1}{4\delta}), B) \leq \frac{3\delta}{4} \lt \delta.$


Q:

How to combine bootstrap 3 form-control input with hidden true

I am using bootstrap 3 and have a little issue. It is better explained with the code:
<input class="form-control" type="text" name="name" id="id" hidden="true"/>

I expect this input to be hidden, but looks like form-control css display property overrides hidden one.
@media (min-width: 768px)
.form-inline .form-control {
    display: inline-block;
    width: auto;
    vertical-align: middle;
}
[hidden], template {
    display: none;
}

I do see in chrome dev-tools that hidden's display has strikethrough.
I know that bootstrap has "hidden" class and it works, but I would expect that hidden attribute would work too. Isn't it a bug?
Thanks

A:

You can add this in your custom css
[hidden], template {
display: none!important;
}

A:

As an answer to what you want, you can use either display: none; or visibility: hidden;
Check http://www.w3schools.com/Css/css_display_visibility.asp or use opacity: 0; and you can unhide with either CSS or JavaScript.


Q:

CacheManager.net (Redis) - Cache.Add only supports hashes?

I've just begun playing around with CacheManager.Net to add distributed caching capabilities to our app. My level 2 cache is Redis and it seem to work fine.
I notice that when I do a Cache.Add(cacheItem), it always gets added as a Hash to redis.  Using CacheManager, is it possible to add objects as other redis data types? Say as a "String"?
Thanks.
U

A:

No that's currently not supported. CacheManager stores meta data with the cached item to implement other things and all that is stored within one hash.
The operation is implemented with lua scripts and is pretty fast, there is almost no overhead vs just storing a string.
If you have specific use cases which can be applied to other cache vendors, too (not only redis) feel free to post a feature request on github


Q:

create one list from one list with random sample

I have a list, then I want to pick 2 elements (RandomSample[list,2]) put them in a new list (those two element will be one element in the new list, like list of lists) and delete them from the my inicial list and follow the process until my first list turn empty. I need that my out be a list of lists of the random sample elements. What can I do?

A:

Let's say you have a list
list = Range[20]
(* {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20} *)

The better approach, as JM already said is to scramble your original list
RandomSample[list]
(* {3, 20, 6, 7, 15, 13, 10, 11, 16, 4, 9, 14, 8, 12, 1, 17, 18, 2, 19, 5} *)

Now, you only need to partition this list and you are done
Partition[%, 2]
(* {{3, 20}, {6, 7}, {15, 13}, {10, 11}, {16, 4}, {9, 14},
   {8, 12}, {1, 17}, {18, 2}, {19, 5}} *)


Q:

Create polygon geometry from BBOX coordinates in PostGIS

I have a table mytable with coordinates representing Bounding BOX of an object as a text string in column geom_bbox like "548477,6591107,548493,6591121". Coordinates in EPSG3301 in meters. I want to create a polygon geometry, a rectangle geometry using those coordinates.
More example coordinates:
"548477,6591107,548493,6591121"
"545827,6587929,545864,6588021"
"539646,6586576,539694,6586621"
"549054,6594762,549101,6594811"
"547131,6589014,547182,6589046"
"547131,6589014,547182,6589046"

Is it possible with PostGIS?

A:

If you have only bounding boxes, use the function ST_MakeEnvelope. This function creates a rectangle from 4 coordinates (2 points). First split the text with string_to_array and the than use the result as coordinates:
SELECT ST_MakeEnvelope(arr[1]::double precision,
                       arr[2]::double precision,
                       arr[3]::double precision,
                       arr[4]::double precision,
                       3301)
FROM (SELECT string_to_array(geom_bbox,',') AS arr FROM mytable) as foo;


Q:

Save .xls file using Microsoft Office 12.0 Object Library

How do you specify the file format as .xls and not .xlsx when saving an excel file in C# programatically?
I've tried using Excel.XlFileFormat.xlXMLSpreadsheet
Which enumeration type will save the spreadsheet as a 2000-2003 formatted excel spreadsheet?

A:

From 2007/2010 automation you wantExcel.XlFileFormat.xlExcel8 for a 2000-2003 .xls.


Q:

Custom Django Forms (crispy)

I have a registration form, I'm using crispy. I want to make the input fields look better so I wanted to add a class to each of them but the site only renders the first input field with the class. (This is my first django project so I'm pretty new to this)
Here's my forms.py file:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm

class UserRegisterForm(UserCreationForm):
email = forms.EmailField()

class Meta:
    model = User
    fields = ['username', 'email', 'password1', 'password2']
    widgets = {
        'username': forms.TextInput(attrs={'class': 'form-control input'}),

        'email': forms.EmailInput(attrs={'class': 'form-control input'}),

        'password1': forms.PasswordInput(attrs={'class': 'form-control input'}),

        'password2': forms.PasswordInput(attrs={'class': 'form-control input'}),

    }

Here's the template:

<form class="form" method="POST">
    {% csrf_token %}
    <fieldset class="form-group">
        <legend class="border-bottom mb-4, sign-up__header">Join Today</legend>
        {{ form|crispy }}
    </fieldset>

        <button class="btn btn-outline-info" type="submit">Sign up</button>

</form>

A:

class UserRegisterForm(UserCreationForm):
email = forms.EmailField()

class Meta:
    model = User
    fields = ['username', 'email', 'password1', 'password2']
#override
def __init__(self, *args, **kwargs):
    super(UserRegisterForm, self).__init__(*args, **kwargs)

    #Custom classok
    self.fields['username'].widget.attrs['class'] = 'input'
    self.fields['email'].widget.attrs['class'] = 'input'
    self.fields['password1'].widget.attrs['class'] = 'input'
    self.fields['password2'].widget.attrs['class'] = 'input'


Q:

Set up my column in Parse as a Pointer from ObjectId in Swift

I've creating some voting buttons in my Swift app, where a user can vote for a film they like. My app is also integrated with Parse.
When the user presses the vote up button in my app, it increments a count and adds to my Parse database. I have now added some code that also add the film information to what they have just voted for. To do this I have created a new Class in Parse called Votes. My code is as follows:
@IBAction func upVoteButton(sender: UIButton) {

    let hitPoint = sender.convertPoint(CGPointZero, toView: self.tableView)
    let hitIndex = self.tableView.indexPathForRowAtPoint(hitPoint)
    let object = objectAtIndexPath(hitIndex)

    if PFUser.currentUser() != nil {

        let votes = PFObject(className: "Votes")
        votes["userUpVoting"] = PFUser.currentUser()?.objectId
        votes["filmVotedUp_test"] = object!.objectId

        votes.saveInBackground()

    }
}

This code works, and saves the objectId for the film the user has voted for, but it only adds it as a String. Ideally, I'd like this set up to be a pointer in the database.
How can I do this from my code?
Or, is there no point in it being set up in this way? Thanks

A:

First, you need t set up a pointer object in the class Votes that points to _User (User Class). In your code, instead of setting PFUser.currentUser()?.objectId to userUpVoting, just set PFUser.currentUser() to userUpVoting. When you need to set a pointer, you need to set the whole object, not just the object id. Another thing I noticed in your code: make sure that, before the app goes into production, you change votes.saveInBackground to votes.saveInBackgroundWithBlock and handle the errors.
For example, you would use:
classInfo.saveInBackgroundWithBlock({ (success: Bool, error: NSError?) in

                        if success == true {

                            // Object(s) was/were successfully saved

                        } else if error != nil {

                            // Display an alert to the user
                            // Use error!.localizedDescription as the message - it will give the user the specific error that occured

                        } else {

                            // Display an alert to the user - something went wrong

                        }

                    })


Q:

C++ Official Operator Names / Keywords

Happy Holidays guys.
I have been working on a C++ preprocessor sequence (using boost) to assist me in generating operator based functors. I have so far completed the source, however I was having trouble finding the most appropriate keywords identifying these functors.
More specifically after reviewing the C++0x draft I failed to find the most appropriate (unique) names for the following operators:

-> and . which are both called in the draft: class member operators
->* and .* which are both called: pointer to member operators

Do you think you can help me name them better?
The references I have used so for:

The C++0x draft (Can be find online)
The "boost/proto/operators.hpp" header which included most of the over-loadable operators.
The Operators in C and C++ from Wikipedia which also provided the following names

. structure reference
-> structure dereference
->* and .* member pointers

Here is the list I have so far created. Any other suggestions will be greatly appreciated.
 Symbol        Keyword           Description
++      , post_increment      , post increment
--      , post_decrement      , post decrement
++      , pre_increment       , pre increment
--      , pre_decrement       , pre decrement
+       , unary_plus          , additive promotion
-       , unary_minus         , additive inversion
!       , negate              , logical negation
~       , complement          , complement
*       , indirect            , indirection
&       , address_of          , address of
+       , add                 , addition
-       , subtract            , subtraction
*       , multiplies          , multiplication
/       , divides             , division
%       , modulus             , modulo
==      , equal               , equality
!=      , inequal             , inequality
>       , greater             , greater than
<       , less                , less than
>=      , greater_equal       , greater or equal than
<=      , less_equal          , less or equal than
&&      , logical_and         , logical and
||      , logical_or          , logical or
&       , bitwise_and         , bitwise and
|       , bitwise_or          , bitwise inclusive or
^       , bitwise_xor         , bitwise exclusive or
<<      , left_shift          , left shift
>>      , right_shift         , right shift
+=      , add_assign          , addition assignment
-=      , subtract_assign     , subtractions assignment
*=      , multiplies_assign   , multiplication assignment
/=      , divides_assign      , division assignment
%=      , modulus_assign      , modulo assignment
>>=     , right_shift_assign  , right shift assignment
<<=     , left_shift_assign   , left shift assignment
&=      , bitwise_and_assign  , bitwise and assignment
^=      , bitwise_or_assign   , bitwise exclusive or assignment
|=      , bitwise_or_assign   , bitwise inclusive or assignment
->*     , arrow_indirect      , pointer to member
,       , comma               , comma
=       , assign              , assignment
[]      , subscript           , subscription
->      , arrow               , class member
.       , dot                 , class member
.*      , dot_indirect        , pointer to member

A:

Try this reference.
New, delete, casting, I think there are some more operators and keywords there.