Custom Font display wrong with Font Awesome?

Question: I have a Custom Font, Roboto Light and Roboto Regular installed on a Joomla t3 Template.
when i add  Font Awesome Icon the custom Font not shown correctly:
in Firefox show as  a serif type
In Safari and Chrome the Roboto Light shown as regular or bold.
the same conflict shown also with glyphicon classes.
May some can help me?
Link: http://kulimot.ch.mistral.ch-meta.net/index.php/de/entsorgungsysteme/ballenpressen.html
Answer: From the link you've added to the question, it looks like you've done this:

     MACFAB-Abfallpressen können die Abfallmenge um bis zu 90% reduzieren

Although this is a glyph icon and not a font-awesome icon, you should probably not set that style on the td itself, but rather add an i element in the td. Something like this:

     MACFAB-Abfallpressen können die Abfallmenge um bis zu 90% reduzieren

P.S. This code uses a font-awesome icon instead of a glpyhicon.
Comment: Ok, but the icon not shown, in Firefox / Safari, and in Chrome is a blurred text
Comment: I checked your page again. It seems you now have an icon in place, BUT you now have the text inside the `i` element.

 Aufgrund ihrer klar strukturierten und einfachen Bedienung sind sie sehr benutzerfreundlich
Answer: I checked your page again. It seems you now have an icon in place, BUT you now have the text inside the i element. Your text is withinh the  opening and the  end tag. See the code I've copied from your page:

     Sie benötigen nur wenig Platz

If you do this, the text will take on the styling defined by the i. Basically it will use the fonts defined in those styles.
Luckily, the solution is simple from this point (I tried it on the code in your page, and it works for me). Just get the text out of the i element.

    Sie benötigen nur wenig Platz

P.S. Not sure why the   is there at the end of your text, you probably wanted it between the icon and your text. So move it to the front of your text.
Comment: Sorry it works only inside   When i made it outside, save and return to code view, the class is deleted automaticily.
Comment: so i have the solution,i add a class validation, i[class] to the TinyMCE Editor plugin, now it works fine. Thank you


Edit a node into a custom form

Question: I need to edit a node into a custom module. In order to access to the form, I have a custom text link in a view, in that view I have different articles, each row is an article and when I click to the custom text link, I can edit it.

My custom module is "evento". I have the next function to take the node id.
   function evento_load($example_id) {

       return $example_id;
  }

Then, this one to call to the fuction that creates the form.
function edicion_wizard($form, &$form_state, $example_id) {

    $form_state['step_information'] = evento_form($form, $form_state, $example_id);

    //$form = $form_state['step_information'];
    $form['finish'] = array(
      '#type' => 'submit',
      '#value' => t('Terminar'),
      '#submit' => array('form_evento_wizard_submit'),
    );

   $form['next']['#validate'] = array();

    return $form;
}

And this is the function to create the form.
function evento_form($form, &$form_state, $node) {
  //fill your form with data from exemple_id item

     $type = node_type_get_type($node);
     //$node = node_load($example_id);
     $form['idioma'] = array(
        '#type' => 'select',
        '#title' => t('Idioma del evento'),
        '#options' => array('es' => t('Castellano'), 'eu' => t('Euskera'), 'am'=> t('Ambos'),),
        '#default_value' => $node->language,
        '#states' => array (
            'visible' => array(
                ':input[name="Idioma"]'=>array("value"=>"Ambos"),
            ),
        ),

   );

  $query = "SELECT name, tid FROM taxonomy_term_data WHERE vid=2 AND language = '$language_url';";
  $result = db_query($query);
  foreach ($result as $row2) {
     $options2[$row2->tid] = t($row2->name);
  }
  $form['municipios'] = array(
     '#type' => 'select',
     '#title' => t('Municipio'),
     '#options' => $options2,
     '#default_value' => $node->field_municipio_simple[LANGUAGE_NONE][0]['tid'],
     '#required' => TRUE,
  );

 /*  $form['Lugar'] = array(
    '#type' => 'textfield',
    '#title' => t('Lugar'),
    '#default_value' => $node->field_municipio_simple,
    '#required' => TRUE,

  );*/

  $form['inicio'] = array(
    '#type' => 'date_popup',
    '#title' => t('Inicio evento'),
    '#date_format' => 'd/m/Y H:i',
    '#required' => TRUE,
    '#prefix' => '

',
    '#suffix' => '	',
    '#default_value' => $node->field_inicio[LANGUAGE_NONE][0]['value'],
  );

  $form['fin'] = array(
    '#type' => 'date_popup',
    '#title' => t('Fin evento'),
    '#date_format' => 'd/m/Y H:i',
    '#required' => TRUE,
    '#prefix' => '',
    '#suffix' => '

',
    '#default_value' => $node->field_fin[LANGUAGE_NONE][0]['value'],
  );

  $form['titulo'] = array(
    '#type' => 'textfield',
    '#title' => t('Título'),
    '#required' => TRUE,
    '#default_value' => $node->title,
  );

  $form['texto1'] = array(
    '#type' => 'text_format',
    '#title' => t('Texto '),
    '#required' => TRUE,
    '#default_value' => $node->field_descripci_n[LANGUAGE_NONE][0],

    );

   $form['titulo_eu'] = array(
    '#type' => 'textfield',
    '#title' => t('Título en Euskera'),
    '#states' => array (
            'visible' => array(
                ':input[name="idioma"]'=>array("value"=>"am"),
            ),
        ),

  );

  $form['texto2'] = array(
        '#type' => 'text_format',
        '#title' => t('Texto en Euskera'),
        '#states' => array (
            'visible' => array(
                ':input[name="idioma"]'=>array("value"=>"am"),
            ),
        ),
  );

  return $form;

}

Obviusly, I have an other one to save the new node values.
The problem that I have is that I can see the values. The form is not show. I don't know if I'm using the right functions or the correct path in the custom text link. (Is the first time I'm doing something like this).
Can anybody help me? Thanks in advance.

ANSWERD:
What I've done is in the hook_menu use the wildcard
$items['evento/editar/node/%'] = array(
        'title' => t('Editar evento de agenda'),
        'description' => t('Editar evento de agenda - Contribuyente'),
        'parent'=> array('evento'),
        'page callback' => 'drupal_get_form',
        'page arguments' => array('edicion_wizard',3),
        'access callback' => TRUE,
        'type' => MENU_NORMAL_ITEM,
        'menu_name' => 'main-menu',
        'customized' => 1, // Must be 1 in order to not dispaly the link in any language
            'language'  => 'es', // language is required in order to make the item translatable
  );

So in 'page arguments' I take the 3rd value that is the wildcard. That way I take the node_id. Now, I don't need evento_load function.
In edicion_wizard function there was a mistake. I need to insert the values into a form, that was the reason of not beeing show.
function edicion_wizard($form, &$form_state, $example_id) {

    $node = node_load($example_id);
    $form_state['step_information'] = edicion_form($form, $form_state, $node);
    **$form = $form_state['step_information'];**
    //$form = $form_state['step_information'];
    $form['finish'] = array(
      '#type' => 'submit',
      '#value' => t('Terminar'),
      '#submit' => array('form_evento_wizard_submit'),
    );

   $form['next']['#validate'] = array();

    return $form;
}

Answer: First you need to define your custom path to process incoming requests to 'evento/editar/node/%node'.  This can be done by implementing hook_menu().
function evento_menu() {
  $items['evento/editar/node/%node'] = array(
      'page callback' => 'drupal_get_form',
      'page arguments' => array('evento_form', 3),
      'access arguments' => array('access content')
  );
  return $items;
}

Note where the path contains %node.  This is a wildcard loader and it will automatically run 'node_load()' for you on the node id that you display in the 3rd argument in the path. (Remember, paths start at 0)
drupal_get_form() has a required input of $form id (the function name that builds your form array) but also accepts any number of additional parameters.
What 'page arguments' => array('evento_form', 3) does, is pass the $form_id evento_form to drupal_get_form and then passes the 3rd element from the URL (the automatically loaded node object %node) as an additional argument to drupal_get_form.  To access this the additional variables you've passed to your form function you will need to use $form_state['build_info']['args']
You can now do your form manipulations with your additional variables passed using hook_menu.
If I misunderstood your question, please clarify. I'll try to update my answer accordingly.
Answer: That's what Devel is for. Install it, enable it, maybe configure permissions. And then let Devel print out the values you need. Like that:
MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  dpm($form_id, 'FORM ID');
}

Let's say the dpm($form_id) returned 'evento_node_form' then you'ld go on like that (and always let Devel print out the values you want):
MYMODULE_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'evento_node_form') {
    dpm($form, 'FORM');
    dpm($form_state, 'FORM STATE');

    // do your custom stuff here
    dpm($node->field_municipio_simple, 'MY FIELD');
  }
}

And don't forget to constantly clear cache when developing.
Comment: You're spot on @koivo. dpm() and dd() are absolutely awesome. :)
Comment: I don't understand what is $form_id for. And also, in MYMODULE_form_alter how do you know that $node has that fields? I mean, you don't have declare that variable anywhere.
Comment: When you `dpm($form)` you will know. Everythings in there, all the fields. Simply create a very fundamental custom module with only my first function in it. So you get the form id. Then you change the function to look like my second function and replace `'evento_node_form'` with the id you got from the `dpm($form_id)` and then you let `dpm($form)` return you the whole node edit form with all its fields. Write these lines in a module, activate it, try to add a node, and you'll see a clickable object on top of the page. Click on it to open it and see the magic :D

Edit a node into a custom form


Found a conflicting setters with name: setWallpaper

Question: I'm Trying to remove value from one database and put it in another but the app crashes every time this is executed and i keep getting this error.
code:
 firebaseDatabase3= FirebaseDatabase.getInstance().getReference().child("User Ordered").child(PID);
    firebaseDatabase3.keepSynced(true);

    firebaseDatabase4= FirebaseDatabase.getInstance().getReference().child("Order Ready").child(PID);
    firebaseDatabase4.keepSynced(true);

    firebaseDatabase5= FirebaseDatabase.getInstance().getReference().child("User Order Ready").child(PID);
    firebaseDatabase5.keepSynced(true);

 void run1() {

    firebaseDatabase4.addListenerForSingleValueEvent(new ValueEventListener() {
        @Override
        public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
            if(dataSnapshot.hasChildren()){

                firebaseDatabase3.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {

                        firebaseDatabase5.child(ID).setValue(firebaseDatabase3);
                        run3();

                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });

            }else{

                firebaseDatabase3.addListenerForSingleValueEvent(new ValueEventListener() {
                    @Override
                    public void onDataChange(@NonNull DataSnapshot dataSnapshot) {
                        firebaseDatabase5.child(ID).setValue(firebaseDatabase3);
                        firebaseDatabase3.removeValue();
                        run3();
                    }

                    @Override
                    public void onCancelled(@NonNull DatabaseError databaseError) {

                    }
                });

            }
        }

        @Override
        public void onCancelled(@NonNull DatabaseError databaseError) {

        }
    });

}

