failed to resolve some method of tkinter

Question: I am creating 2048 game on python with tkinter but I have a issue
I don't know what is wrong in left, right, up and down methods created in PageOne class.
In another class (StartPage), bind function calls these methods but this don't work
So I don't know how toresolve the mistakes, in bind functions or in the left, right, up and down methods?
In particular I get this error when I press the right key:
Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\fabio\PycharmProjects\2048gametk\2048gametk.py", line 198, in right
self.reverse()
AttributeError: 'Event' object has no attribute 'reverse'

And similar error for the other key (up, left and down):
Traceback (most recent call last):
File "C:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\fabio\PycharmProjects\2048gametk\2048gametk.py", line 208, in up
self.transpose()
AttributeError: 'Event' object has no attribute 'transpose'

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
TypeError: PageOne.left() missing 1 required positional argument: 'event'

Exception in Tkinter callback
Traceback (most recent call last):
File "C:\Users\fabio\AppData\Local\Programs\Python\Python310\lib\tkinter\__init__.py", line 1921, in __call__
return self.func(*args)
File "C:\Users\fabio\PycharmProjects\2048gametk\2048gametk.py", line 218, in down self.transpose()
AttributeError: 'Event' object has no attribute 'transpose'

The left one is different because i put event instead of event = None as argument in the left module.
A small problem concern the score_frame that appears also in the StartPage and not only in the PageOne, so i don't know how to combine the frames on the code
Below you can find the entire code
Can anyone help me?
Thanks in advance
import os
import random
import sys
import tkinter as tk
from math import floor

class MyButton(tk.Button):
    def __init__(self, *args, **kwargs):
        tk.Button.__init__(self, *args, **kwargs, bg='brown', fg='white',
                           font="Helvetica 12 bold", width=8, pady='1m')
        self.pack(pady="3m")

class Game(tk.Tk):
    def __init__(self):
        tk.Tk.__init__(self)
        self.title("2048 game")
        self.dim = 4
        self.main_grid = None
        container = tk.Frame(self, width=500, height=600)
        container.grid(pady=(100, 0))
        container.grid_rowconfigure(0, weight=1)
        container.grid_columnconfigure(0, weight=1)
        self.frames = {}
        for F in (StartPage, PageOne):
            frame = F(container, self)
            self.frames[F] = frame
            frame.grid(row=0, column=0, sticky="nsew")
        self.show_frame(StartPage)

        self.bind("<Left>", PageOne.left)
        self.bind("<Right>", PageOne.right)
        self.bind("<Up>", PageOne.up)
        self.bind("<Down>", PageOne.down)
        self.mainloop()

    def show_frame(self, controller): #page_name al posto di controller
        frame = self.frames[controller]
        frame.tkraise()

class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.dim = controller.dim
        label = tk.Label(self, text="2048", font="Helvetica 48 bold", fg="orange")
        label.pack(side="top", fill="x")
        button1 = MyButton(self, text="3x3", command=self.dim_3)
        button1.pack()
        button1.bind("<Return>", self.dim_3)
        button2 = MyButton(self, text="4x4", command=self.dim_4)
        button2.focus_force()
        button2.pack()
        button2.bind("<Return>", self.dim_4)
        button3 = MyButton(self, text="5x5", command=self.dim_5)
        button3.pack()
        button3.bind("<Return>", self.dim_5)
        button4 = MyButton(self, text="8x8", command=self.dim_8)
        button4.pack()
        button4.bind("<Return>", self.dim_8)

    def dim_3(self):
        self.dim = 3
        self.controller.show_frame(PageOne)

    def dim_4(self):
        self.dim = 4
        self.controller.show_frame(PageOne)

    def dim_5(self):
        self.dim = 5
        self.controller.show_frame(PageOne)

    def dim_8(self):
        self.dim = 8
        self.controller.show_frame(PageOne)

