how to acess Struct property by name as a string in runtime in swiftui

Question: i have an JSON RESPONSE
 result:
        [
            Result(date: "2022-04-24", abc: 1463, def: 0, ghi: 0.0),
            Result(date: "2022-04-25", abc: 1451, def: 0, ghi: 0.0),
            Result(date: "2022-04-26", abc: 24838, def: 100, ghi: 25.0),
            Result(date: "2022-04-27", abc: 72833, def: 461, ghi: 115.25),
            Result(date: "2022-04-28", abc: 31881, def: 0, ghi: 0.0),
            Result(date: "2022-04-29", abc: 18706, def: 0, ghi: 0.0)
        ],

, now in my code i am using picker and have to dynamically change the key
**example--->**
result.abc,
result.def,
result.ghi

Code where i have to dynamically change
HStack{

ForEach(downloads.indices, id: \.self){ index in

                if index == downloads.count-1 {

                    Text("\(downloads[index].abc)")
                        .font(.largeTitle.bold())
                        .foregroundColor(.white)

                }

            }
        }
        .frame(maxWidth: .infinity, alignment: .leading)

You can see in above code
downloads[index].**abc**

in place of this i need to change def and ghi but dhynamically
In my Home View where i call above file
@State var selectedScreen: [String] = ["abc","def", "ghi"]
BarGraph(downloads: dataservice.statsdetails, value: selectedScreen[pickerSelectedItem])

but if i pass it dynamically as a string it gives me error
  [1]: https://i.stack.imgur.com/l6kna.png

Can you help me how to solve this
Comment: You may find this helpful https://stackoverflow.com/questions/34994529/access-a-struct-property-by-its-name-as-a-string-in-swift
Comment: @Andrew Thanx but what my return type will be as i only have to return the property
Comment: You can't use the ForEach View with indices
Answer: A straightforward way is to add a function to your struct that returns the right value for a given key.
func stringProperty(for path: String) -> String {
    switch path {
    case "abc":
        return "\(abc)"
    case "def":
        return "\(def)"
    case "ghi":
        return "\(ghi)"
    default:
        fatalError("Unknown property name")
    }
}

Comment: let subvalue = stringProperty(for: value)

            ForEach(downloads.indices, id: \.self){ index in

                if index == downloads.count-1 {

                    Text("\(downloads[index].subvalue)")
                        .font(.largeTitle.bold())
                        .foregroundColor(.white)

                }

            }

it is giving me error ie. Cannot find 'stringProperty' in scope

