text:
Q: ValueError: Number of features of the model must match the input (sklearn) I am trying to run a classifier on some movie review data. The data had already been separated into reviews_train.txt and reviews_test.txt. I then loaded the data in and separated each into review and label (either positive (0) or negative (1)) and then vectorized this data. Here is my code:
from sklearn import tree
from sklearn.metrics import accuracy_score
from sklearn.feature_extraction.text import TfidfVectorizer
#read the reviews and their polarities from a given file

def loadData(fname):
    reviews=[]
    labels=[]
    f=open(fname)
    for line in f:
        review,rating=line.strip().split('\t')
        reviews.append(review.lower())
        labels.append(int(rating))
    f.close()

    return reviews,labels

rev_train,labels_train=loadData('reviews_train.txt')
rev_test,labels_test=loadData('reviews_test.txt')

#vectorizing the input
vectorizer = TfidfVectorizer(ngram_range=(1,2))
vectors_train = vectorizer.fit_transform(rev_train)
vectors_test = vectorizer.fit_transform(rev_test)

clf = tree.DecisionTreeClassifier()
clf = clf.fit(vectors_train, labels_train)

#prediction
pred=clf.predict(vectors_test)
#print accuracy

print (accuracy_score(pred,labels_test))

However I keep getting this error:
ValueError: Number of features of the model must match the input.
Model n_features is 118686 and input n_features is 34169

I am pretty new to Python so I apologize in advance if this is a simple fix.

A: The problem is right here:
vectorizer = TfidfVectorizer(ngram_range=(1,2))
vectors_train = vectorizer.fit_transform(rev_train)
vectors_test = vectorizer.fit_transform(rev_test)

You call fit_transform on both the training and testing data.  fit_transform simultaneously creates the model stored in vectorizer then uses the model to create the vectors.  Because you call it twice, what's happening is that vectors_train is first created and the output feature vectors are generated then you overwrite the model with the second call to fit_transform with the test data.  This results in the difference in vector size as you trained the decision tree with different length features in comparison to the test data.
When performing testing, you must transform the data with the same model that was used for training.  Therefore, don't call fit_transform on the testing data - just use transform instead to use the already created model:
vectorizer = TfidfVectorizer(ngram_range=(1,2))
vectors_train = vectorizer.fit_transform(rev_train)
vectors_test = vectorizer.transform(rev_test) # Change here


text:
Q: PL/SQL Return Types of Result Set Variables or Query Do Not Match I am trying to use a GET stored procedure/cursor to show the GAME NAME of a Lottery Game Table I created in a lottery game database.
Here is the code:
CREATE OR REPLACE PROCEDURE GetLotteryGameName (
  p_lgid IN NUMBER,
  p_value out VARCHAR2,
  p_field IN VARCHAR2
)
IS
BEGIN
  SELECT GAMENAME
  INTO p_value
  FROM LOTTERYGAME
  WHERE LOTTERYGAMEID = p_lgid;
END GetLotteryGameName;

CREATE OR REPLACE PACKAGE GETLOTTERYGAMENAMEPKG IS
  PROCEDURE GetLotteryGameName (
    p_lgid IN NUMBER,
    p_value out VARCHAR2,
    p_field IN VARCHAR2
  );

  TYPE per_ref_cursor IS REF CURSOR;
  PROCEDURE GetGameName (p_lgid IN NUMBER, p_ref OUT per_ref_cursor);

END GETLOTTERYGAMENAMEPKG;

CREATE OR REPLACE PACKAGE BODY GETLOTTERYGAMENAMEPKG IS
  PROCEDURE GetLotteryGameName (
    p_lgid IN NUMBER,
    p_value out VARCHAR2,
    p_field IN VARCHAR2
  )
  IS
  BEGIN
    SELECT GAMENAME
    INTO p_value
    FROM LOTTERYGAME
    WHERE LOTTERYGAMEID = p_lgid;
  END GetLotteryGameName;

  PROCEDURE GetName
    (p_lgid IN NUMBER,
     p_ref OUT per_ref_cursor) IS
     BEGIN
      OPEN p_ref FOR
        SELECT GAMENAME
        FROM LOTTERYGAME
        WHERE LOTTERYGAMEID = p_lgid;
    END GetName;

END GETLOTTERYGAMENAMEPKG;

DECLARE
  v_cursor    GETLOTTERYGAMENAMEPKG.per_ref_cursor;
  v_lgid      LOTTERYGAME.LOTTERYGAMEID%TYPE;
  v_gamename  LOTTERYGAME.GAMENAME%TYPE;

BEGIN
  GETLOTTERYGAMENAMEPKG.GetName (p_lgid = 2,
                                 p_ref => v_cursor);
  LOOP
    FETCH v_cursor
    INTO v_lgid, v_gamename;
    EXIT WHEN v_cursor%NOTFOUND;
    DBMS_OUTPUT.PUT_LINE(v_lgid || ',' || v_gamename);
  END LOOP;
  CLOSE v_cursor;
END;

When I run the above declare statement, I get the following error:
06504. 00000 -  "PL/SQL: Return types of Result Set variables or query do not match"
*Cause:    Number and/or types of columns in a query does not match declared
           return type of a result set  variable, or declared types of two Result
           Set variables do not match.

I know there is an error somewhere in this code, I just don't know what I'm looking for, or how to set myself up to avoid future failures like this.
Any help is much appreciated,
Cheers,
FBF

A: As the error says, you SELECT only GAMENAME in your SELECT but attempt to put into v_lgid, v_gamename.
So adding LOTTERYGAMEID to your CURSOR's SELECT
Or Change your anonymous block.
  PROCEDURE GetName
    (p_lgid IN NUMBER,
     p_ref OUT per_ref_cursor) IS
     BEGIN
      OPEN p_ref FOR
        SELECT GAMENAME,LOTTERYGAMEID
        FROM LOTTERYGAME
        WHERE LOTTERYGAMEID = p_lgid;
    END GetName;

A: You should also correct the syntax error in:
GETLOTTERYGAMENAMEPKG.GetName (p_lgid = 2,
                               p_ref => v_cursor);

which should read
GETLOTTERYGAMENAMEPKG.GetName (p_lgid => 2,
                               p_ref => v_cursor);

Share and enjoy.

redpajama_set_name: RedPajamaStackExchange


text:
Q: What are best practices for error handling when writing an API for the iphone? We are writing an API for iphone developers and we don't know what the best practice is for exception handling. We looked into NSError, standard POSIX way, NSException
What is the convention that most APIs use? Which is the most "Objective-C friendly"?

A: +1 for NSError.
I forget where in the Apple docs I read this, but I also recall them encouraging the coding philosophy of "try first, then check for errors," as opposed to "check for validity, then do the operation."  For example, instead of seeing if the network is available before using it, just try to use it and respond to an error if/when you get one back.
I agree with this philosophy for many use cases because (a) it moves validity-checking to the moment of action, so in a sense it's more accurate, and (b, subjective) it's more fun to work with code in this pattern.
To summarize, the suggestion is to use NSError, and to provide immediate feedback with NSError** parameters that accept NULL, to be very friendly to your API-users!  This pattern is also established in several places in Cocoa/Touch; for example the NSString method writeToFile:atomically:encoding:error:.

A: From the Introduction to Exception Programming Topics:

Important: You should reserve the use of exceptions for programming or unexpected runtime errors such as out-of-bounds collection access, attempts to mutate immutable objects, sending an invalid message, and losing the connection to the window server. You usually take care of these sorts of errors with exceptions when an application is being created rather than at runtime.

...

Instead of exceptions, error objects (NSError) and the Cocoa error-delivery mechanism are the recommended way to communicate expected errors in Cocoa applications. For further information, see Error Handling Programming Guide For Cocoa.

So as I understand it, only use exceptions when something is fatally wrong.  Otherwise, use NSError objects.


text:
Q: If controller in jMeter thread group I'm using jp@gc's Ultimate Thread Group and inside the thread group I have a if controller making sure only every other thread/user continues with
(${__threadNum}%2==0)

There seems to be some issue closing the threads though because after the load has been held for the set amount of time I get as many errors as I have threads going into the controller. I'm not sure what they are about and they don't seem to be about the contents of the if controller because I get them even after deactivating everything inside.
I'm on Windows 10 using jMeter 3.2 with Ultimate Thread Group 2.1.
The error messages:
java.lang.StackOverflowError: null
at java.lang.invoke.MethodHandles.insertArguments(Unknown Source) ~[?:1.8.0_131]
at jdk.internal.dynalink.DynamicLinker.createRelinkAndInvokeMethod(DynamicLinker.java:224) ~[nashorn.jar:?]
at jdk.internal.dynalink.DynamicLinker.link(DynamicLinker.java:201) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.linker.Bootstrap.bootstrap(Bootstrap.java:208) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.linker.Bootstrap.createDynamicInvoker(Bootstrap.java:371) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.linker.Bootstrap.createDynamicInvoker(Bootstrap.java:345) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.linker.InvokeByName.<init>(InvokeByName.java:86) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.linker.InvokeByName.<init>(InvokeByName.java:73) ~[nashorn.jar:?]
at jdk.nashorn.internal.objects.Global.<init>(Global.java:96) ~[nashorn.jar:?]
at jdk.nashorn.internal.runtime.Context.newGlobal(Context.java:1111) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine$2.run(NashornScriptEngine.java:350) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine$2.run(NashornScriptEngine.java:346) ~[nashorn.jar:?]
at java.security.AccessController.doPrivileged(Native Method) ~[?:1.8.0_131]
at jdk.nashorn.api.scripting.NashornScriptEngine.createNashornGlobal(NashornScriptEngine.java:346) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine.createGlobalMirror(NashornScriptEngine.java:340) ~[nashorn.jar:?]
at jdk.nashorn.api.scripting.NashornScriptEngine.createBindings(NashornScriptEngine.java:170) ~[nashorn.jar:?]
at org.apache.jmeter.control.IfController$NashornJsEngine.evaluate(IfController.java:123) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.IfController.evaluateCondition(IfController.java:185) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.IfController.next(IfController.java:239) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.GenericController.nextIsAController(GenericController.java:219) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.GenericController.next(GenericController.java:173) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.LoopController.next(LoopController.java:123) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.LoopController.nextIsNull(LoopController.java:151) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.GenericController.next(GenericController.java:168) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.LoopController.next(LoopController.java:123) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.GenericController.nextIsAController(GenericController.java:222) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.GenericController.next(GenericController.java:173) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.LoopController.next(LoopController.java:123) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.LoopController.nextIsNull(LoopController.java:151) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.GenericController.next(GenericController.java:168) ~[ApacheJMeter_core.jar:3.2 r1790748]
at org.apache.jmeter.control.LoopController.next(LoopController.java:123) ~[ApacheJMeter_core.jar:3.2 r1790748]
at... etc etc

Edit: For now I'm abandoning this and just use the vanilla Thread Group since it does not give any errors.

A: There is a known issue with Ultimate plugin and If controller.you can check this in JSR 223 Element and check only the boolean result in If controller. e.g save vars.putObject("myBoolean", isTrue); and check ${myBoolean} as a condition.
EDIT
Better solution, you can check in if controller ${even} and before of it use JSR223 Element with defining even = true/false as String
if (ctx.getThreadNum() % 2 == 0) {
    vars.putObject("even", "true");
    log.info("even true");
} else {
    vars.putObject("even", "false");
        log.info("even false");
}

A: Since JMeter 3.1 it is recommended to use JSR223 Test Elements and __groovy function for any form of scripting in JMeter so I would recommend switching from JavaScript to Groovy and use __groovy() function in your If Controller's "Condition" area like:
${__groovy(ctx.getThreadNum() %2 == 0,)}