class PageOne(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        self.matrix = None
        self.score = None
        self.cells = []
        for i in range(self.controller.dim):
            row = []
            for j in range(self.controller.dim):
                cell_frame = tk.Frame(self, bg="light grey",
                                      width=500 / self.controller.dim, height=500 / self.controller.dim)
                cell_frame.grid(row=i+10, column=j, padx=10 / self.controller.dim, pady=10 / self.controller.dim)
                cell_number = tk.Label(self, bg="light grey")
                cell_number.grid(row=i+10, column=j)
                cell_data = {"frame": cell_frame, "number": cell_number}
                row.append(cell_data)
            self.cells.append(row)

        score_frame = tk.Frame(controller.main_grid)
        score_frame.place(relx=0.5, y=50, anchor="center")
        tk.Label(score_frame, text="Score", font="Helvetica 18 bold").grid(row=0)
        self.score_label = tk.Label(score_frame, text="0", font="Helvetica 24 bold")
        self.score_label.grid(row=1)
        self.start_game()

    def start_game(self):
        self.matrix = [[0] * self.controller.dim for _ in range(self.controller.dim)]
        row = random.randint(0, self.controller.dim - 1)
        col = random.randint(0, self.controller.dim - 1)
        self.matrix[row][col] = 2
        self.cells[row][col]["frame"].configure(bg="white")
        self.cells[row][col]["number"].configure(bg="white", fg="black", font="Helvetica 24 bold", text="2")
        while self.matrix[row][col] != 0:
            row = random.randint(0, self.controller.dim - 1)
            col = random.randint(0, self.controller.dim - 1)
        self.matrix[row][col] = 2
        self.cells[row][col]["frame"].configure(bg="white")
        self.cells[row][col]["number"].configure(bg="white", fg="black", font="Helvetica 24 bold", text="2")
        self.score = 0

    # move all numbers on the left side
    def stack(self):
        new_matrix = [[0] * self.controller.dim for _ in range(self.controller.dim)]
        for i in range(self.controller.dim):
            fill_pos = 0
            for j in range(self.controller.dim):
                if self.matrix[i][j] != 0:
                    new_matrix[i][fill_pos] = self.matrix[i][j]
                    fill_pos += 1
        self.matrix = new_matrix

    # sum numbers horizontally and combine equal numbers
    def combine(self):
        for i in range(self.controller.dim):
            for j in range(self.controller.dim - 1):
                if self.matrix[i][j] != 0 and self.matrix[i][j] == self.matrix[i][j + 1]:
                    self.matrix[i][j] *= 2
                    self.matrix[i][j + 1] = 0
                    self.score += self.matrix[i][j]

    # this function reverses the order of each row
    def reverse(self):
        new_matrix = []
        for i in range(self.controller.dim):
            new_matrix.append([])
            for j in range(self.controller.dim):
                new_matrix[i].append(self.matrix[i][self.controller.dim - 1 - j])
        self.matrix = new_matrix

    def transpose(self):
        new_matrix = [[0] * self.controller.dim for _ in range(self.controller.dim)]
        for i in range(self.controller.dim):
            for j in range(self.controller.dim):
                new_matrix[i][j] = self.matrix[j][i]
        self.matrix = new_matrix

    def add_number(self):
        if any(0 in row for row in self.matrix):
            row = random.randint(0, self.controller.dim - 1)
            col = random.randint(0, self.controller.dim - 1)
            while self.matrix[row][col] != 0:
                row = random.randint(0, self.controller.dim - 1)
                col = random.randint(0, self.controller.dim - 1)
            self.matrix[row][col] = random.choice([2, 2, 2, 2, 4])

    def update_GUI(self):
        for i in range(self.controller.dim):
            for j in range(self.controller.dim):
                cell_value = self.matrix[i][j]
                if cell_value == 0:
                    self.cells[i][j]["frame"].configure(bg="light grey")
                    self.cells[i][j]["number"].configure(bg="light grey", text="")
                else:
                    self.cells[i][j]["frame"].configure(bg=NUMBER_COLOR[cell_value])
                    self.cells[i][j]["number"].configure(bg=NUMBER_COLOR[cell_value], fg="black",
                                                         font="Helvetica 24 bold", text=str(cell_value))
        self.score_label.configure(text=self.score)
        self.update_idletasks()

        self.game_over()

    def left(self, event):
        self.stack()
        self.combine()
        self.stack()
        self.add_number()
        self.update_GUI()
        self.game_over()

    def right(self, event=None):
        self.reverse()
        self.stack()
        self.combine()
        self.stack()
        self.reverse()
        self.add_number()
        self.update_GUI()
        self.game_over()

    def up(self, event=None):
        self.transpose()
        self.stack()
        self.combine()
        self.stack()
        self.transpose()
        self.add_number()
        self.update_GUI()
        self.game_over()

    def down(self, event=None):
        self.transpose()
        self.reverse()
        self.stack()
        self.combine()
        self.stack()
        self.reverse()
        self.transpose()
        self.add_number()
        self.update_GUI()

    def horiz_moves(self):
        for i in range(self.controller.dim):
            for j in range(self.controller.dim - 1):
                if self.matrix[i][j] == self.matrix[i][j + 1]:
                    return True
        return False

    def vert_moves(self):
        for i in range(self.controller.dim - 1):
            for j in range(self.controller.dim):
                if self.matrix[i][j] == self.matrix[i + 1][j]:
                    return True
        return False

    def number(self):
        if self.controller.dim == 3:
            return 8
        elif self.controller.dim == 4:
            return 2048
        elif self.controller.dim == 5:
            return 8192
        else:
            return 16384

    def restart(self):
        self.bind("<Return>", os.execl(sys.executable, sys.executable, *sys.argv))

    def game_over(self):
        tk.Frame(self).place(relx=0.5, rely=0.5, anchor="center")
        if not any(0 in row for row in self.matrix) and not self.horiz_moves() and not self.vert_moves():
            top = tk.Toplevel()
            top.geometry("300x100")
            top.title("toplevel")
            l2 = tk.Label(top, text="Game Over\n What do you want do?",
                          fg="white", font="Helvetica 12 bold")
            l2.pack()
            tk.Button(top, text="Restart", bg="green",
                      fg="white", font="Helvetica 10 bold",
                      command=self.restart).pack(side='left')
            tk.Button(top, text="Quit", bg="red",
                      fg='white', font="Helvetica 10 bold", command=self.bind("<Return>", quit)).pack(side="right")

        elif any(self.number() in row for row in self.matrix):
            top = tk.Toplevel()
            top.geometry("180x100")
            top.title("toplevel")
            l2 = tk.Label(top, text="You Win!\n What do you want do?", font="Helvetica 12 bold")
            l2.pack()
            tk.Button(top, text="Restart", bg="green",
                      fg="white", font="Helvetica 10 bold",
                      command=self.restart).pack(side='left')
            tk.Button(top, text="Quit", bg="red",
                      fg='white', font="Helvetica 10 bold", command=self.bind("<Return>", quit)).pack(side="right")

    def savegame(self):
        f = open("savedata", "w")

        line1 = " ".join(
            [str(self.matrix[floor(x / self.controller.dim)][x % self.controller.dim])
             for x in range(0, self.controller.dim ** 2)])
        f.write(line1 + "\n")
        f.write(str(self.controller.dim) + "\n")
        f.write(str(self.score))
        f.close()

    def loadgame(self):
#        self.score
#        self.dim
#        self.matrix

        f = open("savedata", "r")

        mat = (f.readline()).split(' ', self.controller.dim ** 2)
        self.controller.dim = int(f.readline())
        self.score = int(f.readline())

        for i in range(0, self.controller.dim ** 2):
            self.matrix[floor(i / self.controller.dim)][i % self.controller.dim] = int(mat[i])

        f.close()

NUMBER_COLOR = {
    2: "#fcefe6",
    4: "#f2e8cb",
    8: "#f5b682",
    16: "#f29446",
    32: "#ff775c",
    64: "#e64c2e",
    128: "#ede291",
    256: "#fce130",
    512: "#ffdb4a",
    1024: "#f0b922",
    2048: "#fad74d",
    4096: "brown",
    8192: "silver",
    16384: "gold"
}

def main():
    Game()

if __name__ == "__main__":
    main()

Comment: Thank you very much for your support, now it work, but i have 2 small errors: I cannot modify the dimension of the matrix, at the moment i set it = 4 (you can see it in Game__init__); and the other is in game over method since the top level window appear twice instead of one
Answer: Replace the code with the following:
    self.bind("<Left>", self.frames[PageOne].left)
    self.bind("<Right>", self.frames[PageOne].right)
    self.bind("<Up>", self.frames[PageOne].up)
    self.bind("<Down>", self.frames[PageOne].down)

The reason for your odd behavior is that you try to reach instances variables and methods but on the level of a class. It's not easy to explain in a few words, but you should research the difference between class an regular methods, the purpose of self and of course the documentation for classes and instances
Update
In order to make your dimensions work you need to create your matrix after you defined the dimensions, not when you initialize your Frame. The shortest way to achive this, is to create a function that is called when your dimension is defined.
In your PageOne you would do something like:
    ...
    self.cells = []

def create_matrix(self):
    for i in range(self.controller.dim):
    ...
    score_frame = tk.Frame(self.controller.main_grid) #add self.
    ...

call this function when the user has chosen by (e.g):
def dim_3(self):
    self.controller.dim = 3 #use self.controller dim
    self.controller.frames[PageOne].create_matrix() #call create_matrix
    self.controller.show_frame(PageOne)

and while you use the variable in your controller the following is not effective:
class StartPage(tk.Frame):
    def __init__(self, parent, controller):
        tk.Frame.__init__(self, parent)
        self.controller = controller
        #self.dim = controller.dim
        #is not a link to your var self.dim stores whats in controller.dim

Update2
in order to make your quit and restart work and with little improvements I have changed your code below. The code is left as an exercise since I still try to figure out the rules of the game. Happy codeing!
def restart(self):
    for widget in self.winfo_children():
        widget.destroy()
    self.cells = []
    self.controller.show_frame(StartPage)

def game_over(self):
    tk.Frame(self).place(relx=0.5, rely=0.5, anchor="center")
    if not any(0 in row for row in self.matrix) and not self.horiz_moves() and not self.vert_moves():
        geo_string = "300x100"
        title = "Game Over!"
        text = "Game Over\n What do you want do?"
        self.message(geo_string,title,text)
    elif any(self.number() in row for row in self.matrix):
        geo_string = "180x100"
        title = "Congratulation!"
        text = "You Win!\n What do you want do?"
        self.message(geo_string,title,text)

def message(self, geo_string,title,text):
    top = tk.Toplevel()
    top.geometry(geo_string)
    top.title(title)
    l2 = tk.Label(top, text=text, font="Helvetica 12 bold")
    l2.pack()
    rbutton = tk.Button(top, text="Restart", bg="green",
                        fg="white", font="Helvetica 10 bold",
                        command=self.restart)
    rbutton.bind('<ButtonRelease-1>',lambda e: self.controller.after(20,top.destroy))
    rbutton.pack(side='left')

    qbutton = tk.Button(top, text="Quit", bg="red",
                        fg='white', font="Helvetica 10 bold",
                        command=self.controller.destroy)
    qbutton.pack(side="right")

Comment: Thank you very much for your support, now it work, but i have 2 small errors: I cannot modify the dimension of the matrix, at the moment i set it = 4 (you can see it in Game__init__); and the other is in game over method since the top level window appear twice instead of one
Comment: @FabioCitti Well you create the dimension by initialize PageOne, changing your variable afterwards has no effect in your code. Consider to [accept](https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work/5235#5235) if this answer solved your original question.


D3.js sort table by number, then alphabetically (as a tie-breaker)

Question: I have a table with two columns of data. When I sort with column [1] I need to further sort based on the alphabetical values of column [0].
This will sort the table by the float values in the second column, but I would like to further sort the tie's alphabetically by the string values in the first column .
return tbody.selectAll("tr").sort(function(a, b)
{
    isSorted = true;
    d3.ascending(parseFloat(a[1]), parseFloat(b[1]));
})

Answer: return tbody.selectAll("tr").sort(function(a, b) {
   d3.ascending(parseFloat(a[1]), parseFloat(b[1])) ||
     d3.ascending(a[0], b[0]);
})

If the values at [1] are equal, d3.ascending returns 0, which will cause javascript to evaluate the 2nd expression after the || (aka or) and return its value.
Note that if the first function call returns 1 or -1 then the function call in the 2nd expression wouldn't even execute.


Rewrite negative number into positive numbers

Question: I'm preparing some charts, with positive and negative values.
I would like to create one pie chart, including all the values (the positive and negative). Of course, this doesn't work as only positive numbers should be considered.
So I tried to rewrite the results (to cancel the "-") but it doesn't work. I would like to have "-100" displayed as "100", and the "100" staying at "100", so that I can create my graph.
Does somebody has an idea?
Answer: For Drupal 7 you could use the Global: Math expression field to perform a mathematical operation. Load the initial field first, suppress it from display and use the replacement token within the Math field: (abs([initial_field])).
For Drupal 8 this field does not exist (yet), though there is a sandbox linked in post #10 here: https://www.drupal.org/node/2544670. It might work.
Comment: Awesome! You can use the check symbol (✓) left of the answer to mark it as solved :)


'nome_da_função': Identificador não encontrado

Question: void inserePoli1(poli **topo1, int val, int expo) {
    polinomio1 *novo;
    char cmd;
    novo = new poli;
    novo->valor = val;
    novo->expoente = expo;
    if (*topo1 == NULL) {
        novo->prox = NULL;
        *topo1 = novo;
    }
    else {
        novo->prox = *topo1;
        *topo1 = novo;
    }
    cout << "Deseja inserir mais um elemento? (sim - S/não - N)" << endl;
    cin >> cmd;
    if (cmd == 's') {
        criaPoli1(val, expo, *topo1);
     }
}

void criaPoli1(int &val, int &expo, poli *topo1) {
    cout << "\nInsira o VALOR: ";
    cin >> val;
     cout << "Insira o EXPOENTE: ";
    cin >> expo;
    inserePoli1(&topo1, val, expo);
}

Levando em consideração que abaixo dessas duas funções a minha main() já possui a chamada para criapoli1, como posso chamar esta mesma função, sendo que colocando criapoli1 acima de inserepoli1 resulta em erro e vice versa também retorna erro uma vez que uma chama a outra...
Answer: Coloca antes só a declaração e deixa a definição para depois:
void criaPoli1(int &val, int &expo, poli *topo1);

Pode até fazer:
void criaPoli1(int &, int &, poli *);

Coloquei no GitHub para referência futura.
Comment: Poderia exemplificar usando meu próprio codigo?
Comment: Eu poderia se tivesse colocado corretamente, mas sem nem dar para entender o que tem nele fica um pouco mais complicado.
Comment: depois que cliquei no link eu compreendi o que precisava fazer, muito obrigado!!


Alterar posição do marker do google maps ao clicar

Question: Estou querendo alterar a posição do marcador do maps ao clicar na tela do Smartphone, no meu código em vez de alterar a posição ele cria vários marcadores.

abaixo o codigo da main activity
package com.t2ti.localizacao;

import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.Toast;

import com.google.android.gms.maps.CameraUpdate;
import com.google.android.gms.maps.CameraUpdateFactory;
import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.SupportMapFragment;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

public class MapsActivity extends FragmentActivity {

    private GoogleMap mMap; // Might be null if Google Play services APK is not available.
    private double latitude;
    private double longitude;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);

        latitude = getIntent().getDoubleExtra("latitude", 0);
        longitude = getIntent().getDoubleExtra("longitude", 0);

        setUpMapIfNeeded();

    }

    @Override
    protected void onResume() {
        super.onResume();
        //setUpMapIfNeeded();
        //configura o zoom do mapa
        LatLng local = new LatLng(latitude, longitude);
        CameraUpdate update = CameraUpdateFactory.newLatLngZoom(local, 15);
        mMap.animateCamera(update);

        mMap .setOnMapClickListener( new GoogleMap.OnMapClickListener() {
            @Override
            public void onMapClick (LatLng latLng) {
                MarkerOptions options = new MarkerOptions() ;
                options.position( latLng ) ;
                mMap .addMarker( options ) ;

                //mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
            }
        });

    }

    /**
     * Sets up the map if it is possible to do so (i.e., the Google Play services APK is correctly
     * installed) and the map has not already been instantiated.. This will ensure that we only ever
     * call {@link #setUpMap()} once when {@link #mMap} is not null.
     *

     * If it isn't installed {@link SupportMapFragment} (and
     * {@link com.google.android.gms.maps.MapView MapView}) will show a prompt for the user to
     * install/update the Google Play services APK on their device.
     *

     * A user can return to this FragmentActivity after following the prompt and correctly
     * installing/updating/enabling the Google Play services. Since the FragmentActivity may not
     * have been completely destroyed during this process (it is likely that it would only be
     * stopped or paused), {@link #onCreate(Bundle)} may not be called again so we should call this
     * method in {@link #onResume()} to guarantee that it will be called.
     */
    private void setUpMapIfNeeded() {
        // Do a null check to confirm that we have not already instantiated the map.
        if (mMap == null) {
            // Try to obtain the map from the SupportMapFragment.
            mMap = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map))
                    .getMap();
            // Check if we were successful in obtaining the map.
            if (mMap != null) {
                setUpMap();
            }
        }
    }

    /**
     * This is where we can add markers or lines, add listeners or move the camera. In this case, we
     * just add a marker near Africa.
     *

     * This should only be called once and when we are sure that {@link #mMap} is not null.
     */
    private void setUpMap() {
        mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
    }

}

