text:
Q: Writing in a binary file My program scans names and birth years and stores them in an array of structures. Scanning from keyboard and printing in screen works fine, but I'm not sure whether printing in my binary file is correct because my program runs without errors and I can't check if the data has been printed correctly in the binary file.
My question is about whether the syntax of my "fwrite" functions is correct.
#include <stdio.h>

#define MAXNAME 50 //size of name
#define MAXPERSONS 2 //Max num of persons

typedef struct{
    char name[MAXNAME];
    int year;
}person_t;

int read_person(person_t[], int);//scans the person
int write_person(const person_t[], int, FILE*);//prints the persons in the screen and the bfile

int main()
{
    FILE *pfile;
    person_t v[3];
    int iscan=0,iprint;

    if((pfile=fopen("persons.bin","wb"))==NULL) printf("couldnt open<vehicles.txt>\n");

    else{
        while(iscan<MAXPERSONS){
            read_person(&v[iscan],iscan+1);
            iscan++;
        }
        for(iprint=0;iprint<iscan;iprint++)
            write_person(&v[iprint],iprint+1,pfile);
    }
    fclose(pfile);
    printf("\n\n");
    return 0;
}

int read_person(person_t v[],int i)
{
    printf("Person %d",i);
    printf("\n\tName: ");
    fflush(stdin);
    gets(v->name);
    printf("\n\tYear: ");
    scanf("%d",&v->year);
}

int write_person(const person_t v[],int j, FILE *pfile)
{
    //print in screen
    printf("\nPerson %d",j);
    printf("\n\tName: %s\n",v->name);
    printf("\n\tYear: %d\n",v->year);

    //print in the binary file
    fwrite(v->name,sizeof(char),1,pfile);
    fwrite(&v->year,sizeof(int),1,pfile);
}

This program reads from the bin file
    #include<stdio.h>

#define MAXNAME 50 //size of name
#define MAXPERSONS 2 //Max num of persons

typedef struct{
    char name[MAXNAME];
    int year;
}person_t;

int read_person(person_t[], int, FILE*);
int write_person(const person_t[], int);
int main(){
    FILE *pfile;
    person_t v[3];
    int iscan=0,iprint;

    if((pfile=fopen("persons.bin","rb"))==NULL) printf("couldnt open<vehicles.txt>\n");

    else{
        while(iscan<MAXPERSONS){
        read_person(&v[iscan],iscan+1,pfile);
        iscan++;
        }
        for(iprint=0;iprint<iscan;iprint++)
            write_person(&v[iprint],iprint+1);
    }
fclose(pfile);
printf("\n\n");
return 0;
}
int read_person(person_t v[],int i, FILE *pfile){
    //read from the binary file
    fread(v->name, sizeof(v->name),1,pfile);
    fread(&v->year,sizeof(v->year),1,pfile);
}
int write_person(const person_t v[],int j){
    //print in screen
     printf("\nPerson %d",j);
        printf("\n\tName: %s\n",v->name);
        printf("\n\tYear: %d\n",v->year);
}

A: Suggest changing fwite() to write the full size of person_t.
int write_person(const person_t v[], int j, FILE *pfile) {
  //print in screen
  printf("\nPerson %d",j);
  printf("\n\tName: %s\n",v[j].name);
  printf("\n\tYear: %d\n",v[j].year);

  //print in the binary file
  if (1 != fwrite(&v[j], sizeof(v[j]),1, pfile)) handle_error();
  return 0;
}

int read_person(person_t v[], int i) {
  printf("Person %d",i);
  printf("\n\tName: ");
  //  don't do this fflush(stdin);
  // consider scanf() gets(v.name);
  // " %49[^\n]": space to consume leading whitespace, 49 (50 -1 ) limit input, [^\n] to read any text but \n
  if (1 != scanf(" %49[\n]", v[i].name)) handle_error();
  printf("\n\tYear: ");
  if (1 != scanf("%d",&v[i].year)) handle_error();
  return 0;
}

A: You might consider writing and reading the entire person_t struct.
int write_person(const person_t v[],int j, FILE *pfile)
{
    //print in screen
    printf("\nPerson %d",j);
    printf("\n\tName: %s\n",v[j].name);
    printf("\n\tYear: %d\n",v[j].year);
    fwrite(&(v[j]),sizeof(person_t),1,pfile);
}

The general idea you are approaching is called 'serialization' or 'marshalling' (depending upon author).  There are many ways serialize or marshall data, but some good approaches are JSON, UBJSON, MessagePack, and ProtocolBuffers, among others.


text:
Q: How do I rerun a successful azure devops YAML pipeline stage, and any stages that follow? Stages A->B->C->D.
C failed with an error that implicates a problem in stage B's output, even though it succeeded. As a failed stage I can rerun C, and D will run if it succeeds (in this instance it still fails). I can rerun B, it succeeds again, but C and D are then "skipped" and I can't find a way to (re)run them.
How do I rerun B such that C and D will follow on success?

A: If you click on your stage box on the main pipeline window, you will see an up and down arrow.  Click on this to expand the stage and then there is a button to re-run the stage.  You could always grab the requests it sends (f12) if you need to do this programatically.

A: I made a test using this build configuration:
stages:
- stage: Test
  jobs:
  - job: A
    steps:
    - bash: echo "A"

- stage: DeployUS1
  dependsOn: Test    # this stage runs after Test
  jobs:
  - job: A
    steps:
    - bash: echo "A"
    - powershell: Invoke-WebRequest -URI https://some-endpoint.free.beeceptor.com/my/api/some

- stage: DeployUS2
  dependsOn: Test    # this stage runs in parallel with DeployUS1, after Test
  jobs:
  - job: A
    steps:
    - bash: echo "A"

- stage: DeployEurope
  dependsOn:         # this stage runs after DeployUS1 and DeployUS2
  - DeployUS1
  - DeployUS2
  jobs:
  - job: A
    steps:
    - bash: echo "A"

I made stage DeployUS1 failing by returning 404 from https://some-endpoint.free.beeceptor.com/my/api/some, and thus:

When I fixed this by changing mock rules to return 200 and I reran failing jobs I got DeployUS1 and next stage DeployEurope executed:

This works as you expected and docs says:

You can now retry a pipeline stage when the execution fails. Any jobs that failed in the first attempt and those that depend transitively on those failed jobs are all re-attempted.

So if you observed different than this it may be caused by misssing dependency:
stages:
- stage: FunctionalTest
  jobs:
  - job:
    ...

- stage: AcceptanceTest
  dependsOn: []    # this removes the implicit dependency on previous stage and causes this to run in parallel
  jobs:
  - job:
    ...

I reran Test which passed and it triggered next stages:

When DeployUS1 and DeployUS2 finished DeployEurope started autmatically:

redpajama_set_name: RedPajamaStackExchange


text:
Q: How can I bind to a helper property in Silverlight For the sake of argument, here's a simple person class
public class Person : DependencyObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public static readonly DependencyProperty FirstNameProperty =
        DependencyProperty.Register( "FirstName",
                                     typeof ( string ),
                                     typeof ( Person ),
                                     null );
    public static readonly DependencyProperty LastNameProperty =
        DependencyProperty.Register( "LastName",
                                     typeof( string ),
                                     typeof( Person ),
                                     null );

    public string FirstName
    {
        get
        {
            return ( string ) GetValue( FirstNameProperty );
        }
        set
        {
            SetValue( FirstNameProperty, value );
            if(PropertyChanged != null)
                PropertyChanged(this, new PropertyChangedEventArgs( "FirstName" ));
        }
    }

    public string LastName
    {
        get
        {
            return ( string ) GetValue( LastNameProperty );
        }
        set
        {
            SetValue( LastNameProperty, value );
            if ( PropertyChanged != null )
                PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) );
        }
    }
}

I want to go about creating a readonly property like this
public string FullName
    {
        get { return FirstName + " " + LastName; }
    }

How does binding work in this scenario? I've tried adding a DependancyProperty and raised the PropertyChanged event for the fullname. Basically I just want to have a property that I can bind to that returns the fullname of a user whenever the first or last name changes. Here's the final class I'm using with the modifications.
public class Person : DependencyObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public static readonly DependencyProperty FirstNameProperty =
        DependencyProperty.Register( "FirstName",
                                     typeof ( string ),
                                     typeof ( Person ),
                                     null );
    public static readonly DependencyProperty LastNameProperty =
        DependencyProperty.Register( "LastName",
                                     typeof( string ),
                                     typeof( Person ),
                                     null );
    public static readonly DependencyProperty FullNameProperty =
        DependencyProperty.Register( "FullName",
                                     typeof( string ),
                                     typeof( Person ),
                                     null );

    public string FirstName
    {
        get
        {
            return ( string ) GetValue( FirstNameProperty );
        }
        set
        {
            SetValue( FirstNameProperty, value );
            if ( PropertyChanged != null )
            {
                PropertyChanged( this, new PropertyChangedEventArgs( "FirstName" ) );
                PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) );
            }
        }
    }

    public string LastName
    {
        get
        {
            return ( string ) GetValue( LastNameProperty );
        }
        set
        {
            SetValue( LastNameProperty, value );
            if ( PropertyChanged != null )
            {
                PropertyChanged( this, new PropertyChangedEventArgs( "LastName" ) );
                PropertyChanged( this, new PropertyChangedEventArgs( "FullName" ) );
            }
        }
    }

    public string FullName
    {
        get { return GetValue( FirstNameProperty ) + " " + GetValue( LastNameProperty ); }
    }
}

A: I'm not sure what you are trying to achieve here, but why is your Person class inheriting from DependencyObject and why are FirstName and LastName DependencyProperties?  If all you want to do is bind the Person properties to user controls on your view, having the Person class implementing INotifyPropertyChanged is enough to make the data binding work.  You will typically bind it to properties of a user control that are dependency properties (eg the Text property of a TextBlock).
Try this for you Person class:
using System.ComponentModel;
public class Person : INotifyPropertyChanged
{
    #region INotifyPropertyChanged Members

    public event PropertyChangedEventHandler PropertyChanged;

    private void RaisePropertyChanged(string propertyName)
    {
        if (PropertyChanged != null)
        {
            PropertyChanged(this, new PropertyChangedEventArgs(propertyName));
        }
    }

    #endregion

    private string _firstName;
    public string FirstName
    {
        get { return _firstName; }
        set
        {
            if (value != _firstName)
            {
                _firstName = value;
                RaisePropertyChanged("FirstName");
                RaisePropertyChanged("FullName");
            }
        }
    }

    private string _lastName;
    public string LastName
    {
        get { return _lastName; }
        set
        {
            if (value != _lastName)
            {
                _lastName = value;
                RaisePropertyChanged("LastName");
                RaisePropertyChanged("FullName");
            }
        }
    }

    public string FullName
    {
        get { return FirstName + " " + LastName; }
    }
}

And use it like this in your view:
<Grid x:Name="LayoutRoot" Background="White" >
    <TextBlock Text="{Binding FullName}"/>
</Grid>

Then, in your codebehind, you could instantiate it like so:
public partial class MainPage : UserControl
{
    public MainPage()
    {
        InitializeComponent();

        DataContext = new Person { FirstName = "John", LastName = "Doe" };
    }
}

HTH,
Phil