See Apache Groovy - Why and How You Should Use It article for more information on Groovy scripting in the context of JMeter tests, benchmarks, best practices, etc.

A: I fixed my problem by removing the if-controller for having every other user/thread make a new call. Instead of having this logic I made it so that only half of the threads are made and their number is instead multiplied by two, having the same effect. This made all types of thread groups work.


text:
Q: Android Camera : Does OS deletes empty file? http://developer.android.com/training/camera/photobasics.html gives a good way of capturing image from camera.
But as per the tutorial it creates a empty file in "external"(can be user defined) location and what if user cancels activity then empty file will still be there. Is this empty file deletion should be taken care by app itself ? or is there a way by which OS can take care (assuming that location is accessible by OS) ?

A:
Is this empty file deletion should be taken care by app itself ?

Yes.

or is there a way by which OS can take care (assuming that location is accessible by OS) ?

Android has no way to know that you want the file to be deleted, unless you delete the file.


text: Q: How can I add ruby code values to disqus javascript variables Here's the default disqus code:


text:
Q: generar figura que cambie de color cada vez que se regenera y funciones extras Estoy haciendo un curso introductorio a js y para finalizarlo debo generar la siguiente figura.
1- Que la figura inicial sea una línea y ésta se va transformando en rectángulo, luego en cuadrado y finalmente desaparece.
2- Hacer que la figura cambie de color cada vez que se genera.
3- Crear una función que cuando el usuario hace un clic en pantalla, cambie el color de la figura y además, en un párrafo se indiquen sus dimensiones (largo y alto).
Tenía estos problemas en un principio
1- La figura cambia de color solo si se recarga la página y no cuando se genera nuevamente.
2- en la función de click, la figura no cambia de color y no me arroja el alto y al ancho, sino que me arroja la posición en positivo y también en negativo, algo así como (210,-210),
Y actualmente arroja

"Uncaught TypeError TypeError: Cannot read properties of null (reading 'getContext')"

o

"numeroAzar is not a function".

El código es el siguiente:

var canvas = document.getElementById("mi canvas");
let ctx = canvas.getContext("2d");
var posicion = 0;
var tamano = 0;
var largo = 1;
var alto = 400;
let color = ["Orange", "Red", "Blue", "Pink", "Green", "Purple", "Brown", "Skyblue", "DeepPink"];
var numeroAzar = Math.floor(Math.random() * color.length);

setInterval(function() {
  ctx.clearRect(0, 0, 400, 400);
  ctx.fillRect(posicion, 0, tamano, 400 - tamano);
  colorAleatorio = color[numeroAzar];
  ctx.fillStyle = colorAleatorio;

  tamano++;
  posicion++;

  if (posicion > 400) {
    posicion = 0;
    largo = 1;
    alto = 400;
    ctx.fillStyle = color[numeroAzar(color.length)];
  }
}, 0);

$("#canvas").click(function() {
  ctx.fillStyle = color[numeroAzar(color.length)];
  $("#distancia").text("El largo de la figura es = " + largo + " y el alto es = " + alto);
});
<!DOCTYPE html>

  <title> Mision JS2 para finalizar curso</title>

  <canvas id="canvas" width="400" height="400"></canvas>

Cualquier ayuda la agradecería!

A: *

*Primer problema detectado: No existe un elemento que tenga este id "mi canvas"

var canvas = document.getElementById("mi canvas");

*

*Segundo problema detectado: No existe una función numeroAzar declarada sino que es una variable, por lo tanto no la puedes usar así:

ctx.fillStyle = color[numeroAzar(color.length)];

*

*Tercer problema detectado: No estás importando correctamente jQuery
src = "https://code.jquery.com/jquery-2.1.0.js"

Por ahora te corrijo esos tres errores, con esto ya no se muestran errores en la consola. Intenta solucionar los demás y regresa a generar una nueva pregunta si tienes más problemas.

var canvas = document.getElementById("canvas");
let ctx = canvas.getContext("2d");
var posicion = 0;
var tamano = 0;
var largo = 1;
var alto = 400;
let color = ["Orange", "Red", "Blue", "Pink", "Green", "Purple", "Brown", "Skyblue", "DeepPink"];
var numeroAzar = Math.floor(Math.random() * color.length);

setInterval(function() {
  ctx.clearRect(0, 0, 400, 400);
  ctx.fillRect(posicion, 0, tamano, 400 - tamano);
  colorAleatorio = color[numeroAzar];
  ctx.fillStyle = colorAleatorio;

  tamano++;
  posicion++;

  if (posicion > 400) {
    posicion = 0;
    largo = 1;
    alto = 400;
    ctx.fillStyle = color[numeroAzar];
  }
}, 0);

$("#canvas").click(function() {
  ctx.fillStyle = color[numeroAzar];
  $("#distancia").text("El largo de la figura es = " + largo + " y el alto es = " + alto);
});
<!DOCTYPE html>

  <title> Mision JS2 para finalizar curso</title>

  <canvas id="canvas" width="400" height="400"></canvas>


text:
Q: Accidentally installed Linux Mint over Windows/Ubuntu. How do I recover data (SSD)? I had Ubuntu and Windows installed on this 480Gb drive (on my laptop) and decided I'd like to try Linux Mint.
One of the options given in the Linux Mint installation Wizard was to delete Ubuntu 15.04 and install Linux Mint in its place.
During the installation, an error occurred and I had to hard restart my laptop. Turning it back on revealed that something was wrong. Booting up Mint from the same USB again showed that the drive now only had 3 partitions.

*

*Fat32 - 512Mb - boot

*ext4 - 438.74Gb

*linux-swap - 7.89Gb

Nothing inside the ext4 partition was from my Windows install.
Did the installation really delete my Windows partition (it seems so)? Did I go about installing Mint incorrectly? And how could I go about recovering any data from my Windows partition (I had nothing on the Ubuntu install)?

A: There might be nothing to recover; mkfs.ext4 executes TRIM by default unless explicitely prevented by making use of the nodiscard option.
               nodiscard
                      Do not attempt to discard blocks at mkfs time.

Try photorec on it, if that doesn't find anything (and no encryption was involved), then there is nothing to be done. The data is dead and gone.

A: If you've only deleted the partition - you stand a better chance of getting your data back. See http://www.dedoimedo.com/computers/linux-data-recovery.html for exmaple.
If you've overwritten data - not just changed your partition table you'll need to use a data carving tool such as scalpel.
You'll get back bits and pieces of a puzzle you'll need to learn how to put together without a filesystem to guide you... Unless you're looking for something specific (like an important document) it's usually not worth the trouble... but can be quite educational.
Good luck!
Similar question:

*

*Retrieve data from free space on 600Go disk after this disk have been dd of=/dev/{this disk} with 4Go data


text:
Q: How to use the value returned from a method     import java.util.Scanner;

public class Movies {
   static Scanner scan = new Scanner(System.in);
   static String movies[] = {"1. IT\tP200", "2. The Battleship Island\tP300", "3. Annabelle Creation\tP180", "4. Woke Up Like This\t100"};
   static String name;
   static int seats=0;
   static int number=0;
    public static void getName(){
        System.out.print("Please enter your Name: ");
        name = scan.nextLine();
        System.out.println("\nWelcome to MOVIEWORLD, " +name);
        getMovieTitle();

    }

public static int getMovieTitle(){

    System.out.println("\nNOW SHOWING");
   for (String movie : movies) {
       System.out.println(movie);
   }
   char choice;
   System.out.print("Would you like to get a ticket? (Y/N)");
   choice= scan.next().charAt(0);
    switch(choice){
        case 'y':
        case 'Y':
            System.out.print("Please select a movie: ");
            number = scan.nextInt();
            System.out.println("You have Selected "+movies[number-1].substring(3,movies[number-1].length()));
            getSeats();
            break;

        case 'n':
        case 'N':
            System.out.println("Thank you!");
            System.exit(0);
            break;
        default:
            getMovieTitle();
            break;
    }
    return number;
}

public static int getSeats(){
    System.out.print("How many seats would you like? ");
    int seat = scan.nextInt();
    System.out.printf("Reserved # of seats is %d ",seat );
    return seat;
}

public static void main(String[] args){
    System.out.println("\tMOVIEWORLD");
    System.out.println("________________________");
    getName();

    int mynum;
    mynum=getMovieTitle();
    int mynum2;
    mynum2=getSeats();
     int mov1 = 200;
     int mov2 = 300;
     int mov3 = 180;
     int mov4 = 100;
     int cost;
     int money;
     int change;
     char c;
     System.out.print("Print Receipt?(y/n)");
     c= scan.next().charAt(0);
     switch(c){
         case 'y':
         case 'Y':
     if(mynum == 1){
         cost=mov1*mynum2;
         System.out.print("Total: Php"+cost);
         System.out.print("Received cash is: Php");
         money=scan.nextInt();
         change=money-cost;
         System.out.print("Your change is: Php"+change);

     }
     else if(mynum == 2){
         cost=mov2*mynum2;
         System.out.print("Total: Php"+cost);
         System.out.print("Received cash is: Php");
         money=scan.nextInt();
         change=money-cost;
         System.out.print("Your change is: Php"+change);
     }
     else if(mynum == 3){
         cost=mov3*mynum2;
         System.out.print("Total: Php"+cost);
         System.out.print("Received cash is: Php");
         money=scan.nextInt();
         change=money-cost;
         System.out.print("Your change is: Php"+change);
     }
     else if(mynum == 4){
         cost=mov4*mynum2;
         System.out.print("Total: Php"+cost);
         System.out.print("Received cash is: Php");
         money=scan.nextInt();
         change=money-cost;
         System.out.print("Your change is: Php"+change);
     }
     break;
         case 'n':
         case 'N':
             System.out.println("Thank you");
             break;

         default:
              System.out.println("Thank you");
              System.exit(0);

}
}
}

I am trying to get the cost, the money received , and the change.  But I am having a trouble in using the returned values in my methods. After selecting how many seats i wanted the program just exits.
This is the values that i would like to use in my main method. First is the number
 System.out.print("Please select a movie: ");
            number = scan.nextInt();
            System.out.println("You have Selected "+movies[number-1].substring(3,movies[number-1].length()));
            getSeats();

        case 'n':
        case 'N':
            System.out.println("Thank you!");
            System.exit(0);
        default:
            getMovieTitle();

    }
    return number;

Second is the seats so i can multiply it with the number.
 public static int getSeats(){
    System.out.print("How many seats would you like? ");
    int seats = scan.nextInt();

    return seats;
}

A: *

*You need a break:
case 'Y':
    System.out.print("Please select a movie: ");
    number = scan.nextInt();
    System.out.println("You have Selected "+movies[number-
        1].substring(3,movies[number-1].length()));
    getSeats();
    break;

*You need to assign the number of seats to the global seats variable that you created in the beginning of the program, rather than a local variable.:
public static int getSeats(){
 System.out.print("How many seats would you like? ");
 seats = scan.nextInt();

 return seats;
}

Update:

*In your updated question, you're capturing the returned values of getMovieTitle() and getSeats() with mynum and mynum2 in the main method, but still calling those methods inside getName() and getMovieTitle() respectively. Just comment those calls:
public static void getName(){
   System.out.print("Please enter your Name: ");
   name = scan.nextLine();
   System.out.println("\nWelcome to MOVIEWORLD, " +name);
   //getMovieTitle();

}

and
case 'Y':
    System.out.print("Please select a movie: ");
    number = scan.nextInt();
    System.out.println("You have Selected "+movies[number-1].substring(3,movies[number-1].length()));
    //getSeats();
    break;


text:
Q: Tangent space to World Space (TBN Matrix) I'm building a renderer using rasterization and depth-buffering in the CPU and now I've included normals maps. Everything works like you can see in the next image:

The issue is that, even that it works, I don't understand WHY! The implementation is against what I think. This is the code to get the normal at each fragment:
const Vector3D TexturedMaterial::getNormal(const Triangle3D& triangle_world, const Vector2D& text_coords) const {
   Vector3D tangent, bitangent;
   calculateTangentSpace(tangent, bitangent, triangle_world);
   // Gets the normal from a RGB Texture [0,1] and maps it to [-1, 1]
   const Vector3D normal_tangent = (Vector3D) getTextureColor(m_texture_normal, m_texture_normal_width, m_texture_normal_height, text_coords);
   const Vector3D normal_world = TangentToWorld(normal_tangent, tangent, bitangent, normal_tangent);

   return normal_world;
}

void TexturedMaterial::calculateTangentSpace(Vector3D& tangent, Vector3D& bitangent, const Triangle3D& triangle_world) const {
  const Vector3D q1 = triangle_world.v2.position - triangle_world.v1.position;
  const Vector3D q2 = triangle_world.v3.position - triangle_world.v2.position;

  const double s1 = triangle_world.v2.texture_coords.x - triangle_world.v1.texture_coords.x;
  const double s2 = triangle_world.v3.texture_coords.x - triangle_world.v2.texture_coords.x;

  const double t1 = triangle_world.v2.texture_coords.y - triangle_world.v1.texture_coords.y;
  const double t2 = triangle_world.v3.texture_coords.y - triangle_world.v2.texture_coords.y;

  tangent = t2 * q1 - t1 * q2;
  bitangent = -s2 * q1 + s1 * q2;

  tangent.normalize();
  bitangent.normalize();
}

My confusion is here:
const Vector3D TexturedMaterial::TangentToWorld(const Vector3D& v, const Vector3D& tangent, const Vector3D& bitangent, const Vector3D& normal) const {
  const int handness = -1; // Left coordinate system
  // Vworld = Vtangent * TBN
  Vector3D v_world = {
    v.x * tangent.x + v.y * bitangent.x + v.z * normal.x,
    v.x * tangent.y + v.y * bitangent.y + v.z * normal.y,
    v.x * tangent.z + v.y * bitangent.z + v.z * normal.z,
  };
  // Vworld = Vtangent * TBN(-1) = V * TBN(T)
  Vector3D v_world2 = {
    v.x * tangent.x   + v.y * tangent.y   + v.z * tangent.z,
    v.x * bitangent.x + v.y * bitangent.y + v.z * bitangent.z,
    v.x * normal.x    + v.y * normal.y    + v.z * normal.z,
  };

  v_world2.normalize();
  // return handness * v_world; --> DOES NOT WORK
  return handness * v_world2; --> WORKS
}

Assuming that I'm working with row vectors:
V = (Vx, Vy, Vz)

      [Tx Ty Tz]
TBN = [Bx By Bz]
      [Nx Ny Nz]

          [Tx Bx Nx]
TBN(-1) = [Ty By Ny] // Assume basis are orthogonal TBN(-1) = TBN(T)
          [Tz Bz Nz]

Then, if T, B and N are the basis vectors of the TBN expressed in the world coordinate system the transformations should be:
 Vworld = Vtangent * TBN
 Vtangent = Vworld * TBN(-1)

But, in my code I am doing exactly the opposite. To transform the normal in tangent space to world space I am multiplying by the inverse of the TBN.
What I am missing or misunderstanding? Is the assumption that T, B and N are expressed in the world coordinate system wrong?
Thank you!

A: Your reasoning is correct - the second version is wrong. A more intuitive way to see that is analyzing what happens when the tangent space normal is (0, 0, 1). In this case, you obviously want to use the triangle normal, which is exactly what the first version should do.
However, you are feeding a wrong parameter:
const Vector3D normal_world = TangentToWorld(normal_tangent,
                                             tangent, bitangent, normal_tangent);

The last parameter needs to be the triangle normal, not the normal you fetch from the texture.


text:
Q: Is correct to use logit link, binomial family in both first and second stage 2SLS? The R package "ivtools" gave this example, but someone told me 2SLS is only applicable to probit link on binary dependent variables.
##---Example 2: logistic model and no covariates---
library(ivtools)
Z <- rbinom(n, 1, 0.5)
X <- rbinom(n, 1, 0.7*Z+0.2*(1-Z))
m0 <- plogis(1+0.8*X-0.39*Z)
Y <- rbinom(n, 1, plogis(psi0*X+log(m0/(1-m0))))
data <- data.frame(Z, X, Y)

#two-stage estimation
fitX.LZ <- glm(formula=X~Z, family="binomial", data=data)
fitY.LX <- glm(formula=Y~X, family="binomial", data=data)
fitIV <- ivglm(estmethod="ts", fitX.LZ=fitX.LZ, fitY.LX=fitY.LX, data=data,
  ctrl=TRUE)
summary(fitIV)


text:
Q: How to query data from timestamp column with delay.? I want a query to get data from a derby table with the timestamp where time value is less than two hours to current time. following query gives and error saying
operator with a left operand type of 'TIMESTAMP' and a right operand type of 'INTEGER' is not supported.
Query:
select * from NEWS WHERE NEWS_DATE < current_timestamp-2

Appriciate any help

A: Here is the answer,
select *from NEWS where {fn TIMESTAMPDIFF( SQL_TSI_MINUTE, NEWS_DATE,current_timestamp)} <120


text:
Q: How to make a textbox appear when turning off a Smartphone? I'm writing a simple app for Android. It's very simple yet, it just take as input a username and a password.
I need to store those user and pwd firstly, then I need to make a textbox asking for those user and password appear when I try to turn off the smartphone.
Could you please help me on how to do it?

A: There is no way to do this reliably.  Even if there was a systemwide shutdown message (and I don't think there is), the user could always just pull the battery.  Or hold the power button for a few seconds to force a reboot.
Even ignoring that-  there's no way to make shutdown wait until a user has entered the info you want.  Even if you could display it, it would just go away and the phone would turn off.  You'd be looking at a custom android os to do this.


text:
Q: How do I remove the line connection between the ellipse? JS Canvas So I am trying to draw a face with Javascript in a canvas and the smile is using ellipse(x, y, rX, rY, rot, start, end. I closed the path (closePath();) and that follow that with a stroke command (stroke();). This draws the ellipse, which looks like a half-circle. But this also draws a stroke which connects the two ends of the half-circle, which I don't want. It looks like this:

var c = document.createElement('canvas');
var ctx = c.getContext('2d');
var w = 500;
var h = 300;

window.onload = function() {
  c.style.backgroundColor = '#aaa';
  c.width = w;
  c.height = h;
  c.tabIndex = '1';
  c.style.outline = 'none';
  c.style.display = 'block';
  c.style.margin = '0 auto';
  c.style.position = 'relative';
  c.style.top = '50px';
  document.body.style.margin = '0';
  document.body.appendChild(c);
}

setInterval(function() {
  ctx.clearRect(0, 0, w, h);

  ctx.beginPath();
  ctx.ellipse(w / 2, h / 2, 30, 35, 0, 0, 2 * Math.PI);
  ctx.closePath();

  ctx.fillStyle = '#cf9454';
  ctx.fill();
  ctx.stroke();

  ctx.beginPath();
  ctx.ellipse(w / 2 - 10, h / 2 - 10, 2, 2, 0, 0, 2 * Math.PI);
  ctx.moveTo(w / 2 + 10, h / 2 - 10);
  ctx.ellipse(w / 2 + 10, h / 2 - 10, 2, 2, 0, 0, 2 * Math.PI);
  ctx.closePath();

  ctx.stroke();
  ctx.fillStyle = '#000';
  ctx.fill();

  ctx.beginPath();
  ctx.ellipse(w / 2, h / 2 + 10, 16, 12, 0, 0, 1 * Math.PI);
  ctx.closePath();

  ctx.stroke();
}, 30);

A: You should simply omit the last closePath() call. Its intention is described in MDN's documentation:

The CanvasRenderingContext2D.closePath() method of the Canvas 2D API attempts to add a straight line from the current point to the start of the current sub-path.

It effectively adds that straight line to the "mouth" shape. So just leave that out:

var c = document.createElement('canvas');
var ctx = c.getContext('2d');
var w = 500;
var h = 140; // reduced to make the smiley appear within the snippet area

window.onload = function() {
  c.width = w;
  c.height = h;
  c.tabIndex = '1';
  c.style.backgroundColor = '#aaa';
  c.style.outline = 'none';
  c.style.display = 'block';
  c.style.margin = '0 auto';
  c.style.position = 'relative';
  c.style.top = '50px';
  document.body.style.margin = '0';
  document.body.appendChild(c);
}

setInterval(function() {
  ctx.clearRect(0, 0, w, h);

  ctx.beginPath();
  ctx.ellipse(w / 2, h / 2, 30, 35, 0, 0, 2 * Math.PI);
  ctx.closePath();

  ctx.fillStyle = '#cf9454';
  ctx.fill();
  ctx.stroke();

  ctx.beginPath();
  ctx.ellipse(w / 2 - 10, h / 2 - 10, 2, 2, 0, 0, 2 * Math.PI);
  ctx.moveTo(w / 2 + 10, h / 2 - 10);
  ctx.ellipse(w / 2 + 10, h / 2 - 10, 2, 2, 0, 0, 2 * Math.PI);
  ctx.closePath();

  ctx.stroke();
  ctx.fillStyle = '#000';
  ctx.fill();

  ctx.beginPath();
  ctx.ellipse(w / 2, h / 2 + 10, 16, 12, 0, 0, 1 * Math.PI);
  //ctx.closePath(); //<----- remove this

  ctx.stroke();
}, 30);

Note that Unicode has characters for smileys. Maybe they are useful for your project? I would also move some of the styling to CSS definitions. The setInterval is currently useless; but I suppose you have it for future purposes.
For example:

var c = document.createElement('canvas');
var ctx = c.getContext('2d');
var w = 500;
var h = 140; // reduced to make the smiley appear within the snippet area

window.onload = function() {
  c.width = w;
  c.height = h;
  c.tabIndex = 1;
  document.body.appendChild(c);
  ctx.font = "70px Verdana";
  ctx.textAlign = "center";
  ctx.textBaseline = "middle";
  setInterval(function() {
    ctx.clearRect(0, 0, w, h);
    ctx.fillText("", w/2, h/2);
  }, 30);
}
canvas {
  background-color: #aaa;
  outline: none;
  display: block;
  margin: 0 auto;
  position: relative;
  top: 50px;
}
body { margin: 0; }


text:
Q: How to add Iframe to my Facebook page I am developing facebook application.I want to add iframe to my facebook page.I don't have any idea ,how to do it.I know we can not create a page using graph api or any api in facebook.

A: All the information you need is here - found by a quick google search:
http://developers.facebook.com/docs/reference/fbml/iframe/

A: You'll need your own hosting server which have HTTPS, and create your page with the language that they support and place the link points directly to the folder to facebook app setting. make sure your width does not go beyonds 520px for facebook custom tab page. if apps u can go up to 760px.
Hope that helps


text:
Q: How to configure ordering for Spring Configuration Classes I am trying to have 2 configuration files. say ConfigA and ConfigB. I want Config B to be called first where it is calling ConfigA all time which is causing me some depenedency issues.
I tried @DependsOn @Order @Import but nothing seems to be helpful. Any help here would be appreciated.
Thanks.


text:
Q: Twitter streaming api with linq2twitter / tweetinvi I want to create C# Web API project to
i.) get all the status tweets of userID   (need help/guidance, as data could be large, so what are my options)
ii.) store them to Azure DB      (hoping, I can achieve this)
iii.) get DB values and display JSON output    (hoping, I can achieve this)
I am trying to achieve this by using Streaming API and LinqToTwitter but no luck.
a. StreamingType.Filter : It is not returning desired status object or returns null, if I use StreamingType.Filter , Track == userName and Follow == userID
b. StatusType.User :  It returns object if I use StatusType. But I am not supposed to use StatusType.
Can I achieve this using Tweetinvi if not using LinqToTwitter. Please help me achieve this.
Thanks. Appreciate your time.