Comment: Não entendi o voto negativo na pergunta.
Comment: zerei ela pra vc, agr nao ta negativa
Answer: Consegui colocando a função clear da variável GoogleMap mMap no inicio do método onclick do map.
exemplo abaixo:
  mMap .setOnMapClickListener( new GoogleMap.OnMapClickListener() {
        @Override
        public void onMapClick (LatLng latLng) {
            //função clear
            mMap.clear();
            MarkerOptions options = new MarkerOptions() ;
            options.position( latLng ) ;
            mMap .addMarker( options ) ;

            //mMap.addMarker(new MarkerOptions().position(new LatLng(latitude, longitude)).title("Marker"));
        }
    });

Comment: Assim o marcador é movido.
Answer: Você deve usar a CameraUpdate para fazer esses movimentos programáticos do mapa.
Para fazer isso, primeiro calcule os limites de todos os marcadores da seguinte forma:
LatLngBounds.Builder builder = new LatLngBounds.Builder();
for (Marker marker : markers) {
    builder.include(marker.getPosition());
}
LatLngBounds bounds = builder.build();

Em seguida, obtenha um objeto de movimento usando a factory CameraUpdateFactory
int padding = 0; // deslocamento das bordas do mapa em pixels
CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(bounds, padding);

Finalmente mova o mapa:
googleMap.moveCamera(cu);

Ou se você quiser uma animação:
googleMap.animateCamera(cu);


Linux: rename file/dir in it's current location w/o changing pwd to that location?

Question: At the command line, lets say my pwd is something like:
/home/whatever

And there is a file in some deep directory that I want to rename. Normally I would do this:
# mv /var/some/deep/folder/structure/fileA /var/some/deep/folder/structure/fileB

What question is, are there any command line tricks to rename a file/dir without having to type out the entire directory structure again?  Something like:
# mv /var/some/deep/folder/structure/fileA fileB

The problem with that command is that it moves fileA to your pwd. Obviously I want to keep it in the same location and simply rename it. So as I said, are there any tricks to achieve this without having to type out the entire directory structure again? It's simply a question out of curiosity and laziness.
Answer: Depends on your shell. In zsh you can:
mv /var/some/deep/folder/structure/{fileA,fileB}

If you're using bash, consider migrating to zsh - it's a pretty straightforward process and I'm sure you'll love zsh. :)
Edit:
It seems to work in bash, see Lunar_Lamp's comment.
Comment: I use this quite often in Bash, but I forgot to suggest that in my answer!
Comment: Wow, it works in bash too, I didn't knew it :)
Answer: There are at least three tricks to eliminate the repetitive typing.
… and they all work in the Bourne-Again shell, the Korn shell, and the Z shell.

Use shell variables:dir=/var/some/deep/folder/structure
mv "${dir}"/fileA mv "${dir}"/fileB
Use brace expansion:mv /var/some/deep/folder/structure/{fileA,fileB}
Use a subshell:(cd /var/some/deep/folder/structure/ && mv fileA fileB)

Other typing-reduction tricks include more shell-specific tricks such as functions and aliases, and shell-neutral tricks such as using your terminal emulator's copy and paste facilities.  ☺
Answer: While there may be more efficient shortcuts, these would be the two methods I'd use frequently:
aa=/var/some/deep/folder/structure/
mv "$aa"fileA "$aa"fileB

Or
cd /var/some/deep/folder/structure
mv fileA fileB
cd -

Now, obviously they're not the efficient solutions that you're after, but they can both (in my opinion) be quicker than typing out the full path each time.


Theory E Minor Dominant First Inversion

Question: I was wondering that the procedure to these type of questions. You have to take special care for these questions. Dominant in a minor key. Because i know you have to raise the 7th in a dominant triad/chord in a minor key. It is just which note needs to be raised and what is the procedure.
Comment: Hi, I'm not sure I understand your question. It seems to be interesting, and I would love to learn something from it, but I'm not sure I get the point.
Comment: "Because I know you have to raise the 7th..." -- usually you raise the _3rd_ of a dominant chord in a minor key.
Answer: Disregard the fact that it's in a minor key. The dominant is built on the 5th, so in Em will be a B chord. To be convincing, it needs a leading note, which here will be D# rather than D, found in the natural minor scale. To be even more convincing, there'll be a tritone within the chord, making it B7. That triton is between D# and A. The 1st inversion puts the 3rd at the bottom, so, D#, F# A, B. Could this be your homework?
Comment: An exam question about the "dominant" chord will not get full marks for an answer about the "domimant 7th" - though what you say is correct *musically* of course.
Comment: That was just an extra bit. How could my answer have achieved more marks?

Theory E Minor Dominant First Inversion


Pegar Apenas Número do Ranking do Registro em Uma Query

Question: Tem como eu pegar o Ranking de um registro na tabela apenas com uma Query (mesmo que tenha uma Subquery) ?
Por exemplo, fiz isso abaixo:
SELECT
    a.id_concessionaria,
    a.avscore,
    @rank := @rank + 1 AS ranking
FROM
    (
        SELECT
            id_concessionaria,
            Avg(rating) AS AvScore
        FROM
            dealer_ratings
        GROUP BY
            id_concessionaria
    ) a
ORDER BY
    a.avscore DESC

E retorna:
12286   5.0000  1
11393   5.0000  2
11784   5.0000  3
11816   5.0000  4
12291   4.3333  5 --------------------- Essa aqui
12634   4.0000  6
19021   3.0000  7
10194   2.0000  8

Tem como eu pegar apenas o Rank do ID que eu quiser ?
Tentei fazer o WHERE, mas daí ele mostra o Rank como 1.
Answer: Faz um SELECT que pega esse resultado e daí nele você faz o WHERE, dessa forma:
SELECT b.ranking FROM (
    SELECT
        a.id_concessionaria,
        a.avscore,
        @rank := @rank + 1 AS ranking
    FROM
        (
            SELECT
                id_concessionaria,
                Avg(rating) AS AvScore
            FROM
                dealer_ratings
            GROUP BY
                id_concessionaria
        ) a
    ORDER BY
        a.avscore DESC
) AS b WHERE b.id_concessionaria = '12291'

Comment: Obrigado, Mano. Era isso mesmo.
Comment: Blz brow! Até +


Can Windows Removable Storage send operator requests remotely?

