text:
Q: images show the name of a button My app generates random images want the name of the image that is generated is displayed on a button
the images are stored in the drawable folder and their names on a chain. I want the image to appear his name appeared on a button possible?

package com.example.antoniocruz.juegamovil;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.ActivityInfo;
import android.media.MediaPlayer;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.support.v7.app.ActionBarActivity;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by Antonio Cruz on 01/06/2015.
 */
public class Categoria extends Activity {

    public static String[] nombre_cosa={"pig " , " bird " , " horse " , " rabbit " , " elephant " , " chicken " , " cat "
            "frog" , "dog" , "duck" , "sheep" , "leon" , " giraffe "
            " Mat" , "cow" , " bus " , " car " , " airplane " , "bicycle" , " truck "
            , "cell " , , , , , , , , "house" , " guitar " , " motorcycle " , " chair " , " television" , " peach " , " strawberry " "mango "
            " grapes " , " watermelon " , " banana " , " coconut " , "pear" , "orange" , "apple "
            " bart " " batman" , "brain" , " guy ", " Goku ", " Homer " " marge "
            " patrician " , " pit " , " Phineas " , " Quico " , " Spiderman ," " Thor" , " superman"};

    public static boolean[] estado={false,false,false,false,false,false,
            false,false,false,false,false,false,
            false,false,false,false,false,false,false,
            false,false,false,false,false,false,false,false,
            false,false,false,false,false,false,false,
            false,false,false,false,false,false,false,false,false,false,
            false,false,false,false,false,false};

    public static int cosas_adivinadas=0;
    private int intentos=3;
    private Button aceptar;
    private TextView mensaje_intentos,mensaje_cuenta;
    private EditText usuario_cosa;
    private int numero_generado=0;
    private ImageView miimagen;
    private MediaPlayer reproductor;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
        requestWindowFeature(Window.FEATURE_NO_TITLE);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        setContentView(R.layout.activity_categoria);
        aceptar=(Button) findViewById(R.id.btnaceptar);
        mensaje_intentos=(TextView) findViewById(R.id.lblintentos);
        mensaje_cuenta=(TextView) findViewById(R.id.lblcuenta);
        usuario_cosa=(EditText) findViewById(R.id.txtcosa);
        miimagen=(ImageView) findViewById(R.id.imgcosa);
        CargarPreferencias();
        new MiTarea().execute();
        reproductor= MediaPlayer.create(this,R.raw.yansha);
        reproductor.setLooping(true);
        reproductor.start();
        mensaje_intentos.setText("Tiene " + intentos + " intentos");
        aceptar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                String nombre=usuario_cosa.getText().toString().toLowerCase();
                if(nombre.equals(nombre_cosa[numero_generado]))
                {
                    establecer_cosa(numero_generado);
                    estado[numero_generado]=true;
                    cosas_adivinadas++;
                    esperar();
                }
                else
                {
                    Toast.makeText(getApplicationContext(), "Incorrecto", Toast.LENGTH_SHORT).show();
                    intentos=intentos-1;
                    mensaje_intentos.setText("Tiene " + intentos + " intentos");
                }

                if (intentos==0)
                {
                    removerPreferencias();
                    Intent i = new Intent(Categoria.this,Perder.class);
                    startActivity(i);
                    finish();
                }
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        reproductor.start();
    }

    public void esperar()
    {
        new CountDownTimer(5000,1000)
        {

            @Override
            public void onTick(long millisUntilFinished) {
                mensaje_cuenta.setText("Generando en " + (millisUntilFinished/1000));
            }

            @Override
            public void onFinish() {

                if (cosas_adivinadas==nombre_cosa.length)
                {
                    finish();
                }
                else
                {
                    new MiTarea().execute();
                    mensaje_cuenta.setText("");
                    usuario_cosa.setText("");
                }
            }
        }.start();
    }

    public void CargarPreferencias()
    {
        SharedPreferences mispreferencias = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
        intentos=mispreferencias.getInt("intentos",3);
        cosas_adivinadas=mispreferencias.getInt("adivinados",0);
        for (int i=0;i<nombre_cosa.length;i++)
        {
            estado[i]=mispreferencias.getBoolean(nombre_cosa[i],false);
        }
    }

    public void GuardarPreferencias()
    {
        SharedPreferences mispreferencias = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = mispreferencias.edit();
        editor.putInt("intentos",intentos);
        editor.putInt("adivinados",cosas_adivinadas);
        for (int i=0;i<nombre_cosa.length;i++)
        {
            editor.putBoolean(nombre_cosa[i], estado[i]);
        }
        editor.commit();
    }

    private void establecer_cosa(int numero)
    {
        int resId = getResources().getIdentifier(nombre_cosa[numero], "drawable", getPackageName());
        miimagen.setImageResource(resId);
    }

    private void establecer_sombra(int numero)
    {
        int resId = getResources().getIdentifier(sombra_cosa[numero], "drawable", getPackageName());
        miimagen.setImageResource(resId);
    }

    private void removerPreferencias()
    {
        SharedPreferences settings = getSharedPreferences("PreferenciaCosa", Context.MODE_PRIVATE);
        settings.edit().clear().commit();
    }

    @Override
    protected void onStop() {
        if (intentos==0)
        {
            removerPreferencias();
        }
        else
        {
            GuardarPreferencias();
        }
        reproductor.pause();
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        if (reproductor.isPlaying())
        {
            reproductor.stop();
            reproductor.release();
        }
        super.onDestroy();
    }

    private class MiTarea extends AsyncTask<Void, Void, Void> {
        private int valor_generado;
        @Override
        protected Void doInBackground(Void... params) {
            do {
                valor_generado=((int)(Math.random()*nombre_cosa.length));
            }while(estado[valor_generado]);
            return null;
        }
        @Override
        protected void onPostExecute(Void aVoid) {
            numero_generado = valor_generado;
            establecer_sombra(valor_generado);
            super.onPostExecute(aVoid);
        }
    }

}

A: Assuming that aceptar is the Button which you talk about, you can just use .setText() method to change his text:
if(nombre.equals(nombre_cosa[numero_generado])){
    aceptar.setText(nombre_cosa[numero_generado]); //here the change
    establecer_cosa(numero_generado);
    estado[numero_generado]=true;
    cosas_adivinadas++;
    esperar();
}

Update: generate images randomly
1) Create your static arrays:
    // your names array
    public static String[] nombre_cosa={"pig " , " bird " , ..., " superman"};

    // your images drawable array
    public static int[] imagenes_cosa= new int[]{R.drawable.pig_image,..., R.drawable.superman_image};

2) Create a random position generator method:
private int getRandomPosition(){
    Random r = new Random();
    return r.nextInt(nombre_cosa.length);
}

3) Set your click listener:
    aceptar.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
               int randomPosition = getRandomPosition();
               aceptar.setText(nombre_cosa[randomPosition]);
               miimagen.setImageResource(imagenes_cosa[randomPosition]);
            }
        });

PS: nombre_cosa and imagenes_cosa should have the same size!


text:
Q: Golang error function arguments too large for new goroutine I am running a program with go 1.4 and I am trying to pass a large struct to a go function.
go ProcessImpression(network, &logImpression, campaign, actualSpent, partnerAccount, deviceId, otherParams)

I get this error:
runtime.newproc: function arguments too large for new goroutine

I have moved to pass by reference which helps but I am wondering if there is some way to pass large structs in a go function.
Thanks,

A: No, none I know of.
I don't think you should be too aggressive tuning to avoid copying, but it appears from the source that this error is emitted when parameters exceed the usable stack space for a new goroutine, which should be kilobytes. The copying overhead is real at that point, especially if this isn't the only time these things are copied. Perhaps some struct either explicitly is larger than expected thanks to a large struct member (1kb array rather than a slice, say) or indirectly. If not, just using a pointer as you have makes sense, and if you're worried about creating garbage, recycle the structs pointed to using sync.Pool.

A: I was able to fix this issue by changing the arguments from
func doStuff(prev, next User)

to
func doStuff(prev, next *User)

The answer from @twotwotwo in here is very helpful.

A: Got this issue at processing list of values([]BigType) of big struct:
for _, stct := range listBigStcts {
    go func(stct BigType) {
        ...process stct ...
    }(stct) // <-- error occurs here

}

Workaround is to replace []BigType with []*BigType

redpajama_set_name: RedPajamaStackExchange


text:
Q: Can a static method return new instances of an object? I have this static method, which purpose is to load the init values of a dictionary.
My concern with this method, is whether it keep creating a new instance every time it is being called,
or will reference the already created instance?
    public static IReadOnlyDictionary<string, string> GetCountryNamesCodes()
    {
        return new Dictionary<string, string>()
        {
            {"AF", "Afghanistan"},
            {"Afghanistan", "AF"},
            {"YT", "Mayotte"},
            {"Mayotte", "YT"}
        };
}

A: Your code will alway return a new instance of the dictionary. If you want to return always the same instance, create a class variable:
private static Dictionary<string, string> countryNames = new Dictionary<string, string>()
        {
            {"AF", "Afghanistan"},
            {"Afghanistan", "AF"},
            {"YT", "Mayotte"},
            {"Mayotte", "YT"}
        };

public static IReadOnlyDictionary<string, string> GetCountryNamesCodes()
{
        return countryNames;
}

If creating the variable is more complicated, you can use a static constructor.


text:
Q: How do I pass the data from the checked List Tile to the next page (Basket) in flutter I previously used a Listview to present my data, but I was advised to use a Checkbox List tile now I'm stuck on how to pass data. I want to pass the selected/checked List tile's data to the next page (Basket). How do I do that, please help me.
I am new to Flutter.
The Main Method Class
import 'package:cart_app1/Basket.dart';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(),
      initialRoute: '/',
      routes: {
        '/': (context) => MyHomePage(),
        Basket.routeName: (context) => Basket(),
      },
    );
  }
}

The product list class
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Map<String, bool> values = {
    "GIN COCKTAILS \nClover Club \t  R65": false,
    "Beers & Ciders \nHeineken NRB \t R29": false,
    "Vodka \nCiroc \t R35": false,
    "Vodka \nCruz Vodka \t R30": false,
    "COGNAC \nHennesy \t R40": false,
    "Tequilla \nEl Jimador \t R30": false,
    "Non-Alcoholic \nSoft-Drink \t R20": false,
    "WHISK[E]Y \nJohnie Walker Red \t R25": false,
  };

  var toggle = false;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("The Wing Republic"),
        actions: <Widget>[
          IconButton(
            icon: Icon(Icons.shopping_basket),
            onPressed: () {
              Navigator.of(context)
                  .pushNamed(Basket.routeName, arguments: values);
            },
          ),
        ],
      ),
      body: ListView(
        children: values.keys.map((String key) {
          return CheckboxListTile(
            title: Text(key),
            subtitle: Text(""),
            isThreeLine: false,
            value: values[key],
            onChanged: (bool value) {
              setState(() {
                values[key] = value;
              });
            },
          );
        }).toList(),
      ),
    );
  }
}

The Basket Method
import 'package:flutter/material.dart';

class Basket extends StatelessWidget {
  static const routeName = '/Basket';

  @override
  Widget build(BuildContext context) {
    final data = ModalRoute.of(context).settings.arguments as Map<String, bool>;
    return Scaffold();
  }
}

A: You can pass arguments in pushNamed method.
Navigator.of(context).pushNamed(Basket.routeName, arguments: values);

On the receiving end, use ModalRoute to get the values.
import 'package:flutter/material.dart';