A: First of all your implementation of the existing FirstName and LastName properties is flawed.  The DependencyObject already has ways to inform bindings of changes to the values and values can be changed by other mechanism than calling the Setter methods.
My first question would be why are FirstName and LastName dependency properties at all?  That seems like a strange choice for this type of class.  Phil's answer has already provided what I would really expect the correct answer to be.
However in case your code was actually a simplification and that there is in fact a genuine need to create dependency properties here is how it should be done:-
public class Person : DependencyObject, INotifyPropertyChanged
{
    public event PropertyChangedEventHandler PropertyChanged;

    public static readonly DependencyProperty FirstNameProperty =
        DependencyProperty.Register( "FirstName",
                                     typeof ( string ),
                                     typeof ( Person ),
                                     OnNamePropertyChanged);

    public static readonly DependencyProperty LastNameProperty =
        DependencyProperty.Register( "LastName",
                                     typeof( string ),
                                     typeof( Person ),
                                     OnNamePropertyChanged);

    private static void OnNamePropertyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
      ((Person)d).OnNamePropertyChanged();
    }

    private void OnNamePropertyChanged()
    {
      if (PropertyChanged != null)
        PropertyChanged(this, new PropertyChangedEventArgs("FullName")));
    }

    public string FirstName
    {
      get { return GetValue(FirstNameProperty) as string; }
      set { SetValue(FirstNameProperty, value); }
    }

    public string LastName
    {
      get { return GetValue(LastNameProperty) as string; }
      set { SetValue(LastNameProperty, value); }
    }
    public string FullName
    {
      get { return FirstName + " " + LastName; }
    }
}


text:
Q: ¿Cuál es la diferencia entre ViewBag, ViewData? Sabemos que  ViewData o ViewBag son utilizados para pasar información del controlador a la vista.
¿Existe alguna diferencia entre ambos?  Por ejemplo, en cuanto al rendimiento y si es recomendable el uso de uno en particular.

A: Básicamente, las diferencias consisten en lo siguiente:
ViewData

*

*ViewData es un objeto de diccionario fuertemente tipado en el que se introducen los datos a través de la conocida sintaxis "key/value".

*ViewData deriva de la clase ViewDataDictionary.

*Uso y asignación al objetos: ViewData["Dato"] = 1

*Lectura del objeto en la vista: @ViewData["Dato"]
ViewBag

*

*El objeto ViewBag es un objeto de tipo dinámico que le permite crear propiedades al vuelo.

*Uso y asignación al objetos ViewBag.Dato = 1

*Lectura del objeto en la vista: @ViewBag.Dato
En general, el uso de uno o de otro (considero) que dependerá de la forma que más te acomodes, ambos te funcionan para el paso de información del controlador a la vista, a menos que desees acarrear esa información durante más de una petición, entonces en ese caso considera usar el diccionario de datos TempData en conjunto con su método Keep().
Referencias a la documentación oficial:

*

*ViewData

*ViewBag

*TempData