can you tell me how i can call that function
Comment: As I said, add it to the struct (Result) and call it inside Text. `Text("(downloads[index].stringProperty(for: value)")`
Comment: one more thing, my function is returning two data type either int or double

 func intProperty(for path: String) -> Int {
        switch path {
        case "abc":
            return abc
        case "def":
            return def
        case "ghi":
            return ghi
        default:
            fatalError("Unknown property name")
        }

ghi is a double. how i can acheive this using this same function
Comment: I don't understand, this has already been done in the answer by returning a string for all types so you can use it in a `Text` component.
Comment: but this is another case i want to access the value in the property and abc and def is of int type and ghi is of double type

so in some part of my code i need to use the value so i make intproperty function

and now the problem is of return type

ghi is of double so it is giving me error

i need to use the value for computaion so how can i use it now
Comment: Access the value directly? If this is another case then perhaps you should ask another question.


Aplicaçao bubble sort com vetor aleatorio

Question: Pessoal alguém pode me ajudar com este código, tenho que utilizar o bubble sort para ordenar um vetor aleatório de n posições, porem não consigo resolver o erro.
#include <bits/stdc++.h>
using namespace std;

const int n=100;

int main()
{    int j,aux,i;
    //criando o vetor
    int *A=(int*) malloc(n*sizeof(int));

    //preenchendo o vetor.
    srand(time(NULL));
    for(int i=0; i<n; i++, A++)
    {
        *A=rand()%50*10;
    }
    //apontando o vetor para o primeiro elemento.,
    A-=n;
    //imprimindo o vetor.
    cout<<"Vetor aleatorio.";
    for(int i=0; i<n; i++, A++)
    {
        cout<< *A<<" ";
    }
    //ordena o vetor .
    for(i=0; i < (n-1); i++)
    {
        for(j=0; j < (n-i-1); j++)
        {
            if(*A[j] > *A[j+1])
            {
                aux=A[j];
                *A[j]=*A[j+1];
                *A[j+1]=aux;
            }
        }
    }
    //imprime o vetor ordenado
    cout<<"Vetor ordenado:\n";
    for(i=0; i<n; i++)
    {
        cout<<*A<<" ";
    }

}

Comment: A ideia é praticar ponteiros ? Porque incrementar o ponteiro do array no `for` com `A++` para logo a seguir fazer `A-=n;` é despropositado e propicio a erros, sendo essa uma das causas do erro
Comment: mesmo corrigindo o incremento do array, continua com o mesmo erro.
Answer: Vou assumir que a ideia é praticar a utilização de ponteiros.
Nesse caso faltaram algumas coisas e outras estão incorretas, sendo que o código deveria ficar assim:
int main()
{
    int j,aux,i;
    int *A=(int*) malloc(n*sizeof(int));

    srand(time(NULL));
    for(int i=0; i<n; i++, A++)
    {
        *A=rand()%50*10;
    }
    A-=n;

    cout<<"Vetor aleatorio.";
    for(int i=0; i<n; i++, A++)
    {
        cout<< *A<<" ";
    }
    A-=n; //faltou aqui voltar de novo para trás

    for(i=0; i < (n-1); i++)
    {
        for(j=0; j < (n-i-1); j++)
        {
            if(A[j] > A[j+1]) //sem *
            {
                aux=A[j];
                A[j]=A[j+1]; //sem *
                A[j+1]=aux; //sem *
            }
        }
    }

    cout<<"Vetor ordenado:\n";
    for(i=0; i<n; i++, A++) //faltou o A++
    {
        cout<<*A<<" ";
    }

}

Retirei os comentários que tinha no código para dar ênfase aos que coloquei face às alterações que fiz.
Os locais em que retirei o * como if(*A[j] > *A[j+1]) não precisam porque ao aceder a uma posição com a notação [] já esta a aceder ao valor apontado.
Veja o código a funcionar no Ideone
A minha sugestão é que não utilize esse padrão a menos que seja por mera prática de ponteiros. Avançar com um ponteiro de um array para a frente no for para no fim voltar para trás com A-=n; é complicado, obscuro e propicio a erros, como já se deve ter apercebido.
Seguindo esse meu conselho e caso não esteja apenas a praticar ponteiros, sugiro que escreva o programa antes assim:
int main()
{
    int *A=(int*) malloc(n*sizeof(int));
    srand(time(NULL));
    for(int i=0; i<n; i++){
        A[i]=rand()%50*10;
    }

    cout<<"Vetor aleatorio.";
    for(int i=0; i<n; i++){
        cout<< A[i]<<" ";
    }

    for(int i=0; i < (n-1); i++){
        for(int j=0; j < (n-i-1); j++){
            if(A[j] > A[j+1]){
                int aux=A[j];
                A[j]=A[j+1];
                A[j+1]=aux;
            }
        }
    }

    cout<<"Vetor ordenado:\n";
    for(int i=0; i<n; i++){
        cout<<A[i]<<" ";
    }

    return 0;
}

Repare que nesta versão apenas declarei as variáveis onde são estritamente necessárias ao invés de no topo do programa. Isto acaba por simplificar e melhorar a legibilidade do código.
Seria também melhor declarar o array estaticamente assim:
int A[n];

Mas vou assumir que a declaração no heap era um requerimento do programa.
Veja também esta versão no Ideone


Enable Password and Confirm Password fields in Registration form

Question: i want to have registration form in my drupal site, but that is limited to the fields email and username.
I also want to have fields "Password" and "Confirm Password" in the registration form, so that the user does not need to check his email for his password and can login to the site directly after registration.
How can i achieve this?
Answer: I think the LoginToboggan module can do everything you need.

The LoginToboggan module offers several modifications of the Drupal login system in an external module by offering the following features and usability improvements:

Allow users to login using either their username OR their e-mail
  address.
Allow users to login immediately.
  Provide a login form on Access Denied pages for non-logged-in (anonymous) users.
The module provides two login block options: One uses JavaScript to display the form within the block immediately upon clicking "log in". The other brings the user to a separate page, but returns the user to their original page upon login.
Customize the registration form with two e-mail fields to ensure accuracy.
Optionally redirect the user to a specific page when using the 'immediate login' feature.
Optionally redirect the user to a specific page upon validation of their e-mail address.
Optionally display a user message indicating a successful login.
Optionally combine both the login and registration form on one page.
Optionally have unvalidated users purged from the system at a pre-defined interval (please read the CAVEATS section of INSTALL.txt for important information on configuring this feature!).
Integrates with Rules module to do various tasks when a user validates via email validation process (see http://drupal.org/node/880904 for an example)
Comment: Any idea for Drupal 8 as this module isn't available yet?
Answer: I got it: I needed to de-select the checkbox that allows to enable the email confirmation of the users, which is listed under "User settings."
In Drupal 7, in admin panel, under Configuration > People > Account Settings > Registration and cancellation > deselect the checkbox: Require e-mail verification when a visitor creates an account.
Comment: But isn't it possible to ask for passwords, and get e-mail confirmation? Just to check if the e-mail excists...
Answer: User registration password module does exactly what you want.

Let users register with a password on the registration form when verification mail is required.
By default, users can create accounts directly on the registration form, set their password and be immediately logged in, or they can create their account, wait for a verification e-mail, and then create their password. With this module, users are able to create their account along with their password and simply activate their account when receiving the verification email.
Comment: I second that.

User Registrationpassword unblocks a user After users click the confirmation link in the e-mail they got after submitting the registration form.


When Class deconstructor is called, std::string throws an error

Question: I am new to coding, so please forgive me if this question seems stupid. I was writing my own List class to get a better understanding of how Lists are structured, but I ran into an issue. I dynamically allocated my list as I added more items to it, and the deconstructor on my program ran just fine with ints. However, as I was testing with std::string, I ran into an issue. It keeps throwing exceptions after my deconstructor is called(, even though (I'm fairly certain) I deleted the memory I allotted alone, and not theirs (read access violation).
I've tried using smart pointers instead of deleting the allocated memory in my deconstuctor, but that ends up having the same issue. Looking online, all I can seem to find is, "only delete with deconstructors," and, "don't have exception handling in deconstructors." Both of which are not even issues with what I've written.
Here is firstly, the relevant code (in my mind) to solving this.
#include <string>
#include <iostream>
using std::cout;
using std::cin;
using std::string;

template <class type>
class List
{
    struct Node
    {
        type data;
        Node* next;
    };

public:

    List();

    ~List();

    void addToList(type var);
private:

    Node head;
    Node *last, *lastAcc;

    unsigned int length, prevPos;
};

template <class type>
List<type>::~List()
{
    Node *prevPtr;
    lastAcc = head.next;

    while (lastAcc->next) // While the next pointer leads to something
    {
        // Go to that something, and delete the item you were on

        prevPtr = lastAcc;
        lastAcc = lastAcc->next;
        delete prevPtr;
    }

    delete lastAcc;
}

template <class type>
void List<type>::addToList(type var)
{
    if (length)
    {
        last->next = new Node;
        last = last->next;
        last->data = var;
    }
    else
    {
        head.data = var;
    }

    lastAcc = last;
    prevPos = length++;
}

template <class type>
List<type>::List()
{
    head.next = 0;
    prevPos = 0;
    lastAcc = last = &head;
    length = 0;
}

int main()
{
    string boi[] = { "Today is a good day", "I had an apple", "It tasted delicious" };

    List<string> multiString;

    for (int i = 0; i < 3; i++)
    {
        multiString.addToList(boi[i]);
    }
    return 0;
}

I expected the code to run just fine, and if I made an error, I thought the error would show up on my code. Not on std::string. Any help would be greatly appreciated.
[Edit] On an added note, [lastAcc] is abbreviated for last accessed; it's just something I implemented to make going through the lists faster than just having to start from 0 every time. [prevPos] shows the position of [lastAcc] in the list. Let me know if you need to see more of my code or explain anything~!
Comment: `#include "List.cpp"` Don't do that.
Comment: Welcome to Stack Overflow! Being new here, you should take the [tour] and read [ask]. Concerning your problem, you need to extract a [mcve] first. Chances are you will find the error yourself doing that, which is exactly why it is required.
Comment: The reason I used #include "List.cpp" is because I was getting a linking error with my template. An online guide pointed out that it was necessary to include the .cpp file instead of the .h file in order to get the templates to extend.
Comment: It is very hard to say what is causing the error. I doubt it comes from `std::string` anyway. On the other hand If you need specific list implementation, why don't you just wrap `std::vector` for your needs ?
Comment: Can you share the source of `decNumLists` you're calling at the end of the destructor?
Comment: Its a static function. Here's what it does.
```
template
void List::decNumLists()
{
 numLists--;
}
```
Comment: @MichaelD. Templates are typically placed in header files (unless you go with C++14 or later - it is then possible to place implementation in .cpp file). The tutorial you took mus have been very old and enforced bad behaviors.
Comment: I'd rather see `addToList` function. For example `while (lastAcc->next)` will fail if you don't initialize `next` to `nullptr`, right?
Comment: As for initializing next to nullptr, I set it to zero in the first and the second constructors. is that equivalent?
Comment: @freakish I see what you mean though about the last part, if head.next is 0 when called, delete lastAcc->next would probably give me an error. I'll fix that now, thank you
Comment: @MichaelD. That's for sure. Also I recommend running the code through a debugger. It's a bit long.
Answer: you aren't initialising last->next in addToList so iteration in your destructor falls off the end of the list. The correct code is:
void List<type>::addToList(type var)
{
    if (length)
    {
        last->next = new Node();
        last = last->next;
        last->data = var;
    }
    else
    {
        head.data = var;
    }

    lastAcc = last;
    prevPos = length++;
}

The difference is new Node() rather than new Node. The first value initialises POD types, the second doesn't.
Alternatively if you define a constructor for Node then new Node and new Node() will be equivalent:
struct Node
{
    Node(): next( 0 ) {}
    type data;
    Node* next;
};

For a small efficiency gain you could move your value into your node to prevent copies:
struct Node
{
    Node(): next( 0 ) {}
    Node(type && data): data( std::move( data ) ), next( 0 ) {}
    type data;
    Node* next;
};

template <typename T>
void addToList(T&& var)
{
    if (length)
    {
        last->next = new Node(std::move(var));
        last = last->next;
    }
    else
    {
        head.data = std::move(var);
    }

    lastAcc = last;
    prevPos = length++;
}

Comment: @MichaelD. the only difference between `class` and `struct` is that `struct` members are public by default and `class` members are private
Comment: I'd rather give `Node` some useful constructors than rely on the subtleties of value-initialization.
Comment: @SebastianRedl Is there any way to construct a struct? I thought that was class only
Comment: You can also define constructors for structs in C++. See here https://stackoverflow.com/questions/1127396/struct-constructor-in-c/1127406
Comment: @MichaelD. in other words, `struct` and `class` both declare a class.


Using COM ports with Virtual Server

Question: I have a couple of servers that I'd like to duplicate as guest instances in virtualserver. One of the applications that runs on them uses the COM ports to communicate between the two servers, and specifically through null-modem/laplink/etc cable.
I've thought about binding the to guest instances COM ports to the host server's COM ports (1 and 2) and then connecting the ports together on with a null-modem cable. Is there a way I can make this connection entirely through virtualserver's control panel without having to physically access my server (it's cold and noisy in there :) )?
Comment: VirtualBox does this out of the box. VirtualServer is kinda sucky IMHO
Answer: You can use a COM port redirector software to create virtual COM ports on both servers and connecting them by a TCP port. The linked Wikipedia page also provides links for both commercial and open source solutions.
Answer: I have a solution that works under VMWare. it uses named pipe for serial communication between two VM. (Be advised that modem signals will not be carried across so hardware handshaking will fail).
Under VMWare you would do this:
On the "client side" add:
serial0.present = "TRUE"
serial0.fileType = "pipe"
serial0.pipe.endPoint = "client"
serial0.yieldOnMsrRead = "TRUE"
serial0.startConnected = "TRUE"
serial0.fileName = "/Virtual Machines/VMware/Serial/devbox_com1"

and this on the server side:
serial0.present = "TRUE"
serial0.fileType = "pipe"
serial0.yieldOnMsrRead = "TRUE"
serial0.startConnected = "TRUE"
serial0.fileName = "/Virtual Machines/VMware/Serial/devbox_com1"

This solution, of course does not apply exactly the same way for server 2005 but I would assume it should work (but I have not tested it).
Under Virtual Server 2005 follow these steps for both VM:

Under Virtual Machines, point to Configure, and then click the virtual machine that you want to modify.
Click the COM ports link.
Under the serial port that you want to configure, click Physical computer serial port, and then click to clear the Wait for modem command to open port check box. Click Named pipe, and then type \.\pipe\name that you want to assign to the named pipe in the Named pipe box. For example, type \.\pipe\com2 and Click OK.

I must warn you that I never tried to get two named pipe setup under Virtual Server 2005 so I do not make guaranty.
Comment: Just realized the question applied to Microsoft Virtual Server... oups! I leave the answer since I had to search a lot to get this. It will definitively not work in this case.
Answer: Using a remote terminal server like a Moxa (http://www.moxa.com/product/NPort_6450.htm) is a common approach.
The serial devices all connect into the Moxa terminal server, then a windows Virtual COM port driver is installed on the VMWare Guest OS. The Virtual COM port driver is configured with the IP address of the Terminal server.
The advantage of this approach is that your virtual server becomes completely hardware independent, you can move the image around to any physical server, and as long as there's IP connectivity to your terminal server, nothing breaks.

Using COM ports with Virtual Server


Prove $(\frac{a}{b-c})^2+(\frac{b}{c-a})^2+(\frac{c}{a-b})^2 \geq 2$

Question: If $a, b, c$ are distinct real numbers, prove that
$(\frac{a}{b-c})^2+(\frac{b}{c-a})^2+(\frac{c}{a-b})^2 \geq 2$
I thought of using AM-GM but that is surely not getting me anywhere ( Maybe some step before i can do AM-GM ?)
I thought of applying AM-GM but that clearly doesnt give anything. Then i thought if a assuming \txtWloga>b>c, that would make the first time greater than 1 so if only i could show that the sumof the other two terms is ≥1 i'd be done but ofc i couldn't progress further from there.
Thanks.
Comment: I solved your problem. If you want to see my solution, show please your attempts.
Comment: I thought of applying AM-GM but that clearly doesnt give anything. Then i thought if a assuming Wlog $a>b>c$, that would make the first time greater than 1 so if only i could show that the sumof the other two terms is $\geq1$ i'd be done but ofc i couldn't progress further from there. Sorry for not mentioning this in the post. Also extremely sorry if i missed anything really obvious as m not really good at it but m still trying hard.
Comment: This has been asked and answered before, e.g. here: https://math.stackexchange.com/questions/2724332/proving-expression-geq-2-where-variables-are-x-y-z.
Answer: $$\sum_{cyc}\frac{a^2}{(b-c)^2}=\left(\sum_{cyc}\frac{a}{b-c}\right)^2-2\sum_{cyc}\frac{ab}{(b-c)(c-a)}=$$
$$=\left(\sum_{cyc}\frac{a}{b-c}\right)^2-2\sum_{cyc}\frac{ab(a-b)}{\prod\limits_{cyc}(a-b)}=\left(\sum_{cyc}\frac{a}{b-c}\right)^2+2\geq2.$$
Comment: @Aayam Mathur Just always prove inequalities. It's a beautiful section. You'll know very many ways to proving inequalities. I think the best place to learn inequalities it's here: https://artofproblemsolving.com/community/c6t243f6_inequalities Just read it.
Comment: You answered an identical question before: https://math.stackexchange.com/a/2724454.
Comment: Fantastic Solution! Could you please provide some tips on attacking inequalities O' inequalities God?
Comment: Will surely have a look at those questions! So practice is the key eh? Thanks!
Answer: Note
$$ \sum a(2a-b-c)=2(a^2+b^2+c^2-ab-bc-ca),$$
and
$$\sum (b-c)^2(2a-b-c)^2=2(a^2+b^2+c^2-ab-bc-ca)^2.$$
Therefore, according to the Cauchy-Schwarz inequality we have
$$\sum \frac{a^2}{(b-c)^2} \geqslant \frac{\left[a(2a-b-c)+b(2b-c-a)+c(2c-a-b)\right] ^2}{(b-c)^2(2a-b-c)^2+(c-a)^2(2b-c-a)^2+(a-b)^2(2c-a-b)^2}=2.$$
Comment: As mentioned in the comments, this question is a duplicate. Since you have a new solution, I would appreciate it if you post your answer in the [original question](https://math.stackexchange.com/questions/2724332/proving-expression-geq-2-where-variables-are-x-y-z).


domain of convergence: Laplace transform of $\sin{bt}$

Question: To find Laplace transform of $\sin{bt}$, I get

How to find the domain of convergence.
Attempt:
It seems to me that it will be for all $s-ib>0$ (the domain for $\mathscr{L}(e^{bt})$ is $\forall ~s-a>0$) but the actual answer I know $s>0$.
Also $\mathscr{L}(e^{at}\sin{bt})=\frac{b}{(s-a)^2+b^2}$ then what will be domain of convergencce of $\mathscr{L}(e^{at}\sin{bt})$?
Answer: Note that the Laplace Transform of $\sin(bt)$ is given by
$$\mathscr{L}\{\sin(bt)\}(s)=\int_0^\infty \sin(bt)e^{-st}\,dt \tag 1$$
We have the estimate
$$\left|\int_0^L \sin(bt)e^{-st}\,dt\right|\le \int_0^L e^{-\text{Re}(s)t}\,dt=\frac{1-e^{-\text{Re}(s)L}}{\text{Re}(s)}$$
Evidently, the integral in $(1)$ converges whenever $\text{Re}(s)>0$.
If $\text{Re}(s)\le  0$, then it is easy to see that the integral diverges.
Therefore, the domain of convergence is $\text{Re}(s)>0$ as was to be shown!
Comment: $$\text{Re}(s-a)>0$$
Comment: then what will be the domain of convergence of $\mathscr{L}(e^{at}\sin{bt})=\frac{b}{(s-a)^2+b^2}$?


AngularJS - text input value not reflecting in scope variable

Question: I have an input text field as :
<input type="text" class="form-control" id="inputValue" name="uservalue" ng-model="inputNumber" ng-required="true" autofocus="true" ng-blur="checkIfValid()"/>

My controller has the ng-blur function as follows:
$scope.checkIfValid = function(){
        console.log("Value is = " + $scope.inputNumber);
}

I have defined - $scope.inputNumber = '';
My console.log shows an empty value even though I input a value in the text field and hit 'Tab' or move on to the next field to invoke the ng-blur function.
What am I doing wrong here?
`
Comment: Possible plunker ?
Comment: 1) Did you by any chance forget to add `ng-app` and `ng-controller `? 2) Change `ng-blur` to `ng-change`. 3) add a `$watch` for `inputValue` and see if it displays anything in the log
Comment: try with ng-change instead ng-blur for debug purposes. also +1 for a plunker detailing the problem.
Comment: agreed on a plunker - how are the controller/directives tied together?
Comment: Does your console displays `Value is = ` or does it not display anything?
Comment: You should try `keyup` instead of `blur`.
Comment: I tried exactly the same code of yours, and it works in my local. So, I agree with @KaushalNiraula that you should check if the function`checkIfValid()` is called.
Comment: The plunker seems to be working fine - it's something in my code - I can see the "Value is = " in my console.log .. i need to work with ng-blur because I need to send the entire text input to my API. Not sure what I am missing :(
Answer: Check this

var app = angular.module("myapp", []);
app.controller("myCtrl", ['$scope', function($scope) {
    $scope.inputNumber="new";

  $scope.checkIfValid = function(){
        console.log("Value is = " + $scope.inputNumber);
}

}]);

   <input type="text" class="form-control" id="inputValue" name="uservalue" ng-model="inputNumber" ng-required="true" autofocus="true" ng-blur="checkIfValid()"/>

{{inputNumber}}

Comment: Even though your answer is correct - this is what worked for me :

I passed inputNumber as a parameter to checkifValid(inputNumber) and then the value enters my controller, any idea why this is happening?
Comment: Hi,  i didnot get ,  you want to pass value as parameter
Comment: Yeah - I passed the ng-model as a parameter , and that worked - I can get the value now in my controller .. but $scope.inputNumber doesn't seem to be binding to the value in input in the text box - any idea why?


Change styles to toggled divs

Question: Im using filtered divs and I want to change the flex-direction of each section only when that specific section is toggled, then go back to original styles when going back to "Show all"
Here is the link for the filtered divs
https://www.w3schools.com/howto/tryit.asp?filename=tryhow_js_filter_elements
Comment: Have you tried anything that is not on w3School ?
Comment: Welcome to StackOverflow, in future you would be well served to show what attempts you have made to solve the problem instead of just providing a link to W3Schools (there are much better resources out there) . For example you mention flex-direction, yet your example doesn't even involve flex. At the minimum you should have reworked the W3Schools version to use flex and attempt to solve the direction switch yourself. The easier you make  it for us to help you the more help (and less downvotes) you will get.
Answer: I didn't understand what you meant by "flexible steering", would it be to replace the phrase "Show all" with the active section? This can be done with jquery, but you would have to replace the element that houses the text.

<button type="button" id="all">Show all</button>
<button type="button" id="cars">cars</button>

Alternative without jquery

<button id="all">Show All</button>
<button id="cars" onclick="cars()">Cars</button>

Alternative to build the tab without so much javascript and css

Bootstrap Collapse: You can use Bootstrap Colapse which already has a structure ready and you would only have to organize the HTML with the divs as per the documentation: https://getbootstrap.com/docs/4.0/components/collapse/

Javascript behavior: Like the previous one, this is a tabbed browsing API, which is identical to the code you are using, with the difference that here you would be using the Bootstrap structure and will not require many modifications, you should note the similarity between this and the previous one, in fact what changes is only the usability, the situations in which you will use one or the other, but the purpose is the same, both seek to hide elements.
https://getbootstrap.com/docs/4.0/components/navs/#javascript-behavior
Comment: jQuery is REALLY not needed here
Comment: It depends on what he intends to do, as I understand it, he wants the text "show everything" to be replaced by the text of the button that the user clicks, that is, the button would change its position and become the first, what I suggested was just change the text instead of changing the position of the button, it seems to me that he does not want to change the active button, but rather to change the position.
Comment: Can still be easily done without jQuery (and I love jQuery)
Answer: The W3 Schools code is not very good. It can be improved greatly but the use of data attributes, proper event listeners and  event bubbling
All we need to to to get your "flex switch" happening is add/remove a class to the ".container" to indicate if filtered or not

var container = document.querySelector(".container");

//Add an event listener to the div containing the buttons
document.getElementById("myBtnContainer").addEventListener("click", function(event) {

  //remove active class from previous active button
  this.querySelector(".active").classList.remove("active");
  //add active class to clicked item
  event.target.classList.add("active");

  //Add filitered to ".container" if "All" clicked, remove otherwise
  container.classList.toggle("filtered", event.target.dataset.target !== "all")

  //Display chosen elements
  var elements = container.querySelectorAll(".filterDiv");
  for (var i = 0; i < elements.length; i++) {
    //Long version of below
    //var categoryArray = elements[i].dataset.category.split(",");
    //var hasTargetCategory = categoryArray.includes(event.target.dataset.target);
    //elements[i].classList.toggle("show",hasTargetCategory);

    elements[i].classList.toggle("show", elements[i].dataset.category.split(",").includes(event.target.dataset.target));
  }
})
.filterDiv {
  background-color: #2196F3;
  color: #ffffff;
  width: 100px;
  line-height: 100px;
  text-align: center;
  margin: 2px;
  flex: none;
}

.container {
  margin-top: 20px;
  display: flex;
  flex-wrap: wrap;
}

/* Style the buttons */

.btn {
  border: none;
  outline: none;
  padding: 12px 16px;
  background-color: #f1f1f1;
  cursor: pointer;
}

.btn:hover {
  background-color: #ddd;
}

.btn.active {
  background-color: #666;
  color: white;
}

/*Class to change flex direction*/
.filtered {
  flex-direction: column;
}

/*Hide elements without the show class*/
.filtered>.filterDiv:not(.show) {
  display: none;
}

  <button class="btn active" data-target="all"> Show all</button>
  <button class="btn" data-target="cars"> Cars</button>
  <button class="btn" data-target="animals"> Animals</button>
  <button class="btn" data-target="fruits"> Fruits</button>
  <button class="btn" data-target="colors"> Colors</button>

BMW

Orange

Volvo

Red

Mustang

Blue

Cat

Dog

Melon

Kiwi

Banana

Lemon

Cow

Change styles to toggled divs


What are the limitations and challenges we have to face migrating from a VS lower version to higher version

Question: I am to migrate my asp.net, c# application from a lower version to higher version VS2012 I want to know what are the limitations and challenges we have to face.
Comment: It is a real question that i dont find suitable soultion yet..
Answer: Check out MSDN for compatibility and upgrading to VS2012  http://msdn.microsoft.com/en-us/library/vstudio/hh266747.aspx they know better than most of us here would.  I would say that going from 2010 to 2012 has so far been pretty easy for us, with the exception of database projects there really hasn't been much conversion.


attr_accesor method for write classes in ruby

Question: need help, I want to use the "attr_accesor" method to save space in the code and use it instead of "get_value" and "set_value", but how?
If the code is:
class Thing
    def initialize(aName, aDescription)
        @name = aName
        @description = aDescription
    end

    def get_name
        return @name
    end

    def set_name(aName)
        @name = aName
    end

    def get_description
        return @description
    end

    def set_description(aDescription)
        @description = aDescription
    end
end

class Treasure < Thing
    def initialize(aName, aDescription, aValue)
        super(aName, aDescription)
        @value = aValue.to_f
    end

    def get_value
        return @value
    end

    def set_value(aValue)
        @value = aValue.to_f
    end
end

t1 = Thing.new("Rock", "costless thing")
puts "Name: #{t1.get_name}"
puts "Description: #{t1.get_description}"

puts ""
puts "Treasure"
t2 = Treasure.new("Nugget", "A gold Nugget", "50000")
puts "Name: #{t2.get_name}"
puts "Description: #{t2.get_description}"
puts "Value: #{t2.get_value}"

Can you tell how to rewrite Thing and Treasure classes using attr_accesor method?
Comment: Use two spaces for indentation.
Answer: You just add them to your class definition, for Thing class you need to add
attr_accessor :name, :description

and for Treausre class you need,
attr_accessor :value

and it will expose both getter and setter methods in your class,
If you just need to define getter or setter you can use the following,
attr_reader -> getter method
attr_writer -> setter method

your classes should now look like
class Thing
  attr_accessor :name, :description

  def initialize(name, description)
    @name = name
    @description = description
  end
end

class Treasure < Thing
  attr_accessor :value

  def initialize(name, description, value)
    super(name, description)
    @value = value.to_f
  end
end

Now you can do things like
t1 = Thing.new("Rock", "costless thing")
puts "Name: #{t1.name}"
puts "Description: #{t1.description}"

puts ""
puts "Treasure"
t2 = Treasure.new("Nugget", "A gold Nugget", "50000")
puts "Name: #{t2.name}"
puts "Description: #{t2.description}"
puts "Value: #{t2.value}"

Comment: If you are using `attr_accessor :name`, you don't need to do `@name = aName`. Do `self.name = aName` instead. Also, please mention naming conventions for variables. `aName` can be simply `name`.
Comment: This code behaves slightly different than `Treasure#set_value`. In original code, you convert the value to float before assigning. With `attr_accessor`, that is not possible.
Comment: ok, for the code:
t1 = Thing.new("Rock", "costless thing")
puts "Name: #{t1.get_name}"
puts "Description: #{t1.get_description}"
What could be the reorder to use the new class "Thing"?
Comment: I think you are correct about the float conversion but I think its better to use @ notation instead of self. because self. could get confusing if OP writes an instance method name to maybe format with name in some way
Comment: I don't think there is an issue with float, the initialize block takes care of it
Comment: `self.note=` is about twice as slow as `@note=` in most situations, although these speed comparisons are relative where each is fast and the difference would be negligible in any application. I personally prefer the `@note=` syntax unless there is any additional logic in the setter, but I am uncertain what the "convention" or "accepted" way is
Answer: Just to add to the already good answer here, attr_accessor is really nothing more than a shortcut to define those getter and setter methods for you.
This:
attr_accessor :index

Will literally do this for you without any additional code:
def index
  return @index
end

def index=(value)
  @index = value
end

If you are familiar with C languages, think of it as a macro for defining basic getter and setters for you without the extra typing. As already stated, the attr_reader will define a getter only, attr_writer a setter only, while attr_accessor does both.
Note that none of these will actually define the instance variable @index simply by placing them in your code, that will still need done elsewhere in your code, such as @index = -1 in your initialize method (or wherever is most appropriate in your code) if you need a "default" value.


What is the unit of "mem" and "memory" in /proc/net/sockstat

Question: What is the unit of mem and memory in /proc/net/sockstat? Bytes, KBytes, Pages?
[kbrandt@ny-kbrandt01: ~] cat /proc/net/sockstat
sockets: used 153
TCP: inuse 7 orphan 0 tw 0 alloc 8 mem 1
UDP: inuse 4 mem 3
UDPLITE: inuse 0
RAW: inuse 0
FRAG: inuse 0 memory 0

Answer: There seems to be no documentation of this besides the kernel source itself, and I presume you don't want to dig quite that deep.
After digging through several pages of search results I finally found one forum post from someone who apparently did read the kernel source, which claims that the mem values for TCP and UDP are in kernel pages, while the memory value in FRAG is in bytes.
I glanced at the corresponding sources myself, and this seems to be true. Though, I am no kernel expert and frequently get lost in that maze...


How to interpret these custom contrasts?

Question: I am doing a one way ANOVA (per species) with custom contrasts.
     [,1] [,2] [,3] [,4]
0.5    -1    0    0    0
5       1   -1    0    0
12.5    0    1   -1    0
25      0    0    1   -1
50      0    0    0    1

where I compare intensity 0.5 against 5, 5 against 12.5 and so on. These is the data I'm working on

with the following results
Generalized least squares fit by REML
  Model: dark ~ intensity
  Data: skofijski.diurnal[skofijski.diurnal$species == "niphargus", ]
       AIC      BIC    logLik
  63.41333 67.66163 -25.70667

Coefficients:
            Value Std.Error  t-value p-value
(Intercept) 16.95 0.2140872 79.17334  0.0000
intensity1   2.20 0.4281744  5.13809  0.0001
intensity2   1.40 0.5244044  2.66970  0.0175
intensity3   2.10 0.5244044  4.00454  0.0011
intensity4   1.80 0.4281744  4.20389  0.0008

 Correlation:
           (Intr) intns1 intns2 intns3
intensity1 0.000
intensity2 0.000  0.612
intensity3 0.000  0.408  0.667
intensity4 0.000  0.250  0.408  0.612

Standardized residuals:
       Min         Q1        Med         Q3        Max
-2.3500484 -0.7833495  0.2611165  0.7833495  1.3055824

Residual standard error: 0.9574271
Degrees of freedom: 20 total; 15 residual

16.95 is the global mean for "niphargus". In intensity1, I'm comparing means for intensity 0.5 against 5.
If I understood this right, the coefficient for intensity1 of 2.2 should be half the difference between means of intensity levels 0.5 and 5. However, my hand calculations don't match those of the summary. Can anyone chip in what am I doing wrong?
ce1 <- skofijski.diurnal$intensity
levels(ce1) <- c("0.5", "5", "0", "0", "0")
ce1 <- as.factor(as.character(ce1))
tapply(skofijski.diurnal$dark, ce1, mean)
       0    0.5      5
  14.500 11.875 13.000
diff(tapply(skofijski.diurnal$dark, ce1, mean))/2
      0.5       5
  -1.3125  0.5625

Comment: Could you provide the lm() function from R that you used to estimate. How exactly did you use the contrasts function?
Comment: @flies since my question, there's been an introduction of `geom_jitter`, which is a shortcut for all the geom_point() parameters that jitter.
Comment: I didn't notice the jitter there. does `geom_jitter(position_dodge)` work? I've been using `geom_points(position_jitterdodge)` to add dots to boxplots with dodging.
Comment: @flies see the docs for `geom_jitter` [here](https://ggplot2.tidyverse.org/reference/geom_jitter.html). In my experience since my above answer, I find it unnecessary to use boxplots. Ever. If I have many points, I use violin plots which show density of points in much finer details than boxplots. Boxplots were invented back when plotting many points or their densities was not convenient. Perhaps it's time we start thinking of dropping this (handicapped) visualization.
Comment: btw `geom_points(position=position_dodge(width=0.75))` will fix the way the points in your plot don't line up with the boxes.
Answer: The matrix you specified for the contrasts is correct in principle. To convert it into an appropriate contrast matrix, you need to calculate the generalized inverse of your original matrix.
If M is your matrix:
M

#     [,1] [,2] [,3] [,4]
#0.5    -1    0    0    0
#5       1   -1    0    0
#12.5    0    1   -1    0
#25      0    0    1   -1
#50      0    0    0    1

Now, calculate the generalized inverse using ginv and transpose the result using t:
library(MASS)
t(ginv(M))

#     [,1] [,2] [,3] [,4]
#[1,] -0.8 -0.6 -0.4 -0.2
#[2,]  0.2 -0.6 -0.4 -0.2
#[3,]  0.2  0.4 -0.4 -0.2
#[4,]  0.2  0.4  0.6 -0.2
#[5,]  0.2  0.4  0.6  0.8

The result is identical to the one of @Greg Snow. Use this matrix for your analysis.
This is a much easier way than doing it manually.

There is an even easier way to generate a matrix of sliding differences (a.k.a. repeated contrasts). This can be done with the function contr.sdif and the number of factor levels as a parameter. If you have five factor levels, like in your example:
library(MASS)
contr.sdif(5)

#   2-1  3-2  4-3  5-4
#1 -0.8 -0.6 -0.4 -0.2
#2  0.2 -0.6 -0.4 -0.2
#3  0.2  0.4 -0.4 -0.2
#4  0.2  0.4  0.6 -0.2
#5  0.2  0.4  0.6  0.8

Answer: If the matrix at the top is how you are encoding the dummy variables (what you are passing to the C or contrast function in R) then they the first one is comparing the 1st level to the others (actually 0.8 times the 1st subtracted from 0.2 times the sum of the others).
The second term compares the 1st 2 levels to the last 3.  The 3rd compares the 1st 3 levels to the last2 and the 4th compares the 1st 4 levels to the last one.
If you want to do the comparisons that you describe (compare each pair) then the dummy variable encoding that you want is:
      [,1] [,2] [,3] [,4]
[1,] -0.8 -0.6 -0.4 -0.2
[2,]  0.2 -0.6 -0.4 -0.2
[3,]  0.2  0.4 -0.4 -0.2
[4,]  0.2  0.4  0.6 -0.2
[5,]  0.2  0.4  0.6  0.8

Comment: The `aov` function calls the `lm` function to do the main computations, so things like contrast matrices will have the same effect in both.
Comment: Is the use of this generalized inverese matrix also necessary when using `aov()` instead of `lm()`? I'm asking, because I have read several tutorials, in which contrast matrices for `aov()` are constructed just as the one given by Roman. E.g. see Chapter 5 in http://cran.r-project.org/doc/contrib/Vikneswaran-ED_companion.pdf


Is there an iterative procedure that pushes the singular values of a matrix toward unity?

Question: Consider a square matrix $A = U \Sigma V^T$.  I want to find $B = UV^T$ — however, it seems wasteful to compute the whole SVD just to re-multiply the two orthogonal matrices.
Does there exist some stable procedure I can use to "push" the entries in the diagonal matrix $\Sigma$ toward ones?
Comment: A related question is discussed in the paper "[Parameter selection and preconditioning for a graph form solver](http://stanford.edu/~boyd/papers/pogs.html)" by Fougner and Boyd at Stanford.
Comment: I doubt that it is possible. Because, To calculate SVD, first one usually finds the diagonal matrix and $U$. $V$ is found such that $A=UDV^T$. Remember that $U$ and $V$ are not unique.
Answer: Set $A_0=A$ and $A_n = (1/2)(A_{n-1}+(A_{n-1}^T)^{-1})$. I claim $A_n \to UV$, and does so rapidly.
Define $f(x) = \frac{x+x^{-1}}{2}$. Suppose $A=UDV$ where the diagonal entries of $D$ are $\sigma_1$, $\sigma_2$, ..., $\sigma_k>0$. Then induction shows that $A_n = U D_n V$ where $D$ is diagonal with entries $f^{(n)}(\sigma_j)$. (Here $f^{(n)}$ means iterate $f$ for $n$ times.) For any $\sigma>0$, $f^{(n)}(\sigma) \to 1$, and does so quite rapidly: $|f^{(n)}(\sigma)-1|$ shrinks like $1/\exp(c \cdot 2^n)$.
Disclaimer: I have not tested this method.
Comment: It is called Heron's method. It can be [refined to speed up](https://en.wikipedia.org/wiki/Polar_decomposition#Numerical_determination_of_the_matrix_polar_decomposition). Similar method by Halley (the same link) can be applied to rectangular matrices too.
Comment: @A.G. Thanks for the reference.
Answer: David , 1. Note that $x\rightarrow (x+1/x)/2$ is the Newton iteration for the calculation of an approximation of $\sqrt{1}$. If $\sigma =1000\approx 2^{10}$, one needs more that $10$ iterations.

What is the interest ? Each matricial iteration has complexity $\sim n^3$; compare with the cost of the calculation of the SVD (in $O(n^3)$) and the multiplication $UV^T$ ($\sim n^3$).
The OP assumes (if I correctly understand his question) that the singular values are unknown. How do you write your iteration ? Anyway, the calculation of the singular values is also in $O(n^3)$.
The couple $U,V$ is not unique but I think that $UV^T$ is unique.
Comment: Regarding 3: I'm iterating the recursion $A_0 = A$, $A_{n+1} = (1/2) (A_n + (A_n^T)^{-1})$. There is no step at which I explicitly compute the SVD. I simply use the fact that the SVD exists to show why this recursion has the convergence properties it does.
Comment: Regarding 2: Basic order of magnitude complexity analysis gives $O(n^3)$ for both methods, so the question is presumably about actual constants and numerical stability. I'm not an expert enough on this subject to know which is better, but the fact that this turned out to be a named method for doing SVD suggests it is not terrible.
Comment: I'm not sure why the OP wanted an iterative procedure of this sort. One reason might be that his or her singular values are all very close to equal (for example, because the input is nearly orthgonal.) In that case, computing the precise matrices $U$ and $V$ will be numerically unstable, while $U V^T$ will be stable, and I would guess that this method should be better since it never goes through the computation of $U$ and $V$.
Comment: @ David Speyer , of course, I agree with your comments. Some remarks: For your 1. OK, each step has complexity $\sim n^3$. For your 2. Indeed the question is about the constants. To calculate the eigenvalues of a generic matrix is at least $\sim 20n^3$. Yet, when the matrix is symmetric, I think that the complexity is lower. For your 3. I think that it is you best argument.  On the other hand, if we consider on $M_n$ the standard inner product $tr(K^TL)$, then when $A$ is invertible, $UV$ is the "orthogonal projection" of $A$ on $O(n)$.


Johansen test - r studio , "ect1" "ect2" etc

Question: Can someone explain to me the result of this test? I am not sure what the ect1, ect2, etc. mean.
Output
$beta
-------------------------|      ect1      |      ect2     |  ect3   |
-------------------------|:--------------:|:-------------:|:-------:|
Current.account.EUR.l3---|---1.000000e+00-|--1.626303e-19-|-1.040834|
Unemployment.EUR.l3------|--4.263256e-14--|1.000000e+00---| 1.421085|
Trade.EUR.l3-------------|---5.221518e-16-| 2.168404------|-191.00--|

I am looking for the betas for a linear regression, but I don't know how to interpret all these betas. Nobody answers concretely online.
FYI : I posted only the first 3 rows (out of a total of 9) and only the first 4 columns (out of a total of 8). The other columns are Betas with other ect..
Comment: What do you think about my answer? If it is helpful and clear, you may accept it by clicking on the tick mark to the left. Otherwise, you may ask for further clarification. This is [how Cross Validated works](https://stats.stackexchange.com/tour).
Comment: Hi! Your output is hard to read...consider formatting it in a proper way.
Answer: These seem to be the slope coefficients on the error correction terms (thus ECTs). They show how fast the dependent variable adjusts towards the long-term equilibrium between the cointegrated variables. The ECTs themselves show how large deviations from equilibra there are. (Each ECT corresponds to a distinct equilibrium relationship.) Usually they are lagged by 1 period, so you know how large the deviations were last time. When a concrete ECT is multiplied by beta, you see by how much the gap from that equilibrium closes. E.g. $\beta_1=-0.5$ combined with a positive gap would mean that half of the gap tends to close in one period. (The gap can be defined as positive or negative w.r.t. the dependent variable, so you have to be careful when interpreting the signs of the betas. See this, this and this).


The number of ways to fill a 3 by 3 grid

Question: I am currently studying the problem of combination. And when I am doing an exercise, I saw the following question:
There is a 3 x 3 grid, and for each cells in the grid, two players take turn to fill each of them with either a cross or a circle (each player picks either a cross or circle, and stays consistent throughout the activity). How many ways the grid can be filled until all the cells are full?
The given answer is 252, but why?
Should the answer be 2 to the power of 9? At least if we consider the grid as a binary string of length 9, the answer should be 2 to the power of 9 ......
Answer: It is not $2^9$ because the two players take turns, and so there must be 4 crosses and 5 circles, or 5 crosses and 4 circles. Thus, we must pick 4 of the 9 total squares to be crosses, or 4 of the total circles squares to be circles, so the answer is $2\cdot\binom94=2\cdot\frac{9\cdot8\cdot7\cdot6}{4\cdot3\cdot2\cdot1}=2\cdot126=252$.
Answer: Note, for a start, that WLOG the first and second player both have the same number of strategies. This means there are really $252/2 = 126$ ways of filling the grid if we disregard who gets crosses and who gets circles.
Then, how many ways are there to pick $5$ of the unique cells (note that this implicitly also picks $4$ cells for the other symbol)? As it turns out, that's ${9 \choose 5} = 126$. After all, the order in which you pick these doesn't really matter.
So what you get is ${9 \choose 5} \cdot 2 = 252$, in the end.
Comment: You meant $\binom{9}{5} \cdot 2 = \color{red}{252}$.
Comment: @N.F.Taussig oops.


Custom submit handler is also called when deleting a node

Question: So these are my functions:
function mycustom_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'b2share_form_submit';
  return $form;
}
I can also attach the custom submit handler in other ways to the form, but only this way I can still access the nid and the bundle of the node.
function b2share_form_submit($form, &$form_state, $entity_id, $entity_type) {
   $values = array(
   'url' => $form_state['values']['b2share_fieldset']['url'],
   'pid' => $form_state['values']['b2share_fieldset']['pid']
  );

  if ( (empty($values['url'] == false) || (empty($values['pid']) == false)) ) {

    $insert = db_insert('field_data_field_b2share')
      -> fields(array(
       'field_b2share_url' => $values['url'],
       'field_b2share_pid' => $values['pid'],
       'entity_id' => $form_state['node']->nid,
       'entity_type' => 'node',
       'bundle' => $form_state['node']->type,
       'delta' => 0,
       'language' => 'und',
    ))
   ->execute();
 }
}

I can add nodes and edit them perfectly, but whenever I try to delete one, the custom handler function is called and prevent drupal from doing anything. No error messages, nothing in the logs.
Can someone help?
Comment: [`hook_form_alter`](https://api.drupal.org/api/drupal/modules!system!system.api.php/function/hook_form_alter/7.x) passes the form by reference (notice the ampersand in `&$form`) and therefor you should not return the $form variable.
Comment: Thank you for the input. I removed that line, but still can't delete any nodes.
Answer: You made the mistake of giving the form submit function a name that matches the patter form-name_submit. So it does not only trigger by your submit button. It is triggered by every submit button in the form.
Rename your function and you should be good.
Comment: Unfortuntely, no. I called it:
function seal_the_deal($form, &$form_state, $entity_id, $entity_type) {...} and it's still called when trying to delete a node.
Comment: I guess I missunderstood you answer at first: renaming the other function to function b2share_form_node_form_alter(&$form, &$form_state, $form_id) {
  $form['actions']['submit']['#submit'][] = 'seal_the_deal';
}
did the trick
Comment: Perhaps the next time it's better to use your real function names. With all the hooks Drupal uses, function names can provide important context. It will help others help you better. I am glad you got this working.


purpose of interface in classes

Question: what is the purpose of interface when writing a class?
heres an example i've seen online.
<?php
interface Chargeable {
    public function getPrice();
}

class Employee implements Chargeable {
    protected $price;

    public function getPrice() {
        return $this->price;
    }
}

$product = new Employee();

?>

Comment: Please see this [question](http://stackoverflow.com/questions/219425/interface-contract-class-object).
Answer: Here is one of the ways how I learned about interfaces and understood them.
Imagine this scenario:
abstract class Plane {
    public function openDoors();
}

interface Fliers {
    public function fly();
}

Now lets use them:
class Boeing747 extends Plane implements Fliers {
    public function fly() {
        // some stuff
    }

    public function openDoors() {
        // do something
    }
}

And:
class Tweety implements Fliers{
    public function fly() {
        // some stuff
    }
}

Boeing747 is Plane that can fly and Tweety is a bird than can fly but it makes no sense for Tweety to "openDoors".
The point is that interfaces can be implemented by different kinds of objects but classes can not. As you can see Boeing747 and Tweety have nothing in common other than both can fly.
Comment: I agree this is a very useful answer. Would love to see it edited for clarity.
Comment: couldnt the same be said if their(Fliers=open door & Plane=Fly) function is reversed and use Class Plane instead of Fliers for function fly. So class tweety extends Plane to fly. While class Boeing747 implements Fliers and extend Plane to open doors and fly respectively.
Comment: only way i can think of is that it'd help save memory as interface can't have nothing defined and abstract class can.
Answer: An interface is a concept in Object Oriented programming that enables polymorphism. Basically an interface is like a contract, that by which classes that implement it agree to provide certain functionality so that they can be used the same way other classes that use the interface
Your example shows classes that guarantee that they have the getPrice method available. You can then write code that take advantage of objects that have this method without worrying about what kind of class it is.
Answer: Interfaces allow you to separate the interface from implementation.  This is handy when you want to have orthogonality in your code among other things.
Basically you will be able to create functions that accept a Chargeable and be able to pass any object in there as long as it implements Chargeable.  This allows you to be flexible down the road if you need to change the Employee class.  Also it allows your method to accept any object that is "chargeable".
Answer: In languages with multiple inheritance instead of interfaces you have abstract classes. In PHP there is no multiple inheritance, so you have interfaces. One class can implement various interfaces. The only point is to guarantee that your class has certain set of methods.
Answer: I'm struggling to grok this myself at the moment (and I think I'm reading the same book as the OP...).
It seems to me that interfaces simply enforce a "contractual" obligation on classes that implement the interface to implement functions/properties that appear in the interface. Yet, isn't it the case that classes/objects which implement the interface can do so in a unique fashion since the implementation is not defined?
There is no actual inheritance involved is there?
Answer: Firstable, interfaces structures provide interface to classes implemented for communicating outside world. Easy example would be a television. Television is a class and buttons on it are interfaces.
adv of using interfaces:
1-Java does not support multiple inheritance. If we want to add two different methods from different classes we cannot  (extend ClassA,ClassB) is not possible implements A,B no problem.
2-The other adv is a security and flexibility An example can be given to be more specific
if we want that some of methods of the class are not reachable  how can we do that?
polymorphism  + interface we can do that
if we do not want walk and bark methods should be unreachable
abstract class Animal {
    String name;
    int age;

    public Animal(String name, int age) {
        super();
        this.name = name;
        this.age = age;
    }

}

class Dog extends Animal implements Run {

    public Dog(String name, int age) {
        super(name, age);
        // TODO Auto-generated constructor stub
    }

    @Override
    public void run() {
        // TODO Auto-generated method stub

    }

    public void bark() {

    }

}

class Cat extends Animal implements Climb {

    public Cat(String name, int age) {
        super(name, age);

    }

    @Override
    public void climb() {
        // TODO Auto-generated method stub

    }

    public void walk() {

    }

}

public class Main {

    public static void main(String[] args) {

        // if we want that some of methods of the class are not reachable how
        // can we do that?
        // polymorphism + interface we can do that
        // for example if we do not want walk and bark methods should be
        // unreachable

        Climb cat = new Cat("boncuk", 5);
        Run dog = new Dog("karabas", 7);

        // see we cannot reach the method walk() or bark()
        dog.walk(); // will give an error. since there is no such a method in the interface.

    }

}}

    enter code here

Answer: let me give you example to understand the the dimnation of this type of classes
public interface transport{
public double getSpeed(){return(0/*the speed*/);}
public void setSpeed(){return(0/*the speed*/);}

}
class car extend transport{
//implementation of transport interface
public double getSpeed(){return(speed/*the speed*/);}
public void setSpeed(){speed=250;}
}
class train extend transport{
//implementation of transport interface
....

}

class plane extend transport{
//implementation of transport interface
....
}

so the interface class is the general concept .
Comment: Bad answer. Or not answer at all.
Comment: an interface 'implements' not extend
Comment: interfaces are implemented, not extended. Also, the idea behind an interface is that any object which implements the interface may be passed as a parameter to a method which expects an object of the interface type. Classic examples are comparitors and comparables.
Comment: Am I using historyOverflow?

purpose of interface in classes


extract some data from an array php

Question: I use this code to know if in an array there are some value
<code> if(in_array("car", $parking))
 { $p_2="ok";  }
  else{ $p_2="KO"; }
</code>
Now suppose that my array is like this
<code> $parking=array("black","blue","car","white");
</code>
I know that in this array it could be some values like car or black because people put in this array through a form.
How can I extract the other data that aren't car o balck?
Comment: Please before asking check for official documentation http://php.net/manual/es/language.types.array.php ... what exactly do you want? to show each value? (use foreach) to search for a specific value? (use in_array just like you've done)
Answer: The method you should use is array_diff that returns the difference between two arrays.
<code>$parking = array("black", "blue", "car", "white");
$diff    = array_diff($parking, array("black", "white"));

print_r($diff);
</code>
Result
<code>Array
(
    [1] => blue
    [2] => car
)
</code>

extract some data from an array php


Soft question: Solutions of $a(x-x_0)+b(y-y_0)+c(z-z_0)=0$?

Question: Soft question:
Let $abc\neq 0$ and $$a(x-x_0)+b(y-y_0)+c(z-z_0)=0$$
Besides  $$x=x_0$$
$$y=y_0$$
$$z=z_0$$
Are there any other solutions?
Comment: What do you mean. The whole point of such equation is any $(x,y,z)$ on the plane is (made) a solution. The solutions are points on the plane with normal vector $\langle a,b,c \rangle$ and where $(x_0,y_0,z_0)$ is a point on the plane.
Comment: Le me get this straight: If  $2(x-3)+5(y-11)+7(z-13)=0$ then any $x,y,z$ is solution?
Comment: Any $(x,y,z)$ on the plane $P$ with normal vector $\langle 2,5,7 \rangle$ and a point $(3,11,13)$ lying on the plane is a solution. But of course not any $(x,y,z)$ is general.
Comment: Take the equation $1(x-1)+1(y-1)+1(z-1)=0$ for example and maybe take $z=0$. So now the problem becomes how many solutions to  $x+y=3$ are there. You know the answer.
Answer: There will be a whole 2 dimensional subspace of solutions.
\begin{eqnarray*}
x &=& x_0 + \frac{\lambda}{a} \\
y &=& y_0 + \frac{\mu}{b} \\
z &=& z_0 - \frac{\lambda+\mu}{c}
\end{eqnarray*}
The equation represents a plane.
Answer: Yes! There's a whole plane of solutions, quite literally.  The equation you've given can be written as ${\bf r} \cdot {\bf n} = {\bf p} \cdot {\bf n}$, where ${\bf r} = (x, y, z)$, ${\bf n} = (a, b, c)$ and ${\bf p} = (x_0, y_0, z_0)$, which is exactly the equation of a plane. (See here and here)
Answer: Clearly so. Specify any two of $x,y,z$ arbitrarily, and then solve the simple linear equation explicitly for the third (since none of $a,b,c$ can be $0$).
Answer: Let's perturb our proposed solution, so that $z$ changes from $z_0$ to $z_0 + \delta_z$.
Then in order to compensate the change, we need to add to $x$ and $y$ the terms $\delta_x$ and $\delta_y$, such that $a\delta_x$ + $b\delta_y$ = $c\delta_z$. To parametrize this space, we need parameters $\alpha$ and $\beta$, both real.
Therefore the solution space is $x = x_0 + \frac{\alpha}{a}$, $y = y_0 + \frac{\beta}{b}$, and $z = z_0 - \frac{\alpha + \beta}{c}$ by inspection. This is a plane, of course.


Entity Framework: Not able to use migration command when entityFramework dll is referenced manually (Not installed from Nuget package)

Question: I am aware that 'Enable-Migrations' and 'Add Migrations' commands are used for migrations on package manager console. But in my project, we have not installed EF from nuget. We are explicitely (manaully) referencing EF's dll in bin folder.
Now, I am not able to run migration command. Could anybody help in this context.
Please note that we are using Code-First approach.
Thanks In Advance
Answer: The commands are part of the NuGet package and are added when installing the package. In your current project you can remove the reference to EntityFramework.dll and install the package. Another alternative would be to use migrate.exe but the experience is far more inferior than running commands from the Package Manager Console.


Não estou conseguindo acessar o MySQL pelo PHP

Question: Estou com o seguinte problema, eu utilizo o Ubunto e instalei o mariadb, e quando eu tento acessar o mysql com:
mysql -u root

Aparece o seguinte erro:
ERROR 1698 (28000): Access denied for user 'root'@'localhost'

E então consigo acessa-lo apenas utilizando o:
sudo mysql -u root

E agora, quando tento fazer:
$conexao = mysqli_connect('localhost', 'root', '', 'php_alura');

Não acontece nada, e minha página nem renderiza.
Alguém pode me ajuda?
Atualização:
Uma observação importante é que só consigo acessar o mysql pelo bach utilizando a permissão sudo, ou seja com:
sudo mysql -u root

Eu consigo ter acesso.
Comment: Qual o código que está a utilizar para aceder aos dados  e mostrar os mesmos? Qual o código da página que não renderiza?
Comment: Então amigo, o código de conexão é o seguinte: `$conexao = mysqli_connect('localhost', 'root', '', 'php_alura');` Porém eu eu dei um restart no apache e agora está renderizando as páginas, porem não consigo fazer a conexão com o mysql. **OBS:** Eu só consigo mexer no mysql pelo painel usando a permissão de **sudo**, acredito que tenha alguma relação, mas não sei como resolver.
Answer: Você está apenas fazendo a conexão ou está executando uma query também ?
O código abaixo executa a conexão e faz a verificação se houve erro, em caso de erro irá mostrar a mensagem de erro e finalizar, em caso de haver sucesso na conexão mostrará a mensagem de sucesso e depois fechará a conexão com a base de dados.
<?php
$link = mysqli_connect("HOST", "USUARIO", "SENHA", "BASE");
if (!$link) {
    echo "Error: Falha ao conectar-se com o banco de dados MySQL." . PHP_EOL;
    echo "Debugging errno: " . mysqli_connect_errno() . PHP_EOL;
    echo "Debugging error: " . mysqli_connect_error() . PHP_EOL;
    exit;
}
echo "Sucesso: Sucesso ao conectar-se com a base de dados MySQL." . PHP_EOL;
mysqli_close($link);

Atualização
Siga os passos na ordem:
1 - finalize o mysql:
sudo /usr/local/mysql/support-files/mysql.server stop

2 - Inicie-o no modo de segurança:
sudo mysqld_safe --skip-grant-tables

3 - Este será um comando contínuo até o processo terminar, então abra outra janela de shell / terminal e faça o login sem uma senha como root:
mysql -u root
FLUSH PRIVILEGES;
ALTER USER 'root'@'localhost' IDENTIFIED BY 'NOVASENHA';

Altere NOVASENHA por uma senha desejada e inicie o MySQL
sudo /usr/local/mysql/support-files/mysql.server start

Comment: Me retornou:

Error: Falha ao conectar-se com o banco de dados MySQL. Debugging errno: 1698 Debugging error: Access denied for user 'root'@'localhost'
Comment: Então amigo, eu tentei fazer o comando:

`sudo /usr/local/mysql/support-files/mysql.server stop `

Porem voltou o seguinte

`sudo: /usr/local/mysql/support-files/mysql.server: comando não encontrado`

Então dei uma pesquisada e tentei fazer o seguinte:

`sudo /etc/init.d/mysql stop`

Que retornou o seguinte:

`[ ok ] Stopping mysql (via systemctl): mysql.service.`

Então tentei fazer o segundo comando que me passou e retornou isso:
`170801 13:26:23 mysqld_safe Logging to syslog.
170801 13:26:23 mysqld_safe A mysqld process already exists`
Comment: Já que você consegue acessar o MySQL pelo terminal usando sudo, siga os passou dessa print : http://imageshack.com/a/img922/2082/60pALx.png
Comment: Depois é só configurar no php para se conectar sem senha
Comment: Deve ficar assim, certo? http://imageshack.com/a/img923/7910/EmVqKQ.png
Comment: Porem o seu código ainda aparece: `Error: Falha ao conectar-se com o banco de dados MySQL. Debugging errno: 1698 Debugging error: Access denied for user 'root'@'localhost' `
Comment: Sim, tem que trocar os valores, HOST, USUARIO, SENHA e BASE ficando assim $link = mysqli_connect("localhost", "root", "", "php_alura");
Comment: mas está igual `$link = mysqli_connect("localhost", "root", "", "php_alura");`
Comment: Agora fica um pouco difícil de poder ajudar, pois estou no trabalho, aqui não consigo ver a print que você colocou no comentário, se alguém poder ajudar. se não só amanha cedo quando eu chegar em casa
Comment: Tudo bem cara, mas o print era apenas eu mostrando que fiz exatamente o que pediu ` | root | mysql_native_password | ` (tabela no mysql)
Comment: Isso, é pra ficar desse jeito da print mesmo. Tente reinstalar o mysql, removendo ele primeiro por completo
Comment: Muito Obrigado amigo!!! Eu não havia reiniciado o computador e agora que testei o que me pediu funcionou!!!!! (Não precisei re instalar) Muito obrigado mesmo!!!!


Project layout using Wicket

Question: Where should I put the .html files in a wicket Application?
my current project layout is as follows:
src/myproject
  --classes+ duplicated html files
web
--numerous .html files - previewed
web/img
--resource files such as css/png/js files

i want to avoid putting the html files on dupliate locations. what is a good non-redundant strategy to put the html and resource files?
this is using tomcat so obviously, when deployed the directory structure changes to
img
WEB-INF
WEB-INF/classes/myproject

and the .html files stay at the toplevel, as well alongside the .class files - which is bad.
of course, the preview function in plain html should have no problems with relative paths
are there any examples for this? do i need special code (such as a IResourceStreamLocator) in my wicketappllication class?
i am using wicket 1.4-rc1.
Answer: Should I put html and java files in the same package (folder) in Apache Wicket?
Answer: so after gathering some experience with wicket, it turned out that the default location for the html files is just fine. no need to reinvent the wheel.
you can link resources without troubles with relative paths, and still preserve the preview ability.
Answer: I would suggest using Maven to build your application. Never depend on an IDE to build your application. IDE's might differ between developers. When you want to use a CI server you need to fall back to scripting if you don't use a build system.
Maven also separates resources from sources.
Although Maven requires some time to get into it is very much worth the effort.

Project layout using Wicket


Exceptions while sending email Java

Question: I am facing the problem with Exceptions while sending an email. Here is my code below
public static void sendEmail(String email, String subjectBody, String srcAndFile) throws Exception {
    System.out.println(srcAndFile);

    try {
        logger.debug("sending email to: " + email + "with attached file: " + srcAndFile);

        Properties props = System.getProperties();
        props.put("mail.smtp.host", address);
        props.put("mail.smtp.port", "25");
        props.put("mail.smtp.auth", "false");

        Session session_m = Session.getDefaultInstance(props, null);
        MimeMessage message = new MimeMessage(session_m);
        message.setFrom (new InternetAddress(sender, sender));
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
        message.setSubject(subjectBody);
        message.setText("Hi");
        message.setHeader("Content-Type","text/plain;charset=windows-1251");

        Multipart multiPart = new MimeMultipart();
        MimeBodyPart messageText = new MimeBodyPart();
        messageText.setContent(subjectBody, "text/plain");
        multiPart.addBodyPart(messageText);

        MimeBodyPart rarAttachment = new MimeBodyPart();
        File f = new File(srcAndFile);
        FileDataSource rarFile = new FileDataSource(f);
        rarAttachment.setDataHandler(new DataHandler(rarFile));
        rarAttachment.setFileName(rarFile.getName());
        multiPart.addBodyPart(rarAttachment);

        message.setContent(multiPart);

        SMTPTransport t = (SMTPTransport)session_m.getTransport("smtp");
        t.connect(addrress, sender, null);
        t.sendMessage(message, message.getAllRecipients());
        success = true;

        } catch (AddressException e) {
            logger.error(e.getMessage());
            throw new AddressException("[sendEmail]: Incorrect email address");

        } catch (MessagingException e) {
            logger.error(e.getMessage());
            throw new MessagingException("[sendEmail]: Unable to send email");

        } catch (IOException e) {
            logger.error(e.getMessage());
            throw new IOException("[sendEmail]: Unable to find file to attach");

        } catch (Exception e) {
            logger.error(e.getMessage());
            DBWrapper.processStatusDB("[sendEmail]","failed",e.getMessage());
            throw  new Exception("[sendEmail]: Error in method " + e.getMessage());
        }
        DBWrapper.processStatusDB("[sendEmail]","finished","process to send an email with " + FileManager.getFile(srcAndFile) + " has finished properly");

}

Now the problem arises when I want to catch some errors:

Invalid address
Unable to connect to server

Both of these cases are caught on (MessagingException e). Is there a way to split them in different exceptions.
The thing is that if email address of receiver is invalid, my program should continue with other recipients. But if the program is unable to connect to mail server, then the program should terminate. But in my case it terminates even when email address is invalid. Since (MessagingException e) throws error as shown in the code.
Is there any other exceptions to catch INVALID EMAIL ADDRESS? (AddressException e) is not catching the error with invalid email.
Thank you.
Comment: Have a look at the stack trace and see if both exceptions come from the same line.
Comment: `logger.error("Exception class: " + e.getClass().getName());` or javadoc
Answer: I feel, it is better to validate the mail address before trying to send the mail. This is something you know and can correct it even before the exception occurs. Mail server not accessible is an exception which you can expect and thus make sense to catch it and do the post processing.
Comment: There is a problem with it:

For example if I say my email address is AKaldybayev@domain then if I change my address to AKaldybaye@domain then it will still give me INVALID ADDRESS exception. The server side checks if the user with such address exists or not. If the user doesn't exists then it throws INVALID ADDRESS.

The short is I can't validate by structure firstname.lastname@example.com
Answer: You could use the SendFailedException. An excerpt from the docs

This exception is thrown when the message cannot be sent.
The exception includes those addresses to which the message could not
  be sent as well as the valid addresses to which the message was sent
  and valid addresses to which the message was not sent.
Comment: Thank you. It worked and now I can differentiate when the exceptions: when address is invalid or if i can't connect to server. From now on will remember this SendFailedException. It is exactly what I was searching
Comment: Glad to be of help! :)
Comment: Ayan, it would be nice to know how your code was modified to incorporate SudoRahul's answer.
Answer: I was facing same problem a few days back. Try using
Session session = Session.getInstance(props,
          new javax.mail.Authenticator() {
            protected PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password);
            }
          });

instead of
Session session_m = Session.getDefaultInstance(props, null);

Also recheck your port number.
Comment: My mailing module works fine. It sends correctly. It is just while testing system for different case scenarios I wanted to catch most common errors while sending mail such as invalid address or can't connect to server or file to attach doesn't exist. Thank you anyways

Exceptions while sending email Java


Create a Boolean column for unique rows in a grouped data frame

Question: I have a grouped data frame df_grouped, I would like to create a new boolean column df_grouped["Unique"] where for each subset of grouping, this column is True if the values of location is unique within the grouping & False if it's not unique.
dataset = {
    'ID': ['One', 'One', 'One', 'Five', 'Five','Five','Four'],
    'Day': [2, 2, 2, 1, 1,1,0],
    'Location': ['London', 'London', 'Paris', 'London', 'Paris','Paris','Berlin']}

df = pd.DataFrame(dataset)
df_grouped = df.groupby(['Name','Day'])

Expected output for the unique column:
'Unique': [False, False, True, True, False, False, True]

Answer: Use DataFrame.duplicated with keep=False and inverted mask by ~:
df['Unique'] = ~df.duplicated(['ID','Day', 'Location'], keep=False)
print (df)
     ID  Day Location  Unique
0   One    2   London   False
1   One    2   London   False
2   One    2    Paris    True
3  Five    1   London    True
4  Five    1    Paris   False
5  Five    1    Paris   False
6  Four    0   Berlin    True


Intraclass correlation coefficient interpretation

Question: I'm having a look at the intraclass correlation coefficient in SPSS.
Data: 17 participants rated two lists of 9 & 7 items from 0 to 5 (0 being unimportant and 5 being very important).
All participants rated all the items and the participants are a sample of a large population.
The following output has been produced in SPSS.

I am struggling to find anything online which deals with interpreting this, nor does any book interpret this in the level of detail I need.
There is surprisingly little information/examples of the interpretation online on this, the literature is about choosing an intraclass correlation coefficient and not interpreting it.
One problem I foresee here is the F test. The data is only 17 responses, which do not follow the normality assumption.
Comment: You might find this resource useful: http://neoacademic.com/2011/11/16/computing-intraclass-correlations-icc-as-estimates-of-interrater-reliability-in-spss/
Answer:
I am struggling to find anything online which deals with interpreting
  this

The output you present is from SPSS Reliability Analysis procedure. Here you had some variables (items) which are raters or judges for you, and 17 subjects or objects which were rated. Your focus was to assess inter-rater aggreeement by means of intraclass correlation coefficient.
In the 1st example you tested p=7 raters, and in the 2nd you tested p=9.
More importantly, your two outputs differ in the respect how the raters are considered. In the 1st example, the raters are a fixed factor, which means they are the population of raters for you: you infer about only these specific raters. In the 2nd example, the raters are a random factor, which means they are a random sample of raters for you, while you want infer about the population of all possible raters which those 9 pretend to represent.
The 17 subjects that were rated constitute a random sample of population of subjects. And, since each rater rated all 17 subjects, both models are complete two-way (two-factor) models, one is fixed+random=mixed model, the other is random+random=random model.
Also, in both instances you requested to assess the consistency between raters, that is, how well their ratings correlate, - rather than to assess the absolute agreement between them - how much identical their scores are. With measuring consistency, Average measures ICC (see the tables) are identical to Cronbach's alpha. Average measures ICC tells you how reliably the/a group of p raters agree. Single measures ICC tells you how reliable is for you to use just one rater. Because, if you know the agreement is high you might choose to inquire from just one rater for that sort of task.
If you tested the same number of the same raters (and the same subjects) under both models you'd see that the estimates in the table are the same under both models. However, as I've said, the interpretation differs in that you can generalize the conclusion about the agreement onto the whole population of raters only with two-way random model. You can see also a footnote saying that the mixed model assumes there is no rater-subject interaction; to put clearer, it means that the raters lack individual partialities to subjects' characteristics not relevant to the rated task (e.g. to hair colour of an examenee).
SPSS Reliability Analysis procedure assumes additivity of scores (which logically implies interval or dichotomous but not ordinal level of data) and bivariate normality between items/raters. However, F test is quite robust.
Comment: This relates to two questions from an administered questionnaire.

Say the second one is the correct model, how do you go about interpreting the numbers within the table.
Comment: I don't understand your comment. [Essentially, all models are wrong, but some are useful](http://en.wikipedia.org/wiki/George_E._P._Box).
Comment: Consider the second picture above.  How would you deal with interpreting the numbers within it. I want "to assess the consistency between raters, that is, how well their ratings correlate", so I agree with that.
Answer: You might want to read the article by LeBreton and Senter (2007). It's a fairly accessible overview of how to interpret ICC and related indicators of inter-rater agreement.
LeBreton, J. M., & Senter, J. L. (2007). Answers to 20 questions about interrater reliability and interrater agreement. Organizational Research Methods.
Answer: Let me provide a response for the first situation that you analysed because the second situation essentially parallels it, except that you have two more items in the second situation and you chose a different model (more about that below).  In providing this response, in some places I have a different interpretation from the extended explanation that has been provided elsewhere in these posts.
As I understand it, you had 17 raters (participants), each of whom provided a rating on 5-point scales to seven different items AND you are wanting to see whether there is much agreement between the 17 raters in how they rated those 7 items.  I think that, in order to do this (which is surely a pretty unusual situation; usually there are not as many as 17 raters involved in assessing something), you should have selected ABSOLUTE (not consistent) measures in SPSS, and, if your participants are the only raters of interest in this situation (I assume they are, and that you are not wanting to generalize your results to other participants / raters) you should indeed have chosen Model 3 (i.e., 2-way mixed, NOT Model 2 as you did in your second setup), which is the FIRST model offered in SPSS.  So, in essence, you have made a basic mistake in selecting the kind of ICC that provides a consistency solution SPSS.  (Sorry to give you the bad news.)
Next, when you choose an ICC from the output you should choose the ICC from the row titled "Single measures" (i.e., .133) because each of your participants made a single rating for each of the 7 items (and I assume you entered 17 scores into the ICC analysis for each item).  If you had averaged all of your 17 participants' ratings on each item BEFORE entering the data into the ICC analysis, it would be appropriate for you to report the ICC that pertains to the Averaged measures (.519).  But, from your description, you didn't average the ratings that were made by your participants.
If you had chosen Absolute rather than Consistency for your first analysis, an ICC as low as .133 would indicate that your 17 participants / raters exhibited EXTREMELY little agreement among themselves in terms of how they rated the 7 items.
An article in 2016 by Trevethan in the journal Health Services and Outcomes Research Methodology provides the background for this answer as well as a lot of other information concerning the selection and interpretation of ICCs.
Finally, the small number of items (7 in the first situation) might create some problems statistically.  I am sorry, but I am not able to provide advice about that. Maybe it's OK in your situation, but it might be advisable to consult a friendly statistician.
References
Trevethan, R. (2016). "Intraclass correlation coefficients: Clearing the air, extending some cautions, and making some requests." Health Services and Outcomes Research Methodology. DOI 10.1007/s10742-016-0156-6. (Online publication available until volume, issue, and page numbers have been assigned.)
Comment: Could you add a full citation for the Trevethan (2016) article?
Comment: Sure, here's the full reference for the Trevethan (2016) article.  The article has just been published and I didn't have the full reference because the volume, issue, and page numbers have not yet been assigned.  Here is as much as I can provide:

Trevethan, R.  (2016). Intraclass correlation coefficients:  Clearing the air, extending some cautions, and making some requests.  Health Services and Outcomes Methodology.  The DOI has been assigned, but I'm not sure it's yet operating as of 26 August 2016.  It is 10.1007/s10742-016-0156-6.
Comment: I've added that into the article (feel free to edit to change the formatting) - usually best not to leave things in the comments, partly because people don't always read them and partly because comments are best treated as transient (can't be guaranteed they will be around forever!)
Comment: Thanks for this.  Appreciated.  In my haste I made a mistake, however. The journal title is Health Services and Outcomes Research Methodology.  If I can't alter it in the post, please feel free to do it on my behalf.   Cheers, RT.
Answer: I have traced the answer in new Stata 13 documentation on
ICC.
The question remains on whether the F test in this case can be used given the data does not follow the assumptions of normal distribution.


clarification on k fold cross validation

Question: I understand k fold cross validation has been discussed many times here and I read some of them. I understand how k Fold works, but what confuses me is the following:
Cross validation in my understanding is used for model validation, which validates an existing model. For example, a model builds on full dataset. But what I read about k fold is that it will build 5 different models based on 4/5 of the full date set (sampled 5 times) and test it on the rest 1/5 dataset, if k =5. It seems it has nothing to do with validating an existing model.
Could anyone kindly comment on this?
Answer: Cross-validation estimates the performance of a method of producing a model, not of the model itself.  The performance of the model can reasonably be expected to be consistent with the performance of models generated by this method, but the indirect inference there is usually not stated.
Answer: I like this question because it touches a common source of confusion: the overloaded use of the term model. In this contest, model refers to a the mathematical formulation of a solution (a method $ \hat f (x, \theta)$) rather than a specific instance of a model where every parameter ($\theta$) has been set.
I have also seen the k trained model instances generated in a k-fold cross validation exercise moved to production and used as an ensemble instead of training one, single model on the whole calibration set.
This is a particularly concerning topic, because as the number of folds declines, depending on the performance of the learning method with respect to the training set size, might result on k-fold model instances being biased - not only in their estimate of the generalization error but, in this specific context, biased in their estimation of the target variable.

Edit 1

If I understand what you said correctly, k fold validation is more
  used to compare modeling algorithms, but a specific model itself. What
  I am not quite understand is the bias you talked about. Would you
  please comment on that? Thanks!

Your understanding is correct and the comparison takes place on the generalization error, which we estimate calculating the error, or cost, on each validation set and then (very likely) averaging it.
As every estimator, our estimator of the generalization error suffers of bias and variance, which we have to trade-off. An Introduction to Statistical Learning covers this topic in detail. Some other treads explain this thoroughly: this and this for example.
Comment: If I understand what you said correctly, k fold validation is more used to compare modeling algorithms, but a specific model itself. What I am not quite understand is the bias you talked about. Would you please comment on that? Thanks!


Calculate log2 ratio

Question: I have to calculate log2 ratio for odds and don't know how to do it.
 Group A      Group B
 0.031571     0.0170071

There are occurrences of event in GroupA and Group B - I want to calculate how much Group A has this specific event compared to Group B, hence I need log2 for odds ratio.
I was thinking that such ratio should be calculated like this:
log2(GroupA/GroupB) = log2(0.031571/0.0170071) = 0.892463

However in this stackoverflow answer they calculate it like this:
(GroupA/GroupB)/log(2) = (0.031571/0.0170071)/log(2) = 2.67814

My question is - how to calculate log2 ratio; and what is the difference between these two approaches?
Comment: Remember that the log of a ratio is equal to the difference of the logs: $\operatorname{log}_{k}(a/b)=\operatorname{log}_{k}(a)-\operatorname{log}_{k}(b)$, where $k$ is the base ($k=2$ in your case). Maybe that helps you figuring out if this is what you want to calculate.
Comment: Apparently, in the link I gave they tried to calculate log of a ratio in `awk` and `awk` can't calculate `log2(A/B)` and one has to `log(A/B)/log(2)`.
Comment: I added a comment to that SO answer pointing out the mistake. I think it's just a typo, but because it resulted in hugely erroneous example output, I have also downvoted that answer pending a correction.
Answer: The log odds ratio is the log of the odds ratio, not the odds ratio divided by a log. I don't know what problem the link you gave was trying to solve, but it wasn't this one. You take the log of the OR because the OR is bounded by 0 and infinity and is multiplicatively symmetric around 1; while the log(OR) is unbounded and additively symmetric around 0.

Calculate log2 ratio


export generated data to excel with php/js

Question: I have 2 date input fields(startdate,endate) that a user can selected. Once selected, data will show that is registered between the 2 dates provided by the user in a table format. how can I export that data that is shown in the table to excel with a button click without third party plugins ?
code that I used :

    <form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
        startdate: <input type="date" name="from_date">
        enddate: <input type="date" name="to_date">
        <input type="submit" name="date" id="date">
    </form>

    <?php
    require('settings.php');
    mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

    if (isset($_POST["date"])) {
        $startDate = date("Y-m-d", strtotime($_POST['from_date'])); // Y-m-d
        $endDate = date("Y-m-d", strtotime($_POST['to_date'])); // something weird is happening with the dates random dates slip between date ranges

        $sql = "SELECT distinct latestv.* from(
        select distinct Werkomschrijving_nr from POH_GL4 where versie Between ? and ? ) changedw
        left join
        (select distinct Werkomschrijving_nr, max(versie) AS maxdate, omschrijving from POH_GL4
        group by Werkomschrijving_nr,omschrijving) latestv on latestv.Werkomschrijving_nr = changedw.Werkomschrijving_nr";

        $stmt = $db->prepare($sql);
        $stmt->execute([$startDate, $endDate]);
        $result = $stmt->fetchAll();

        echo "
";
        echo "
nr werkomschrijving	Last change date 	Omschrijving
";

        foreach ($result as $key => $row) {

            echo "
";
            echo "" . $row['Werkomschrijving_nr'] . "	";
            echo "" . $row['maxdate'] . "	";
            echo "" . $row['omschrijving'] . "	";
            echo "
";
        }}

Answer: The exportTableToExcel() function convert HTML table data to excel and download as XLS file (.xls).
=> tableID – Required. Specify the HTML table ID to export data from.
=> filename – Optional. Specify the file name to download excel data.
js code:-
function exportTableToExcel(tableID, filename = ''){
    var downloadLink;
    var dataType = 'application/vnd.ms-excel';
    var tableSelect = document.getElementById(tableID);
    var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');

    // Specify file name
    filename = filename?filename+'.xls':'excel_data.xls';

    // Create download link element
    downloadLink = document.createElement("a");

    document.body.appendChild(downloadLink);

    if(navigator.msSaveOrOpenBlob){
        var blob = new Blob(['\ufeff', tableHTML], {
            type: dataType
        });
        navigator.msSaveOrOpenBlob( blob, filename);
    }else{
        // Create a link to the file
        downloadLink.href = 'data:' + dataType + ', ' + tableHTML;

        // Setting the file name
        downloadLink.download = filename;

        //triggering the function
        downloadLink.click();
    }
}

Html Table:
The HTML table contains some users data with some basic fields, in Your case you have dates, in below code you see name, email,,etc...

        Name
        Email
        Country

        John Doe
        firstname.lastname@example.com
        USA

        Michael Addison
        email@example.com
        UK

        Sam Farmer
        firstname.lastname@example.com
        France

The button triggers exportTableToExcel() function to export HTML table data using JavaScript.
<button onclick="exportTableToExcel('tblData')">Export Table Data To Excel File</button>

If you want to export data with the custom file name, pass your desired file name in the exportTableToExcel() function.
<button onclick="exportTableToExcel('tblData', 'members-data')">Export Table Data To Excel File</button>

This code helps you to add export functionality in the table data without any third-party jQuery plugin or server-side script. You can easily export the table data using minimal JavaScript code. Also, the functionality of the example code can be extended as per your needs.


What are the best collaborative ways to edit code? (real time)

Question: Over the shoulder is of course the best, but sometimes we work remotely and want a good way to both edit the same file.
Stuff we've tried:

Skype screen sharing
SubEthaEdit
Google Wave

How do you collaborate in real time environments?
Answer: You should take a look at Skywriter.


Mutable Wrapper for Immutable Dictionary

Question: Here is the problem; I have an immutable dictionary with huge set of items. The key type and the value types contained within this dict are themselves immutable. I would like to be able to mutate this dict (adding/removing/replacing key-value pairs) without having to do a full copy of the dict.
I am imagining some wrapper class for the immutable dict which adheres to the dict contract, and defaults to the immutable dict for values that have not been updated. I see the post How to "perfectly" override a dict? which I plan to leverage to make this wrapper.
Before I embark on implementing this design I just wanted to ask- is this construct already provided by the language? Or how else can I achieve the desired effect? I am on the latest version of Python (3.7) so I can use all language features available. Thanks!
Answer: Take a look at collections.ChainMap. It's a wrapper around multiple dictionaries: all writes go to the first dictionary, and lookups are searched in order of the maps. So I think you could just do something like:
modified_map = {}
mutable_map = collections.ChainMap(modified_map, huge_immutable_map)

Comment: I guess the one thing it can't do is remove an item that is in the immutable dict, if you wanted to be able to do that.
Comment: [Looks like it does!](https://docs.python.org/3/library/collections.html) "Lookups search the underlying mappings successively until a key is found. In contrast, writes, updates, and deletions only operate on the first mapping." Fantastic, thank you so much!
Comment: nope, I want the immutable dict to remain immutable. I'm just trying to prevent a full copy to be able to do so.
Answer: Let's say you used a frozendict implementation like this one:
class frozendict(collections.Mapping):
    """
    An immutable wrapper around dictionaries that implements the complete :py:class:`collections.Mapping`
    interface. It can be used as a drop-in replacement for dictionaries where immutability is desired.
    """

    dict_cls = dict

    def __init__(self, *args, **kwargs):
        self._dict = self.dict_cls(*args, **kwargs)
        self._hash = None

    def __getitem__(self, key):
        return self._dict[key]

    def __contains__(self, key):
        return key in self._dict

    def copy(self, **add_or_replace):
        return self.__class__(self, **add_or_replace)

    def __iter__(self):
        return iter(self._dict)

    def __len__(self):
        return len(self._dict)

    def __repr__(self):
        return '<%s %r>' % (self.__class__.__name__, self._dict)

    def __hash__(self):
        if self._hash is None:
            h = 0
            for key, value in self._dict.items():
                h ^= hash((key, value))
            self._hash = h
        return self._hash

If you wanted to mutate it, you could just reach in and mutate self._dict:
d = frozendict({'a': 1, 'b': 2})
d['a'] = 3  # This fails
mutable_dict = d._dict
mutable_dict['a'] = 3  # This works
print(d['a'])

It's a little yucky reaching into a class's protected members, but I'd say that's okay because what you're trying to do is a little yucky. If you want a mutable dictionary (just a dict) then use one. If you never want to mutate it, use a frozendict implementation like the one above. A hyrid of mutable and immutable makes no sense. All frozendict does is it doesn't implement the mutation dunder methods (__setitem__, __delitem__, etc.). Under the hood a frozendict is represented by a regular, mutable dict.
The above approach is superior in my view to the one you linked. Composability (having frozendict have a _dict property) is much easier to reason about than inheritance (subclassing dict) in many cases.
Comment: Ah, I'm not sure I was clear in the original question. I don't wish to mutate the immutable backing dict. It's shared with other code.