Question: I'm playing around with a LTO tape-archival setup using Windows 2003 and Remote Storage Service. Everything's working great, but one thing I've noticed is that Operator Requests only seem to be able to be displayed on the desktop of the system. This means that in order to be notified about tape changes and other events, I basically need to be looking at the desktop the whole time.
Is there a way in which I could be notified of these events via email, or some other remote mechanism?
Answer: The built-in functionality is limited to the "tray" icon and messages sent using the now-deprecated "Messenger" service. I doubt you're going to find much out there to help you, as Removable / Remote Storage was deprecated in Windows Server 2008 R2.
The built-in Rss command-line tool for administering Removable / Remote Storage lacks any functionality to deal with operator requests. If you wanted to code something you might be able to use the Removable Storage Manager APIs to come up with something that waited for operator requests and fired-off notifications, but it would be strictly a "you build it" kind of effort. (As I'm looking at that API, though, it looks like it might not even have functionality to do what you want.)


Nested getline in AWK script

Question: Please let me know if we can use nested getline within AWK scripts like:
while ( ("tail -f log" |& getline var0) > 0) {

    while ( ("ls" | getline ) > 0) {
    }
    close("ls")
    while ( ("date" | getline ) > 0) {
    }
    close("date")
}
    close("tail -f log")

What is the depth we can make use of nested getline functionality and will there be any data loss of output at any level of the nested getline? What are the things we should make sure in implementing this style?
==================================================================================
UPDATE===================UPDATE==============UPDATE===============UPDATE=======
Requirement : Provide real time statistical data and errors by probing QA box and webserver / services logs and system status. Report would be generated in following format:
Local Date And Time | Category| Component | Condition
Assumption -: AWK script would execute faster than shell script with added advantage of using its inbuilt parsing and other functionalities.
Implementation : - The main command loop is command0="tail -f -n 0 -s 5 ...........". This command would start an infinite loop extracting appended logs of services / webserver of QA box. . Note the -f, -s and –n options which makes to dump all appended data to logs, sleep for 5 seconds after each iterations and start without printing any default content from the existing logs.
After each iteration, capture and verify the system time and execute various OS resource commands after 10 seconds interval (5 seconds sleep in-between each iteration and 4 seconds after processing the tail output – assuming that processing all tail command roughly take 1 sec, hence in all 10 seconds)
Various command I have used for extracting OS resources are:
I.  command1="vmstat | nl | tr -s '\\t '"
II. command2="sar -W 0"
III.    command3="top -b -n 1 | nl | tr -s '\\t '"
IV. command4="ls -1 /tmp | grep EXIT"

Search for respective command(?) in the script and go thru the while loop of it in the script to figure output processing of the respective command. Note I nave used 'nl' command for development / coding ease
Ultimately presence of /tmp/EXIT file on the box will make the script to exit after removing the same from the box
Below is my script - I have added comments as much as possible for self explanatory:
#Useage - awk -f script.awk
BEGIN {
    command0="tail -f -n 0 -s 5 /x/web/webserver/*/logs/error_log /x/web/webserver/service/*/logs/log"
    command1="vmstat | nl | tr -s '\\t '"
    command2="sar -W 0"
    command3="top -b -n 1 | nl | tr -s '\\t '"
    command4="ls -1 /tmp | grep EXIT"
    format = "%a %b %e %H:%M:%S %Z %Y"
    split("", details)
    split("", fields)
    split("", data)
    split("", values)
    start_time=0

    printf "\n>%s:\n\n", command0 #dummy print for debuggng command being executed

    while ( (command0 |& getline var0) > 0) { #get the command output
        if (start_time == 0) #if block to reset the start_time variable
        {
                start_time = systime() + 4
        }
        if (var0 ~ /==>.*<==/) { #if block to extract the file name from the tail output - outputted in '==>FileName<==' format
                gsub(/[=><]/, "", var0)
                len = split(var0, name, "/")
                if(len == 7) {file = name[5]} else {file = name[6]}
        }
        if (len == 7 && var0 ~ /[Ee]rror|[Ee]xception|ORA|[Ff]atal/) {  #extract the logs error statements
                print strftime(format,systime()) " | Error Log | " file " | Error :" var0
        }
        if(systime() >= start_time) #check if curernt system time is greater than start_time as computed above
        {
                start_time = 0 #reset the start_time variable and now execute the system resource command
                printf "\n>%s:\n\n", command1
                while ( (command1 |& getline) > 0) { #process output of first command
                if($1 <= 1)
                        continue #not needed for processing skip this one
                if($1 == 2) #capture the fieds name and skip to next line
                {
                        for (i = 1; i <= NF; i++){fields[$i] = i;}
                        continue
                }
                if ($1 == 3) #store the command data output in data array
                        split($0, data);
                print strftime(format,systime()) " | System Resource | System | Time spent running non-kernel code :" data[fields["us"]]
                print strftime(format,systime()) " | System Resource | System | Time spent running kernel code :" data[fields["sy"]]
                print strftime(format,systime()) " | System Resource | System | Amount of memory swapped in from disk :" data[fields["si"]]
                print strftime(format,systime()) " | System Resource | System | Amount of memory swapped to disk :" data[fields["so"]]
                }
                close(command1)

                printf "\n>%s:\n\n", command2 #start processing second command
                while ( (command2 |& getline) > 0) {
                        if ($4 ~ /[0-9]+[\.][0-9]+/) #check for 4th positional value if its format is of "int.intint" format
                        {
                                if( $4 > 0.0) #dummy check now to print if page swapping
                                        print strftime(format,systime()) " | System Resource | Disk | Page rate is > 0.0 reads/second: " $4
                        }
                }
                close(command2)

                printf "\n>%s:\n\n", command3 # start processing command number 3
                while ( (command3 |& getline ) > 0) {
                        if($1 == 1 && $0 ~ /load average:/) #get the load average from the output if this is the first line
                        {
                                split($0, arr, ",")
                                print strftime(format,systime())" | System Resource | System |" arr[4]
                        }
                        if($1 > 7 && $1 <= 12) # print first top 5 process that are consuming most of the CPUs time
                        {
                                f=split($0, arr, " ")
                                if(f == 13)
                                        print strftime(format,systime())" | System Resource | System | CPU% "arr[10]" Process No: "arr[1] - 7" Name: "arr[13]
                        }
                }
                close(command3)
                printf "\n>%s:\n\n", command4 #process command number 4 to check presence of file
                while ( (command4 |& getline var4) > 0) {
                        system("rm -rf /tmp/EXIT")
                        exit 0 #if file is there then remove the file and exit this script execution
                }
                close(command4)
        }
    }
        close(command0)
}

Output -:
>tail -f -n 0 -s 5 /x/web/webserver/*/logs/error_log /x/web/webserver/service/*/logs/log:

>vmstat | nl | tr -s '\t ':

Sun Dec 16 23:05:12 PST 2012 | System Resource | System | Time spent running non-kernel code :9
Sun Dec 16 23:05:12 PST 2012 | System Resource | System | Time spent running kernel code :9
Sun Dec 16 23:05:12 PST 2012 | System Resource | System | Amount of memory swapped in from disk :0
Sun Dec 16 23:05:12 PST 2012 | System Resource | System | Amount of memory swapped to disk :2

>sar -W 0:

Sun Dec 16 23:05:12 PST 2012 | System Resource | Disk | Page rate is > 0.0 reads/second: 3.89

>top -b -n 1 | nl | tr -s '\t ':

Sun Dec 16 23:05:13 PST 2012 | System Resource | System | load average: 3.63
Sun Dec 16 23:05:13 PST 2012 | System Resource | System | CPU% 12.0 Process No: 1 Name: occworker
Sun Dec 16 23:05:13 PST 2012 | System Resource | System | CPU% 10.3 Process No: 2 Name: occworker
Sun Dec 16 23:05:13 PST 2012 | System Resource | System | CPU% 6.9 Process No: 3 Name: caldaemon
Sun Dec 16 23:05:13 PST 2012 | System Resource | System | CPU% 6.9 Process No: 4 Name: occmux
Sun Dec 16 23:05:13 PST 2012 | System Resource | System | CPU% 6.9 Process No: 5 Name: top

>ls -1 /tmp | grep EXIT:

Comment: AFAIK you can do arbitrary levels of nesting. Depending on your version of awk you might run into the problem of maximum number of file descriptors available, but this can usually be worked around by closing unused ones.
Comment: Concur, with the additional observation that your example looks like it wants you to try Python or Perl instead.
Comment: Yes and DON'T! awk is a tool for parsing text files. It is not an OS for invoking commands from. You are using the wrong tool for this job. Tell us what you're trying to do with sample input and expected output and we can help you.
Comment: @Thor - Thanks for the info. If would close each command after completion (outside while loop) I think I might not land into issues then
Comment: @Ed - Please find my script and requirement updated in the question section
Comment: Your assumption that awk would execute faster than shell is odd since you're still using shell but instead of doing shell->date you're adding a couple of layers to get shell->awk->systime()->shell->date. I'll take a look at your script and post a shell version, best I can tell from the commands you're using.
Answer: This is your second post that I can recall about using getline this way. I mentioned last time that it was the wrong approach but it looks like you didn't believe me so let me try one more time.
Your question of "how do I use awk to execute commands with getline to read their output?" is like asking "how do I use a drill to cut glass?". You could get an answer telling you to tape over the part of the glass where you'll be drilling to avoid fracturing it and that WOULD answer your question but the more useful answer would probably be - don't do that, use a glass cutter.
Using awk as a shell from which to call commands is 100% the wrong approach. Simply use the right tool for the right job. If you need to parse a text file, use awk. If you need to manipulate files or processes or invoke commands, use shell (or your OS equivalent).
Finally, please read http://awk.freeshell.org/AllAboutGetline and don't even think about using getline until you fully understand all the caveats.
EDIT: here's a shell script to do what your posted awk script does:
tail -f log |
while IFS= read -r var0; do
    ls
    date
done

Look simpler? Not saying it makes sense to do that, but if you did want to do it, THAT's the way to implement it, not in awk.
EDIT: here's how to write the first part of your awk script in shell (bash in this case), I ran out of enthusiasm for translating the rest of it for you and I think this shows you how to do the rest yourself:
format = "%a %b %e %H:%M:%S %Z %Y"
start_time=0

tail -f -n 0 -s 5 /x/web/webserver/*/logs/error_log /x/web/webserver/service/*/logs/log |
while IFS= read -r line; do

    systime=$(date +"%s")

    #block to reset the start_time variable
    if ((start_time == 0)); then
        start_time=(( systime + 4 ))
    fi

    #block to extract the file name from the tail output - outputted in '==>FileName<==' format
    case $var0 in
        "==>"*"<==" )
            path="${var0%% <==}"
            path="${path##==> }"
            name=( ${path//\// } )
            len="${#name[@]}"
            if ((len == 7)); then
                file=name[4]
            else
                file=name[5]
            fi
            ;;
    esac

    if ((len == 7)); then
        case $var0 in
            [Ee]rror|[Ee]xception|ORA|[Ff]atal )    #extract the logs error statements
                printf "%s | Error Log | %s | Error :%s\n" "$(date +"$format")" "$file" "$var0"
                ;;
        esac
    fi

    #check if curernt system time is greater than start_time as computed above
    if (( systime >= start_time )); then

        start_time=0 #reset the start_time variable and now execute the system resource command
        ....

Note that this would execute slightly faster than your awk script but that absolutely does not matter at all since your tail is taking 5 second breaks between iterations.
Also note that all I'm doing above is translating your awk script into shell, it doesn't necessarily mean it'd be the best way to write this tool from scratch.
Comment: @Ed - I have copied my awk script in question. Please provide your opinion on same. I wanted to achieve benefits twofold - learn awk and benefit our QAs of their environment stability they are working on. Thanks in advance
Comment: @Prakash - Wanting to learn awk is great. An important part of that is learning what to use awk for and that is parsing text files. Using it as an environment from which to invoke shell commands is absolutely wrong - it's not what the tool or language were designed for, it's what the shell was designed for, and so will lead to ugly, complicated, inefficient scripts.
Comment: Thanks Ed for the help and proper direction. I would migrate my AWK script to a Shell Script

Nested getline in AWK script


Laravel - create array of objects and arrays in PHP

Question: I am trying to create an array of objects in laravel php. I have achieved this so far.
When I return the array I get the response which I have added a image for clarity.
I get this output

I want to create a response like this...
<code>[
    {
        "student": "Jaime Thomas",
        "subjects": [
            {
                "subject": "Physics",
                "marks_": 0
            },
            {
                "subject": "Chemistry",
                "marks_": 0
            }
        ]
    },
    {
        "student": "Jaime Dey",
        "subjects": [
            {
                "subject": "Physics",
                "marks_": 0
            },
            {
                "subject": "Chemistry",
                "marks_": 0
            }
        ]
    }
]

</code>
<code>  $usersData = User::where('user_id', 2)->where("stud_class", $exam_details->exam_class_id)->where("XXXX", $exam_details->exam_branch_id)->get();
            foreach ($exam_data as  $subject) {
                $att_exams =  MODEL::where('XXXXX', $subject->subject_id)
                    ->where('XXXX', $user->id)
                    ->first();
                if ($att_exams) {
                    $marks =  MODEL::where('XXXX', $att_exams->attended_exams_id)->get();
                    $right = 0;
                    $wrong = 0;
                    $total_marks = $marks->sum('XXXX');

                    $total_negative_marks = $wrong * $subject->negative_marks;
                    $subjectsArray[] = array(
                        "subject" => $subject->subject_name,
                        "marks_" => $total_marks - $total_negative_marks,
                    );
                } else {
                    $subjectsArray[] = array(
                        "subject" => $subject->subject_name,
                        "marks_" => 0,
                    );
                }
            }
            $studentsArray["subjects"] = array($subjectsArray);
        }
        return $studentsArray;