class Basket extends StatelessWidget {
  static const routeName = '/Basket';

  @override
  Widget build(BuildContext context) {
    final data = ModalRoute.of(context).settings.arguments as Map<String, bool>;
    return Scaffold();
  }
}

Routes in MyApp is incorrect. If you want to use routes, you can't use home property. Instead of home specify initialRoute.
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      initialRoute: '/',
      routes: {
        '/': (context) => MyHomePage(),
        Basket.routeName: (context) => Basket(),
      },
    );
  }
}


text:
Q: Find files whose path doesn't contain a word I am trying to list all the .hpp files but those whose path contain a word,
for example :
find -name '*.hpp' would give
folder1/folder2/something.hpp
folder1/folder3/something.hpp
folder1/folder4/something.hpp

I'd like to exclude the files in the folder2 in order to have only these :
folder1/folder3/something.hpp
folder1/folder4/something.hpp

A: Just negate a -path condition:
find -name '*.hpp' -not -path '*/folder2/*'

To exclude several directories, either repeat the condition:
find -name '*.hpp' -not -path '*/folder2/*' -not -path '*/folder3/*'

Or use alternative in a regex:
find -name '*.hpp' -not -regex '.*/\(folder2\|folder3\)/.*'


text:
Q: Java won't read my second process I am studying Java now and I have a problem. In my scenario I created a series of methods and I asked the user to choose from one of them. After choosing the desired method there will be a message that will ask to input a string or an integer. My problem is After choosing the desired method it skipped the second phase which is asking to input any string/integer.
Hope you'd understand my problem.
Here's my simple code:
import java.util.*;

import java.io.*;

public class MachineProblemChoser {

    static Scanner console = new Scanner(System.in);

    public static void main(String[] args) {

        int chosenProblem;

        System.out.println("Choose a problem you want to process");
        System.out.println("***********************************************");
        System.out.println("  1 -- Sum of digit");
        System.out.println("  2 -- Days of the month");
        System.out.println("  3 -- Largest number");
        System.out.println("  4 -- Fibonacci");
        System.out.println("  5 -- Palindrome");
        System.out.println(" -1 -- Exit");
        System.out.println("***********************************************");
        System.out.print(" Choose from(1-5) and -1 for exit: ");
        chosenProblem = console.nextInt();

        String numberSeries;
        int inputs;

        switch(chosenProblem) {

            case 1:

                //FROM THIS PART IT SKIPPED THE INPUT FROM THE USER
                System.out.println("SUM OF DIGIT");
                System.out.println("Input any integer separated by space:");
                numberSeries = console.nextLine();

                System.out.println("Count is: " + numberSeries.length());

            break;

            case 2:
                //machineProblemTwo();
            break;

            case 3:
                //machineProblemThree();
            break;

            case 4:
               // machineProblemFourth();
            break;

            case 5:
               //machineProblemFifth();
            break;

            case -1:
               exitProgram();
            break;

            default:
               System.out.println(" Oops: Choose a valid number for the selection!");

        }

    }

    public static void machineProblemOne(String chosenNumber) {
        System.out.println("Chose number are: " + chosenNumber);
    }

    public static int validateInput(int inputs) {

        return 0;
    }

    public static void exitProgram() {
        System.out.println(" Thanks for using the Machine Problem Choser! ");
    }

}

Here's the output:
Choose a problem you want to process
***********************************************
  1 -- Sum of digit
  2 -- Days of the month
  3 -- Largest number
  4 -- Fibonacci
  5 -- Palindrome
 -1 -- Exit
***********************************************
 Choose from(1-5) and -1 for exit: 1
SUM OF DIGIT
Input any integer separated by space:         ---- From this it skipped
Count is: 0

A: okay I tested out your problem and this might work:
Try replacing this:
numberSeries = console.nextLine();

with this:
numberSeries = System.console().readLine();

It might help.

A: scanner.nextInt(); reads only the next integer from input.  You need to clear the remaining carriage return.  Try this:
...
System.out.println("***********************************************");
System.out.print(" Choose from(1-5) and -1 for exit: ");
chosenProblem = console.nextInt();
console.nextLine();//this clears out the rest of the input line

String numberSeries;
int inputs;
....


text:
Q: Is there a way to vectorize selection of columns (with repetition) from a matrix? I have a matrix L of size n x k and a vector Z of size p. Z is composed of integers which represent the column indices of L. I want to create a matrix X of size n x p which is the aggregation of the corresponding columns of L selected based on the values in Z.
Z = c(1, 3, 1, 2)
L = matrix(c(73,50,4,14,87,5,34,51,17,57,47,65),nrow=4)
> L
     [,1] [,2] [,3]
[1,]   73   87   17
[2,]   50    5   57
[3,]    4   34   47
[4,]   14   51   65

I want X to be
> X
     [,1] [,2] [,3] [,4]
[1,]   73   17   73   87
[2,]   50   57   50    5
[3,]    4   47    4   34
[4,]   14   65   14   51

In my original data, p, k and n are quite big (30K, 500 and 2K, respectively), and a loop over all Z values to select and combine the columns from L takes a very long time. Can there be a vectorized way (no loops) to do this task?

A: Pretty sure this is just:
L[,Z]
#     [,1] [,2] [,3] [,4]
#[1,]   73   17   73   87
#[2,]   50   57   50    5
#[3,]    4   47    4   34
#[4,]   14   65   14   51

R doesn't care if you have repeating column indexes when you do selections from most objects.


text:
Q: How to eliminate multiple instances of a substring from a string I got a string
str = "HI".

I want to eliminate duplicate instances of  and  to get HI.
There could potentially be more than two instances.
I tried to use squeeze(''), but it doesn't seem to do the job.

A: you could do this:
str = "HI"
str.gsub('', '').
    gsub('', '') # => "HI"

A: you can do something like this
str = "HI"

p str[/<.*?>/]+ str[/>([^<]*)<\//,1]+str[/<\/.*?>/]

A: Other option would be to use regex to get the desired result.
str.match(/<[a-z]+>[a-zA-Z]+<[\/a-z]+>/)
=> #<MatchData "HI">

A: This can be done multiple ways, one of which is using gsub, like this:
str
  .gsub(/()+/, '')
  .gsub(/(<\/strong>)+/, '')

The first gsub replaces one or more consecutive instances of  with one , and the second gsub replaces one or more consecutive instances of  with one  (note the / in the regular expression part needs to be escaped).
It's worth noting that this approach does not ensure there are a matched number of opening and closing  tags.


text:
Q: Quicksight calculated field Im trying to created a calculated field
where sum and max functions are used.
Sum({$<DateID =  {$(=max(DateID))}>}  InServiceDays)
This above statement means i want sum of inservicedays where dateid=max(dateid)
but how to make this thing possible using calculated field or parameters in quicksight.

A: If I understand correctly, you have field called dateID and you want to sum {InServiceDays} for rows whose dateID is the maximum.
This can be expressed using the following calculated field in QuickSight
sumIf({inServiceDays}, DateID = maxOver(dateID,[], PRE_AGG))


text:
Q: NoSuchBeanDefinitionException exception using AnnotationConfigApplicationContext I am getting "org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'employee' is defined" error and I am not sure what I am doing wrong. Please find below the code.

*

*) AppConfig Class:
@ComponentScan("com.spring.annotation.propertyconfigurer")
@Configuration
@PropertySource("classpath:employee.properties")
public class AppConfig {

@Bean
public static PropertySourcesPlaceholderConfigurer    propertySourcesPlaceholderConfigurer() {
    return new PropertySourcesPlaceholderConfigurer();
 }
}

2) Employee Class
@Component("employee")
public class Employee {

    @Value("${emp.empId}")
    private int empId;
    @Value("${emp.name}")
    private String name;
    @Autowired
    private Address address;

    public int getEmpId() {
        return empId;
    }

    public void setEmpId(int empId) {
        this.empId = empId;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Address getAddress() {
        return address;
    }

    public void setAddress(Address address) {
        this.address = address;
    }

    public void print() {
        System.out.println("Employee Id -> " + empId);
        System.out.println("Employee Name -> " + name);
        System.out.println("Employee Address -> [ " + address.getCity() + "," + getAddress().getCountry() + "]");
    }
}

3) Address Class:
@Component("address")
public class Address {

    private String city;
    private String country;

    public String getCity() {
        return city;
    }

    public void setCity(String city) {
        this.city = city;
    }

    public String getCountry() {
        return country;
    }

    public void setCountry(String country) {
        this.country = country;
    }
}

4) Main Class
public class PropertyConfigurerApp {

    public static void main(String[] args) {
        try (AbstractApplicationContext context = new AnnotationConfigApplicationContext("AppConfig.class")) {
            Employee employee = (Employee) context.getBean("employee");
            employee.print();

        } catch (Exception e) {
            e.printStackTrace();
        }

    }

}

Please help me to resolve this issue.
Thanks,
Kamal

A: You've to register your beans to the configuration, for example using Component Scanning on packages of your Components.
There are several ways to do this

*

*via xml config   <context:component-scan base-package="org.example"/>

