text:
Q: Calculate the hash of a file longer than 256 characters? I am using Boe Prox's script to print a list of all the files and folders in a directory.  I need Prox's script (as opposed to other windows print directory commands) because it uses robocopy to print filepaths longer than 260 characters.
My problem is, I also want the filehash to be printed alongside the file name.  I have modified the script to obtain hashes (please see below) and it generally works except when the filepath is longer than 260 characters.  Long filepaths get a blank in the hash column of the final output.
Research I have done:

*

*According to this stackoverflow question, Robocopy has several switches that can be modified.  I have scoured Boe's blog, as well as the list of robocopy commands, but there is nothing about a filehash switch.

Attempts to fix the problem:

*

*I have also tried to modify the syntax of the filehash to make it more in line with the rest of the script ie.  Hash = $matches.Hash
(this returns all blanks in place of the filehashs)

*I tried taking off the part of the regex that seems to specify an item rather than the content of the item ie:If ($_.Trim() -match "^(?<Children>\d+)\s+") {
(this leads to the error code WARNING: Cannot bind argument to parameter 'Path' because it is null.)

I'm pretty hopeful that this can happen though: comments in Boe's original script includes the line: "Version 1.1 -Added ability to calculate file hashes"
Here's is my (partially working script):
Function Get-FolderItem {

    [cmdletbinding(DefaultParameterSetName='Filter')]
    Param (
        [parameter(Position=0,ValueFromPipeline=$True,ValueFromPipelineByPropertyName=$True)]
        [Alias('FullName')]
        [string[]]$Path = $PWD,
        [parameter(ParameterSetName='Filter')]
        [string[]]$Filter = '*.*',
        [parameter(ParameterSetName='Exclude')]
        [string[]]$ExcludeFile,
        [parameter()]
        [int]$MaxAge,
        [parameter()]
        [int]$MinAge
    )
    Begin {
        $params = New-Object System.Collections.Arraylist
        $params.AddRange(@("/L","/E","/NJH","/BYTES","/FP","/NC","/XJ","/R:0","/W:0","T:W"))
        If ($PSBoundParameters['MaxAge']) {
            $params.Add("/MaxAge:$MaxAge") | Out-Null
        }
        If ($PSBoundParameters['MinAge']) {
            $params.Add("/MinAge:$MinAge") | Out-Null
        }
    }
    Process {
        ForEach ($item in $Path) {
            Try {
                $item = (Resolve-Path -LiteralPath $item -ErrorAction Stop).ProviderPath
                If (-Not (Test-Path -LiteralPath $item -Type Container -ErrorAction Stop)) {
                    Write-Warning ("{0} is not a directory and will be skipped" -f $item)
                    Return
                }
                If ($PSBoundParameters['ExcludeFile']) {
                    $Script = "robocopy `"$item`" NULL $Filter $params /XF $($ExcludeFile  -join ',')"
                } Else {
                    $Script = "robocopy `"$item`" NULL $Filter $params"
                }
                Write-Verbose ("Scanning {0}" -f $item)
                Invoke-Expression $Script | ForEach {
                    Try {
                        If ($_.Trim() -match "^(?<Children>\d+)\s+(?<FullName>.*)") {
                           $object = New-Object PSObject -Property @{
                                FullName = $matches.FullName
                                Extension = $matches.fullname -replace '.*\.(.*)','$1'
                                FullPathLength = [int] $matches.FullName.Length
                                Length = [int64]$matches.Size
                                FileHash = (Get-FileHash -Path $matches.FullName).Hash
                                Created = (Get-Item $matches.FullName).creationtime
                                LastWriteTime = (Get-Item $matches.FullName).LastWriteTime
                            }
                            $object.pstypenames.insert(0,'System.IO.RobocopyDirectoryInfo')
                            Write-Output $object
                        } Else {
                            Write-Verbose ("Not matched: {0}" -f $_)
                        }
                    } Catch {
                        Write-Warning ("{0}" -f $_.Exception.Message)
                        Return
                    }
                }
            } Catch {
                Write-Warning ("{0}" -f $_.Exception.Message)
                Return
            }
        }
    }
}

Get-FolderItem "C:\TestingFileFolders"

A: In Windows PowerShell, you can prepend \\?\ to the full path and read the file:
Get-FileHash -Path "\\?\$($matches.FullName)"


text:
Q: Integrate $e^{\frac{x-y}{x+y}}$ over the triangle bounded by $x=0$, $y=0$, and $y=1-x$ Using change of variables, integrate $\exp\left(\frac{x-y}{x+y}\right)$  over the triangle bounded by $x=0$, $y=0$, and $y=1-x$.
I'm using $u=x-y$ and $v=x+y$ but running into the issue where I have to integrate something like $ve^{u/v} \, dv$ which is nasty.
Any ideas?

A: You actually don't end up integrating $v e^{u/v}$.
The variable change $u=x-y,v=x+y$ is a linear map, and so it multiplies areas everywhere by the constant amount given by the determinant of the matrix of partials, which for this linear function are all $+1$ or $-1$. I got the multiplying factor is $2$, so that you end up in fact integrating
$$\frac{1}{2}e^{u/v}$$
over the triangle whose vertices are $(0,0),(1,1),(-1,1)$.
Setting this up as an iterated integral, so that we integrate over $u$ and then $v$, gives
$$\int_0^1 \int_{-v}^{v} e^{u/v} \, du \, dv.$$
The value of the inside integral here is $\dfrac12\left(e-\dfrac1e\right)v$, and when this is then integrated from $0$ to $1$ we get $\dfrac12\left(e-\dfrac1e\right) \cdot \dfrac12,$ or
$$\frac{e-\dfrac1e}{4}.$$

redpajama_set_name: RedPajamaStackExchange


text:
Q: iteration count display in mapply I am using mapply(function,args), for a big dataset. After 100 iterations I need to set a delay for 1 sec. So the question is if it possible to show iteration count or progress bar within mapply (function, args)
Thanks

A: No, but if you switch to using the corresponding functions from plyr you can add a progress bar to the function call.
Without you giving us a minimal, reproducible example I'm not going to the effort of finding the exact plyr equivalent, but it will be one of the m*ply functions:
> ls(pos=2,pattern="m.*ply")
[1] "maply" "mdply" "mlply" "m_ply"

A: If you know the total number of iterations in advance, you could just add another argument to mapply as an iteration counter. In this example I added z. This example makes the command line sleep for 1 second every 3 iterations....
mapply( function(x,y,z) { if(z%%3==0){Sys.sleep(1);
    cat(paste0( "Interation " , z , " ...sleeping\n") ) }
    x*y } ,x=1:10,y=1:10,z=1:10)
#Interation 3 ...sleeping
#Interation 6 ...sleeping
#Interation 9 ...sleeping
# [1]   1   4   9  16  25  36  49  64  81 100

If you need more convincing wrap the statement in system.time(). I get a runtime of 3.002 seconds.


text:
Q: Rectangle - Emgu CV I'm trying to distinguish circular and rectangular objects from an image. I've labeled the round ones, using contours and the formula:
metric = 4*pie*contour.Area / (contour.perimeter^2)

Since I'm almost done, I wanted to know the alternate of this formula, which works for Rectangles. I'm bit weak in mathematics.

A: There is a simple tutorial from Emgu cv on finding shapes in an image.
It lets you find circles, triangles and squares.
You can check it out here shape tutorial.
Hope this helps you with your problem.


text:
Q: C, enum within struct, error C2016, header file Got it working, thanks all ;]
code
enum genre {A, B, C, D, E};

struct recipe
{
    genre category;
    char name[50];
    char ingredients[50];
    char instruction[1000];
};

void menu();
void file_check(char *name);

errors:
error C2016: C requires that a struct or union has at least one member
error C2061: syntax error : identifier 'genre'
error C2059: syntax error : '}'

This is my header file. I can't figure out what compiler want from me :( I thought it would work this way

A: C requires you to use:
enum genre category;

instead of
genre category;

To use genre category declaration, you'd need to typedef:
typedef enum {A, B, C, D, E} genre;

instead of
enum genre {A, B, C, D, E};

A: C language requires that an identifier of struct/enum/union type, have its type by your left-side in each place you want to use it. For avoid typying this each time, you can use typedef keyword.


text:
Q: Append a link to a div using ajax I want to add a link to a div based on: if true, append link1, else, append link2.
I tried:
The div

testing link

Javascript:
if($.inArray(id, data) !== -1){
    $('.mainDiv').find('a#link'+id).attr('href','link1.php');
}else{
    $('.mainDiv').find('a#link'+id).attr('href','link2.php');
}


text:
Q: No he podido con este problema Debo hacer un programa que tenga un arreglo con 10 numeros. El arreglo se llena a partir de entradas y tan pronto como termine de llenar el arreglo el programa debe imprimir la posición en la cual se encuentra el numero mayor....
Hasta el momento solo he podido llenar las entradas, he intentado comparar los elementos dentro del arreglo pero no he podido, no se como hacerlo... Esto es lo que llevo del programa:
    package main;
    import java.util.Scanner;
    public class Main {
        static int [] numeros = new int [10];
        public static void main(String[]args) {
            Scanner entrada = new Scanner(System.in);
            for(int i = 0; i < numeros.length; i++ ) {
                System.out.print("Llene el arreglo por favor: ");
                numeros[i] = entrada.nextInt(); //Se llena el arreglo
            }
            // Se recorre el arreglo para mirar donde esta el numero mas grande
            /**for(int i = 0; i < numeros.length; i++) {
               int mayor = 0;
               if(numeros[mayor] > numeros [i] ) {
            System.out.println("El numero mayor esta en la posicion: " + numeros[i]);
               }
               }*/

        }
    }

A: Agrego código comentado.
package main;
import java.util.Scanner;
public class Main {
    static int[] numeros = new int[10];

    // 1. Agregar variable para guardar el mayor
    int mayor = Integer.MIN_VALUE;
    // 2. Agregar variable para guardar la posicion
    int posicion = 0;

    public static void main(String[] args) {
        Scanner entrada = new Scanner(System.in);
        for (int i = 0; i < numeros.length; i++) {
            System.out.print("Llene el arreglo por favor: ");
            numeros[i] = entrada.nextInt(); //Se llena el arreglo

            // 3. evaluar aquí si el número ingresado es mayor
            // que el actual mayor y actualizar
            if (numeros[i] > mayor) {
                mayor = numeros[i];
                // 4. guardar la posicion actual
                posicion = i;
            }
        }
        // 5. imprimir la posicion del numero mayor
        System.out.println("El numero mayor esta en la posicion " + posicion);
    }
}

Actualización:

Como hace mayor para interactuar con el arreglo si no esta adentro de
el?

No lo hace. La variable mayor es independiente al arreglo. Lo único que tiene en común con el arreglo es que mayor también está dentro del ciclo for por lo que se aprovecha para calcular su valor al mismo tiempo que se va llenando el arreglo.

¿Porque se iguala la variable con el arreglo?

La variable mayor no se iguala con el arreglo. Se iguala con el elemento del arreglo en la posición i la cual contiene el número recién ingresado.