</code>
Comment: Try `return [$studentsArray];`
Comment: @MuhammadTashfeen sir I want to add subjects array into the main studentArray. {"student" : "abc","subjects : [ {}, {} ]} like this sir...
Answer: You can try the below code:
<code>$studentsArray = [];
        $usersData = User::where('user_id', 2)->where("stud_class", $exam_details->exam_class_id)->where("XXXX", $exam_details->exam_branch_id)->get(['name', 'id']);
        foreach ($usersData as $user) {
            $subjectsArray = [];
            foreach ($exam_data as  $subject) {
                $att_exams =  MODEL::where('XXXXX', $subject->subject_id)
                    ->where('XXXX', $user->id)
                    ->first();
                if ($att_exams) {
                    $marks =  MODEL::where('XXXX', $att_exams->attended_exams_id)->get();
                    $right = 0;
                    $wrong = 0;
                    $total_marks = $marks->sum('XXXX');
                    foreach ($marks as $mark) {
                        if ($mark->XXX== 0) {
                            $wrong++;
                        } else {
                            $right++;
                        }
                    }
                    $total_negative_marks = $wrong * $subject->negative_marks;
                    $subjectsArray[] = [
                        "subject" => $subject->subject_name,
                        "marks_" => $total_marks - $total_negative_marks,
                    ];
                } else {
                    $subjectsArray[] = array(
                        "subject" => $subject->subject_name,
                        "marks_" => 0,
                    );
                }
            }
            $studentsArray[] = [
                "student" => $user->name,
                "subjects" => $subjectsArray
            ];
        }
        return $studentsArray;
</code>
Comment: sir. I tried your code but it is not returning the array which I want. Please check I have updated the question.
Comment: I have updated the answer, check it out.
Comment: Reaching out to get an update if this eventually works for you


ng-include not working like it supposed to

Question: I have a form and it has several buttons. When clicking one of this button, this form should remove and load another form. I'm trying to do this using ng-include method. I have done a similar thing before and got it to work. But I cannot understand why this is not working.
I have given the 2nd form inside script tag and when clicking the above mentioned button it calls for this form. But it does not load.
I have removed the existing form using ng-if method in the controller.
My html code

    <form role="form" id="info_form" name="info_form" ng-controller="infoCtrl" ng-app="app"  novalidate>

                    Fill your medical information

                    <?php
                    echo form_open('info/addInfo');
                    ?>

                                            Age

                                                <input class='input' type="number" class="form-control" name="Age" id="Age" ng-model="data.age" placeholder="Enter your age" required>

                                                Value cannot be blank

                                            Sex

                                                <select class='input' name="Sex" id="Sex" ng-model="data.sex" ng-selected="" required>
                                                    <option value="" disabled selected>Select Your Option</option>
                                                    <option value="M">Male</option>
                                                    <option value="F">Female</option>
                                                </select>

                                                Value cannot be blank

                                            Blood Pressure

                                                <input class='input' type="number" class="form-control" name="Pressure" id="Pressure" ng-model="data.blood_pressure" placeholder="Enter your blood pressure" required>

                                                Value cannot be blank

                                            Blood Sugar

                                                <select class='input' name="Sugar" id="Sugar" ng-model="data.sugar" ng-selected="" required>
                                                    <option value="" disabled selected>Select Your Option</option>
                                                    <option value="PF">Low</option>
                                                    <option value="NPF">Normal</option>
                                                    <option value="C">High</option>
                                                </select>

                                                Value cannot be blank

                                            Maximum Heart Rate

                                                <input class='input' type="number" name="Heart" id="Heart" class="form-control"  ng-model="data.heart_rate" placeholder="Enter Value" required>

                                                Value cannot be blank

                                            Slope The Peak Exercise ST Segment

                                                <input class='input' type="number" name="Slope" id="Slope" class="form-control"  ng-model="data.slope" placeholder="Enter Value" required>

                                                Value cannot be blank

                                            Number of major vessels

                                                <select class='input' name="Vessel" id="Vessel" ng-model="data.vessels" ng-selected="" required>
                                                    <option value="" disabled selected>Select Your Option</option>
                                                    <option value="0" >0</option>
                                                    <option value="1">1</option>
                                                    <option value="2">2</option>
                                                    <option value="3">3</option>
                                                </select>

                                                Value cannot be blank

                                            Smoking

                                                <select class='input' name="Smoke" id="Smoke" ng-model="data.smoking" ng-selected="" required>
                                                    <option value="" disabled selected>Select Your Option</option>
                                                    <option value="0">No</option>
                                                    <option value="1">Yes - Heavy Smoker</option>
                                                    <option value="2">Yes - Light Smoker</option>
                                                </select>

                                                Value cannot be blank

                                            Exercising

                                                <select class='input' name="Exercise" id="Exercise" ng-model="data.exercise" ng-selected="" required>
                                                    <option value="" disabled selected>Select Your Option</option>
                                                    <option value="0">No</option>
                                                    <option value="1">Yes</option>
                                                </select>

                                                Value cannot be blank

                                            Consuming Alcohol

                                                <select class='input' name="Alcohol" id="Alcohol" ng-model="data.alcohol" ng-selected="" required>
                                                    <option value="" disabled selected>Select Your Option</option>
                                                    <option value="0">No</option>
                                                    <option value="1">Yes - Heavy Consumer</option>
                                                    <option value="2">Yes - Light Consumer</option>
                                                </select>

                                                Value cannot be blank

                                            How Long Do You Work Per Day?

                                                <select class='input' name="Work" id="Work" ng-model="data.work" ng-selected="" required>
                                                    <option value="" disabled selected>Select Your Option</option>
                                                    <option value="0">4-5 Hours</option>
                                                    <option value="1">5-6 Hours</option>
                                                    <option value="2">6-7 Hours</option>
                                                    <option value="3">More than 7 Hours</option>
                                                </select>

                                                Value cannot be blank

                                        <input class="input" type="hidden" name="Email" id="Email" class="form-control" ng-model="data.email" value="<?php echo($email); ?>">

                        <button href="" type="submit" ng-click="submitted = true;
                                    train(data);" class="btn btn-primary">Train data</button>
                        <button href="" type="submit" ng-click="submitted = true;
                                    submit(data);
                                    template = 'addeditview'" class="btn btn-primary">Submit</button>
                        Cancel

                    <?php
                    echo form_close();
                    ?>

            <ng-include src="template"></ng-include>

Comment: I see multiple `ng-app` instances. I doubt that's going to work correctly
Comment: I removed the ng-app in code inside script tags..still not working
Comment: anyone can help me?
Answer: The src attribute has to point to a valid html file, taking into account the root folder as www (or at least where you're supposed to) As such:
<ng-include src="template.html"></ng-include>

I would suggest not to discredit a very respected and solid framework only because you don't understand the documentation :)


Integral solutions of a Diophantine equation

Question: Find some integral solution of the equation.
$$x^2+6xy-4y^2-4x-12y-19=0$$
What is the form of integral solution?
Comment: Hint: express $x$ or $y$ as a function of the other variable, and discuss the "integrality" of the expression.
Comment: It is recommended that in addition to the statement of the problem you want help with, some context is supplied in the body of the Question.  One way to do this is by explaining your own attempt to solve it, but there are other kinds of context that help Readers respond in a way you will find useful.
Answer: Hint. The equation is equivalent to
$$(x-2+3y)^2-13y^2=23.$$
We can get a solution as soon as we find $y$ such that $y^2+23$ is a perfect square. Then
$$x = -3y+2\pm\sqrt{13y^2+23}.$$
For example for $y=1$, we have $(5,1)$, $(-7,1)$, and for $y=-1$ we get $(-1,-11)$, $(11,-1)$. For $y=\pm 431$ and $y=\pm 1739$ we can obtain more solutions (they are infinite!).
Comment: Yes and very ugly general solution.
Comment: @MichaelRozenberg not so bad, just two orbits..
Answer: As $23$ is prime there are two similar linear recurrences that give all the values of $y,$ note that it is necessary to use both $\pm v$ form these:
In both cases of $u^2 - 13 v^2 = 23$ we get
$$ v_{n+2} = 1298 v_{n+1} - v_n   $$
$$  -1, \; 431, \; 559439, \; 726151391, $$
$$ 1, \; 1729, \; 2244241, \; 2913023089,  $$
<code>jagy@phobeusjunior:~$  ./Pell_Target_Fundamental
  Automorphism matrix:
    649   2340
    180   649
  Automorphism backwards:
    649   -2340
    -180   649

  649^2 - 13 180^2 = 1

 u^2 - 13 v^2 = 23

Sun Jun  4 10:28:24 PDT 2017

u:  6  v:  1 ratio: 6  SEED   KEEP +-
u:  1554  v:  431 ratio: 3.60557  SEED   BACK ONE STEP  6 ,  -1
u:  6234  v:  1729 ratio: 3.60555
u:  2017086  v:  559439 ratio: 3.60555
u:  8091726  v:  2244241 ratio: 3.60555

Sun Jun  4 10:29:24 PDT 2017

 u^2 - 13 v^2 = 23

jagy@phobeusjunior:~$
</code>


Choice Between Alternatives in Machine Learning

Question: I need some advice on the simplest/best way to structure an ML model for a (slightly) non-standard situation.
Setup: I have many teams in a company that have leaders. Each team has two options for a leader (A & B). The teams and their leader options differ a lot across the company, but the choice of A or B for each team is more or less arbitrary/random. I can measure teams' performance (y) consistently and potential leaders' characteristics (x_A, x_B).
Goal: I want to predict what kinds of leaders are best. Should A or B have been chosen?
Analysis: there are a few ways to set this problem up and here's where I need advice. Say f is some ML model function of characteristics, should I fit

y ~ f(x_Winner) -- this is primarily the relationship I want, but the model doesn't see what the alternative leader was for each team (just the winner)
y ~ f(x_i, T_i) -- that is, have two observations per team, one for A & B each. Add A and B's characteristics and include T_i which is equal to 1 if the person was chosen as leader. The model still doesn't see the alternative and predictions may be inconsistent across observations (f(x_A,1) should = f(x_B,0))
y ~ f(x_A, x_B, T_A) -- now the model sees both alternatives, but the ordering of inputs is very arbitrary; does A or B go in the first slot?

I wanted advice on what's most standard to do here and how to evaluate which model is best. Do I care most about whether the model predicts y? or, since each choice is relative, how the predicted effect (f(A wins) - f(B wins)) is most related to y?
Edits: Since the morality of this came up, this is purely a conceptual question. There's no actual organization or teams. If you prefer, think about a situation where I observe a series of binary choices, characteristics about the choices, which choice was made, and the ultimate outcome. I want to predict the 'best choices.' The choice is always binary between A & B, but the labels don't mean anything other than "first choice" and "second choice."
Comment: It's not clear why you think that the features of the loser should be relevant for your model - assuming the performance of each team depends on the characteristics of it's leader, why does it matter who was *not* chosen ? The meaning of the "A" and "B" labels is also not clear, is that just random labeling or are there candidates of "type A" and "type B" ?
Comment: The losers' characteristics ultimately might not be predictive. However, by telling the model about both options, it might learn what was relevant in the change (how A was different from B) and what was simply inevitable (characteristics A & B share). A & B are arbitrary labels not types, each one (in this example) is an individual.
Comment: Let me know if that's helpful. Part of my question, per above, would simply be the most appropriate metric for assessing model accuracy. When testing about including the loser's characteristics, should I assess accuracy based on the final prediction? or should I assess based on what the model says about the difference between choosing A or B (since the relative choice is all that matters)?
Comment: The point is that you have no way of knowing if a given choice is correct or not because you don't know what the teams' performance *would have been* had the other candidate been chosen.  The only relevant metric I can see here is the accuracy of the prediction given the characteristics of the leader
Comment: Your vote for this metric & feature set is helpful & if you put it in an answer with additional logic I will accept it. Thank you. In particular, if you would say more about why you prefer the absolute metric to the relative one I proposed, that is getting at the question.

I don't think it's right to say that we can't have any handle on the alternative choices and this means ignoring features. Losers' features may (or may not) have contextual value. Even a simple model y = x+1 makes a prediction for x=2.3 even if we don't see x=2.3 itself.
Answer: It's not a machine learning problem and it is a bad idea.
First, it is ethically dubious to have black-box software to make career decisions that would potentially influence the future of those employees. There are tons of research and real-life examples showing how machine learning algorithms can make biased decisions. Weapons of Math Destruction by Cathy O'Neil is a nice start to learning more.
Second, the choice needs to be based on past performance data. So if you have relevant data on the performance of candidates A and B, you just need to pick the one that performed better. If you don't have the data, you cannot make such a decision. So you need to come up with good metrics (relevant, measurable, etc) and make decisions based on them. You also need to give both candidates an equal chance to prove their worth. If you don't have such data, you don't have grounds for making the decision. If you have the data, you don't need machine learning. If you instead just threw some random data to the algorithm, you are risking getting a biased, useless, garbage in, garbage out result. If you had such data, you could use some simple, explainable algorithm like linear regression that could help you to find out how much should you weigh each of the criteria used for making the decision, but anything above that is dubious.
Finally, if you had such an algorithm, it may be bad for your organization in the long run. As noticed above, you risk legal and reputational costs if the algorithm ends up biased. You also risk that your employees get demotivated if they knew that career decisions are made by an "unpredictable" black-box algorithm. In such a case, people would not know what is expected of them to succeed, what is demotivating. They will not know how the decision is made, but this wouldn't stop them from gaming the system and doing all the crazy things that they perceive that the algorithm considers as advantageous for them.
I agree with you that arbitrary career decisions are not a good thing, but "AI" is not a solution here. I guess that the decisions are arbitrary because you don't have relevant data to make the decision. Whatever machine learning algorithm you pick, it would use the same crappy data available to people who made the decisions in the past. It would also need to learn from the data of "arbitrary" career decisions made by humans and it will end up repeating those decisions because this would be the only reality that it would know from the data. You rather need an organizational change, not machine learning.
Comment: This is a really negative and unhelpful response. This is a conceptual question for my learning about structuring predictive models. I don't work in anything related to hiring and firing decisions, I just gave a simple example to illustrate a type of problem.

I appreciate that your points are important for broad questions about ML, but it would have been helpful if you'd included these as a sidenote and addressed my main (conceptual) question. Just listing "linear regression" is not an answer to the question I asked which was about structure and metrics, not fit functions.


While executing an express application it crashed

Question: node .\\index.js
node:events:490
throw er; // Unhandled 'error' event
^

Error: listen EADDRINUSE: address already in use :::3000
at Server.setupListenHandle \[as \_listen2\] (node:net:1774:16)
at listenInCluster (node:net:1822:12)
at Server.listen (node:net:1910:7)
at Function.listen (D:\\Gamaca AI\\Express2\\node_modules\\express\\lib\\application.js:635:24)
at Object.\<anonymous\> (D:\\Gamaca AI\\Express2\\index.js:9:5)
at Module.\_compile (node:internal/modules/cjs/loader:1275:14)
at Module.\_extensions..js (node:internal/modules/cjs/loader:1329:10)
at Module.load (node:internal/modules/cjs/loader:1133:32)
at Module.\_load (node:internal/modules/cjs/loader:972:12)
at Function.executeUserEntryPoint \[as runMain\] (node:internal/modules/run_main:83:12)
Emitted 'error' event on Server instance at:
at emitErrorNT (node:net:1801:8)
at process.processTicksAndRejections (node:internal/process/task_queues:82:21) {
code: 'EADDRINUSE',
errno: -4091,
syscall: 'listen',
address: '::',
port: 3000
}

Node.js v19.8.1

$ node index.js

We tried to execute from this command.
Check it Out the code !
const express = require('express');
const app = express();

app.get('/', (res, req) => {
  res.send("Hello Rushikesh! ");
});

app.listen(3000, () => {
  console.log("App is lodding in Port no 3000 !");
});

Answer: The answer is in question.
Error: listen EADDRINUSE: address already in use :::3000

The port 3000 already in use.
You need to kill all process for this port before running your express or any app which use 3000 port.
For windows
Find PID of your process.
netstat -aon | findstr 3000

It will reponse like this message
  TCP    0.0.0.0:3000          0.0.0.0:0              LISTENING       2980
  TCP    [::]:3000             [::]:0                 LISTENING       2980

then kill process
taskkill /f /pid 2980

Answer: Make sure your port 3000 is available or try to run it on a different port.


Swift: add more lines in drop down options (make tableView cells bigger depending on content)

Question: I have this project where I use drop down options, which content are changing from time to time. Right now, if the content is wider than the width of the drop down, you will not be able to see all of the content. I want the options to be higher, the more content there are, so you always are able to see everything no matter how long the content are. I have tried following various guides on the internet, but the problem is that they have all made their tableViews in the viewController, and I have made mine programmatically. I hope it all makes sense. You can see the  problem and my code if you follow the link below
https://github.com/Rawchris/See-all-text-of-drop-down
I hope you are able to help ;)
Answer: add these lines to override init(frame: CGRect)
tableView.estimatedRowHeight = 50
tableView.rowHeight = UITableViewAutomaticDimension

then add numberOfLines = 0 to your UITableViewCell
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = UITableViewCell()

        cell.textLabel?.text = dropDownOptions[indexPath.row]
        cell.textLabel?.numberOfLines = 0
        cell.backgroundColor = UIColor.darkGray
        return cell
    }