A: ViewBag es simplemente un wrapper sobre ViewData. La diferencia es que mientras que ViewData es de tipo ViewDataDictionary (que implementa un IDictionary<string, object>, ViewBag es de tipo dynamic lo que simplifica el código ligeramente.
Ejemplo:
ViewData["Persona"] = new Persona("Alice");

// o

ViewBag.Persona = new Persona("Alice");

En cuando a diferencia en rendimiento debería ser despreciable, preocúpate mejor por otros lugares que pueden realmente ser un cuello de botella como por ejemplo acceso a base de datos
En cuanto a cual es mejor, pues la sintaxis de dynamic es ligeramente mas corta, pero es cuestión de gustos. Ten en cuenta que ninguna de las dos opciones son strongly typed lo cual puede conllevar a tener errores en tiempo de ejecución si tipeas mal el key en este caso Persona . Lo ideal en realidad es pasar toda la información entre el controller y la vista mediante un Model

A: En realidad no dejan de ser dos caras de la misma moneda.
La principal diferencia es que mientras ViewData es un diccionario de objetos en el que puedes acceder a elementos de tipo Object a través de una cadena, ViewBag es un objeto dinámico en el que puedes acceder a elementos a través de propiedades creadas de forma dinámica y que pueden tener un tipo de datos definido.
A la hora de la verdad MVC almacena la información en el mismo contenedor de forma que un valor definido en el controlador como ViewData["dato1"] = xxxxx puede ser accedido desde la vista como ViewBag.dato1 y viceversa.

A: Ambos tienen el mismo objetivo pasar datos desde el controlador a la vista.
El ViewData es de tipo Object y hay que hacer cast en la vista para utilizarlo, mientras que el ViewBag se genera dinámicamente con el tipo de dato asignado.
ViewData: Requiere casting de tipo para datos de tipos complejos y comprobar los valores nulos para evitar errores.
ViewBag: No requiere casting de tipo para tipo de datos complejos.
Controlador:
public class HomeController : Controller
{
   public ActionResult Index()
   {
      var emp = new Empleado
      {
        IdEmpleado=101,
        Nombre = "Pedro",
        Salario = 3500,
        Direccion = "Chiapas"
      };

      ViewData["emp"] = emp;
      ViewBag.Empleado = emp;

      return View();
   }
}

Vista:
@model MyProject.Models.Empleado;
 @{
    Layout = "~/Views/Shared/_Layout.cshtml";
    ViewBag.Title = "Bienvenido";
    var viewDataEmpleado = ViewData["emp"] as Empleado; //se hace el casting
  }

Bienvenido

 Mejor empleado del año!

@ViewBag.Empleado.Nombre

@viewDataEmpleado.Nombre

A: primero que todo gracias por sus repsuestas. Me han aclarao la duda, no obstante quisiera publicar otra respuesta con el fin de contribuir a esclarecer este tema, aunque creo que ya lo han cubierto todo bastante bien.
Técnicamente, todos los datos se pasan de los controladores a las vistas a través de un ViewDataDictionary (una clase de diccionario especializada) llamada ViewData. Puede establecer y leer valores en el diccionario ViewData utilizando la sintaxis del diccionario estándar de la siguiente manera:
ViewData["CurrentTime"] = DateTime.Now;

Aunque esto continúa estando disponible, ASP.NET MVC 3 aprovechó la palabra clave dynamic de C # 4 para permitir una sintaxis más simple. ViewBag es un contenedor dinámico alrededor de ViewData. Le permite establecer los valores como sigue:
ViewBag.CurrentTime = DateTime.Now;

Así, ViewBag.CurrentTime es equivalente a ViewData["CurrentTime"].
Generalmente, la mayoría del código actual que encontrarás usa ViewBag en vez de ViewData
en su mayor parte. Usted no tiene una verdadera ventaja técnica al elegir una sintaxis sobre la otra. ViewBag es simplemente atajo de sintaxis que algunas personas prefieren sobre la sintaxis del diccionario. Simplemente se ve mejor.
Aunque es posible que no tenga una ventaja técnica para elegir un formato sobre
el otro, usted debe ser consciente de algunas diferencias importantes entre las dos
Sintaxis
Una diferencia obvia es que ViewBag funciona sólo cuando la clave a la que está accediendo
Es un identificador de C # válido. Por ejemplo, si coloca un valor en ViewData ["Key
Con Espacios "], no puede acceder a ese valor con ViewBag porque el código
No se compilará.
Otra cuestión clave a considerar es que no se pueden transmitir valores dinámicos como parámetros a los métodos de extensión. El compilador C # debe conocer el tipo real de cada parámetro en tiempo de compilación para elegir el método de extensión correcto.
Si cualquier parámetro es dinámico, la compilación fallará. Por ejemplo, este código
Siempre fallan: @ Html.TextBox ("nombre", ViewBag.Name). Para evitar esto,
Use ViewData ["Name"] o moldee el valor a un tipo específico: (string) ViewBag.Name.
ViewDataDictionary es una clase especializada de diccionario, no solo un Dictionary genérico
.Una razón para esto es que tiene una propiedad de modelo adicional que permite un
Objeto de modelo específico que debe estar disponible para la vista. Porque sólo puede tener un objeto modelo en
ViewData, usar esto para pasar una clase específica a la vista es conveniente. Esto le permite a su vista especificar la clase que espera el objeto del modelo deseado, lo que significa que puede aprovechar fuertemente tipado.
Esto es traducido de un libro el cual considero de los mejores que he leido Professional ASP.Net MVC5


text:
Q: NHibernate select query I have the following problem:
public IList<Category> GetLeafCategories()
{
    // select all categories that are not ParentCategory
    string sqlQuery =  @"
    select * from Catalog_Categories c
    where c.CategoryId not in (
        select distinct ParentCategoryId
        from Catalog_Categories)
    ";

    //
    // I need an equivalent nHibernate query
    //
    var categs = NHibernateSession.Current.Query<Category>();
    IQueryable<Category> leafCategs = from cat in categs
                                      where cat.Id not in // HOW TO???
                                          (from c in categs
                                           select c.ParentCategory.Id)
                                        select cat;
    return leafCategs.ToList();
}

A: Im not tested this, but it should work:
var session = NHibernateSession.Current;

var subquery = session.Query<Category>
    .Select(x => x.ParentCategory.Id);

return session.Query<Category>
    .Where(x => !subquery.Contains(x.Id))
    .ToList();

A: var categs = NHibernateSession.Current.Query<Category>();
IQueryable<Category> leafCategs = from cat in categs
                                  let parentIds =
                                      (from c in categs
                                       select c.ParentCategory.Id)
                                  where !parentIds.Any( p => p == cat.Id)
                                 select cat;

You can do it like above.


text:
Q: ListVectorPlot crashes kernel after two evaluations I am currently trying to produce many plots by using ListVectorPlot, but every time I re-evaluate my code, the kernel crashes. I have set $HistoryLength=0 and ClearGlobal[] without any result. Even if I reduce the size of the matrix I'm using (say 28 elements), it still crashes. If I quit the kernel before each evaluation it works, but I have many plots to make, so doing this is a pain. I am using the option VectorPoint->All, I don't know if it has to do with anything.
Thanks in advance.

A: I saw this problem recently on the Wolfram Community website and answered it there. I'll copy my answer here (http://community.wolfram.com/groups/-/m/t/603973)
I'm not sure if there's a simple way to prevent the issue. I would do this by basically reconstructing the ListVectorPlot Function from VectorPlot. To make it easy, I'll just make an Interpolation of the x and y values for the vectors separately:
(* Here's some example data *)
    data = {WeatherData[#, "Coordinates"],
         First[
           WeatherData[#,
            "WindSpeed"]]*{-Sin[WeatherData[#, "WindDirection"]], -Cos[
             WeatherData[#, "WindDirection"]]}} & /@ {"KSPI", "KORD",
        "KMDW", "KCMI", "KBMI"};

(* Munging the data into a form acceptable by Interpolation *)
xvals = ReplaceAll[data, {position_, {xval_, yval_}} :> {position, xval}];
yvals = ReplaceAll[ data, {position_, {xval_, yval_}} :> {position, yval}];

(* Create Interpolations of the data *)
xfunc = Interpolation[xvals, InterpolationOrder -> 1];
yfunc = Interpolation[yvals, InterpolationOrder -> 1];

(* These interpolations can be used with VectorPlot *)
VectorPlot[{xfunc[x, y], yfunc[x, y]}, {x, 39, 42}, {y, -89, -87}]

You have to specify the range over which you want VectorPlot to plot. In this case, the range is a bit out of the bounds of the Interpolation, so there are some error messages. We can also get the actual Min/Max values in the dataset and use these.
{xmin, xmax} = MinMax@data[[All, 1, 1]];
{ymin, ymax} = MinMax@data[[All, 1, 2]];

VectorPlot[{xfunc[x, y], yfunc[x, y]}, {x, xmin, xmax}, {y, ymin, ymax}]


text:
Q: What does it mean if Android MediaCodec dequeueOutputBuffer returns -1? I followed the official Android documentation to setup an encoder for my audio input using a MediaCodec object. But the method dequeueOutputBuffer in the code below always returns -1. What does this return value mean?
My code:
/*configuarion of MediaCodec object*/
codec = MediaCodec.createEncoderByType("audio/mp4a-latm");
MediaFormat format = new MediaFormat();
format.setString(MediaFormat.KEY_MIME, "audio/mp4a-latm");
format.setInteger(MediaFormat.KEY_CHANNEL_COUNT, 1);
format.setInteger(MediaFormat.KEY_SAMPLE_RATE, 44100);
format.setInteger(MediaFormat.KEY_BIT_RATE, 64 * 1024);
format.setInteger(MediaFormat.KEY_AAC_PROFILE,MediaCodecInfo.CodecProfileLevel.AACObjectHE);
codec.configure(format, null, null, MediaCodec.CONFIGURE_FLAG_ENCODE);

codec.start();
 ByteBuffer[] inputBuffers = codec.getInputBuffers();
 ByteBuffer[] outputBuffers = codec.getOutputBuffers();

/*main loop to encode audio data*/
 for (;;) {
   int inputBufferIndex = codec.dequeueInputBuffer(-1); -->this is never zero so data should be written correctly!
   if (inputBufferIndex >= 0) {

     // write data from audiorecord in queue
     inputBuffer = inputBuffers[inputBufferIndex];
     inputBuffer.clear();

     inputBuffer.put(buf);-->data from audiorecord object

     encoder.queueInputBuffer(inputBufferIndex, 0, buf.length, 0, 0);
     codec.queueInputBuffer(inputBufferIndex, ...);

   }

   int outputBufferIndex = codec.dequeueOutputBuffer(bufferInfo, 0);-------->>> "-1"
   if (outputBufferIndex >= 0) {

       //do something but never called because outputbufferindex is always -1??

A: Getting -1 as return value when you have passed non negative timeoutUS indicates that call to dequeueOutputBuffer has timed out. According to Android Sample, it returns following integer
 public static final int INFO_TRY_AGAIN_LATER = -1;

A: As far as my knowledge goes, you have to increment the timestamp field in "encoder.queueInputBuffer" everytime because if the same timestamp is given everytime, buffer may be dropped by encoder.


text:
Q: Tool for Hibernate queries in IntelliJ IDEA I'm looking for a tool that could be used in Intellij Idea that would graphically show the output of my database queries in a tablar format. If you know one, please tell me about it

A: Good news for you. :) IntelliJ Idea provides Hibernate Console [1] out-of-the-box.
[1] http://www.jetbrains.com/idea/webhelp/using-hibernate-console.html


text:
Q: Vectors as basis for a subspace Here's a statement that I ran into,
The set $\{\mathbf{u}_{1},\mathbf{u}_{2}\cdots,\mathbf{u}_{6}\}$
is a basis for a subspace $\mathcal{S}$ of $\mathbb{R}^{m}$ if and
only if $\{\mathbf{u}_{1}+\mathbf{u}_{2},\mathbf{u}_{2}+\mathbf{u}_{3}\cdots,\mathbf{u}_{6}+\mathbf{u}_{1}\}$
is also a basis for $\mathcal{S}$.
I intuitively think the statement is true, but I don't know how to explain it. How should I start proving the statement? or is there a counter example for the statement?

A: You can take a linear combination of the second basis and factor it to a linear combination of the first basis and show the linear combination is zero only if all the coefficients are zero. If so the vectors in the second basis are linearly independent, if there is any other values than zero that makes  linear combination of the first basis zero then second basis is not linearly independent. Edit: can do Gaussian elimination on coefficient matrix.
Then show that any linear combination of the first basis can be written as a linear combination of the second basis. Which means the second basis spans the space of the first basis.
Is this clear? Please let me know.

A: If the $\mathbf{u_i}$ are the standard basis for $\mathbb{R}^6$,  $\mathbf{e_1},\ldots,\mathbf{e_6}$, then all the vectors in the second collection are orthogonal to $\left(1,-1,1,-1,1,-1\right)$ so they are not independent.

A: As usual, the approach is to turn it into one of the standard algebra problems for matrices, and then use your tools to find the solution.
A fairly literal translation of the problem is as follows: let
$$ A = \left[
\begin{matrix} \mathbf{u_1} \\ \mathbf{u_2} \\ \cdots \\ \mathbf{u_6} \end{matrix} \right] $$
and
$$ B = \left[
\begin{matrix} \mathbf{u_1} + \mathbf{u_2}  \\ \mathbf{u_2} + \mathbf{u_3} \\ \cdots \\ \mathbf{u_6} + \mathbf{u_1} \end{matrix} \right] $$
and you want to know if these two matrices have the same rowspace. Clearly the rowspace of $B$ is contained in the rowspace of $A$, so it's the other direction we need to do work to discover.
The usual method for finding a standard form for the rowspace of a matrix is to do row operations to reduce the matrix. While we can't do it in the usual way, it can still be done with $B$.
Another approach is possible: part of the difficulty is that while the form of $B$ is clear, it is complicated by the appearances of containing unknown vectors. So we can factor it:
$$ B = \left[ \begin{matrix} 1 & 1 & 0 & \cdots & 0
\\ 0 & 1 & 1 & \cdots & 0
\\ \vdots & \vdots & \vdots & & \vdots
\\ 1 & 0 & 0 & \cdots & 1 \end{matrix}
\right] A $$
Call this new matrix $C$. $C$ is all numbers, so we can row reduce it without having to devise a new algorithm to do it "symbolically".
The linear transformation induced by $C$ is thus a linear transformation from the rowspace of $B$ to the rowspace of $A$.
If $C$ is an invertible matrix, then we also have
$$ C^{-1} B = A$$
and so the rowspace of $A$ is thus contained in the rowspace of $B$.
If $C$ is not invertible, then it proves $B$ cannot be either. This gives a lead for finding a counterexample....

But maybe it's not clear the full extent of what this is telling us. The following will be a somewhat more sophisticated argument, but gives (IMO) a nice demonstration of the more complex arguments that can be made with the linear algebra tools you're learning about.
Our subgoal was to see if the rowspace of $A$ is contained in the rowspace of $B$. That is, for every vector $\mathbf{v}$, we are wondering if there is a solution for $\mathbf{x}$ in the equation
$$ \mathbf{v} A = \mathbf{x} B $$
Well, we can rewrite this as
$$ \mathbf{v} A = \mathbf{x} C A $$
$$ (\mathbf{v} - \mathbf{x} C) A = 0 $$
or equivalently, we seek a solution in $\mathbf{x}$ and $\mathbf{w}$ to
$$(\mathbf{v} - \mathbf{x} C) = \mathbf{w}$$
where $\mathbf{w}$ is required to be a left nullvector of $A$. Rearranging, we get:
$$\mathbf{v} = \mathbf{w} + \mathbf{x} C$$
Thus, this has solutions for every $\mathbf{v}$ if and only if:
$$ \text{NS}(A) + \text{RS}(C) = \mathbb{R}^6 $$
where $\text{NS}(A)$ is the left nullspace of $A$, and $\text{RS}(C)$ is the rowspace of $C$. Why? Because this is the vector space of all possible values the right hand side can have: $\mathbf{w}$ can be any element of $\text{NS}(A)$, and similarly $\mathbf{x} C$ can be any element of $\text{RS}(C)$.
It turns out that $\mathbf{C}$ has rank $5$. So this condition thus holds if and only if $A$ has any left nullvector that is not in the rowspace of $C$ (because this sum would thus have dimension strictly greater than $5$, and thus must be $6$).
We can even do better than this: we can compute the right nullspace to $C$, and find that it is spanned by the vector
$$ \mathbf{u} = \left[ \begin{matrix} 1 \\ -1 \\ 1 \\ -1 \\ 1 \\ -1 \end{matrix} \right] $$
Conversely, this means the left nullsapce of $\mathbf{u}$ is precisely the rowspace of $C$. Thus, a vector $\mathbf{y}$ is in the rowspace of $C$ if and only if $\mathbf{y} \mathbf{u} = 0$.
So, finally, we can state the following theorem:

$A$ and $B$ have the same rowspace if and only if there exists a vector $\mathbf{x}$ such that $\mathbf{x}A = 0$ and $\mathbf{xu} \neq 0$.

or even more simply

... if and only if $N \mathbf{u} \neq \mathbf{0}$

where $N$ is any matrix whose rows span the left nullspace of $A$.

A: A more "turn crank" approach to this problem borrows from exterior algebra concepts.
A subspace is represented by an element of the exterior algebra.  This element is merely the wedge product of vectors that span the subspace.  So this would be written as $S = u_1 \wedge u_2 \wedge \ldots \wedge u_6$.
The wedge product is distributive over addition, so the basis given would evaluate to
$$S' = (u_1 + u_2) \wedge (u_2 + u_3) \wedge \ldots \wedge (u_6 + u_1)$$
The wedge product of a vector with itself is zero.  The wedge product is also associative and anticommutative.
Now, there are $2^6 = 64$ different terms here that have to be multiplied out and summed.  Lame!  But doing this in a clever way can reduce some of the complexity of the problem.
Consider just $(u_1 + u_2) \wedge (u_2 + u_3) = u_1 \wedge u_2 + u_1 \wedge u_3 + u_2 \wedge u_3$.  We can do this for 3 pairs of vectors to get
$$\begin{align*}S' &= (u_1 \wedge u_2 + u_1 \wedge u_3 + u_2 \wedge u_3) \\ &\wedge (u_3 \wedge u_4 + u_3 \wedge u_5 + u_4 \wedge u_5) \\ &\wedge (u_5 \wedge u_6  + u_5 \wedge u_1 + u_6 \wedge u_1)\end{align*}$$
The key to evaluating this expression is to remember that any term that is nonzero must contain all of the six basis vectors.  Pay special attention to $u_2, u_4, u_6$.  Each of these only appears in one row, and as a result, we can eliminate products that do not obviously contain all of them.  Indeed, only the first and last columns of bivectors contribute to the final result.
$$S' = u_1 \wedge u_2 \wedge u_3 \wedge u_4 \wedge u_5 \wedge u_6 + u_2 \wedge u_3 \wedge u_4 \wedge u_5 \wedge u_6 \wedge u_1$$
So we take the second term, move $u_1$ to the front at the cost of a minus sign for each switch.  There are five such swaps, so the second term has a minus sign compared to the first term
And we get zero?!
Yes, as a matter of fact, $S' = 0$, and the second set of vectors cannot form a basis set for $S$.  This is because
$$u_6 + u_1 = (u_5 + u_6) - (u_4 + u_5) + (u_3 + u_4) - (u_2 + u_3) + (u_1 + u_2)$$
And so one vector in the set is expressable as a linear combination of the others.
This only happens when the set has even dimensionality.  If there were only 5 vectors in the set, the pattern of alternating additions and subtractions would make this linear dependence impossible.
The exterior algebra approach is helpful because one need not try to identify that one vector is a linear combination of the others.  The wedge product gives a "turn crank" test that merely tests one's ability to compute several wedge products to see if the resulting subspace is nonzero.


text:
Q: How to delete default Measure Groups in the SSAS CUBE? I have created a CUBE. By default CUBE created few Measure Groups.
When I go to Aggregations, I can see the default Measure Groups. I want to delete them all and want to create as per the requirement.
Attached is the screenshot,

A: If you need to delete a Measure Group from your cube, you can simply go to Cube Structure tab and right click on the Measure Group and select Delete.


text:
Q: boost::process::child will not exit after closing input stream In the following example I try to write some data to a child process, which processes the data and writes it to a file. After closing the stream the parent process waits indefinitely for the child to finish. I am at a loss to know how to indicate that I'm done writing the data and would like the child process to stop reading and finish whatever it is doing. According to the documentation calling terminate would send a SIGKILL which I don't think is what I want.
What am I missing? I checked this question but I would rather try to make the actual code work with synchronous IO first.
#include <boost/process.hpp>
#include <iostream>

namespace bp = boost::process;

int main(int argc, char **argv)
{
    boost::process::opstream in{};
    boost::process::child child("/path/to/test.py", bp::std_in < in);

    in << "test1\n";
    in << "test2\n";
    in << "test3\n";
    in << std::flush;

    std::cerr << "Closing the stream…\n";
    in.close();
    std::cerr << "Waiting for the child to exit…\n";
    child.wait(); // Parent seems to hang here.

    return 0;
}

test.py just writes the data to a file like so:
#!/usr/local/homebrew/opt/python@3.8/bin/python3

import sys

with open("/tmp/test.txt", "w") as f:
    for line in sys.stdin:
        f.write(line)

A: After inspecting the source code, I found out that closing the stream did not close the associated pipe at least in this case. Doing that manually did solve the issue:
...
in.close();
in.pipe().close();
child.wait(); // Does not hang.

A: The documentation warns that using synchronous IO to child processes is prone to deadlock.
Here's a minimal reword to async IO:
#include <boost/process.hpp>
#include <iostream>

namespace bp = boost::process;

int main() {
    boost::asio::io_context ioc;
    bp::async_pipe in{ioc};
    bp::child child("./test.py", bp::std_in < in, bp::std_out.close());

    for (auto msg : { "test1\n", "test2\n", "test3\n" }) {
        write(in, bp::buffer(msg, strlen(msg)));
    }

    std::cerr << "Closing the pipe…\n";
    in.close();
    std::cerr << "Waiting for the child to exit…\n";
    ioc.run(); // already awaits completion

    child.wait(); // Parent seems to hang here.
}

You can make it more realistic by doing some delays:
#include <boost/process.hpp>
#include <iostream>

using namespace std::chrono_literals;
namespace bp = boost::process;

int main() {
    boost::asio::io_context ioc;
    bp::async_pipe in{ioc};
    bp::child child("./test.py", bp::std_in < in, bp::std_out.close());

    std::thread th([&] {
        for (auto msg : { "test1\n", "test2\n", "test3\n" }) {
            write(in, bp::buffer(msg, strlen(msg)));
            std::this_thread::sleep_for(1s);
        }

        std::cerr << "Closing the pipe…\n";
        in.close();
    });

    std::cerr << "Waiting for the child to exit…\n";
    ioc.run(); // already awaits completion
    th.join();

    child.wait(); // Parent seems to hang here.
}

For fullblown async IO see other examples:

*

*simultaneous read and write to child's stdio using boost.process

*How to retrieve program output as soon as it printed?

*Running a process using boost process in async mode with timeout


text:
Q: How to minimize total distance for deliveries? There are n houses on an infinitely long road where baskets are to be delivered. Imagine the road as an x-axis starting from negative infinity to positive infinity. We have to select a position of new warehouse in the road so that we can minimize the total distance for deliveries.
there is a single Truck that carry a maximum of m baskets.
task is to find the position for warehouse so that total distance needed to deliver all basket will be minimum possible.
Can anyone help me with question please?


text:
Q: Get single elements from Firestore Document How can I get single items from my Document in Firebase?

I can get all elements with this code:
 let key = UserDefaults.standard.value(forKey: "uid") as! String
        let docRef = firebaseDB.collection("user").document(key)

        docRef.getDocument { (document, error) in
            if let document = document, document.exists {
                let dataDescription = document.data().map(String.init(describing:))
                print("Document data: \(dataDescription)")

            } else {
                print("Document does not exist")
            }
        }

I only wish to get the name and phone number. How can I filter my result?

A: FirebaseFirestore has a handy way of caching single documents:
First, you need to specify the document by it's ID:
let key = UserDefaults.standard.value(forKey: "uid") as? String ?? "Null" // Unique user key
let docRef = db.collection("user").document(key)

Get the document:
docRef.getDocument { (document, error) in
     if let document = document, document.exists {
         let docData = document.data()
         // Do something with doc data
      } else {
         print("Document does not exist")

      }
}

Access the doc data:
 let status = docData!["phone"] as? String ?? ""


text:
Q: Creating a number list with nested For loops in Python I've been working on this now for well over four hours and i've tried to check several resources.
I'm trying to get something like this:
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
0 1 2 3 4 5 6 7 8 9
My current code for this is:
for i in range(10):
    print(i, end = '')
    for j in range(10):
        print(j, end = '')
    print()

which prints this:
00123456789
10123456789
20123456789
30123456789
40123456789
50123456789
60123456789
70123456789
80123456789
90123456789

So I just need to get rid of the very most left-hand side. Additionally, I'm trying to produce something that looks like this:
0
0 1
0 1 2
0 1 2 3
0 1 2 3 4
0 1 2 3 4 5
0 1 2 3 4 5 6
0 1 2 3 4 5 6 7
0 1 2 3 4 5 6 7 8
0 1 2 3 4 5 6 7 8 9
And I can get it from this:
triangle = ''
n = 9
for i in range(0, n+1):
    triangle = triangle + (str(i))
    print(triangle)
print()

for i in range(11):
    for j in range(0+i):
        print(j,end=" ")
    print()

The problem with the first one is there isn't two for loops, one nested in the other. The problem with the second one is that I have range at 11 to get it to print to 9.
Lastly, I'm trying for this:
10
11 12
13 14 15
16 17 18 19
20 21 22 23 24
25 26 27 28 29 30
31 32 33 34 35 36 37
38 39 40 41 42 43 44 45
46 47 48 49 50 51 52 53 54
Which I've been getting with this:
x = 10
for i in range (10):
    print (*range (x, x+i))
    x += i

But I need two for loops. I feel like I'm very close, but just can't get the finished product.
Thanks.

A: Issue with first code is that you are printing i , you do not need to print i . Code would be something like -
for i in range(10):
    for j in range(10):
        print(j, end = ' ')
    print()

For the rest of the question, if you are getting the answer without nested loops, why do you need nested loops?

A: For the first instance, try this:
print('', end = '')

For the second instance, the mistake is that you are adding 0 to the second for loop. Change it to:
for j in range(0, 1+i):

The thing with range is that it goes until one number lower. Have a look at docs
For the last one, you can use the following code, where y starts at 10.
y = 10
for i in range(0,10):
    for j in range(0, i):
        print(y + j, end=' ')
    print('')
    y += i

A: Here is how to go about it -
First is very simple
ht = 10
y = range(ht)
"\n".join(map(lambda x: " ".join(map(str,x)), [y]*ht))

Second one is a bit interesting
ht = 10
y = range(ht)

for i in range(1, ht+1):
    print "  ".join(map(str, y[0:i]))

Third one
start = 10
ht = 9
limit = (ht*(ht+1))/2 # using the sum of n to find out total elements
y = range(start, limit+1)
for i in range(1, ht+1):
    print " ".join(map(str, y[0:i]))
    y =  y[i:]

The complicated map(str, y) is only to get a string to be printed.
Is this what you want?


text:
Q: Sending a request from one WSDL to another WSDL I want to know is it possible to send a request from one wsdl to another wsdl. If yes, then how do I do that?
The flow will be :
I want to expose a wsdl using switchyard say wsdl-1 which might have 100 parameters, with create, get, delete and set request.
I want a XSLT which will take the request from wsdl-1 and I will pick only few parameters and will ignore the other remaining parameter.
Now with the picked parameters in XSLT, I want to send another request to my other wsdl say wsdl-2 which will perform its task.

I am not sure how do I do this and need some guidance . Please let me if the question is not clear from my end.
EDIT :
Adding the exact flow architecture which I am looking for. I want to know how would I communication with WSDL Country 1 and my SIM WSDL.
I want to know whether is it possible or not (communication between two wsdls).
Please let know if you need more explanation.

A: You may try the link below, it provids detailed expalianation on your all the above questions :
https://developer.jboss.org/message/910909#910909


text:
Q: sending dbus message from chromeOS to Concierge/Cicerone shows error i am trying to send a dbus message within the chromeos terminal to actually shutdown the vm.
there is a dbus-api for that
either
https://chromium.googlesource.com/chromiumos/platform/system_api/+/master/dbus/vm_cicerone/dbus-constants.h
or
https://chromium.googlesource.com/chromiumos/platform/system_api/+/master/dbus/vm_concierge/dbus-constants.h
i always get:
The name org.chromium.VmCicerone was not provided by any .service files /
The name org.chromium.VmConcierge was not provided by any .service files
i am trying to call the method StopVm respectively ContainerShutdown
it seems that the cicerone service or concierge service is not running.
any idea, what i am doing wrong, or why the serivce is not running?
thanks


text:
Q: Lightweight data mining + organization & visualization I'm looking to do some simple data mining that consists of going once per day to a single page and collect the following information:

*

*List of movie theaters

*Movies today on each theater

*Session times for each movie

*Availability of tickets for each session (boolean yes/no)

I want to catalog this information and after 1 year see an overlay graph showing for each movie (if the same movie exists on 2 theaters I want 2 distinct instances):

*

*x axis: time (discrete dates)

*y axis: number of sold out sessions

Aditionally, it would be useful to get another heatmap graph letting me know for each movie what times were the most sold out.
What would be a lightweight solution to go about this? I'm not familiar with data scraping tools or simple lightweight databases for this. I'm inexperienced in this line of work and looking to do the least coding possible. Excel would be fine for me. I've had past experience with Java and C# but would like to avoid killing a fly with a bazooka.
I'm currently thinking about doing this with ParseHub but not sure how to merge the information from 1 csv file per day to obtain the information I'm looking for.
PS: I found the JSON source that populates the web page so I could fetch that once per day, I just need to grab the important information from that file and structure it (in an Excel). Just don't know what tools I could use to accomplish such a task.
Thank you

A: My recommendation is to pick up Python.  There are lots of tutorials to get you going, and there are TONS of examples on how to scrape websites using tools like BeautifulSoup, and if you found a JSON api then you can grab it using tools like "requests".
Then you can schedule your program to run daily using tools like cron if you are under Linux.  On Windows you can use the Task Scheduler to run your Python script.
The Python program can append to a comma-separated-variable (CSV) file each day, which you could then open in Excel to play around with plotting.  There are also Python plotting utilities -- use whatever tools work for you.
Once you have these tools in your toolbelt, you'll be able to do all kinds of other projects while you wait a year to build up your database of movies!


text:
Q: URL Rewriting with htaccess if iam giving my url as http://localhost/york/aboutus.php it is working fine, but the problem i am having is that if i provide http://localhost/york/aboutus.php/ or any character after the trailing slash of the above url and then if load that page then  all the css and javascript files are not working.  Please provide me the solution to this problem.. Thanks in advance..

A: The problem is most likely the way you are including the javascript / css files in your page. With more details you will probably get a more detailed answer, but I would guess you are using .htaccess to rewrite the page in question and then in your html you are using a relative path for the src/link attributes of js/css. Every forward slash in your URL, the clients browser will assume is a directory and it will calculate relative paths accordingly.
The solution is to provide all your src/js paths relative to Root not your cwd. That is to say they should begin with a forward slash and then have the full path from your root directory. This way the clients browser will request http://www.domain.com/path/to/style.css, regardless of how many slashes are in the pages URL.


text:
Q: Download PDF in ASP MVC I am attempting to download a pdf file in ASP MVC using C#.
I have a UI-dialog with a button invoking the call to the controller:
 "Download PDF": function () {
            $.post(Urls.Action.DownloadPDF);

In the controller I am using a PDF converter to convert the html to PDF:
public ActionResult DownloadPDF()
     {
         string htmlToConvert = RenderViewAsString("~/Content/Eula.htm");
         HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
         byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert,null);
         HttpContext.Response.AddHeader("content-disposition", "attachment; filename=Download.pdf");
         FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
         fileResult.FileDownloadName = "Download.pdf";

         return fileResult;
     }

The code runs through the method without issue in the debugger and the post returns successful but the browser is not downloading the PDF.
EDIT -

Key Value
Response    HTTP/1.1 200 OK
Cache-Control   private, s-maxage=0,private,no-store,no-cache,s-maxage=0,max-age=0,must-revalidate,proxy-revalidate,no-transform
Pragma  no-cache
Content-Type    application/pdf
Expires -1
Server  Microsoft-IIS/7.5
Set-Cookie
FB; path=/; HttpOnly
X-AspNetMvc-Version 3.0
content-disposition attachment; filename=Download.pdf
Content-Disposition attachment; filename=Download.pdf
X-AspNet-Version    4.0.30319
X-Powered-By    ASP.NET
X-Content-Type-Options  nosniff
X-XSS-Protection    1; mode=block
X-UA-Compatible IE=edge,chrome=1
Date    Fri, 07 Jun 2013 03:31:34 GMT
Content-Length  81862

A: I think your controller method should be something like this:
public FileContentResult DownloadPDF()
{
    string htmlToConvert = RenderViewAsString("~/Content/Eula.htm");

    HtmlToPdf htmlToPdfConverter = new HtmlToPdf();
    byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert,null);

    return File(pdfBuffer, "application/pdf", "Download.pdf");
}

I haven't had a whole lot of experience with file downloads but similar code works for me to download excel files.
I found this post that specifically talks about downloading PDF's. It outline the difference between ActionResult and FileResult - ActionResult doesn't contain the content type. It also explains the different results that build on FileResult:

If the content you want to transfer is stored within a disk file, you
  can use the FilePathResult object. If your content is available
  through a stream you use FileStreamResult and you opt for
  FileContentResult if you have it available as a byte array. All these
  objects derive from FileResult and differ from one another only in the
  way that they write out data to the response stream.

EDIT: After a little searching, I believe I found the root of the problem. You may be able to use the same code, but you would need to call WriteFile to write the content to the response stream - using File(...) does that by default:

The result object that is prepared by this method is written to the
  response by the ASP.NET MVC framework when the object is executed.

See the MSDN docs for more info:

*

*FileResult

*File


text:
Q: The code for a calculator I made doesn't act like I thought it would? (Python 3.x) I'm actively learning Python at the moment. I've already had some experience with code, but not nearly enough that I would call myself a good coder (or even a competent one tbh).
I tried to create a (pretty) simple calculator script. I wanted to make sure the user could choose how many different values (s)he wanted to calculate together. To do that I created a while loop.
uArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

def divide():
    uAmount = int(input("How many different values do you want to add together? (max 10) "))
    if uAmount <= 10:
        for amount in range(0, uAmount):
            uArray[amount] = int(input("enter a number: "))
    else:
        print("ERROR\nMax 10 different values supported")
        return 1

    global uTotal
    uTotal = 1
    for amount1 in range(0, (uAmount - 1)):
        uTotal /= uArray[amount1]

    print("The result is: " + str(uTotal))

I know this code might look REAL ugly to a lot af you and I'm sure that the same process could be done way easier and simpler if I knew how.
I just can't figure out why my current method doesn't work, even after trying to google it.
EXAMPLE: If I choose to use 2 different values. And I make those values 50 and 2, it should give 25 of course. But it gives 0.02 instead.
Thanks in advance to anyone willing to help! (and sorry if this is a noob question ahaha)

A:
I just can't figure out why my current method doesn't work

Simple. You start with uTotal equal to 1. Then you divide by each of your numbers (except the last). Since you only have two numbers, 50 and 2 and you don't use the second one (due to range(0, uAmount - 1)), the whole calculation equals to this:
1 / 50 # => 0.02

How to fix?
Instead of setting uTotal to 1, set it to the value of the first element. Then apply your operation (division, in this case), using all other elements (except the first).
Array unpacking syntax may come in handy here:
total, *rest = uArray
for operand in rest:
  total /= operand

A: Currently it's taking 1 and dividing it by your first input, which is 50.
Note that the for loop won't iterate like you were thinking. Need to remove the '- 1'
Here's a version:
uArray = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0]

def divide():
    uAmount = int(input("How many different values do you want to add together? (max 10) "))
    if uAmount <= 10:
        for amount in range(0, uAmount):
            uArray[amount] = int(input("enter a number: "))
    else:
        print("ERROR\nMax 10 different values supported")
        return 1

    global uTotal
    uTotal = uArray[0]
    for amount1 in range(1, (uAmount)):
        uTotal /= uArray[amount1]

    print("The result is: " + str(uTotal))


text:
Q: How to send data frame from r to SQL? #setwd('Desktop/IE332')
install.packages("wakefield")
install.packages("RMySQL")
install.packages("randomNames")
install.packages('password')
install.packages('OpenRepGrid')
library(RMySQL)
library(password)
library(wakefield)
library(randomNames)

industriesData <- read.csv('Industries.csv')
skills <- read.csv('Skills.csv')
sp500 <- read.csv("http://www.princeton.edu/~otorres/sandp500.csv")
companies <- sample(sp500$Name, 100)

locations <- c('Northwest', 'Midwest', 'Northeast', 'South', 'Southwest', 'Southeast',
'International') # Locations
gpas <- c(4,3.5,3,2.5,2)
n <- 100
locPrefs <- numeric(n)

studentSkills <- matrix(nrow=100,ncol=10)
studentInd <- matrix(nrow=100,ncol=5)
jobSkills <- matrix(nrow=100,ncol=5)
for(j in 1:n){ # Samples random skills assigned to students
  studentSkills[j,] <- sample(skills[,1],10,replace=FALSE)
  studentInd[j,] <- sample(industriesData[,1],5,replace=FALSE)
  jobSkills[j,] <- sample(skills[,1],5,replace=FALSE)
}

studentData <- data.frame('first names'=randomNames(n, which.names = 'first'),'last
names'=randomNames(n, which.names = 'last'),'username'=seq(1,
n),'password'=password(8,numbers=TRUE),'gpa'=gpa(n, mean = 85.356, sd = 3.2, name =
"GPA"),'visa'=sample(c("N","Y"), size = n, replace = TRUE, prob = c(.78, .22)), 'loc
pref'=sample(locations,n,replace = TRUE), 'skill'=studentSkills, 'Industry'=studentInd) # Student data
employerData <- data.frame('company names'=companies, 'pref
gpa'=sample(gpas,n,replace=TRUE), 'sponser?'=sample(c('N','Y'), size=n, replace = TRUE, prob
= c(.78, .22)), 'job id'=sample(seq(100,999),n,replace=FALSE),'pref skill'=jobSkills,
'industry'=sample(industriesData[,1],n,replace=TRUE),'location'=sample(locations,n,replace =
TRUE)) # Employer data

I am trying to send certain columns of the studentData and employerData to tables in SQL, how would i go about doing that? I have a table named students where I would like to upload the first and last names of the studentsData data frame into this SQL table.


text:
Q: Remove all strings with duplicates in an NSArray I am trying to figure out how to implement this in Objective-C.
I want to remove the strings in an NSArray that have appear more than once in the array.
At the end I want to have an array that only has the unique lines in an array (meaning that not just the duplicates are deleted but also the original string that matches the duplicates.)
For example if you had the following array:
NSArray *array = [NSArray arrayWithObjects:@"bob", @"frank", @"sarah", @"sarah", @"fred", @"corey", @"corey", nil];

I would want the new array to look like this:
@"bob", @"frank", @"fred"

A: A slightly different approach from Jacob's:
NSArray *array = [NSArray arrayWithObjects:@"bob", @"frank", @"sarah", @"sarah", @"fred", @"corey", @"corey", nil];

NSCountedSet *namesSet = [[NSCountedSet alloc] initWithArray:array];
NSMutableArray *namesArray = [[NSMutableArray alloc] initWithCapacity:[array count]];

[namesSet enumerateObjectsUsingBlock:^(id obj, BOOL *stop){
    if ([namesSet countForObject:obj] == 1) {
        [namesArray addObject:obj];
    }
}];

And
NSLog(@"old: %@\nNew: %@", array, namesArray);

gives:
2011-06-16 18:10:32.783 SetTest[1756:903] old: (
    bob,
    frank,
    sarah,
    sarah,
    fred,
    corey,
    corey
)
New: (
    frank,
    fred,
    bob
)

Blocks are your friends! And since NSCountedSet is a subclass of NSSet you can use the block methods that are available there.

A: Use an NSCountedSet:
NSCountedSet *countedSet = [NSCountedSet setWithArray:yourArray];
NSMutableArray *finalArray = [NSMutableArray arrayWithCapacity:[yourArray count]];

for(id obj in countedSet) {
   if([countedSet countForObject:obj] == 1) {
      [finalArray addObject:obj];
   }
}

@Caleb suggested adding a method to NSCountedSet called -objectsWithCount:,, which I've implemented here:
@interface NSCountedSet (JRCountedSetAdditions)

- (NSArray *) objectsWithCount:(NSUInteger) count;

@end

@implementation NSCountedSet (JRCountedSetAdditions)

- (NSArray *) objectsWithCount:(NSUInteger) count {
   NSMutableArray *array = [NSMutableArray array];
   for(id obj in self) {
      if([self countForObject:obj] == count) {
        [array addObject:obj];
      }
   }
   return [array copy];
}

@end

Once that's done, all you need is one line:
NSArray *finalArray = [[NSCountedSet setWithArray:yourArray] objectsWithCount:1];

By the way, this is type-agnostic, so this will work with any Objective-C object. :-)

A: Here is the simplest approach to remove duplicate strings:
NSArray *array = [NSArray arrayWithObjects:@"bob", @"frank", @"sarah", @"sarah", @"fred", @"corey", @"corey", nil];
NSArray *distintStrings = [array valueForKeyPath:@"@distinctUnionOfObjects.self"];

A: One liner : uniqueArray = [[NSSet setWithArray:duplicateArray] allObjects]; if you don't care about the ordering :D


text:
Q: Выключение экрана WinAPI C++ Только учусь winAPI, весь вечер вчера пытался написать программу, которая бы выключала экран и включала при нажатие на клавишу F2, код ниже. Проблема в том, что при появлении окошка нажимаю на ОК и программа закрывается, не выполняя мою функцию NewWndProc, подскажите, что делать? Решил выключать экран в цикле, т.к без него экран загорается при передвижении мышкой или нажатии на клавиатуру.
КОД С++
#include <Windows.h>
#include <conio.h>
#include <winuser.h>

struct project1 {
    LONG pPrevProc;
}ppjct1;

LRESULT CALLBACK NewWndProc(HWND   hwnd, UINT   uMsg, WPARAM wParam, LPARAM lParam) {
    bool key = true;
    while (key) {
        SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, 2);
        switch (uMsg) {
        case WM_KEYUP:
            switch (wParam) {
            case VK_F2:
                {
                key = false;
                break;
                }
            }
        }
    }
    return CallWindowProc(WNDPROC(ppjct1.pPrevProc), hwnd, uMsg, wParam, lParam);
}

int WINAPI WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance, LPSTR lpCmdLine, int nCmdShow) {
    MessageBox(NULL, (LPCWSTR)L"Programm is started!", (LPCWSTR)L"Screen killer", MB_OK);
    ppjct1.pPrevProc = SetWindowLongPtr(NULL, GWL_WNDPROC, (LONG_PTR)NewWndProc);
    SendMessage(HWND_BROADCAST, WM_SYSCOMMAND, SC_MONITORPOWER, -1);

}

A: Вызов SetWindowLongPtr с NULL в качестве первого параметра ничего не делает. Выключать монитор в цикле также бесполезно, так как он по факту будет все время включаться - выключаться. Если хотите выключать экран, то придется копать глубже и отключать его полностью.


text:
Q: How to use a button to delete a "to do" list item that was added through javascript I'm adding trying create a delete button to delete the corresponding list item. I've tried trying to make a for loop to iterate through the list items but there are no items to begin with, so no array to iterate through. not sure if my logic is right here or I'm overlooking something.
This is my code, what do I need to do to make the delete button work?

TO DO LIST

    <form id="taskForm">
      <input id="taskInput"></input>
      <button type="button" id="taskButton">Click Here</button>
     </form>


text:
Q: Div Alignment and shape What would be the best way to align these two columns - .responseNum & .responseText:
Also the num column has a background -> Am I able to do this shape with CSS3 as I am unable to get the image proportions correct?

HTML:

        1

Not bad morbi no bad luke crying twitter le me sit superhero cellphone. Strangers silent hill party problem? Loki cereal guy gentlemen monocle high school lose trolololo men true story. On freddie mercury asian le girlfriend happy facepalm blizzard bart. Charlie Sheen bacon search pokeman unsave i see what you did there vegan cookie monster humor final week.

CSS:
.textMessageResponse{
    height:60px;
    background-color:#fff;
    margin:10px;
}
.textMessageResponse .responseNum .responseText{
    float:left;
    display:inline-block;
}

.textMessageResponse .responseNum{
    width:35px;
    height:35px;
}

.textMessageResponse .responseNum .number{
    background:url('../images/numBG.png') no-repeat;
    width:25px;
    height:25px;
    color:#fff;
    text-align:center;
    font-weight:bold;
}

A: Change your css like this,
.textMessageResponse{
    height:60px;
    background-color:#fff;
    margin:10px;
}
.textMessageResponse .responseNum, .textMessageResponse .responseText{/*change*/
    float:left;
}

.textMessageResponse .responseText{
    width:300px;/*Add this*/
}

.textMessageResponse .responseNum{
    width:35px;
    height:35px;
}

.textMessageResponse .responseNum .number{
    background:url('http://jzm.co.nz/clients/dev/_assets/images/numBG.png') no-repeat;
    width:25px;
    height:25px;
    color:#fff;
    text-align:center;
    font-weight:bold;
    display:block; /*change*/
}

I hope it will help you.

A: in CSS select the display-option for the parent of your .responseNum & .responseText classes. Thus, type in css under parent class 'textMessageResponse' either:
display: inline; or display: inline-block; for horizontal alignment of your divs or
display: block; for vertical alignment of your divs.


text:
Q: How to download PDF using URL in iOS app multiple times I am getting getting multiple PDF urls from server response and showing them in tableview with download option for each cell.
I am able to download each pdf file only once, But, Tried to second time download, It is showing already downloaded error.
How to fix this?
Here is my code
 func downloadButtonTapped(index: Int) {

        let finalUrlStr = "(dataResponse?[index].brochure)")

        let fileURL = URL(string: finalUrlStr)
        let fileName = String((fileURL!.lastPathComponent)) as NSString

        // Create destination URL
        let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
        let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
        //Create URL to the source file you want to download
        let sessionConfig = URLSessionConfiguration.default
        let session = URLSession(configuration: sessionConfig)
        let request = URLRequest(url:fileURL!)
        LoadingView.show()
        let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
            if let tempLocalUrl = tempLocalUrl, error == nil {
                // Success
                if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                    print("Successfully downloaded. Status code: \(statusCode)")
                }
                do {
                    try FileManager.default.copyItem(at: tempLocalUrl, to: destinationFileUrl)
                    do {
                        //Show UIActivityViewController to save the downloaded file
                        let contents  = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
                        for indexx in 0..<contents.count {
                            if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
                                let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
                                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                                    self.present(activityViewController, animated: true, completion: nil)
                                    LoadingView.hide()
                                }
                            }
                        }
                    }
                    catch (let err) {
//                        DispatchQueue.main.async {
                        print("error: \(err.localizedDescription)")
                        LoadingView.hide()
                        self.showBasicAlert(title: "\(err.localizedDescription)", message: "")
                       // }
                    }
                } catch (let writeError) {
                    print("Error creating a file \(destinationFileUrl) : \(writeError)")
                    LoadingView.hide()
                    self.showBasicAlert(title: "\(writeError.localizedDescription)", message: "")
                }
            } else {
                print("Error took place while downloading a file. Error description: \(error?.localizedDescription ?? "")")
                self.showBasicAlert(title: "\(error?.localizedDescription ?? "")", message: "")
            }
        }
        task.resume()
    }