*using @ComponentScan({package1, .., package n}) in your @Configuration
You can also add a @Bean for your @Components in your @Configuration
See spring documentation
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle
http://docs.spring.io/spring/docs/current/spring-framework-reference/htmlsingle/#beans-annotation-config
HOW TO CHANGE YOUR CODE
1- give to your classes a package (if you didn't it already). I Used test.component for the employee and address
2- in AppConfig change
     @ComponentScan("com.spring.annotation.propertyconfigurer")

with
    @ComponentScan("test.component")

or
    @ComponentScan(basePackages={"test.component"})

3- In propertyConfigurerApp change
            AbstractApplicationContext context = new AnnotationConfigApplicationContext("AppConfig.class")

with
  AbstractApplicationContext context = new AnnotationConfigApplicationContext(AppConfig.class)

It should work (put your employee.properties on root of classpath)
However you didn't need to make all this componentscanning stuffs as you don't use autowiring in your example.


text:
Q: "Order by" in DynamoDB using params I'm not understanding by reading Amazon DynamoDB guide if there's a way to order Items after a query/scan.
For example:
--My database table--
        TableName:"Projects",
           Item:{
              "projectOwner": "User1",
              "projectName": "Project1",
              "creationDate": "Wed Nov 20 2016",
              "updateDate": "Wed Nov 29 2016",
         }Item:{
              "projectOwner": "User1",
              "projectName": "Project2",
              "creationDate": "Wed Nov 20 2016",
              "updateDate": "Wed Nov 28 2016",
         }Item:{
              "projectOwner": "User1",
              "projectName": "Project3",
              "creationDate": "Wed Nov 20 2016",
              "updateDate": "Wed Nov 30 2016",
         }

So I want to scan my database and return all the Items ordered by "updateDate". Is there a way to achieve this using dynamoDB params?
        params = {
             TableName: "Projects",
             ProjectionExpression: "projectName",
             KeyConditionExpression: "projectOwner = :userId",
             ExpressionAttributeValues: {
                 ":userId":userId
             }
        };

A: There is no Order By in DynamoDB. You have to sort the result set at client side if the attribute is not defined as Sort key.
However, if the updateDate is defined as Sort key, the API has the feature to sort the data by ascending or descending order.

If ScanIndexForward is true, DynamoDB returns the results in the order
  in which they are stored (by sort key value). This is the default
  behavior. If ScanIndexForward is false, DynamoDB reads the results in
  reverse order by sort key value, and then returns the results to the
  client.
Specifies the order for index traversal: If true (default), the
  traversal is performed in ascending order; if false, the traversal is
  performed in descending order.


text:
Q: How can I add certain values of an array together and then sort by the sum? So I am trying to find the best model within our database to match the user's inputted values for Height, Weight, etc. I have generated a variable called heightMatchMultiple based on weighted values and stored all the results in a global array $models. How can I apply math to only the ____MatchMultiple fields and then sort by the result? For example, I store the modelID of each model but I only want to add up the other values and then find the highest average.
Here is some relevant code:
while($row=mysqli_fetch_array($array))
{
    $userHeight=$_POST['height'];
    $userWeight=$_POST['weight'];
    $userShoulder=$_POST['shoulder'];
    $userWaist=$_POST['waist'];
    $userInseam=$_POST['inseam'];
    $heightMatchMultiple=0;

    //creates a weighted variable for height
    if(isset($row['modelHeight']))
    {
        if($userHeight==$row['modelHeight'])
        {
            $heightMatchMultiple=10;
        }
        elseif($userHeight==($row['modelHeight']+1) || $userHeight==($row['modelHeight']-1))
        {
            $heightMatchMultiple=9;
        }
        //same code down til multiple hits 1
        else
        {
            $heightMatchMultiple=1;
        }

        //similar code for the weight, shoulders, etc.......
        //....
        array_push($models,array("modelID" => $row['modelID'],
                                 "modelHeightMatch" => $heightMatchMultiple,
                                 "modelWeightMatch" => $weightMatchMultiple,
                                 "modelShoulderMatch" => $shoulderMatchMultiple,
                                 "modelWaistMatch" => $waistMatchMultiple,
                                 "modelInseamMatch" => $inseamMatchMultiple));

I would like to make a function that adds all of the _____MatchMultiple variables within the array (not including modelID) and then divides by the number of items within the array for each. This way I can find out which model is the closest match.

A: Does this sum_array() function solve it for you?
function safe_key_inc(&$arr, $key, $inc)
{
  if (array_key_exists($key, $arr))
    $arr[$key] += $inc;
  else
    $arr[$key] = $inc;
}

function sum_array($arr)
{
  $sum_arr = [];

  foreach ($arr as $el)
    foreach ($el as $key => $val)
    {
      if (strstr($key, "Match"))
         safe_key_inc($sum_arr,$key,$val);
    }

  return $sum_arr;
}

A: function getAverage($array) {

     var $myTotal = 0

     for ($i = 1; $i<= sizeof($array) - 1; $i++) {

         $myTotal += $array[$i]

     }

     var $myAverage = $myTotal/(sizeof(array) - 1)

     return($myAverage)
}


text:
Q: WPF app doesn't shut down because of invisible main window instance Some mysterious things are happening to my WPF app. I changed main window and after closing it app doesn't shut down. Here's my App.xaml:
    <Application
         xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
         xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
         xmlns:local="clr-namespace:LogAnalysis" x:Class="LogAnalysis.App"
         StartupUri="ChartWindow.xaml" ShutdownMode="OnMainWindowClose">
        <Application.MainWindow>
            <local:ChartWindow/>
        </Application.MainWindow>
    </Application>

I tried to figure out why process is still alive after closing and wrote this:
    foreach (var window in Application.Current.Windows)
    {
        MessageBox.Show((window as Window).Title);
    }

Two message boxes with the same message were shown.
So, it seem like there are two instances of main window are running in the one instance of app.
I can't use solution with this:
    protected override void OnClosed(EventArgs e)
    {
        base.OnClosed(e);
        Application.Current.Shutdown();
    }

because Window.Closing event is triggered twice because of the second instance of the window (and it corrupts user settings).

A: Not that this is an exact answer to your question, because I have no way of knowing why there are two MainWindow instances, but you could move the saving of your user settings to the Application.ApplicationExit (WinForms) or Application.Current.Exit (WPF) method, which will only get called once, after calling Shutdown().

A: Oh, finally got it. In the App.xaml file there is no need to determine Main Window property explicity. So, this code is not only redundant, it also calls window constructor:
    <Application.MainWindow>
        <local:ChartWindow/>
    </Application.MainWindow>

It will be enough to change only StartupUri property.
Hope it will help someone.


text:
Q: Setting text color in text box C# I have a multi line text box which is used to display the status messages of the operations that I do in the application. I want to set separate colors for different lines in the text box. If I use the ForeColor property, it sets the color of all the text. I want to set the color of a single line. How can I do this?
Thanks,
Rakesh.

A: You need to use the RichTextBox instead. You can then use the properties SelectionStart, SelectionLength, and SelectionColor to achieve what you want, as the easiest solution. You can also modify the RTF directly. You can actually just edit the designer code and change System.Windows.Forms.TextBox references to RichTextBox, then make some small modifications to your code.

A: TextBox control doesn't support coloring of intermediate lines. use ListView instead. You can achieve a similar look-and-feel by using "Details" or "List" View mode.

A: You can't do that with the built in control.
Either inherit it and create your own control, or use something like this:
Background color of a ListBox item (winforms)
In there it's background color but you can same way apply different fore color.

A: TextBox does not support multiple colors (or fonts or sizes). You'll have to use RichTextBox.

A: You can't.
You need to use Rich TextBox instead.

A: You have to use a richtextbox for this. You can specify all sorts of formatting inline with your text


text:
Q: Teradata - what index strategy is best? For example, I have to create a table with following fields:
client_id (num)
local_id (num)
unit_id (char)
category (char)
first_product_date (date)

client_id is unique. All fields will be used in joins, WHERE etc.
Please explain, which way to use indexes is best and why?
1) Primary unique + others in secondary
PRIMARY UNIQUE INDEX (client_dk)
SECONDARY INDEX (local_id, unit_id, category, first_product_date)

2) Primary non unique + others in secondary
PRIMARY INDEX (client_dk)
SECONDARY INDEX (local_id, unit_id, category, first_product_date)

3) All in primary
PRIMARY INDEX (client_dk, local_id, unit_id, category, first_product_date)

4) Secondary unique + others in primary
PRIMARY INDEX (local_id, unit_id, category, first_product_date)
SECONDARY UNIQUE INDEX (client_dk)

5) Any other way?
Thx!

A: A few notes for TD indexes:
Your primary index is the most important one -- pick it based on:
1) Access - how do you access data from the table
2) Distribution - how unique is the data --> PI value hash is used to store/locate rows
3) Volatility - how often do the PI values change --> reduce data relocation
Ideally, you want a unique index, but it really depends on how plan to access the data.  Having a non-unique index is not necessarily bad.
To target specific problem queries and tables, you can try:
1) Using DIAGNOSTIC HELPSTATS ON FOR SESSION to see recommended statistics for specific queries.  Run an EXPLAIN on your query and you'll get some stat collection ideas.
2) Playing with join Indexes.
3) Like mentioned earlier, secondary indexes are not always very useful.  So don't go creating them all over the place.
And like the folks before said, figure out how all the tables relate to each other and the type of questions you plan to ask of your data.  That will dictate your index choices.


text:
Q: Collapsible CSS left-hand column and auto-expanding right-hand column... expanding vertically? I have a tricky design to put into practice. There will be two CSS columns, the left of which is a left-hand menu (~300px) which collapses to 85px when not in use. The right column should expand to fill whatever space is available when the menu collapses.
This in itself is not too tricky and I've achieved it using the overflow: hidden trick (essentially the same as the accepted answer on CSS layout with 2 columns, taking up all width of browser, where left column can collapse)
However I am now looking at how I can have both columns expand vertically to fill the available screen space.
The variable width left-hand column seems to prevent me from using the Faux Columns technique. I'm not sure other than that.
I also have CSS transitions on the width so that the collapse/expand movement is more fluid, which I'd like to maintain.
Any advice would be gratefully received.
EDIT: This is as close as I can get: http://jsfiddle.net/tsr5a/:
html, body { height:100%;}
#menu { width: 100%; height: 50px; }
#container { overflow: hidden; height:100%; }
#left-column { background:yellow; float:left; height:100%; width:300px; }
#right-column { background:red; height:100%;}
#container .shrink { width:85px; }

I'm not sure why the right-hand column is offset vertically by 1 line. Also note that while I can set 100% height on the columns, this doesn't take into account the fixed height toolbar at the top of the page.

A: Good Luck
you need include this
#container{display:inline-flex;width:100%; }
#right-column{;width:100%}

JSFiddle

A: If you remove overflow: hidden; from your #container it should work as desired.
JSFiddle
#container {height:100%;}

Edit: I hope I understood your question/issue correctly.


text:
Q: Flatten a Directory then delete the empty folders Hello I'm trying to write a command to flatten a directory of shows (Library>Show>Season>Episode) to be just (Library>episodes)
I have this right now and it works if I type it manually in CMB, But if I save it as a .cmd and double click it it doesn't seem to do anything. Am I doing something wrong? I would like it as a .cmd so I can have Task Scheduler do this on a regular basis
F:
cd F:\Downloads\TDARR Shows
for /r %f in (*) do @move "%f" .
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do rd "%d"

A: In a batch script you have to use double percent characters for variables like %f.
In your .cmd script, try
F:
cd "F:\Downloads\TDARR Shows"
for /r %%f in (*) do @move "%%f" .
for /f "delims=" %%d in ('dir /s /b /ad ^| sort /r') do rd "%%d"

Edit: I added quotes around the directory name containing a space in the cdcommand, although this specific command seems to work without quotes.


text:
Q: forEach on a 'new Array' isn't doing what I expect I'm just learning how to use JS higher-order functions (map, forEach, reduce, etc), and have stumbled into confusion.  I'm trying to write a simple 'range' function, but can't seem to populate my output array.  This is the goal:
range(1, 4) // [1, 2, 3, 4]

I'm getting this:
[undefined × 4]

Here is my code:
 function range(num1, num2) {
      var rangeArr = new Array((num2 + 1) - num1);
      return rangeArr.map(function(e, i, arr) {return arr[i] = num1 + i});
    }

What am I missing here?  As far as I can tell the problem appears to have something to do with the way I'm utilizing 'new Array', but beyond that I'm lost.
Oh, and here's the part that really confuses me.  This works fine:
function bleck() {
    var blah = [1, 2, 3, 4];
    var x = 'wtf';
    return blah.map(function(e, i, arr) {return arr[i] = x})
}

["wtf", "wtf", "wtf", "wtf"]

Thanks!!

A: The forEach method iterates over the indices of the array. Interestingly enough, when you create a new array via new Array(n), it contains no indices at all. Instead, it just sets its .length property.
> var a = new Array(3);
> console.info(a)
[]
> console.info([undefined, undefined, undefined])
[undefined, undefined, undefined]

MDN describes forEach, and specifically states:

forEach executes the provided callback once for each element of the
  array with an assigned value. It is not invoked for indexes which have
  been deleted or elided.

Here's a neat technique to get an array with empty, but existing, indices.
var a = Array.apply(null, Array(3));

This works because .apply "expands" the elided elements into proper arguments, and the results ends up being something like Array(undefined, undefined, undefined).

A: The array is defined with 4 entires each of which is undefined.
Map will not iterate over undefined entires, it skips them.

callback is invoked only for indexes of the array which have assigned
  values; it is not invoked for indexes that are undefined, those which
  have been deleted or which have never been assigned values.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/map

A: When you create a new Array(x) it is creating what is called a sparse array, which might behave a bit differently, as you can see, some browsers will say [undefined x 20,"foo", undefined x 5] if you just set one value, and I believe it doesn't iterate over those values.