A: Web API is inherently stateless, so a stream won't work, regardless of LINQ to Twitter, any other tool, or writing it yourself. On every request, the stream starts and stops. This doesn't make sense because a stream is intended as a persistent and long running connection. Twitter has guidance on using their stream API and it seems like bad things could happen if you reconnect too many times.
For Web API, you're better off using a Search query:
        var searchResponse =
            await
            (from search in twitterCtx.Search
             where search.Type == SearchType.Search &&
                   search.Query == "\"LINQ to Twitter\""
             select search)
            .SingleOrDefaultAsync();

I have a blog post on Working with Timelines with LINQ to Twitter that can help you manage the query via SinceID and MaxID parameters. It's based on the previous version of LINQ to Twitter, but the concepts remain the same. There are demos in the Downloadable Source Code for paging with other query types.
Other Notes:

*

*On the TwitterContext instance, you can read the RawResult property
if you need the JSON from the query. JSON.NET is very useful here too.

*On Azure, check out DocumentDB,which has a nice set of APIs,
including LINQ.

A: With tweetinvi you can easily do this by just using the following code
var fs = Stream.CreateFilteredStream();
fs.AddFollow(userId);
fs.MatchingTweetReceived += (sender, args) => { Console.WriteLine(args.Tweet); };
fs.StartStreamMatchingAllConditions();


text:
Q: how to get duration of video using ffmpeg? I write this command in commandPrompt but that can not get Duration

ffmpeg  -i d:\12.flv 2>&1 | grep \"Duration\"

I have this error
'grep ' is not recognized as an internal or external command, operable programe or batch file
What is problem?

A: best way I have found is:
ffmpeg -i input.ext 2>&1 | find "Duration"

now, that gives you the duration start and bitrate line.
hope this helps.


text:
Q: Ububntu 13.10 x64 SWAP I'm using ubuntu 13.10 64 bit. Established a system by default, compliance, sisema allocated to SWAP 35Gb file.
How to reduce size SWAP file?

A: Here are the steps:

*

*Start GParted in live Ubuntu session (if you need to make changes to your Ubuntu partitions; otherwise you could do it from the desktop session too),

*Right click on swap partition and select swapoff,

*Shrink the swap to the size that you want. To do this, right click the swap partition and select Resize/Move option, and drag the slider left/right whichever seems appropriate (also make sure the unallocated space should be in that side which would allow an easy merge with other partitions). And then click the Resize/Move button,