Even though, PDF not downloaded even one time before download file, activitycontroller displaying and If we close that without download/save file, Again trying to download, Same error message showing like already exist file
How to download multiple times like whenever user taps on download option, It should download the pdf file.
Also after downloaded pdf, I need to show open pdf from external not inside app

Any suggestions?

A: I have fixed it by myself by removing condition.
Now I am able to download whenever user tap on download button.
Here is the code.
 func downloadButtonTapped(index: Int) {
        //     print("index \(index)")

        let finalUrlStr = "(dataResponse?[index].brochure)")
        let fileURL = URL(string: finalUrlStr)
        if let fileUrl = fileURL {
            let fileName = String((fileUrl.lastPathComponent)) as NSString

            // Create destination URL
            let documentsUrl:URL =  FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
            let destinationFileUrl = documentsUrl.appendingPathComponent("\(fileName)")
            //Create URL to the source file you want to download
            let sessionConfig = URLSessionConfiguration.default
            let session = URLSession(configuration: sessionConfig)
            let request = URLRequest(url:fileUrl)
            LoadingView.show()
            let task = session.downloadTask(with: request) { (tempLocalUrl, response, error) in
                if error == nil {
                    // Success
                    if let statusCode = (response as? HTTPURLResponse)?.statusCode {
                        print("Successfully downloaded. Status code: \(statusCode)")
                    }
                    do {
                        //Show UIActivityViewController to save the downloaded file
                        let contents  = try FileManager.default.contentsOfDirectory(at: documentsUrl, includingPropertiesForKeys: nil, options: .skipsHiddenFiles)
                        for indexx in 0..<contents.count {
                            if contents[indexx].lastPathComponent == destinationFileUrl.lastPathComponent {
                                let activityViewController = UIActivityViewController(activityItems: [contents[indexx]], applicationActivities: nil)
                                DispatchQueue.main.asyncAfter(deadline: DispatchTime.now() + 1) {
                                    self.present(activityViewController, animated: true, completion: nil)
                                    LoadingView.hide()
                                }
                            }
                        }
                    }
                    catch (let err) {
                        print("error: \(err.localizedDescription)")
                        DispatchQueue.main.async {
                            LoadingView.hide()
                            self.showBasicAlert(title: "\(err.localizedDescription)", message: "")
                        }
                    }
                }
            }
            task.resume()
        }
    }