error
com.google.firebase.database.DatabaseException: Found a conflicting setters with name: setWallpaper (conflicts with setWallpaper defined on android.content.ContextWrapper)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.<init>(com.google.firebase:firebase-database@@19.3.0:521)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.loadOrCreateBeanMapperForClass(com.google.firebase:firebase-database@@19.3.0:329)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(com.google.firebase:firebase-database@@19.3.0:166)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(com.google.firebase:firebase-database@@19.3.0:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(com.google.firebase:firebase-database@@19.3.0:675)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(com.google.firebase:firebase-database@@19.3.0:167)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(com.google.firebase:firebase-database@@19.3.0:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(com.google.firebase:firebase-database@@19.3.0:675)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(com.google.firebase:firebase-database@@19.3.0:167)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(com.google.firebase:firebase-database@@19.3.0:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(com.google.firebase:firebase-database@@19.3.0:675)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(com.google.firebase:firebase-database@@19.3.0:167)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(com.google.firebase:firebase-database@@19.3.0:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(com.google.firebase:firebase-database@@19.3.0:675)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(com.google.firebase:firebase-database@@19.3.0:167)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.access$200(com.google.firebase:firebase-database@@19.3.0:47)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper$BeanMapper.serialize(com.google.firebase:firebase-database@@19.3.0:675)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.serialize(com.google.firebase:firebase-database@@19.3.0:167)
        at com.google.firebase.database.core.utilities.encoding.CustomClassMapper.convertToPlainJavaTypes(com.google.firebase:firebase-database@@19.3.0:60)
        at com.google.firebase.database.DatabaseReference.setValueInternal(com.google.firebase:firebase-database@@19.3.0:282)
        at com.google.firebase.database.DatabaseReference.setValue(com.google.firebase:firebase-database@@19.3.0:159)
        at com.example.shopkeeperapp.UserOrders$7$1.onDataChange(UserOrders.java:241)
        at com.google.firebase.database.Query$1.onDataChange(com.google.firebase:firebase-database@@19.3.0:179)
        at com.google.firebase.database.core.ValueEventRegistration.fireEvent(com.google.firebase:firebase-database@@19.3.0:75)
        at com.google.firebase.database.core.view.DataEvent.fire(com.google.firebase:firebase-database@@19.3.0:63)
        at com.google.firebase.database.core.view.EventRaiser$1.run(com.google.firebase:firebase-database@@19.3.0:55)
        at android.os.Handler.handleCallback(Handler.java:883)
        at android.os.Handler.dispatchMessage(Handler.java:100)
        at android.os.Looper.loop(Looper.java:214)

Answer: Java objects that you want to write to/read from the Firebase database must follow JavaBean conventions for property naming, and can only contain types that can be serialized to/from JSON.
In your case you're trying to write a android.content.ContextWrapper object, which does not meet these requirements. This happens from one of these lines:
firebaseDatabase5.child(ID).setValue(firebaseDatabase3);

The firebaseDatabase3 in here is a DatabaseReference, which does not meet the requirements.

It seems like you want to write the value that you read from one location to another location, in which case you need to get that value from the DataSnapshot instead of the DatabaseReference:
firebaseDatabase5.child(ID).setValue(dataSnapshot.getValue());

Answer: Make sure your POJO follows the coding STYLE STANDARDS for attributes, methods, and constants; put TRANSIENT on everything inside the POJO that shouldn't be SERIALIZED; the Attributes in Firebase must be EXACTLY the same as in POJO; DO NOT USE, for example: myAtributteURI or executeMyAtributteURI(), but myAtributteUri and executeMyAtributteUri(). Remember that it will run in Debug, but it will bug in the minified, obfuscated version. Therefore, follow the Proguard rules specific to FIREBASE. In this link:
https://firebase.google.com/docs/database/android/start#proguard


Desenhar triângulos com OpenGL ES 2.0

Question: Estou aprendendo OpenGL ES 2.0 para Android, e após certa familiarização com a ordem da programação estou tentando desenhar 2 triângulos na tela, a partir de 2 objetos diferente. É algo muito simples, mas não está dando certo, apenas meu "triangle2" é desenhado na tela.
Poderiam em ajudar?
Classe 1
public class MainActivity extends Activity {

GLSurfaceView myGLSurfaceView;

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

    myGLSurfaceView = new GLSurfaceView(this);
    myGLSurfaceView.setEGLContextClientVersion(2);
    myGLSurfaceView.setRenderer(new RendererClass());

    setContentView(myGLSurfaceView);

}

}

Classe 2 - Triângulo 1
public class ObjectTriangle {

int BYTES_PER_FLOAT = 4;
int shaderProgram;
FloatBuffer vertexInBuffer;

public ObjectTriangle(){

    float[] vertexArray = {

            0.0f,  0.5f, 1.0f, 0.0f, 0.0f,
            0.0f, -0.5f, 0.0f, 1.0f, 0.0f,
            0.5f,  0.0f, 0.0f, 0.0f, 1.0f

    };

    vertexInBuffer = ByteBuffer.allocateDirect(vertexArray.length*BYTES_PER_FLOAT)
                                           .order(ByteOrder.nativeOrder())
                                           .asFloatBuffer()
                                           .put(vertexArray);

}

public void inicializeObjectShaders(){

    String vertexShaderCode = "attribute vec4 a_Position;"
                            + "attribute vec4 a_Color;"
                            + "varying vec4 v_Color;"

                            + "void main(){"
                            +     "gl_Position = a_Position;"
                            +     "v_Color = a_Color;"
                            + "}";

    String fragmentShaderCode = "precision mediump float;"
                              + "varying vec4 v_Color;"

                              + "void main(){"
                              +     "gl_FragColor = v_Color;"
                              + "}";

    int vertexShaderID = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
    int fragmentShaderID = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);

    GLES20.glShaderSource(vertexShaderID, vertexShaderCode);
    GLES20.glShaderSource(fragmentShaderID, fragmentShaderCode);

    GLES20.glCompileShader(vertexShaderID);
    GLES20.glCompileShader(fragmentShaderID);

    shaderProgram = GLES20.glCreateProgram();

    GLES20.glAttachShader(shaderProgram, vertexShaderID);
    GLES20.glAttachShader(shaderProgram, fragmentShaderID);

    GLES20.glLinkProgram(shaderProgram);

}

public void setVertexAttribPointer(){

    int aPositionLocation = glGetAttribLocation(shaderProgram, "a_Position");
    int aColorLocation = glGetAttribLocation(shaderProgram, "a_Color");

    vertexInBuffer.position(0);
    glVertexAttribPointer(aPositionLocation, 2, GL_FLOAT, false, (2+3)*BYTES_PER_FLOAT, vertexInBuffer);
    glEnableVertexAttribArray(aPositionLocation);

    vertexInBuffer.position(2);
    glVertexAttribPointer(aColorLocation, 3, GL_FLOAT, false, (2+3)*BYTES_PER_FLOAT, vertexInBuffer);
    glEnableVertexAttribArray(aColorLocation);

}

public void useProgram(){
    GLES20.glUseProgram(shaderProgram);
}

public void draw(){
    glDrawArrays(GL_TRIANGLES, 0, 3);
}

}

Classe 3 - Triângulo 2 (99% igual o triângulo1, só muda o local de 1 vértice)
public class ObjectTriangle2 {

int BYTES_PER_FLOAT = 4;
int shaderProgram;
FloatBuffer vertexInBuffer;

public ObjectTriangle2(){

    float[] vertexArray = {

            0.0f,  0.5f, 1.0f, 0.0f, 0.0f,
           -0.5f,  0.0f, 0.0f, 1.0f, 0.0f,
            0.0f, -0.5f, 0.0f, 0.0f, 1.0f

    };

    vertexInBuffer = ByteBuffer.allocateDirect(vertexArray.length*BYTES_PER_FLOAT)
                                           .order(ByteOrder.nativeOrder())
                                           .asFloatBuffer()
                                           .put(vertexArray);

}

public void inicializeObjectShaders(){

    String vertexShaderCode = "attribute vec4 a_Position;"
                            + "attribute vec4 a_Color;"
                            + "varying vec4 v_Color;"

                            + "void main(){"
                            +     "gl_Position = a_Position;"
                            +     "v_Color = a_Color;"
                            + "}";

    String fragmentShaderCode = "precision mediump float;"
                              + "varying vec4 v_Color;"

                              + "void main(){"
                              +     "gl_FragColor = v_Color;"
                              + "}";

    int vertexShaderID = GLES20.glCreateShader(GLES20.GL_VERTEX_SHADER);
    int fragmentShaderID = GLES20.glCreateShader(GLES20.GL_FRAGMENT_SHADER);

    GLES20.glShaderSource(vertexShaderID, vertexShaderCode);
    GLES20.glShaderSource(fragmentShaderID, fragmentShaderCode);

    GLES20.glCompileShader(vertexShaderID);
    GLES20.glCompileShader(fragmentShaderID);

    shaderProgram = GLES20.glCreateProgram();

    GLES20.glAttachShader(shaderProgram, vertexShaderID);
    GLES20.glAttachShader(shaderProgram, fragmentShaderID);

    GLES20.glLinkProgram(shaderProgram);

}

public void setVertexAttribPointer(){

    int aPositionLocation = glGetAttribLocation(shaderProgram, "a_Position");
    int aColorLocation = glGetAttribLocation(shaderProgram, "a_Color");

    vertexInBuffer.position(0);
    glVertexAttribPointer(aPositionLocation, 2, GL_FLOAT, false, (2+3)*BYTES_PER_FLOAT, vertexInBuffer);
    glEnableVertexAttribArray(aPositionLocation);

    vertexInBuffer.position(2);
    glVertexAttribPointer(aColorLocation, 3, GL_FLOAT, false, (2+3)*BYTES_PER_FLOAT, vertexInBuffer);
    glEnableVertexAttribArray(aColorLocation);

}

public void useProgram(){
    GLES20.glUseProgram(shaderProgram);
}

public void draw(){
    glDrawArrays(GL_TRIANGLES, 0, 3);
}

}

Classe 4 - O Renderer
public class RendererClass implements Renderer {

ObjectTriangle triangle;
ObjectTriangle2 triangle2;

@Override
public void onSurfaceCreated(GL10 arg0, EGLConfig config) {

    GLES20.glClearColor(0.0f, 0.5f, 1.0f, 1.0f);

    triangle = new ObjectTriangle();
    triangle.inicializeObjectShaders();
    triangle.setVertexAttribPointer();

    triangle2 = new ObjectTriangle2();
    triangle2.inicializeObjectShaders();
    triangle2.setVertexAttribPointer();

}

@Override
public void onSurfaceChanged(GL10 arg0, int width, int height) {

    glViewport(0, 0, width, height);

}

@Override
public void onDrawFrame(GL10 glUnused) {

    GLES20.glClear(GLES20.GL_COLOR_BUFFER_BIT);

    triangle.useProgram();
    triangle.draw();

    triangle2.useProgram();
    triangle2.draw();

}

}

Answer: De acordo com seu código, você cria dois programas exatamente iguais, um para cada objeto. O que não é necessário, e aliás, consome recursos extras desnecessariamente.
É possível utilizar o mesmo programa para desenhar quantos objetos forem necessários, apenas chamando os devidos
GLES20.glVertexAttribPointer(...);

antes das chamadas
GLES20.glDrawXXX(...);

Mesmo que você utilize dois ou três programas diferentes, você deve chamar os glVertexAttribPointer antes dos glDrawXXX, pois a informação de vértices não fica armazenada junto com o programa, conforme essa pessoa já respondeu no SO: https://stackoverflow.com/questions/18645148/what-is-the-scope-of-glvertexattribpointer-and-glenablevertexattribarray
Como você só altera o programa, e executa dois glDrawArrays, as duas chamadas ao método glDrawArrays estão efetivamente desenhando a mesma coisa na tela duas vezes, utilizando a última coisa que foi atribuída através do glVertexAttribPointer, que no seu caso, foram as informações do triângulo 2.
Outro detalhe é a forma com que você está utilizando o stride. Você está utilizando (2+3)*BYTES_PER_FLOAT, o que não é verdade. O stride deve ser a quantidade de bytes entre elementos consecutivos, conforme a documentação do OpenGL diz: glVertexAttribPointer.
Se você só tivesse coordenadas X, Y, X, Y, X, Y... seu stride seria 0. Como você tem dados diferentes intercalados, seu stride não será 0, mas também não será (2+3)*BYTES_PER_FLOAT.
Pelo que pude entender, seus dados estão da seguinte forma:
X, Y, R, G, B,
X, Y, R, G, B,
X, Y, R, G, B, ...
Assim, para os dados de coordenadas, existem 3 floats entre cada par de coordenadas: o stride para aPositionLocation deveria ser 3*BYTES_PER_FLOAT.
Já para os dados das cores, existem 2 floats entre cada trio de cores: o stride para aColorLocation deveria ser 2*BYTES_PER_FLOAT.
Só mais um detalhe, por questão de desempenho, se possível, é melhor criar VAO's, e utilizá-los, em vez de ficar passando seu vetor criado em Java toda vez que precisar desenhar (isso consome processamento desnecessariamente).
Assim, na hora de inicializar o objeto, basta fazer:
int[] buf = new int[1];
//cria um buffer, e armazena seu id em buf[0]
GLES20.glGenBuffers(1, buf, 0);

//armazena o id do buffer em uma variável, para não precisar utilizar um array sempre
int bufId = buf[0];

//- Supondo que vertices seja um vetor float[] com as informações dos meus vértices
//- Se você já tivesse um Buffer, a chamada FloatBuffer.wrap é desnecessária
//- O * BYTES_PER_FLOAT é porque glBufferData precisa do tamanho em bytes, e não em elementos
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER,
                    bufId);
GLES20.glBufferData(GLES20.GL_ARRAY_BUFFER,
                    vertices.length * BYTES_PER_FLOAT,
                    FloatBuffer.wrap(vertices),
                    GLES20.GL_STATIC_DRAW);

Para que, na hora de desenhar, seja preciso fazer apenas isto, em vez de passar o vetor inteiro de novo:
GLES20.glBindBuffer(GLES20.GL_ARRAY_BUFFER, bufId);
GLES20.glVertexAttribPointer(...);
GLES20.glDrawXXX(...);

Desenhar triângulos com OpenGL ES 2.0


Qual é maneira mais performática de agrupar os dados de um array PHP?

Question: Eu tenho um array que foi gerado pelo Database Query Builder do Laravel 5.1.x.
array:96 [▼
  0 => {#1256 ▼
    +"customer_id": 58
    +"city": "Rio de Janeiro"
    +"program_id": 3
    +"program": "PROGRAMA XPTO"
    +"subregion": "SUB-REGIÃO UM"
    +"mr_name": "2015/02"
    +"info_1": 8
    +"info_2": 9
    +"info_3": 239
    +"info_4": 10
    +"info_5": 295
    +"info_6": "12.3430962343096"
  }
  1 => {#1255 ▼
    +"customer_id": 58
    +"city": "Rio de Janeiro"
    +"program_id": 3
    +"program": "PROGRAMA XPTO"
    +"subregion": "SUB-REGIÃO UM"
    +"mr_name": "2015/03"
    +"info_1": 8
    +"info_2": 9
    +"info_3": 239
    +"info_4": 21
    +"info_5": 377
    +"info_6": "7.51145646543136"
  }
  2 => {#1254 ▼
    +"customer_id": 58
    +"city": "Rio de Janeiro"
    +"program_id": 3
    +"program": "PROGRAMA XPTO"
    +"subregion": "SUB-REGIÃO UM"
    +"mr_name": "2015/04"
    +"info_1": 8
    +"info_2": 9
    +"info_3": 239
    +"info_4": 19
    +"info_5": 607
    +"info_6": "13.3670997577626"
  }
  ...
]

Meu problema => Eu preciso agrupar a informação deste array da seguinte forma:
array: [▼
    "customers" => { ▼
        +"Rio de Janeiro": array [▼
            +"programs": array [▼
                "PROGRAMA XPTO": array [▼
                    +"subregions": array [▼
                        "SUB-REGIÃO UM": array [▼
                            "months": array [▼
                                "2015/02": array [],
                                "2015/03": array [],
                                "2015/04": array [],
                                "2015/05": array [],
                                "2015/06": array [],
                                "2015/07": array [],
                                ...
                            ]
                        ]
                    ]
                ]
            ]
        ]
    ]
  ...
]

Usando PHP puro e iterando cada valor do array, eu tive um aumento de 5 a 10 segundos na execução/renderização do método (código abaixo):
if (!empty($result)) {
    $city = $result[0]->city;
    $program = null;
    $subregion = null;
    $school = null;
    $class = null;

    $data['customers'] = [];

    foreach ($result as $r => $row) {
        if (isset($data[$row->city])) {
            continue;
        }

        $city = $row->city;
        $data['customers'][$city] = [];
        $data['customers'][$city]['customer_id'] = $row->customer_id;

        foreach ($result as $pid => $programs) {
            if ($city == $programs->city) {
                if (isset($data[$city]['programs'][$programs->program])) {
                    continue;
                }

                $program = $programs->program;

                $data['customers'][$city]['programs'][$program] = [
                    'program_id' => $programs->program_id,
                    'total_escolas' => false,
                    'total_turmas' => false,
                    'students' => false,
                    'subregions' => []
                ];

                foreach ($result as $subId => $subregions) {
                    if (($city == $subregions->city)
                        and ($program == $subregions->program)
                    ) {
                        $subregion = $subregions->subregion;
                        $data['customers'][$city]['programs'][$program]['subregions'][$subregions->subregion] = [
                            'months' => []
                        ];

                        foreach ($result as $mId => $months) {
                            if (($city == $months->city)
                                and ($program == $months->program)
                                and ($subregion == $months->subregion)
                                and !empty($data['customers'][$city]['programs'][$program]['subregions'][$subregion]['months'][$months->mr_name])
                            ) {
                                $mr_name = $months->mr_name;
                                $data['customers'][$city]['programs'][$program]['subregions'][$subregion]['months'][$mr_name] = [
                                    'info_1' => $months->info_1,
                                    'info_2' => $months->info_2,
                                    'info_3' => $months->info_3,
                                    'info_4' => $months->info_4,
                                    'info_5' => $months->info_5,
                                    'info_6' => $months->info_6
                                ];
                            }
                        }
                    }
                }
            }
        }
    }
}

Obs.: minha query é executada em 137ms e a execução total do método em média 8 segundos.

Sendo assim

O que estou fazendo errado? Onde está o gargalo?
Existe uma outra maneira de agrupar tais dados?

Se precisarem de mais informações me avisem.
Comment: Só query não é suficiente, poste o código do query builder.
Comment: O query builder e não é o problema. Ele retorna o primeiro array em 137ms. O foco da minha dúvida é como agrupar o array. De qualquer forma agradeço.
Answer: Resolvido.
O principal problema foi um erro de sintaxe mesmo. Uma comparação incorreta.
Em alguns locais eu esqueci de adicionar o index ['customers'] no array:
foreach ($result as $r => $row) {
    // ERRADO - if (isset($data['customers'][$row->city])) {
    if (isset($data['customers'][$row->city])) {
        continue;
    }

    ...

    foreach ($result as $pid => $programs) {
        if ($city == $programs->city) {
            // ERRADO - if (isset($data[$city]['programs'][$programs->program])) {
            if (isset($data['customers'][$city]['programs'][$programs->program])) {

Desde já agradeço a ajuda de todos.


Get Proper XPath for SelectNodes

Question: I just started using HtmlAgilityPack to scrape some text from websites. I have experimented and found that some websites are easier than others in regards to getting the proper XPath when using the SelectNodes method. I believe I am doing something wrong but can't figure it out.
For example when exploring the DOM in Google Chrome, I am able to copy the XPath: //*[@id="page"]/span/table[7]/tbody/tr[1]/td/span[2]/a then I would do something like..
var search = doc.DocumentNode.SelectNodes("//[@id=\"page\"]//span//table//tr//td//span//a"
When using the search in a foreach loop I get a null reference error and sure enough the debugger says search is null. So I am assuming the XPath is wrong..(or I am doing something else totally wrong) So my question is how exactly do I get the proper XPath for HtmlAgilityPack to find these nodes?
Comment: I think I was able to figure it out.. The xpath was contained in an iframe.
Comment: Be aware that you can use extensions that support css selectors, such as `ScrapySharp`, along with `HtmlAgilityPack`, and you will be able to use css instead of xpath, if that makes it easier for you (for me it does, since I am already familiar with css but not with xpath). In addition, `AngleSharp` is a parser like `HtmlAgilityPack` but provides built in support for css selectors, with no need for other packages.
Comment: @Veverke I will check out your suggestions. Thank you sir!
Comment: @Veverke would you happen to know a library that would be able to scrape data off an iFrame on the current page? I've tested ScrapySharp and it is much easier (Thanks again) however just like HtmlAgilityPack, it does not work on direct iframe source on the page. It would only work if I scrape the iframe source url itself.
Comment: What is the site you are trying to parse ? I can take a look. However, if the iframe is loaded by javascript or loaded dynamically in the html - it will not indeed be available at request response time and thus parsing alone will not help. AngleSharp - I thought was able to process javascript before rendering the final html document - but I was not able to have it working for me yet.
Comment: @Veverke how about this link http://financials.morningstar.com/company-profile/c.action?t=AAPL&region=usa&culture=en-US .. I'm trying to get the email. But it looks like the site has some fancy js or iframe that is not allowing me to scrape anything
Answer: Following up on what you request in your last comment, the html is fully rendered only after the http get request is returns.
Several javascript calls insert blocks of html into the document.
You want the following of them: loadCompanyProfileData('ContactInfo'), which generates an http get request that looks like:
http://financials.morningstar.com/cmpind/company-profile/component.action?component=ContactInfo&t=XNAS:AAPL&region=usa&culture=en-US&cur=&_=1465809033745.
This returns the email, which you can extract with code like the following:
            HtmlWeb w = new HtmlWeb();
            var doc = w.Load("http://financials.morningstar.com/cmpind/company-profile/component.action?component=ContactInfo&t=XNAS:AAPL&region=usa&culture=en-US&cur=&_=1465809033745");
        var emails = doc.DocumentNode.CssSelect("a")
            .Where(a => a.GetAttributeValue("href")
                .StartsWith("mailto:"))
                .Select(a => a.GetAttributeValue("href")
                    .Replace("mailto:", string.Empty));

emails ends up containing 1 element, being email@example.com.
You problem is to determine what should be the "cur" parameter that the loadCompanyProfileData javascript function uses for each distinct company.
I could not locate in the code where/how is this parameter generated.
One alternative would be to execute a browser emulator (like selenium web driver port for c#) so you can execute javascript code - and run the call to loadCompanyProfileData('ContactInfo') for each company request.
But I could not get this to work as well, my web drive script execution does not look to be working.
Comment: Thank for the taking the time to interpret this for me!
Comment: Many others did the same for me here, am just (trying) to give back ;)
Comment: how were you able to get the link provided in your answer? I need to get other stuff as well but would like to try to figure it out myself. Did you get it by inspecting the element source in Chrome or Firefox? I was able to get "financials.morningstar.com/cmpind/company-profile/component.action?component="+component+"&t=XNAS:AAPL&region=usa&culture=en-US&cur="
Comment: Mouse right-click on the page, anywhere, then select View Source Code.

Get Proper XPath for SelectNodes


How do definitions work in Martin-Lof type theory?

Question: The classical viewpoint is that we can found mathematics by specifying a formal system $F$ whose theorems are precisely those of ZFC. However, since $F$ has essentially no support for the concept of a definition, we have to also make use of another system $G$ for managing all our definitions. We write proofs in the (dynamic, extensible) language of $G$, and $G$ then translates our proofs into the language of ZFC so that system $F$ can verify their validity.

Question. How do definitions work in Martin-Lof type theory? Do we still need a second formal system $G$ for managing all our
  definitions, or does Martin-Lof have some kind of innate support for
  them?
Answer: I guess that the answer to your question is no, but I also believe that a little of explaination is required.
The point is that there is no formal system which is exensible, at least not in the sense that you can throw in new constant.
At the very beginning of defining every formal system you have to specify the basic terms from which you build every other construct in the language (terms, formulas and judgments).
Once you have stated what are such constants they are fixed, if you change them you are changing the language, hence the formal system.
What we actually do in set theory is this: we consider an extension of  ZFC-language, that has more symbols than ZFC ($\subseteq$,$\cap$,$\cup$,...) and consider ZFC axioms in such extended language. The we add new axioms, the definitions, which usually have the form of equations (for terms' definitions) or of double-implications (for predicates' definitions), the purpose of this axioms is state an equivalence in the formal system that allows to substitue complex terms/formula build in the old language with simpler objects. And that's what definitions are for, allows substitution of complex terms by simpler one.
By the way it can be formally proved that every theorem of such expanded language, which is a formula in ZFC-(non extended)language can be equally proved in ZFC. So this change of formal system doesn't change the deductive power of the system. If you wonder why do we need the non extended system then? the answer is that proving meta-property of any formal system it's easier if the language has the very few primitives.
Type theories of any kind having their own languages cannot escape this fate either.
Hope this helps.
Comment: Hmm okay. This surprises me. So what does it mean, then, to "define" an inductive type?
Comment: @user18921 Definition of inductive type in a type theory works like the definition of any other type: you state a rule for the introduction of the type (one that state that the constant of language that represent the type is indeed a type) and some constructors, eliminators and computational rules. The only difference is that such rules are required to have a certain format.
Comment: Sorry I don't get it. If there *are* no definitions, how can we just "state" a bunch of rules and thereby define a new type?
Comment: Definitions **are** the rules for the type.
Comment: Anyway if you have more question I suppose it's better to go in chat :)
Comment: Maybe later, I'm actually trying to study for an exam atm


Convergence of serie in sense of distributions

Question: Let $u\in \mathscr{E}^{\prime}(-\pi,\pi)$ and define $a_{k}=\dfrac{1}{2\pi}\left\langle u,e^{-ikt}\right\rangle.$ Discuss series convergence $\displaystyle\sum a_{k}e^{ikt}$ in $\mathcal{D}^{\prime}(-\pi,\pi).$
I did an exercise that I think I can use here.
Let $(a_{k})_{k\in\mathbb{Z}}$ a sequence that satisfies $|a_{k}|\leq M |k|^{N}, k\neq 0, k \in \mathbb{Z},$ where $M,N$ be a constants. Then the series $\displaystyle \sum_{k=-\infty}^{\infty}a_{k}e^{ikt}$ converges in $\mathcal{D}^{\prime}(-\pi,\pi).$
Could someone help me please?
Answer: We have
$$|a_k| = \dfrac{1}{2\pi} |\left\langle u, e^{-ikt} \right\rangle |.$$
Since $u \in \mathcal{E}'(-\pi, \pi)$ then exits $L$ compact in $(-\pi, \pi), C>0 $ and $n \in \mathbb{Z}_{+}$ such that
$$ |\left\langle u, \varphi \right\rangle | \leq C \sum_{|\alpha| \leq n} \sup_{L} |\partial^{\alpha} \varphi |,$$ where $\varphi = e^{-ikt},$ i.e,
$$|a_k| =  \dfrac{1}{2\pi} |\left\langle u, \varphi \right\rangle | \leq  \dfrac{1}{2\pi} C \sum_{|\alpha| \leq n} \sup_{L} |k^{|\alpha|} \varphi | \leq \tilde{C} |k|^N,$$ for some $N \in \mathbb{N}.$ Using the exercise you mentioned, it follows that $\sum a_k e^{ik t }$ is convergence in $\mathcal{D}'(-\pi,\pi).$


How do I subscribe to solution and project events from a VSPackage

Question: I'm developing a language service for Visual Studio through a VSPackage. I need to update my parse data whenever files get added/removed from the solution's projects.
I want to subscribe to solution and project events.
I tried as follows, but none of these events get fired when I add/remove projects to the solution or add/remove items to projects.
DTE dte = (DTE)languageService.GetService(typeof(DTE));
if (dte == null)
    return;

((Events2)dte.Events).SolutionEvents.ProjectAdded += SolutionEvents_ProjectAdded;
((Events2)dte.Events).SolutionEvents.ProjectRemoved += SolutionEvents_ProjectRemoved;
((Events2)dte.Events).ProjectItemsEvents.ItemAdded += ProjectItemsEvents_ItemAdded;
((Events2)dte.Events).ProjectItemsEvents.ItemRemoved += ProjectItemsEvents_ItemRemoved;

What's the best way to subscribe to these events from a VSPackage?
Answer: Alternatively you could use IVsSolutionEvents3, which has much better events
[PackageRegistration( UseManagedResourcesOnly = true )]
[InstalledProductRegistration( "#110", "#112", "1.0", IconResourceID = 400 )]
// add these 2 Annotations to execute Initialize() immediately when a project is loaded
[ProvideAutoLoad( VSConstants.UICONTEXT.SolutionHasSingleProject_string )]
[ProvideAutoLoad( VSConstants.UICONTEXT.SolutionHasMultipleProjects_string )]
[Guid( GuidList.XYZ )]
public sealed class UnityProjectUpdateHandlerPackage : Package, IVsSolutionEvents3
{
    private DTE _dte;
    private IVsSolution solution = null;
    private uint _hSolutionEvents = uint.MaxValue;

    protected override void Initialize()
    {
        Trace.WriteLine( string.Format( CultureInfo.CurrentCulture, "Entering Initialize() of: {0}", this.ToString() ) );
        base.Initialize();

        this._dte = (DTE) this.GetService( typeof( DTE ) );

        AdviseSolutionEvents();
    }

    protected override void Dispose( bool disposing )
    {
        UnadviseSolutionEvents();

        base.Dispose( disposing );
    }

    private void AdviseSolutionEvents()
    {
        UnadviseSolutionEvents();

        solution = this.GetService( typeof( SVsSolution ) ) as IVsSolution;

        if ( solution != null )
        {
            solution.AdviseSolutionEvents( this, out _hSolutionEvents );
        }
    }

    private void UnadviseSolutionEvents()
    {
        if ( solution != null )
        {
            if ( _hSolutionEvents != uint.MaxValue )
            {
                solution.UnadviseSolutionEvents( _hSolutionEvents );
                _hSolutionEvents = uint.MaxValue;
            }

            solution = null;
        }
    }

    private Project[] GetProjects()
    {
        return _dte.Solution.Projects
            .Cast<Project>()
            .Select( x => ( (VSProject) x.Object ).Project )
            .ToArray();
    }

    public int OnAfterLoadProject( IVsHierarchy pStubHierarchy, IVsHierarchy pRealHierarchy )
    {
        // Do something
        return VSConstants.S_OK;
    }

    public int OnAfterOpenSolution( object pUnkReserved, int fNewSolution )
    {
        foreach ( var project in GetProjects() )
            ; // Do something

        return VSConstants.S_OK;
    }

    public int OnBeforeUnloadProject( IVsHierarchy pRealHierarchy, IVsHierarchy pStubHierarchy )
    {
        // Do something
        return VSConstants.S_OK;
    }

    public int OnAfterCloseSolution( object pUnkReserved )
    { return VSConstants.S_OK; }

    public int OnAfterClosingChildren( IVsHierarchy pHierarchy )
    { return VSConstants.S_OK; }

    public int OnAfterMergeSolution( object pUnkReserved )
    { return VSConstants.S_OK; }

    public int OnAfterOpenProject( IVsHierarchy pHierarchy, int fAdded )
    { return VSConstants.S_OK; }

    public int OnAfterOpeningChildren( IVsHierarchy pHierarchy )
    { return VSConstants.S_OK; }

    public int OnBeforeCloseProject( IVsHierarchy pHierarchy, int fRemoved )
    { return VSConstants.S_OK; }

    public int OnBeforeClosingChildren( IVsHierarchy pHierarchy )
    { return VSConstants.S_OK; }

    public int OnBeforeOpeningChildren( IVsHierarchy pHierarchy )
    { return VSConstants.S_OK; }

    public int OnBeforeCloseSolution( object pUnkReserved )
    { return VSConstants.S_OK; }

    public int OnQueryCloseProject( IVsHierarchy pHierarchy, int fRemoving, ref int pfCancel )
    { return VSConstants.S_OK; }

    public int OnQueryCloseSolution( object pUnkReserved, ref int pfCancel )
    { return VSConstants.S_OK; }

    public int OnQueryUnloadProject( IVsHierarchy pRealHierarchy, ref int pfCancel )
    { return VSConstants.S_OK; }
}

Comment: What is `_hSolutionEvents` in `Initialize()`?
Comment: You're right, updated the code! Had another thought on `_hSolutionEvents` which is needed for `UnadviseSolutionEvents` and add the new code, too. It's a shame that there is not much information out there about making plugins for the best DevTool...
Answer: DTE Events are a little weird, you need to cache the event source object (SolutionEvents and ProjectItemEvents in your case), so that COM Interop knows to keep them alive.
public class MyClass
{
    SolutionEvents solutionEvents;

    public void ConnectToEvents()
    {
        solutionEvents = ((Events2)dte.Events).SolutionEvents;
        solutionEvents.ProjectAdded += OnProjectAdded;
        // Etc
    }
}

More on this @ http://msdn.microsoft.com/en-us/library/ms165650(v=vs.80).aspx
Answer: Lets focus on ProjectAdded event (although described issue is exactly the same for the rest of the events).
The code sample you've shown attempts to register the SolutionEvents_ProjectAdded handler for the ProjectAdded event. However, the SolutionEvents object exposing the event, has lifetime scope limited to the closure of its wrapping method (you haven't shown its signature - let's call it Connect). After the control flow had left that scope, local object has already been garbage collected, so its event is never called:
Broken code:
public class Connector
{
    public void Connect()
    {
        ((Events2)dte.Events).SolutionEvents.ProjectAdded += SolutionEvents_ProjectAdded;
    }
    void SolutionEvents_ProjectAdded()
    {
        // callback is dead
    }
}

To fix that, you need to assign the SolutionEvents object to some variable, whose lifetime spans over the SolutionEvents_ProjectAdded handler - e.g. over the entire wrapping class. In the example below, the scope extends over the entire type (let's call it Connector), and ensures that the handler is accessible during the lifetime of that type:
Fixed code:
public class Connector
{
    SolutionEvents _solutionEvents;
    public void Connect()
    {
        _solutionEvents = ((Events2)dte.Events).SolutionEvents;
        _solutionEvents.ProjectAdded += SolutionEvents_ProjectAdded;
    }
    void SolutionEvents_ProjectAdded()
    {
        // callback works
    }
}

To be more precise, check this MSDN reference - Scoping Variables Appropriately in Event Handlers:

A common mistake in programming event handlers is connecting the event
  handler to an object that has been declared with a scope too limited
  for the purpose of handling the event. The object must have a life
  that spans not just over the function that connects the callback
  method as an event handler of the object, but also over the callback
  method itself where the event is actually handled. Otherwise, if the
  object is out of scope and is no longer defined in the callback
  method, the callback method is not called and the event is not handled
  as desired.


Mapping skeleton joints to create a skeleton

Question: I have been researching this for several days now with no success, looking at other questions being stack overflow being one of my sources.
I am creating a program using the Kinect for Windows which will track a user's joints and draw a skeleton on  a separate 'screen', I have already mapped the joints themselves and I'm using an image (a red dot) to demonstrate the location of the mapped joint.
My next step is to construct the skeleton itself by drawing a line from one joint to another, the issue I am having is how to draw the line...I have a tendency to overcomplicate things so I'm wondering if I am just making things difficult for myself rather than the just finding
the simplest solution.
I feel I am 99% of the way there but there is still one error I am encountering which I cannot get my head around, please find below the error message and related C# code.
"cannot convert from 'Microsoft.Kinect.SkeletonPoint' to 'System.Windows.Point"

code:
private void DrawBone (Joint jointFrom, Joint jointTo)
{
    Brush centerPointBrush;
    Pen trackedBonePen = new Pen(Brushes.White, TrackedBoneThickness);
    inferredBonePen = new Pen(Brushes.Gray, InferredBoneThickness);
    DrawingVisual visual = new DrawingVisual();
    DrawingContext context = visual.RenderOpen();

    centerPointBrush = Brushes.Red;

    if (jointFrom.TrackingState == JointTrackingState.NotTracked
        || jointTo.TrackingState == JointTrackingState.NotTracked)
    {
        return;
    }

    if (jointFrom.TrackingState == JointTrackingState.Inferred
        || jointTo.TrackingState == JointTrackingState.Inferred)
    {
        context.DrawLine(inferredBonePen,jointFrom.Position, jointTo.Position);
    }

    if (jointFrom.TrackingState == JointTrackingState.Tracked
        || jointTo.TrackingState == JointTrackingState.Tracked)
    {
        context.DrawLine(trackedBonePen, jointFrom.Position, jointTo.Position);
    }
}

The error related to the lines starting context.DrawLine, as these are the not correct arguments for a DrawLine function, I am getting an accompanying error of:
Error 4 The best overloaded method match for
'System.Windows.Media.DrawingContext.DrawLine(System.Windows.Media.Pen,
System.Windows.Point, System.Windows.Point)' has some invalid arguments

Answer: Don't reinvent the wheel. The guys from Microsoft did a great job there. Maybe this code helps you:
private void DrawBonesAndJoints(Skeleton skeleton, DrawingContext drawingContext)
        {
            // Render Torso
            this.DrawBone(skeleton, drawingContext, JointType.Head, JointType.ShoulderCenter);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderLeft);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.ShoulderRight);
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderCenter, JointType.Spine);
            this.DrawBone(skeleton, drawingContext, JointType.Spine, JointType.HipCenter);
            this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipLeft);
            this.DrawBone(skeleton, drawingContext, JointType.HipCenter, JointType.HipRight);

            // Left Arm
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderLeft, JointType.ElbowLeft);
            this.DrawBone(skeleton, drawingContext, JointType.ElbowLeft, JointType.WristLeft);
            this.DrawBone(skeleton, drawingContext, JointType.WristLeft, JointType.HandLeft);

            // Right Arm
            this.DrawBone(skeleton, drawingContext, JointType.ShoulderRight, JointType.ElbowRight);
            this.DrawBone(skeleton, drawingContext, JointType.ElbowRight, JointType.WristRight);
            this.DrawBone(skeleton, drawingContext, JointType.WristRight, JointType.HandRight);

            // Left Leg
            this.DrawBone(skeleton, drawingContext, JointType.HipLeft, JointType.KneeLeft);
            this.DrawBone(skeleton, drawingContext, JointType.KneeLeft, JointType.AnkleLeft);
            this.DrawBone(skeleton, drawingContext, JointType.AnkleLeft, JointType.FootLeft);

            // Right Leg
            this.DrawBone(skeleton, drawingContext, JointType.HipRight, JointType.KneeRight);
            this.DrawBone(skeleton, drawingContext, JointType.KneeRight, JointType.AnkleRight);
            this.DrawBone(skeleton, drawingContext, JointType.AnkleRight, JointType.FootRight);

            // Render Joints
            foreach (Joint joint in skeleton.Joints)
            {
                Brush drawBrush = null;

                if (joint.TrackingState == JointTrackingState.Tracked)
                {
                    drawBrush = this.trackedJointBrush;
                }
                else if (joint.TrackingState == JointTrackingState.Inferred)
                {
                    drawBrush = this.inferredJointBrush;
                }

                if (drawBrush != null)
                {
                    drawingContext.DrawEllipse(drawBrush, null, this.SkeletonPointToScreen(joint.Position), JointThickness, JointThickness);
                }
            }
        }

Answer: The error message says it all. Instead of using the jointFrom.Position directly you will need to create a System.Windows.Point to represent the coordinates of the jointFrom and pass that to DrawLine instead.
The same goes for jointTo…
The complication is that the skeleton position, and thus fromJoint.Position, represents a 3D coordinate whereas the point used to draw lines is a 2D coordinate. So a direct conversion is not possible. Rather you will need to project the joint position in 2D and use the projected point to draw the line.
Your other option would be to use 3D drawing in WPF rather than just drawing to a visual.
Answer: As Miky Dinescu points out, your immediate issue is the need to translate a Microsoft.Kinect.Joint.Position to a System.Windows.Point.
You likely do not care about the Z value (depth) and therefor need to normalize the X and Y to the size of you window.  Depending on how you are wanting the drawn skeleton to behave this may be as simple as always placing the JointType.Spine in the center of the window; or you may have to do additional math in order to translate where in the window the skeleton needs to appear based on where the player is in the Kinect's FOV.
Drawing a skeleton based off the Kinect's input is demonstrated in multiple examples, available from the Kinect for Windows Toolkit.  The "Skeleton Basics" and "Shape Game" examples are two that come to mind immediately.  You can also find code only at the Kinect for Windows Samples CodePlex page (these examples are coded for SDK 1.6, which will all work just fine in SDK 1.7).
Here is the MainWindow.xaml.cs for the "Skeleton Basics" examples.  Take note of the DrawBonesAndJoints' andDrawBone' functions to demonstrate what you are wanting to do.
Answer: Maybe I didn't understand correctly, but why would you want to do something that's already been done?. Here's a sample code from Kinect Developer Toolkit 1.8.
    private void DrawBone(Skeleton skeleton, DrawingContext drawingContext, JointType jointType0, JointType jointType1)
    {
        Joint joint0 = skeleton.Joints[jointType0];
        Joint joint1 = skeleton.Joints[jointType1];

        // If we can't find either of these joints, exit
        if (joint0.TrackingState == JointTrackingState.NotTracked || joint1.TrackingState == JointTrackingState.NotTracked)
        {
            return;
        }

        // Don't draw if both points are inferred
        if (joint0.TrackingState == JointTrackingState.Inferred && joint1.TrackingState == JointTrackingState.Inferred)
        {
            return;
        }

        // We assume all drawn bones are inferred unless BOTH joints are tracked
        Pen drawPen = this.inferredBonePen;

        if (joint0.TrackingState == JointTrackingState.Tracked && joint1.TrackingState == JointTrackingState.Tracked)
        {
            drawPen = this.trackedBonePen;
        }

        drawingContext.DrawLine(drawPen, this.SkeletonPointToScreen(joint0.Position), this.SkeletonPointToScreen(joint1.Position));
    }


Ajax not working inside hook_field_widget_form()

Question: How to make ajax work inside hook_field_widget_form()
    /**
      * Implements hook_field_widget_form().
     */
        function test_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
      $form_field['autocomplete'] = array(
        '#type' => 'textfield',
        '#title' => 'Tags',
        '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
        '#size' => $instance['widget']['settings']['size'],
        '#maxlength' => 1024,
        '#element_validate' => array('taxonomy_autocomplete_validate'),
        '#prefix' => '
',
        '#suffix' => '
',
      );
      if (isset($form_state['values']['autocomplete'])) {
        $form_field['autocomplete']['#value'] = 'new value';
      }

      $form_field['search_tags'] = array(
        '#type' => 'button',
        '#value' => 'Recommend Tags',
        '#ajax' => array(
          'callback' => 'call_ajax_replace_value',
          'wrapper' => 'subscribers-name',
          'method' => 'replace',
        ),
      );
      $element += $form_field;
      return $element;
    }

    function call_ajax_replace_value($form, &$form_state) {
       return $form['field_tags'][LANGUAGE_NONE][0]['autocomplete'];
    }