A: The problem is that map doesn't iterate undefined entries (*).
I suggest using a for loop instead:
var rangeArr = new Array((num2 + 1) - num1);
for(var i=0; i<=num2-num1; ++i)
    rangeArr[i] = num1 + i;
return rangeArr;

(*) With undefined entries I mean rangeArr.hasOwnProperty(i) === false, not to be confused with rangeArr[i] === void 0.


text:
Q: FileSaver.js can't specify the charset I'm using a FilseSaver.js to save a rtf file. This is working fine.
However when I'm using special chars, it goes wrong... The charset automatically "changes" from ansi to utf-8 and characters aren't displayed right in the rtf document.
I've tried "forcing" ansi, but it seems like all browsers ignore this setting?
Here is a part of my script:
var blob = new Blob([rtf], {type: "application/rtf;charset=windows-1252"});
saveAs(blob, filename);

This can be fixed by converting my special characters to unicode of hex characters. However using the correct charset seems simpler. Why isn't my script working and how should I fix this?
Thanks!

A: I've come across the same problem, and it seems there's no possibility of stating the charset in the constructor, other than to manually encode your data into the encoding you need.
See this issue https://github.com/eligrey/FileSaver.js/issues/14


text:
Q: If statement ignoring equality Scenario: I have a Function that compares the data in 2 different arrays and writes a corresponding value to a worksheet.
Array1:
+-------+----------------+-----------------+
| Name1 | Current Level1 | Previous Level1 |
+-------+----------------+-----------------+
| ID1   | b              | c               |
+-------+----------------+-----------------+
| ID2   | f*             | g               |
+-------+----------------+-----------------+
| ID3   |                |                 |
+-------+----------------+-----------------+
| ID4   | e              | e               |
+-------+----------------+-----------------+

Array2:
+----+--------------+
| ID | Corresponder |
+----+--------------+
| a  | 1            |
+----+--------------+
| b  | 2            |
+----+--------------+
| c  | 3            |
+----+--------------+
| d  | 4            |
+----+--------------+
| e  | 5            |
+----+--------------+
| f* | 6            |
+----+--------------+
| g  | 7            |
+----+--------------+
| h  | 8            |
+----+--------------+
| i  | 9            |
+----+--------------+

Scenario: I am running a loop that reads the letters in the first array, find a corresponding value in the second array (like a Vlookup) and writes an array exactly like the first, but instead with the corresponding numbers).
output:
+-------+----------------+-----------------+
| Name1 | Current Level1 | Previous Level1 |
+-------+----------------+-----------------+
| ID1   | 2              | 3               |
+-------+----------------+-----------------+
| ID2   | 6              | 7               |
+-------+----------------+-----------------+
| ID3   |                |                 |
+-------+----------------+-----------------+
| ID4   | 5              | 5               |
+-------+----------------+-----------------+

Issue: I am running this code, but for some of the values , even though the comparison is positive, the loop still jumps the inner commands.
Code:
Function match_up_values(cleanoutputArray As Variant, matchArray As Variant, targetColumn As Integer, matchColumn As Integer)

    For loopvar1 = 2 To UBound(cleanoutputArray, 1)
        For loopvar2 = 2 To UBound(matchArray, 1)
            If CStr(cleanoutputArray(loopvar1, targetColumn + 1)) = CStr(matchArray(loopvar2, ratingsColumn)) And CStr(cleanoutputArray(loopvar1, targetColumn + 1)) <> "" Then ' some times, even if this if is true, it steps to the next loopvar2
                shtOutput1.Cells(loopvar1, targetColumn + 1) = matchArray(loopvar2, matchColumn + 1)
                shtOutput1.Cells(loopvar1, 1) = cleanoutputArray(loopvar1, 1)
                shtOutput1.Cells(loopvar1, 2) = cleanoutputArray(loopvar1, 2)
                Exit For
            End If
        Next loopvar2
    Next loopvar1

End function

Question: What could be causing this error?

A: This code is not the fix to your problem. However, it is a little tool that might help you with your issue:
Function stringcompare(strA As String, strB As String)
    If StrComp(strA, strB, vbTextCompare) = 0 Then stringcompare = "Text match (case insensitive)"
    If StrComp(strA, strB) = 0 Then stringcompare = "Perfect match"
    If Len(strA) <> Len(strB) Then stringcompare = "Length of strings not matching"
    If StrComp(Trim(strA), Trim(strB), vbTextCompare) = 0 Then stringcompare = "Text match (case insensitive) but with padding"
    If StrComp(Trim(strA), Trim(strB)) = 0 Then stringcompare = "Perfect match but with padding"
    If stringcompare <> "" Then Exit Function
    Dim i As Long
    For i = 1 To Len(strA)
        stringcompare = stringcompare & "('" & Mid(strA, i, 1) & IIf(Mid(strA, i, 1) = Mid(strB, i, 1), "'='", "'<>'") & Mid(strB, i, 1) & "') "
    Next
End Function

Using this in the right place at the right time will allow you to see what is causing the two strings to mismatch.

A: You have a number of errors in your code which would no doubt cause this issue:

*

*ratingsColumn is not referenced in the function header (probably your issue)

*shtOutput1 is not referenced in the scope of the function (it might be a global variable though)

Another issue could potentially be non-printing characters within the values

The following is untested but should work. It also currently directly replaces the values within the InArray which may not work with your other code without tweaking...

Function InnerReplace(ByRef InArray As Variant, ByVal MatchArray As Variant, TargetCol As Long, MatchCol As Long, ReplaceCol As Long)
    Dim i As Long, j As Long, Str1 As String, Str2 As String
    For i = 2 To UBound(InArray, 1)
        Str1 = CleanStr(CStr(InArray(i, TargetCol + 1)))
        For j = 2 To UBound(MatchArray, 1)
            Str2 = CleanStr(CStr(MatchArray(j, MatchCol)))
            If Str1 = Str2 And Str1 <> "" Then
                InArray(i, TargetCol + 1) = MatchArray(j, ReplaceCol) 'Str2
'                shtOutput1.Cells(i, TargetCol + 1) = MatchArray(j, MatchCol + 1)
'                shtOutput1.Cells(i, 1) = InArray(i, 1)
'                shtOutput1.Cells(i, 2) = InArray(i, 2)
'                Exit For
            End If
        Next j
    Next i

End Function

Function CleanStr(ByVal Value As String, Optional Clean As String = False) As String
    Dim i As Long, NonPrint() As Variant: NonPrint = Array(127, 129, 141, 143, 144, 157)
    For i = LBound(NonPrint) To UBound(NonPrint)
        CleanStr = Replace(CleanStr, Chr(NonPrint(i)), "")      ' Replace non-printing characters
    Next i
    CleanStr = Replace(CleanStr, Chr(160), Chr(32))             ' Replace strange space character

    If Clean = True Then CleanStr = Application.WorksheetFunction.Clean(CleanStr)
End Function


text:
Q: A good introductory discrete mathematics book. I am professor of mathematics and I am scheduled to teach a newly designated discrete math class for computer science majors.  The prerequisite for the class is only Calc 1 and Id like a book that isnt too expensive, has a chapter on logic and proofs, and isnt too difficult but addresses some modern concepts.
Any suggestions?
If I can get a book that addresses all of these criteria except price, then that would work too.

A: Given that it's for computer science majors, my first choice would be Susanna S. Epp, Discrete Mathematics with Applications, which meets all of your criteria except price. Among the standard discrete math texts it offers one of the gentler introductions to reading and writing proofs. Unfortunately, it's obscenely expensive. Edward R. Scheinerman's Mathematics: A Discrete Introduction is merely expensive and is in my opinion a significantly better book, but it's aimed more at math majors than at computer science majors; still, I recommend taking a look at it. It also makes a serious effort to accustom the neophyte to reading and writing proofs.
I've also used the notes by Lovász & Vesztergombi mentioned in another answer; they have the great virtue of being free, and in general they're well written, but there are few exercises, and they lack coverage of a number of topics that are pretty standard in discrete math courses for computer science students. You would probably have to supplement them fairly extensively. Here are some other freely available texts and lecture notes; I've not used them, so I prefer not to offer any judgements.

*

*Marcel B. Finan, Lecture Notes in Discrete Mathematics.

*WWWL Chen, Discrete Mathematics.

*C.D.H. Cooper, Discrete Mathematics: Notes for DMTH137 $-$ suitable only as supplementary material.
Added: In my experience Graham, Knuth, & Patashnik, Concrete Mathematics, is pretty much out of the question for students with no more background than Calc 1. I used it several times in an upper division course, with students who had had at least some exposure to theoretical mathematics, and a majority of them had trouble with it. The coverage is also rather idiosyncratic for a discrete math course for computer science students, and it certainly doesn't include a chapter on logic and proofs.
Do you know yet what topics are to be central to the course?

A: I am in a similar boat, with a couple of differences.  First, I've taught the course previously, but am looking for a free alternative to the rather expensive text I've used in the past. Second, our course requires only pre-Calc, and will have a mix of Math & CIS students so the math abilities will vary.  I have perused free texts by Finan as well of those by Chen and Lovasz posted in this thread.  Right now I am leaning toward Chen, which has a nice selection of topics from which to choose or omit as you see fit.  A clearing house of free texts is here.  Best of luck.

A: I like these lecture notes, though they may be too elementary:

*

*László Lovász, Katalin Vesztergombi, Discrete Mathematics, Lecture Notes, Yale University, Spring 1999.

A: My colleagues have written some notes which you might find suitable, available here and here. Before we had these notes, I used the text by Grimaldi, which I thought was pretty good.


text:
Q: Adjust UIImage into UIImageView Im trying to fit an image into uiimageview, the images are downloaded and loaded dinamically, and theres only one resolution available for ios and android apps.
So, i need images to keep aspect ratio and scale to width, i set UIImageView content mode to
UIViewContentModeScaleAspectFill, but it centers image, so it goes out of screen for both top and bottom, images will be designed so that the bottom is unnecessary.
How can i align the image to the top-left corner?
And can UIImageView scale to width for me too? or how can i do it?
Thanks in advance.
EDIT:
I tried setcliptobounds and that cuts the image to imageview size, thats not my problem.
UIViewContentModeTopLeft is working well, but now i cant apply UIViewContentModeScaleAspectFill, or can i apply both?

A: You could scale the image to suit the image view's width.
You could use a category on UIImage that creates a new image with chosen width.
@interface UIImage (Scale)

-(UIImage *)scaleToWidth:(CGFloat)width;

@end

@implementation UIImage (Scale)

-(UIImage *)scaleToWidth:(CGFloat)width
{
    UIImage *scaledImage = self;
    if (self.size.width != width) {
        CGFloat height = floorf(self.size.height * (width / self.size.width));
        CGSize size = CGSizeMake(width, height)

        // Create an image context
        UIGraphicsBeginImageContext(size);

        // Draw the scaled image
        [self drawInRect:CGRectMake(0.0f, 0.0f, size.width, size.height)];

        // Create a new image from context
        scaledImage = UIGraphicsGetImageFromCurrentImageContext();

        // Pop the current context from the stack
        UIGraphicsEndImageContext();
    }
    // Return the new scaled image
    return scaledImage;
}

@end

This way you can use it to scale the image
UIImage *scaledImage = [originalImage scaleToWidth:myImageView.frame.size.width];
myImageView.contentMode = UIViewContentModeTopLeft;
myImageView.image = scaledImage;

A: UIView which is the superclass of UIImageView has a property contentMode.
You can use the following constant for top left alignment of your image.
UIViewContentModeTopLeft

Aligns the content in the top-left corner of the view.