text:
Q: Cmake error while configuring openCV with CUDA Cmake is showing this error while configuring openCV with CUDA:
CMake Error: The following variables are used in this project, but they are set to NOTFOUND.
Please set them or make sure they are set and tested correctly in the CMake files:
opencv_dep_CUDA_cufft_LIBRARY
    linked by target "opencv_core" in directory C:/opencv/sources/modules/core
    linked by target "opencv_test_core" in directory C:/opencv/sources/modules/core
    linked by target "opencv_perf_core" in directory C:/opencv/sources/modules/core
    linked by target "opencv_flann" in directory C:/opencv/sources/modules/flann
    linked by target "opencv_test_flann" in directory C:/opencv/sources/modules/flann
    linked by target "opencv_imgproc" in directory C:/opencv/sources/modules/imgproc
    linked by target "opencv_test_imgproc" in directory C:/opencv/sources/modules/imgproc
    linked by target "opencv_perf_imgproc" in directory C:/opencv/sources/modules/imgproc
    linked by target "opencv_highgui" in directory C:/opencv/sources/modules/highgui
    linked by target "opencv_test_highgui" in directory C:/opencv/sources/modules/highgui
    linked by target "opencv_perf_highgui" in directory C:/opencv/sources/modules/highgui
    linked by target "opencv_test_features2d" in directory C:/opencv/sources/modules/features2d
    linked by target "opencv_features2d" in directory C:/opencv/sources/modules/features2d
    linked by target "opencv_perf_features2d" in directory C:/opencv/sources/modules/features2d
    linked by target "opencv_calib3d" in directory C:/opencv/sources/modules/calib3d
    linked by target "opencv_test_calib3d" in directory C:/opencv/sources/modules/calib3d
    linked by target "opencv_perf_calib3d" in directory C:/opencv/sources/modules/calib3d
    linked by target "opencv_test_ml" in directory C:/opencv/sources/modules/ml
    linked by target "opencv_ml" in directory C:/opencv/sources/modules/ml
    linked by target "opencv_test_video" in directory C:/opencv/sources/modules/video
    linked by target "opencv_video" in directory C:/opencv/sources/modules/video
    linked by target "opencv_perf_video" in directory C:/opencv/sources/modules/video
    linked by target "opencv_test_legacy" in directory C:/opencv/sources/modules/legacy
    linked by target "opencv_legacy" in directory C:/opencv/sources/modules/legacy
    linked by target "opencv_perf_objdetect" in directory C:/opencv/sources/modules/objdetect
    linked by target "opencv_objdetect" in directory C:/opencv/sources/modules/objdetect
    linked by target "opencv_test_objdetect" in directory C:/opencv/sources/modules/objdetect
    linked by target "opencv_perf_photo" in directory C:/opencv/sources/modules/photo
    linked by target "opencv_photo" in directory C:/opencv/sources/modules/photo
    linked by target "opencv_test_photo" in directory C:/opencv/sources/modules/photo
    linked by target "opencv_perf_gpu" in directory C:/opencv/sources/modules/gpu