How do i update autocomplete textfield value on AJAX callback?
Answer: Just assign the value in callback function.
/**
 * Implements hook_field_widget_form().
 */
function test_field_widget_form($form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
  $form_field['autocomplete'] = array(
    '#type' => 'textfield',
    '#title' => 'Tags',
    '#autocomplete_path' => 'taxonomy/autocomplete' . '/' . $field['field_name'],
    '#size' => $instance['widget']['settings']['size'],
    '#maxlength' => 1024,
    '#element_validate' => array('taxonomy_autocomplete_validate'),
    '#prefix' => '
',
    '#suffix' => '
',
  );

  $form_field['search_tags'] = array(
    '#type' => 'button',
    '#value' => 'Recommend Tags',
    '#ajax' => array(
      'callback' => 'call_ajax_replace_value',
      'wrapper' => 'subscribers-name',
      'method' => 'replace',
    ),
  );
  $element += $form_field;
  return $element;
}

function call_ajax_replace_value($form, &$form_state) {
  if (isset($form_state['values']['autocomplete'])) {
    $form_field['autocomplete']['#value'] = 'new value';
  }
  return $form['field_tags'][LANGUAGE_NONE][0]['autocomplete'];
}


Web2Py insert into database error

Question: I am trying to make insert. This is my code:
db.define_table('orders',
            Field('idProduct', type = 'integer'),
            Field('quantity', type = 'integer'),
            Field('idUser', type = 'integer'),
            Field('status'),
            Field('order_date'),
            Field('product_price', type = 'integer'))