Comment: Thank you for your answer! Maybe you also are able to answer my other question: https://stackoverflow.com/questions/61293578/swift-drop-down-height-bugs-at-first-click


Is it possible to get the actual sheet music for a particular song?

Question: I just started learning the piano after 25 years.
I'm trying to find sheet music for a particular song I want to play.
The internet is full of arrangements done by other people; however, I am wondering if there is a way to get the actual sheet music composed for the song?
Do artists submit sheets when they copyright a song? If so, is there a legitimate way to purchase access to them?
Comment: Very often there **is** no original sheet music. Singer-songwriters don't compose their pieces on paper, they usually don't play them from sheet music, they aren't in the business of selling notated music, and they don't particularly want others to copy their set lists. (When you live in a free-market society and some obvious good simply isn't to be had for sale, the most probable reason is that it doesn't exist in the first place.)
Answer: Generally speaking, no, songwriters do not submit sheet music when they copyright a song. If they do, and this is rare these days, it is usually only a "lead sheet" which has the melody line with the lyrics, and the chord symbols above the melody line, and nothing more.
There are a few areas of music where meticulously notated sheet music is published and available for sale or rent. One is that of compositions which are written for solo piano in the first place. Another is orchestral conductors scores and individual parts for each instrument/section in the orchestra, for music written for the symphony orchestra concert stage or for the soundtracks to motion pictures. These scores are most often available for rent, not for purchase, and are very expensive, because they can also involve licensing arrangements for the recipient to perform the works in public and sell tickets to the concerts.
The other example are scores for musical theater and opera productions. These are almost always strictly available for rental, and again, they are very expensive because the right to perform the work for profit (in a specific location, on specific dates) is negotiated into the rental agreement. All scores have to be returned to the renting agency when the performances are complete.
If you want to determine what scores might be available, start by identifying the publishing company through which the songwriter published the music. Then find out what sheet music company the publishing company works with to print, rent or sell scores. You need to assume that whatever printed sheet music titles you find are in fact simplified re-arrangements of the original, unless stated otherwise. The words "original score", "transcription" or "conductor's score" might indicate that you are getting what you want. But you might have to write to publishing companies and sheet music printing companies and ask questions before making a purchase.
Answer: There is not much I can add to Wheat's excellent answer.
As Wheat said, newer material is not likely to have sheet music included in the document submitted with the copyright registration package.  I am a songwriter and have registered my copyright on many of my songs.  But these days all I have to submit is a copy of the lyrics and a recorded sound file (such as an MP3) for the music.  Before being able to upload MP3 files through the internet, songwriter's and composers could register a copyright on a recorded work by submitting a cassette tape or CD via the mail.
I am guessing that prior to the ability to register a copyright on a recorded work, that it was more common to submit sheet music or something akin to it.  Songs and musical compositions registered with the US Copyright Office are available to the public for a fee.  To learn more about how to search what is on file at the US Copyright Office and obtain copies thereof - click this link Obtain Copies from Copyright Office
Obtaining a copy of a song from the copyright office,  does not give you authorization or license or the right to use the copyrighted work for commercial purposes - or to reproduce or copy it for distribution to others.  But if you use it to learn to play a song at home for your own enjoyment, I think you are safe.
You can purchase sheet music with full music notation for multiple instruments (including piano) from numerous sources.  But most of those are arrangements written out by someone who interpreted the original artists or songwriter's work.  Many of these arrangements may have been created under license or with permission from the copyright owner, but that still does not mean it was the original songwriter or composer who wrote the score or notation.
In probably more cases than not, the original writer or composer my have never written any sheet music or score for the song (I never do - and neither do any of the song writers I know) - so the only thing that will ever be available is sheet music created by someone who interpreted the song and arranged it according to what they hear in a recording.
If the song you want to play is a popular song, it is very likely that someone has taken the time to create a very authentic arrangement and published it (perhaps with permission) in fully notated sheet music form.  If you have not already tried it, I would enter Song Title Sheet Music in your internet search engine and see if that yields some results.  Alternatively - search for sheet music by the artists name as opposed to song title.  Often entire song books of sheet music are published for songs by a particular artists or for all the songs on a particular album.
Good luck.


Laravel - The requested URL was not found on this server

Question: O que eu fiz
Fiz um formulário que faz o cadastro dos dados no banco de dados. Localmente ele funcionou perfeitamente.
Problema
Ele simplesmente diz que não está encotrando a URL. É estranho, pois o erro abaixo diz que o index.php do public não foi encontrado, e caso estejam se perguntando, o action do formulário está certo, ele está chamando o método gerarPdf.
The requested URL /var/www/laravel/barcodeAssinatura/public/index.php was not found on this server.
url acessada
https://osite.com.br/pasta/barcode/
public/.htacces
<IfModule mod_rewrite.c>
    <IfModule mod_negotiation.c>
        Options -MultiViews
    </IfModule>

    RewriteEngine On

    # Redirect Trailing Slashes...
    RewriteRule ^(.*)/$ /$1 [L,R=301]

    # Handle Front Controller...
    RewriteCond %{REQUEST_FILENAME} !-d
    RewriteCond %{REQUEST_FILENAME} !-f
    RewriteRule ^ index.php [L]
</IfModule>

routes.php
Route::get('/', 'HomeController@index');
Route::post('gerarPdf', 'HomeController@gerarPdf');

OBS: Foi criado um Alias para que ao acessar o site ele chame o public/index.php.
Comment: Também estou com um erro assim. A rota post está retornando erro 301 Moved Permanently quando eu tento acessar por ajax. Porém a rota existe e é encontrada quando envio o formulário pela url de navegador.
Comment: Seu servidor é linux? você verificou se o mod_rewrite do apache está habilitado? A url que você especificou acima não condiz com os dados informados do route.php
Answer: eu resolvi esse problema removendo essa linha do .httaccess: RewriteRule ^(.*)/$ /$1 [L,R=301]