To keep Aspect ratio
UIViewContentModeScaleAspectFit

Scales the content to fit the size of the view by maintaining the aspect ratio. Any remaining area of the view's bounds is transparent.

A: You can't both align and retain aspect ratio with UIImageView, However there is a great subclass of UIImageView named UIImageViewAligned that makes this possible for you. You can find this project on github from here.
What you need to do is as follows:

*

*First Copy header and implementation from UIImageViewAligned-master/UIImageViewAligned/ to your project

*Insert an ImageView object from object library in IB to your view.

*Change class of ImageView to UIImageViewAligned in Identity Inspector from the Utilities pane

*Then add your desired alignment as a key path in User Defined Runtime Attributes section of Identity Inspector

That's it. Run your project to make sure of it.


text:
Q: var foo = (function(){...})(); ... foo() doesn't work as expected it invokes the function foo the first time, but when i want to use the function another time the following error is thrown:
Uncaught TypeError: Property 'foo' of object [object DOMWindow] is not a function

the intention was to define a function (which has to be called immediately, but also later on) - do i have to write the following instead:
function foo() {...}
foo();
... // later on
foo();

or is there a more elegant solution?
EDIT: if you cannot use a variable (even if it's an anonymous function) as a function, what is its advantage anyway?
(why does
var foo = (function(){...})();
... // later on
foo();

not work?)

A: If you expand
var foo = (function(){...})();
foo();

you will get this:
function temp() {
    ...
}
foo = temp();

As you can see, you are calling the temp function (bolded here): var foo = (function(){...})();. This means that foo is not being assigned to a function object, but the return value of that function call. Therefore, unless the temporary function returns a function (and in that case you might want to consider refactoring), the value stored in foo will not be callable.
In JavaScript, there are two ways to store a function object:
A) Pass a function without calling it (i.e. foo = bar; instead of foo = bar()).
B) (If you need to pass parameters) pass a function call wrapped in another function (without calling the wrapper function) (i.e. foo = function {bar(param1, param2);}; instead of foo = function {bar(param1, param2);}(); (notice the () at the end? -- you don't want that)).

A: It does not work because you assign the result of calling the anonymous function to foo, instead of the function itself.
When you then try to call foo(), you are trying to treat the result of the first function call (apparently of type DOMWindow) as a function, which is incorrect.

A: You could use
var foo;
(foo = function(){...})();

but this is not well-readable.

A: Shouldn't it be

var foo = function()  { ..... }

instead of

var foo = (function() { .. } ) ();

in your case you are assigning a anonymous function to foo.


text:
Q: Regression followed by a t-test? I am new to statistics so basic answers are appreciated. I am a psychology student and am looking at dark triad traits and endorsement for lying. So I have carried out a regression to investigate whether any of the three traits predict endorsement for lying. I then had hoped to see if there was any difference between male and female participants. I ran a t-test but realised that I have only ran it on whether there was a difference between males and females and their endorsement of lying.  This is not good to me as I specifically want to look at whether there was a difference between males and females based on the outcome of the regression - if that makes any sense at all.  My question is - how would I do that?  if it is possible at all.
Thanks

A: If you are not familiar with statistics, I think it would be a mistake to jump right into running statistical tests. First, plot your data in various ways, and clarify what question you want statistics to answer. In detail. Once you have an unambiguous question, you can seek help to answer it with stats.

A:
I then had hoped to see if there was any difference between male and
  female participants.

That depends what is being different as implied by your statement above.
If it's "does endorsement differ by sex, after adjusting for trait," then add sex into the regression as another independent variable. Like this:
$$Lying = \beta_0 + \beta_1 traitYes + \beta_2 Male$$
If it's "does the relationship between trait and endorsement differ by sex," then add sex and the interaction between trait and sex into the model. Like this:
$$Lying = \beta_0 + \beta_1 traitYes + \beta_2 Male + \beta_3 traitYes \times Male$$
Suppose Male = 1 for male and Male = 0 for female, for female, the association would be just $\beta_1$, and the association for male would be $\beta_1 + \beta_3$. If $\beta_3$ is different from 0, the association between trait and endorsement differs by sex.


text:
Q: Audio Slowly Desynchronizing When Segmenting I use ffmpeg's ability to segment video while I record so I can record constantly without my hard drive filling up.
It works really well, expect the audio desynchronizes from the video when the file segments. The video seems to be uninterrupted but I can actually hear a tiny jump in the audio when I join segments later on. One would think that ffmpeg would store packets in a queue during segmentation so nothing is lost but that doesn't seem to be the case... Any way I could force it to do something like that?
Here is my current block:
ffmpeg -y -thread_queue_size 5096 -f dshow -video_size 3440x1440 -rtbufsize 2147.48M -framerate 100 -pixel_format nv12 ^
-itsoffset 00:00:00.012 -i video="Video (00 Pro Capture HDMI 4K+)" -thread_queue_size 5096 -guess_layout_max 0 -f dshow ^
-rtbufsize 2147.48M -i audio="SPDIF/ADAT (1+2) (RME Fireface UC)" -map 0:0,1:0 -map 1:0 -c:v h264_nvenc -preset: llhp ^
-pix_fmt nv12 -b:v 250M -minrate 250M -maxrate 250M -bufsize 250M -b:a 384k -ac 2 -r 100 -vsync 1 ^
-max_muxing_queue_size 5096 -segment_time 600 -segment_wrap 9 -f segment C:\Users\djcim\Videos\PC\PC\PC%02d.mp4

I am delaying the video stream because right out the gate it's a little bit ahead of the audio.
PS: aresample or async seem to have no effect or at least not a desirable one.

A: Using -reset_timestamps in conjunction with encoding .ts instead of .mp4 has mostly solved this issue. -reset_timestamps does not appear to work when encoding .mp4, not sure why, maybe a bug?
I say mostly because audio still drifts around a frame after the first segment, but not exponentially. I find audio de-synced by one frame acceptable. Although I should mention now when I try to concat the clips back together I have audio drift issues, not always, but sometimes. Using aresample=async=250 fixes the drift after concat but you can hear the audio stretch a bit when doing so. Can't expect everything to work perfectly.
ffmpeg - y -thread_queue_size 9999 -indexmem 9999 -guess_layout_max 0 -f dshow -video_size 3440x1440 -rtbufsize 2147.48M ^
-framerate 200 -pixel_format nv12 -i video="Video (00 Pro Capture HDMI 4K+)":audio="SPDIF/ADAT (1+2) (RME Fireface UC)" ^
-map 0:0,0:1 -map 0:1 -flags +cgop -force_key_frames expr:gte(t,n_forced*2) -c:v h264_nvenc -preset: llhp -pix_fmt nv12 ^
-b:v 250M -minrate 250M -maxrate 250M -bufsize 250M -c:a aac -ar 44100 -b:a 384k -ac 2 -r 100 ^
-af "atrim=0.038, asetpts=PTS-STARTPTS, aresample=async=250" -vsync 1 -ss 00:00:01.096 -max_muxing_queue_size 9999 ^
-f segment -segment_time 600 -segment_wrap 9 -reset_timestamps 1 C:\Users\djcim\Videos\PC\PC\PC%02d.ts


text:
Q: WifiP2pInfo.groupOwnerAddress.getHostAddress() wrong IP I've got two devices - Note 3 (N9005) and G Pad 8.3 (also tested with Nexus 4 instead of the note 3, same results).
When I create a Wifi P2P group when the Note 3 is the group owner, on the G Pad (client) the method WifiP2pInfo.groupOwnerAddress.getHostAddress() return the right IP.
But when I create a Wifi P2P group when the G Pad is the group owner, on the Note 3 (client) the method return wrong IP address!
here is an ipconfig from the G Pad as group owner with the right ip address:

and here is the ECONNREFUSED exception on the Note 3 when trying to connect the given ip address:
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ java.net.ConnectException: failed to connect to /192.168.49.1 (port 7958) after 5000ms: isConnected failed: ECONNREFUSED (Connection refused)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at libcore.io.IoBridge.isConnected(IoBridge.java:223)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at libcore.io.IoBridge.connectErrno(IoBridge.java:161)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at libcore.io.IoBridge.connect(IoBridge.java:112)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:460)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at java.net.Socket.connect(Socket.java:833)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at com.yoavst.wifidirectlib.WifiP2P$5.run(WifiP2P.java:237)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at java.lang.Thread.run(Thread.java:841)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ Caused by: libcore.io.ErrnoException: isConnected failed: ECONNREFUSED (Connection refused)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ at libcore.io.IoBridge.isConnected(IoBridge.java:208)
11-25 21:04:53.264    4817-4986/com.example.wifidirect.app W/System.err﹕ ... 7 more

192.168.49.1 is not 192.168.49.129
Here are also the code, but I don't think it is the problem:
Client
Socket socket = new Socket();
                    socket.setReuseAddress(true);
                    socket.connect((new InetSocketAddress(info.groupOwnerAddress.getHostAddress(), PORT_GET_IP)), 5000);
                    OutputStream os = socket.getOutputStream();
                    ObjectOutputStream oos = new ObjectOutputStream(os);
                    oos.writeObject(HANDSHAKE_STRING);
                    oos.close();
                    os.close();
                    socket.close();

Server
ServerSocket serverSocket = new ServerSocket(PORT_GET_IP);
                            Socket client = serverSocket.accept();
                            ObjectInputStream objectInputStream = new ObjectInputStream(client.getInputStream());
                            Object object = objectInputStream.readObject();
                            if (object.getClass().equals(String.class) && object.equals(HANDSHAKE_STRING)) {
                                otherDeviceINetAddress = client.getInetAddress();
                                initClient(client.getInetAddress().toString().substring(1));
                            }

A: According to your last comment, you can't set the device you want as the group owner. What steps have you taken so far? Per the android documentation, you can try to set the Group Owner when you first try to connect via the WifiP2pConfig class setting the groupOwnerIntent However, this is not 100% reliable and the system may end up deciding who the group owner will be, specially if you had already established a connection in the past and the group information has been persisted.


text:
Q: "Screens not found" error when editing xorg.conf upon reboot This is my xorg.conf file:
Section "Screen"
    Identifier   "Screen0"
    Device       "Device0"
    Monitor      "Montior0"
    DefaultDepth 24
    Subsection   "Display"
        Depth      24
        Modes      "1024 x 768" "1280 x 960" "1366 x 768" "1280 x 1024" "1440 x 900" "1440 x 960" "1440 x 1080" "1600 x 1200" "1920 x 1080" "1920 x 1200"
    EndSubsection
EndSection

Section "Monitor"
    VendorName  "Monitor0"
    ModelName   "Model0"
    HorizSync   30 - 300
    VertRefresh 30 - 500
EndSection

        Modeline "1440x1080_60.00"  129.00  1440 1528 1680 1920  1080 1083 1087 1120 -hsync +vsync
When I reboot my PC, I find that I'm unable to get a graphical login.
The error I get is along the lines of:
Error in xorg.conf
This section must have an Identifier line.
EE problem/error parsing the config line
Fatal server error: no screens found

What's the reason for this and how can solve it?
All questions on this have no solutions...
Output of /var/log/Xorg.0.log:
[    34.304]
X.Org X Server 1.15.1
Release Date: 2014-04-13
[    34.304] X Protocol Version 11, Revision 0
[    34.304] Build Operating System: Linux 3.2.0-76-generic x86_64 Ubuntu
[    34.304] Current Operating System: Linux pointcarre-OptiPlex-755 3.13.0-24-generic #47-Ubuntu SMP Fri May 2 23:30:00 UTC 2014 x86_64
[    34.304] Kernel command line: BOOT_IMAGE=/boot/vmlinuz-3.13.0-24-generic root=UUID=94e3a36a-e676-4f71-b4fd-1edcc90700da ro quiet splash
[    34.304] Build Date: 12 February 2015  02:49:29PM
[    34.304] xorg-server 2:1.15.1-0ubuntu2.7 (For technical support please see http://www.ubuntu.com/support)
[    34.304] Current version of pixman: 0.30.2
[    34.304]    Before reporting problems, check http://wiki.x.org
    to make sure that you have the latest version.
[    34.304] Markers: (--) probed, (**) from config file, (==) default setting,
    (++) from command line, (!!) notice, (II) informational,
    (WW) warning, (EE) error, (NI) not implemented, (??) unknown.
[    34.304] (==) Log file: "/var/log/Xorg.0.log", Time: Fri Nov 13 21:00:30 2015
[    34.390] (==) Using system config directory "/usr/share/X11/xorg.conf.d"
[    34.427] (==) No Layout section.  Using the first Screen section.
[    34.427] (==) No screen section available. Using defaults.
[    34.427] (**) |-->Screen "Default Screen Section" (0)
[    34.427] (**) |   |-->Monitor ""
[    34.427] (==) No monitor specified for screen "Default Screen Section".
    Using a default monitor configuration.
[    34.427] (==) Automatically adding devices
[    34.427] (==) Automatically enabling devices
[    34.427] (==) Automatically adding GPU devices
[    34.427] (WW) The directory "/usr/share/fonts/X11/cyrillic" does not exist.
[    34.427]    Entry deleted from font path.
[    34.427] (WW) The directory "/usr/share/fonts/X11/100dpi/" does not exist.
[    34.427]    Entry deleted from font path.
[    34.427] (WW) The directory "/usr/share/fonts/X11/75dpi/" does not exist.
[    34.427]    Entry deleted from font path.
[    34.427] (WW) The directory "/usr/share/fonts/X11/100dpi" does not exist.
[    34.427]    Entry deleted from font path.
[    34.427] (WW) The directory "/usr/share/fonts/X11/75dpi" does not exist.
[    34.427]    Entry deleted from font path.
[    34.428] (==) FontPath set to:
    /usr/share/fonts/X11/misc,
    /usr/share/fonts/X11/Type1,
    built-ins
[    34.428] (==) ModulePath set to "/usr/lib/x86_64-linux-gnu/xorg/extra-modules,/usr/lib/xorg/extra-modules,/usr/lib/xorg/modules"
[    34.428] (II) The server relies on udev to provide the list of input devices.
    If no devices become available, reconfigure udev or disable AutoAddDevices.
[    34.428] (II) Loader magic: 0x7f4070706d40
[    34.428] (II) Module ABI versions:
[    34.428]    X.Org ANSI C Emulation: 0.4
[    34.428]    X.Org Video Driver: 15.0
[    34.428]    X.Org XInput driver : 20.0
[    34.428]    X.Org Server Extension : 8.0
[    34.428] (II) xfree86: Adding drm device (/dev/dri/card0)
[    34.429] (--) PCI:*(0:1:0:0) 10de:0a65:1043:848f rev 162, Mem @ 0xfd000000/16777216, 0xc0000000/268435456, 0xd0000000/33554432, I/O @ 0x0000dc80/128, BIOS @ 0x????????/524288
[    34.429] Initializing built-in extension Generic Event Extension
[    34.429] Initializing built-in extension SHAPE
[    34.429] Initializing built-in extension MIT-SHM
[    34.429] Initializing built-in extension XInputExtension
[    34.429] Initializing built-in extension XTEST
[    34.429] Initializing built-in extension BIG-REQUESTS
[    34.429] Initializing built-in extension SYNC
[    34.429] Initializing built-in extension XKEYBOARD
[    34.429] Initializing built-in extension XC-MISC
[    34.430] Initializing built-in extension SECURITY
[    34.430] Initializing built-in extension XINERAMA
[    34.430] Initializing built-in extension XFIXES
[    34.430] Initializing built-in extension RENDER
[    34.430] Initializing built-in extension RANDR
[    34.430] Initializing built-in extension COMPOSITE
[    34.430] Initializing built-in extension DAMAGE
[    34.430] Initializing built-in extension MIT-SCREEN-SAVER
[    34.430] Initializing built-in extension DOUBLE-BUFFER
[    34.430] Initializing built-in extension RECORD
[    34.430] Initializing built-in extension DPMS
[    34.430] Initializing built-in extension Present
[    34.430] Initializing built-in extension DRI3
[    34.430] Initializing built-in extension X-Resource
[    34.430] Initializing built-in extension XVideo
[    34.430] Initializing built-in extension XVideo-MotionCompensation
[    34.430] Initializing built-in extension SELinux
[    34.430] Initializing built-in extension XFree86-VidModeExtension
[    34.430] Initializing built-in extension XFree86-DGA
[    34.430] Initializing built-in extension XFree86-DRI
[    34.430] Initializing built-in extension DRI2
[    34.430] (WW) "glamoregl" will not be loaded unless you've specified it to be loaded elsewhere.
[    34.430] (II) "glx" will be loaded by default.
[    34.430] (WW) "xmir" is not to be loaded by default. Skipping.
[    34.430] (II) LoadModule: "glx"
[    34.430] (II) Loading /usr/lib/x86_64-linux-gnu/xorg/extra-modules/libglx.so
[    34.456] (II) Module glx: vendor="NVIDIA Corporation"
[    34.456]    compiled for 4.0.2, module version = 1.0.0
[    34.456]    Module class: X.Org Server Extension
[    34.456] (II) NVIDIA GLX Module  340.93  Wed Aug 19 16:23:51 PDT 2015
[    34.456] Loading extension GLX
[    34.456] (==) Matched nvidia as autoconfigured driver 0
[    34.456] (==) Matched nouveau as autoconfigured driver 1
[    34.456] (==) Matched nvidia as autoconfigured driver 2
[    34.456] (==) Matched nouveau as autoconfigured driver 3
[    34.456] (==) Matched modesetting as autoconfigured driver 4
[    34.456] (==) Matched fbdev as autoconfigured driver 5
[    34.456] (==) Matched vesa as autoconfigured driver 6
[    34.456] (==) Assigned the driver to the xf86ConfigLayout
[    34.456] (II) LoadModule: "nvidia"
[    34.456] (II) Loading /usr/lib/x86_64-linux-gnu/xorg/extra-modules/nvidia_drv.so
[    34.457] (II) Module nvidia: vendor="NVIDIA Corporation"
[    34.457]    compiled for 4.0.2, module version = 1.0.0
[    34.457]    Module class: X.Org Video Driver
[    34.457] (II) LoadModule: "nouveau"
[    34.457] (II) Loading /usr/lib/xorg/modules/drivers/nouveau_drv.so
[    34.472] (II) Module nouveau: vendor="X.Org Foundation"
[    34.472]    compiled for 1.15.0, module version = 1.0.10
[    34.472]    Module class: X.Org Video Driver
[    34.473]    ABI class: X.Org Video Driver, version 15.0
[    34.473] (II) LoadModule: "modesetting"
[    34.473] (II) Loading /usr/lib/xorg/modules/drivers/modesetting_drv.so
[    34.473] (II) Module modesetting: vendor="X.Org Foundation"
[    34.473]    compiled for 1.15.0, module version = 0.8.1
[    34.473]    Module class: X.Org Video Driver
[    34.473]    ABI class: X.Org Video Driver, version 15.0
[    34.473] (II) LoadModule: "fbdev"
[    34.473] (II) Loading /usr/lib/xorg/modules/drivers/fbdev_drv.so
[    34.473] (II) Module fbdev: vendor="X.Org Foundation"
[    34.473]    compiled for 1.15.0, module version = 0.4.4
[    34.473]    Module class: X.Org Video Driver
[    34.473]    ABI class: X.Org Video Driver, version 15.0
[    34.473] (II) LoadModule: "vesa"
[    34.474] (II) Loading /usr/lib/xorg/modules/drivers/vesa_drv.so
[    34.474] (II) Module vesa: vendor="X.Org Foundation"
[    34.474]    compiled for 1.15.0, module version = 2.3.3
[    34.474]    Module class: X.Org Video Driver
[    34.474]    ABI class: X.Org Video Driver, version 15.0
[    34.474] (II) NVIDIA dlloader X Driver  340.93  Wed Aug 19 16:01:53 PDT 2015
[    34.474] (II) NVIDIA Unified Driver for all Supported NVIDIA GPUs
[    34.474] (II) NOUVEAU driver Date:   Thu Nov 7 14:56:48 2013 +1000
[    34.474] (II) NOUVEAU driver for NVIDIA chipset families :
[    34.474]    RIVA TNT        (NV04)
[    34.474]    RIVA TNT2       (NV05)
[    34.474]    GeForce 256     (NV10)
[    34.474]    GeForce 2       (NV11, NV15)
[    34.474]    GeForce 4MX     (NV17, NV18)
[    34.474]    GeForce 3       (NV20)
[    34.474]    GeForce 4Ti     (NV25, NV28)
[    34.474]    GeForce FX      (NV3x)
[    34.474]    GeForce 6       (NV4x)
[    34.474]    GeForce 7       (G7x)
[    34.474]    GeForce 8       (G8x)
[    34.474]    GeForce GTX 200 (NVA0)
[    34.474]    GeForce GTX 400 (NVC0)
[    34.474] (II) modesetting: Driver for Modesetting Kernel Drivers: kms
[    34.474] (II) FBDEV: driver for framebuffer: fbdev
[    34.474] (II) VESA: driver for VESA chipsets: vesa
[    34.474] (++) using VT number 8

[    34.477] (II) Loading sub module "fb"
[    34.477] (II) LoadModule: "fb"
[    34.532] (II) Loading /usr/lib/xorg/modules/libfb.so
[    34.532] (II) Module fb: vendor="X.Org Foundation"
[    34.532]    compiled for 1.15.1, module version = 1.0.0
[    34.532]    ABI class: X.Org ANSI C Emulation, version 0.4
[    34.532] (WW) Unresolved symbol: fbGetGCPrivateKey
[    34.532] (II) Loading sub module "wfb"
[    34.532] (II) LoadModule: "wfb"
[    34.533] (II) Loading /usr/lib/xorg/modules/libwfb.so
[    34.533] (II) Module wfb: vendor="X.Org Foundation"
[    34.533]    compiled for 1.15.1, module version = 1.0.0
[    34.533]    ABI class: X.Org ANSI C Emulation, version 0.4
[    34.533] (II) Loading sub module "ramdac"
[    34.533] (II) LoadModule: "ramdac"
[    34.533] (II) Module "ramdac" already built-in
[    34.533] (WW) Falling back to old probe method for modesetting
[    34.534] (WW) Falling back to old probe method for fbdev
[    34.534] (II) Loading sub module "fbdevhw"
[    34.534] (II) LoadModule: "fbdevhw"
[    34.534] (II) Loading /usr/lib/xorg/modules/libfbdevhw.so
[    34.534] (II) Module fbdevhw: vendor="X.Org Foundation"
[    34.534]    compiled for 1.15.1, module version = 0.0.2
[    34.534]    ABI class: X.Org Video Driver, version 15.0
[    34.534] (EE) open /dev/fb0: No such file or directory
[    34.534] (WW) Falling back to old probe method for vesa
[    34.534] (II) NVIDIA(0): Creating default Display subsection in Screen section
    "Default Screen Section" for depth/fbbpp 24/32
[    34.534] (==) NVIDIA(0): Depth 24, (==) framebuffer bpp 32
[    34.534] (==) NVIDIA(0): RGB weight 888
[    34.534] (==) NVIDIA(0): Default visual is TrueColor
[    34.534] (==) NVIDIA(0): Using gamma correction (1.0, 1.0, 1.0)
[    34.534] (**) NVIDIA(0): Enabling 2D acceleration
[    35.126] (II) NVIDIA(0): Display (Samsung SyncMaster (DFP-0)) does not support NVIDIA
[    35.126] (II) NVIDIA(0):     3D Vision stereo.
[    35.126] (II) NVIDIA(GPU-0): Found DRM driver nvidia-drm (20150116)
[    35.127] (II) NVIDIA(0): NVIDIA GPU GeForce 210 (GT218) at PCI:1:0:0 (GPU-0)
[    35.127] (--) NVIDIA(0): Memory: 1048576 kBytes
[    35.127] (--) NVIDIA(0): VideoBIOS: 70.18.64.00.05
[    35.127] (II) NVIDIA(0): Detected PCI Express Link width: 16X
[    35.129] (--) NVIDIA(0): Valid display device(s) on GeForce 210 at PCI:1:0:0
[    35.129] (--) NVIDIA(0):     CRT-0
[    35.129] (--) NVIDIA(0):     CRT-1
[    35.129] (--) NVIDIA(0):     Samsung SyncMaster (DFP-0) (boot, connected)
[    35.129] (--) NVIDIA(0):     DFP-1
[    35.129] (--) NVIDIA(GPU-0): CRT-0: 400.0 MHz maximum pixel clock
[    35.129] (--) NVIDIA(GPU-0): CRT-1: 400.0 MHz maximum pixel clock
[    35.129] (--) NVIDIA(0): Samsung SyncMaster (DFP-0): Internal TMDS
[    35.129] (--) NVIDIA(GPU-0): Samsung SyncMaster (DFP-0): 330.0 MHz maximum pixel clock
[    35.129] (--) NVIDIA(0): DFP-1: Internal TMDS
[    35.129] (--) NVIDIA(GPU-0): DFP-1: 165.0 MHz maximum pixel clock
[    35.129] (**) NVIDIA(0): Using HorizSync/VertRefresh ranges from the EDID for display
[    35.129] (**) NVIDIA(0):     device Samsung SyncMaster (DFP-0) (Using EDID frequencies
[    35.129] (**) NVIDIA(0):     has been enabled on all display devices.)
[    35.132] (==) NVIDIA(0):
[    35.132] (==) NVIDIA(0): No modes were requested; the default mode "nvidia-auto-select"
[    35.132] (==) NVIDIA(0):     will be used as the requested mode.
[    35.132] (==) NVIDIA(0):
[    35.132] (II) NVIDIA(0): Validated MetaModes:
[    35.132] (II) NVIDIA(0):     "DFP-0:nvidia-auto-select"
[    35.132] (II) NVIDIA(0): Virtual screen size determined to be 1280 x 1024
[    35.156] (--) NVIDIA(0): DPI set to (95, 96); computed from "UseEdidDpi" X config
[    35.156] (--) NVIDIA(0):     option
[    35.156] (II) UnloadModule: "nouveau"
[    35.156] (II) Unloading nouveau
[    35.156] (II) UnloadModule: "modesetting"
[    35.156] (II) Unloading modesetting
[    35.156] (II) UnloadModule: "fbdev"
[    35.157] (II) Unloading fbdev
[    35.157] (II) UnloadSubModule: "fbdevhw"
[    35.157] (II) Unloading fbdevhw
[    35.157] (II) UnloadModule: "vesa"
[    35.157] (II) Unloading vesa
[    35.157] (--) Depth 24 pixmap format is 32 bpp
[    35.157] (II) NVIDIA: Using 768.00 MB of virtual memory for indirect memory access.
[    35.161] (II) NVIDIA(0): Setting mode "DFP-0:nvidia-auto-select"
[    35.212] Loading extension NV-GLX
[    35.237] (==) NVIDIA(0): Disabling shared memory pixmaps
[    35.237] (==) NVIDIA(0): Backing store enabled
[    35.237] (==) NVIDIA(0): Silken mouse enabled
[    35.237] (==) NVIDIA(0): DPMS enabled
[    35.237] Loading extension NV-CONTROL
[    35.238] Loading extension XINERAMA
[    35.238] (II) Loading sub module "dri2"
[    35.238] (II) LoadModule: "dri2"
[    35.238] (II) Module "dri2" already built-in
[    35.238] (II) NVIDIA(0): [DRI2] Setup complete
[    35.238] (II) NVIDIA(0): [DRI2]   VDPAU driver: nvidia
[    35.238] (--) RandR disabled
[    35.244] (II) SELinux: Disabled on system
[    35.245] (II) Initializing extension GLX
[    35.261] (II) XKB: reuse xkmfile /var/lib/xkb/server-B20D7FC79C7F597315E3E501AEF10E0D866E8E92.xkm
[    35.265] (II) config/udev: Adding input device Power Button (/dev/input/event1)
[    35.265] (**) Power Button: Applying InputClass "evdev keyboard catchall"
[    35.265] (II) LoadModule: "evdev"
[    35.265] (II) Loading /usr/lib/xorg/modules/input/evdev_drv.so
[    35.285] (II) Module evdev: vendor="X.Org Foundation"
[    35.285]    compiled for 1.15.0, module version = 2.8.2
[    35.285]    Module class: X.Org XInput Driver
[    35.285]    ABI class: X.Org XInput driver, version 20.0
[    35.285] (II) Using input driver 'evdev' for 'Power Button'
[    35.285] (**) Power Button: always reports core events
[    35.285] (**) evdev: Power Button: Device: "/dev/input/event1"
[    35.285] (--) evdev: Power Button: Vendor 0 Product 0x1
[    35.285] (--) evdev: Power Button: Found keys
[    35.285] (II) evdev: Power Button: Configuring as keyboard
[    35.285] (**) Option "config_info" "udev:/sys/devices/LNXSYSTM:00/LNXPWRBN:00/input/input1/event1"
[    35.285] (II) XINPUT: Adding extended input device "Power Button" (type: KEYBOARD, id 6)
[    35.285] (**) Option "xkb_rules" "evdev"
[    35.285] (**) Option "xkb_model" "pc105"
[    35.285] (**) Option "xkb_layout" "gb"
[    35.287] (II) XKB: reuse xkmfile /var/lib/xkb/server-2B4266AA55228AE7D9557A18F1965DBA19850816.xkm
[    35.288] (II) config/udev: Adding input device Power Button (/dev/input/event0)
[    35.288] (**) Power Button: Applying InputClass "evdev keyboard catchall"
[    35.288] (II) Using input driver 'evdev' for 'Power Button'
[    35.288] (**) Power Button: always reports core events
[    35.288] (**) evdev: Power Button: Device: "/dev/input/event0"
[    35.288] (--) evdev: Power Button: Vendor 0 Product 0x1
[    35.288] (--) evdev: Power Button: Found keys
[    35.288] (II) evdev: Power Button: Configuring as keyboard
[    35.288] (**) Option "config_info" "udev:/sys/devices/LNXSYSTM:00/device:00/PNP0C0C:00/input/input0/event0"
[    35.288] (II) XINPUT: Adding extended input device "Power Button" (type: KEYBOARD, id 7)
[    35.288] (**) Option "xkb_rules" "evdev"
[    35.288] (**) Option "xkb_model" "pc105"
[    35.288] (**) Option "xkb_layout" "gb"
[    35.288] (II) config/udev: Adding drm device (/dev/dri/card0) card0 /sys/devices/pci0000:00/0000:00:01.0/0000:01:00.0/drm/card0
[    35.288] (II) config/udev: Ignoring already known drm device (/dev/dri/card0)
[    35.289] (II) config/udev: Adding input device HDA NVidia HDMI/DP,pcm=3 (/dev/input/event12)
[    35.289] (II) No input driver specified, ignoring this device.
[    35.289] (II) This device may have been added with another device file.
[    35.289] (II) config/udev: Adding input device HDA NVidia HDMI/DP,pcm=7 (/dev/input/event11)
[    35.289] (II) No input driver specified, ignoring this device.
[    35.289] (II) This device may have been added with another device file.
[    35.290] (II) config/udev: Adding input device HDA NVidia HDMI/DP,pcm=8 (/dev/input/event10)
[    35.290] (II) No input driver specified, ignoring this device.
[    35.290] (II) This device may have been added with another device file.
[    35.290] (II) config/udev: Adding input device HDA NVidia HDMI/DP,pcm=9 (/dev/input/event9)
[    35.290] (II) No input driver specified, ignoring this device.
[    35.290] (II) This device may have been added with another device file.
[    35.290] (II) config/udev: Adding input device HDA Intel Line Out (/dev/input/event6)
[    35.290] (II) No input driver specified, ignoring this device.
[    35.290] (II) This device may have been added with another device file.
[    35.291] (II) config/udev: Adding input device HDA Intel Front Headphone (/dev/input/event5)
[    35.291] (II) No input driver specified, ignoring this device.
[    35.291] (II) This device may have been added with another device file.
[    35.291] (II) config/udev: Adding input device HDA Intel Mic (/dev/input/event8)
[    35.291] (II) No input driver specified, ignoring this device.
[    35.291] (II) This device may have been added with another device file.
[    35.291] (II) config/udev: Adding input device HDA Intel Line (/dev/input/event7)
[    35.291] (II) No input driver specified, ignoring this device.
[    35.291] (II) This device may have been added with another device file.
[    35.292] (II) config/udev: Adding input device USB OPTICAL MOUSE (/dev/input/event2)
[    35.292] (**) USB OPTICAL MOUSE: Applying InputClass "evdev pointer catchall"
[    35.292] (II) Using input driver 'evdev' for 'USB OPTICAL MOUSE'
[    35.292] (**) USB OPTICAL MOUSE: always reports core events
[    35.292] (**) evdev: USB OPTICAL MOUSE: Device: "/dev/input/event2"
[    35.292] (--) evdev: USB OPTICAL MOUSE: Vendor 0x93a Product 0x2516
[    35.292] (--) evdev: USB OPTICAL MOUSE: Found 3 mouse buttons
[    35.292] (--) evdev: USB OPTICAL MOUSE: Found scroll wheel(s)
[    35.292] (--) evdev: USB OPTICAL MOUSE: Found relative axes
[    35.292] (--) evdev: USB OPTICAL MOUSE: Found x and y relative axes
[    35.292] (II) evdev: USB OPTICAL MOUSE: Configuring as mouse
[    35.292] (II) evdev: USB OPTICAL MOUSE: Adding scrollwheel support
[    35.292] (**) evdev: USB OPTICAL MOUSE: YAxisMapping: buttons 4 and 5
[    35.292] (**) evdev: USB OPTICAL MOUSE: EmulateWheelButton: 4, EmulateWheelInertia: 10, EmulateWheelTimeout: 200
[    35.292] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1d.2/usb7/7-1/7-1:1.0/input/input5/event2"
[    35.292] (II) XINPUT: Adding extended input device "USB OPTICAL MOUSE" (type: MOUSE, id 8)
[    35.292] (II) evdev: USB OPTICAL MOUSE: initialized for relative axes.
[    35.292] (**) USB OPTICAL MOUSE: (accel) keeping acceleration scheme 1
[    35.292] (**) USB OPTICAL MOUSE: (accel) acceleration profile 0
[    35.292] (**) USB OPTICAL MOUSE: (accel) acceleration factor: 2.000
[    35.292] (**) USB OPTICAL MOUSE: (accel) acceleration threshold: 4
[    35.293] (II) config/udev: Adding input device USB OPTICAL MOUSE (/dev/input/mouse0)
[    35.293] (II) No input driver specified, ignoring this device.
[    35.293] (II) This device may have been added with another device file.
[    35.293] (II) config/udev: Adding input device Chicony USB Keyboard (/dev/input/event3)
[    35.293] (**) Chicony USB Keyboard: Applying InputClass "evdev keyboard catchall"
[    35.293] (II) Using input driver 'evdev' for 'Chicony USB Keyboard'
[    35.293] (**) Chicony USB Keyboard: always reports core events
[    35.293] (**) evdev: Chicony USB Keyboard: Device: "/dev/input/event3"
[    35.293] (--) evdev: Chicony USB Keyboard: Vendor 0x4f2 Product 0x402
[    35.293] (--) evdev: Chicony USB Keyboard: Found keys
[    35.293] (II) evdev: Chicony USB Keyboard: Configuring as keyboard
[    35.293] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1d.2/usb7/7-2/7-2:1.0/input/input6/event3"
[    35.293] (II) XINPUT: Adding extended input device "Chicony USB Keyboard" (type: KEYBOARD, id 9)
[    35.293] (**) Option "xkb_rules" "evdev"
[    35.293] (**) Option "xkb_model" "pc105"
[    35.293] (**) Option "xkb_layout" "gb"
[    35.294] (II) config/udev: Adding input device Chicony USB Keyboard (/dev/input/event4)
[    35.294] (**) Chicony USB Keyboard: Applying InputClass "evdev keyboard catchall"
[    35.294] (II) Using input driver 'evdev' for 'Chicony USB Keyboard'
[    35.294] (**) Chicony USB Keyboard: always reports core events
[    35.294] (**) evdev: Chicony USB Keyboard: Device: "/dev/input/event4"
[    35.294] (--) evdev: Chicony USB Keyboard: Vendor 0x4f2 Product 0x402
[    35.294] (--) evdev: Chicony USB Keyboard: Found keys
[    35.294] (II) evdev: Chicony USB Keyboard: Configuring as keyboard
[    35.294] (**) Option "config_info" "udev:/sys/devices/pci0000:00/0000:00:1d.2/usb7/7-2/7-2:1.1/input/input7/event4"
[    35.294] (II) XINPUT: Adding extended input device "Chicony USB Keyboard" (type: KEYBOARD, id 10)
[    35.294] (**) Option "xkb_rules" "evdev"
[    35.294] (**) Option "xkb_model" "pc105"
[    35.294] (**) Option "xkb_layout" "gb"
[   111.577] (II) NVIDIA(GPU-0): Display (Samsung SyncMaster (DFP-0)) does not support NVIDIA
[   111.577] (II) NVIDIA(GPU-0):     3D Vision stereo.
[   117.074] (II) NVIDIA(GPU-0): Display (Samsung SyncMaster (DFP-0)) does not support NVIDIA
[   117.074] (II) NVIDIA(GPU-0):     3D Vision stereo.
[   117.811] (II) NVIDIA(GPU-0): Display (Samsung SyncMaster (DFP-0)) does not support NVIDIA
[   117.811] (II) NVIDIA(GPU-0):     3D Vision stereo.
[   118.912] (II) XKB: reuse xkmfile /var/lib/xkb/server-7996F6726817F73651B9DE0FDA11E35FC4524568.xkm
[   119.477] (II) XKB: reuse xkmfile /var/lib/xkb/server-F4830027FD6DFAF7D5CB4AF430AE062CB8989800.xkm
[   139.935] (II) NVIDIA(GPU-0): Display (Samsung SyncMaster (DFP-0)) does not support NVIDIA
[   139.935] (II) NVIDIA(GPU-0):     3D Vision stereo.
[   150.687] (II) XKB: reuse xkmfile /var/lib/xkb/server-F4830027FD6DFAF7D5CB4AF430AE062CB8989800.xkm
[   150.691] (II) XKB: reuse xkmfile /var/lib/xkb/server-F4830027FD6DFAF7D5CB4AF430AE062CB8989800.xkm
[   150.695] (II) XKB: reuse xkmfile /var/lib/xkb/server-F4830027FD6DFAF7D5CB4AF430AE062CB8989800.xkm
[   150.698] (II) XKB: reuse xkmfile /var/lib/xkb/server-F4830027FD6DFAF7D5CB4AF430AE062CB8989800.xkm
[   150.702] (II) XKB: reuse xkmfile /var/lib/xkb/server-F4830027FD6DFAF7D5CB4AF430AE062CB8989800.xkm
[   150.706] (II) XKB: reuse xkmfile /var/lib/xkb/server-F4830027FD6DFAF7D5CB4AF430AE062CB8989800.xkm

A: The error is exactly what it says. One of your sections (in the xorg.conf file) does not have an Identifier line.
The Section "Monitor" section has VendorName, ModelName, HorizSync and VertRefresh lines but no Identifier.
Add the following line directly after Section "Monitor" and before VendorName:
Identifier   "Monitor0"
Your Section "Screen" references a Monitor "Montior0" (sic). Therefore it needs to find a Monitor with the Identifier "Montior0" (sic). It also highlights a possible typo there too.
Therefore, change "Montior0" to "Monitor0" in the Section "Screen" and add the Identifier "Monitor0" line in the Section "Monitor". Hopefully that should do it.
In case you (or future readers of this post) don't know how: Edit the xorg.conf file with the following command:
sudo nano /etc/X11/xorg.conf

A: To expand on my comment into a more accessible answer, there are 2 steps to attempt to fix this.

*

*Move (Delete) ~/.config/monitors.xml
Step 1: Since we cannot use a GUI (Graphical User Interface) we will have to boot into Grub.
Step 2: Once in Grub, enable networking, then drop to shell prompt.
Step 3: Once in Grub do mv ~/.config/monitors.xml ~/.config/old_monitors.xml
Step 4: Move on to the second step we will need to do (Re-installing xorg)
<>

*Re-install Xorg
Pre-steps: Repeat steps 1 & 2 from above, to get to shell.
Step 1: Do apt-get purge xauth
Step 2: Do apt-get autoremove
Step 3: Do apt-get install xauth
Step 4: Do reboot now
Done! Enjoy your new working Xorg installation!


text:
Q: Trouble with variable replacement I'm having a lot of trouble with functions build from other functions. I'm struggling to understand the nuance of variable replacement. Here is an example:
p2[x_, l_, m_] := ((-1)^m / (2^l l!) * (1 - x^2)^(m/2) * D[(y^2 - 1)^l, {y, l + m}]) /. y -> x

p3[x_, l_, m_] = p2[x, l, m] * 1;

The p2 equation works, for example:
p2[x, 2, 1] $-3x\sqrt{1-x^2}$, and p2[1/2, 2, 1] $=-\frac{1}{4} \left(3 \sqrt{3}\right)$.
But the second equation doesn't work, p3[1/2, 2, 1] gives the error: General::ivar: 1/2 is not a valid variable.
The second equation only works if I replace $x$ afterwards. p3[x, 2, 1] /. x -> 1/2 $=-\frac{1}{4} \left(3 \sqrt{3}\right)$. I don't understand this behavior.

A: Your troubles comes from the derivative. To do away with not relevant factors, define p2 as:
p2[x_, l_, m_] := (D[(y^2 - 1)^l, {y, l + m}]) /. y -> x
By using "Set" and not "SetDelayed" you are evaluating p3 at once. By specifying p3[x_, l_, m_] = p2[x, l, m] * 1; you actually evaluate p2 with unknown variables x,l,m. This results in:

This means: take the (1+m) th derivative of (-1+x^2)^l relative to x.
If you now call p3[1/2, 2, 1] you replace x by 1/2, l by 2  and m by 1, resulting in

This means derive 9/16 relative to 1/2 three times, what is nonsense.
On the other hand, if you use "SetDelayed", specifying:
p3[x_, l_, m_] := p2[x, l, m]*1;

p2 is only evaluate when x,l, and m are known and x,l and m are replaced by their numerical values before p2 is evaluated. The derivative now reads:

what makes sense.


text:
Q: Is it possible to set a button layout from FXML? I just want to ask when I make a new button in JavaFX within an FXML scene, is it possible to load the layout of the button from a supplementary FXML file?
For instance, instead of manually creating a button like this:
(Note: Not supposed to be correct code, just an example)
Button a = new Button();
HBox b = new HBox();
a.getChildren().add(b);
a.setOpacity(0.5)

would it be possible to load it from a supplementary FXML file? A file that would contain all basic properties.. like size, position, contents, images, etc. Something like:
FXMLLoader b = new FXMLLoader(getClass().getResource(fxmlPath));
Button a = b.loadElement(id_of_a_in_fxmlfile);

Is this a thing?

A: Okay indeed this isn't a function currently available in JavaFX, HOWEVER..
It is possible using AOP (AspectJ) to define an extra method within FXMLLoader to allow this, but of course you'd have to analyze how FXMLLoader opens and loads FXML files and define the behavior yourself.
This is currently the only way.


text:
Q: mssql server database inserting more rows than expected in pandas iterrows odbc driver ubuntu machine print(f"df_shape {df.shape}")
 (3497, 39)

But, I see row above 30 thousand getting imported in to database.
for index, row in df.iterrows():
    cursor.execute('INSERT INTO tbl_A(Sno,A,B) \
     values(?,?,?,)', \
         row.Sno, row.A, row.B)
cnxn.commit()
cursor.close()

A: Similar approached solved the issue,
df = df.loc[~df.index.duplicated()]
Pandas `groupby.aggregate` on `df.index.duplicated()`
duplicate removal Pandas concat: ValueError: Shape of passed values is blah, indices imply blah2


text:
Q: C++ Random Number 1,0 Not Working I am trying to put either an X or an O in an array.  It doesn't seem to work, however.  It says, "Run-Time Check Failure #2 - Stack around the variable 'row1' was corrupted."
char row1[19];
char row2[19];
char row3[19];
char row4[19];

for (int i = 0; i < 20; i++)
{
    int r = int(((double) rand() / (RAND_MAX)) + 1);

    if (r == 0)
    {
        row1[i] = 'X';
    }
    else
    {
        row1[i] = 'O';
    }

}

cout << row1[0] << endl;

How can I generate a random X or O?  Thank you.

A: As elmigranto stated: your loop is incorrect. It should be:
for (int i = 0; i < 19; i++)

That is because char row4[19]; is an array that contains 19 elements. The first element is row4[0] and the last is row4[18] because the numbering is starts from 0. So in the last loop row[19] will cause an error.

A: If you want a coin flipping, you could do something like
char row1[20];
char row2[20];
char row3[20];
char row4[20];

for (int i = 0; i < 20; i++)
{
    int r = rand() % 2;

    if (r == 0)
    {
        row1[i] = 'X';
    }
    else
    {
        row1[i] = 'O';
    }

}

although I have no idea what row2 - row4 are for in your code. The stack corruption occurs with row1[19], since you specified 19 elements only, but 0..19 means 20 elements needed.

A: const int arr_size = 19;
char row1[arr_size];

for (int i = 0; i < arr_size; ++i) {
    row1[i] = rand() % 2 ? 'O' : 'X';
}