The SQL:
sql = "Insert into orders (idProduct,idUser,quantity,status,order_date,product_price) values "
sql = sql + "(" + str(idProduct) + "," + str(idUser) + "," + str(quantity) + ",'cart','" + str(order_date)+ "," + str(product_price)+"')"

and I am getting following error:
<class 'sqlite3.OperationalError'> 5 values for 6 columns

I don't understand what is wrong, because if i remove product_price, everything is working.
Thanks.
Answer: You have extra quote before the last closing bracket. Remove it and it will fix the error:
sql = sql + "(" + str(idProduct) + "," + str(idUser) + "," +
str(quantity) + ",'cart','" + str(order_date)+ "," +
str(product_price)+")"

Comment: Thanks, i did the same thing before, but my code is broken somewere and it still does not work.
Comment: Another error:  unrecognized token: "'16-5-2016 11:30,None)"
Comment: It's for the same sql statement? 16-5-2016 11:30 is started with quote, but not closed. And None is not valid sql value. It should be quoted if it is string or probably you're using some uninitialized variable. As far as it's new problem (with probably another root cause), try to open new question.

Web2Py insert into database error


sql optimize a query using the join

Question: I have a table productHistory
productHistory (id_H , id_product , name , tsInsert);

I wanna get from the table productHistory the last product in the giving period (start, end):
tsInsert must be between the start and the end.
I can do like this:
select max(id_H)
from productHistory
where tsInsert>=:start and tsInsert <=:end
group by id_product;