HtmlRouteProvider not found error

Question: I've just started using the Modal module version  4.1.15 and haven't made any changes to the file structure, now after clearing the cache I get this error:
Error: Class 'Drupal\modal_page\Entity\RouteProvider\ModalHtmlRouteProvider' not found in Drupal\Core\Entity\EntityTypeManager->createHandlerInstance() (line 272 of /var/www/html/core/lib/Drupal/Core/Entity/EntityTypeManager.php)
Is there a new class I need to create to serve a route to the function, or is this an easy fix?
Comment: Can you confirm the module is actually enabled?
Comment: It does allow itself to be enabled, but gives that same error upon enabling it.
Comment: You don't need to create classes for the module to work. If the module is using a wrong class for an entity handler, that's a bug with the module.
Comment: Actually, the [`Drupal\modal_page\Entity\RouteProvider\ModalHtmlRouteProvider`](https://git.drupalcode.org/project/modal_page/-/blob/4.1.15/src/Entity/RouteProvider/ModalHtmlRouteProvider.php) exists and it's used by the [`Modal`](https://git.drupalcode.org/project/modal_page/-/blob/4.1.15/src/Entity/Modal.php) class.
Answer: It seems the RouteProvider folder containing the class I needed was deleted somehow, dropping it back in and clearing the cache fixed the issue.

HtmlRouteProvider not found error


Additional basketball qualification tournaments for 2020 Olympics

Question: Helo! I would like to ask for some help in understanding how qualifications for Olympic men's basketball tournament at 2020 Olympics work.
Firstly, i know that there would be 12 teams at basketball's tournament. One of the places is reserved for the host nation's team, in this case Japan. Next seven places is going to be determined at the World Cup in the China next year:
https://en.wikipedia.org/wiki/Basketball_at_the_2020_Summer_Olympics_–_Men%27s_qualification
I have a problem in understanding how additional wild card tournaments are structured. I know that the best 16 teams from World Cup that didn't qualified by the World Cup, will participate in these wild card tournaments. Now, things get a little bit more unclear, because of the following picture:

So, my question is next:
If it is going to be 4 wild card tournaments with 6 teams in each, how can they add additional 2 teams per FIBA region in addition to 16 teams from World Cup, because that gives the number of 26 teams?
Please, could anyone clarify this a little bit more?
Answer: Based on the 2019 World Cup qualifying, it looks like the Asia and Oceania regions are combined into one region, so there are only 4 regions for the purposes of the "+2 from each region" detail. So they take the best remaining 16 teams regardless of region, then the next best two teams from each region.
Comment: Thank you! I guess that's how they are going to decide additional 2 tems per region. The fact that at the World Cup, Asian and Oceanian places are separated, confused me, because they are one region in qualifiers.


Passing lists to the view .Net Core

Question: Im looping through all the results from the SQL query in a .Net Core project. here is Model
    public class Mymessagesinfo
{
    public int MyMessagesCount { get; set; }

    public List<int> MessagesIDs { get; set; }
    public List<int> MessagesSendersid { get; set; }
    public List<string> MessagesSenders { get; set; }
    public List<string> MessagesTitles { get; set; }
    public List<string> MessagesInformation { get; set; }

    public List<string> MessagesStatus { get; set; }

}

I loop through the users messages in my controller then i pass that model to the view
sqlcon.Open();
        int? userid = HttpContext.Session.GetInt32("UserID");
        SqlCommand sqlcom = new SqlCommand("select * from messages where Messagereceiver=" +userid , sqlcon);
        SqlDataReader reader = sqlcom.ExecuteReader();
        if(reader.HasRows)
        {

            int index = 0;
            while(reader.Read())
            {
                string s;
                s = reader[0].ToString();

                Mymessages.MessagesIDs.Add(int.Parse(s));
                Mymessages.MessagesSendersid.Add(int.Parse(reader[1].ToString()));
                Mymessages.MessagesTitles.Add(reader[3].ToString());
                Mymessages.MessagesInformation.Add(reader[4].ToString());
                Mymessages.MessagesStatus.Add(reader[5].ToString());
                index++;
            }
            Mymessages.MyMessagesCount = index;

        }

the very first line Mymessages.MessagesIDs.Add(int.Parse(s));  it throws an exception saying System.NullReferenceException: 'Object reference not set to an instance of an object
i wanted to make sure that reader was holding the results so i added int s and checked on it and it was holding the value it was supposed to.
whats going wrong here? is this how we are supposed to pass list-like data to the view?
Comment: Does this answer your question? [Null Reference Exception for Class Lists](https://stackoverflow.com/questions/38510963/null-reference-exception-for-class-lists)
Answer: You need to initlize MessagesIDs in entity Mymessages, like this:
var Mymessages = new Mymessagesinfo()
{
    MessagesIDs = new List<int>()
};

Mymessages.MessagesIDs.Add(id);

Or just define the class like this,
public class Mymessagesinfo
{
    public int MyMessagesCount { get; set; }

    public List<int> MessagesIDs { get; set; } = new List<int>();
    public List<int> MessagesSendersid { get; set; } = new List<int>();
    public List<string> MessagesSenders { get; set; } = new List<string>();
    public List<string> MessagesTitles { get; set; } = new List<string>();
    public List<string> MessagesInformation { get; set; } = new List<string>();

    public List<string> MessagesStatus { get; set; } = new List<string>();

}

Answer: Here is how I would restructure what you have to make it work.
First, your model class:
public class Mymessagesinfo
{
    public List<MessageInfo> Messages { get; set; } = new List<MessageInfo>();
}

public class MessageInfo
{
    public int ID { get; set; }
    public int Senderid { get; set; }
    public string Sender { get; set; }
    public string Title { get; set; }
    public string Information { get; set; }
    public string Status { get; set; }
}

With this approach you have a list of message objects, instead of a bunch of lists containing property data.
Here is how I would suggest you load it from SQL Server:
    var data = new Mymessagesinfo();
    int? userid = HttpContext.Session.GetInt32("UserID");

    var messagesTable = new System.Data.DataTable("messages");
    using (var sqlcom = sqlcon.CreateCommand())
    {
        sqlcom.CommandText = $"select * from messages where Messagereceiver='{userid}'";
        using (var adapter = new SqlDataAdapter(sqcom))
        {
            adapter.Fill(messagesTable);
        }
    }
    // we are now done with SQL and have the data in memory...
    foreach(DataRow row in messagesTable.Rows)
    {
        data.Messages.Add( new MessageInfo {
            ID = row.Field<int>(0),
            Senderid = row.Field<int>(1),
            Sender = row.Field<string>(2),
            Title = row.Field<string>(3),
            Information = row.Field<string>(4),
            Status = row.Field<string>(5),
        });
    }

    return View(data);

 This is a lot cleaner and by using a DataAdapter and DataTable you minimize the amount of time that the connection to the database is connected.

Here is how you would use this model in an MVC View:
@Model Mymessagesinfo

     @foreach(var message in Model.Messages)
     {

 @message.Title - @message.Id

     }

Comment: this is awesome thank you so much. Data Reader was killing me

Passing lists to the view .Net Core


Ambiguous column name 'Created_Date'?

Question: I utilize SQL SSMS. Due to the following, SQL prompts error. After I utilized the same script with many other inner joins the following error remains. I have tried to modify my script, and I keep getting the same messages:
Msg 209, Level 16, State 1, Line 9 Ambiguous column name 'Created_Date'.
Msg 209, Level 16, State 1, Line 17 Ambiguous column name 'Created_Date'.
Msg 209, Level 16, State 1, Line 18 Ambiguous column name 'Created_Date'.
Msg 209, Level 16, State 1, Line 19 Ambiguous column name 'Created_Date'.
Msg 209, Level 16, State 1, Line 20 Ambiguous column name 'Created_Date'.

[My script]
 SELECT
 rs.Resident_ID,
 [UserName] = rsdt.First_Name + ' ' + rsdt.Last_Name,
 in.Invoice_Amount,
 in.Due_Date as due,
 in.Created_Date,
 DATEDIFF(day, [Created_Date], Getdate()) as " Number_of_Days ",
 in.Paid_Date as paid,
 in.Description,
 ar.Payment_Type,
 ar.Receipt_Descriptions,

 CASE
     WHEN DATEDIFF(day, [Created_Date], Getdate()) Between 90 AND 119 Then '90 days'
     WHEN DATEDIFF(day, [Created_Date], Getdate()) Between 120 AND 179 Then '120 days'
     WHEN DATEDIFF(day, [Created_Date], Getdate()) Between 180 AND 364 Then '180 days'
     WHEN DATEDIFF(day, [Created_Date], Getdate()) >= 365 Then '365+ days'
     END As [Days Outstanding]

   FROM dbo.ar_receipts AS ar
   INNER JOIN dbo.residents AS rs
   ON ar.Resident_ID = rs.Resident_ID

   INNER JOIN dbo.invoices AS in
   ON ar.Created_Date = in.Created_Date

   WHERE
   DATEDIFF(Day, in.Created_Date, GETDATE ()) > = 90
   AND in.Created_Date >= DATEADD(MONTH, -48, GETDATE())
   Order by in.Created_Date

Comment: Edited column name, it was just my thought process when originally building my question.
Comment: Does this answer your question? [Postgresql column reference "id" is ambiguous](https://stackoverflow.com/questions/9821121/postgresql-column-reference-id-is-ambiguous)
Answer: You have:
CASE WHEN DATEDIFF(day, [Created_Date], Getdate()) Between 90 AND 119

But the error message is clear: more than one table in your query has a column named Created_Date. So, you need to use the table aliases you created to tell SQL Server which one you mean. Presumably it is from dbo.invoices, so:
CASE WHEN DATEDIFF(day, in.[Created_Date], Getdate()) Between 90 AND 119

Though in is also a poor name choice for an alias because, like double, it is a reserved word/keyword and at the very least will light up in various editors or, in some contexts, cause a syntax error.
More importantly:
DATEDIFF(day, in.[Created_Date], Getdate()) >= 365

This is much more efficiently written as:
in.Created_Date < DATEADD(DAY, -365, CONVERT(date, GETDATE())

It's a few extra characters, I know, but that at least has a shot of using an index.
Also, if you traverse the opposite way (oldest category to newest), you don't have to handle the BETWEEN scenario at all, because the first scenario that matches will render the rest of the comparisons no-ops:
CASE
WHEN in.Created_Date < DATEADD(DAY, -365, CONVERT(date, GETDATE())
  THEN '365+ Days'
WHEN in.Created_Date < DATEADD(DAY, -180, CONVERT(date, GETDATE())
  THEN '180 Days'
WHEN in.Created_Date < DATEADD(DAY, -120, CONVERT(date, GETDATE())
  THEN '120 Days'
WHEN in.Created_Date < DATEADD(DAY, -90,  CONVERT(date, GETDATE())
  THEN '90 Days'
END AS [Days Outstanding]

You could also simplify it by:
DECLARE @today date = GETDATE();

CASE
WHEN in.Created_Date < DATEADD(DAY, -365, @today)
  THEN '365+ Days'
...

Comment: Answer: Your answer was correct, I needed to select the column from specific table, in this case I included "in.Created_Date" on the 'CASE WHEN' and then all data listed correctly. Thank you, very glad to receive your explanation, script logic worked just fine!
Answer: Both dbo.invoices and dbo.ar_receipts have a Created_Date column.
   INNER JOIN dbo.invoices AS in
   ON ar.Created_Date = in.Created_Date

You need to fully qualify each use of Created_Date as you did above.
For example, DATEDIFF(day, [Created_Date], Getdate()) as " Number_of_Days " needs to specify which table's Created_Date. Probably in.Created_Date, but only you can answer that for sure.

Ambiguous column name 'Created_Date'?


Why does the caret::train function generate an error if called with a formula instead of x,y?

Question: In the following example, the predict function generates an error when the model is produced by the caret::train function called with a formula (y~x).  The predict function works if the model was generated with an x,y specification.  Why is this? Should one use the x,y specification? Until now I thought it was just based on user preference?  Is there a way to make the predict function work with the formula specification?
I had thought the models might be different because of the use of factor variables. However, the models appear to produce identical regression equations.  There is no difference in the in-sample predictions.
library(ggplot2)
library(caret)
data("diamonds")
set.seed(42)
trainIndex <- createDataPartition(diamonds$price, p=0.8, list = FALSE)
train <- diamonds[trainIndex,]
test <- diamonds[-trainIndex,]
lm_formula <- train(
    price ~ ., train,
    method = "lm",
    trControl=trainControl(method="none")
)
lm_xy <- train(y = train$price,
                 x = train[,-which(colnames(train)=="price")],
                 method = "lm",
                 trControl=trainControl(method="none")
)

# the following generates the error shown beneath it
pred_formula <- predict(lm_formula$finalModel,test)
# Error in eval(predvars, data, env) : object 'cut.L' not found

pred_xy <- predict(lm_xy$finalModel,test)

# The following produces zero indicating the in-sample fits are identical
sum((lm_formula$finalModel$fitted.values-lm_xy$finalModel$fitted.values)^2)

Answer: The problem is caused by the fact you are not using caret predict function but rather predict.lm because of the class of
class(lm_xy$finalModel) #lm

If you just do
pred_formula <- predict(lm_formula, test)
pred_xy <- predict(lm_xy, test)

using caret predict.train which will predict upon the best model:
all.equal(pred_xy, pred_formula)
#TRUE

now if you check:
summary(lm_formula$finalModel)
summary(lm_xy$finalModel)

you will see the name of the contrasts in the formula case has `` around several  instances which prevents the default predict.lm from functioning correctly. This is not an issue for caret predict.train.


How to get the SerDe Properties of an existing Hive Table

Question: My colleague created a table in hive and added a tricky SerDe Regex. I'd like to see what the regex is but the "SHOW CREATE TABLE" command doesn't have it.
Is there any other way to view the SERDEPROPERTIES that a table was created with?
Example:
hive> CREATE TABLE foo (
  bar STRING
)
ROW FORMAT SERDE 'org.apache.hadoop.hive.contrib.serde2.RegexSerDe'
WITH SERDEPROPERTIES ( "input.regex" = "(.*)", "output.format.string" = "%1$s" );

OK
Time taken: 0.078 seconds

hive> SHOW CREATE TABLE foo;
OK
CREATE  TABLE foo(
  bar string COMMENT 'from deserializer')
ROW FORMAT DELIMITED
STORED AS INPUTFORMAT
  'org.apache.hadoop.mapred.TextInputFormat'
OUTPUTFORMAT
  'org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat'
LOCATION
  'maprfs:/user/hive/warehouse/foo'
TBLPROPERTIES (
  'transient_lastDdlTime'='1383248078')
Time taken: 0.091 seconds, Fetched: 11 row(s)

I'm using hive 0.11. Thanks!
Answer: You can do a describe extended which will show you everything about your table, including the serde properties you mentioned.
For example for your table:
$ hive -e "describe extended foo"
Detailed Table Information  Table(tableName:foo, dbName:default, owner:cloudera, createTime:1383250992, lastAccessTime:0, retention:0, sd:StorageDescriptor(cols:[FieldSchema(name:bar, type:string, comment:null)], location:hdfs://localhost.localdomain:8020/user/hive/warehouse/foo, inputFormat:org.apache.hadoop.mapred.TextInputFormat, outputFormat:org.apache.hadoop.hive.ql.io.HiveIgnoreKeyTextOutputFormat, compressed:false, numBuckets:-1, serdeInfo:SerDeInfo(name:null, serializationLib:org.apache.hadoop.hive.contrib.serde2.RegexSerDe, parameters:{output.format.string=%1$s, serialization.format=1, input.regex=(.*)}), bucketCols:[], sortCols:[], parameters:{}, skewedInfo:SkewedInfo(skewedColNames:[], skewedColValues:[], skewedColValueLocationMaps:{}), storedAsSubDirectories:false), partitionKeys:[], parameters:{transient_lastDdlTime=1383250992}, viewOriginalText:null, viewExpandedText:null, tableType:MANAGED_TABLE)

If you look in the object returned, you can see the interesting part below:
serdeInfo:SerDeInfo(name:null, serializationLib:org.apache.hadoop.hive.contrib.serde2.RegexSerDe, parameters:{output.format.string=%1$s, serialization.format=1, input.regex=(.*)})

Comment: how can we add new serde properties based on this out put ?


How to pass a parameter into a form upon creating?

Question: I have a form, which contains an additional field. And I want to initiate the field via the form constructor.
class ServicesForm extends FormBase {

    private $service_type;

    public function __constructor($_service_type){
        $this->service_type = $_service_type;
    }

The form is created in a controller.
class ServicesController extends ControllerBase {

    public function getServices($service_type){
        $data['form'] = \Drupal::formBuilder()->getForm('\Drupal\palom_services\Form\ServicesForm');

        return $data;
    }

Could you clarify me, how to pass the parameter $service_type to the form inside the controller method ?
Maybe, should I do it without FormBuilder and getForm ?
Answer: Just add it to your form's buildForm method signature:
public function buildForm(array $form, FormStateInterface $form_state, $arg = NULL) {
  // Use $arg
}

Then literally pass it to the form builder's getForm method:
$data['form'] = \Drupal::formBuilder()->getForm('\Drupal\palom_services\Form\ServicesForm', $service_type);

Answer: I have tried the Clive's solution, however, it breaks the interface of FormInterface.
In the \Drupal::formBuilder()->getForm() method, the code is the following:
  public function getForm($form_arg) {
    $form_state = new FormState();

    $args = func_get_args();
    // Remove $form_arg from the arguments.
    unset($args[0]);
    $form_state->addBuildInfo('args', array_values($args));

    return $this->buildForm($form_arg, $form_state);
  }

So you don't need to modify the signature of buildForm(), you should access these values from $form_state.
It should be usable this way: $form_state->getBuildInfo()['args']
Comment: Really good and clean method.


on Murray-von Neumann equivalence of range projections

Question: Let $M$ be a von Neumann algebra and $a\in A$. Then for the range projections $[a]\sim [a^\ast]$, since when $a=v|a|$ is the polar decomposition $v^\ast v$ is the projection onto $ran(v^\ast)=ker(v)^\bot=ker(a)^\bot=ran(a^\ast)$.
Apparently $vv^\ast$ is supposed to be the range projection of $a$, but how do I see this?
Thanks in advance!

Soultion: Now, in the view of daylight, I think my admittedly ridiculous problem was the following:
It is known (without having any further knowledge on the polar decomposition of $a^*$ that $vv^*$ is the orthogonal projection onto $ran\ v$ and that this is in fact:
$ran\ v = (ker\ v^*)^\bot \stackrel{!}{=} (ker\ a^*)^\bot = ran\ a^*$, beacause we also know from the polar decomposition of $a$, that $ran\ a =ran\ v$, which in turn implies : $(ran\ a)^\bot=(ran\ v)^\bot$ and $ker\ a^* = ker\ v^*$.
My brain was too stubborn to think that the indicated equation might be as easy as it is and is not due to knowing anything about the polar decomposition of $a^*$.
Thank you @Martin Argerami for your patience nevertheless!
Answer: You have
$$
\operatorname{ran} vv^*=(\ker vv^*)^\perp=(\ker v^*)^\perp=\overline{\operatorname{ran} a}.
$$
For the middle equality, it is true in general that $\ker x^*x=\ker x$. The inclusion $\ker x\subset\ker x^*x$ is trivial. The converse is easily seen if $x\in B(H)$: in that case, if $x^*x\xi=0$, then
$$
0=\langle x^*x\xi,\xi\rangle=\langle x\xi,x\xi\rangle=\|x\xi\|^2.
$$
Comment: Thanks, but I got the feeling I'm struggling more with the last equation:

Why is the kernel of $ker\ v^* = ker\ a^*$, i.e. how much of the polar decomposition of the adjoint do I know from the polar decomposition of the operator itself?
Comment: Not sure what you expect. In the proof above replace $a$ with $a^*$ and $v$ with $v^*$, and use $\overline{\operatorname{ran} a^*}=(\ker a)^\perp$ that you already established in your question.
Comment: is $|a|=|a^*|$?, it looks convincing, but $|a|=(a^*a)^{1/2}$ and $|a^*|=(aa^*)^{1/2}$ but then? $a$ needn't be normal, right?
Comment: No, they are not equal, unless $a$ is normal.
Comment: so , does $a^*=v^*|a^*|$ hold then? And if so : why is this? As |a| is hermitian this clearly could not come from anti multiplicity of the involution, otherwise I would not know why the kernels of $a^*$ and $v^*$ should coincide
Comment: The relation is $|a^*|=v|a|v^*$. At this stage, I  have no idea what your question is.


Views multiple entities output

Question: I am new to Drupal 7, so I hope I am using the word entity in the right context.
I am using the profile2 module to collect additional information when yours signup. Of course, the users are required to provide an email address and they can also upload a photo of themselves.
My issue is how to use the same view to return a users user information (email, username, photo) and all the profile2 collected information.
Comment: have you tried the ```profile2_page``` module? It's a part of the profile2 module.
Answer: When you create a view for users or the profile nodes, you should be able to add a relation to the other one. Not shure thou whether this works in both directions.

Views multiple entities output