A: facil necesitas un sentinel que este pendiente de la posicion
array = (a0. a1 ...an)
al inicio tu numero mayor va ser a0
ENTONCES
sentinel =  0;
mayor = a[0]
for i = 1 hasta n-1
   si mayor <a[i]
     sentinel = i
     mayor = a[i]

si sentinel no cambia osea siempre es 0 en la 0 esta el mayor puedes hacerlo así pero si es un array grande lo mejor es hacer divide and conquer

A: Veo que ya respondieron esta pregunta pero creo que es importante que recuerdes que en los arreglos se empieza a contar desde el 0 y no desde el 1. Yo le agregaría una pequeña suma ya que, puede dar error por un valor, la ubicación del numero más alto por -1.
Te dejo el código, espero te sirva:
    int NumeroMayor = 0;
    int Posicion = 0;

    for(int i = 0; i < numeros.length; i++ ) {
        if (numeros[i] >= NumeroMayor) {
            NumeroMayor = numeros[i];
            Posicion = i+1;
        }

Saludos.


text:
Q: Ordenar os filhos em consulta Linq Estou com problema em fazer uma ordenação em uma consulta onde tenho que ordenar os filhos pelo o ID, Segue o Fonte.
public Grid GetByOrderGridData(long id)
{
    var query = from c in context.Set<Grid>()
                where c.Id == id
                orderby c.GridDatas.OrderBy(p => p.Id)
                select c;
    return query.FirstOrDefault();
}

o fonte compila sem problema mas ao consultar.

{"DbSortClause expressions must have a type that is order comparable.\r\nNome do parâmetro: key"}

A: A resposta é esta:
public Grid GetByOrderGridData(long id)
{
        var query = from c in context.Set<Grid>()
                    where c.Id == id
                    orderby c.Id
                    select c;
        return query.FirstOrDefault();
}

Se você quiser pegar de ordem decrescente basta fazer:
orderby c.Id descending

Você também pode fazer assim:
public Grid GetByOrderGridData(long id)
{
     return = (from c in context.Set<Grid>()
              where c.Id == id
              select c).OrderBy(p => p.Id).FirstOrDefault();
}

E também pode fazer usando expressão lambda:
public Grid GetByOrderGridData(long id)
{
     return context.Set<Grid>().Where(x => x.Id.Equals(id)).OrderBy(x => x.Id).FirstOrDefault();
}

A: Você tem duas opções viáveis:

*

*Ordernar os dados depois de consultar
var query = from c in context.Set<Grid>()
            where c.Id == id
            select c;

var retorno = query.FirstOrDefault();
retorno.GridDatas = retorno.GridDatas.OrderBy(x => x.Id).ToList();

return retorno;

*Executar uma query separada para trazer os elementos filhos:
var elemento = context.context.Set<Grid>().FirstOrDefault(g => g.Id == id);
var entry = context.Entry(elemento);

entry.Collection(e => e.GridData).Query().OrderBy(c => c.Id).Load();

A: Eu resumiria tudo em.
public Grid GetByOrderGridData(long id)
{
    var grid = (from c in context.Set<Grid>()
                where c.Id == id
                orderby c.
                select c
              ).FirstOrDefault();

    if(grid != null)
        grid = grid.GridDatas.OrderBy(p => p.Id);

    return grid;
}

Uma vez que você vai ao banco usando o FirstOrDefault. você tem os dados em memoria é pode trabalha, uma observação aqui é que o FirstOrDefault retorna NULL como Default e se isso não for tratado seu grid.GridDatas.OrderBy retornara erro.


text:
Q: MySQL doesn't seem to work correct I have this college database where i have to Retrieve names of instructors teaching Computer Science courses, the sections (course number, section number, year, semester) they are teaching, and the total number of students in the sections
So far this is what have managed but the output is not correct.
SELECT  i.instructor_id,o.year,o.semester,o.section_number, o.number as CourseNumber,o.Total_num_student
FROM Instructor i JOIN
(SELECT t.instructor_id,t.year,t.semester,t.section_number,o1.number,o1.Total_num_student
 FROM teaches t JOIN
 (SELECT COUNT(s.student_id) as Total_num_student,e.section_number,e.number
  FROM Student s JOIN
  enrolls e
  ON s.student_id=e.student_id
  GROUP BY section_number,e.number) as o1
 ON o1.section_number=t.section_number) as o
on i.instructor_id=o.instructor_id
WHERE department='Computer Science';

Can you see what is wrong with the output.
create table Course (
  number int,
  title varchar(255),
  credits int,
  syllabus varchar(255),
PRIMARY KEY (number)
  );
INSERT INTO Course VALUES (620,'Algorithm',3,'XYZ');
INSERT INTO Course VALUES (621,'Algorithm',3,'XYZ');
INSERT INTO Course VALUES (232,'Java',2,'ABC');
INSERT INTO Course VALUES (420,'Cpp',2,'PQRS');
INSERT INTO Course VALUES (720,'Big Data',3,'NVGY');
INSERT INTO Course VALUES (120,'Intelligent System',4,'KJHU');
INSERT INTO Course VALUES (220,'Operating System',3,'GED');
INSERT INTO Course VALUES (480,'Graphics',4,'RSFN');
INSERT INTO Course VALUES (520,'Distributed Networks',3,'NHU');
INSERT INTO Course VALUES (820,'Data Mining',3,'TYU');
INSERT INTO Course VALUES (700,'Cryptography',1,'MNO');

create table Student (
  student_id int,
  name varchar(255),
  department varchar(255),
  PRIMARY KEY (student_id)
  );

INSERT INTO Student VALUES (2345,'Mike','Computer Science');
INSERT INTO Student VALUES (346,'Rob','Computer Science');
INSERT INTO Student VALUES (789,'Nick','Game Design');
INSERT INTO Student VALUES (675,'Sara','Computer Science');
INSERT INTO Student VALUES (123,'Raj','Chemical');
INSERT INTO Student VALUES (5331,'Jack','Biotech');
INSERT INTO Student VALUES (1023,'Michelle','Chemical');
INSERT INTO Student VALUES (9800,'Jie','Game Design');
INSERT INTO Student VALUES (7834,'Dan','Petroleum');
INSERT INTO Student VALUES (4567,'Patrick','Computer Science');

create table Instructor (
  instructor_id int,
  name varchar(255),
  department varchar(255),
  title varchar(255),
  PRIMARY KEY (instructor_id)
  );

INSERT INTO Instructor VALUES (12,'John','Computer Science','Java');
INSERT INTO Instructor VALUES (23,'Bischof','Mechanical','Drawing');
INSERT INTO Instructor VALUES (56,'Kwon','Biotech','Biology');
INSERT INTO Instructor VALUES (78,'Deever','Security','Cryptography');
INSERT INTO Instructor VALUES (45,'Jin','Computer Science','Cpp');
INSERT INTO Instructor VALUES (67,'Bailey','Petroleum','Metalurgy');
INSERT INTO Instructor VALUES (90,'Richard','Industrial','Manufacture');
INSERT INTO Instructor VALUES (11,'Joe','Chemical','Chemistry');
INSERT INTO Instructor VALUES (24,'Roger','Game Design','Cpp');
INSERT INTO Instructor VALUES (55,'Zack','Computer Science','Design');

create table CourseOffering (
  number int,
  year int,
  semester int,
  section_number int,
  classroom int,
  PRIMARY KEY (number,year,semester,section_number),
  FOREIGN KEY (number) REFERENCES Course (number)
  );

INSERT INTO CourseOffering VALUES (620,2012,2,102,3540);
INSERT INTO CourseOffering VALUES (621,2013,3,103,3545);
INSERT INTO CourseOffering VALUES (232,2011,1,103,3455);
INSERT INTO CourseOffering VALUES (420,2013,3,101,2650);
INSERT INTO CourseOffering VALUES (720,2013,3,100,3455);
INSERT INTO CourseOffering VALUES (120,2014,1,102,3000);
INSERT INTO CourseOffering VALUES (220,2008,2,104,1450);
INSERT INTO CourseOffering VALUES (480,2009,4,106,1400);
INSERT INTO CourseOffering VALUES (520,2010,3,102,3500);
INSERT INTO CourseOffering VALUES (820,2008,3,100,2700);
INSERT INTO CourseOffering VALUES (700,2012,1,103,2540);

create table CourseOffering_Timing (
  number int,
  year int,
  semester int,
  section_number int,
  timing int,
  PRIMARY KEY (number,year,semester,section_number,timing),
  FOREIGN KEY (number) REFERENCES Course (number)
  );

INSERT INTO CourseOffering_Timing VALUES (620,2012,2,102,9);
INSERT INTO CourseOffering_Timing VALUES (621,2013,3,103,9);
INSERT INTO CourseOffering_Timing VALUES (232,2011,1,103,3);
INSERT INTO CourseOffering_Timing VALUES (420,2013,3,101,2);
INSERT INTO CourseOffering_Timing VALUES (720,2013,3,100,5);
INSERT INTO CourseOffering_Timing VALUES (120,2014,1,102,4);
INSERT INTO CourseOffering_Timing VALUES (220,2008,2,104,10);
INSERT INTO CourseOffering_Timing VALUES (480,2009,4,106,12);
INSERT INTO CourseOffering_Timing VALUES (520,2010,3,102,4);
INSERT INTO CourseOffering_Timing VALUES (820,2008,3,100,2);
INSERT INTO CourseOffering_Timing VALUES (700,2012,1,103,3);

create table PreRequisite (
  number int,
  prerequisite_number int,
  PRIMARY KEY (number,prerequisite_number),
  FOREIGN KEY (number) REFERENCES Course(number)
  );

INSERT INTO PreRequisite VALUES (620,480);
INSERT INTO PreRequisite VALUES (621,481);
INSERT INTO PreRequisite VALUES (232,120);
INSERT INTO PreRequisite VALUES (420,320);
INSERT INTO PreRequisite VALUES (720,580);
INSERT INTO PreRequisite VALUES (120,110);
INSERT INTO PreRequisite VALUES (220,130);
INSERT INTO PreRequisite VALUES (480,380);
INSERT INTO PreRequisite VALUES (520,360);
INSERT INTO PreRequisite VALUES (820,700);
INSERT INTO PreRequisite VALUES (700,610);

create table enrolls (
  student_id int,
  number int,
  year int,
  semester int,
  section_number int,
  grade varchar(10),
  PRIMARY KEY (student_id,number,year,semester,section_number),
  FOREIGN KEY (number,year,semester,section_number) REFERENCES CourseOffering(number,year,semester,section_number),
  FOREIGN KEY (student_id) REFERENCES Student (student_id)
  );

INSERT INTO enrolls VALUES (2345,620,2012,2,102,'A');
INSERT INTO enrolls VALUES (346,232,2011,1,103,'B');
INSERT INTO enrolls VALUES (789,420,2013,3,101,'A');
INSERT INTO enrolls VALUES (675,621,2013,3,103,'C');
INSERT INTO enrolls VALUES (123,120,2014,1,102,'B');
INSERT INTO enrolls VALUES (5331,220,2008,2,104,'A');
INSERT INTO enrolls VALUES (1023,480,2009,4,106,'B');
INSERT INTO enrolls VALUES (9800,520,2010,3,102,'A');
INSERT INTO enrolls VALUES (7834,820,2008,3,100,'C');
INSERT INTO enrolls VALUES (4567,700,2012,1,103,'F');

create table teaches (
  instructor_id int,
  number int,
  year int,
  semester int,
  section_number int,
  PRIMARY KEY (instructor_id, number, year, semester, section_number),
  FOREIGN KEY (instructor_id) REFERENCES Instructor(instructor_id),
  FOREIGN KEY ( number, year, semester, section_number) REFERENCES CourseOffering( number, year, semester, section_number)
  );

INSERT INTO teaches VALUES (12,620,2012,2,102);
INSERT INTO teaches VALUES (12,621,2013,3,103);
INSERT INTO teaches VALUES (23,232,2011,1,103);
INSERT INTO teaches VALUES (56,420,2013,3,101);
INSERT INTO teaches VALUES (78,720,2013,3,100);
INSERT INTO teaches VALUES (45,120,2014,1,102);
INSERT INTO teaches VALUES (67,220,2008,2,104);
INSERT INTO teaches VALUES (90,480,2009,4,106);
INSERT INTO teaches VALUES (11,520,2010,3,102);
INSERT INTO teaches VALUES (24,820,2008,3,100);
INSERT INTO teaches VALUES (55,700,2012,1,103);

A: See if this will work for you
SELECT Instructor.name AS instructor_name, teaches.section_number AS section_number,
 teaches.year AS year, teaches.semester AS semester, COUNT(enrolls.student_id) FROM Instructor
 INNER JOIN teaches ON teaches.instructor_id = Instructor.instructor_id
 INNER JOIN enrolls ON teaches.section_number = enrolls.section_number AND teaches.semester = enrolls.semester AND teaches.year = enrolls.year
 WHERE department='Computer Science'
 GROUP BY Instructor.name, teaches.section_number, teaches.year, teaches.semester;

A: I'm not completely sure what you are trying to achieve but this is if you like to retain the section info:
SELECT a.instructor_id, group_concat(DISTINCT a.year SEPARATOR ', ') YEAR, group_concat(DISTINCT a.semester SEPARATOR ', ') SEMESTER, group_concat(DISTINCT a.section_number SEPARATOR ', ') SECTION_NUMBER, group_concat(DISTINCT a.coursenumber SEPARATOR ', ') COURSENUMBER, count(a.student_id) as Total_num_student FROM (
SELECT e.student_id, i.instructor_id, t.year,t.semester,t.section_number, t.number as CourseNumber
FROM instructor i
JOIN teaches t
ON i.instructor_id = t.instructor_id
JOIN enrolls e
ON e.section_number=t.section_number
WHERE department='Computer Science') a
GROUP BY a.instructor_id
;

SELECT a.instructor_id,  a.year, a.semester, a.section_number, a.coursenumber, count(a.student_id) as Total_num_student FROM (
SELECT e.student_id, i.instructor_id, t.year,t.semester,t.section_number, t.number as CourseNumber
FROM instructor i
JOIN teaches t
ON i.instructor_id = t.instructor_id
JOIN enrolls e
ON e.section_number=t.section_number
WHERE department='Computer Science') a
GROUP BY a.instructor_id, a.section_number
;

SQLFiddle demo


text:
Q: Question about changing alpha value of a specified bitmap region in Android I'm having trouble setting an alpha value of a region path drawn on a bitmap, using SurfaceView.
I'm creating my bitmap and erase with a black color (and 255 as alpha)
bitmap = Bitmap.createBitmap(480, 724, Bitmap.Config.ARGB_8888);
bitmap.eraseColor(0xFF000000);
Canvas canvas = new Canvas(bitmap);

Next, in my onDraw method I draw a path on the bitmap with his own alpha, white color as stroke, black as fill color and 1 as alpha value :
Paint border = new Paint();
border.setStyle(Paint.Style.STROKE);
border.setStrokeWidth(1);
border.setStrokeCap(Paint.Cap.BUTT);
border.setStrokeJoin(Paint.Join.MITER);
border.setColor(Color.WHITE);

Paint inside = new Paint();
inside.setAntiAlias(false);
inside.setStyle(Paint.Style.FILL);
int alpha = 1<<24;
inside.setColor(alpha);

canvas.drawBitmap(bitmap,0,0, null);
canvas.drawPath(path, border);
canvas.drawPath(path, inside);

Finally, in my onTouchEvent method, i'm doing this :
int index = bitmap.getPixel((int)event.getX(), (int)event.getY());
int alpha = index >>> 24;
Log.v("TAG", " Region path alpha :"+ String.valueOf(alpha));

So, when I click inside the path region, I'm expecting to have 1 (0x01) as alpha value,
but instead I'm still have 255 (0xFF). What's wrong with that ? Thanks in advance.

A: I am trying this in usual Java, and getting no errors ! probably you should try debugging the value of index. Output the value of index and check, or just try
Color.alpha(index)

http://developer.android.com/reference/android/graphics/Color.html#alpha(int)


text:
Q: Django responding to different request from different browser with one python session I'm actually a php(CodeIgniter) web developer though I love python I just installed Bitnami's Django Stack which has Apache, MySQL, PostgreSQL and Python 2.7.9 with Django installed. During installation itself it generated a simple Django project.
Though it looked familiar to me I started adding some lines of codes to it but when I save it and refresh the page or even restart the browser I found that python instance is still running the old script. The script updates only when I restart start the Apache Server(I believe that's where the Python instance got terminated).
So, to clarify this problem with Python I created a simple view and URLed it to r'^test/'
from django.http import HttpResponse

i = 0

def test_view(request):
    global i
    i += 1
    return HttpResponse(str(i))

Then I found that even switching between different browser the i value keep on increasing i.e increasing value continues with the other browse.
So, can anyone tell me is this a default behavior of Django or is there something wrong with my Apache installation.

A: This is the default behavior, it may reset if you were running with gunicorn and killing workers after X requests or so, I don't remember. It's like this because the app continues to run after a request has been served.
Its been a while I've worked with PHP but I believe, a request comes in, php starts running a script which returns output and then that script terminates. Special global variables like $_SESSION aside, nothing can really cross requests.
Your Django app starts up and continues to run unless something tells it to reload (when running with ./manage.py runserver it will reload whenever it detects changes to the code, this is what you want during development).
If you are interested in per visitor data see session data. It would look something like:
request.session['i'] = request.session.get('i', 0) + 1

You can store data in there for the visitor and it will stick around until they lose their session.


text:
Q: OleDbDataReader reading blank rows from Excel spreadsheet Not sure what is going on as I've used the OleDbDataReader before to pull data off an Excel spreadsheet, but suddenly my C# batch job is not stopping at blank rows via the while(_reader.Reader()) loop.
Here is the C# code I'm using. I'm simply trying to pull all the record off an Excel spreadsheet and loop through the data right now. For some reason, though, the _reader.Read() function comes back true no matter what.
    private static OleDbDataReader _reader;
    static void Main(string[] args)
    {
        string connString = @"Provider=Microsoft.ACE.OLEDB.12.0;Data Source= \\prdhilfs03\l&i-sales&mkt\WORKAREA\Agencyservices\Shared\AIC\Analysts_and_Reporting\Realignments\2014\MassUpdateTesting\Validate\ZipCodeTest.xlsx;Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
        string queryString = "SELECT * FROM [Query1$]";

        Validation validation;
        ZipCodeTerritory record;

        bool flag = true;
        try
        {
            Stopwatch watch = new Stopwatch();
            watch.Start();

            using (OleDbConnection connection = new OleDbConnection(connString))
            {
                //Set connection objects to pull from spreadsheet
                OleDbCommand command = new OleDbCommand(queryString, connection);
                connection.Open();
                _reader = command.ExecuteReader();

                //Instantiate validation object with zip and channel values
                _allRecords = GetRecords();
                validation = new Validation();
                validation.SetLists(_allRecords);

                while (_reader.Read())
                {
                    record = new ZipCodeTerritory();
                    record.ChannelCode = _reader[0].ToString();
                    record.DrmTerrDesc = _reader[1].ToString();
                    record.IndDistrnId = _reader[2].ToString();
                    record.StateCode = _reader[3].ToString().Trim();
                    record.ZipCode = _reader[4].ToString().Trim();
                    record.EndDate = Convert.ToDateTime(_reader[5].ToString());
                    record.EffectiveDate = Convert.ToDateTime(_reader[6].ToString());
                    record.LastUpdateId = _reader[7].ToString();
                    record.ErrorCodes = _reader[8].ToString();
                    record.Status = _reader[9].ToString();
                    record.LastUpdateDate = DateTime.Now;

                    if (string.IsNullOrEmpty(record.LastUpdateId))
                    {
                        //Add to error list
                        _issues++;
                        _errorList.Add(record, "Missing last update Id");
                        continue;
                    }

                    if (_reader[10] != DBNull.Value)
                    {
                        record.Id = Convert.ToInt32(_reader[10]);
                    }

                    _errorMsg = validation.ValidateZipCode(record);

                    if (!string.IsNullOrWhiteSpace(_errorMsg))
                    {
                        _errorList.Add(record, _errorMsg);
                        continue;
                    }
                    else if (flag)
                    {
                        //Separate updates to appropriate list
                        SendToUpdates(record);
                    }

                    //Console.WriteLine(record.Id.ToString());
                }

I found this question on stack overflow and tried to follow the selected answer by changing the queryString to the following. However, this simply throws an OleDbException when the OleDbCommand runs its .ExecuteReader() method. (the Message property of the exception reads "No value given for one or more required parameters")
SELECT * FROM [Query1$] WHERE NOT ([ChannelCode] = '' and [DrmTerrDec] = '' and [StateCode] = '' and [ZipCode] = '' and [EndDate] = '' and [EffectiveDate] = '')
EDIT
Just added all the code inside the while loop.

A: This helped me
dataTable = dataTable.Rows.Cast<DataRow>().Where(row => !row.ItemArray.All(field => field is System.DBNull || string.Compare((field as string).Trim(), string.Empty) == 0)).CopyToDataTable();e

Taken from https://stackoverflow.com/a/9233678


text:
Q: What is the best facebook connect library for node.js? I've seen multiple tools for working with node.js and facebook connect.  However many of them seem incomplete, overly-complex (non abstract) or no longer updated/maintained.
I've found these three projects:
https://github.com/DracoBlue/node-facebook-client
https://github.com/dominiek/node-facebook
https://github.com/egorFiNE/facebook-connect
https://github.com/ciaranj/node-oauth
Here one of the authors even discusses why he once again rolled his own, due to shortcomings in other implementations:
http://groups.google.com/group/nodejs/browse_thread/thread/bb46cb08e51fdda6
Does anyone have any real experience actually authenticating users and storing their facebook id's in their database using node.js and facebook connect?
I have a feeling that the answer is pretty much no and I'll have to build on top of one of the above systems to make things much simpler, but I wanted to check first.
Edit: Note make sure you use the STABLE version of node.js

A: I find passport-facebook fairly simple and useful.
I also like that the core passport module has 80+ auth strategies.
(e.g. twitter, google, foursquare, github, digg, dropbox).
From the creator's github README:
// Set up the strategy
passport.use(new FacebookStrategy({
        clientID: FACEBOOK_APP_ID,
        clientSecret: FACEBOOK_APP_SECRET,
        callbackURL: "http://localhost:3000/auth/facebook/callback"
    },
    function(accessToken, refreshToken, profile, done) {
        User.findOrCreate({ facebookId: profile.id }, function (err, user) {
            return done(err, user);
        });
    }
));

// Use the authentication
app.get('/auth/facebook',
    passport.authenticate('facebook'),
    function(req, res){
        // The request will be redirected to Facebook for authentication, so
        // this function will not be called.
});

app.get('/auth/facebook/callback',
    passport.authenticate('facebook', { failureRedirect: '/login' }),
    function(req, res) {
        // Successful authentication, redirect home.
        res.redirect('/');
});

A: Did you not find ciaranj's connect-auth
const fbId = ""; #x
const fbSecret = ""; #y
const fbCallbackAddress= "http://localhost:4000/auth/facebook";
//var RedisStore = require('connect-redis');
var express= require('express');
var auth= require('connect-auth')
var app = express.createServer();
app.configure(function(){
  app.use(express.cookieDecoder());
  app.use(express.logger());
  //app.use(connect.session({ store: new RedisStore({ maxAge: 10080000 }) }));
  app.use(express.session());
  app.use(auth( [
    auth.Facebook({appId : fbId, appSecret: fbSecret, scope: "email", callback: fbCallbackAddress})
  ]) );
});

app.get('/logout', function(req, res, params) {
    req.logout();
    res.writeHead(303, { 'Location': "/" });
    res.end('');
});

app.get('/', function(req, res, params) {
    if( !req.isAuthenticated() ) {
        res.send('                                              \n\
                                                       \n\
            <title>connect Auth -- Not Authenticated</title> \n\
             \n\
                                                       \n\

                               \n\

Not authenticated
                     \n\

          \n\
                        \n\
                   \n\
                    Connect with Facebook                    \n\
                                                      \n\
                                                         \n\

');
    } else {
         res.send( JSON.stringify( req.getAuthDetails()) );
    }
});

// Method to handle a sign-in with a specified method type, and a url to go back to ...
app.get('/auth/facebook', function(req,res) {
  req.authenticate(['facebook'], function(error, authenticated) {
     if(authenticated ) {
        res.send("
Hello Facebook user:" + JSON.stringify( req.getAuthDetails() ) + ".
")
      }
      else {
        res.send("
Facebook authentication failed :(
")
      }
   });
});

app.listen(4000);

A: I have used Brian Noguchi's everyauth. It works w/ node.js v.0.4.x. You can find that here.
It has native support for mongodb using mongoose-auth plugin, again written by brian.


text:
Q: Difference between Scala pattern matching using variable binding and guard While pattern matching, what would be a scenario where variable binding would be necessary, where guarding would not suffice?
  "hello" match {
    case greeting @ ("yo" | "hello" | "hola") => println(s"greeting is $greeting")
    case _                                    => println("some other greeting")
  }

  "hello" match {
    case greeting if (greeting == "yo" || greeting == "hello" || greeting == "hola") => println(s"greeting is $greeting")
    case _ => println("some other greeting")
  }

Both of these approaches seem to be solving the same problem.

A: When matching on sealed traits, there's a huge difference
sealed trait Option[+A]
case class Some[A](get: A) extends Option[A]
case object None extends Option[Nothing]

val x: Option[String] = ???

With pattern matching it's nice and readable:
x match {
  case Some(string) => println("got " + string)
  case None => println("didn't get anything")
}

And also compiler will issue a warning if you miss a case:
x match {
  case Some(string) => println("got " + string)
} // gives you warning that match might fail on None

For guard version, you need to use casts, and there's no warnings for forgotten cases:
x match {
  case some if some.isInstanceOf[Some[_]] =>
    println("got " + some.asInstanceOf[Some[String]].get)
  case none if some == None =>
    println("didn't get anything")
}

Furthermore, guards get ugly quickly when want to check structure deeper than one level. Compare:
case Some(Some(string)) => println(string)

with
case s if s.isInstanceOf[Some[_]] && s.asInstanceOf[Some[_]].get.isInstanceOf[Some[_]] =>
  println(s.asInstanceOf[Some[_]].get.asInstanceOf[Some[String]].get)


text:
Q: spring boot : how to run a test class only on jenkins? We have a test class which I'd like to run only on Jenkins.
I think this can be achieved by checking the active spring profile (such as jenkins) or when the local machine name is XYZ.
The issue is, the loading of the application context fails when we try to run this on machines other than jenkins.
So I cannot check the profile or a parameter in the @Before method of the test class per se.
@RunWith(SpringRunner.class)
@SpringBootTest(classes = Config.class)
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
@ActiveProfiles("clusterMongo")
public class MongoTest {

    @Before
    public void setupClass() {

        // Ignore test if not running on white listed machines
        org.junit.Assume.assumeTrue(AuthTools.isJenkins());   // wonT work !!

    }

...
Any ideas how we can achieve this?
Can i maybe use Conditional beans?

A: Instead of doing it programmatic, you have a declarative option.
You can configure the surefire plugin to skip certain tests for a certain Maven profile:
<profile>
<id>skip-test</id>
  <build>
    <plugins>
    <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <configuration>
                    <excludes>
                        <exclude>**/MongoTest.java</exclude>
                    </excludes>
            </configuration>
    </plugin>
</plugins>
</build>
</profile>

On non-Jenkins run: mvn test -Pskip-test


text:
Q: Running NUnit tests on Travis for dot net core 2.0 fails - System.Reflection.ReflectionTypeLoadException I have just started to use Travis CI to build a project on git hub but am struggling to get NUnit tests to run successfully. I am experiencing a System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded..
My run-test.sh looks like:
nunit-console Code/Shared/ORMS.Shared.SharedKernel.UnitTests/bin/Release/netcoreapp2.0/ORMS.Shared.SharedKernel.UnitTests.dll

which should be the correct path to my test project. My .travis.yml looks like:
language: csharp
dist: trusty
sudo: required
mono: none
dotnet: 2.0.0
solution: OpenRMS.sln
branches:
  only:
    - master-net-core
before_install:
  - sudo apt-get install nunit-console
before_script:
  - chmod +x build.sh
  - chmod +x run-tests.sh
script:
  - ./build.sh
  - ./run-tests.sh

which should be loading the NUnit test runner which it appears to do from the output but there is another dependency load issue, which I cannot get to the bottom of.
Failed output:
$ ./run-tests.sh
NUnit-Console version 2.6.0.0
Copyright (C) 2002-2012 Charlie Poole.
Copyright (C) 2002-2004 James W. Newkirk, Michael C. Two, Alexei A. Vorontsov.
Copyright (C) 2000-2002 Philip Craig.
All Rights Reserved.
Runtime Environment -
   OS Version: Unix 4.4.0.93
  CLR Version: 4.0.30319.17020 ( Mono 4.0 ( 3.2.8 (Debian 3.2.8+dfsg-4ubuntu1.1) ) )
ProcessModel: Default    DomainUsage: Single
Execution Runtime: mono-4.0
Unhandled Exception:
System.Reflection.ReflectionTypeLoadException: The classes in the module cannot be loaded.
Server stack trace:
  at (wrapper managed-to-native) System.Reflection.Assembly:GetTypes (System.Reflection.Assembly,bool)
  at System.Reflection.Assembly.GetExportedTypes () [0x00000] in <filename unknown>:0
  at NUnit.Core.CoreExtensions.InstallAdhocExtensions (System.Reflection.Assembly assembly) [0x00000] in <filename unknown>:0
  at NUnit.Core.Builders.TestAssemblyBuilder.Load (System.String path) [0x00000] in <filename unknown>:0
  at NUnit.Core.Builders.TestAssemblyBuilder.Build (System.String assemblyName, Boolean autoSuites) [0x00000] in <filename unknown>:0
  at NUnit.Core.Builders.TestAssemblyBuilder.Build (System.String assemblyName, System.String testName, Boolean autoSuites) [0x00000] in <filename unknown>:0
  at NUnit.Core.TestSuiteBuilder.BuildSingleAssembly (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0
  at NUnit.Core.TestSuiteBuilder.Build (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0
  at NUnit.Core.SimpleTestRunner.Load (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0
  at NUnit.Core.ProxyTestRunner.Load (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0
  at NUnit.Core.ProxyTestRunner.Load (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0
  at NUnit.Core.RemoteTestRunner.Load (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0
  at (wrapper xdomain-dispatch) NUnit.Core.RemoteTestRunner:Load (object,byte[]&,byte[]&)
Exception rethrown at [0]:
  at (wrapper xdomain-invoke) NUnit.Core.RemoteTestRunner:Load (NUnit.Core.TestPackage)
  at NUnit.Util.TestDomain.Load (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0
The command "./run-tests.sh" exited with 156.

I think the key line is...
at NUnit.Util.TestDomain.Load (NUnit.Core.TestPackage package) [0x00000] in <filename unknown>:0

... so it looks as if it is loading an unknown file?
Any suggestions how to narrow this down. I am very new to Travis and normally use MSTest at work, but want to use NUnit as it has some features which I believe MSTest is yet to implement.

A: You are trying to run .NET Core unit tests from a mono-based version of the NUnit console runner, which does not support .NET Core dlls (see GitHub issue).
To run tests, use dotnet test on the test project or dotnet vstest on the publish output created by running dotnet publish on the test project.


text:
Q: How to center items of RecyclerView? I have vertical RecyclerView with some elements, the RecyclerView takex up all screen size. I want to find a way to set items(from RecyclerView) on the vertical center of screen. How can I make it?

I don't want use wrap_content for my RecyclerView and put it in the
other view(with gravity=center)


text:
Q: Qubo: Energy of of Non Overlapping Constraint in Taillard's Job Shop Problem Suppose we have a set of tasks $T = \{t_1, t_2, \dots, t_n\}$ with durations $\{d(t)| t \in T\}$, that need to be executed on some machine such that their execution times do not overlap.
We can represent the start time of task $t$ as $x(t),\, x \in \mathbb{N}$. We don't care about the execution order.

Regardless whether this problem is trivially solved by just exceuting each task after previous ends, I'd like to encode this constraint as minimizing a polynomial $p: X \times \Xi \to \mathbb{R}$ where $X = \{x(t) : t \in T\}$ and $\Xi$ denotes the set of any extra variables one might need to introduce.
Currently my approach is to use the classic double well in combination with slack variables:
For each pair of tasks $(t_i, t_j)$, we want that $x(t_i) + d(t_i) \leq x(t_j)$ or $x(t_j) + d(t_j) \leq x(t_i)$. Introducing the slack variable $\xi \geq 0$, this translates to
$$x(t_i) + d(t_i) + \xi - x(t_j) = 0 \quad \text{or} \quad x(t_j) + d(t_j) + \xi - x(t_i) = 0$$
Multiplying both options and squaring gives
$$
p_{ij}(x, \xi) = (x(t_i) + d(t_i) + \xi - x(t_j))^2(x(t_j) + d(t_j) + \xi - x(t_i))^2.
$$
It is easy to check that $p_{ij}$ is minimized iff tasks $t_i$ and $t_j$ do not overlap and that $0$ is the global minimum value. Thus summing over all combinations of tasks gives the desired constraint energy for all tasks.
My issue now is that each $p_{ij}$ is of degree 4. Having polynomials of degree $\geq$ 2 adds additional variables and constraints when we compile $p$ down to a QUBO.
Can we encode these non-overlapping constraints with polynomials of degree < 4?

A: For each pair $(t_i, t_j)$ of tasks with $i < j$, introduce a binary variable $z_{ij}\in \lbrace 0,1\rbrace$ which will be 0 if $t_i$ precedes $t_j$ and 1 if $t_j$ precedes $t_i$. The approach is to add a pair of constraints representing those two possibilities, such that for each value of $z_{ij}$ one constraint enforces a particular precedence and the other constraint is vacuous (automatically satisfied). Here you would use the following: $$ x(t_i) + d(t_i) - x(t_j) \le T z_{ij}$$ and $$x(t_j) + d(t_j) - x(t_i) \le T(1-z_{ij}).$$ This is what @RobPratt was getting at.


text:
Q: How to hide a div only on mobiles(large screen always has to be displayed) based on a content using Angularjs or css hide a div only on mobiles(large screen always has to be displayed) based on a content using Angularjs or css

A: Change the 2000px to 480px or other value, it depents of you

.box{
  width: 100px;
  height: 100px;
  background-color: blue;
  display: block;
}

@media screen and (max-width: 2000px){
  .box{
    display: none;
  }
  input:checked + .box{
    display: block;
  }
}
<input type="checkbox">
<div class="box">
</div>

A: Add class = "divclass" to your html then in your css file:
@media (max-width:480px) {
  .divclass{
     display: none;
  }
}


text:
Q: Текстовый(code) редактор в Android Доброго времени суток. Я занимаюсь разработкой веб-интерфейсов на ExtJs4 & php.
Периодически совершаю длительные поездки, в связи с чем приобрел себе планшет на ос Android 2.3; сейчас в поездках читаю.
Иногда в голову приходят мысли, которые в тот момент кажутся умными. Записываю их, если выходит, на бумагу.
Но вот возник вопрос: может кто подскажет приложение, по типу блокнота?) вообще было бы очень не плохо, если бы с подсветкой синтаксиса, но это уже второстепенное.
По маркету пробежался, на первый взгляд ничего такого не нашел.
Суть: нужно приложение для Android, по типу блокнота. Должен открывать файлы форматов .js, .php, .sql, .log как текстовые. Приятным дополнением было бы - подсветка синтаксиса.
Спасибо.
A: Скорее всего вам сюда
Из представленного, подходят, данный, еще вот и вот. Так же есть и платные версии.
Нашел вот такой viewer, в списке поддерживаемых языков, но скорее всего не умеет редактировать текст:

*

*ActionScript 3 (as3)

*Terminal scripts (bash, shell, sh)

*C/C++ (c, cc, cpp, h, hpp)

*C# (c-sharp, csharp, cs)

*CSS

*Delphi/Pascal

*Diff/patch files

*Groovy

*Java

*JavaFX (jfx)

*JavaScript (js, jscript)

*Perl (pl)

*PHP

*Text (txt)

*PowerShell (ps)

*Python (py)

*Ruby (rails, ror)

*Scala

*SQL

*Visual Basics (vb, vbnet)

*Verilog & System Verilog (v, sv)

*XML (xml, xaml, xslt, html, xhtml)


text:
Q: Replace text marker with column text I am having several columns with text. Furthermore, I have a column, which is called Replacement text. This columns contains strings that have markers in it, like [1], [2], etc.
I would like to replace the markers with the text that is in the marker`s row.

For example, Here you can find [5] becomes Here you can find b, because [5] is the markers column and in the row of the string b is the value for the marker.
I was thinking of creating a large if-else construct and substitute the text, which is extremely error-prone.
However, I kindly ask you if there is an easier solution?
I appreciate your input!

A: This answer is highly plagiarised from Thomas Inzina's first version of his answer, but a very simple way of performing the replacement would be:
Sub ReplaceText()
    Dim r As Long
    Dim c As Long
    With ActiveSheet
        For r = 3 To .Range("K" & .Rows.Count).End(xlUp).Row
            For c = 1 To 10
                .Cells(r, "K").Replace "[" & c & "]", .Cells(r, c).Value
            Next
        Next
    End With
End Sub

The above code will attempt to do a substitution using all ten columns.
As Thomas has noted, the following code will only do the substitution if a substitution is necessary and therefore could be an order of magnitude faster, so is undoubtedly a better solution:
Sub ReplaceText()
    Dim r As Long
    Dim c As Long
    With ActiveSheet
        For r = 3 To .Range("K" & .Rows.Count).End(xlUp).Row
            For c = 1 To 10
                If Instr(.Cells(r, "K").Value, "[" & c & "]") > 0 Then
                    .Cells(r, "K").Replace "[" & c & "]", .Cells(r, c).Value
                End If
            Next
        Next
    End With
End Sub

(Many thanks to Thomas for his effort in performing speed tests on the two different methods.)

A: ReplaceBrackets1: uses RegEx to extract the column number. It takes 15.03 Seconds to processed 100K records.

Sub ReplaceBrackets1()
    'http://analystcave.com/excel-regex-tutorial/
    Dim c As Range
    Dim Match As Object, Matches As Object, regex As Object
    Set regex = CreateObject("VBScript.RegExp")

    With regex
        .Global = True
        .Pattern = "\[(.*?)\]"
    End With

    For Each c In Range("K3", Range("K" & Rows.Count).End(xlUp))
        If regex.Test(c.Text) Then
            Set Matches = regex.Execute(c.Text)
            For Each Match In Matches
                c.Replace Match, c.EntireRow.Columns(CInt(Match.SubMatches(0)))
            Next Match

        End If
    Next
End Sub

ReplaceBrackets2: loades the data into arrays, uses RegEx to extract the column number and only writes to the worksheet 1 time. It takes 1.27 seconds to process 100K records.

Sub ReplaceBrackets2()
'http://analystcave.com/excel-regex-tutorial/
    Dim x As Long, column As Long
    Dim arData, values
    Dim Match As Object, Matches As Object, regex As Object
    Set regex = CreateObject("VBScript.RegExp")

    With regex
        .Global = True
        .Pattern = "\[(.*?)\]"
    End With

    values = Range("K3", Range("K" & Rows.Count).End(xlUp))
    arData = Range("A3", "L" & UBound(values, 1) + 2)

    For x = 1 To UBound(values, 1)
        If regex.Test(values(x, 1)) Then
            Set Matches = regex.Execute(values(x, 1))
            For Each Match In Matches
                column = Match.SubMatches(0)
                values(x, 1) = arData(x, column)
            Next Match
        End If
    Next

    Range("K3", Range("K" & Rows.Count).End(xlUp)) = values

End Sub

After converting ReplaceBrackets1 into a UDF (getReplacedText) I was amazed to find that it only took 2.53 seconds to fill the formula in for a 100K records.  I'm not sure way this would be faster that the original. But having that many formulas really slows down the spreadsheet.
getReplacedText: Uses a Static RegEx to parse the data.
Function getReplacedText(ReplacementText As String, Source As Range)
'http://analystcave.com/excel-regex-tutorial/
    Dim Match As Object, Matches As Object
    Static regex As Object
    If regex Is Nothing Then
        Set regex = CreateObject("VBScript.RegExp")

        With regex
            .Global = True
            .Pattern = "\[(.*?)\]"
        End With
    End If

    If regex.Test(ReplacementText) Then
        Set Matches = regex.Execute(ReplacementText)
        For Each Match In Matches
            ReplacementText = Replace(ReplacementText, Match, Source.Columns(CInt(Match.SubMatches(0))))
        Next Match

    End If

    getReplacedText = ReplacementText
End Function


text:
Q: rake db:setup shows rake aborted! KeyError: key not found: "URL_HOST" error i have rails app ubuntu 18.04. bundle install run successful but when i run rake db:setup it shows
rake aborted!
KeyError: key not found: "URL_HOST"
/var/www/myapp/code/config/environments/production.rb:71:in fetch'
/var/www/myapp/code/config/environments/production.rb:71:inblock in '
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/railtie.rb:210:in instance_eval'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/railtie.rb:210:inconfigure'
/var/www/myapp/code/config/environments/production.rb:3:in <top (required)>'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inrequire'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in block in require'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:240:inload_dependency'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in require'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:598:inblock (2 levels) in '
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:597:in each'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/engine.rb:597:inblock in '
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:30:in instance_exec'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:30:inrun'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:55:in block in run_initializers'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:44:ineach'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:44:in tsort_each_child'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/initializable.rb:54:inrun_initializers'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:352:in initialize!'
/var/www/myapp/code/config/environment.rb:5:in'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:in require'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inblock in require'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:240:in load_dependency'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/activesupport-4.2.11.1/lib/active_support/dependencies.rb:274:inrequire'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:328:in require_environment!'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/railties-4.2.11.1/lib/rails/application.rb:457:inblock in run_tasks_blocks'
/home/myappuser/.rvm/gems/ruby-2.5.0/gems/rake-13.0.0/exe/rake:27:in <top (required)>'
/home/myappuser/.rvm/gems/ruby-2.5.0/bin/ruby_executable_hooks:24:ineval'
/home/myappuser/.rvm/gems/ruby-2.5.0/bin/ruby_executable_hooks:24:in `'
Tasks: TOP => db:setup => db:schema:load_if_ruby => environment
(See full trace by running task with --trace)
Need help

A: Seems like some config settings for URL_HOST is missing.


text:
Q: Can't open the connection after upgrading to SQL Server 2014 Recently I have upgraded my SQL Server from 2012 to SQL Server 2014.
Now all my applications connected to this server can't instantiate the connection.
I debug the code and I get the following exception :

'Connection.ServerVersion' threw an exception of type
  System.InvalidOperationException

My connection string like this :
 <add name="sql_r"
      connectionString="Data Source=172.XX.XX.X;Initial Catalog=Attendance;User ID=ll_web;password=XXXXXXXXXXX;"
      providerName="System.Data.SqlClient"/>

A: Apart from the code, there are a couple of possible things which could make your SQL Server Connection failed from the setup itself. I will try to list 3 which I think might be common:

*

*Check your SQL service, whether it is running. Check your service by running "service.msc" from your Run windows. Check for service name SQL Server (YourInstanceName) (the default for YourInstanceName is MSSQLSERVER). Check if it is running. You may also want to check if SQL Server Browser is running. Run them.

*Check you Firewall, check if your newly installed SQL Server paths are among the allowed paths. You could get the paths by [right-clicking - properties -> path to executable] on the service names of your SQL Server in point 1. Include them in your Firewall allowed paths.

*Check your TCP Port, Open the SQL Server 2014 Configuration Manager, in the SQL Server Network Connection -> Protocols for [YourInstanceName] -> TCP/IP. Do right-click -> properties -> IP Addresses Tab, check the TCP Port for you IP Addresses. Typically all is set to 1433, including the IPAll. If this is not the case, set them.


text:
Q: What spacetime symmetry corresponds to conservation of total angular momentum $|\vec{J}|$ (not angular momentum in one particular direction)? It is well known that the symmetry of spacetime with respect to rotating about some axis results in angular momentum along that axis being conserved, by Noether's theorem. E.g. rotational symmetry with respect to the $x$ axis implies $J_x$ is conserved.
Is there some symmetry that corresponds with total angular momentum $|\vec{J}|$ (or $J^2$ if you like) being a conserved quantity?

A: If the Lagrangian of a system is invariant under rotations with respect to an arbitrary  direction $\mathbf{n}$ in space, the corresponding conserved quantity is the component $\mathbf{n} \cdot \mathbf{J}$ of the total angular momentum in this direction. If this invariance holds for any direction $\mathbf{n}$ in space, the total angular momentum  vector $\mathbf{J}$ of the system is conserved and consequently also $\mathbf{J}^2$.
The relevant symmetry group is $\rm SO(3)$ (or $\rm SU(2)$ for systems with half-integer spin).

A: *

*The symmetry Lie group for angular momentum is ${\rm Spin}(3)$.

*If $\delta_{J_x}, \delta_{J_y}, \delta_{J_z}$ are the infinitesimal symmetries of the action $S$, generated by the angular momentum $J_x$, $J_y$, $J_z$, for rotations around the $x$, $y$, and $z$ axis, respectively; then $$2|\vec{J}|\delta_{|\vec{J}|}~=~
\delta_{J^2}~=~2J_x\delta_{J_x}+2J_y \delta_{J_y}+2J_z \delta_{J_z}\tag{1}$$ is the infinitesimal symmetry generated by the angular momentum square $J^2$. Eq. (1) follows e.g. from my Phys.SE answer here.


text:
Q: How can I boot an Ubuntu DVD, and use the DVD drive while the system is running? I would like to boot the Ubuntu system from the installation DVD, and then make the system, after it started, run no longer from the DVD. It should continue to run using a hard disk or a ram drive, and no longer require access to the boot medium, or the DVD drive.
The purpose is to allow the use of the DVD drive for other tasks in preparation for the Ubuntu installation.
The idea sounds somewhat far-fetched, but I am fairly optimistic that it is possible.
Is there a standard way to do it?
Or are there reasons why it could be impossible?
Possible approaches are:

*

*Copying the DVD to a ram drive, and somehow change the directories in / to symbolic links.

*Find a way to overlay multiple file systems, in a way that the DVD file system continues to exist, but is never accessed again, followed by somehow making the DVD drive no longer depend on the file system.

*Just remount the root file system somehow?

*some kind of 'bind' mount?

A: The standard way to run two or more operating systems at the same time is in a virtual machine application. The operating system that runs on the physical machine's bare metal hardware is the host OS. A guest OS is an operating system that runs inside the virtual machine application.
What you're thinking about in your question is that different virtual machine applications have different feature sets that target different scenarios for creating guest OSs.
I don't think you're going to be happy with this explanation unless I illustrate the reverse case where for security reasons applications can run natively inside virtual machines that are elevated to the status of core components of the operating system as is done in Qubes OS. Virtualization is performed by Xen, and user environments can be based on Fedora, Debian, Whonix, and Microsoft Windows, among other operating systems.


text:
Q: Sum of the Time elapsed during the transition from OFF to ON, group by the day I want to know  the time elapsed when state changes from OFF to ON and create the sum of the these elapsed for each day.
Final outcome should look like(example dataframe):
[Date             Elapsed_Time (min)
2021 05 01          200
2021 05 02          340
2021 05 03           0][1]

For the missing dates it can be given a value of zero.
the data for state changes and the time when it is updated:
state   last _updated
on      4/30/2021 16:04
on      4/30/2021 16:05
off     5/1/2021 1:00
off     5/1/2021 2:57
off     5/1/2021 2:58
off     5/1/2021 3:09
off     5/1/2021 3:10
off     5/1/2021 3:14
off     5/1/2021 3:15
off     5/1/2021 8:25
off     5/1/2021 8:26
off     5/1/2021 9:02
off     5/1/2021 9:03
on      5/1/2021 13:00
on      5/1/2021 14:00
on      5/1/2021 14:01
on      5/1/2021 14:08
on      5/1/2021 14:11

A: To get you starting you can do something like this:
(I created a shorter table with data...)

DROP TABLE if exists states;
CREATE TABLE states (
   state CHAR(4),
   last_updated datetime);

INSERT INTO states VALUES
   ('on', '2021-04-30 16:04'),
   ('on', '2021-04-30 16:05'),
   ('off', '2021-05-01 01:00'),
   ('off', '2021-05-01 02:57'),
   ('on', '2021-05-01 13:00');

SELECT
   state,
   CASE WHEN state <> lag(state) over (order by last_updated Desc)
        THEN TIMEDIFF(lag(last_updated) over (order by last_updated desc),last_updated)
        ELSE null END as X
FROM states
order by last_updated;

output:
+ ---------- + -------- +
| state      | X        |
+ ---------- + -------- +
| on         |          |
| on         | 08:55:00 |
| off        |          |
| off        | 10:03:00 |
| on         |          |
+ ---------- + -------- +


text:
Q: The .properties file is getting overridden. How to overcome from that? The config.properties file in java is getting overridden after every execution. What I want is, The previous data should also be saved with the new updated one.
Below is the code which i have used to store the value to config.properties file. And my config.properties file already contain some data.
try (OutputStream output = new FileOutputStream("path\\to\\config.properties")) {

            Properties prop = new Properties();

            // set the properties value
            prop.setProperty("IFCode", "34253");

            // save properties to project root folder
            prop.store(output, null);

            System.out.println(prop);

        } catch (IOException io) {
            io.printStackTrace();
        }

And here is my config.properties file data which is already present there:-
#Tue Jul 23 02:38:34 EDT 2019
File=987
Read=098

Now, when I run the above code these already available data is getting omitted and the new one is getting written like this:-
#Tue Jul 23 02:38:34 EDT 2019
IFCode=34253

What I want basically is:-
#Tue Jul 23 02:38:34 EDT 2019
File=987
Read=098
IFCode=34253

How to overcome this problem using java?

A: Try to add the boolean append parameter for your FileOutputStream:
OutputStream output = new FileOutputStream("path\\to\\config.properties", true)

FileOutputStream(File file, boolean append)
  Creates a file output stream to write to the file represented by the specified File object. Check for reference:
  https://docs.oracle.com/javase/7/docs/api/java/io/FileOutputStream.html

A: Here is the solution:
  try (OutputStream output = new FileOutputStream("path\\to\\config.properties",true)) {

    Properties prop = new Properties();

    // set the properties value
    prop.setProperty("IFCode", "34253");

    // save properties to project root folder
    prop.store(output, null);

    System.out.println(prop);

}  catch (FileNotFoundException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}


text:
Q: How to decrease total number of the database hits in C# entity framework? I've implemented a data-driven localization in my own CMS using the entity framework.
Currently, to read a localization value from the database, I create a new EF context, connect to the database and read the value, so the total number of the database hits is a lot.
How can I decrease the total number of hits to the database?

A: You can achieve it with Unit of work pattern.
Simple implementation of that you can check int this article of Radu Pascal: https://www.codeproject.com/Articles/243914/Entity-Framework-context-per-request


text:
Q: Entity Framework and serialized/remote data access I'm new to entity framework, so forgive me if I'm off-base with my question.   In our environment, our external web servers are located in the DMZ and direct access from the web servers in the DMZ to our SQL server inside the internal firewall is prohibited.   In the past we had created a custom data portal so that sql commands executed from code on the web server would be serialized and remoted to a middleware service inside the firewall, which would then connect to the SQL server execute the command and return a dataset to the caller on web server.
We'd like to look into using Entity Framework.  Are there options within Entity Framework to work within our policy?

A: AFAIK it's required to have a direct connection to database via special Entity Framework ADO.NET providers to use entity framework. So looks like it's impossible in your case.

A: You can replace your middleware service inside firewall with RIA Service. RIA Service on the top of Entity Framework will make your middleware service and you will be able to access it and control it easily from outside world.


text:
Q: Grouping using row number function I have been using the row_number() function to only select the observations that I need.
In my scenario, whenever there is two different name for a particular <id, entity_id, period, element>, the National one should be left-out. In case there is only one, take the only one.
+----+-----------+--------+---------------+---------------------------+
| id | entity_id | period |    element    |           name            |
+----+-----------+--------+---------------+---------------------------+
| 12 | ABC123    |   2021 | Overall value | National Compatible - XYZ |
| 12 | ABC123    |   2021 | Overall value | Overall Estimation        |
+----+-----------+--------+---------------+---------------------------+

With cases like above, the following did the trick:
SELECT *
FROM   (SELECT *,
               Row_number()
                 OVER (
                   partition BY id, entity_id, period, element
                   ORDER BY NAME DESC) AS rn
        FROM   mydata) table
WHERE  table.rn = 1

Problem is that now there are other cases like the following:
+----+-----------+--------+---------------+---------------------------+
| id | entity_id | period |    element    |           name            |
+----+-----------+--------+---------------+---------------------------+
| 12 | ABC123    |   2021 | Overall value | National Based - ZYX      |
| 12 | ABC123    |   2021 | Overall value | Base Estimation           |
+----+-----------+--------+---------------+---------------------------+

And with the current SQL this would not work as I would have to change the order by from descending to ascending.
Is there any possibility to de-prioritize the "National..." record and take the other one in case there are multiple ones?
I am running the query on Hive/Impala.

A: If you add another derived-table layer (or use a CTE) then you can add a CASE WHEN to check for "name" starting with 'National' and give it a simple integer "tag" value you can use to de-prioritize those rows.
...like so:
WITH q AS (
    SELECT
        "id",
        "entity_id",
        "period",
        "element",
        "name",
        CASE WHEN "name" LIKE 'National%' THEN 1 ELSE 2 END AS "tag"
    FROM
        mydata
),
filtered AS (
    SELECT
        *,
        ROW_NUMBER() OVER (
            PARTITION BY
                "id", "entity_id", "period", "element"
            ORDER BY
                "tag" DESC,
                "name" DESC
        ) AS rn
    FROM
        q
)
SELECT
    *
FROM
    filtered
WHERE
    rn = 1


text:
Q: why npm sass compile not running?
I am also doing editing in my code , but sass-compiler not showing any error(red lines ) or any compile successfull line(green lines ). What is my mistake ?

A: As we are using sass compiler , which is related to css opeartions , and i am doing changes in my html file , But when I edit my any sass file then it started to work ,that's it .


text:
Q: Clear user defaults of my OS X application after uninstall I am developing an OS X application on swift, and i have requirement to delete my application's user default preferences after uninstalling it. As i want to clear user preferences on a fresh install of the application. Unlike in iOS, uninstalling the application doesn't clear my application's user defaults in OS X. Currently i know how to delete user defaults programatically but i do not know where to put the below code :-
let domain = Bundle.main.bundleIdentifier!
UserDefaults.standard.removePersistentDomain(forName: domain)
UserDefaults.standard.synchronize()

Please help on finding the correct trigger point for the above code.
Edit 1 : By Uninstalling the application, i mean deleting the application (moving to Bin)


text:
Q: select and input in one Is there any plugin or way to make select with search option, and if there is no option like entered in search that entered value would be like input..
Have form with lots of manufacturers and models to select.. but also there is lots of new ones and want to make it in one place.. so that wouldn't need to go another page ant save the model or manufacturer..
for now thinking about making it with chosen plugin (https://harvesthq.github.io/chosen/) like tag input.. but still more want to make like select with input in  one..
also must work with select/input with names of array like manufacturer_id[] etc..

A: Do you know Select2 ?
https://select2.github.io/examples.html
Maybe you can do something with it.


text:
Q: Compile & Fill Jasper Report - XML datasource I am hoping someone can tell me why the code below is creating an empty pdf file every time?
I am trying to compile, fill and run the xmldatasource sample project that ships with JasperReports 4.0.2. Although I am attempting to do it Programatically as I want to use a similar (non ant-based) compilation method in my own software. The same project that comes with Jasper uses ant scripts to create the report and it works. So I know there is no issue with the JRXML files. However, I cannot seem to fill the report with data correctly.
When I debugged the Jasper engine source to see if my XML source document is being loaded correctly I see that the PARAMETER_XML_DOCUMENT had the value

[#document: null]

Do you think this would mean that the XML source file is not being read correctly?
The code compiles and runs without errors and all of the relevant files are generated (.jasper, .jrprint and .pdf) but for some reason the rendered PDF document appears to have only one blank page every time.
Any help is greatly appreciated...
public static void main(String[] args) {
        Map map = new RenderReportBean().execute("northwind", "OrdersReport");

    }

    @SuppressWarnings({ "rawtypes", "unchecked" })
    public Map execute(String sourceFileId, String templateId, Integer[] formats) {
        Map params = new HashMap();
        Document document;
        Map<Integer, Boolean> renderedSuccessList = new HashMap<Integer, Boolean>();
        try {

            document = JRXmlUtils.parse(JRLoader.getLocationInputStream(sourceFileId + ".xml"));

            params.put(JRXPathQueryExecuterFactory.PARAMETER_XML_DATA_DOCUMENT, document);
            params.put(JRXPathQueryExecuterFactory.XML_DATE_PATTERN, "yyyy-MM-dd");
            params.put(JRXPathQueryExecuterFactory.XML_NUMBER_PATTERN, "#,##0.##");
            params.put(JRXPathQueryExecuterFactory.XML_LOCALE, Locale.ENGLISH);
            params.put(JRParameter.REPORT_LOCALE, Locale.US);

            JasperCompileManager.compileReportToFile(templateId + ".jrxml", templateId + ".jasper");

            JasperFillManager.fillReportToFile(templateId + ".jasper", params);

            JasperExportManager.exportReportToPdfFile(templateId + ".jrprint", sourceFileId + ".pdf");

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

OrdersReport.jrxml
<?xml version="1.0" encoding="UTF-8"?>

<jasperReport
        xmlns="http://jasperreports.sourceforge.net/jasperreports"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
        name="OrdersReport" pageWidth="500" pageHeight="842" columnWidth="500" leftMargin="0" rightMargin="0" topMargin="0" bottomMargin="0">
    <style name="Sans_Normal" isDefault="true" fontName="DejaVu Sans" fontSize="8" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Bold" isDefault="false" fontName="DejaVu Sans" fontSize="8" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Italic" isDefault="false" fontName="DejaVu Sans" fontSize="8" isBold="false" isItalic="true" isUnderline="false" isStrikeThrough="false"/>
    <parameter name="CustomerID" class="java.lang.String"/>
    <queryString language="xPath"><![CDATA[/Northwind/Orders[CustomerID='$P{CustomerID}']]]></queryString>
    <field name="Id" class="java.lang.String">
        <fieldDescription><![CDATA[OrderID]]></fieldDescription>
    </field>
    <field name="OrderDate" class="java.util.Date">
        <fieldDescription><![CDATA[OrderDate]]></fieldDescription>
    </field>
    <field name="ShipCity" class="java.lang.String">
        <fieldDescription><![CDATA[ShipCity]]></fieldDescription>
    </field>
    <field name="Freight" class="java.lang.Float">
        <fieldDescription><![CDATA[Freight]]></fieldDescription>
    </field>
    <variable name="TotalFreight" class="java.lang.Float" calculation="Sum">
        <variableExpression><![CDATA[$F{Freight}]]></variableExpression>
    </variable>
    <pageHeader>
        <band height="14">
            <frame>
                <reportElement x="0" y="2" width="356" height="10" forecolor="#ccffff" backcolor="#ccffff" mode="Opaque"/>
                <staticText>
                    <reportElement mode="Opaque" x="0" y="0" width="48" height="10" backcolor="#ccffff" style="Sans_Bold"/>
                    <textElement textAlignment="Right"/>
                    <text><![CDATA[ID]]></text>
                </staticText>
                <staticText>
                    <reportElement mode="Opaque" x="54" y="0" width="87" height="10" backcolor="#ccffff" style="Sans_Bold"/>
                    <textElement textAlignment="Center"/>
                    <text><![CDATA[Order Date]]></text>
                </staticText>
                <staticText>
                    <reportElement mode="Opaque" x="146" y="0" width="108" height="10" backcolor="#ccffff" style="Sans_Bold"/>
                    <text><![CDATA[Ship City]]></text>
                </staticText>
                <staticText>
                    <reportElement mode="Opaque" x="259" y="0" width="92" height="10" backcolor="#ccffff" style="Sans_Bold"/>
                    <textElement textAlignment="Right"/>
                    <text><![CDATA[Freight]]></text>
                </staticText>
            </frame>
        </band>
    </pageHeader>
    <detail>
        <band height="14">
            <textField>
                <reportElement x="0" y="2" width="51" height="10"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{Id}]]></textFieldExpression>
            </textField>
            <textField isStretchWithOverflow="true" pattern="yyyy, MMM dd">
                <reportElement positionType="Float" x="54" y="2" width="87" height="10"/>
                <textElement textAlignment="Center"/>
                <textFieldExpression class="java.util.Date"><![CDATA[$F{OrderDate}]]></textFieldExpression>
            </textField>
            <textField isStretchWithOverflow="true">
                <reportElement positionType="Float" x="146" y="2" width="108" height="10"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{ShipCity}]]></textFieldExpression>
            </textField>
            <textField isStretchWithOverflow="true" pattern="¤ #,##0.00">
                <reportElement positionType="Float" x="259" y="2" width="92" height="10"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression class="java.lang.Float"><![CDATA[$F{Freight}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <summary>
        <band height="14">
            <frame>
                <reportElement x="0" y="2" width="356" height="10" forecolor="#33cccc" backcolor="#33cccc" mode="Opaque"/>
                <staticText>
                    <reportElement mode="Opaque" x="160" y="0" width="67" height="10" backcolor="#33cccc" style="Sans_Bold"/>
                    <textElement textAlignment="Right"/>
                    <text><![CDATA[Total :]]></text>
                </staticText>
                <textField>
                    <reportElement mode="Opaque" x="259" y="0" width="92" height="10" backcolor="#33cccc" style="Sans_Bold"/>
                    <textElement textAlignment="Right"/>
                    <textFieldExpression class="java.lang.Float"><![CDATA[$V{TotalFreight}]]></textFieldExpression>
                </textField>
                <textField>
                    <reportElement mode="Opaque" x="227" y="0" width="27" height="10" backcolor="#33cccc" style="Sans_Bold"/>
                    <textElement textAlignment="Right"/>
                    <textFieldExpression class="java.lang.Integer"><![CDATA[$V{REPORT_COUNT}]]></textFieldExpression>
                </textField>
            </frame>
        </band>
    </summary>
</jasperReport>

CustomersReport.jrxml
<?xml version="1.0" encoding="UTF-8"?>

<jasperReport
        xmlns="http://jasperreports.sourceforge.net/jasperreports"
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
        xsi:schemaLocation="http://jasperreports.sourceforge.net/jasperreports http://jasperreports.sourceforge.net/xsd/jasperreport.xsd"
        name="CustomersReport" pageWidth="595" pageHeight="842" columnWidth="515" leftMargin="40" rightMargin="40" topMargin="50" bottomMargin="50">
    <style name="Sans_Normal" isDefault="true" fontName="DejaVu Sans" fontSize="12" isBold="false" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Bold" isDefault="false" fontName="DejaVu Sans" fontSize="12" isBold="true" isItalic="false" isUnderline="false" isStrikeThrough="false"/>
    <style name="Sans_Italic" isDefault="false" fontName="DejaVu Sans" fontSize="12" isBold="false" isItalic="true" isUnderline="false" isStrikeThrough="false"/>
    <queryString language="xPath"><![CDATA[/Northwind/Customers]]></queryString>
    <field name="CustomerID" class="java.lang.String">
        <fieldDescription><![CDATA[CustomerID]]></fieldDescription>
    </field>
    <field name="CompanyName" class="java.lang.String">
        <fieldDescription><![CDATA[CompanyName]]></fieldDescription>
    </field>
    <title>
        <band height="50">
            <line>
                <reportElement x="0" y="0" width="515" height="1"/>
                <graphicElement/>
            </line>
            <staticText>
                <reportElement x="0" y="10" width="515" height="30" style="Sans_Normal"/>
                <textElement textAlignment="Center">
                    <font size="22"/>
                </textElement>
                <text><![CDATA[Customer Orders Report]]></text>
            </staticText>
        </band>
    </title>
    <pageHeader>
        <band height="21">
            <staticText>
                <reportElement mode="Opaque" x="0" y="5" width="515" height="15" forecolor="#ffffff" backcolor="#333333" style="Sans_Bold"/>
                <text><![CDATA[Customer Order List]]></text>
            </staticText>
        </band>
    </pageHeader>
    <detail>
        <band height="50">
            <textField>
                <reportElement x="5" y="5" width="100" height="15" isPrintWhenDetailOverflows="true" style="Sans_Bold"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{CustomerID}]]></textFieldExpression>
            </textField>
            <staticText>
                <reportElement isPrintRepeatedValues="false" x="404" y="5" width="100" height="15" isPrintWhenDetailOverflows="true" style="Sans_Bold"/>
                <text><![CDATA[(continued)]]></text>
            </staticText>
            <line>
                <reportElement x="0" y="20" width="515" height="1" isPrintWhenDetailOverflows="true"/>
                <graphicElement/>
            </line>
            <subreport>
                <reportElement isPrintRepeatedValues="false" x="5" y="25" width="507" height="20" isRemoveLineWhenBlank="true" backcolor="#ffcc99"/>
                <subreportParameter name="XML_DATA_DOCUMENT">
                    <subreportParameterExpression>$P{XML_DATA_DOCUMENT}</subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="XML_DATE_PATTERN">
                    <subreportParameterExpression>$P{XML_DATE_PATTERN}</subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="XML_NUMBER_PATTERN">
                    <subreportParameterExpression>$P{XML_NUMBER_PATTERN}</subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="XML_LOCALE">
                    <subreportParameterExpression>$P{XML_LOCALE}</subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="XML_TIME_ZONE">
                    <subreportParameterExpression>$P{XML_TIME_ZONE}</subreportParameterExpression>
                </subreportParameter>
                <subreportParameter name="CustomerID">
                    <subreportParameterExpression>$F{CustomerID}</subreportParameterExpression>
                </subreportParameter>
                <subreportExpression class="java.lang.String"><![CDATA["OrdersReport.jasper"]]></subreportExpression>
            </subreport>
            <textField>
                <reportElement x="109" y="5" width="291" height="15" isPrintWhenDetailOverflows="true" style="Sans_Bold"/>
                <textFieldExpression class="java.lang.String"><![CDATA[$F{CompanyName}]]></textFieldExpression>
            </textField>
        </band>
    </detail>
    <pageFooter>
        <band height="40">
            <line>
                <reportElement x="0" y="10" width="515" height="1"/>
                <graphicElement/>
            </line>
            <textField>
                <reportElement x="200" y="20" width="80" height="15"/>
                <textElement textAlignment="Right"/>
                <textFieldExpression class="java.lang.String"><![CDATA["Page " + String.valueOf($V{PAGE_NUMBER}) + " of"]]></textFieldExpression>
            </textField>
            <textField evaluationTime="Report">
                <reportElement x="280" y="20" width="75" height="15"/>
                <textElement/>
                <textFieldExpression class="java.lang.String"><![CDATA[" " + String.valueOf($V{PAGE_NUMBER})]]></textFieldExpression>
            </textField>
        </band>
    </pageFooter>
</jasperReport>

A: Ok so I found out the issue and it's a bit of an odd one really as the other means of compiling the templates do not call for the same approach.
The example above uses nested reports and for some reason the runtime compile option requires you to compile both templates individually instead of just compiling the Super report and Jasper picking up the sub-report bu default - as seems to be the case when compiling from ant scripts.
So to make the above code work the line:
JasperCompileManager.compileReportToFile(templateId + ".jrxml", templateId + ".jasper");

needs to be included for each template (super and sub) that are required for the report.

A: The problem is here:
document = JRXmlUtils.parse(JRLoader.getLocationInputStream(sourceFileId + ".xml"));
The API says:
getLocationInputStream
public static java.io.InputStream getLocationInputStream(java.lang.String location)
                                                  throws JRException
Tries to open an input stream for a location.

The method tries to interpret the location as a file name, a resource name or an URL. If any of these succeed, an input stream is created and returned.

Parameters:
    location - the location
Returns:
    an input stream if the location is an existing file name, a resource name on the classpath or an URL or null otherwise.
Throws:
    JRException

If the method is not able to return an input stream, it will return null. Basically the string you are passing as parameter is incorrect. Try passing the absolute path.


text:
Q: Flexslider change code I use WordPress. Theme name Wp-tuts. My site: http://www.memuralimi.com.
I use the slider; Flexslider. When I click with the mouse, the images are changing.
I want that when the mouse comes over the thumbnail, the images change.
flexslider-home.js
jQuery(function($){
    $(window).load(function() {
        $('.featured-slider-preloader').hide();
        $('#featured-slider').flexslider({
            slideshow : true,
            controlsContainer: "#featured-slider-wrap",
            animation : 'fade',
            pauseOnHover: true,
            animationSpeed : 400,
            smoothHeight : true,
            directionNav: false,
            prevText : '',
            nextText : '',
            controlNav : "thumbnails"
        });
    });
});

Content-featured-slider.php
<?php
$wpex_featured_cat = get_theme_mod( 'wpex_homepage_slider_cat' );
// Show homepage featured slider if theme panel category isn't blank
if( $wpex_featured_cat !== '' && $wpex_featured_cat !== '-1' ) {

    // Get posts based on featured category
    $wpex_query = new WP_Query( array(
        'post_type'         =>'post',
        'posts_per_page'    => get_theme_mod( 'wpex_homepage_slider_count', '6' ),
        'no_found_rows'     => true,
        'tax_query'         => array(
            'relation'      => 'AND',
            array(
                'taxonomy'  => 'category',
                'field'     => 'ID',
                'terms'     => $wpex_featured_cat
                )
            ),
        'meta_query'    => array(
            array(
                'key'   => '_thumbnail_id',
            )
        )
    ) );

    if( $wpex_query->have_posts() ) {

        // Get Scripts
        wp_enqueue_script( 'flexslider', WPEX_JS_DIR_URI .'/flexslider.js', array( 'jquery' ), '', true );
        wp_enqueue_script( 'wpex-flexslider-home', WPEX_JS_DIR_URI .'/flexslider-home.js', array( 'flexslider' ), '', true); ?>

                        <?php
                        // Loop through each post
                        while( $wpex_query->have_posts() ) : $wpex_query->the_post(); ?>
                            <li class="featured-slider-slide" data-thumb="<?php echo aq_resize( wp_get_attachment_url( get_post_thumbnail_id() ), 490, 340, true ); ?>">

                                    <a href="<?php the_permalink(); ?>" title="<?php echo esc_attr( the_title_attribute( 'echo=0' ) ); ?>">
                                        <img src="<?php echo aq_resize( wp_get_attachment_url( get_post_thumbnail_id() ), '400', '225', true ); ?>" alt="<?php echo the_title(); ?>" />

                        <?php endwhile; ?>

    <?php } ?>
    <?php wp_reset_postdata(); ?>
<?php } ?>


text:
Q: SQL MS Access Conditional Update Query Referencing Other Tables I am getting my feet wet in SQL, particularly because of the problem that I am working on now, I know how I would accomplish the task using a referential Countif formula in Excel but because I am dealing with close to 1 million records, Excel keeps bombing out on me and SQL seemed like a more efficient means to accomplish the task.
Background:
Basically I have a 'summary' table like this:
 ID_summary(ID_num, exist_2009, exist_2010, exist_2011, exist_2012)

I then have 4 tables each corresponding to 2009, 2010, 2011 and 2012 with just two columns in each table ID_num and date.
2009(ID_num,date)

The ID_summary table has a comprehensive list of all the unique IDs that exists in the four year tables.  I created this list through unions of the four year table.
The problem:
I want to write an update query(?) to populate the ID_summary table with "TRUE" or a "1" for each "exists_20XX" column, for each record, if the ID number appears in the corresponding year tables.
For example, if ID 002 only appears in 2009 and 2012 then the row for ID 002 in the summary table should look like this
ID_summary(ID_num, exist_2009, exist_2010, exist_2011, exist_2012)
ID_002,TRUE,FALSE,FALSE,TRUE

I've done similar basic queries to do some data cleaning and have gotten successful results but it was always just referencing other fields in the same table to determine if a field should get re coded.
I am using MS Access 2010.
Any help is greatly appreciated!

A: OK, I checked here.
http://msdn.microsoft.com/en-us/library/office/bb221186%28v=office.12%29.aspx
Seems the syntax might be slightly different
for MS Access than it is for SQL Server.
Try these two in this order:
update ID_summary
set exist_2009 = 0 -- false

update
ID_summary ids
left join table_2009 t on ids.ID_num = t.ID_num
set
ids.exist_2009 = 1 -- true
where
(t.ID_Num is not null)

If it was SQL Server, one would need to
use a slightly different syntax.
But we're talking MS Access here.
update ids
set
ids.exist_2009 = 0 -- false
from
ID_summary ids

update ids
set
ids.exist_2009 = 1 -- true
from
ID_summary ids
left join table_2009 t
on ids.ID_num = t.ID_num
where
(t.ID_Num is not null)


text:
Q: Empty range between strings representing numbers Here are two range values.
('1'..'10').to_a   => ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10"]

but,
('2'..'10').to_a  => []

Why does the second one return an empty array in ruby 1.8.7?

A: The issue is that Ruby 1.8 is trying to determine whether ('2'..'10') is a valid range as part of its analysis of the code, and deciding that it's invalid. '2' sorts after '10' making the range values backwards.
This is a common problem when people try to sort string values, and they'll encounter it again and again until they learn that trick never works.
Using 1.8.7:
('2'..'10').to_a
=> []
('02'..'10').to_a
=> ["02", "03", "04", "05", "06", "07", "08", "09", "10"]

Or:
(2..10).map(&:to_s)
=> ["2", "3", "4", "5", "6", "7", "8", "9", "10"]

I'd probably use the last method if I needed compatibility with 1.8 and 1.9+ Rubies.

A: irb(main):001:0> '2' > '10'
=> true
irb(main):002:0> '1'>'10'
=> false

Because of the string comparison algorithm, range cannot be created with lower bound bigger than the upper bound.
ACTUALLY it works in 1.9.3. Strange.

A: That's not what I'm getting:
irb(main):001:0> ('2'..'10').to_a
=> ["2", "3", "4", "5", "6", "7", "8", "9", "10"]

Unrelated to the question, though: the correct way is:
(2..10).to_a

(I am using Ruby 1.9.3)

A: in ruby2.0.0-p-0 this is what I am getting :
["2", "3", "4", "5", "6", "7", "8", "9", "10"]


text:
Q: using histogram distances for clustering Business context: for our retail client there are a few crucial products. All of them have 3 phases (introduction, stable phase and end of life). After correcting for seasonality and discounts (as much as possible) we used the weekly sales % change and tried to fit a distribution to it. Not surprisingly non gaussian but it even escaped Poisson. The end goal is to ensure that other products (that the client is having trouble in categorizing) can be modeled using these as proxies.
Statistical solutions (so far): I used histograms for each phase and calculated the histogram distances (used EMD) and generated a matrix which indicates the distance of each phase's distribution from the other.
ex : matrix(0,0) = 123, matrix(0,1) = 2560, matrix(0,3) = 288 , matrix(1,3)= 300
I would like to use this signature (assuming I have used all available data points to generate the histograms above) to assign other products (also please note that the "other" products also have just been introduced, hence haven't seen a complete life cycle yet) the appropriate signature so that the planners have a good idea about their volumes.
Question : can I generate an eigenvector for the square matrix generated above (in the example matrix) so I can use this in clustering eigenvectors generated from the other products? given that clustering distance matrices is a little befuddling to me.