I have working CUDA without openCV otheriwse.

A: Solution is to choose Visual Studio 11 Win64 instead of Visual Stuidio 11 as generator in CMAKE. this will lead to clean configuration.

A: Choose the Visual Studio Win 64 version when CMake prompts for a compiler. cufft.lib should be located in your CUDA/vX.x/lib/x64 folder.


text:
Q: Use bash string to provide multiple arguments to a program, where some argument include whitespace When writing a script that calls wget, I want to make use of a variable that holds all of the headers, but if I attempt the following, then the whitespace within the header strings breaks them into multiple parameters (not a single header):
HEADERS='--header "Accept-Encoding: gzip, deflate"'
wget $HEADERS "$URL"
# ... $HEADERS is interpreted as 4 strings instead of 2 ...
wget --header Accept-Encoding: gzip, deflate http://example.com

I can't wrap $HEADERS in quotation marks because I need it to be interpreted as 2 arguments instead of 1. (And if I had many headers in the variable, it would need to be split into still more arguments.)
I often write bash scripts that assemble arguments for other programs, and I often encounter this issue. Is there a solution in bash?

A: Do not use a regular variable; use an array.
headers=(--header "Accept-Encoding: gzip, deflate")
wget "${headers[@]}" "$URL"


text:
Q: How to access Extjs nested models (loaded from Xml)? Having difficulty getting my head around the 'Associations' feature of Models and how
a developer can access the nested data through the association.
Here's a simple XML file we're trying to parse.
<?xml version="1.0" encoding="UTF-8"?>
<contacts>
    <contact>
        <id>1</id>
        <name>Bob Jones</name>
        <emails>
            <email>
                <addr>bjones1@dom.com</addr>
                <display>B. Jones 1</display>
            </email>
            <email>
                <addr>bjones2@dom.com</addr>
                <display>B. Jones 2</display>
            </email>
        </emails>
    </contact>
    <contact>
        <id>2</id>
        <name>John Rodeo</name>
        <emails>
            <email>
                <addr>jrodeo1@dom.com</addr>
                <display>J. Rodeo 1</display>
            </email>
            <email>
                <addr>jrodeos2@dom.com</addr>
                <display>J. Rodeo 2</display>
            </email>
        </emails>
    </contact>