then select all from productHistory  where id_H in the previous selection.
This query is very heavy, is there any other solution using the right join for example?
Comment: Your statement is as good as it gets. All I can suggest to "optimize" is to add proper indexes on your tables. What DBMS are you using? Can you post a query plan?
Comment: By "very heavy" do you mean that execution time is to long?
Answer: I tried this solution:
SELECT * FROM productHistory  x

    INNER JOIN
    (
        SELECT  MAX(id_H) as maxId
        FROM productHistory
        GROUP id_product
    ) y

ON x.id_H = y.maxId
and x.TSINSERT >=:start and x.TSINSERT <=:end

Comment: You shouldn't answer your own question with an addition to your question. Please *edit* your question and add the additional information. Also try to add an execution plan and add what DBMS you are using.
Comment: but that is my solution
Comment: lol, my mistake but I doubt this returns what you need. Consider following two rows `id_h, id_product, tsInsert`: `1, 99, 01/01/2000` and `2, 99, 01/01/1990` and your `:start` being > 1990 will return **no rows**.
Comment: I can't see what's the pb with this query?
Comment: I was trying to create a Fiddle but the site seems to be down but in a nutshell: from my example, would you expect `id_h `1 to be returned when querying for `:start` > 1990 or not?
Comment: if the :end >01/01/2000, it should be returned
Comment: You solution wouldn't return that row, that was the point I was trying to make.

