text:
Q: Need Help on Java Programmin HandlingException so i just got this Homework

Make a Java Program using GUI(JpanelForm) with implementation of
  handling Exception ArithmeticException, NegativeArraySizeException,
  ArrayIndexOutofBOundsException, and NullPointerException

/**
 *
 * @author Inoyama
 */
public class OLCHandlingException extends javax.swing.JFrame {

    /**
     * Creates new form OLCHandlingException
     */
    public OLCHandlingException() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jTextField1 = new javax.swing.JTextField();
        jTextField2 = new javax.swing.JTextField();
        jTextField3 = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jLabel3 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jTextField1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField1ActionPerformed(evt);
            }
        });

        jTextField2.setText(" ");
        jTextField2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField2ActionPerformed(evt);
            }
        });

        jTextField3.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextField3ActionPerformed(evt);
            }
        });

        jLabel1.setText("Bilangan 1");

        jLabel2.setText("Bilangan 2");

        jLabel3.setText("Hasil");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jLabel2)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(8, 8, 8)
                        .addComponent(jLabel3)))
                .addGap(27, 27, 27)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                    .addComponent(jTextField3)
                    .addComponent(jTextField1)
                    .addComponent(jTextField2, javax.swing.GroupLayout.DEFAULT_SIZE, 106, Short.MAX_VALUE))
                .addContainerGap(208, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(65, 65, 65)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jTextField2, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel2))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextField3, javax.swing.GroupLayout.PREFERRED_SIZE, 56, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel3))
                .addContainerGap(117, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    private void jTextField1ActionPerformed(java.awt.event.ActionEvent evt) {

// TODO add your handling code here:
      String A_String;

      A_String=jTextField1.getText();
      int A = Integer.parseInt(A_String);
      jTextField1.setText(""+A);
    }

    private void jTextField2ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
         String B_String;
         String C_String;
         C_String = jTextField1.getText();
         int C = Integer.parseInt(C_String);

         B_String=jTextField2.getText();
         int B = Integer.parseInt(B_String);

         try{
             float total;
             total = C * B;
             jTextField3.setText("Result is "+total);
         }
         catch(NegativeArraySizeException e){
              System.out.println("Failed");
         }
    }

    private void jTextField3ActionPerformed(java.awt.event.ActionEvent evt) {
        // TODO add your handling code here:
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(OLCHandlingException.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(OLCHandlingException.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(OLCHandlingException.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(OLCHandlingException.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new OLCHandlingException().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JTextField jTextField1;
    private javax.swing.JTextField jTextField2;
    private javax.swing.JTextField jTextField3;
    // End of variables declaration
}

if possible can you give me explanation + example of program usage and why my program not working
it doexnt calculat C * B ...

A: public void exceptionExamples(){

         String B_String = null;
         String C_String = null;
         C_String = jTextField1.getText();
         B_String=jTextField2.getText();
         try{
         int C = Integer.parseInt(C_String);
         int B = Integer.parseInt(B_String);
         float total;
         total = C * B;
         jTextField3.setText("Result is "+total);
         }
         catch(Exception e){
              e.printStackTrace();
              System.out.println("Failed");
         }

}

you are not handling the exceptions correctly you dont need to handle a negativearrayexception when trying to convert a string to a number the exception type you need to handle is NumberFormatException , bt ifyou are accepting Exception class object in your catch it will handle every exception
which i have done .
by the way you are getting a numberformat exception because you are having a " 4" this is wrong it has a space before the 4 change this to "4" and try the code.


text:
Q: Wordpress custom header I am currently using custom header image with randomize uploaded image option. It's working fine. Every time I reload the page it header image changes to new one. Is there a way to change that images manually like setting a timer. I'm new to wordpress. My current code is like this
In functions.php
$args = array(
'width'         => 1856,
'height'        => 448,
'default-image' => 'http://wordpress/wp-content/uploads/2015/02/mbuntu-11.jpg',
'uploads'       => true,);

add_theme_support( 'custom-header', $args );

And in header.php
<header class="intro-header" style="background-image: url('<?php header_image(); ?>')">

A: Add multiple images on the custom theme page.
Go to -> theme customize -> header images -> add images and save.
Now check on your page it's working like slider.

redpajama_set_name: RedPajamaStackExchange


text:
Q: how do I get fileshares to mount after a wireless connection is established? Changed the computer from a wired to wireless connection for a few days. Now the network shares will not mount at boot. But they will mount with sudo mount -a. I tried adding _netdev but that made no difference.
Relevant line in /etc/fstab:
//192.168.1.9/video/shows /media/tv cifs credentials=/home/media/.smbcredentials,_netdev,iocharset=utf8,gid=1000,uid=1000,file_mode=0777,dir_mode=0777 0 0

How do I get _netdev to work with a wireless connection?


text:
Q: strcmp finaliza la ejecucion El problema que tengo es que durante la ejecución de la siguiente función el programa(IDE codeblocks) crashea indicando lo siguiente: status -1073741510 (0xc0000005).
bool existeNombreCol(COLUMNA* cabeza, char *nombre) {
    COLUMNA* cActual = cabeza;
    if(cActual == NULL || &cActual->nom == NULL){
        return false;
    }else{
        while(cActual != NULL && cActual->nom != NULL){
            if(strcmp(cActual->nom,nombre) == 0){
                return true;
            }else{
                cActual = cActual->next;
            }
        }
    }
    return false;
}

Adjunto la definición de la estructura de dato y como la creo:
Definición:
typedef struct col {
    char *nom;              //nombre de la columna
    TIPO t;                 //tipo de la columna
    float max, min, prom;   //máximo, mínimo y promedio
    int histograma[5];      //información para histograma
    ETIQUETA *lista;        //lista de etiquetas STR
    struct col *next;       //puntero a la siguiente columna
} COLUMNA;

Generación de una ED columna(Hay otros métodos que la modifican):
COLUMNA* crearCol(char* nombre) {
    COLUMNA* columna = (COLUMNA*)malloc(sizeof(COLUMNA));
    if (columna == NULL) {
        return NULL;
    }

    columna->nom = (char*)malloc((strlen(nombre) + 1) * sizeof(char));
    strcpy(columna->nom, nombre);

    columna->t = VOID;
    columna->lista = (ETIQUETA*)malloc(sizeof(ETIQUETA));
    columna->lista = NULL;
    columna->next = (COLUMNA*)malloc(sizeof(COLUMNA));
    columna->next = NULL;

    return columna;
}

A: El problema está aqui:
while(cActual != NULL && &cActual->nom != NULL){
    if(strcmp(cActual->nom,nombre) == 0){//LA EJECUCION SE DETIENE

debería ser:
while(cActual != NULL && cActual->nom != NULL){
    if(strcmp(cActual->nom,nombre) == 0){//LA EJECUCION SE DETIENE

Explicación
El while debe ejecutarse mientras el puntero al nombre no sea NULL. Ese se chequea con cActual->nom != NULL. El error está en que comparas &cActual->nom, que vendría siendo la dirección donde está el puntero al nombre. Como la estructura existe y tiene reservado un espacio para ese puntero, &cActual->nom siempre será distinto de NULL.
Demostración
int main() {
    COLUMNA col;
    col.nom = "Juan";
    col.next = NULL;
    char* nom = "Juan";
    char* nom2 = "Jose";

    printf("Buscando %s: ", nom);
    printf(existeNombreCol(&col, nom) ? "Existe" : "No existe");
    printf("\nBuscando %s: ", nom2);
    printf(existeNombreCol(&col, nom2) ? "Existe" : "No existe");
    return 0;
    }

produce
Buscando Juan: Existe
Buscando Jose: No existe


text:
Q: What's does the vertical bar mean in JavaScript? I came across this code at school
var CAR = ' |8|9|10|11|12|13|15|16|';

I understand that this is a variable named car, but I don't understand how it's being initialized or what it means.

A: It's a pipe | character, and in your case it has absolutely no meaning.  You have a string literal, and the text is literally |8|9|10|11|12|13|15|16|.

A: It's a bitwise OR when used outside the context of a string.  In your case, it's inside a string, so it's probably being used somewhere else in the code as a delimiter of numeric values. ie - 8,9,10,etc.


text:
Q: Invalid shape (64, 125, 125, 3) for image data after using ImageDataGenerator So I'm trying to display image that already augmented. But got Invalid shape (64, 125, 125, 3) for image data error. This is my code:
from tensorflow.keras.preprocessing.image import ImageDataGenerator

train_datagen = ImageDataGenerator(rescale=1./255,
                                    zoom_range=0.1,
                                    rotation_range=25,
                                    width_shift_range=0.1,
                                    height_shift_range=0.1,
                                    shear_range=0.1, horizontal_flip=True,
                                    fill_mode='nearest')

val_datagen = ImageDataGenerator(rescale=1./255)

# build image augmentation generators
train_generator = train_datagen.flow(train_data, train_labels_enc, batch_size=64, shuffle=True)
val_generator = val_datagen.flow(val_data, val_labels_enc, batch_size=64, shuffle=False)

from matplotlib import pyplot
for i in range(9):
    # define subplot
    pyplot.subplot(330 + 1 + i)
    # generate batch of images
    batch = train_generator.next()
    # convert to unsigned integers for viewing
    image = batch[0].astype('uint8')
    # plot raw pixel data
    pyplot.imshow(image)

pyplot.show()

And the error pointed to pyplot.imshow(image). Any help would be appreciated

A: The batch object is a tuple of (images, labels) so if you select batch[0] you select all the images.
Try:
for i in range(9):
    pyplot.subplot(330 + 1 + i)
    images, labels = train_generator.next()
    image = (images[0]*255).astype('uint8')
    pyplot.imshow(image)


text:
Q: Permission on session files created by .net core inside /tmp/.dotnet/shm are too open When my application is started .net is creating some build session files inside /tmp/.dotnet/shm
drwxrwxrwx 2 user user 120 Jun  9 09:28 session10811
Folder as well as file permissions are too open. Group or other's rw is unnecessary and might present a security risk.
So far I tried to change the location where this files are created, thinking maybe dotnet clean is not deleting this file because of some race conditions.
To do this I created a text file inside root project named Directory.Build.props and put this inside
<Project>
 <PropertyGroup>
   <Deterministic>true</Deterministic>
 </PropertyGroup>
 <PropertyGroup>
   <BaseIntermediateOutputPath>path</BaseIntermediateOutputPath>
 </PropertyGroup>
 <OutputPath>path</OutputPath>
</Project>

But unsuccesful, the directory where these files are created has not been changed.
Also I tried to add this in .csproj
<PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|AnyCPU'">
        <OutputPath Condition="'$(OutputPath)'=='' ">path</OutputPath>
</PropertyGroup>

But still without success.
I know there is an opened thread somehow related to this problem, but following the suggested steps didn't do anything for me.
Do you know how to stop the creation of these session files or at least change their permissions when they are created ?


text:
Q: How to handle queue of background tasks in Android? I am new to Android programming and my scenario goes like this.
I have several tasks which are in queue like this:
Name.       Time.(sec)   and some other attributes
Task 1      0
Task 2      1.5
Task 3      3.5
Task 4      6.5
Task 5      9.5
Task 6      10.5
Task 7      11.5
Task 8      12
...

This table basically says that execute Task 1 at 0th second, Task 2 at 1.5 second, Task 3 at 3.5 second and so on. I am using Task 1 as the starting time i.e. 0th second. It may be possible that there are multiple tasks running in parallel i.e Task i may still be running when it is time to schedule Task j. All of these tasks are network-intensive.
As I said I am not familiar with Android and I'm trying to figure out the best way to tackle this in Android.
I am thinking of using one AsyncTask(let's say Queue) that loops through all the tasks and see if it is time to schedule any task. If it is not time to schedule any task then sleep till next schedule time i.e nextTaskTime - currentTime. If it is time to schedule then create Runnable instance(or may be another AsyncTask) for the Task and start the execution. So, basically Main thread will create AsyncTask named Queue which may in turn create other threads for Tasks.
Is this correct way to approach this problem?
If there are other ways then please let me know.
Thank you.

A: You will the Serial executor it will execute the Background task serially likewise queue...
DownloadImageTask o1 = new DownloadImageTask();
o1.executeOnExecutor(AsyncTask.SERIAL_EXECUTOR);


text:
Q: Symfony3 Missing argument 2 for CommonBundle\Controller\{closure}() I have an error and can't find where it's from:
->add('Webmaster',          ChoiceType::class, array(
        'required' => false,
        'choices' => $listWebmasters,
        'choice_label' => function($value, $key, $index)
        {
            return ($this->getDoctrine()->getManager()->getRepository('CommonBundle:Compte')->find($value)->getNom().' '.$this->getDoctrine()->getManager()->getRepository('CommonBundle:Compte')->find($value)->getPrenom());
        },
        'choice_value' => function($value, $key, $index)//Line of the error
        {
            return ($this->getDoctrine()->getManager()->getRepository('CommonBundle:Compte')->find($value)->getNom().' '.$this->getDoctrine()->getManager()->getRepository('CommonBundle:Compte')->find($value)->getPrenom());

        }))

I tried without the 'choice_value' option and it works; I tried with a copy of the 'choice_label' and still not working. 'choice_value' is used as 'choice_label'. http://symfony.com/doc/current/reference/forms/types/choice.html#choice-value
EDIT
The exact error:

Warning: Missing argument 2 for
  CommonBundle\Controller\DefaultController::CommonBundle\Controller{closure}()

A: Try to remove $key and $index from parameters. It helped me.
 'choice_value' => function($value)
    {
        ...
    }


text:
Q: JavaNIO: check File lock created by a root-user from a process running under a normal user? I have two processes which I am to synchronize.
Process A is running as root and creates a Reentrant-Lock on a specific file.
Process B is running under a "normal" user and should wait for the lock being releases by process A.
I tried many ways but cannot get it working because of wrong file permissions.
Here is the code:
(removed the in-VM-synchronisation-stuff):
Lock:
FileChannel channel = new RandomAccessFile(pFile, "rw").getChannel();
lock = channel.tryLock();

hasLock:
RandomAccessFile file = new RandomAccessFile(pFile, "rw");
FileChannel channel = file.getChannel();
FileLock lock = channel.tryLock();
if (lock == null) {
 return true;
}
lock.release();

The problem I have is that the lock gets created as:
-rw-r--r--. 1 root root 0 May  7 21:42 lockfile.lock

if I try to check the lock (by process B running as normal user) I get a
java.io.FileNotFoundException: _lockfile_ (Permission denied)
    at java.io.RandomAccessFile.open(Native Method)
    at java.io.RandomAccessFile.<init>(RandomAccessFile.java:212)

I tried to umask the directory to all g=rwx,o=rwx but this seems to be ignored. I tried to create the file first, setWritable(true, false) but this seems to be resetted. I did not get any method to work. I tried to use mode "r" instead of "rw" in hasLock but this leads to a ChannelNotWritableException.
So the main question is: how can I influence the permissions of the created lockfile?
Does anyone has some suggestions?
Regards Michael

A: You are up against the umask of the root process, which masks the "rw" you supplied when creating the file to deny write access to group and others. There is nothing you can do about this except change the root's umask, which is a seriously terrible idea for security reasons.
You should look into having the lock file exist permanently, or, as Peter suggests, using a file that is already part of your application as the lock file.

A: Finally I got a solution:
The way of first creating the file was the correct one. The mistake I made was that I set the permissions before file creation (expecting that the permissions are stored in the file object and used on creation). I have to first create the file, then set the permissions to all and then lock it:
file.createNewFile();
file.setWritable(true, false);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
channel.tryLock()

the lockfile is now created with worlwide-writable (this may be a security issue but actually there is no problem visible as the file does not contain any content.
Thanks to everyone helping me to find a solution!
Regards Michael


text:
Q: Mongoose: validation error path `name` is required Here is my HTML with the form piece.
<form [formGroup]="form" (submit)="onSave()" *ngIf="!isLoading">
    <mat-form-field>
    <input matInput type="text" formControlName="name" placeholder="Organization Name">

Here is the code for onSave() from my component.ts file.
onSave() {
  if (this.form.invalid) {
    return;
  }
  this.isLoading = true;
  if (this.mode === "create") {
    this.objsService.add(
      this.form.value.name
    );
  } else {
    this.objsService.update(
      this.id,
      this.form.value.name
    );
  }
  this.form.reset();
}

Here is the add() function from my service.
/* #region  Create of CRUD */
add(name: string) {
  const objData = new FormData();
  objData.append("name", name);
  this.http
    .post<{ message: string; obj: Organization }>(
      'http://localhost:3000/api/organizations',
      objData
    )
    .subscribe(responseData => {
      this.router.navigate(["/organizations"]);
    });
}
/* #endregion */

And lastly here is my .post to the router in mp api.
/* #region  Create of CRUD */
router.post('', (req, res, next) => {
  console.log('req.body.name: ' + req.body.name);
  const obj = new objModel({
    name: req.body.name
  });
  obj.save().then(createdObj => {
    res.status(201).json({
      message: capitalize(plural) + ' added successfully',
      obj: {
        ...createdObj,
        id: createdObj._id
      }
    });
  });
});
/* #endregion */

As you can see in my api I''m running "console.log('req.body.name: ' + req.body.name);", it's output is "req.body.name: undefined".  How could this be?  What am I missing?
In my service I ended up add the following line.
add(name: string) {
  const objData = new FormData();
  objData.append('name', name);
  console.log(name);
  console.log(objData);

Here's what showed up in the console.
dfgasdfg

FormData {}
  __proto__: FormData
    append: ƒ append()
    ...
    values: ƒ values()
      arguments: (...)
      ...
      name: "values"
        __proto__: ƒ ()
        ...
        name: ""

name: "" should be name: "dfgasdfg".  Is the .append syntax incorrect?
Here's my server.js file.  I did include body-parser.  Did I implement it improperly?
const path = require("path");
const express = require("express");
const bodyParser = require("body-parser");
const mongoose = require("mongoose");

const postsRoutes = require("./routes/posts");
const organizationsRoutes = require("./routes/organizations");

const app = express();

app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));

Thank you in advance!

A: i think you missing body-parser middleware in node api that's why you getting undefined in req.

A: const bodyParser = require('body-parser');
const app = express();
app.use(express.json());
app.use(bodyParser.json({limit: '50mb'}));
app.use(bodyParser.urlencoded({limit: '50mb', extended: true}));

please try to use above express middleware in server.js root file, to get data in req.body object.

A: Ok, I'm an idiot.  I needed to use the following.
app.use(bodyParser.urlencoded({extended: true}));

I was using:
app.use(bodyParser.urlencoded({extended: false}));

Thanks for the direction!!!!
P.S.
Ok, I take it back.  It wasn't a permanent fix.  I am running express 6.9.0, doesn't express 4.16+ have it's own parser?  I changed my code to now have this:
app.use(express.json());
app.use(express.urlencoded());

In my route for the API it looks like it's still not populating req.body.name with the value from the form.
Using this:
console.log('req.body.name: ' + req.body.name);

I get this:
req.body.name: undefined


text:
Q: Does your appearance change based on your morality? In Mass Effect 2, Shepard's physical appearance (especially when you decided to go Renegade) could end up changing pretty drastically, though you could permanently reverse it if you chose to.
Does this behavior continue in Mass Effect 3? I'd like to know so I can customize my character's appearance accordingly if this is going to happen again, especially if she's going to end up with Terminator eyes...

A: Yep. Renegade sheps will see the same trademark fire red facial scars and red eyes.
Random screenshot:

However, the scars and glowing eyes are based on your current, ME3 alignment. Since even a full renegade bar from ME2 only amounts to a token chunk of Renegade points, Shepard will always have minimal scarring at the start when imported, regardless of whether you upgraded the Med Lab in the previous installment.
Consider it a result of the 'low stress environment' that is an Alliance brig awaiting court martial.

A: A message soon after you start the game appears when you are upgrading you and your squads powers. This message states that (assuming you are going renegade) if you continue to be harsh and cause stress, the scars derived from your implants will start up again.

A: It's been confirmed that Renegade Players get the trademark scars like in ME2. If you import your character they should keep the scars too.
Sounds like Shepard keeps the glowing eyes (see On Orbit's post) as well though I haven't personally confirmed this (I'm Paragon).

A: It's true.  Apparently, Bioware is consistent about it as well.  In Knights of the Old Republic this also happens.  The moral of the story is, if you accept the dark side, whether it was long long ago, or far into the future you'll end up getting scars and red eyes.


text:
Q: How to view IndexedDB content in chrome? I am fairly new to writing code, but I played around with some chrome apps which use WebSQL for DB. I decided to learn IndexedDB, but needed something more visual, to help me out. WebSQL database entries can be easily seen in in resources tab in "debugger", but indexedDB database is not shown there.
Chrome is v17, OS Ubuntu 11.10
Is there a workaround for this( plugin or anything else) ?

A: If you use Chromium or the dev channel of Chrome you can enable an experimental Dev Tools feature to surface IndexedDB in the Resources panel.
https://plus.google.com/u/0/100132233764003563318/posts/7pbJUZCGk8U

A: In chrome, click on developer tools or use ctr+shift+I
Click on the application menu
Right click on IndexDB
Click Refresh IndexDB
Then you will see your database content.

A: The accepted answer is 10 years old, mentioning experimental DevTools. So, I decided to rewrite answer.

*

*In Chrome, press F12 or click application menu > More Tools > Developer Tools to open Chrome Developer tools.

*Go to Application tab.

*On the menu left, expand IndexedDb under Storage section and you will see your IndexedDb content.


text:
Q: Local class instance creation expression in a static-context The JLS 15.9.2 tells us how to determine an enclosing instance:
Let C be the class being instantiated, and let i be the instance being created.

If C is an inner class, then i may have an immediately enclosing
  instance (§8.1.3), determined as follows:
[...]
If C is a local class, then:

*

*If C occurs in a static context, then i has no immediately enclosing
  instance.

*Otherwise, if the class instance creation expression occurs in a
static context, then a compile-time error occurs.

*Otherwise, let O be the immediately enclosing class of C. Let n be an
  integer such that O is the n'th lexically enclosing type declaration
  of the class in which the class instance creation expression appears.
The immediately enclosing instance of i is the n'th lexically
  enclosing instance of this.

I didn't get what the bolded case means. Let me provide the example I wasn't supposed to be compiled:
class A{
    int a;
    public static void main (String[] args) throws java.lang.Exception{
        class Foo{
            void bar(){
            }
        }
        Foo f = new Foo(); //Instance creation expression occured in the static context
    }
}

DEMO
What's wrong with that? Couldn't you provide an actual example describing the second point?

A: I guess the following case is meant:
public class A {

   public class B { /* ... */ }

   public static void createB() {
      new B();  // <<=== This should fail
   }
}

The marked line should fail, since the inner class B is not static, so it requires en enclosing instance of A. There is no such enclosing instance, since the method createB() is static.
UPDATE: I mistook the question beeing about inner classes in general, which is what my example shows. In the context of Local Classes I also can't interpret the documentation.

A: You should read these two lines :

*

*If C occurs in a static context, then i has no immediately enclosing instance.

*Otherwise, if the class instance creation expression occurs in a static context, then a compile-time error occurs.

Your case is the first case - you defined the class Foo in a static context (the main method), and therefore the instance f has no enclosing instance.
If, however, you'd define the class Foo outside the main method, and try to create the instance of Foo in the main method, you'll get an error, unless you change Foo to be a static class.
class A
{
    int a;
    class Foo
    {
        void bar()
        {
        }
    }
    public static void main (String[] args) throws java.lang.Exception
    {
        Foo f = new Foo(); // this should fail
    }
}


text:
Q: $A^2 + B^2 + C^2 = D^2 + E^2 + F^2$ and $A^2 + F^2 = B^2 + E^2 = C^2 + D^2$, distinct positive integers I am looking for parametric formula to this system of equations:
$A^2 + B^2 + C^2 = D^2 + E^2 + F^2$
$A^2 + F^2 = B^2 + E^2 = C^2 + D^2$
for distinct positive integers $A,B,C,D,E,F$. According to my computations, solutions for this system are rare. It looks like this is the smallest one:
$421^2 + 541^2 + 49^2 = 559^2 + 149^2 + 371^2$
$421^2 + 371^2 = 541^2 + 149^2 = 49^2 + 559^2$
I would like to know if there is any known algebraic formula (or method) to find these solutions faster (better than bruteforce).

A: Since the equations are all homogeneous of degree $2$, we can multiply a solution by a constant to produce another solution.
We may assume we have a primitive solution, i.e. $\gcd(A,B,C,D,E,F)=1$.
Let's start with $A^2 + F^2 = B^2 + E^2 = C^2 + D^2$.  Call this common value $x$.   Note that if $x \equiv 0 \mod 4$, all of $A,B,C,D,E,F$ are even, so in a primitive solution $x \equiv 1$ or $2 \mod 4$.  Moreover, in a primitive solution $x$ can't be divisible by any prime $\equiv 3 \mod 4$.  You need $x$ to be divisible by at least $3$ (not necessarily distinct) primes $\equiv 1 \mod 4$ to allow $x$ to be written as the sum of two squares in $3$ different ways with all distinct squares.
So one approach would be to look at products of three (or more) primes $\equiv 1 \mod 4$ and (optionally) $2$.  For each such $x$,
consider all ways to write $x$ as the sum of two squares. Take choices of three of those which involve $6$ distinct squares, and
see if you can get $A^2 + B^2 + C^2 = D^2 + E^2 + F^2$.
Taking three such primes $< 300$ and optionally $2$, I get your solution as well as one other:
$$(A,B,C,D,E,F) = (931, 1541, 1691, 1099, 1301, 1789)$$
Using four primes $< 200$ and $2$, I get another solution:
$$(A,B,C,D,E,F) = (137, 1123, 1523, 283, 1067, 1543)$$
EDIT: And here's another one:
$$(A,B,C,D,E,F) = (15953, 23393, 24553, 18263, 19727, 26113)$$


text:
Q: Multi-level regression interpretation: questio of statistical significance I am running (multi-level) logit models on hospital data testing whether the ratio two hospital tariffs has any effect on the probability of being admitted to the hospital.
My models are the following:
f1 <- glm(admit ~  log_ratio, data=dat, family = "binomial")
f2 <- glm(admit ~  log_ratio*as.factor(Condition2), data=dat, family = "binomial")
f3 <- lmer(admit ~  log_ratio + (1|provider_id), data=dat_first, REML = F)
f4 <- lmer(admit ~  log_ratio + log_ratio:as.factor(Condition2) + (1|provider_id), data=dat, REML = F)
f5 <- lmer(admit ~  log_ratio*as.factor(Condition2) + (1|provider_id), data=dat, REML = F)

where admit is a binary variable indicating hospital admission, log_ratio is the log-transformed ratio of the two tariffs, Condition2 is the condition for which the patient received  treatment and provider_id is the id of the treatment provider.
My results are the following:

============================================================================================================
                                                                   Dependent variable:
                                              --------------------------------------------------------------
                                                                          admit
                                                     logistic                         linear
                                                                                mixed-effects
                                                  (1)         (2)         (3)          (4)          (5)
------------------------------------------------------------------------------------------------------------
log_ratio                                      0.605***     1.385*      0.012***     0.013***      0.012
                                                (0.058)     (0.808)     (0.001)      (0.002)      (0.013)

as.factor(Condition2)Brain Disorder                          1.392                                 -0.001
                                                            (1.304)                               (0.021)

as.factor(Condition2)Amputation                              2.352                                 0.0002
                                                            (2.257)                               (0.072)

as.factor(Condition2)Chronic pain                           4.403**                                -0.026
                                                            (2.161)                               (0.055)

as.factor(Condition2)Nervous system                          2.391                                 0.006
                                                            (1.551)                               (0.026)

as.factor(Condition2)Organ Disorder                          1.114                                 -0.018
                                                            (1.787)                               (0.043)

log_ratio:as.factor(Condition2)Brain Disorder               -0.098                   0.014***      0.014
                                                            (0.825)                  (0.002)      (0.014)

log_ratio:as.factor(Condition2)Amputation                   -0.067                   0.053***      0.053
                                                            (1.741)                  (0.003)      (0.059)

log_ratio:as.factor(Condition2)Chronic pain                 -1.926                   0.009***      0.024
                                                            (1.230)                  (0.001)      (0.030)

log_ratio:as.factor(Condition2)Nervous system               -1.537                   0.005***     -0.0003
                                                            (1.050)                  (0.001)      (0.018)

log_ratio:as.factor(Condition2)Organ Disorder                0.457                   0.023***      0.037
                                                            (1.242)                  (0.001)      (0.032)

Constant                                       -4.476***   -6.550***    0.022***      0.007        0.008
                                                (0.075)     (1.293)     (0.008)      (0.009)      (0.023)

------------------------------------------------------------------------------------------------------------
Observations                                    115,376     115,376     115,376      115,376      115,376
Log Likelihood                                -12,589.260 -12,229.590  56,636.920   56,935.280   56,935.630
Akaike Inf. Crit.                             25,182.530  24,483.190  -113,265.800 -113,852.600 -113,843.300
Bayesian Inf. Crit.                                                   -113,227.200 -113,765.700 -113,708.100
============================================================================================================
Note:                                                                            *p<0.1; **p<0.05; ***p<0.01

My main interest is in log_ratio and whether it has any association with the probability of hospital admission. My secondary interest is whether this correlation is different per condition. Log-ratio is significant in every model (logit or multi-level logit) except for when I do an interaction effect with condition (with all main effects in the model, such as in Models 2 & 5). The variables with log-ratio then lose their significance.
My question is which model do I believe? My gut feeling is that log-ratio is in fact significant, but due to small sample size per condition or some other reason it is not showing up as significant in Models 2 & 5. Could this be true?
Also, could Model 4 be an acceptable specification of the model? That is, in my case, do I need to have all main effects in the model?

A: Building off Matt Barstead's comment, looking at the fit information of model 3 vs model 4, I see no evidence that model 4 is the better model. The log likelihood is higher (with 5 additional degrees of freedom used), both AIC and BIC are higher, suggesting that model 4 is not doing a better job of prediction. You can use R's anova() function to test the two models. A quick and dirty calculation suggests that model 4 does not improve fit:
> 1-pchisq((-2*56636.920)-(-2*56935.280), 5)
[1] 0

Because the log likelihood of the more parsimonious model is smaller than the log likelihood from the less parsimonious model in your case, the chi-square test value of 0 is saying the more complicated model is no better than the less complicated model. See information on these tests here.


text:
Q: Append/Combine Shape Files I have a very simple operation I would like to perform: combining two shape files. Specifically, I have census tract shape files for each state in the US that I would like to combine into one shape file. Ultimately, I want to take the combined shape file and perform an overlay on a set of latitude and longitude coordinates, to determine which census tracts my coordinates fall into.
I have seen much discussion on this (Combining bordering shapefiles in R). However, all of the discussion are outdated and I am hoping that the packages have been improved in the meantime.
The files I am using are located here: ftp://ftp2.census.gov/geo/tiger/TIGER2010/TRACT/2010/
The code below can be used to recreate the files I am working with. It requires downloading two files, approximately 11 megabytes total. The run time should be only a minute.
Any help is greatly appreciated. This seems like a trivial operation to perform. Perhaps if I had more experience with geo-spatial mapping I could make better use of the documentation available.
Here are a few things I have tried:
### Insert your file path here
FPATH <- './data'

### Set up library
require(rgeos)
require(maptools)
require(RCurl)
require(parallel)
cl <- makeCluster(detectCores())

### Download files... (~11,000 KB total for this example)
ftp <- 'ftp://ftp2.census.gov/geo/tiger/TIGER2010/TRACT/2010/'
files <- getURLContent(ftp, dirlistonly = T)
files <- unlist(strsplit(files, split = '\r\n', fixed = T))
files <- grep('2010_[[:digit:]]{2}_', files, value = T)[1:2]  # Only grab two files for this example
clusterMap(cl, download.file, url = paste0(ftp, files), destfile = paste0(FPATH, files))

### Unzip shape files
files <- list.files(FPATH, full.names = T)
clusterMap(cl, unzip, zipfile = files, exdir = FPATH)

### Read in shape files
files <- list.files(FPATH, pattern = "shp$", full.names = T)
a <- readShapePoly(fn = files[1])
b <- readShapePoly(fn = files[2])

### Attempt to join two shape files
spRbind(a, b)  # Error in spRbind(as(obj, "SpatialPolygons"), as(x, "SpatialPolygons")) : non-unique polygon IDs
gUnion(a, b)   # Error in RGEOSBinTopoFunc(spgeom1, spgeom2, byid, id, "rgeos_union")   : geos_geospolygon2SpatialPolygons: ng > length(IDs)

Thank you for your time.

A: You've got duplicated polygon IDs.  You can change them manually, or use taRifx.geo:
library(devtools)
install_git("git://github.com/gsk3/taRifx.geo.git")
library(taRifx.geo)
rbind(a,b, fix.duplicated.IDs=TRUE)

Code available for inspection here.


text:
Q: java.lang.NoSuchMethodError: $.refArrayOps(java.lang.Object[]) I have the following spark code stated below
spark-submit --class lr --master yarn --deploy-mode client --driver-memory 4g  --executor-memory  --num-executors 4 --executor-cores 4 --queue xxxxx_p1  /dd/ff/ff/fff/dd/dd/ddd/ddd/Automation/full-1.0-SNAPSHOT.jar  /dd/dd/dd/dd/dd/dd/dd/dd/dd/lr_srvc_dt.properties

When I run this I get the following error,
22/06/29 04:50:41 ERROR SparkSubmit$$anon$2: 'scala.collection.mutable.ArrayOps scala.Predef$.refArrayOps(java.lang.Object[])'
java.lang.NoSuchMethodError: 'scala.collection.mutable.ArrayOps scala.Predef$.refArrayOps(java.lang.Object[])'
        at labresult$.main(labresult.scala:30)
        at labresult.main(labresult.scala)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.base/java.lang.reflect.Method.invoke(Method.java:566)
        at org.apache.spark.deploy.JavaMainApplication.start(SparkApplication.scala:52)
        at org.apache.spark.deploy.SparkSubmit.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:958)
        at org.apache.spark.deploy.SparkSubmit.doRunMain$1(SparkSubmit.scala:180)
        at org.apache.spark.deploy.SparkSubmit.submit(SparkSubmit.scala:203)
        at org.apache.spark.deploy.SparkSubmit.doSubmit(SparkSubmit.scala:90)
        at org.apache.spark.deploy.SparkSubmit$$anon$2.doSubmit(SparkSubmit.scala:1060)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:1069)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)

Build definitions:
Scala version 2.12.15, OpenJDK 64-Bit Server VM, 11.0.14.1

Spark_Version:- version 3.2.0.3-eep-810

JDK-8

I can't figure out what causes this. And how to resolve such issue? Any ideas?


text:
Q: How can I explicitly specify the Web.config XML Transformation in a Web Deploy pubxml file? Web Deployment and *.pubxml files in Visual Studio have a neat feature that allows web.config XML Transformations to be applied at Deploy Time, not just Build Time, which enables per-deployment (i.e. per-environment) web.config customizations.
Problem is, the transformation happens "by magic" - if you have a file in your website root named web.{profile name}.config then it will be applied during publish - but you have no way of disabling this functionality, or (as far as I can tell) specifying a different transformation file. I also cannot see how you can transform other web.config files (such as the Views/web.config file in an MVC project) using pubxml files.
I did notice that pubxml files are just MSBuild XML files in their own right - so clearly the Deploy process is just a matter of executing those MSBuild files with the right targets - so to get the functionality I want, I just need to modify the pubxml file with my own custom build-steps.
...but how should I add those build-steps? What is the extensibility-point and event to target?

A: Pubxml configuration still happens at build time it just assumes you will deploy at the same time as well and allows you to adjust your config accordingly.
If you want true deploy-time configuration changes you should use WebDeploy parameterization. It is much more capable and is applied when the WebDeploy package is deployed.
We use it for 50+ product deployments to 4 different environments (DEV, QA, MOCK, PROD) with great success.
http://www.dotnetcatch.com/2014/09/08/parameterizationpreview-visual-studio-extension/


text:
Q: jQuery AJAX function - data not being passed Not sure what I'm doing wrong here but I have the following AJAX function. console.log(make_id); is working fine, however data: {make:make_id}, doesn't seem to pass to /get_models.php - this line of code $make_id = $POST['make'];
$(document).ready(function() {
    $("#select_make").change(function() {
        var make_id = $(this).val();
        console.log(make_id);
        $.ajax({
            url: '/car_clearance_form/get_models.php',
            type: 'post',
            data: {
                make: make_id
            },
            dataType: 'json',
            success: function(response) {
                console.log(response);
                var len = response.length;
                $("#select_model").empty();
                for (var i = 0; i < len; i++) {
                    var model_id = response[i]['model_id'];
                    var model_name = response[i]['model_name'];
                    $("#select_model").append("<option value='" + model_id + "'>" + model_name + "</option>");
                }
            }
        });
    });
});

This is the code for get_models.php
I am getting the following error PHP Warning:  mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given. $sql seems to be returning false, as $make_id isn't getting passed any thing from the AJAX function
<?php
   include "config.php";
   $make_id = $POST['make'];
   $sql = "SELECT model_name, model_id FROM models WHERE make_id = ".$make_id;
   $result = mysqli_query($con, $sql);
   $models_array = array();
   while ($row = mysqli_fetch_array($result) ) {
     $model_id = $row['model_id'];
     $model_name = $row['model_name'];
     $models_array = array("model_id" => $model_id, "model_name" => $model_name);
   }
   // encoding array to JSON format
   echo json_encode($models_array);
   ?>

A: A couple of problems:
1) As BeingSunny pointed out, $POST['Make'] is a typo and should be $_POST['make']
2) As both BeingSunny and I pointed out, when you said your console.log is
"...only returning the last item from $models_array", that's not actually true.
The real problem is that $models_array only contains the last item from the database results in the first place. The console.log is reporting exactly what it's given. The root cause of this is that $models_array = array("model_id" => $model_id, "model_name" => $model_name); over-writes the $models_array variable every time the loop runs.
$models_array[] = array("model_id" => $model_id, "model_name" => $model_name);

will fix that, as it will add a new entry to the array instead of completely obliterating the whole variable.
Also note my comments re your vulnerability to SQL injection attacks. Although this is not directly related to the question, it's certainly a problem you should address urgently.

A: Try putting "make" inside quotes so the code becomes:

$(document).ready(function() {
        $("#select_make").change(function() {
        var make_id = $(this).val();
        console.log(make_id);
        $.ajax({
            url: '/car_clearance_form/get_models.php',
            type: 'post',
            data: {'make':make_id},//here
            dataType: 'json',
            success:function(response) {
            console.log(response);
                var len = response.length;

                $("#select_model").empty();
                for(var i = 0; i<len; i++) {
                    var model_id = response[i]['model_id'];
                    var model_name = response[i]['model_name'];

                    $("#select_model").append("<option
            value='"+model_id+"'>"+model_name+"</option>");
                }

            }

            });
            });
            });


text:
Q: Using SFINAE on non static data members? I'm new to SFINAE and I'm trying to write a simple Vector template. What I'm trying to achieve is to enable the z member variable based on the dimensions set for the Vector.
I have tried to achieve this effect using the following code:
template<unsigned int DIMENSIONS>
class Vector {
    // The x and y variables (same as z)

    template<typename = typename std::enable_if<DIMENSIONS >= 3>::type>
    /// <summary>
    /// The z coordinate.
    /// </summary>
    Float& z;

    Vector() : x(values[0]), y(values[1]) {
    }

    // Other member functions and variables

    std::vector<float> values;
};

template <>
Vector<3>::Vector() : x(values[0]), y(values[1]), z(values[2]) {
}

This should enable the z variable when there are 3 or more dimensions. This makes the compiler complain with the following error:
'Vector<DIMENSIONS>::z': only static data member templates are allowed

Also, I'm not entirely sure how to use initialization lists with SFINAE in such a situation. Because if the dimensions are smaller than 3, z would not have to be initialized (since it wouldn't exist). So far I've used a specialized constructor for 3D vectors (see the code above).
But intelliisense still reports that Members 'x', 'y', 'z' are not initialized in this constructor.
Any help would be appreciated.

A: You could do something like this:
struct no_z_var {};

struct z_var
{
    float z;
};

template<std::size_t n>
struct my_vector : std::conditional_t<( n >= 3 ), z_var, no_z_var>
{
    float x, y;
};

int main()
{
    my_vector<3> mv3;
    mv3.z = 3.4f;
    my_vector<2> mv2;
    mv2.z = 3.4f; // error; no 'z'
}

However, is this a good solution/design? I'm not so sure; it can get messy. It will most likely present other difficulties during the implementation...

A: You simply can't conditionally enable variables like that. Your best bet is just to provide multiple specializations of Vector:
template <>
struct Vector<2> {
    float x, y;

    Vector(std::vector<float> const& values)
    : x(values[0])
    , y(values[1])
    { }
};

template <>
struct Vector<3> {
    float x, y, z;

    Vector(std::vector<float> const& values)
    : x(values[0])
    , y(values[1])
    , z(values[2])
    { }
};

// etc.

Though it might be more straightforward to use an array instead:
template <size_t DIM>
struct Vector {
    std::array<float, DIM> values;

    Vector(std::vector<float> const& vs)
    : Vector(vs, std::make_index_sequence<DIM>{})
    { }

private:
    template <size_t... Is>
    Vector(std::vector<float> const& vs, std::index_sequence<Is...> )
    : values{{vs[Is]...}}
    { }
};

A: You could use inheritance.
template<int n>
struct VecBase;

template<>
struct VecBase<1> {
    float x;
};

template<>
struct VecBase<2> : VecBase<1> {
    float y;
};

template<>
struct VecBase<3> : VecBase<2> {
    float z;
};

template<>
struct VecBase<4> : VecBase<3> {
    float w;
};

And then define your vector class:
template<int n>
struct Vector : VecBase<n> {
    // operations
};

If you want to make n-dimentional operation, you can use std::get and std::index_sequence. Let's start by making overloads for std::get:
namespace std {

template<size_t I, int n, enable_if_t<(I == 0 && I < n), int> = 0>
float& get(VecBase<n>& vec) {
    return vec.x;
}

template<size_t I, int n, enable_if_t<(I == 1 && I < n), int> = 0>
float& get(VecBase<n>& vec) {
    return vec.y;
}

template<size_t I, int n, enable_if_t<(I == 2 && I < n), int> = 0>
float& get(VecBase<n>& vec) {
    return vec.z;
}

template<size_t I, int n, enable_if_t<(I == 3 && I < n), int> = 0>
float& get(VecBase<n>& vec) {
    return vec.w;
}

}

Note that you will have to implement them for const.
Then, you can implement your operations by making a base class that implement operations:
template<int, typename>
struct VecOps;

template<int n, std::size_t... S>
struct VecOps<n, std::index_sequence<S...>> : VecBase<n> {
    float dotp(Vector<n>& vec) const {
        // Where sum is adding each parameter variadically.
        return sum((std::get<S>(*this) * std::get<S>(vec))...);
    }
};

And finally, make Vector extending VecOps:
template<int n>
struct Vector : VecOps<n, std::make_index_sequence<n>> {};

Note that I don't have a compiler at my disposition for the moment. If your got compiler error, just leave a comment and I'll check this out.

A: Specialize the entrie class for 1, 2, 3 dimensions if you want this, i.e., template<> class Vector<3> { ... }.

A: You don't really need SFINAE here. Just use specialization:
template<unsigned int DIMENSIONS>
class Vector {
  template<int I>
  struct ZContainer {};
  template<> struct ZContainer<3> {
    float z;
  };
  ZContainer<DIMENSIONS> possibleZ;
};

This has the advantage that you don't need additional templates. You can just add functions to the ZContainers for your class behavior.


text:
Q: OpenGL ES render to UIImage, image is black I have some problems with image processing with the help of OpenGL ES.
I have created a texture, load shaders, and attached them to the program and when I want to render my
texture to UIImage, the image is fully black :(
Texture init:
glActiveTexture(GL_TEXTURE0);
glGenTextures(1, &_name);
glBindTexture(self.format, _name);
glTexParameteri(self.format, GL_TEXTURE_MIN_FILTER, GL_LINEAR);
glTexParameteri(self.format, GL_TEXTURE_MAG_FILTER, GL_LINEAR);
glTexParameteri(self.format, GL_TEXTURE_WRAP_S, GL_CLAMP_TO_EDGE);
glTexParameteri(self.format, GL_TEXTURE_WRAP_T, GL_CLAMP_TO_EDGE);
glBindTexture(self.format, 0);

Texture load code:
self.pixelSize = CGSizeMake(self.size.width * self.scale, self.size.height * self.scale);

    BOOL shouldScale = NO;

    if (self.limitedSize.width < self.pixelSize.width ||
        self.limitedSize.height < self.pixelSize.height) {
        self.pixelSize = self.limitedSize;
    }

    if (shouldScale) {
        CGFloat normalizedWidth = ceil(log2(self.pixelSize.width));
        CGFloat normalizedHeight = ceil(log2(self.pixelSize.height));

        self.pixelSize = CGSizeMake(pow(2.0, normalizedWidth), powf(2.0, normalizedHeight));
        self.data = (GLubyte *)calloc(1, self.bytes);

        CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
        CGBitmapInfo bitmapInfo = kCGBitmapByteOrder32Little | kCGImageAlphaPremultipliedFirst;
        CGContextRef context = CGBitmapContextCreate(self.data, normalizedWidth, normalizedHeight, 8, normalizedWidth * 4, colorSpace, bitmapInfo);
        CGContextDrawImage(context, CGRectMake(0, 0, normalizedWidth, normalizedHeight), image.CGImage);
        CGContextRelease(context);
        CGColorSpaceRelease(colorSpace);
    }
    else {
        CFDataRef dataRef = CGDataProviderCopyData(CGImageGetDataProvider(image.CGImage));
        self.data = (GLubyte *)CFDataGetBytePtr(dataRef);
        CFRelease(dataRef);
    }

    glBindTexture(self.format, self.name);
    glTexParameteri(GL_TEXTURE_2D, GL_TEXTURE_MIN_FILTER, GL_LINEAR_MIPMAP_LINEAR);
    glTexImage2D(self.format, 0, GL_RGBA, self.pixelSize.width, self.pixelSize.height, 0, GL_BGRA, self.type, self.data);
    glGenerateMipmap(GL_TEXTURE_2D);

Frame buffer:
glActiveTexture(GL_TEXTURE1);
glGenFramebuffers(1, &_buffer);
glBindFramebuffer(GL_FRAMEBUFFER, _buffer); // self.format is GL_TEXTURE_2D
glBindTexture(self.texture.format, self.texture.name);
glTexImage2D(self.texture.format, 0, GL_RGBA, self.width, self.height, 0, GL_RGBA, GL_UNSIGNED_BYTE, 0);
glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, self.texture.format, self.texture.name, 0);

GLint status = glCheckFramebufferStatus(GL_FRAMEBUFFER);
if (status != GL_FRAMEBUFFER_COMPLETE) {
    NSLog(@"GLBuffer: Failed to make framebuffer object");
}

glBindTexture(self.texture.format, 0);

Render:
[self.buffer bind];
[self.program use];

glClearColor(0.0f, 0.0f, 0.0f, 1.0f);
glClear(GL_COLOR_BUFFER_BIT);

glActiveTexture(GL_TEXTURE2);
[self.texture bind];

glUniform1i([self.texture uniformForKey:@"inputImageTexture"], 2);
glUniform1f([self.texture uniformForKey:@"red"], 1.0);
glUniform1f([self.texture uniformForKey:@"green"], 0.0);
glUniform1f([self.texture uniformForKey:@"blue"], 0.0);

glVertexAttribPointer([self.texture attributeForKey:@"position"], 2, GL_FLOAT, 0, 0, [self.texture vertices]);
glEnableVertexAttribArray([self.texture attributeForKey:@"position"]);

glVertexAttribPointer([self.texture attributeForKey:@"inputTextureCoordinate"], 2, GL_FLOAT, 0, 0, [self.texture coordinates]);
glEnableVertexAttribArray([self.texture attributeForKey:@"inputTextureCoordinate"]);

glDrawArrays(GL_TRIANGLE_STRIP, 0, 4);

[self.buffer unbind];
[self.texture unbind];

Texture to image:
  [self.buffer bind];
   GLubyte *rawPixels = (GLubyte *)malloc([self.texture bytes]);

glReadPixels(0, 0, [self.texture width], [self.texture height], GL_RGBA, GL_UNSIGNED_BYTE, rawPixels);
CGDataProviderRef dataProvider = CGDataProviderCreateWithData(NULL, rawPixels, [self.texture bytes], NULL);

NSUInteger bytesPerRow = [self.texture pixelWidth] * 4;
CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault | kCGImageAlphaLast;
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();

CGImageRef cgImage = CGImageCreate([self.texture pixelWidth],
                                   [self.texture pixelHeight],
                                   8,
                                   32,
                                   bytesPerRow,
                                   colorSpace,
                                   bitmapInfo,
                                   dataProvider,
                                   NULL,
                                   NO,
                                   kCGRenderingIntentDefault);

UIImage *image = [UIImage imageWithCGImage:cgImage];

CGImageRelease(cgImage);
CGDataProviderRelease(dataProvider);
CGColorSpaceRelease(colorSpace);

after i removed glClear(GL_COLOR_BUFFER_BIT) from my rendering method, texture renders correctly on simulator, but not on real device. Any suggestions?

A: Convert texture to UIImage
`#pragma mark - Convert GL image to UIImage`
-(UIImage *) glToUIImage
{

    imageWidth = 702;
    imageHeight = 962;

    NSInteger myDataLength = imageWidth * imageHeight * 4;

    // allocate array and read pixels into it.
    GLubyte *buffer = (GLubyte *) malloc(myDataLength);
    glReadPixels(0, 0, imageWidth, imageHeight, GL_RGBA, GL_UNSIGNED_BYTE, buffer);

    // gl renders "upside down" so swap top to bottom into new array.
    // there's gotta be a better way, but this works.
    GLubyte *buffer2 = (GLubyte *) malloc(myDataLength);
    for(int y = 0; y < imageHeight; y++)
    {
        for(int x = 0; x < imageWidth * 4; x++)
        {
            buffer2[((imageHeight - 1) - y) * imageWidth * 4 + x] = buffer[y * 4 * imageWidth + x];
        }
    }

    // make data provider with data.
    CGDataProviderRef provider = CGDataProviderCreateWithData(NULL, buffer2, myDataLength, NULL);

    // prep the ingredients
    int bitsPerComponent = 8;
    int bitsPerPixel = 32;
    int bytesPerRow = 4 * imageWidth;
    CGColorSpaceRef colorSpaceRef = CGColorSpaceCreateDeviceRGB();
    CGBitmapInfo bitmapInfo = kCGBitmapByteOrderDefault;
    CGColorRenderingIntent renderingIntent = kCGRenderingIntentDefault;

    // make the cgimage
    CGImageRef imageRef = CGImageCreate(imageWidth, imageHeight, bitsPerComponent, bitsPerPixel, bytesPerRow, colorSpaceRef, bitmapInfo, provider, NULL, NO, renderingIntent);

    // then make the uiimage from that
    UIImage *myImage = [UIImage imageWithCGImage:imageRef];
    return myImage;
}

Just get your image by calling this method like this -
UIImage *yourImage = [self glToUIImage];

Source = http://www.bit-101.com/blog/?p=1861


text:
Q: android - How to handle the Web service exception In my application i getting the exceptions when i am calling the web service. The exceptions are
07-11 18:46:54.942: INFO/System.out(1180): Webservice calling error ->java.net.UnknownHostException: Host is unresolved: www.roadbrake.com:80
07-11 18:46:54.942: INFO/System.out(1180): Soap Method Error ->java.lang.NullPointerException
is it code problem or Web service problem. if it is coding problem how can i handle it?
Please can anybody help me.
thanks

A: You should check your network connection before calling web service..
here is the code to check Network Connection...
ConnectivityManager conMgr =  (ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.CONNECTED
    ||  conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.CONNECTING  ) {

    //notify user you are online

}
else if ( conMgr.getNetworkInfo(0).getState() == NetworkInfo.State.DISCONNECTED
    ||  conMgr.getNetworkInfo(1).getState() == NetworkInfo.State.DISCONNECTED) {
    //notify user you are not online

}


text:
Q: "in the night of" VS "On the night of"
*

*In the night of 22 to 23 August 1791, men and women, torn from Africa and sold into slavery, revolted against  the slave system to obtain freedom and independence for Haiti, gained in 1804.

*On the night of 22 to 23 August 1791, men and women, torn from Africa and sold into slavery, revolted against  the slave system to obtain freedom and independence for Haiti, gained in 1804.

Which one is suitable?

A: On the night is correct in this context. It's a way of referring back to some recent or historical action that took place on (or commenced on) a certain night.
In a court case, lawyers would refer to such an action as having occurred on the night of the date concerned.
In the night is used more loosely, often in songs, poems, novels and the like to refer to the period of darkness and all that people associate with it.

In the night ghouls and ghosties are about.
In the night owls can be heard calling across the valley.

There is also the more prosaic at night, used to refer to night time activities.

My shifts involve work at night.
The shop remains open at night.

https://english.stackexchange.com/questions/121858/at-night-or-in-the-night
https://www.quora.com/Why-do-we-say-in-the-morning-but-not-in-the-night


text:
Q: CSS3 Columns - Force non breaking/splitting element? I'm using some CSS3 columns (column-count: 2;column-gap: 20px;) to split some content into two columns. In my content I have a <p>, followed by a <blockquote>, followed by another <p>.
My question: Is there a way of preventing my <blockquote> (or any other specified element) from splitting into two columns?
For example, currently my <blockquote> is partially in column 1, and partially in column 2.

Ideally I'd like to make it so the <blockquote> stays together in either column 1 or 2.

Any idea if this can be achieved?
Thanks!

A: According to MDN, the correct solution is
blockquote {
  break-inside: avoid-column;
}

However this is not yet implemented in all browsers, so a practical solution is:
blockquote {
  display: inline-block;
}

A: Just general FYI for others that bump into this forum and need a solution for Firefox.
At the moment writing this, Firefox 22.0 didn't support column-break-inside property even with -moz- prefix.
But the solution is quite simple: Just use display:table;. You can also do **display:inline-block; The problem with these solutions is that the list items will lose their list style item or bullet icon.
**Also, one problem I've experienced with display:inline-block; is that if the text in two consecutive list items is very short, the bottom item will wrap itself up and inline with the one above it.
display:table; is the least worst of both solutions.
More info here: http://trentwalton.com/2012/02/13/css-column-breaks/

A: In theory the property you are looking for is...
blockquote {
  column-break-inside : avoid;
}

However, last time I checked it wasn't properly implemented in Webkit, no idea about firefox. I've had more luck with:
blockquote {
  display: inline-block;
}

As the renderer treats it as an image and doesn't break it among columns.

A: Add display:inline-block; to the item you want to prevent from splitting.


text:
Q: Having trouble Implementing a Custom Comparator for a TreeSet (Dijkstra's) I'm currently trying and implementing my own custom O(N.lgN) solution of Dijkstra's using Adjacency Lists. Now if you are familiar with this algorithm (most likely you are), I was having trouble storing the tuple for each Vertex. If you have no clue what i'm talking about, have alook at: http://qr.ae/LoESY
Tuples can easily be stored in C++ using
pair <int,int>.

Anyways, i found a solution to that and came to know, against all odds, that a similar class DOES exist its called the 'AbstractMap.SimpleEntry' Class. Details are given here:
https://stackoverflow.com/a/11253710/4258892
Now that you've read it, this works almost the same as pair<> and suffices to store the Adjacent Edge as the key and Weight as the Value in the tuple.
Declaration: Map.Entry pair= new AbstractMap.SimpleEntry(1,2);
Now i have all the inputs in the form of tuples stored in an ArrayList for each vector. I planned on adding the tuples of the source entered to the TreeSet and sort them in ascending order wrt the weights (right?). However, if i just add these tuples to the TreeSet, I am throw an error:
Exception in thread "main" java.lang.ClassCastException:java.util.AbstractMap$SimpleEntry cannot be cast to java.lang.Comparable

Now i don't know how to implement a custom comparator for a TreeSet which sorts my values ascendingly (In Dijkstra's, the edge with least weight would come out first right?). Also, if not possible with TreeSet, could you provide me with a Priority Queue with a comparator implemented?
Even if you didn't follow, Here's my code. Hopefully you'll understand:
EDIT Code Edited as per suggestion from below answer
package GRAPH;

import java.io.*;
import java.util.*;

/**
 * Created by Shreyans on 3/25/2015 at 7:26 PM using IntelliJ IDEA (Fast IO Template)
 */

class DIJKSTA_TRY
{
    public static void main(String[] args) throws Exception
    {
        InputReader in = new InputReader(System.in);
        OutputWriter out = new OutputWriter(System.out);
        //Initializing Graph
        List<ArrayList<AbstractMap.SimpleEntry<Integer,Integer>>>gr=new ArrayList<ArrayList<AbstractMap.SimpleEntry<Integer, Integer>>>();//AbstractMap.SimpleEntry<Integer,Integer> is similar to pair<int a,int b> in C++
        System.out.println("Enter no of Vertices");
        int v=in.readInt();
        System.out.println("Enter no of Edges");
        int e=in.readInt();
        for(int i=0;i<=v;i++)//Initializing rows for each vertex
        {
            gr.add(new ArrayList<AbstractMap.SimpleEntry<Integer, Integer>>());
        }
        System.out.println("Enter <Vertex> <Adjacent Vertex> <Weight>");
        for(int i=0;i<e;i++)
        {
            int a = in.readInt();
            int b = in.readInt();
            int c = in.readInt();
            gr.get(a).add(new AbstractMap.SimpleEntry<Integer, Integer>(b, c));
        }
        out.printLine(gr);
        System.out.printf("Enter Source");
        int s=in.readInt();
        Comparator<AbstractMap.SimpleEntry<Integer, Integer>> comparator=new WeightComparator();
        TreeSet<AbstractMap.SimpleEntry<Integer, Integer>>ts=new TreeSet<AbstractMap.SimpleEntry<Integer, Integer>>(comparator);
        for(AbstractMap.SimpleEntry<Integer, Integer> pair: gr.get(s))//Error:Exception in thread "main" java.lang.ClassCastException: java.util.AbstractMap$SimpleEntry cannot be cast to java.lang.Comparable
        {
            ts.add(pair);
        }
        out.printLine(ts);
        {
            out.close();
        }
    }

    static public class WeightComparator implements
            Comparator<AbstractMap.SimpleEntry<Integer, Integer>>
    {
        @Override
        public int compare(AbstractMap.SimpleEntry<Integer, Integer> one,
                           AbstractMap.SimpleEntry<Integer, Integer> two)
        {
            return Integer.compare(one.getValue(), two.getValue());
        }
    }
    //FAST IO
    private static class InputReader
    {
        private InputStream stream;
        private byte[] buf = new byte[1024];
        private int curChar;
        private int numChars;
        private SpaceCharFilter filter;

        public InputReader(InputStream stream)
        {
            this.stream = stream;
        }

        public int read()
        {
            if (numChars == -1)
                throw new InputMismatchException();
            if (curChar >= numChars)
            {
                curChar = 0;
                try
                {
                    numChars = stream.read(buf);
                } catch (IOException e)
                {
                    throw new InputMismatchException();
                }
                if (numChars <= 0)
                    return -1;
            }
            return buf[curChar++];
        }

        public int readInt()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            int res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public String readString()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            StringBuilder res = new StringBuilder();
            do
            {
                res.appendCodePoint(c);
                c = read();
            } while (!isSpaceChar(c));
            return res.toString();
        }

        public double readDouble()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            double res = 0;
            while (!isSpaceChar(c) && c != '.')
            {
                if (c == 'e' || c == 'E')
                    return res * Math.pow(10, readInt());
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            }
            if (c == '.')
            {
                c = read();
                double m = 1;
                while (!isSpaceChar(c))
                {
                    if (c == 'e' || c == 'E')
                        return res * Math.pow(10, readInt());
                    if (c < '0' || c > '9')
                        throw new InputMismatchException();
                    m /= 10;
                    res += (c - '0') * m;
                    c = read();
                }
            }
            return res * sgn;
        }

        public long readLong()
        {
            int c = read();
            while (isSpaceChar(c))
                c = read();
            int sgn = 1;
            if (c == '-')
            {
                sgn = -1;
                c = read();
            }
            long res = 0;
            do
            {
                if (c < '0' || c > '9')
                    throw new InputMismatchException();
                res *= 10;
                res += c - '0';
                c = read();
            } while (!isSpaceChar(c));
            return res * sgn;
        }

        public boolean isSpaceChar(int c)
        {
            if (filter != null)
                return filter.isSpaceChar(c);
            return c == ' ' || c == '\n' || c == '\r' || c == '\t' || c == -1;
        }

        public String next()
        {
            return readString();
        }

        public interface SpaceCharFilter
        {
            public boolean isSpaceChar(int ch);
        }
    }

    private static class OutputWriter
    {
        private final PrintWriter writer;

        public OutputWriter(OutputStream outputStream)
        {
            writer = new PrintWriter(new BufferedWriter(new OutputStreamWriter(outputStream)));
        }

        public OutputWriter(Writer writer)
        {
            this.writer = new PrintWriter(writer);
        }

        public void print(Object... objects)
        {
            for (int i = 0; i < objects.length; i++)
            {
                if (i != 0)
                    writer.print(' ');
                writer.print(objects[i]);
            }
        }

        public void printLine(Object... objects)
        {
            print(objects);
            writer.println();
        }

        public void close()
        {
            writer.close();
        }

        public void flush()
        {
            writer.flush();
        }
    }
}

Enter Source1
[[], [2=3, 4=3], [3=4], [1=7], [3=2]]
[2=3]

EDIT Works. Thanks @rgettman

A: You received the error because the AbstractMap.SimpleEntry class doesn't implement Comparable.  A TreeSet that isn't given a Comparator must assume that its elements are Comparable, but they aren't.
You were right to determine that you need to create a Comparator, to tell the TreeSet how to order the elements.
Create your own class that implements Comparator<AbstractMap.SimpleEntry<Integer, Integer>>.  In the compare method, extract the weights and compare them.
public class WeightComparator implements
    Comparator<AbstractMap.SimpleEntry<Integer, Integer>>
{
    @Override
    public int compare(AbstractMap.SimpleEntry<Integer, Integer> one,
                       AbstractMap.SimpleEntry<Integer, Integer> two)
    {
        return Integer.compare(one.getValue(), two.getValue());
    }
}


text:
Q: rails assets urls don't have digest when calling from css.scss I deployed my project to production and some of my assets don't work.
Those assets, which I use in html.erb with
<%= image_tag('outstaffing/outstaff2.svg') %>

work normally and return
<img src="/assets/outstaffing/outstaff2-eade8e303c63a428e7430e84866b732dae91cda0639d8d3d422c2ee86fb254aa.svg" alt="Outstaff2 eade8e303c63a428e7430e84866b732dae91cda0639d8d3d422c2ee86fb254aa">

However fonts and some images don't.
I have app/assets/fonts/RobotoCondensedRegular.ttf and app/assets/images/common/footer.svg which I try to call from css files.
 style.css.scss
@font-face {
   font-family: 'RobotoRegular';
   src: url(font-path('RobotoCondensedRegular.ttf'))  format('truetype');
}

#some_div{
   background: asset-url('common/footer.svg');
}

After precompilling I have public/assets/styles-h5digest.css with
@font-face{
  font-family:'RobotoRegular';
  src:url("/assets/RobotoCondensedRegular-4a7c36df4318fee50a8159c3a0ebde4572abab65447ae4a651c2fe87212302b5.ttf") format("truetype")
}

This should work but returns me errors:

Failed to load resource: the server responded with a status of 500 (Internal Server Error)

Server is trying to load assets/fonts/RobotoCondensedRegular.ttf but file name should be with digest. The same thing is with footer image.
I have already tried to change assets.rb, production.rb and application.rb in many ways. Moreover, I tried different extensions of my css files (css, css.scss, scss, css.erb) and helpers (asset-url, image-url, asset-data-url, asset_data_path, <%= asset_path() %>).
I am using Rails 4.2.0 and ruby 2.2.3.
My  production.rb
config.serve_static_files = true
config.assets.js_compressor = :uglifier
config.assets.css_compressor = :sass
config.assets.compile = false
config.assets.digest = true

My  application.rb
config.assets.enabled = true
config.assets.paths << Rails.root.join('app', 'assets', 'fonts')
config.assets.paths << Rails.root.join('app', 'assets', 'images', 'img', 'main')

My  assets.rb
Rails.application.config.assets.precompile << /\.(?:svg|eot|woff|ttf|jpg|png)\z/
Rails.application.config.assets.precompile += ['styles.css', 'careers.css', 'team.css', 'home.css', 'services.css', 'contacts.css']

Error from log:

"GET /assets/fonts/RobotoCondensedBold.ttf HTTP/1.1" 500 1812 "http://...ip..../assets/application-6b568a81a81290ff96d145fa1f76bbf33919b85dad0f4235d8bf8759787a5076.css"

I think problem is in my server (apache) but i have no solution.

A: I added these two gems to my Gemfile:
gem 'rails_serve_static_assets'
gem 'rails_stdout_logging'

And set in my  production.rb
config.serve_static_files = false

Now all fonts and images are working good.


text:
Q: Elasticseach: indexing 100k small docs per sec, more indexes with 5 shards seems to give a little better performance than 1 big index Summary
Our use case is indexing 100k small documents per second, with a small search throughput of ~2-3/sec.
This initial version of this question was based on benchmarks run on version 2.3.1/2.3.2 where, in order to reach the scale needed, I ended up using more indexes with 5 shards instead of one index with more shards (we tried 1x, 2x or 4x number_of_nodes). This is not an issue for us since we already partition our data-set for other purposes, so it is easy to create one index for each partition.
I ran a quick benchmark on elasticsearch version 2.4.0 and the difference between 1 index 47 shards and 10 indexes 5 shards each is not big, but 10 index version still performs better.
However since the difference is not significant, this question is not so relevant anymore. However just the benchmark data might be useful for some people so please find below some details for those interested.
Details
This articleTuning data ingestion performance for Elasticsearch on Azure by Masashi Narumoto has some interesting benchmarks and I used prime number of shards suggested here 19, 47, 83.

The tests also illustrated one other important point. In this scenario, increasing the number of nodes can improve data ingestion throughput, but the results do not necessarily scale linearly. Conducting further tests with 12 and 15 node clusters could show the point at which scale-out brings little additional benefit. If this number of nodes provides insufficient storage space, it may be necessary to return to the scale-up strategy and start using more or bigger disks based on premium storage.

Elasticsearch version 2.4.0 was used, cluster has 12 nodes, 16GB/8core/SSD digitalocean droplets.

At first old version 2.3.2 of the Java API (TransportClient) was used, then client was upgraded to version 2.4.0.
See below graph showing slightly better performance when using 10 indexes:

3x8GB digitalocean droplets were used as client nodes. Each node simulated 10 transport clients each with 2 concurrent requests.
Example bulk sizes:
bulk finished 7600, bytes: 5243143
bulk finished 7600, bytes: 5243143
bulk finished 7600, bytes: 5243235
bulk finished 7600, bytes: 5243143
bulk finished 7571, bytes: 5242948
bulk finished 7571, bytes: 5243040
bulk finished 7601, bytes: 5243354
bulk finished 7600, bytes: 5243235
bulk finished 7600, bytes: 5243235
bulk finished 7601, bytes: 5243354
bulk finished 7600, bytes: 5243235
bulk finished 7601, bytes: 5243272
bulk finished 7627, bytes: 5243251

Between each test:

*

*clients were stopped

*all indexes were DELETEd

*mapping changed

*clients reconfigured to use 1 index or 10 indexes and started back up

Mappings
  "settings" : {
      "number_of_shards" : 47,
      "number_of_replicas": 1,
      "refresh_interval": "30s",
      "index.translog.flush_threshold_size": "2gb",
      "index.codec": "best_compression"
  },
  "mappings": {
    "MessageRecord": {
      "_source": {
        "enabled": true
      },
      "properties": {
        "timestamp": { "type": "date"},
        "host": { "type": "string", "index": "not_analyzed" },
        "IP": { "type": "string", "index": "not_analyzed" },
        "process": { "type": "integer"},
        "username": { "type": "string", "index": "not_analyzed" },
        "email": { "type": "string", "index": "not_analyzed" },
        "sessionId": { "type": "string", "index": "not_analyzed" },
        "APIName": { "type": "string", "index": "not_analyzed" },
        "componentName": { "type": "string", "index": "not_analyzed" },
        "className": { "type": "string", "index": "not_analyzed" },
        "methodName": { "type": "string", "index": "not_analyzed" },
        "message": { "type": "string" }
      }
    }
  }

12 nodes, 1 index, 19 shards, 1 replica
Shards
curl -s localhost:9200/_cat/shards?v | perl -ne '@v=split(/\s+/); $h{$v[7]} .= "$v[1]$v[2],"; END{foreach $k (sort(keys(%h))) {print "$k: $h{$k}\n"}}'
db1: 3p,16r,15p,
db10: 13r,5p,17p,
db11: 16p,12r,15r,4p,
db12: 18r,11p,5r,
db2: 14r,18p,6p,
db3: 9p,8r,2r,
db4: 10p,17r,4r,
db5: 9r,12p,0p,
db6: 8p,7r,1r,
db7: 14p,11r,2p,
db8: 1p,13p,10r,
db9: 3r,7p,6r,0r,

Sample shards
blabla-2016.09.12_0 8  p STARTED 546347 390.3mb 10.135.32.20  db6
blabla-2016.09.12_0 8  r STARTED 565703 407.6mb 10.135.35.193 db3
blabla-2016.09.12_0 16 r STARTED 573101 493.9mb 10.135.34.141 db1
blabla-2016.09.12_0 16 p STARTED 536669 370.5mb 10.135.35.41  db11

12 nodes, 1 index, 47 shards, 1 replica
Shards
db1: 15p,34r,25r,45r,27p,11r,39p,3p,
db2: 42p,30p,20r,31r,6p,37r,18p,7r,
db3: 42r,33p,32r,21p,10r,23r,9p,45p,
db4: 13r,24r,46p,34p,10p,35r,22p,
db5: 1r,15r,24p,12p,36p,14r,39r,0p,
db6: 30r,38r,20p,32p,44p,9r,22r,8p,
db7: 38p,1p,2p,4r,14p,26p,27r,17r,
db8: 13p,16r,2r,46r,26r,25p,37p,43r,
db9: 33r,31p,19p,21r,41r,43p,7p,8r,
db10: 28r,40r,5p,29p,19r,6r,41p,17p,
db11: 28p,40p,16p,5r,29r,4p,44r,18r,
db12: 12r,36r,35p,23p,11p,3r,0r,

Sample iostat
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    71.73    4.15   49.15    33.17  3739.81   141.58     0.28    5.24    0.51    5.64   0.38   2.03
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00  1027.20    0.20  563.60     1.60 30052.00   106.61     2.10    3.73    0.00    3.73   0.33  18.44
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00   867.60    0.00  407.60     0.00 51499.20   252.69     4.19   10.27    0.00   10.27   0.37  15.06
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00   424.20    0.00  296.00     0.00 20040.80   135.41     1.74    5.88    0.00    5.88   0.40  11.80
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00   661.20    0.00  466.80     0.00 11922.40    51.08     0.19    0.41    0.00    0.41   0.36  16.66

Sample shards
blabla-2016.09.12_0 42    r      STARTED 574413 399.1mb 10.135.35.193 db3
blabla-2016.09.12_0 28    p      STARTED 557903 399.9mb 10.135.35.41  db11
blabla-2016.09.12_0 28    r      STARTED 557903 394.9mb 10.135.36.136 db10
blabla-2016.09.12_0 33    r      STARTED 412963 286.8mb 10.135.32.60  db9

12 nodes, 1 index, 83 shards, 1 replica
Shards
db1: 39p,24r,33r,74r,69p,51p,23r,8p,27p,15p,3p,11r,67r,0r,
db2: 40r,42p,69r,7r,50r,56r,18p,65p,79r,77p,17r,29r,30p,54p,
db3: 78r,57p,32r,33p,80p,53r,9p,21p,68p,20r,59r,45p,43r,72r,
db4: 82r,81p,58p,22p,35r,34p,70p,21r,75r,64r,44r,54r,46p,
db5: 24p,13r,36p,37r,25r,60p,12p,68r,1r,46r,62r,72p,48p,0p,
db6: 32p,42r,19r,31r,58r,9r,56p,71r,79p,77r,20p,52r,44p,67p,
db7: 74p,38p,50p,73r,60r,26p,8r,61r,10r,15r,14p,2p,62p,3r,
db8: 13p,36r,37p,73p,25p,12r,6p,47r,1p,49p,26r,61p,10p,2r,
db9: 78p,57r,19p,31p,66p,7p,51r,41r,18r,70r,6r,55p,30r,43p,
db10: 39r,5p,80r,28r,53p,4r,16r,41p,76p,64p,17p,29p,49r,63r,
db11: 40p,5r,38r,28p,66r,4p,16p,76r,75p,52p,63p,27r,14r,48r,
db12: 82p,81r,22r,35p,34r,65r,71p,59p,47p,23p,55r,45r,11p,

Sample shards
blabla-2016.09.12_0 82    r      STARTED 100491  88.3mb 10.135.32.114 db4
blabla-2016.09.12_0 82    p      STARTED 100491  91.3mb 10.135.35.169 db12
blabla-2016.09.12_0 39    p      STARTED 178524   145mb 10.135.34.141 db1
blabla-2016.09.12_0 39    r      STARTED 178524 144.8mb 10.135.36.136 db10
blabla-2016.09.12_0 40    p      STARTED 289205   220mb 10.135.35.41  db11
blabla-2016.09.12_0 40    r      STARTED 289205 216.7mb 10.135.35.108 db2

12 nodes, 10 indexs, 5 shards each, 1 replica
Shards
db1: 4/4r,7/3p,6/1p,1/3p,0/3p,3/2r,2/0r,9/2r,8/0r,
db2: 5/4p,4/2p,7/4r,6/2r,1/4r,3/0p,9/0p,
db3: 5/2r,4/0r,6/1r,0/3r,3/3p,2/1p,9/3p,8/1p,
db4: 5/0p,7/4p,6/2p,1/4p,0/4p,3/3r,2/1r,9/3r,8/1r,
db5: 5/3r,4/1r,7/0p,1/0p,0/0p,3/4p,2/2p,9/4p,8/2p,
db6: 5/1r,4/4p,6/4r,0/4r,3/2p,2/0p,9/2p,8/0p,
db7: 4/3r,7/2p,6/0p,1/2p,0/2p,3/1r,2/4p,9/1r,8/4p,
db8: 5/4r,4/2r,7/1p,1/1p,0/1p,3/0r,2/3p,9/0r,8/3p,
db9: 5/0r,4/3p,7/3r,6/3r,1/3r,0/2r,3/1p,9/1p,
db10: 5/3p,4/1p,7/2r,6/0r,1/2r,0/1r,2/4r,8/4r,
db11: 5/1p,7/0r,6/3p,1/0r,0/0r,3/4r,2/2r,9/4r,8/2r,
db12: 5/2p,4/0p,7/1r,6/4p,1/1r,2/3r,8/3r,

Sample iostat
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00   103.87    7.07   72.41    45.14  5544.77   140.66     0.40    4.98    0.54    5.41   0.34   2.70
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    62.80    7.40  136.40    30.40 52532.80   731.06     4.47   31.10    0.03   32.79   0.40   5.80
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    73.20    0.00   30.40     0.00  5904.00   388.42     0.04    1.27    0.00    1.27   0.55   1.68
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    40.60    0.20   32.00     0.80  6009.60   373.32     0.05    1.44    0.00    1.45   0.55   1.78
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    44.00    0.00   34.00     0.00  6209.60   365.27     0.04    1.24    0.00    1.24   0.53   1.80
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    44.00    0.00   31.80     0.00  5554.40   349.33     0.04    1.23    0.00    1.23   0.55   1.74
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    45.60    0.00   35.40     0.00  6614.40   373.69     0.05    1.49    0.00    1.49   0.62   2.18
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    55.20    0.00   33.00     0.00  5828.00   353.21     0.04    1.32    0.00    1.32   0.59   1.94
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    94.60    0.20   96.60     0.80 34596.80   714.83     2.65   27.41    0.00   27.47   0.44   4.30
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    45.60    0.20   75.60     0.80 25184.80   664.53     1.55   20.39    0.00   20.45   0.45   3.40
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    45.60    0.00   32.60     0.00  6132.00   376.20     0.04    1.28    0.00    1.28   0.55   1.78
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    57.00    0.00   41.40     0.00  7424.00   358.65     0.05    1.31    0.00    1.31   0.52   2.16
Device:         rrqm/s   wrqm/s     r/s     w/s    rkB/s    wkB/s avgrq-sz avgqu-sz   await r_await w_await  svctm  %util
vda               0.00    40.20    0.00   27.20     0.00  4672.80   343.59     0.03    1.25    0.00    1.25   0.60   1.62

Sample shards
blabla-2016.09.12_5 2     p      STARTED 270216 229.5mb 10.135.35.169 db12
blabla-2016.09.12_5 2     r      STARTED 291290 243.5mb 10.135.35.193 db3
blabla-2016.09.12_5 0     p      STARTED 266065 225.6mb 10.135.32.114 db4
blabla-2016.09.12_5 0     r      STARTED 273731 230.7mb 10.135.32.60  db9
blabla-2016.09.12_4 2     r      STARTED 295275 241.5mb 10.135.36.175 db8
blabla-2016.09.12_4 2     p      STARTED 295275 212.8mb 10.135.35.108 db2
blabla-2016.09.12_4 4     r      STARTED 280898   240mb 10.135.34.141 db1
blabla-2016.09.12_4 4     p      STARTED 265626 345.2mb 10.135.32.20  db6


text:
Q: Can we Call REST api from Azure Serverless Database Stored Procedures Is it possible to call REST Api (Azure Application Insights Api) from Azure Serverless Database Stored Procedures?
It seems, SQL CLR is not available for Azure Serverless Sql Database. Any other options?

A: According to the official document, CLR Stored Procedures are supported only on SQL Database Managed Instances.
At this moment, there's no integration between SQL Database and Event Grid, so your only option is to perform the http request right after the commit operation in your SQL.
https://learn.microsoft.com/en-us/azure/azure-sql/database/features-comparison


text:
Q: Setting Values on a derived class from the base class constructor using Reflection I have two classes like this:
public abstract class MyBase
{
     protected MyBase(){
         Initialize();
     }

     protected IDictionary<string,string> _data;

     private void Initialize() {
         // Use Reflection to get all properties
         // of the derived class (e.g., call new MyDerived() then
         // I want to know the names "Hello" and "ID" here
         var data = GetDataFromBackend(propertyNamesFromDerived);
         _data = data;
     }
}

public class MyConcrete : MyBase
{
     public MyConcrete(){
         // Possibly use Reflection here
         Hello = _data["Hello"];
         ID = new Guid(data["ID"]);
     }

     public string Hello {get;set;}
     public Guid ID {get; set;}
}

As you see, I want the constructor of my base class to know about the properties of the derived class I'm instantiating.
Now, this seems like a huge and big code smell, so let me give some more background about my intentions, maybe there is a better way.
I have a backend system that stores Key/Value Pairs, essentially a Dictionary<string,string>. I want to abstract away working with this backend system in a way where people can create classes whose properties are Keys into the backend system. When they construct this object, it will automatically load the data from that system and initialize all the variables to it.
In other words, I've just reinvented serialization, except that I don't control the backend system and just rather make working with it really painless. I don't want callers to have to call Initialize() after constructing the object, because in 100% of the cases you have to initalize it after constructing.
I don't want to move the initialize code into the Derived Classes, except for string-to-business-object conversion.
Would I have to use a Factory? Or is it considered safe to look at the property names of a derived class in a base constructor? (Don't care about their values and that they aren't initialized, just need the names).
Or is there a better way altogether to provide a facade between a Dictionary of strings and a concrete business object?
Edit: This is .net 3.5, so no System.Dynamic which would make this trivial :(
Edit 2: After looking at the Answers and thinking through this some more, I guess my question really boils down to this now: Is calling GetType().GetProperties() from a base constructor in order to get the Names of Properties and if they are decorated with a certain Attribute safe?

A: Wait, let's stop here for a second and do this properly. It shouldn't be MyBase's responsibility to do this.
So you write a class that manages getting stuff out of the backend for you, and you write a method on that class that is something like
T Get<T>() where T : new()

and you make Get responsible for reading the dictionary out of the backend and using reflection to populate an instance of T. Thus, you say
var concrete = foo.Get<MyConcrete>();

This isn't hard, and it's the right way to do it.
Incidentally, the code for Get is going to look something like
T t = new T();
var properties = typeof(T).GetProperties();
foreach(var property in properties) {
    property.SetValue(t, dictionary[property.Name], null);
}
return t;

where dictionary is your loaded up key/value pairs. It turns out there are more optimal ways to do this, but unless it's a bottleneck I wouldn't worry about it.

A: The better way to do this would be to make the classes use the dictionary directly:
public string Hello {
    get { return (string)base.data["Hello"]; }
    set { base.data["Hello"] = value; }
}

You may want to call TryGetValue in the getter so that you can return a default value if the key isn't there.  (You should probably do that in a separate method in the base class)
You can make a code snippet to make the properties easier to create.
If you don't want to do it this way, you can call GetType().GetProperties() to get PropertyInfo objects for the properties in your class, then call SetValue(this, value).
This will be slow; there are various tricks you can use to speed it up using expression trees, CreateDelegate, or IL generation.

A: Maybe try the Template method pattern

A: Have you considered using an ExpandoObject? With it you can dynamically add properties and inspect them (when serializing for example).

A: I'm not sure if it's what you really should do, but here's what you asked for (put this in Initialize, and you'll get a list of the derived property names):
        var derivedProps = this.GetType().GetProperties();
        var propNames = new List<string>(derivedProps.Select(x => x.Name));

From there, using the PropertyInfos in derivedProps, you can set the properties.

A: You can't really safely do anything to those properties in the base-class constructor anyway as some derived constructor may reset them anyway.  You're much better off doing a two-phased load (e.g. call Initialize explicitly)


text:
Q: The standard discrete metric is a pre-measure Let $F$ be the ring of all finite unions of intervals of the form $(a,b]$ on $(0,1]$ and let $\delta_x$ for $x \in (0,1]$ and for $A \in F$ be the standard discrete metric.
I need to show that $\delta_x$ is a pre-measure on $F$.
Well, the domain of $\delta_x$ is a ring and it maps only to values greater or equal than 0. $\delta_x(\emptyset)=0$ since the empty set doesn't contain any elements hence $x \notin A$.
Now I need to show that
$\delta_x(\bigcup_{i=1}^{\infty}A_i)=\sum_{i=1}^{\infty} \delta_x(A_i)$
I'm not sure how I can achieve this.

A: Assuming the definition of $\delta_x$ is:
$\delta_x(A) = 1$ if $x \in A$,
$\delta_x(A) = 0$ otherwise
Then, if $A_i$ are disjoint elements of $F$ (note: this "disjoint" condition is lacking in your question; perhaps this is what is blocking you?), we want to show that
$\delta_x(\bigcup_{i=1}^{\infty}A_i)=\sum_{i=1}^{\infty} \delta_x(A_i)$

*

*If $\exists j, x \in A_j, \delta_x(A_j)=1$. Then as $A_i$ are disjoint, $\forall i \ne j, x \notin A_i, \delta_x(A_i)=0$. So $\sum_{i=1}^{\infty} \delta_x(A_i)=1$.
For the RHS: $x \in \bigcup_{i=1}^{\infty}A_i$, so $\delta_x(\bigcup_{i=1}^{\infty}A_i) = 1$

*Otherwise $\forall i, x \notin A_i, \delta_x(A_i) = 0, \sum_{i=1}^{\infty} \delta_x(A_i)=0$.
For the RHS: $x \notin \bigcup_{i=1}^{\infty}A_i$, so $\delta_x(\bigcup_{i=1}^{\infty}A_i) = 0$