</contacts>

And here's the related Models
Ext.define('MyApp.model.Contact', {
    extend: 'Ext.data.Model',
    uses: [
        'MyApp.model.Emails'
    ],

    fields: [
        {
            name: 'id'
        },
        {
            name: 'name'
        }
    ],

    hasMany: {
        model: 'MyApp.model.Emails',
        autoLoad: true,
        foreignKey: 'addr',
        name: 'emailAddresses'
    }
});

Ext.define('MyApp.model.Emails', {
    extend: 'Ext.data.Model',
    uses: [
        'MyApp.model.Contact'
    ],

    idProperty: 'addr',

    fields: [
        {
            name: 'addr'
        },
        {
            name: 'display'
        }
    ],

    belongsTo: {
        model: 'MyApp.model.Contact'
    }
});

And finally, here's the store:
Ext.define('MyApp.store.MyXmlStore', {
    extend: 'Ext.data.Store',
    requires: [
        'MyApp.model.Contact'
    ],

    constructor: function(cfg) {
        var me = this;
        cfg = cfg || {};
        me.callParent([Ext.apply({
            autoLoad: true,
            storeId: 'MyXmlStore',
            model: 'MyApp.model.Contact',
            proxy: {
                type: 'ajax',
                url: 'data/data.xml',
                reader: {
                    type: 'xml',
                    record: 'contact'
                }
            }
        }, cfg)]);
    }
});

We created a simple Grid and link it to the Store...and presto,
it shows the contacts (quick ascii rendering)
+---------------------------+
| My Grid Panel             |
+-----+---------------------+
| Id  | Name                |
+-----+---------------------+
|  1  | Bob Jones           |
|  2  | John Rodeo          |

But we are at a complete loss as to how to retrieve the associated Email
records.
I've read that the GridPanel may not be able to correctly render associated
data. That's no problem for us -- we're just trying to get our heads around
how we can access it programatically using this mock-up data.
For example, let's say we wanted to create a simple onXmlstoreLoad event attached
to the store and we wanted to just console.log() the email addresses after loading
-- What would be the correct syntax?
We've tried the recommended approach:
onXmlstoreLoad: function(store, records, successful, operation, options) {
    console.log(store.emailAddresses.getAt(0));
}

But this results in an undefined reference.
I recognize it may boil down to us describing our Models incorrectly, but we've tried
dozens of different configurations and can't figure out whether or not the problem
is the data's not getting into the store...or whether or not we can't refer to is
syntactically correctly.

A: Finally figured out what I was missing to be able to successfully read nested models correctly. Once we populated our store correctly, it was a simple matter to access the nested data records.
The key bit we were missing had todo with the Proxy/reader.  EACH of the Model's needs to have their own Proxy reader so you can specify the 'record' and 'root' parameters.
I recommend anyone who stumbles across this thread check out the excellent site maintained by  Neil McGuigan -- http://extjs-tutorials.blogspot.com/2012_05_01_archive.html. There is tons of important tips & best practices you should follow.
One important clue Neil provided to our solution was that developers should hang Proxy's and Readers off Models, not off the store.  This made it simple to manage the Xml specific record/root parameters.
Whew this was a tough one...to anyone who's first entering the deep end of Extjs, I strongly recommend you get up close an personal with Firebug. Stepping into the extjs source code started to answer alot of important questions about how the various bits & pieces fit together.
The extjs code base is extremely well documented. And although the developers are clearly black-belts in Javascript which occasionally makes it a challenge to follow where they are going, the end result is well worth the effort.
In case you're looking for working code...
Our Store
Ext.define('MyApp.store.MyXmlStore', {
    extend: 'Ext.data.Store',
    requires: [
        'MyApp.model.Contact'
    ],

    constructor: function(cfg) {
        var me = this;
        cfg = cfg || {};
        me.callParent([Ext.apply({
            autoLoad: true,
            storeId: 'MyXmlStore',
            model: 'MyApp.model.Contact',
            listeners: {
                load: {
                    fn: me.onXmlstoreLoad,
                    scope: me
                }
            }
        }, cfg)]);
    },

    onXmlstoreLoad: function(store, records, successful, operation, options) {
        console.log("onXmlstoreLoad:"+ successful);
        console.log(s.getAt(0).emailAddressesStore.getAt(0));

    }

});

And our Models
Ext.define('MyApp.model.Contact', {
    extend: 'Ext.data.Model',
    uses: [
        'MyApp.model.Emails'
    ],

    fields: [
        {
            mapping: 'id',
            name: 'id',
            type: 'int'
        },
        {
            mapping: 'name',
            name: 'name',
            type: 'string'
        }
    ],

    hasMany: {
        associationKey: 'emails',
        model: 'MyApp.model.Emails',
        name: 'emailAddresses'
    },

    proxy: {
        type: 'ajax',
        url: 'data/data.xml',
        reader: {
            type: 'xml',
            root: 'contacts',
            record: 'contact'
        }
    }
});
Ext.define('MyApp.model.Emails', {
    extend: 'Ext.data.Model',
    uses: [
        'MyApp.model.Contact'
    ],

    fields: [
        {
            mapping: 'addr',
            name: 'addr',
            type: 'string'
        },
        {
            mapping: 'display',
            name: 'display',
            type: 'string'
        }
    ],

    proxy: {
        type: 'ajax',
        url: 'data/data.xml',
        reader: {
            type: 'xml',
            root: 'emails',
            record: 'email'
        }
    },

    belongsTo: {
        model: 'MyApp.model.Contact'
    }
});


text:
Q: Server.MapPath throws error when using web image cropping library I have an image stored on server at location:
C:\inetpub\wwwroot\imageupload\images

in my code i want to use an image from folder images so i am trying as follows:
Server.MapPath("/images/sample1.jpg")

But i am getting the error as:

Please help me to solve the error
As on several answer asking to post the code,it is as follows
.aspx
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<%@ Register Assembly="CS.Web.UI.CropImage" Namespace="CS.Web.UI" TagPrefix="cs" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body>
 <cs:CropImage ID="wci1" runat="server" />
    </body>
</html>

.aspx.cs
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {

        wci1.Crop(Server.MapPath("/imageupload/images/sample1.jpg"));

        /*
         this part is just to show the image after its been cropped and saved! so focus on just the code above.
         */
        Image img = new Image();
        img.ImageUrl = "images/sample1.jpg?rnd=" + (new Random()).Next();  // added random for caching issue.
        this.Controls.Add(img);
    }
}

Crop method is from a .dll file i have used from http://imagecropping.codeplex.com/

A: There error is in the CSA.Web.UI.CropImage.Crop method, as described by the stack trace.
Server.MapPath, to my knowledge, will not return a null string (it'll throw an exception if it can't map - but not a NullReferenceException).
I'd suggest you look into the method I mention and possibly post the relevant code, too.
EDIT:
So, I had a quick look at the Crop code from the CodePlex project you mention and found the following lines (formatting mine):
private string ImagePath { get { return ViewState["ImageUrl"].ToString(); } }

drawing.Image image = drawing.Image.FromStream(
    new MemoryStream(
        System.IO.File.ReadAllBytes(
            HttpContext.Current.Server.MapPath(this.ImagePath)
        )
    )
);

cropedImage.Save(path);

Now, it seems to me that:

*

*Argument Path is not null*

*Argument ImageUrl is null**

*Though it might be 'incorrect' it isn't the problem right now.
**Meaning the call ToString is the breaking factor in this code.
Basically, the control doesn't have an image set to crop and this is evident in your own code:
//currently no ImageUrl set...
<cs:CropImage ID="wci1" runat="server" />

//your'e trying to crop here without an ImageUrl...
wci1.Crop(Server.MapPath("/imageupload/images/sample1.jpg"));

The fix is to specify an image via ImageUrl, AFAIK, however I can't see how to do so.

A: You have stored your images in imageupload\images but when you tried to grab them you forgot to add in the imageupload directory:
Server.MapPath("/imageupload/images/sample1.jpg")

A: Try a relative path instead:
Server.MapPath("images/sample1.jpg")

A: consider using "~/images/sample1.jpg" for your source. the "~" is replace by the application name in the call to Server.MapPath

A: According to:
https://webcropimage.svn.codeplex.com/svn/trunk/CS.WebControls/WebCropImage/CropImage.cs
Method Crop(), gives a path where to save the cropped image.
Which image should be cropped is stored in wci1.ImagePath
Please check if this value is null, and this should point out the problem.
As there is no <Form runat="Server">, maybe it cannot access the ViewState:
private string ImagePath { get { return ViewState["ImageUrl"].ToString(); } }


text:
Q: Get order of list by value I have an order of list with different values:
List<Double> values = new LinkedList<Double>();
values.add(0.1);
values.add(0.8);
values.add(0.3);

What is the fastest way to get a list with indexes depending on the order of values of the given list, in this case {1, 3, 2} because 0.1 is the smallest, 0.2 the second smallest and 0.8 the third smallest?

A: If all the values are uniques, one way is to use a TreeMap and then get back the corresponding indexes calling values().
TreeMap<Double, Integer> map = new TreeMap<>();
int index = 0;
for(Double d : values){
    map.put(d, ++index);
}
System.out.println(map.values()); //[1, 3, 2]