sql optimize a query using the join


Error "subscript out of range"

Question: I want to auto delete all VBA modules present in personal workbook, I am trying below code but this is showing an error 9 saying "subscript out of range "
Please help me to solve this error
Sub deletemodule()
    Dim vbCom As Object
    Dim i As Integer
    For i = 2 To 10
        On Error GoTo abc
        Set vbCom = Application.VBE.ActiveVBProject.VBComponents
        vbCom.Remove vbComponent:=vbCom.Item("Module" & i)
    Next
abc:
End Sub

Thanks in advance
Comment: This might be helpfull? [link](https://stackoverflow.com/questions/18518493/remove-all-vba-modules-from-excel-file)
Comment: On the Set, or the .Remove line?
Comment: Are you running an international version of Excel? The module default names differ in different versions. Verify that your modules have names following the Module*X* syntax.
Answer: Try to revert loop:
For i = 10 To 2 step -1
On Error GoTo abc
Set vbCom = Application.VBE.ActiveVBProject.VBComponents
vbCom.Remove vbComponent:=vbCom.Item("Module" & i)
Next

Comment: how can i add screen shot here pls help
Comment: I'm not suggesting to change the name but to revert loop. I guess you are trying to remove item from collection which is not there anymore. If you remove item no. 2 then there is no more item no. 10 as it was moved to position no. 9. etc...
Comment: I agree but in this situation name of the module will not be changed & will remains the same as before "module10" only position will be changed from no 10 to no 9.
Comment: there may be a solution if I could count no of modules available so then upper limit of i will be set to that no. I think so not sure ...
Comment: see the link proposed by @JvdV presenting the other answer of mine or alternative one with `.count` being similar to this answer.
Answer: This code removes all Standard & Class modules from the workbook.
Note sure what other types there will be - Chart sheets, forms, macro sheets(?)
Modules are a collection so you can step through them using a For...Each loop rather than needing to know how many or what they're called beforehand.
Public Sub DeleteAllModules()

    Dim vbcom As Object
    Dim vMod As Object

    Set vbcom = Application.VBE.ActiveVBProject.VBComponents

    For Each vMod In vbcom
        Select Case vMod.Type
            Case 1, 2 'Standard & Class modules
                vbcom.Remove vMod
            Case 100 'Sheet & ThisWorkbook modules
                'Do nothing
        End Select
    Next vMod

End Sub

Error "subscript out of range"


How to configure backup/maintanance screen for http server?

Question: Is it possible to configure in some way (ideally on dns level) such scenario:
1) when all is fine, all requests goes to www.domain.com
2) in case when www.domain.com is down, all requests immediately go to other box (other IP in different datacenter) so users will get nice "maintanace page"
I am using IIS7, but i want this to work even when server is rebooting ort not available
Answer:
1) when all is fine, all requests goes
  to www.domain.com 2) in case when
  www.domain.com is down, all requests
  immediately go to other box (other IP
  in different datacenter) so users will
  get nice "maintanace page"

No. Beacuse the web server has no say ni the IP - basically if your server isdown, yo need to dfeed a different IP via DNS. THis means a VERY short TTL which ahs other problems.
Normally people using this use a special routing setup, but this is not feasible for a small dude.
What you need is TWO servers in a NLB based cluster, then one can get out and the other gets all requests. Same data center.
Comment: Thanks for help Tom. During last 3 months I faced situaltion when whole datacenter was not accessible for couple of hours, so just reserved server + load balancing  will not help.
Answer: Not really. It's not quite possible to achieve the seamlessness you're looking for. A short DNS TTL will likely be ignored among other things. There are two other solutions, but neither is ideal:

Less load, but less seamless: Tell your users to bookmark example.com. /index.php is a PHP file that tests to see if the main server is up, in which case it redirects to www.example.com/ (your main site). Otherwise it echos the maintenance page.
More seamless, but more load: www.example.com/* requests 10.12.34.56/* (your main server), and on failure, displays the maintenance page.

Neither of these solutions are ideal! The only good solution in my opinion is using a cluster or advanced routing mechanism in a dependable network.


Add Calculated Column into DF and Plot 2 Lines

Question: I start with the dataframe below, where each row is a new trial:
    test_group   range     success
0      test        1-5         1
1      test        1-5         0
2      test        1-5         1
3      test        6-10        1
4      test        6-10        0
5      test        6-10        0
6      control     1-5         0
7      control     1-5         0
8      control     1-5         1
9      control     6-10        1
10     control     6-10        1
11     control     6-10        1

I want to compute the mean success-value and group by test-group and range.
To do so, I'd write the following code:
df = df.groupby('test_group','range').success.mean()

My result looks like the following
test_group    range
test          1-5    0.66
              6-10   0.33
control       1-5    0.33
              6-10   1.00

Ideally, I want my final output to look like the following so that I can plot both test groups on the same chart, with the x-axis being each range and the y-axis being the success-rate:
 test_group   range     success-rate
0      test        1-5         0.66
1      test        1-5         0.66
2      test        1-5         0.66
3      test        6-10        0.33
4      test        6-10        0.33
5      test        6-10        0.33
6      control     1-5         0.33
7      control     1-5         0.33
8      control     1-5         0.33
9      control     6-10        1.00
10     control     6-10        1.00
11     control     6-10        1.00

Answer: you can use transform() method:
In [35]: df['success-rate'] = df.groupby(['test_group','range'])['success'].transform('mean')

In [36]: df
Out[36]:
   test_group range  success  success-rate
0        test   1-5        1      0.666667
1        test   1-5        0      0.666667
2        test   1-5        1      0.666667
3        test  6-10        1      0.333333
4        test  6-10        0      0.333333
5        test  6-10        0      0.333333
6     control   1-5        0      0.333333
7     control   1-5        0      0.333333
8     control   1-5        1      0.333333
9     control  6-10        1      1.000000
10    control  6-10        1      1.000000
11    control  6-10        1      1.000000

Groupby.transform() method applies an aggregating function to all original  rows
Comment: Thanks, @MaxU! This is what I was looking for. Can you explain a bit what's happening under the hood?


WooCommerce Conditionally add text below price on Products

Question: Trying to set a custom text message below a WooCommerce product, using the woocommerce_get_price_html filter with a conditional to ceratin products in an array - but it is applying the $addedtext variable to all products, where am I going wrong here?
add_filter( 'woocommerce_get_price_html', 'custom_price_message' );

function custom_price_message( $price ) {
 if( is_product (array( 799,796,792)) ) {
  $addedtext = '(Upfront Paid in Full Price)';
 return $price . '
' . $addedtext . '';
 }
 else {
    return $price;
 }
}

Answer:  //add meta box to each product which will take status to add text or not
function add_events_metaboxes() {
    add_meta_box('wpt_events_product', 'Add text to product', 'wpt_events_products', 'product', 'side', 'default');
}

add_action( 'add_meta_boxes', 'add_events_metaboxes' );

function wpt_events_products() {
    //checkbox to select add text or not
        echo '<input id="wp_add_text_to_woo_product" name="text_enable" type="checkbox"></input>';
}

//function will update post meta on save post button
function my_project_updated_post_meta( $post_id ) {
    update_post_meta($post_id, 'enable_text', $_POST['text_enable']);
}

add_action( 'save_post', 'my_project_updated_post_meta' );

//function will check for perticular product for which check box is set and assign text for them.
function custom_price_message( $price ) {
    $args = array('post_type' => 'product', 'nopaging' => true);
        $product_query = new WP_Query($args);
        $posts = $product_query->get_posts();
            foreach ($posts as $post) {

        $text_status = get_post_meta($post->ID,'enable_text',true);
                if($text_status == "on")  {
                    $addedtext = '(Upfront Paid in Full Price)';
                    return $price . '
' . $addedtext . '';
                    }
                else {
                           return $price;
                    }
            }
}
add_filter( 'woocommerce_get_price_html', 'custom_price_message' );

Answer: Got this from woo support - works well
add_filter( 'woocommerce_get_price_html', 'custom_price_message' );

function custom_price_message($price) {

global $post;

$product_id = $post->ID;
$my_product_array = array( 799,796,792);
if (in_array($product_id, $my_product_array)) {
    $addedtext = '(Upfront Paid in Full Price)';
    return $price . '
' . $addedtext . '';
}

else {
    return $price;
 }
}

Answer: Not only do the previous code answers fail to persist the checkbox state, they also update all prices, not just individual products. Try this code below instead:
//add meta box to each product which will take status to add text or not
function add_events_metaboxes() {
    add_meta_box('wpt_events_product', 'Add \'From only\' text to product', 'wpt_events_products', 'product', 'advanced', 'default');
}

add_action( 'add_meta_boxes', 'add_events_metaboxes' );

function wpt_events_products($post) {
    $text_status = get_post_meta( $post->ID, 'enable_text', true) ;
    //checkbox to select add text or not
    echo '<input id="wp_add_text_to_woo_product" name="text_enable" type="checkbox" '. checked('on', $text_status, false) .'></input>';

}

//function will update post meta on save post button
function my_project_updated_post_meta( $post_id ) {
    update_post_meta($post_id, 'enable_text', $_POST['text_enable']);
}

add_action( 'save_post', 'my_project_updated_post_meta' );

//function will check for perticular product for which check box is set and assign text for them.
function custom_price_message( $price, $product ) {
    $text_status = get_post_meta( $product->get_id(), 'enable_text', true) ;

    if($text_status == "on") {
        $addedtext = 'From only ';
        return '' . $addedtext . '' . $price;
    }

    return $price;

}
add_filter( 'woocommerce_get_price_html', 'custom_price_message', 10, 2 );


Aliasing/Quality issues in Media Foundation H264 hardware encoder, especially for text(aliasing and blur on text)

Question: I've been working on Streaming real-time video using hardware accelerated h.264 encoding, decoding and I've been able to make it work using Windows Media Foundation .
I've compressed the frames from RGB to NV12 format using d3d11 Video Processor and encoded to h.264 using Hardware MFT.
The Only problem I have now is that after decoding and rendering the video, aliasing and halo effect appear on the screen along with the text.
The Images down below shows my problem.
Frame before Encoding

Frame after encoding and decoding

After some research, I came across H.264/AVC 444 in which Microsoft solved this by introducing full-screen AVC 444 mode with RDP 10.
In AVC 444 mode, we can get 4:4:4 quality text with 4:2:0 hardware encoders / decoders by improving the frame throughput significantly.

Introducing the AVC 444 mode The main challenge to use AVC/H.264 as the one and only Codec in Remote Desktop scenarios is that text shows a halo effect with typical implementations of AVC/H.264. This is caused by the color conversion process that happens as part of the compression which throws away some of the chrominance information, as represented in the 4:2:0 format. To the human eye the lack of chrominance information is not as apparent with video content, however with Remote Desktop scenarios, where mostly text is used, it is something that is noticeable and users will perceive this as blurry. The AVC/H.264 standard defines the capability to use 4:4:4 format which doesn't lose the chrominance during conversion, however typically this isn't part of most AVC/H.264 hardware encoder and decoder implementations and thus provides a challenge. To show the difference between 4:4:4 and 4:2:0 please see the following image which shows easily noticeable differences:

I tried to achieve the same in Media Foundation but unable find any resource to crack that yet.
I have figured out that color conversion to NV12 is the reason behind this problem and I've been trying to solve it, I have also tried YUV 444 but unable to find a hardware MFT that supports it. I was not able to encode any other color format except NV12 using Hardware MFT
Is there any way to overcome this problem?Any help would be appreciated.
Answer:
You could use a Screen capture optimized codec:
https://learn.microsoft.com/en-us/windows/win32/medfound/usingthewindowsmediavideo9screencodec

NVIDIA supports 4:4:4 hardware assisted on a wide variety of cards:
https://developer.nvidia.com/video-encode-decode-gpu-support-matrix

Scale your screen from 1920x1080 to 3840x2160 convert to NV12 (4:2:0) compress to H.264 and do the reverse on the receiver. The upscaling and the subsequent 4:2:0 conversion should retain the full color resolution. This sounds wasteful but if it is done on hardware it should work.
Comment: Thanks for sharing. I will start to research windows media video
Answer: This is NOT an answer, rather an observation for whomever is looking into AVC444.
I am using AVC444 (hardware) (This is confirmed by looking into Windows Event Logs) and although it's pretty good for normal RDP purposes, the text is not as clear as the original (or the normal RDP encoder). I immediately noticed color aliasing in high-contrast text when I turned ON AVC444.
Here is a comparison between the original and the AVC444 encoded one.


Protractor jasmine2-html-reporterHTML verify element was clicked

Question: My jasmine-spec-reporter verifies that an element was clicked I see the check marks in the console view however in my protractor-jasmine2-html-reporter shows that the spec was skipped when it was actually clicked. How can I correct this?

I Know this has something to do with an expect statement for example this visually shows passed expect(browser.getCurrentUrl()).toEqual('https://adp.com');

However I am stomped on how to write and expect statement to show an element was clicked so that the protractor-jasmine2-html-reporter shows passed. Any Help would be appreciated. this is my code below
 it('Load WFN home page - completed', function() {
        browser.get('https://wfn-iat.adp.com/public/index.htm');
        expect(browser.getCurrentUrl()).toEqual('https://wfn-iat.adp.com/public/index.htm');
    });

    it('click admin login - completed', function () {
        var adminlogin;
         adminlogin = ($('#adminLogin'));
        browser.wait(EC.elementToBeClickable(adminlogin), 5000).then(function() {
        adminlogin.click();
          // browser.sleep(10000);
        });

Comment: it looks like I will have to go to the page after the click to verify that the link was actually click and verify and attribute on that page for the to get a pass for protractor-jasmine2-html-reporter. This actually worked this is some of the code i used.

expect(userid.getAttribute('class')).toEqual('forgotUID');

However if there is another way which out having to write some much code it would be appreciated
Answer: You can try with expect(EC.stalenessOf($('#adminLogin'),1000)).toBeTruthy(), so you check, if the Button is no longer present in the DOM.
That way the test would fail on invalid credentials, because in those case you'd probably stay on the page and show some error.
Also using .not seems an option, so something like:  expect($('#adminLogin')).not.toBePresent()


Need to calculate the percentage of distribution

Question: I have a set of numbers for a given set of attributes:
red    = 4
blue   = 0
orange = 2
purple = 1

I need to calculate the distribution percentage. Meaning, how diverse is the selection? Is it 20% diverse? Is it 100% diverse (meaning an even distribution of say 4,4,4,4)?
I'm trying to create a sexy percentage that approaches 100% the more the individual values average to the same value, and a lower value the more they get lopsided.
Has anyone done this?
Here is the PHP conversion of the below example. For some reason it's not producing 1.0 with a 4,4,4,4 example.
$arrayChoices = array(4,4,4,4);

foreach($arrayChoices as $p)
    $sum += $p;

print "sum: ".$sum."
";

$pArray = array();

foreach($arrayChoices as $rec)
{
    print "p vector value: ".$rec." ".$rec / $sum."\n
";
    array_push($pArray,$rec / $sum);
}
$total = 0;

foreach($pArray as $p)
    if($p > 0)
        $total = $total - $p*log($p,2);

print "total = $total
";

print round($total / log(count($pArray),2) *100);

Thanks in advance!
Answer: A simple, if rather naive, scheme is to sum the absolute differences between your observations and a perfectly uniform distribution
red    = abs(4 - 7/4) = 9/4
blue   = abs(0 - 7/4) = 7/4
orange = abs(2 - 7/4) = 1/4
purple = abs(1 - 7/4) = 3/4

for a total of 5.
A perfectly even spread will have a score of zero which you must map to 100%.
Assuming you have n items in c categories, a perfectly uneven spread will have a score of
(c-1)*n/c + 1*(n-n/c) = 2*(n-n/c)

which you should map to 0%. For a score d, you might use the linear transformation
100% * (1 - d / (2*(n-n/c)))

For your example this would result in
100% * (1 - 5 / (2*(7-7/4))) = 100% * (1 - 10/21) ~ 52%

Better yet (although more complicated) is the Kolmogorov–Smirnov statistic with which you can make mathematically rigorous statements about the probability that a set of observations have some given underlying probability distribution.
Comment: Thank you! This was great. I nearly had it. :)
Answer: One possibility would be to base your measure on entropy.  The uniform distribution has maximum entropy, so you could create a measure as follows:
1) Convert your vector of counts to P, a vector of proportions
    (probabilities).
2) Calculate the entropy function H(P) for your vector of
    probabilities P.
3) Calculate the entropy function H(U) for a vector of equal
    probabilities which has the same length as P. (This turns out
    to be H(U) = -log(1.0 / length(P)), so you don't actually
    need to create U as a vector.)
4) Your diversity measure would be 100 * H(P) / H(U).
Any set of equal counts yields a diversity of 100.  When I applied this to your (4, 0, 2, 1) case, the diversity was 68.94.  Any vector with all but one element having counts of 0 has diversity 0.
ADDENDUM
Now with source code!  I implemented this in Ruby.
def relative_entropy(v)
  # Sum all the values in the vector v, convert to decimal
  # so we won't have integer division below...
  sum = v.inject(:+).to_f

  # Divide each value in v by sum, store in new array p
  pvals = v.map{|value| value / sum}

  # Build a running total by calculating the entropy contribution for
  # each p.  Entropy is zero if p is zero, in which case total is unchanged.
  # Finally, scale by the entropy equivalent of all proportions being equal.
  pvals.inject(0){|total,p| p > 0 ? (total - p*Math.log2(p)) : total} / Math.log2(pvals.length)
end

# Scale these by 100 to turn into a percentage-like measure
relative_entropy([4,4,4,4])     # => 1.0
relative_entropy([4,0,2,1])     # => 0.6893917467430877
relative_entropy([16,0,0,0])    # => 0.0

Comment: I'd love to see an example in code of this technique based on the values above. Looks interesting.
Comment: @MarkLöwe There you go.
Comment: I'm having trouble converting your ruby code. Could you look at my php example above?
Comment: The division by `log2(arraylength)` is done after all the terms have been totaled, not term-by-term.
Comment: I think I finally got! Thank you brother.
Comment: It's ideal...simple...and easy to maintain. Thank you again.


RHEL8 based system has multiple kernels but module will only load in one of them

Question: As the title says I have multiple kernels on my system
4.18.0-193.19.1.el8_2.x86_64
4.18.0-240.el8.x86_64
4.18.0-372.26.1.el8_6.x86_64

Issue is I am using mpt3sas on my system and when i installed it on 4.18.0-193.19.1 it was perfect.  Now on a later kernel I am seeing that kernel does't detect that module.  I can't modinfo it or modprobe it.  But when I attempt to install it it does detect that it's already installed.  It is in the /lib/modules/4.18.0-193.19.1.el8_2.x86_64/weak-updates & /lib/modules/4.18.0-193.19.1.el8_2.x86_64/extra directories if that makes a difference.
Any ideas on what I can do?  Should I uninstall it and reinstall it on the newer kernel?  I attempted to copy the directories & .ko files but that didn't make a different it seems.
EDIT:
I attempted to remove the old version in there and install it via dnf and now it seems I have two version installed on the system.  Here is the output of modinfo mpt3sas:
 modinfo mpt3sas                                                                                PLEX
filename:       /lib/modules/4.18.0-372.26.1.el8_6.x86_64/extra/mpt3sas/mpt3sas.ko
alias:          mpt2sas
version:        32.100.00.00
license:        GPL
description:    LSI MPT Fusion SAS 3.0 Device Driver
author:         Avago Technologies <firstname.lastname@example.com>
rhelversion:    8.2
srcversion:     7C68C3E1EC928FA96966F19
alias:          pci:v00001000d000000E6sv*sd*bc*sc*i*
alias:          pci:v00001000d000000E5sv*sd*bc*sc*i*
alias:          pci:v00001000d000000B2sv*sd*bc*sc*i*
alias:          pci:v00001000d000000E2sv*sd*bc*sc*i*
alias:          pci:v00001000d000000E1sv*sd*bc*sc*i*
alias:          pci:v00001000d000000D1sv*sd*bc*sc*i*
alias:          pci:v00001000d000000ACsv*sd*bc*sc*i*
alias:          pci:v00001000d000000ABsv*sd*bc*sc*i*
alias:          pci:v00001000d000000AAsv*sd*bc*sc*i*
alias:          pci:v00001000d000000AFsv*sd*bc*sc*i*
alias:          pci:v00001000d000000AEsv*sd*bc*sc*i*
alias:          pci:v00001000d000000ADsv*sd*bc*sc*i*
alias:          pci:v00001000d000000C3sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C2sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C1sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C0sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C8sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C7sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C6sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C5sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C4sv*sd*bc*sc*i*
alias:          pci:v00001000d000000C9sv*sd*bc*sc*i*
alias:          pci:v00001000d00000095sv*sd*bc*sc*i*
alias:          pci:v00001000d00000094sv*sd*bc*sc*i*
alias:          pci:v00001000d00000091sv*sd*bc*sc*i*
alias:          pci:v00001000d00000090sv*sd*bc*sc*i*
alias:          pci:v00001000d00000097sv*sd*bc*sc*i*
alias:          pci:v00001000d00000096sv*sd*bc*sc*i*
alias:          pci:v00001000d0000007Esv*sd*bc*sc*i*
alias:          pci:v00001000d000002B1sv*sd*bc*sc*i*
alias:          pci:v00001000d000002B0sv*sd*bc*sc*i*
alias:          pci:v00001000d0000006Esv*sd*bc*sc*i*
alias:          pci:v00001000d00000087sv*sd*bc*sc*i*
alias:          pci:v00001000d00000086sv*sd*bc*sc*i*
alias:          pci:v00001000d00000085sv*sd*bc*sc*i*
alias:          pci:v00001000d00000084sv*sd*bc*sc*i*
alias:          pci:v00001000d00000083sv*sd*bc*sc*i*
alias:          pci:v00001000d00000082sv*sd*bc*sc*i*
alias:          pci:v00001000d00000081sv*sd*bc*sc*i*
alias:          pci:v00001000d00000080sv*sd*bc*sc*i*
alias:          pci:v00001000d00000065sv*sd*bc*sc*i*
alias:          pci:v00001000d00000064sv*sd*bc*sc*i*
alias:          pci:v00001000d00000077sv*sd*bc*sc*i*
alias:          pci:v00001000d00000076sv*sd*bc*sc*i*
alias:          pci:v00001000d00000074sv*sd*bc*sc*i*
alias:          pci:v00001000d00000072sv*sd*bc*sc*i*
alias:          pci:v00001000d00000070sv*sd*bc*sc*i*
depends:        scsi_transport_sas,raid_class
name:           mpt3sas
vermagic:       4.18.0-193.el8.x86_64 SMP mod_unload modversions
sig_id:         PKCS#7
signer:         ELRepo.org Secure Boot Key
sig_key:        E9:D4:71:CF:B4:FE:13:6C
sig_hashalgo:   sha256
signature:      94:52:91:50:DC:0D:4E:BF:96:69:4C:35:7C:37:99:60:49:7A:6E:E1:
                E6:6B:0F:C5:3B:C1:60:FF:81:B8:0B:60:72:26:0E:26:11:C4:8A:21:
                96:E9:2A:BF:A0:EA:60:40:2E:B4:1E:99:AB:B5:B7:A9:35:95:CC:31:
                1B:BF:72:2E:07:2C:D3:D9:F9:85:C4:94:01:C9:F4:73:A9:E9:A5:12:
                F5:65:79:B0:F5:54:E0:C5:CB:BC:1E:F5:28:5B:E1:A5:96:3B:12:7A:
                9D:E8:51:B5:D7:56:B2:7C:06:88:D2:6D:CD:69:DE:36:2D:D7:09:8F:
                79:B5:41:E6:5C:00:FD:89:E1:F6:6F:25:CC:2A:B6:AC:41:12:F7:80:
                CB:71:EE:22:4F:BF:E1:44:3A:29:5C:29:EF:76:99:63:34:47:EE:9F:
                35:63:5E:2A:EF:FD:30:5B:69:F7:F6:AD:E6:AF:0D:BD:69:D9:19:80:
                55:25:64:83:C4:41:AD:41:86:4B:CE:E5:73:61:83:F9:9E:86:7B:82:
                33:38:94:1A:D7:D3:A7:4A:A1:96:67:02:3E:7F:D5:02:2C:B3:27:10:
                AB:0F:B0:AA:A7:FD:18:5A:BC:04:8A:38:09:9A:FC:B9:35:54:5E:89:
                9E:AC:42:A7:90:DA:74:7E:05:D0:B3:79:37:7F:3E:16:82:4A:F8:DF:
                BD:CA:58:6D:80:15:1C:14:B0:38:7B:4D:48:6D:D9:EE:3C:AD:CF:DA:
                79:71:ED:2B:3A:5F:0F:7A:D8:BB:68:3B:27:6F:58:AA:A9:B1:E3:A8:
                C7:65:2A:56:1F:C4:16:3F:EE:B8:FE:27:85:5F:45:3B:53:73:1F:BC:
                9F:F5:88:78:50:87:30:33:25:30:D4:2D:62:45:CC:55:FF:15:C9:52:
                CF:1E:2F:30:6B:9D:39:20:6F:51:5C:F1:F4:33:16:03:ED:AB:7E:DF:
                EA:5B:E1:AB:A2:4E:CF:68:DF:94:F7:E3:E8:63:7F:AE:63:47:11:61:
                2C:9F:7F:95:06:D1:22:6C:BA:64:28:BF:D2:9A:66:E1:F7:59:68:33:
                A5:BE:14:DE:E8:DD:60:E5:D4:3F:34:15:F8:94:6B:4E:2D:1F:27:9E:
                5E:CF:5A:FD:45:70:77:CE:8E:D1:C9:7E:57:08:3F:73:F7:6A:18:86:
                2F:6E:8F:08:D1:FF:77:CC:50:FF:23:D6:D9:79:84:96:EE:68:D3:7F:
                BF:2D:D4:91:FE:5B:2E:2A:BA:E6:AC:10:E6:28:9A:AC:90:9F:87:43:
                BA:72:20:BF:8B:67:D9:84:1C:E6:A1:48:A4:1B:F1:85:46:7C:B4:44:
                43:71:1B:AB:5F:0B:65:02:FA:FC:4C:90
parm:           logging_level: bits for enabling additional logging info (default=0)
parm:           max_sectors:max sectors, range 64 to 32767  default=32767 (ushort)
parm:           missing_delay: device missing delay , io missing delay (array of int)
parm:           max_lun: max lun, default=16895  (ullong)
parm:           hbas_to_enumerate: 0 - enumerates both SAS 2.0 & SAS 3.0 generation HBAs
                  1 - enumerates only SAS 2.0 generation HBAs
                  2 - enumerates only SAS 3.0 generation HBAs (default=0) (ushort)
parm:           diag_buffer_enable: post diag buffers (TRACE=1/SNAPSHOT=2/EXTENDED=4/default=0) (int)
parm:           disable_discovery: disable discovery  (int)
parm:           prot_mask: host protection capabilities mask, def=7  (int)
parm:           enable_sdev_max_qd:Enable sdev max qd as can_queue, def=disabled(0) (bool)
parm:           max_queue_depth: max controller queue depth  (int)
parm:           max_sgl_entries: max sg entries  (int)
parm:           msix_disable: disable msix routed interrupts (default=0) (int)
parm:           smp_affinity_enable:SMP affinity feature enable/disable Default: enable(1) (int)
parm:           max_msix_vectors: max msix vectors (int)
parm:           irqpoll_weight:irq poll weight (default= one fourth of HBA queue depth) (int)
parm:           mpt3sas_fwfault_debug: enable detection of firmware fault and halt firmware - (default=0)
parm:           perf_mode:Performance mode (only for Aero/Sea Generation), options:
                0 - balanced: high iops mode is enabled &
                interrupt coalescing is enabled only on high iops queues,
                1 - iops: high iops mode is disabled &
                interrupt coalescing is enabled on all queues,
                2 - latency: high iops mode is disabled &
                interrupt coalescing is enabled on all queues with timeout value 0xA,
                default - default perf_mode is 'balanced' (int)
 root ~    $ modprobe mpt3sas                                                                                PLEX
modprobe: ERROR: could not insert 'mpt3sas': Unknown symbol in module, or unknown parameter (see dmesg)

Comment: I was able to fix this by following these instructions:

https://www.networkshinobi.com/centos-8-with-lsi-sas2008/
Answer: Kernel modules are specific to kernel versions and a new kernel requires that the module gets updated/recompiled as well.
When the original provider hasn't built the required new binary RPM package yet, install the source package and build your own binary RPM package that matches your new kernel i.e.
See for example https://www.ibm.com/docs/pt/ess-p8/5.1.0?topic=guide-instructions-updating-mpt3sas-driver

Download the SRPM
Rebuild the RPMs for the running kernel.
rpmbuild --rebuild SRC_RPM_LOCATION/mpt3sas-13.100.00.00-1.el7_2.src.rpm

This command creates two RPMs.
Unload the current mpt3sas driver.
rmmod mpt3sas

Install the RPMs.
rpm -Uvh /root/rpmbuild/RPMS/ppc64le/kmod-mpt3sas*rpm
rpm -Uvh /root/rpmbuild/RPMS/ppc64le/mpt3sas*rpm

Load the updated modules.
modprobe mpt3sas

Verify that the module is loaded.
modinfo mpt3sas

Comment: Attempted to rebuild with this command but I only have the kmod driver, not the mpt3sas driver

`rpmbuild --rebuild kmod-mpt3sas-28.100.00.00-3.el8_2.elrepo.x86_64.rpm`

`Installing kmod-mpt3sas-28.100.00.00-3.el8_2.elrepo.x86_64.rpm`

`warning: kmod-mpt3sas-28.100.00.00-3.el8_2.elrepo.x86_64.rpm: Header V4 DSA/SHA1 Signature, key ID baadae52: NOKEY`

`error: source package expected, binary found`

`error: kmod-mpt3sas-28.100.00.00-3.el8_2.elrepo.x86_64.rpm cannot be installed`


jquery draggable/droppable

Question: Any help with the following will be much appreciated. I need to have a picture outside a droppable box. The user should be able to drag the picture to the box and once the picture is inside the box, the user should still be able to drag it, but only inside of the box.
Thank you in advance for any pointers.
Comment: Can you post the code you have so far that just supports the dragging it inside a droppable box? If you'd like help doing that first half, let us know and we can help you out. But if you post that half of your code, then we can append what is necessary to support the subsequent contained draggable. You can use [jsFiddle](http://jsfiddle.net/) to share with us. Welcome to SO!
Comment: Thank you. Here is an draggable/droppable example from the web that I have modified. http://jsfiddle.net/sPdwm/
Comment: I added $( "#draggable" ).draggable({containment:"#droppable"}); to the drop: function and was able to contain the movement of the picture, I updated the code and seems to work ok.
Comment: here is the updated code http://jsfiddle.net/sPdwm/1/
Comment: Ok, I added the code in your example as the answer (for future reference).
Answer: This can be done by adding the "containment" option to the draggable object in the droppable object's "drop" callback.  For example:
<code>$(function() {
    $( "#draggable" ).draggable();
    $( "#droppable" ).droppable({
        drop: function( event, ui ) {
            $( this )
                .addClass( "ui-state-highlight" )
                .find( "p" )
                .html( "Dropped!" );
            $( "#draggable" ).draggable({containment:"#droppable"});
        }  });
});
</code>
In the option above, once the item is actually dropped, the drop callback fires and causes the draggable item to be constrained to the item in the "containment" option.

jquery draggable/droppable