(it would have been easy if you included the partition layout that you have. If you're not sure about this step, you could edit your question to include a snapshot of partition layout or the output of the command sudo fdisk -l)

*Then unmount (if they're mounted) the partition in which you plan to merge the unallocated space just created and again with resize/move option, extend the slider to cover up all the unallocated space,

*After specifying such move and resize options, from the menu select Edit -> Apply All Operations or click the apply button in the toolbar. The resize and particularly move option will take a long time depending on the size of the files to be moved. So wait patiently.


text:
Q: How to add 1 pixel of vert-spacing to an Emacs font? I don't know if this can easily be done with Emacs (read below for my hack in case there's no easy way to do this) so...
How can I add one pixel of vertical-spacing between each line under Emacs?
I know that screen real estate is precious but I'm using a "custom" font (ProggyFont) and, under IntelliJ IDEA, I can modify the vertical spacing to something that I like.
Under Emacs, however, I find the text hard to read because the pixels from one line are too close from the pixel of another line, so I'd like to add one "one pixel" empty vertical line between every line.  Can this be done simply?
If there's no "simple way", how do I take a "x by y" bitmap font and turn it into a "x by (y+1)" bitmap font?  I don't mind using a font editor: been there, done that.  But I don't know exactly everything that would be involved.

A: Check out the line-spacing variable, e.g.
(setq line-spacing 0.2)

From the docs:
Additional space to put between lines when displaying a buffer.
The space is measured in pixels, and put below lines on window systems.
If value is a floating point number, it specifies the spacing relative
to the default frame line height.  A value of nil means add no extra space.


text:
Q: How can I detect artificial mouse movements? We wrote a game where you shoot targets as quickly as you can, and someone wrote a program to automatically shoot the targets (via simulated mouse movement/clicks).
How can I detect this? I thought of monitoring mouse speed, etc., but it seems too easy to get around. If it helps, the game runs on Windows / is written in C++. Is there no way to just tell that the movement isn't coming from hardware?

A: See How to detect if mouse click is legit or automated? Essentially it says that it can't be done reliably, because of several reasons, one of which is that the programmer will find a way to get around whatever you try to do.
As suggested, heuristics seem to be a viable option. Monitor variable mouse speed, miss rates and accuracy, pauses, sudden jumps, et c. The better the heuristics get, the more the programmer will have to make his bot closer to a real player, and the less successful he gets.
PS: Even for well known shooter games like Counter Strike, there are hacks that shoot everything perfectly for you , so they haven't figured out how / don't want to stop it either.


text:
Q: Prepend element and add function to it How to make working the function to a prepended element? Sorry if the question sounds wrong. Now Im using this code:
function listOfProduct() {
    $('.list-of-product li').prepend('<input type="checkbox" name="list-of-product">');
    $('.list-of-product li').each(function (i) {
        i++ ;
        $(this).prev('input').attr('id', 'list-of-product-' + i);
        $(this).prop('for', 'list-of-product-' + i);
    });
}

I add to
 these elements which are inside the prepend()and after that I want dynamicaly add specific attributes. Now its not working. Can anyone explain me why?

A: you can't have an <input> as previous element to an
...they are children of the

try:
$('.list-of-product li').each(function (i) {
        i++ ;
        $(this).find('input').attr('id', 'list-of-product-' + i);
        $(this).find('label').prop('for', 'list-of-product-' + i);
});

A: I believe, in the second one, you need to use $('.list-of-product li label') because, for is for . And also, the label's previous is the <input />.
Try this:
function listOfProduct() {
    $('.list-of-product li').prepend('<input type="checkbox" name="list-of-product">');
    $('.list-of-product li label').each(function (i) {
        i++ ;
        $(this).prev('input').attr('id', 'list-of-product-' + i);
        $(this).attr('for', 'list-of-product-' + i);
    });
}


text:
Q: How can I read from unmanaged memory in C#? I'd like to create Foo objects in C# from an unmanaged array of Foo structs created in C++.
This is how I think it should work:
On the C++ side:
extern "C" __declspec(dllexport) void* createFooDetector()
{
    return new FooDetector();
}

extern "C" __declspec(dllexport) void releaseFooDetector(void* fooDetector)
{
    FooDetector *fd = (FooDetector*)fooDetector;
    delete fd;
}

extern "C" __declspec(dllexport) int detectFoo(void* fooDetector, Foo **detectedFoos)
{
    FooDetector *fd = (FooDetector*)fooDetector;
    vector<Foo> foos;
    fd->detect(foos);

    int numDetectedFoos = foos.size();
    Foo *fooArr = new Foo[numDetectedFoos];
    for (int i=0; i<numDetectedFoos; ++i)
    {
        fooArr[i] = foos[i];
    }

    detectedFoos = &fooArr;

    return numDetectedFoos;
}

extern "C" __declspec(dllexport) void releaseFooObjects(Foo* fooObjects)
{
    delete [] fooObjects;
}

On C# side:
(I ommitted some fancy code making it possible to call the C++ functions from within C# for better readability);
List<Foo> detectFooObjects()
{
    IntPtr fooDetector = createFooDetector();

    IntPtr detectedFoos = IntPtr.Zero;
    detectFoo(fooDetector, ref detectedFoos);

    // How do I get Foo objects from my IntPtr pointing to an unmanaged array of Foo structs?

    releaseFooObjects(detectedFoos);

    releaseFooDetector(fooDetector);
}

But I don't know how to retrieve the objects from the IntPtr detectedFoos. It should be possible somehow...
Any hints?
UPDATE
Let's assume, Foo is a simple detection rectangle.
C++:
struct Foo
{
    int x;
    int y;
    int w;
    int h;
};

C#:
[StructLayout(LayoutKind.Sequential)]
public struct Foo
{
    public int x;
    public int y;
    public int width;
    public int height;
}

Is it possible to read from unmanaged memory and create new managed objects from it before releasing the unmanaged memory?
I don't know how may Foo objects will be detected, so I don't know, how much memory to allocate in C# before calling detectFoo(). That's why I alloc/free memory in C++ and just pass a pointer to it. But somehow I can't retrieve the detectedFoos pointer address under C#. How do I do that?

A: You must re-declare Foo in your C# project. Assuming you know the count of Foos and the value of sizeof(Foo) you should be able to use System.Runtime.Interopservices.Marshal.PtrToStructure() to retrieve your Foo structures one at a time.

A: You have to define your struct again in C#, and it depends on your stuct. Your struct have to be blitable (the memory layout of the C# struct ave to be the same as it is for the C struct)
Have a look at "Marshalling structs"
Or post your real "Foo" struct and i can show you the C# version
UPDATE:
Because your struct seems to be blitable, you can simple cast the pointer to unmanaged memory to a pointer to the struct defined in c#:
If it is ok for your application to use unsafe code you can write:
unsafe List<Foo> detectFooObjects()
{
 List<Foo> res = new List<Foo>()
IntPtr fooDetector = createFooDetector();

IntPtr detectedFoos = IntPtr.Zero;
int nNumFoos = detectFoo(fooDetector, ref detectedFoos );
for(int i=0;i<nNumFoos;i++)
{
   Foo** ppDetectedFoos = detectedFoos.ToPointer();

   Foo* pFoo = *ppDetectedFoos
   res.Add(*pFoo); //copies the struct because is a struct
   ppDetectedFoos++:
}

releaseFooObjects(detectedFoos);

releaseFooDetector(fooDetector);
return res;
}

A: I ended up solving my problem by using a C++/CLI wrapper class.


text:
Q: How to install xps package for R 3.0.3 I am trying to install the xps package from http://www.bioconductor.org/packages/release/bioc/html/xps.html
for R 3.0.3 on Windows 8.1 x64.
When I try:
source("http://bioconductor.org/biocLite.R")
biocLite("xps")

I get the following messages:
BioC_mirror: http://bioconductor.org
Using Bioconductor version 2.13 (BiocInstaller 1.12.0), R version 3.0.3.
Installing package(s) 'xps'
package 'xps' is available as a source package but not as a binary
Warning message:
package 'xps' is not available (for R version 3.0.3)

So I try installing by downloading the package source for xps
When I try to install it I get the following message:
* installing *source* package 'xps' ...
testing for presence of ROOT...
perl: not found
   found  of ROOT in directory C:\root\/bin...OK
** libs
  running 'src/Makefile.win' ...
Syntax error: Unterminated quoted string
Syntax error: Unterminated quoted string
g++ -pipe -mwindows  -I/include -include w32pragma.h -O2 -DWIN32 -c TMLMath.cxx
cc1plus.exe: fatal error: w32pragma.h: No such file or directory
compilation terminated.
make: *** [TMLMath.o] Error 1
Warning: running command 'make --no-print-directory -f "Makefile.win"' had status 2
ERROR: compilation failed for package 'xps'
* removing 'D:/Program Files/R/R-3.0.3/library/xps'

A: The xps landing page says that xps is not available for 64-bit windows. If you run 32-bit R you'll be able to install the binary with biocLite.


text:
Q: SPF Exists and Redirect I've been helping a client with their email system and realised that their webmaster entered the following as their SPF record.
v=spf1 exists:%{i}._spf.somedomain.com redirect=_spf.somedomain.com ?all

I've looked into the exists and redirect options. From what I can tell these mean that all emails sent "from" their domain would come through as authenticated with SPF?

A: The first part:
exists:%{i}._spf.somedomain.com

says insert the IP address, say 1.2.3.4 for example, giving:
exists:1.2.3.4._spf.somedomain.com

which says, if that DNS 'A' lookup works, it is a pass.
Having both a redirect and an all is kind of odd.
Redirect happens if everything else fails (which is why it should always be at the end of the SPF record), but all never fails to match.
If the all wasn't there the redirect:
redirect=_spf.somedomain.com

would says go fetch that SPF record process it.


text:
Q: How to configure spring lemon to send emails via Sendgrid? I successfully sent emails via sendgrid's SMTP api, without change to my spring-lemon code. I did it just by configuring environment variables on cloudfoundry.
I would now like to use sendgrid java library
I then created the following class
    SendGrid sendgrid = new SendGrid('api_key');

SendGrid.Email email = new SendGrid.Email();
email.addTo("example@example.com");
email.setFrom("other@example.com");
email.setSubject("Hello World");
email.setText("My first email with SendGrid Java!");

try {
  SendGrid.Response response = sendgrid.send(email);
  System.out.println(response.getMessage());
}
catch (SendGridException e) {
  System.err.println(e);
}

How do I get spring-lemon to use this class instead of SmtpMailSender ?

A: Having your custom implementation of MailSender, and configuring that as a bean should suppress Spring Lemon's SmtpMailSender configuration, because Spring Lemon's MailConfiguration class is annotated with @ConditionalOnMissingBean(MailSender.class). (Refer page 79 of the blueprint book - Allowing developers to provide their implementations)
@ConditionalOnMissingBean is notorious, but I had tested it to be working in this case.


text:
Q: Is there a continuous, or smooth, generalization of the iterated logarithm $\log^* n$? I was wondering about the properties of certain classes of functions related to algorithmic runtimes in this post.
So I know that $n!$ has a continuous/smooth generalization to the gamma function. Is there a continuous/smooth generalization of the iterated logarithm $\log_*n$?

A: Let $f(x)$ be smooth s.t. $f(0) = 1$, $f(x) = 0$ if $|x| > 1$ - bump function, for example $f(x) = \exp(-\frac{1}{1 - x^2})$ if $|x| < 1$ and $f(x) = 0$ otherwise.
Then $g(x) = \sum\limits_{n=1}^\infty \log^*n \cdot f(x - n)$ (this series has at most one non-zero term for any given $x$, so convergence isn't an issue) is smooth extension of iterated logarithm: $g(n) = \log^* n$. It's quite useless, however.
You may also be interested in super logarithm - it has the same asymptotic, $\log^*n = \lceil \operatorname{slog}n\rceil$, and it has analytic extension. For details, check Uniqueness of Analytic Abel Functions in
Absence of a Real Fixed Point by Trappman, Kouznetsov and references from it.


text:
Q: Voice Authentication Libraries for android I am making an app with needs to identify the user through his/her voice to authenticate that person.. I have searched google but it either gives me voice recognition or speech recognition tutorials.. Is it possible to perform Voice authentication in android ?
Please Advice.
Thanks in advance !! :)

A: You can use ViGo library for voice biometrics.


text:
Q: Pandas measure elapsed time since a condition I have the following dataframe:
               Time   Work
2018-12-01 10:00:00     Off
2018-12-01 10:00:02     On
2018-12-01 10:00:05     On
2018-12-01 10:00:06     On
2018-12-01 10:00:07     On
2018-12-01 10:00:09    Off
2018-12-01 10:00:11    Off
2018-12-01 10:00:14     On
2018-12-01 10:00:16     On
2018-12-01 10:00:18     On
2018-12-01 10:00:20    Off

I would like to creat a new column with the elapsed time since the device started working.
               Time   Work    Elapsed Time
2018-12-01 10:00:00    Off               0
2018-12-01 10:00:02     On               2
2018-12-01 10:00:05     On               5
2018-12-01 10:00:06     On               6
2018-12-01 10:00:07     On               7
2018-12-01 10:00:09    Off               0
2018-12-01 10:00:11    Off               0
2018-12-01 10:00:14     On               3
2018-12-01 10:00:16     On               5
2018-12-01 10:00:18     On               7
2018-12-01 10:00:20    Off               0

How can I do it?

A: IIUC first with transform
(df.Time-df.Time.groupby(df.Work.eq('Off').cumsum()).transform('first')).dt.seconds
Out[1090]:
0     0
1     2
2     5
3     6
4     7
5     0
6     0
7     3
8     5
9     7
10    0
Name: Time, dtype: int64

A: You could use two groupbys. The first calculates the time difference within each group. The second then sums those within each group.
s = (df.Work=='Off').cumsum()
df['Elapsed Time'] = df.groupby(s).Time.diff().dt.total_seconds().fillna(0).groupby(s).cumsum()

Output
                  Time Work  Elapsed Time
0  2018-12-01 10:00:00  Off           0.0
1  2018-12-01 10:00:02   On           2.0
2  2018-12-01 10:00:05   On           5.0
3  2018-12-01 10:00:06   On           6.0
4  2018-12-01 10:00:07   On           7.0
5  2018-12-01 10:00:09  Off           0.0
6  2018-12-01 10:00:11  Off           0.0
7  2018-12-01 10:00:14   On           3.0
8  2018-12-01 10:00:16   On           5.0
9  2018-12-01 10:00:18   On           7.0
10 2018-12-01 10:00:20  Off           0.0

A: Using a groupby, you can do this:
df['Elapsed Time'] = (df.groupby(df.Work.eq('Off').cumsum()).Time
                      .transform(lambda x: x.diff()
                                 .dt.total_seconds()
                                 .cumsum())
                      .fillna(0))

>>> df
                  Time Work  Elapsed Time
0  2018-12-01 10:00:00  Off           0.0
1  2018-12-01 10:00:02   On           2.0
2  2018-12-01 10:00:05   On           5.0
3  2018-12-01 10:00:06   On           6.0
4  2018-12-01 10:00:07   On           7.0
5  2018-12-01 10:00:09  Off           0.0
6  2018-12-01 10:00:11  Off           0.0
7  2018-12-01 10:00:14   On           3.0
8  2018-12-01 10:00:16   On           5.0
9  2018-12-01 10:00:18   On           7.0
10 2018-12-01 10:00:20  Off           0.0

A: A numpy slicy approach
u, f, i = np.unique(df.Work.eq('Off').values.cumsum(), True, True)
t = df.Time.values

df['Elapsed Time'] = t - t[f[i]]
df

                  Time Work Elapsed Time
0  2018-12-01 10:00:00  Off     00:00:00
1  2018-12-01 10:00:02   On     00:00:02
2  2018-12-01 10:00:05   On     00:00:05
3  2018-12-01 10:00:06   On     00:00:06
4  2018-12-01 10:00:07   On     00:00:07
5  2018-12-01 10:00:09  Off     00:00:00
6  2018-12-01 10:00:11  Off     00:00:00
7  2018-12-01 10:00:14   On     00:00:03
8  2018-12-01 10:00:16   On     00:00:05
9  2018-12-01 10:00:18   On     00:00:07
10 2018-12-01 10:00:20  Off     00:00:00

We can nail down the integer bit with
df['Elapsed Time'] = (t - t[f[i]]).astype('timedelta64[s]').astype(int)
df

                  Time Work  Elapsed Time
0  2018-12-01 10:00:00  Off             0
1  2018-12-01 10:00:02   On             2
2  2018-12-01 10:00:05   On             5
3  2018-12-01 10:00:06   On             6
4  2018-12-01 10:00:07   On             7
5  2018-12-01 10:00:09  Off             0
6  2018-12-01 10:00:11  Off             0
7  2018-12-01 10:00:14   On             3
8  2018-12-01 10:00:16   On             5
9  2018-12-01 10:00:18   On             7
10 2018-12-01 10:00:20  Off             0

A: You can use groupby:
# df['Time'] = pd.to_datetime(df['Time'], errors='coerce') # Uncomment if needed.
sec = df['Time'].dt.second
df['Elapsed Time'] = (
    sec - sec.groupby(df.Work.eq('Off').cumsum()).transform('first'))

df
                  Time Work  Elapsed Time
0  2018-12-01 10:00:00  Off             0
1  2018-12-01 10:00:02   On             2
2  2018-12-01 10:00:05   On             5
3  2018-12-01 10:00:06   On             6
4  2018-12-01 10:00:07   On             7
5  2018-12-01 10:00:09  Off             0
6  2018-12-01 10:00:11  Off             0
7  2018-12-01 10:00:14   On             3
8  2018-12-01 10:00:16   On             5
9  2018-12-01 10:00:18   On             7
10 2018-12-01 10:00:20  Off             0

The idea is to extract the seconds portion and subtract the elapsed time from the first moment the state changes from "Off" to "On". This is done using transform and first.
cumsum is used to identify groups:
df.Work.eq('Off').cumsum()

0     1
1     1
2     1
3     1
4     1
5     2
6     3
7     3
8     3
9     3
10    4
Name: Work, dtype: int64

If there's a possibility your device can span multiple minutes while in the "On", then, initialise sec as:
sec = df['Time'].values.astype(np.int64) // 10e8

df['Elapsed Time'] = (
    sec - sec.groupby(df.Work.eq('Off').cumsum()).transform('first'))

df
                  Time Work  Elapsed Time
0  2018-12-01 10:00:00  Off           0.0
1  2018-12-01 10:00:02   On           2.0
2  2018-12-01 10:00:05   On           5.0
3  2018-12-01 10:00:06   On           6.0
4  2018-12-01 10:00:07   On           7.0
5  2018-12-01 10:00:09  Off           0.0
6  2018-12-01 10:00:11  Off           0.0
7  2018-12-01 10:00:14   On           3.0
8  2018-12-01 10:00:16   On           5.0
9  2018-12-01 10:00:18   On           7.0
10 2018-12-01 10:00:20  Off           0.0


text:
Q: Problem loading an tfidf object with pickle I have an issue with pickle:
from a previous job, I created an sklearn tfidfvectorizer object and I saved it thanks to pickle.
Her is the code I used to do it :
def lemma_tokenizer(text):
     lemmatizer=WordNetLemmatizer()
     return [lemmatizer.lemmatize(token) for token in
word_tokenize(text.replace("'"," "))]

punctuation=list(string.punctuation)
stop_words=set(stopwords.words("english")+punctuation+['``',"''"]+['doe','ha','wa'])
tfidf = TfidfVectorizr(input='content',tokenizer=lemma_tokenizer,stop_words=stop_words)

pickle.dump(tfidf, open(filename_tfidf, 'wb'))

I saw that if i wan't to load the this tfidf object thanks to pickle, I need to define the function "lemma_tokenizer" before.
So I create the following python script named 'loadtfidf.py' to load the tfidf object :
import pickle
from nltk.stem import WordNetLemmatizer
from nltk.tokenize import word_tokenize

def lemma_tokenizer(text):
    lemmatizer=WordNetLemmatizer()
    return [lemmatizer.lemmatize(token) for token in word_tokenize(text.replace("'"," "))]

tfidf = pickle.load(open('tfidf.sav', 'rb'))

if I run this script the object is well loaded and everything goes well!
BUT then, I create another python script named 'test.py' in the same directory of 'loadtfidf.py' where I simply try to import loadtfidf:
import loadtfidf

And when I try to run this one line I have the following error :
"""Can't get attribute 'lemma_tokenizer' on module 'main' from '.../test.py'"""
I really don't understand why... I don't even know what to try to fix this error... can you help me to fix it?
Thank you in advance for your help !


text:
Q: How do I type a hyphen in iOS 12? You know, in SE markup language in the editor, a row of hyphens is useful.  You can either make a headline by putting a row of hyphens under a short line, or you can create a horizontal rule with a line of hyphens separated by white space.
When I try that in iOS 12, I get this
———
Or this
Headline
———
Note that I have hit "hyphen" six times and gotten 3 dashes.   And it does not work.  No horizontal rule (all the way across). No headline.
The problem is, they're not real hyphen-minuses from 7-bit ASCII.  They are some sort of typographical oddity - em space dash, en space dash, whatever.  I see I can also hold the hyphen key and it will give me the options for em space dash  and en space dash.  None are a hyphen!
How do I tape a plain ASCII hyphen-minus in iOS 12?
I realize this is a bit of an XY, but I need plain hyphens for lots of other things too.
Edit: Forgot to mention, I need to do this on other people's iPads, so it is not my purview to arbitrarily and permanently reconfigure their iPad to my tastes.  Besides I am not opposed to typographical features, I just need to use StackExchange from time to time.

A: If you have the SE app, you can do it easily there, as it's one of the shortcuts on the editing row.
Another option (that also works in-browser), possibly faster than deleting spaces, is:

*

*Type a hyphen

*Copy it

*Paste repeatedly

This will also sidestep the smart punctuation.
(As pointed out in comments...)
For further efficiency, you can copy-paste increasingly longer blocks of hyphens until you get the length you need. Then, once you have a full set, you can copy it once and carry it with you in the clipboard, allowing you to reuse it easily throughout the answer.

A: In addition to what's been mentioned already, you can tap the microphone and say "hyphen hyphen hyphen hyphen hyphen hyphen".

A: Turning off Smart Punctuation (in Settings → General → Keyboard) allows me to type multiple hyphens without them being converted to em-dashes.
(Side note: here's a post by the creator of Markdown about this feature.)

As far as I can tell, this setting has two effects:

*

*Change repeated hyphens to dashes

*Change quotes and apostrophes to smart, locale-aware quotes (e.g., "" will become «» when the language is set to French).

These can't be toggled independently. The Apple help article for Numbers on iPad explicitly says:

Numbers automatically converts double hyphens (--) to dashes (—) and
  converts straight quotation marks to curly quotation marks as you
  type. You can turn this setting off or on at any time.
Note: The setting affects both hyphens and quotation marks—they're
  both either off or on.
[...]
Tip: To use different formatting for specific text, change the
  setting, type the text, then change the setting back.

(Even though it says "Numbers automatically converts [...]," the setting is the same: Settings → General → Keyboard → Smart Punctuation. It's not specific to Numbers.)
This blog post suggests developers can turn this off selectively:

A first step, if using a UITextInputTraits conforming control, would
  be to set smartQuotesType to UITextSmartQuotesTypeNo, and set
  smartDashesType to UITextSmartDashesTypeNo.

If it's only about Markdown, you don't need to change any settings. Alternate syntax is available for both headers and horizontal rules:
# Header 1
## Header 2

- - -
***
____

Gives:

Header 1
Header 2

That last uses underscores (_).

A: If you don't want to turn off Smart Punctuation as suggested in muru's answer, you can type a space between each hyphen then go back and delete the spaces. The hyphens will not be changed into typographic dashes.
The obvious suggestion would be to set up a text replacement in Settings > General > Keyboard > Text Replacement, so that (for example) typing 4dash gave you a sequence of four hyphens, but that doesn't seem to work either, at least on iOS 12.3.1. I tried a couple of different international keyboards and also dictating 'dash'es or 'hyphen's by voice, and none of those got the desired result.
The only other thing I can think of to suggest is to install a third-party keyboard, but I don't use any so I don't know how they interact with Smart Punctuation.


text:
Q: Need floating point precision, GUI gui uses int I have a flow layout. Inside it I have about 900 tables. Each table is stacked one on top of the other. I have a slider which resizes them and thus causes the flow layout to resize too.
The problem is, the tables should be linearly resizing. Their base size is 200x200. So when scale = 1.0, the w and h of the tables is 200.
I resize by a fixed amount each time making them 4% bigger each time. This means I would expect them to grow by 8 pixels each time. What happens is, every few resizes, the tables grow by 9 pixels. I use doubles everywhere. I have tried rounding, floor and ceil but the problem persists. What could I do so that they always grow by the correct amount?
void LobbyTableManager::changeTableScale( double scale )
    {
        setTableScale(scale);
    }

    void LobbyTableManager::setTableScale( double scale )
    {
        scale += 0.3;
        scale *= 2.0;

        std::cout << scale << std::endl;
        agui::Gui* gotGui = getGui();
        float scrollRel = m_vScroll->getRelativeValue();
        setScale(scale);
        rescaleTables();
        resizeFlow();
    ...

    double LobbyTableManager::getTableScale() const
        {
            return (getInnerWidth() / 700.0) * getScale();
        }

    void LobbyFilterManager::valueChanged( agui::Slider* source,int val )
    {
        if(source == m_magnifySlider)
        {

            DISPATCH_LOBBY_EVENT
            {
                (*it)->changeTableScale((double)val / source->getRange());
            }
        }
    }

void LobbyTableManager::renderBG( GraphicsContext* g, agui::Rectangle& absRect, agui::Rectangle& childRect )
    {
        int cx, cy, cw, ch;
        g->getClippingRect(cx,cy,cw,ch);
        g->setClippingRect(absRect.getX(),absRect.getY(),absRect.getWidth(),absRect.getHeight());
        float scale = 0.35f;
        int w = m_bgSprite->getWidth() * getTableScale() * scale;
        int h = m_bgSprite->getHeight() * getTableScale() * scale;

        int numX = ceil(absRect.getWidth() / (float)w) + 2;
        int numY = ceil(absRect.getHeight() / (float)h) + 2;

        float offsetX = m_activeTables[0]->getLocation().getX() - w;
        float offsetY = m_activeTables[0]->getLocation().getY() - h;
        int startY = childRect.getY() + 1;
        if(moo)
        {
            std::cout << "TS: " << getTableScale() << " Scr: " << m_vScroll->getValue() << " LOC: " << childRect.getY() << " H: " << h << std::endl;
        }
    if(moo)
    {
        std::cout << "S=" << startY << ",";
    }
        int numAttempts = 0;
        while(startY + h < absRect.getY() && numAttempts < 1000)
        {
            startY += h;
            if(moo)
            {
                std::cout << startY << ",";
            }

            numAttempts++;
        }

        if(moo)
        {
            std::cout << "\n";
            moo = false;
        }
        g->holdDrawing();
        for(int i = 0; i < numX; ++i)
        {
            for(int j = 0; j < numY; ++j)
            {
                g->drawScaledSprite(m_bgSprite,0,0,m_bgSprite->getWidth(),m_bgSprite->getHeight(),
                    absRect.getX() + (i * w) + (offsetX),absRect.getY() + (j * h) + startY,w,h,0);
            }
        }
        g->unholdDrawing();
        g->setClippingRect(cx,cy,cw,ch);
    }

        void LobbyTable::rescale( double scale )
        {
            setScale(scale);
            float os = getObjectScale();
            double x = m_baseHeight * os;
            if((int)(x + 0.5) > (int)x)
            {
                x++;
            }
            int oldH = getHeight();
            setSize(m_baseWidth * os, floor(x));
    ...

I added the related code. The slider sends a value changed which is multiplied to get a 4 percent increase (or 8 percent if slider moves 2 values etc...) then the tables are rescaled with this.

The first 3 are when the table size increased by 9, the 4th time it increased by 8px. But the scale factor increases by 0.04 each time.
Why is the 4th time inconsistant?
the pattern seems like 8,8,8,9,9,9,8,8,8,9,9,9...
It increases by 1 pixel more for a few and then decreases by 1 ten increases by 1 etc, thats my issue...

A: I still don't see the "add 4%" code there (in a form I can understand, anyway), but from your description I think I see the problem: adding 4% twice is not adding 8%.  It is adding 8.16% (1.04 * 1.04 == 1.0816).  Do that a few more times and you'll start getting 9 pixel jumps.     Do it a lot more times and your jumps will get much bigger (they will be 16 pixel jumps when the size gets up to 400x400).  Which, IMHO is how I like my scaling to happen.


text:
Q: How to set username on tortoisegit dcommit? I set up a svn server using svnserve to test how svn-git works.
When trying to dcommit I run into the problem that the tortoise gui does not give the option to choose the username, it just prompts for the password:
http://img1.uploadscreenshot.com/images/orig/11/31810164510-orig.png
Initially the username shown by the prompt used to be the windows authentication user (Razvan).

A: posting this as a temporary solution, if there is a better one I will accept it:
One solution would be to dcommit from command prompt and set the username:
git svn dcommit --username desiredusername

TortoiseGit will remember the username and password for future dcommits.


text:
Q: Find intersection of 2 large sorted arrays using MapReduce How do you find the intersection of 2 large sorted arrays using MapReduce

A: I don't think MapReduce is the right tool; since your arrays are sorted, you could do what amounts to a merge except that instead of gathering up all of the results, you only keep those that appear in both arrays.  Nice linear algorithm.  But since you asked...
The Map part of MapReduce takes in a set of (key,value) pairs.  So give one where each pair corresponds to a element in one of the arrays, with key being the element's value and the value identifying which array it came from.  Then reduce throws out any key which doesn't have a value from both arrays.  I'll leave dealing with duplicates as an exercise.


text:
Q: How can I resolve CORS problems when accessing the SharePoint-API via AJAX-request? I have setup a Dynamics-Portal for a customer. The customer wants to display images from SharePoint on the Portal.
My idea was using jQuery with Ajax to access the SharePoint-API.
Since my experience with web programming is rather limited, I need help to understand the errors that I'm getting.
After some reading this was my first attempt:
$.ajax({
          url: "https://example.SharePoint.com/_api/web/GetFolderByServerRelativeUrl('/ImageFolder')/Files",
          type: 'GET',
          Accept: "application/json;odata=verbose",
          crossDomain: true,
          contentType: 'application/json;odata=verbose',
          dataType: 'json',
          xhrFields: { withCredentials: true }
        })

This produces the following error:
Access to XMLHttpRequest at 'https://example.SharePoint.com/_api/web/GetFolderByServerRelativeUrl('/ImageFolder')/Files'
    from origin 'https://myDynamicsPortal.com' has been blocked by CORS policy:
    Response to preflight request doesn't pass access control check:
    The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include'.
    The credentials mode of requests initiated by the XMLHttpRequest is controlled by the withCredentials attribute.

Now I change the above Ajax by adding "?callback=?" to the URL. Like this:
url:"https://example.SharePoint.com/_api/web/.../Files?callback=?"

Which seems to do the same as changing:
dataType: 'json'
to
dataType: 'jsonp'

The error is gone but this warning apears instead:
Cross-Origin Read Blocking (CORB) blocked cross-origin response
https://example.SharePoint.com/_api/web/GetFolderByServerRelativeUrl('/ImageFolder')/Files?callback=jQuery13423412342134134_1234123412341234&_=12341341234
with MIME type application/atom+xml.

See https://www.chromestatus.com/feature/5629709824032768 for more details.

The status code is 200 but the error: "JQuery13423412342134134_1234123412341234 was not called" shows up.
What I understood/interpreted from these errors, warnings and my research is this:
Once credentials are necessary the server can no longer use the wildcard for the allowed origins. Since I'm unable to change the SharePoints origin policy I looked for other ways to resolve the problem.
Seemingly the server did not understand that I expected a callback, because I did not configure "jsonp" or "?callback=?". After doing so the error is gone but it appears, that my Portal will not accept the response due to CORB (Cross Origin Read Blocking).
Why does SharePoint suddenly accept my request? (or does it?)
Why do I get a http 200 success - but this error:
"JQuery13423412342134134_1234123412341234 was not called"

together with a parsing error?
Thanks in advance and best regards
Jek

A: Try add the code (support.cors):
$.support.cors = true;

A: Aparently this is not possible in this scenario, since I cannot change the CORS-Settings of SharePoint. The solution seems to be SharePoint add-ins.


text:
Q: How can I check the status of battle.net? I found myself unable to connect to battle.net (the gaming network as opposed to the battle.net website). In this case the problem was with battle.net service. In the future I would like to check if the issue is on my side or if the battle.net service is down.
I was using the battle.net login client.
Specifically, I was unable to log into the battle.net service. I am not interested in any of the game specific servers.
How can I check the status of battle.net?
Is there an official status of the battle.net service available somewhere?

A: Newer versions of the Battle.net desktop client display server maintenance alerts. These alerts seem to be for individual services (eg WoW, Starcraft 2) and might not be visible if the battle.net alert infrastructure itself is down.
If you know of a reliable way of checking the status of Battle.net if the Battle.net alerts aren't working, please post an answer or update this one. (Other possibilities include through a 3rd party eg Twitter, Reddit.)

A: As ChaseC mentionned, there is here and there some Forum "blue" (Blizzard employe) Posts that you can visit to see the service statut of a specific game easely accessible with the lest google skills. Although, you can directly go on your Battle.net desktop application if you have it. There you can see if each of the games or available for play.
If the servers are up but you can't access the games the problem is on your side. Check if something has changed in your network. I don't know your situation and then who has the administration on your router. But contact him/her and ask if something changed. (port forwarding and firewall.. I'm not really aware of those stuff but the chances are he/she will and letting him/her know won't make things worst hey?!
Finnaly, If you have installation or run-time problem or errors, Blizzard actualy provide a very good customer support on their websites. Go give it a try if you feel the need! :P

Hope it will help you!

A: Here is the link for you to check out the server status of diablo 3. :)
http://us.battle.net/d3/en/forum/5394512/


text:
Q: Creating Processes in Linux using fork() Function I've been trying to compile a piece of C code which should create processes using the fork() function.`
#include <stdio.h>
#include <unistd.h>
main()
{
    int n=15, z=20, count=3, mult=1;
    while(count<3)
    {
        if(z!=0)
        {
            z=fork();
            n=n+15;
        }
        else
        {
            z=fork(); n=n+10; mult=mult*n;
        }
        printf(" z=%d   mult=%d",z,mult);
        count=count+1;
    }
}

Compiled with "gcc -Wall -W -Werror main.c -o ProcessCreateC" in the terminal. I'm getting error:
main.c:3:5: error: return type defaults to 'int' [-Werror=return-type]
main.c: In function 'main':
main.c:20:5: error: control reaches end of non-void function [-Werror=return-type]
cc1: all warnings being treated as errors

Since I only have experience compiling in Windows and have little experience with Linux, I have no idea what is causing this. Any ideas??

A: Add return 0;or a similar expression that returns an integer, to the end of your main(), and change main() to int main(), and I think you will find that the code works fine.
When no return type is specified for main(), it defaults to int. Furthermore, with the compiler flags you have enabled, not specifying a type for main() causes an error.

A: The problem is twofold (since all warnings are errors):

*

*main should return int, e.g. actually end with return 0;

*you should be explicit about main returning int, i.e. write int main(, not just main(.

A: You have not mentioned the return type of the main function as void so gcc is defaulting it to an integer return value.
Since GCC follows the ANSI C standard, you have to specify the return type of main as int like:
int main()
{
    //Do stuff
     return 0;
}

It is important to remember standards used by compilers, else you will continue making these mistakes and spend more time debugging rather than doing something productive.


text:
Q: What makes a limit 'go away'? According to this video  $$\lim\limits_{x\to\infty} \frac{11 - e^{-x}}{7} = \frac{11}{7}$$
I understand how this works, I don't understand the limit part though. I know $\lim\limits_{x\rightarrow \infty}{e^{-x}} = 0$, but what makes the limit disappear? I conclude that it disappears either because:
A.
There are no more variables in the equation so no point to having a limit so we just start ignoring it
B.
Is has been used once so it goes away.
Option B seems more likely, but it also it confusing because only one term seemed to be effected by the limit.

A: If we continuously extend the real exponential to have values $e^{+\infty} = +\infty$ and $e^{-\infty} = 0$, then this can be seen as taking the limit of a continuous function, which can be done by simply plugging in the limiting value:
$$\lim_{x\to +\infty} \frac{11 - e^{-x}}{7} = \frac{11 - e^{-(+\infty)}}{7}
= \frac{11 - e^{-\infty}}{7} = \frac{11 - 0}{7} = \frac{11}{7} $$

A: The limit of a constant is just the value of constant, and when $\lim f(x)$ and $\lim g(x)$ both exist they satisfy
$$\lim(f(x)+g(x)) = \lim f(x) + \lim g(x)$$
$$\lim(f(x)g(x)) = \lim f(x) \cdot \lim g(x)$$
In other words, here, you have
$$\lim \frac{11-e^{-x}}{7} = \lim \frac{1}{7} \cdot \lim(11-e^x) = \lim \frac{1}{7}(\lim 11 - \lim e^{-x})$$
Since $\frac{1}{7}$ and $11$ are constant, $\lim e^{-x} = 0$, you get
$$\lim \frac{11-e^{-x}}{7} = \frac{1}{7} \cdot (11 + 0) = \frac{11}{7}$$
(I've left the subscript $x \to \infty$ off the limit signs.)

A: Option (A) is almost right!
Specifically, it is a property of limits that if $c$ is a constant,
\begin{equation*}
\lim_{x\to a}{c}=c.
\end{equation*}
You can prove this using the definition of a limit (that is, using a $\delta$-$\epsilon$ proof).
So $\lim_{x\to\infty}{\frac{11}{7}}=\frac{11}{7}$, having no limit on the right-hand side, just like $\lim_{x\to\infty}{e^{-x}}=0$, having no limit on the right-hand side.

A: I can guess that your doubt comes from a first step that you do in your mind that goes like this: "$\lim_{x\rightarrow \infty}{e^{-x}} = 0$, so I can replace $e^{-x}$ with $0$ in the text and I remain with
$$
\lim_{x\to ∞} \frac{11-0}{7},
$$
then what happens to the limit in this last equation?"
This reflects a common misunderstanding. Repeat after me: in a limit, one cannot replace arbitrary subexpressions with their limit. There is no theorem that says that. If you've been doing that, you are wrong; change your habits.
For an easier example when this doesn't work, $\lim_{x\to 0} x = 0$, but
$$
\lim_{x\to 0} \frac{x+x^3}{x^2} \neq \lim_{x\to 0} \frac{0+x^3}{x^2}.
$$
Clive Newstead's and Ilmari Karonen's answers show some alternative manipulations that are legitimate by theorems.

A: As EPAstor notes, your reason (A) is closer to the truth, but it's not the complete answer.
The reason why $\displaystyle \lim_{x \to \infty} e^{-x} = 0$ implies $\displaystyle \lim_{x \to \infty} \frac{11 - e^{-x}}{7} = \frac{11}{7}$ is that
$$\lim_{x \to \infty} \frac{11 - e^{-x}}{7}
= \frac{\lim_{x \to \infty} 11 - e^{-x}}{7}
= \frac{11 - (\lim_{x \to \infty} e^{-x})}{7}
= \frac{11 - 0}{7}
=  \frac{11}{7}$$
and the reason we can move the limit inside the fraction like that is that the functions
$$z \mapsto 11 - z \quad \text{and} \quad z \mapsto \frac z 7$$
are both everywhere continuous.  It is a rather straightforward consequence of the definition of continuity (prove it!) that, if a function $f$ is continuous at $c = \displaystyle\lim_{x \to a} z(x)$, then
$$\lim_{x \to a} f(z(x)) = f(\lim_{x \to a} z(x)) = f(c).$$

A: First note that
$$ \lim\limits_{x\to\infty} f(x)= f\left(\lim\limits_{x\to\infty} x\right) $$
And
$$ \lim\limits_{x\to\infty} e^{-x}= \lim\limits_{x\to\infty} \frac{1}{e^{x}} =0$$
Therefore
$$\lim\limits_{x\to\infty} \frac{11 - e^{-x}}{7} = \frac{11 - \lim\limits_{x\to\infty} e^{-x}}{7} =\frac{11}{7}$$


text:
Q: Login to webmin with user has no password (SSH) I have an simple Ubuntu 12.04 instance running on AWS EC2
I have webmin installed and accessable, but am presented with a login requiring username and password.
As part of the AWS install, you don't have a "root" user you can access, but an "ubuntu" user with sudo rights. This user does not have a password, access is via SSH key pair
I don't want to set a password for ubuntu user, preferring the security of SSH.
How do I access webmin without needing to enter a password? Is it best I create a new userid with a password that is also a sudoer? Seems a bit daft given that is one reason i want webmin in the first place :-)

A: A slightly updated answer.
Running Ubuntu 20.04 and Webmin 1.99, changepass.pl was actually located in /usr/share/webmin/changepass.pl.  If yours is not in that location, you can run sudo find / -name changepass.pl to find it.
Also, Webmin was setup with username root instead of ubuntu so the correct command to change the Webmin username was:
sudo /usr/share/webmin/changepass.pl /etc/webmin root <your_password>
After running that command I was able to login to the web interface.

A: I also have that same problem when installing webmin on DigitalOcean Droplet. A bit of research shows me that I can change the password in SSH terminal.
Let's say you want your webmin user ubuntu to have password foo:
/usr/libexec/webmin/changepass.pl /etc/webmin ubuntu foo
Now you can login to webmin with your new password.

A: The Webmin wiki has a documentation section where it explains the process of granting users specific per module or system-wide rights. You will also find examples on how to create new webmin users and how to modify existing user privileges. In effect you can bypass the sudo system but at the same time design a more granular per module per user access control system.


text:
Q: EF TPT Creating and Reading I have an order class with has a collection of products...
public class Order
{
    int id { get; set; }
    public virtual ICollection<Product> Products { get; set; }
}

public abstract class Product
{
    int id { get; set; }
}

Derived from product, I have several different types of product...
public class ProductA : Product
{
    public string CustomFieldA {get; set;}
}

public class ProductB : Product
{
    public string CustomFieldB {get; set;}
}

I can add these derived products to the order and save them to the database...
var producta = new ProductA();
producta.CustomFieldA = "abc";
order.Products.Add(product);
order.SaveChanges();

This updates the database correctly.
What I can't then figure out is how I access this data!
Order.Products just contains the base class, how can I check which type of derived class each record in Order.Products is and access, for example, CustomFieldA of any that are ProductA.
I suspect either I'm missing something really obvious, or I've done the first part completely wrong!


text:
Q: Content on contert_placeholder overlaps on footer I'm using asp.net and the contents of my content_place holder overlaps outside my footer
here is the Footer

here is my css:
.footer {
   background-color: orange;
position: absolute;
left: 0;
bottom: 0;
width: 100%;
text-align:center;
clear:both;
 height: 50px;
}

here is the content_place holder css
#content_area
{

       width:80%;
            margin-left:10%;
            margin-right:10%;
            height:100%;
}

How could I make my footer stick in the bottom?or just my make contents stop on overlapping?

A: Give the <body> css a position:relative;
Add to your css:
body {
   position:relative;
   min-height:100%;
   margin:0px;
   padding:0px;
}
html {
   height:100%;
   margin:0px;
   padding:0px;
}

To make the .footer's absolute position be relative to the body.
If that alone didnt help you:
Keep the body css and:
You cannot use the ID of a <asp:ContentPlaceHolder> element for your css design. The reason is that the <asp:ContentPlaceHolder> never gets into the client's browser. This element lives only on the server side, and its purpose is like its name - to be replaced by the content you give it.
To design the contents of your <asp:ContentPlaceHolder> surround it with a <div> element and then apply the css styling on the <div>.
See example:
<div id="content_area_div">
   <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
      <%--Placeholder for the pages--%>
   </asp:ContentPlaceHolder>
</div>

And your css:
#content_area_div
{
   width:80%;
   margin-left:10%;
   margin-right:10%;
   height:100%;
}

In the client side the only thing that will remain is the surrounding div and the content you will push into the <asp:ContentPlaceHolder>
Hope it helps!


text:
Q: HELM: How to convert a string into lower/upper case inside if-else condition? Use case: I have values.yaml where I have a field mode.
Values.yaml
mode: start

or user can enter a value for the field mode in any of the below mentioned ways:
mode: STart or START or sTart

Now, I have a file where I am using an if condition as shown below:
command: {{ if eq .Values.mode "start" }} do this {{ esle }} do that {{ end }}

Now, my challenge is how can I covert the ".Values.mode" into lower alphabets before doing the comparison. I have tried the below mentioned ways:
1.
{{ if eq .Values.mode | lower "start" }} do this {{ esle }} do that {{ end }}

*

{{ if eq lower .Values.mode "start" }} do this {{ esle }} do that {{ end }}

Both of the above methods errored out.
Note: we are using a third-party tool, hence JSON schema check won't help me.

A: lower is a function handed to you in the templates. It has a return value, which you wish to compare to another value.
Simply group the function call of lower with parenthesis:
{{ if eq "start" (lower .Values.mode) }} do this {{ else }} do that {{ end }}


text:
Q: ComboBox item imports info to textbox with dataclass When I select an item in my combobox I want it to show information from my dataclass into my textboxes, so for instance when I select a customer, it inserts his first name / last name and age.
I had this part:
        DataClasses1DataContext db = new DataClasses1DataContext();
        var customer = from employee in db.employees select employee;
        List<employee> myCustomers = customer.ToList();
        cmbKlant.ItemsSource = myCustomers;
        tbxFirstname.DisplayMemberPath = "firstnaam";

But the last part needs to be converted to a string and not show firstname but the actual data, someone knows how to make this work?

A: First of all you should be using a ViewModel with the MVVM pattern. Have a property there with the customers that you bind the ItemsSource to then have another property for the SelectedCustomer that you bind the selectedItem property of the combobox to which will the always contain the seletced item which you then can bind your textboxes to like SlectedCustomer.Firstname etc.


text:
Q: android:adding license to simple hello world application on emulator I want to add license to my application(using LVL) and test the same on the emulator.
I am new to android.
Can anyone help me on this and explain it to me with simple hello world application.
TIA


text:
Q: Purpose of passing parameters in collection in java I see a return method that has parameter like this:
return new HashSet<Books>(bookService.getBookData(Books.class,customer.getVisitingCustomer);

But I am not able to understand the idea of passing Books.class, customer.getVisitingCustomer as parameter. I also sometimes
see more than two parameters?
Can someone explain me the purpose of passing parameters in collection?

A: The code (fixed) is presumably

return new HashSet(bookService.getBookData(Books.class,
        customer.getVisitingCustomer()));

and that involves three operations;

*

*customer.getVisitingCustomer()

*bookService.getBookData(Books.class, <STEP 1>)

*return new HashSet(<STEP 2>)
The first is retrieving a visiting customer from the customer. The second invokes a bookService method that takes Books.class (presumably to perform some form of Object-Relational Mapping). The third then forces the results of that method to be unique (a Set).


text:
Q: IndexError: index 917 is out of bounds for axis 0 with size 11, on npargmax in tensorflow I am using the example here
to classify images. I have 2147 images belonging to 11 classes. I am running the classifier on the batch of images. So far program is going well but I am not able to assign the labels because I am getting the following error on the code: labels_batch=image_labels[np.argmax(result_batch, axis=-1)]

Traceback (most recent call last): > > labels_batch=image_labels[np.argmax(result_batch, axis=-1)]
  IndexError: index 917 is out of bounds for axis 0 with size 11

More information:
My labels are categories = ["Categorical_Boxplot", "Column_Charts", "Dendogram", "Heatmap", "Line_Chart", "Map","Node-Link_Diagram", "Ordination_Scatterplot", "Pie_Chart", "Scatterplot", "Stacked_Area_Chart"]
and here is how I am trying to assign this label to the classifier
image_labels = np.array(categories)

result_batch = classifier_model.predict(image_batch)
labels_batch = image_labels[np.argmax(result_batch, axis=-1)]
labels_batch

result_batch.shape

(32, 1001)

The shape of my data

Image batch shape:  (32, 224, 224, 3)
  Label batch shape:  (32, 11)

I don't know where I am going wrong and how can I fix it? I already tried to append the image_labels to labels_batch instead of assigning it with =. But it did not work.
Classifier:
classifier_url = "https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/2" #@param {type:"string"}
IMAGE_SIZE = hub.get_expected_image_size(hub.Module(classifier_url))
classifier_layer = layers.Lambda(classifier, input_shape=IMAGE_SIZE + [3])
classifier_model = tf.keras.Sequential([classifier_layer])
classifier_model.summary()

A: Your model definition is incomplete. The model from the tutorial has 1001 classes while your model has only 11, so ou should attach a new classfiction head to your model like this.
classifier_url = "https://tfhub.dev/google/imagenet/mobilenet_v2_100_224/classification/2" #@param {type:"string"}
IMAGE_SIZE = hub.get_expected_image_size(hub.Module(classifier_url))
classifier_layer = layers.Lambda(classifier, input_shape=IMAGE_SIZE + [3])
classifier_model = tf.keras.Sequential([classifier_layer, layers.Dense(11, activation='softmax')])
classifier_model.summary()


text:
Q: Convert bit sequence to uint32_t in c++ User specifies register (LFSR) length with integer as a parameter for a function, for example he enters number 5. I need to initialize this 5-bit length LFSR with all 1 bits (for length 5 it will be 11111) and get a seed mask in a format uint32_t - for 5-length register it will be 0x0001f.
What is the best way to get mask 0x0001f for 5 bit length register when a user enters only length of the register as an integer number 5?

A: To generate a mask of n bits (where n < 32):
uint32_t mask = (1U << n) - 1U;

Explanation: consider the example where n = 5:
1U << n = 1U << 5 = 0000 0000 0000 0000 0000 0000 0010 0000 = 0x20

then we subtract 1 and get:
                    0000 0000 0000 0000 0000 0000 0001 1111 = 0x1f

A: Another option is
std::uint32_t mask = ~(~0U << n);

Also you have to make sure unsigned int isn't less than 32 bits on your system, it may be better to write
std::uint32_t mask = ~(~(std::uint32_t)0 << n);


text:
Q: JSON Post to a url I need to start with a new project where I need to get data from firebase.  The programmer for the firebase app wants to post the data to me in JSON to a url.  I have experience in PHP but I have no idea how to create this url to where he must post.  Can someone please point me in the direction to go?  Must I create a page on my website or what must I do here?
Help will be greatly appreciated.

A: I think you should start looking at creating a rest api on a server (I havent worked with php so dont know the best practices there but got this when i googled)
The rest api can then handle the post request and then save the data into firebase.


text:
Q: Text shadow opacity Is it possible to adjust the opacity of just the text shadow, rather than the text itself as well?
E.g I have purple text with a blue shadow. I'd like to make the blue shadow have an opacity without losing anything on the purple.
h1.blue {text-shadow: 3px 3px 0px #3f6ba9;}

A: Yes, but specify color in rgba mode to add alpha transparency.
h1.blue {text-shadow: 3px 3px 0px rgba(63,107,169, 0.5)} //half of transparency

A: To add on the answer for anyone looking to use HEX code instead of RGB:
h1.blue {text-shadow: 3px 3px 0px #3f6ba980;}

The last 2 characters in the above HEX code has opacity set at 50%. For other opacity values, please refer to opacity-hex charts as linked here. Alternatively, if you are using VScode, you will be able to use their in-built color picker to adjust the opacity.


text:
Q: What is the best way to get a sample k8 yaml to edit as per requirement? In declarative approach , what is the best way to get a default/sample yaml file which we can edit on vi as per our requirement , do we need to copy it everytime from k8 doc ?

A: Some resource samples can be created with kubectl create <resource type> <resource name> --dry-run=client -o yaml. To see which resource can be created run kubectl create --help.
For example, to create a deployment named demo with nginx image, run:
kubectl --namespace=default create deploy demo --image=nginx --port=80 --dry-run=client -o yaml

It generates:
apiVersion: apps/v1
kind: Deployment
metadata:
  creationTimestamp: null
  labels:
    app: demo
  name: demo
  namespace: default
spec:
  replicas: 1
  selector:
    matchLabels:
      app: demo
  strategy: {}
  template:
    metadata:
      creationTimestamp: null
      labels:
        app: demo
    spec:
      containers:
      - image: nginx
        name: nginx
        ports:
        - containerPort: 80
        resources: {}
status: {}

Another example with Ingress. Write YAML definition to demo-ingress.yaml
kubectl create ingress demo --rule="foo.com/api=api-svc:8080,tls=my-cert" --dry-run=client -o yaml > demo-ingress.yaml

A: yes, k8s documentation is the best place to start with a default yaml file for the required setup as its up-to-date and you are sure that it works without any surprises for beginners.

A: The VSCode Kubernetes plugin includes scaffolds for the major object types. I'm guessing there are similar plugins for other editors.


text:
Q: SQLiteDatabase hosted on server android I have an application that uses the SQLiteDatabase as its database, because each application has its own, custom database (well, custom values), for another app I am making, I want to hose a single SQLiteDatabase that every app will access, for example one app adds a row, while another then reads it at a later time.
Is there anyway to do this? Everything I've found has left me believing there is not, but there has to be.
Any ideas?
Update:
I'm not sure if you've quite understood what I'm trying to do, sorry. The apps accessing this db are all the "same" app, but from different phones, for example, the database could be used to store a user id and their favorite color, so another phone could search their user id, and get the color in db with that user id –
I'm sorry if I did not make that clear enough

A: Of course there is way to do it! There is always a way!
Anywho, what I think you are looking for is a remote server. These can be done in a few way depending on how much money you have.
(1)If you're broke like me all the time, then you can make an extra computer you have at home act as a server for your app. This can cause a few ( :) hehe few) security issues for your home though. Also you will have a lot of traffic on your home network.
(2)Another option it's to get a domain name and web host. Most of the web hosting services I have seen offer database support. So what you could do is hop on, create your database on the web host server then link your app to your server. The cost on that varies based on your needs.
Really though, is your app interfacing with mulitple people? I can't think of a reason you would want this feature on any other phone (device) than your (relative to us customers) device. I rarely hand my device over to others, and never unless it's locked.

A: SQLite is serverless. In a situation as described there are no guarantees that it will work properly. Your solution is to create a database server that will cater to multiply Android clients simultaneously.
For more information on SQLite see LinuxForu.com and/or SQLite.org