This approach runs in O(nlogn) (but uses extra memory space).
If the values are not unique, you could use a TreeMap<Double, List<Integer>> and then flatmap the Collection<List<Integer>>

A: A way to get this index list, using only jdk5
    List<Float> positions = new ArrayList<Float>();
    List<Integer> indexes = new ArrayList<Integer>();
    positions.add(0.1f);
    positions.add(0.8f);
    positions.add(0.3f);

    // copy float elements to another List, so to keep the order
    List<Float> sortedPositions = new ArrayList<Float>();
    Collections.copy(sortedPositions, positions);
    Collections.sort(sortedPositions);

    for (Float position : positions) {
        indexes.add(sortedPositions.indexOf(position));
    }

    for (Integer index : indexes) {
        System.out.print(index + ",");
    }
    // prints 1,3,2,

A: You have to sort the list so that it will be sorted in the natural order before using is:
Collections.sort(values);


text:
Q: Expansion in Fourier series involving a complicated "argument" I know how to expand a function $f(x)$ into a Fourier series with the period $2L$:
$$f(x) = \frac{a_0}{2} + \sum_{n=1}^\infty a_n\cos(n\pi x/L)+\sum_{n=0}^\infty b_n\sin(n\pi x/L),$$
but what if I want to expand $f(x)$ into a series of the type
$$f(x) = \frac{a_0}{2} + \sum_{n=1}^\infty a_n\cos(g(n)\pi x/L)+\sum_{n=0}^\infty b_n\sin(g(n)\pi x/L),$$
where $g(n)$ can be a slightly more complicated function of $n$? Does this even make sense?
To clarify, let me describe a recent scenario in which I've run into problems, what I've tried and where I've failed:
I have a solution the the transient, one-dimensional heat equation on the form
$$\psi(x,t) = \sum_{n=0}^\infty a_ne^{-\kappa\lambda_n^2t}\cos(\lambda_nx),$$
where
$$\lambda_n = (1+2n)\frac{\pi}{2L},$$
so I guess the period is here $4L$ (note that the period in the present example ($4L$) is different from the definition above ($2L$)). The initial condition is
$$\psi(x,0) = \phi(x),$$
where
$$\phi(x)=\frac{RL^2}{2k}\left[1-\frac{x^2}{L^2}\right].$$
Thus, I'm faced with the problem of finding the $a_n$ given the condition
$$\sum_{n=0}^\infty a_n\cos(\lambda_nx) = \phi(x).$$
I've found that
$$\int_{-2L}^{2L}\cos(\lambda_nx)\cos(\lambda_kx)dx = \cases{2L, \quad n = k\\0, \quad n \neq k},$$
so I figured I could just write
$$a_k2L = \int_{-2L}^{2L}\phi(x)\cos(\lambda_kx)dx$$
$$\Rightarrow a_k = -\frac{8 L^2 R}{k\pi^2(1 + 2n)^2}.$$
However, inserting this, the initial condition isn't satisfied.
Is my general approach to this problem right? If not, how am I supposed to go about solving it?


text:
Q: Button click to show overlay over image (only CSS) I am trying to achieve that when you click the yellow circle with fa-icon inside that then the overlay shows over my image. Now the overlay shows below the image (green background with white text). My overlay code works, to see that, change div id="overlay" to div class="overlay".
How to make the button click show my overlay over the image (no javascript)?

/*@media screen and (max-width: 767px) {*/
  .button i {
    padding: 8px 13px;
    display: inline-block;
    -moz-border-radius: 180px;
    -webkit-border-radius: 180px;
    border-radius: 180px;
    -moz-box-shadow: 0px 0px 2px #888;
    -webkit-box-shadow: 0px 0px 2px #888;
    box-shadow: 0px 0px 2px #888;
    background-color: yellow;
    color: red;
    position: absolute;
    left: 20%;
    top: 20%;
  }
/*}*/

.button i:hover {
  color:#FFF;
  background-color:#000;
 }

/*@media screen and (min-width: 768px) {*/
  .product-detailscar:hover .overlay {
    opacity: 1;
  }
/*}*/

.product-detailscar {
    background-color: #E6E6E6;
    text-align: center;
  position: relative;
}

.intro, .userfield1car {
  color:#fff;
  font-weight:700;
  font-size:22px;
  text-align:center;
  background-color:green;
 }

.product-detailscar .overlay {
  /*.well.carousel .overlay {*/
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0;
  border-radius: 0;
  background: blue;
  color: #FFF;
  text-align: left;
  border-top: 1px solid #A10000;
  border-bottom: 1px solid #A10000;
  /*vertical-align: middle;*/
  -webkit-transition: opacity 500ms;
  -moz-transition: opacity 500ms;
  -o-transition: opacity 500ms;
  transition: opacity 500ms;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>

                    Intro description car

                    Userfield-1-car

                    Userfield-2-car

                    Userfield-3-car

A: You can add the following part to your CSS:
#overlay {
  display: none;
}

#overlay:target {
  display: block;
}

And then in your code change:
.product-detailscar .overlay

To:
#overlay

And change opacity to more then 0, ex. 0.5;
Note that it will only work one way, so it will only show the overlay. If you want to show/hide overlay in pure CSS, the checkbox hack is the way to go. For more info check https://css-tricks.com/the-checkbox-hack/
Updated example (no checkbox hack):

  .button i {
    padding: 8px 13px;
    display: inline-block;
    -moz-border-radius: 180px;
    -webkit-border-radius: 180px;
    border-radius: 180px;
    -moz-box-shadow: 0px 0px 2px #888;
    -webkit-box-shadow: 0px 0px 2px #888;
    box-shadow: 0px 0px 2px #888;
    background-color: yellow;
    color: red;
    position: absolute;
    left: 20%;
    top: 20%;
  }

.button i:hover {
  color:#FFF;
  background-color:#000;
 }

  .product-detailscar:hover .overlay {
    opacity: 1;
  }

.product-detailscar {
    background-color: #E6E6E6;
    text-align: center;
    position: relative;
}

.intro, .userfield1car {
  color:#fff;
  font-weight:700;
  font-size:22px;
  text-align:center;
  background-color:green;
 }

#overlay {
  display: none;
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  opacity: 0.5;
  border-radius: 0;
  background: blue;
  color: #FFF;
  text-align: left;
  border-top: 1px solid #A10000;
  border-bottom: 1px solid #A10000;
  -webkit-transition: opacity 500ms;
  -moz-transition: opacity 500ms;
  -o-transition: opacity 500ms;
  transition: opacity 500ms;
}

#overlay:target {
  display: block;
}
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>

                    Intro description car

                    Userfield-1-car

                    Userfield-2-car

                    Userfield-3-car

BTW, it is a good idea to clean up your code ;)

A: You can move the overlay div just beneath the image-video-linkssidebar class like this:
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.3/css/font-awesome.min.css" rel="stylesheet"/>

                    Intro description car

                    Userfield-1-car

                    Userfield-2-car

                    Userfield-3-car

Then add these styles to overlay:
position: absolute;
    z-index: 9999;
    margin: 0 auto;
    width: 100%;


text:
Q: create product after user loggedin We have 2 buttons in Product view page, after we click on 1st button, we are creating Product Programtaically.
once click on 2nd button [ after entering email, password] we are assigning the product to that customer.
Here issue is we are creating product immediately after click on 1st button, but we need to save the product in session and nwe want to create that product after user click on 2nd button.
protected function _createProduct($type, $doSave = true, $originalProduct, $newImagePath = "")
    {

        Mage::register('isSecureArea', true);
        $session = Mage::getSingleton('customer/session');

        $result = array(
            'success' => false
        );

        $login = "";
        $productId = "";
        if ($this->getRequest()->isPost()) {
            $login = $this->getRequest()->getPost('login');
            $productId = $this->getRequest()->getPost('product_id');
        }

        try {
            if (isset($login) && (is_array($login) && !empty($login)) || ($login != "")) {
                $designId = Mage::getSingleton('core/session')->getData('mydesign_id');
                $session->login($login['username'], $login['password']);
                $result['redirect'] = $this->_getRefererUrl() ? $this->_getRefererUrl() : Mage::getUrl('customer/account', array(
                    '_secure' => true
                ));
                $result['success'] = true;
                $customerId = Mage::getSingleton('customer/session')->getCustomerId();
                $model = Mage::getModel('example/mydesign')->load($designId);
                if ($model->getId()) {
                    $model->setData('customer_id',$customerId);
                    $model->save();
                }

                Mage::getSingleton('core/session')->unsetData('mydesign_id');
                $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));
                return $this;
            } else {
                $customerId = "";
            }

            $product = Mage::getModel('catalog/product');

            $product->setName($originalProduct->getName());

            $customerId = Mage::getSingleton('customer/session')->getCustomerId();
            $product->setCustomUid($customerId);

            if ($doSave) {
            }
            $product->save();

            $fav1_id = '';
            $data = array(
                'title' => $fav1_id,
                'product_id' => $product->getId(),
                'customer_id' => $customerId

            );
            //echo '<pre/>';
            $model = Mage::getModel('example/mydesign')->setData($data);
            try {
                $fav1_id = $model->save()->getId();
                if (!$customerId) {
                    Mage::getSingleton('core/session')->setData('mydesign_id', $fav1_id);
                }

            } catch (Exception $e) {
                echo $e->getMessage();
            }
            // To save

            return $product;

        } catch (Mage_Core_Exception $e) {
            switch ($e->getCode()) {
                case Mage_Customer_Model_Customer::EXCEPTION_EMAIL_NOT_CONFIRMED:
                    $message = Mage::helper('customer')->__('This account');
                    break;
                default:
                    $message = $e->getMessage();
            }
            $result['error'] = $message;
            $session->setUsername($login['username']);

        } catch (Exception $e) {
            $result = "ERROR :" . $e->getMessage();

        }

        Mage::unregister('isSecureArea');
        $this->getResponse()->setBody(Mage::helper('core')->jsonEncode($result));

    }

A: You can save your entire created product in session like
Mage::getModel('core/session')->setMyProduct("your product variable");
and get it back when you set your customer by
Mage::getModel('core/session')->getMyProduct();


text:
Q: How does resizing work for edit-in-place JQuery UI textarea editable? I have problems getting a JQuery Edit-In-Place textarea to be a fixed size.
Basically I have one HTML file, part of which has a paragraph named editable-large:

About Me

         Ansel Easton Adams (February 20, 1902 – April 22, 1984) was an American photographer and environmentalist, best known for his black-and-white photographs of the American West, especially in Yosemite National Park.

And I have a JQuery JS file associated with that paragraph that allows it to be edited in place. So whenever someone clicks on the paragraph, it turns into a textarea.
$(".editable-large").editable(
    {  submit: "Save",
       cancel: "Cancel",
       type: "textarea",
       options: {"cols": 80, "rows": 10},
    }).css({"cols": 80,"rows": 10});

I want the textarea to have a certain width and height (80 & 10), but no matter what values I put in, it's always the same size and looks like this. I'd greatly appreciate any help in making that textarea a fixed size.

A: You can do that be giving your textarea a width and height ex:
textarea{
    width:100px;
    height:50px;
}

A: $(".editable-large").editable(
    {  submit    : "Save",
       cancel    : "Cancel",
       type      : "textarea",
       width     : '100',
       height    : '50'
    }
);