Compare arrays in swift

Question: Trying to understand how swift compares arrays.
var myArray1 : [String] = ["1","2","3","4","5"]
var myArray2 : [String] = ["1","2","3","4","5"]

// 1) Comparing 2 simple arrays

if(myArray1 == myArray2) {
    println("Equality")
} else {
    println("Equality no")
}
// -> prints equality -> thanks god

// 2) comparing to a "copy" of an array

// swift copies arrays when passed as parameters (as per doc)
func arrayTest(anArray: [String]) -> Bool {
    return anArray == myArray1
}

println("Array test 1 is \(arrayTest(myArray1))")
println("Array test 2 is \(arrayTest(myArray2))")
// equality works for both

myArray2.append("test")
println("Array test 2 is \(arrayTest(myArray2))")
// false (obviously)

myArray2.removeAtIndex(5)
println("Array test 2 is \(arrayTest(myArray2))")
// true

Apple says there are optimisations behind the scene on array copies. Looks like sometimes - not always - structures are actually copied or not.
That said,
1) is == iterating over all the array to perform a element-based comparison ? (looks like it)
-> How about performance / memory usage on very large arrays then ?
2) Are we sure == will ever return true if all elements are equal ? I have bad memories of == on Java Strings
3) Is there a way to check if myArray1 and myArray2 are technically using the same "memory location" / pointer / etc. ? i'm after understanding how the optimisation works and potential caveats.
Thanks.
Comment: In the module definition, array equality is defined as `func ==(lhs: [T], rhs: [T]) -> Bool` with the comment `/// Returns true if these arrays contain the same elements.`
Comment: Direct pointer comparison is `===`
Comment: Doesn't work. === says -> [String] does not conform to AnyObject
Comment: @Anorak `===` is only for classes, `Array` is a struct.
Answer: You're right to be slightly nervous about ==:
struct NeverEqual: Equatable { }
func ==(lhs: NeverEqual, rhs: NeverEqual)->Bool { return false }
let x = [NeverEqual()]
var y = x
x == y  // this returns true

[NeverEqual()] == [NeverEqual()] // false
x == [NeverEqual()] // false

let z = [NeverEqual()]
x == z // false

x == y // true

y[0] = NeverEqual()
x == y // now false

Why?  Swift arrays do not conform to Equatable, but they do have an == operator, defined in the standard library as:
func ==<T : Equatable>(lhs: [T], rhs: [T]) -> Bool

This operator loops over the elements in lhs and rhs, comparing the values at each position.  It does not do a bitwise compare – it calls the == operator on each pair of elements.  That means if you write a custom == for your element, it'll get called.
But it contains an optimization – if the underlying buffers for the two arrays are the same, it doesn't bother, it just returns true (they contain identical elements, of course they're equal!).
This issue is entirely the fault of the NeverEqual equality operator.  Equality should be transitive, symmetric and reflexive, and this one isn't reflexive (x == x is false). But it could still catch you unawares.
Swift arrays are copy-on-write – so when you write var x = y it doesn't actually make a copy of the array, it just points x's storage buffer pointer at y's.  Only if x or y are mutated later does it then make a copy of the buffer, so that the unchanged variable is unaffected.  This is critical for arrays to behave like value types but still be performant.
In early versions of Swift, you actually could call === on arrays (also in early versions, the mutating behaviour was a bit different, if you mutated x, y would also change even though it had been declared with let – which freaked people out so they changed it).
You can kinda reproduce the old behaviour of === on arrays with this (very implementation-dependent not to be relied-on except for poking and prodding investigations) trick:
let a = [1,2,3]
var b = a

a.withUnsafeBufferPointer { outer in
    b.withUnsafeBufferPointer { inner in
        println(inner.baseAddress == outer.baseAddress)
    }
}

Comment: Just for the sake of being correct. Now [[1]] == [[1]] returns true (Swift 2.3)
Comment: There's more to this than meets the eye. `[1] == [1]` returns `true`, but `[[1]] == [[1]]` returns `false`. Beware!
Comment: Ah yes, fun one that.  It's actually because of a bug in the Swift compiler (confirmed by the Swift team previously), and it shouldn't compile. It is not using the `Array` `==` operator. Can't be, because arrays are not equatable so doesn't match the definition I gave in my post. Instead what's happening is Swift is doing an implicit conversion of the array literals to a pointers, and then the `==` for `UnsafePointer` is being used. The bug is, this should not kick in for operators, only for function calls (it's only there to make calling of C functions that need to take a const array easier).
Comment: Actually, arrays conform to Equatable when the types of their elements conform to Equatable. It wouldn't make sense for the `==` to be defined on arrays if they were never equatable. See https://developer.apple.com/documentation/swift/array/2949952
Answer: == in Swift is the same as Java's equals(), it compares values.
=== in Swift is the same as Java's ==, it compares references.
In Swift you can compare array content values as easy as this:
["1", "2"] == ["1", "2"]

But this will not work if you want to compare references:
var myArray1 = [NSString(string: "1")]
var myArray2 = [NSString(string: "1")]

myArray1[0] === myArray2[0] // false
myArray1[0] == myArray2[0] // true

So the answers:

I think the performance is optimal for doing value (not reference)
comparisons
Yes, if you want to compare values
Swift arrays are value type and not reference type. So the memory
location is the same only if you compare it to itself (or use unsafe
pointers)
Comment: `===` will only work for reference types. Value types always has only 1 reference to to them so `===` wouldn't makes sense for them. Arrays are "considered" to be copied like all structs, but for performance reason under the hood arrays are not copied unless the are being mutated.
Comment: Keep in mind that `==` array comparison only works if array items are non-optional. For example, if `let str1: String? = "abc"`, and `let str2: String? = "abc"`, then `[str1] == [str2]` is `false`, but `[str1!] == [str2!]` is `true`.
Comment: === doesn't work. Apparently it used to. Any other way to do it ? Plus what if you call a func with a very large array ? Is this gonna copy the whole array as stated in the documentation ? Looks like overhead to me.
Comment: The reason `myArray1 == myArray2` is that `NSObject` conforms to `Equatable`, calling `-[equals:]` to conduct the test.
Comment: @BrianNickel If you had a chance, can you take a look at [this question](https://stackoverflow.com/questions/50275692/remove-duplicates-from-a-multi-dimensional-array?noredirect=1#comment87568249_50275692). It's about your comment. Kirsteins's answer seems a bit misleading :)
Answer: It depends on how do you want to compare. For example:

["1", "2"] == ["1", "2"] // true

but

["1", "2"] == ["2", "1"] // false

If you need that second case to also be true and are ok with ignoring repetitive values, you can do:

Set(["1", "2"]) == Set(["2", "1"]) // true

(use NSSet for Swift 2)
Answer: For compare arrays of custom objects we can use elementsEqual.
class Person {

    let ID: Int!
    let name: String!

    init(ID: Int, name: String) {

        self.ID = ID
        self.name = name
    }
}

let oldFolks = [Person(ID: 1, name: "Ann"), Person(ID: 2, name: "Tony")]
let newFolks = [Person(ID: 2, name: "Tony"), Person(ID: 4, name: "Alice")]

if oldFolks.elementsEqual(newFolks, by: { $0.ID == $1.ID }) {

    print("Same people in same order")

} else {

    print("Nope")
}

Comment: +1 for using elementsEqual. To check whether two arrays are exactly equal, sort them before applying elementsEqual method
Comment: Isn't `elementsEqual` the same as the `==` operator in the form of a method?
Answer: Arrays conform to Equatable in Swift 4.1, negating the caveats mentioned in previous answers.  This is available in Xcode 9.3.
https://swift.org/blog/conditional-conformance/

But just because they implemented == did not mean Array or Optional conformed to Equatable. Since these types can store non-equatable types, we needed to be able to express that they are equatable only when storing an equatable type.
This meant these == operators had a big limitation: they couldn't be used two levels deep.
With conditional conformance, we can now fix this. It allows us to write that these types conform to Equatable—using the already-defined == operator—if the types they are based on are equatable.
Answer: Whereas comparing arrays in swift, must be clear what are the comparison entities.
Ex:
A = [1,2,3]
B = [2,1,3]

return A == B -> false
The comparison is being made traversing both arrays and comparing its index's data.

return Set(A) == Set(B) -> true
Because of function Set(), the comparison is made by whole single value collection.

"Set operations are not limited to use with other sets. Instead, you
can perform set operations with another set, an array, or any other
sequence type."
Use the "equal to" operator (==) to test whether two sets contain  > the same elements.
https://developer.apple.com/documentation/swift/set

Can find more here:
https://docs.swift.org/swift-book/LanguageGuide/CollectionTypes.html
Answer: If you have an array of custom objects, one has to be careful with the equality test, at least with Swift 4.1:
If the custom object is not a subclass of NSObject, the comparison uses the static func == (lhs: Nsobject, rhs: Nsobject) -> Bool, which has to be defined.
If it is a subclass of NSObject, it uses the func isEqual(_ object: Any?) -> Bool, which has to be overridden.
Please check the following code, and set breakpoints at all return statements.
class Object: Equatable {

    static func == (lhs: Object, rhs: Object) -> Bool {
        return true
    }
}

The following class inheritates Equatable from NSObject
class Nsobject: NSObject {

    static func == (lhs: Nsobject, rhs: Nsobject) -> Bool {
        return true
    }

    override func isEqual(_ object: Any?) -> Bool {
        return true
    }

}

They can be compared with:
let nsObject1 = Nsobject()
let nsObject2 = Nsobject()
let nsObjectArray1 = [nsObject1]
let nsObjectArray2 = [nsObject2]
let _ = nsObjectArray1 == nsObjectArray2

let object1 = Object()
let object2 = Object()
let objectArray1 = [object1]
let objectArray2 = [object2]
let _ = objectArray1 == objectArray2

Compare arrays in swift


Is there a way to downgrade core from 9.3.6 to 9.2.7?

Question: After updating the Drupal core version from 9.2.7 to 9.3.6 I got an error.

TypeError: Argument 1 passed to Drupal\Core\File\FileUrlGenerator::generateAbsoluteString() must be of the type string, null given

I tried to apply the patch in TypeError: Argument 1 passed to Drupal\Core\File\FileUrlGenerator::generateString() must be of the type string, null given but it gives an error.

Could not apply patch! Skipping. The error was: Cannot apply patch 3254245-78.patch.

Is it possible to downgrade the core version to get rid of this issue?
Comment: Which patch from that issue did you try? The latest ones are against 9.4, so it doesn't surprise that they don't apply. Maybe try https://www.drupal.org/project/drupal/issues/3254245#comment-14339531 before downgrading. And yes, downgrading core is an option, but probably not the best one. Drupal 9.2 is still maintained until June 15, 2022, see https://www.drupal.org/about/core/policies/core-release-cycles/schedule
Comment: I tried to apply the patch you mentioned but I am getting the same error
Comment: Just wait the patch is committed. Usually, they commit it on Drupal 9.4 and Drupal 9.3. As @berliner said, the latest working patch is for Drupal 9.4; without cherry-picking, it's not possible to use it on Drupal 9.3.
Answer: If you already ran the database updates, no, you cannot downgrade; you need to fix the error.
If you did not run the database updates, you should be able to revert the code (for example, in git if you're using that) without any problem.
The real solution is to always make a database backup (and code backup if you are not using version control) before updating anything.
If you already have a database backup
You can re-install the old version of Drupal (9.2.7) and then restore the database backup and everything should be fine.  You can do it locally with whatever environment you are using to develop your site.
Comment: I have the database backup, but I am not using any type of version control is it possible to do it in local environment
Comment: @SamBara Yes, should be no problem.  Restore the code; then restore the database.
Comment: can I use the same method which is used to upgrade Drupal manually like deleting all the file except the sites, module and profile file and then paste the file from this zip
Comment: @SamBara Yes, you can.  You can install an old version in exactly the same way that you upgrade to a new version.  In the future, you can make your life a lot easier if you learn to use git for version control and install Drupal that way; using git, you can undo a bad upgrade with a single command (`git revert`) and a database restore.
Comment: Thanks for the help my site is up and running again.
Comment: @SamBara You're welcome.  However, on *Drupal Answers* and other Stack Exchange network sites, you don't need to say thanks; instead, check the checkbox to accept the answer and upvote the question by clicking the up arrow.


Combinatorics struggles

Question: I am stuck in combinatorics problem that there must be a solution to but every experiment is leaving me stuck.
I am needing to build a bracket for a some games at a graduation event:

There will be $8$ teams doing eight events. They will complete against each other in each event. The eight events will be in two different time blocks.
So events $1$-$4$ will happen simultaneously and will be repeated for a total of four times, then events $5$-$8$ will happen simultaneously and will be repeated for a total of four times.

$\textsf{My goal}$ is to have each team face all the other teams.
I realize each team will have to repeat one event and face one team twice. It is quite similar to a round robin tournament but I cant figure out how to keep them from repeating events.
Help would be greatly appreciated.
Comment: What is an event? Is an event like a match/game, where two teams face against each other?
Answer: For any one team, there is a maximum of $7$ distinct pairings with other teams for the various events. Since you have $8$ events, you must have at least one pairing repeat. Another way of thinking about this would be the fact that there are only 28 distinct team pairings and you are trying to uniquely assign 32 events, which is impossible.
The easiest solution would be to eliminate one of the events.
For example Teams $1-8$ competing in Events $A-G$ could be matched up as follows:
$$
\begin{array}{c|cccccccc}
 &1&2&3&4&5&6&7&8\\ \hline
1& &A&B&C&D&E&F&G\\
2&A& &C&D&E&F&G&B\\
3&B&C& &E&F&G&A&D\\
4&C&D&E& &G&A&B&F\\
5&D&E&F&G& &B&C&A\\
6&E&F&G&A&B& &D&C\\
7&F&G&A&B&C&D& &E\\
8&G&B&D&F&A&C&E&
\end{array}
$$
If you insist on $8$ events, assign the pairings for event $H$ the same pairing of event $A$. Now you'll want to run events $A,B,C,D$ as your first group of events and $E,F,G,H$ as your second group of events.

Combinatorics struggles


How to redirect to CodeIgniter controller using angular js

Question: I am using CodeIgniter controller functions.
(example)
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Me extends CI_Controller {
    public function __construct()
       {
            parent::__construct();
            if (is_logged_in()){if (is_admin()) { redirect('login');  }}
            else { redirect('login');}
       }
    public function change_password()
    {
        $id=$this->session->userdata['user_data']['id'];
        $data = json_decode(file_get_contents("php://input"));

        $my_data=array(
            'pass'=>$data->pass,
            'new_pass'=>$data->new_pass,
            );
        $result=$this->vanesh_model->change_pass($id,$my_data);
        if($result==1)
        {
            $arr = array('msg' => "Password changed successfuly.", 'error' => '');
            $jsn = json_encode($arr);
            print_r($jsn);
        }
        else if($result==2)
        {
            $arr = array('msg' => "", 'error' => 'Old Password is Invalid');
            $jsn = json_encode($arr);
            print_r($jsn);
        }
        else if($result==3)
        {
            $arr = array('msg' => "", 'error' => 'Sorry, Password change failed');
            $jsn = json_encode($arr);
            print_r($jsn);
        }
    }
}
?>

I am afraid of using angular session services, so I want to maintain sessions with only CI. What I am doing in my application is add, update, delete only if he is logged in. And I am using information stored in session. Consider the situation, suppose, I am logged in and doing something, side by side: I destroy the session using browser tools. Now I am continuing with application (doing operations like: change password). I have/had maintained error messages, success messages, its ok. If session OFF, it gives error message. But instead of error messages, I want to redirect to LOGIN page(with page refresh).
Note: For CI Login controller, I didn't used angular js. I have used angularjs only after login.

If by opening new tab I destroy the session, and come back to application's tab: I am able to perform tasks(may be with errors,). If session is OFF I see this in Browser's console: http://localhost/ums/login
This is because of CI constructor(please look over the code).
Answer: You should separate angular and CI as much as possible, since both have view-controller it creates a mess. Instead you should have CI in a separate folder, call it api, for example, after that anything you will need from CI should be acessed from angular with ajax calls.
I made a small webapp a while ago and this seemed to be the best way to organize code.
Few updates have been made to angular since then so if there's a better way please let me know
Answer: Solved.
Used javascript function. Checking session by http request everytime. If response comes "1". Means redirect to login as:
/* function for checking logged-in and role */
function check_session()
{
    $.get("servercontroller/check_session", function(data, status){
         if(data=="1") /* error 1 => un-athorized user */
        {
            window.location.href="/login-page-url";
        }
        });
}


Comparar duas listas sem interferência de letras em maiúsculo e minúsculo

Question: Quero desenvolver um sistema de log-in onde não permite que usuários novos possuam os mesmos nomes já utilizados por outros usuários já cadastrados, mas estou tendo uma dificuldade em questão de letras maiúsculas e minúsculas quando comparo as listas. Como faço para deixar as duas listas com todas letras minúsculas?
current_users  = [ 'Hiquinho', 'pup', 'billy', 'jp', 'pichuto', 'schuh']
new_users = [ 'HIQUINHO', 'sara', 'Billy', 'amalia', 'lucca', 'Schuh']
if new_users:
    for new_user in new_users:
        if new_user.lower() in current_users:
            print('Nome ja em uso, forneça outro ID\n')
        elif new_user.lower() not in current_users:
            print('Seja bem vindo, somos muito gratos pelo seu login '
            + new_user.title() + '!\n')

Answer: Quando o nome do usuário é 'HIQUINHO', ao chamar lower ele se torna hiquinho, e você compara com os valores da outra lista, que só tem 'Hiquinho', por isso ele acha que este usuário ainda não foi utilizado.
Sendo assim, você deve comparar cada novo usuário com a versão em minúsculas dos usuários atuais:
current_users  = [ 'Hiquinho', 'pup', 'billy', 'jp', 'pichuto', 'schuh']
new_users = [ 'HIQUINHO', 'sara', 'Billy', 'amalia', 'lucca', 'Schuh']
current_users_lowercase = list(map(str.lower, current_users))

for new_user in new_users:
    if new_user.lower() in current_users_lowercase:
        print(f'Nome {new_user} já em uso, forneça outro ID')
    else:
        print(f'Seja bem vindo, somos muito gratos pelo seu login {new_user.title()}!')

Veja também que não precisa testar se a lista new_users está vazia. Se estiver, ele nem entra no for, então o if new_users:  é redundante.
E a condição do elif também é redundante. Se o usuário está na lista, ele entra no if, e se não estiver, ele vai para o else (ou seja, não precisa testar de novo isso com elif, pode usar else direto).
A saída do código acima é:
Nome HIQUINHO já em uso, forneça outro ID
Seja bem vindo, somos muito gratos pelo seu login Sara!
Nome Billy já em uso, forneça outro ID
Seja bem vindo, somos muito gratos pelo seu login Amalia!
Seja bem vindo, somos muito gratos pelo seu login Lucca!
Nome Schuh já em uso, forneça outro ID

Vale lembrar que, dependendo dos caracteres que podem ter no nome do usuário, nem sempre lower() funciona. Por exemplo, o caractere alemão ß é equivalente a "ss", mas lower() não o altera. Para estes - e muitos outros - casos, a documentação recomenda o uso de casefold:
print('ß'.lower()) # ß
print('ß'.casefold()) # ss

Ou seja, bastaria trocar para:
current_users  = [ 'Hiquinho', 'pup', 'billy', 'jp', 'pichuto', 'schuhss']
new_users = [ 'HIQUINHO', 'sara', 'Billy', 'amalia', 'lucca', 'Schuhß']

# usar casefold em vez de lower
current_users_lowercase = list(map(str.casefold, current_users))

for new_user in new_users:
    if new_user.casefold() in current_users_lowercase: # usar casefold em vez de lower
        print(f'Nome {new_user} já em uso, forneça outro ID')
    else:
        print(f'Seja bem vindo, somos muito gratos pelo seu login {new_user.title()}!')

Claro que se só tiver caracteres ASCII, usar lower é o suficiente.
Comment: muito obrigado!
Answer: Caso o objetivo seja apenas emitir a mensagem de saudação sem ter que fazer qualquer ação configuração adicional é possível utilizar uma abordagem mais funcional usando uma expressão lambda aplicada com o builtin map() dentro de list comprehension cujo o texto a ser exibido seja decidido através de uma expressão condicional.
current_users  = [ 'Hiquinho', 'pup', 'billy', 'jp', 'pichuto', 'schuh']
new_users = [ 'HIQUINHO', 'sara', 'Billy', 'amalia', 'lucca', 'Schuh', 'User1']

#Converte cada elemento de current_users caixa alta e armazena no array users
users= [str.casefold(e) for e in current_users]

#Junta todos os log e os imprime separados por um \n
print("\n".join([
    #Operador ternário se t[0] for true devolve a primeira frase senão devolve a outra.
    f'{str.title(t[1])} já está em uso, forneça outro ID.'
    if t[0] else f'Seja bem vindo {str.title(t[1])}, obrigado pelo login!'
    #Para cada elemento e em new_users retorna a tupla t (str.casefold(e) in users, e).
    for t in map(lambda e : (str.casefold(e) in users, e), new_users)
]))

Resultado:
Hiquinho ja em uso, forneça outro ID.
Seja bem vindo Sara, obrigado pelo login!
Billy ja em uso, forneça outro ID.
Seja bem vindo Amalia, obrigado pelo login!
Seja bem vindo Lucca, obrigado pelo login!
Schuh ja em uso, forneça outro ID.
Seja bem vindo User1, obrigado pelo login!

Teste o exemplo no repl.it
Caso o objetivo seja realizar uma ou mais ações dependo do resultado da verificação de que o elemento de new_users esteja ou não contido em current_users você pode usar um controle de fluxo mais imperativo usando for e if:
current_users  = [ 'Hiquinho', 'pup', 'billy', 'jp', 'pichuto', 'schuh']
new_users = [ 'HIQUINHO', 'sara', 'Billy', 'amalia', 'lucca', 'Schuh', 'User1']

#Converte cada elemento de current_users caixa alta e armazena no array users
users= [str.casefold(e) for e in current_users]

#Essa lista irá receber os nomes de usuário que estiver em new_users e
# que não estejam em current_users.
trusted_users = []

#Para cada elemento e em new_users retorna a tupla t (str.casefold(e) in users, e).
for t in map(lambda e : (str.casefold(e) in users, e), new_users):
  #Verifica resultado da expressão str.casefold(e)...
  if t[0]:
    #...se True o usuário já está em uso.
    print(f'{str.title(t[1])} já em uso, forneça outro ID.')
  else:
    #...se False o nome de usuário ainda não está em uso.
    trusted_users.append(t[1]) #... o adiciona a lista trusted_users.
    print(f'Seja bem vindo {str.title(t[1])}, obrigado pelo login!')

#Imprime a lista trusted_users.
print(f'\nNovos usuários verificados: {trusted_users}')

Resultado:
Hiquinho ja em uso, forneça outro ID.
Seja bem vindo Sara, obrigado pelo login!
Billy ja em uso, forneça outro ID.
Seja bem vindo Amalia, obrigado pelo login!
Seja bem vindo Lucca, obrigado pelo login!
Schuh ja em uso, forneça outro ID.
Seja bem vindo User1, obrigado pelo login!

Novos usuários verificados: ['sara', 'amalia', 'lucca', 'User1']

Teste o código no repl.it
Comment: muito obrigado!


C++ copy and move constructors with lambda expressions

Question: I've bumped into something strange with C++ copy and move constructors, here when passing to the lambda expression both the copy and move constructors get executed. Strangely though, when I change the declared type of the lambda to auto or use the regular_test function, I get the expected behaviour (copy construction only). Does anyone understand why this is? (tested with both clang and gcc, not msvc)
#include <iostream>
#include <iomanip>
#include <functional>

using namespace std;

struct Test {
    inline Test() {
        cout << setw(20) << "constructor ";
        PrintAddress();
    }

    Test(const Test&) {
        cout << setw(20) << "copy constructor ";
        PrintAddress();
    }

    Test& operator=(const Test&) {
        cout << setw(20) << "copy assignment ";
        PrintAddress();
        return *this;
    }

    Test(Test&& other) {
        cout << setw(20) << "move constructor ";
        PrintAddress();
    }

    Test& operator=(Test&&) {
        cout << setw(20) << "move assignment ";
        PrintAddress();
        return *this;
    }

    virtual ~Test() {
        cout << setw(20) << "destructor ";
        PrintAddress();
    }

    void PrintAddress() {
        cout << "Test&: " << this << endl;
    }
};

Test regular_test (Test t) {
    cout << "regular_test" << endl;
    return t;
}

int main() {
    cout << "start" << endl;
    function<Test(Test)> lambda_test = [] (Test t) {
        cout << "lambda_test" << endl;
        return t;
    };
    Test t;
    lambda_test(t);
    //regular_test(t);
    cout << "done" << endl;
    return 0;
}

start
        constructor Test&: 0x7fffef6faf28
   copy constructor Test&: 0x7fffef6faf08
   move constructor Test&: 0x7fffef6fade8
lambda_test
   move constructor Test&: 0x7fffef6faf10
         destructor Test&: 0x7fffef6fade8
         destructor Test&: 0x7fffef6faf10
         destructor Test&: 0x7fffef6faf08
done
         destructor Test&: 0x7fffef6faf28

Comment: auto:  `function`
Answer: because std::function::operator() is defined based on the template type of class.
R operator()( Args... args ) const; // Args are parameter of the *class*

so std::function<Test(Test)> would have Test operator()(Test), which would make a copy by itself, then forward to lambda_test (a move)
Comment: ok but why does changing `function lambda_test` to `auto lambda_test` fix the problem?
Comment: @DavidCarpenter because auto doesn't add another wrapper. (the lambda is not even copied)


PHP crashing during oAuth scripts

Question: I just installed Nginx 1.2.4 and PHP 5.4.0 (from svn) (php fpm). CentOs 5.8 64
The problem I have is that PHP crashes the moment I run any social oAuth scripts. I have tried to log into Facebook, Twitter and Google with various scripts that I know work on my other servers. When I load the scripts I get a 502 error from Nginx. And I find these errors in the log:
in php-fpm log:
WARNING: [pool www] child 23821 exited on signal 11 (SIGSEGV) after 1132.862984 seconds from start

in nginx log:
ERROR: recv() failed (104: Connection reset by peer) while reading response header from upstream

From what I can see, it goes wrong when PHP tries to make a request to any of the oAuth servers.
https://github.com/mahmudahsan/PHP-SDK-3.0---Graph-API-base-Facebook-Connect-Tutorial-Source for example is one of the scripts that works perfectly on my other machines, but causes PHP to crash.
I found: https://stackoverflow.com/questions/3616191/nginx-php-fpm-502-bad-gateway which seems to be a similar problem, but I cannot find a way to solve it.
+++ UPDATE +++
Now I have been doing some debugging in 1 of the scripts that is playing up.
If you go to line 808 http://pastebin.com/gSnzRtXb it runs the curl_exec()
command.
When that is ran, it crashes. If i echo'test';exit; just above that line, it
echo's correctly, if i do it below that line, php crashes.
Which means it's that line 808 which causes the crash.
So I made a very simple script to do some testing: http://pastebin.com/Rshnyhcm
which also uses curl_exec, but that runs just fine.
So I started to dig deeper into that query from the facebook script to see what
values the $opts array contains from line 806.
Output of that array is: http://pastebin.com/Cq9ffd3R
What the problem is, I still have no clue :(
Comment: Your problem sounds like a mismatch between libcurl version and php-curl module.  Do you have more than one libcurl installed?  When you compiled PHP it may have used a different version of libcurl than the one it's trying to use now.
Comment: How could I find out if this is the case?
Comment: Did you say PHP 5.4.0? I'm quite sure there have been several bug-fix releases since then...
Comment: Found out what is causing the problem. cURL requests in PHP that request an https:// link cause PHP to crash. http:// links work fine. Weirdly enough cURL is configured with https support though: http://i.imgur.com/zfkj5.png so I have no idea how to fix it.
Comment: That means it's likely a difference between libcurl's openssl library and either PHP or apache's openssl library
Comment: Hi DerfK, how could I check the difference between the libcurl and php openssl library?
Answer: Was solved by upgrading to PHP 5.4.8

PHP crashing during oAuth scripts


How to hide empty region in Omega

Question: It seems that by default all regions are rendered in Omega theme because of the Debug blocks.

Sidebar First

This is a debugging block

Is there a way to have an option to debug blocks and hide empty blocks at the same time?
Answer: Go to admin/appearance/settings/your_subtheme_name. Check attached image. You can set rights on who is or isn't allowed to see debugging stuff.
Uncheck debugging options will hide empty blocks...
Comment: But this hides debugging option from the user completely. I want to be able to see debugging blocks and hide them completely without going to configs.
Comment: Use roles option. check for "administrator" only...
Comment: yes, but then as administrator I will see the broken page..
Comment: I will vote up the answer as it is helpful, but there is still a problem with the theme as it is not practical to change config all the time. I would rather had this region removed completely when Debug is off in the theme.
Comment: this doesn't make sense. if debug option is checked, then empty block will be shown . thats it.....
Comment: why does it need to show the empty block, sorry I don't get it.
Comment: To use debugging option
Comment: This is inconvenient, cause it breaks layout even when I hide blocks.

How to hide empty region in Omega


Redirection of http to https not working

Question: I want to redirect my subdomain to https. My .htaccess file contains the following:
RewriteEngine On
RewriteCond %{HTTPS} !on
RewriteRule (.*) https: //%{HTTP_HOST}%{REQUEST_URI}

It's redirecting to https but my chrome browser giving an error

This webpage has a redirect loop The webpage at https:
  //sub.domain.com/ has resulted in too many redirects. Clearing your
  cookies for this site or allowing third-party cookies may fix the
  problem. If not, it is possibly a server configuration issue and not a
  problem with your computer. Learn more about this problem. Error code:
  ERR_TOO_MANY_REDIRECTS

please help me
Comment: Does your .htaccess file really have a space between `https:` and `//`?  If so, there's your trouble.
Answer: I'm currently using following configuration for redirecting all requests for http://somedomain to https://somedomain:
RewriteRule ^(.*)$ https://%{HTTP_HOST}$1 [redirect=301]


How to compute the left singular eigenvector matrix (U) from the output of prcomp() for PCA in R?

Question: I am examining the output of the prcomp() function in R for PCA in light of the singular value decomposition equation:
$X = U \cdot \Sigma \cdot V^{T}$, where:
$X$: is the standardized original data matrix
$\Sigma$: is the eigenvalues matrix given by the output of prcomp() as $sdev but squared root
$V$: is the right singular eigenvector matrix (wrongly called loadings) in the output of prcomp() as $rotation
$U$: is the left singular eigenvector is NOT given by the output of prcomp(), unlike svd() as $u, however prcomp() provides the raw component scores matrix ($U\cdot \Sigma$) as $x which is practically useful for plotting purposes.
Now suppose I want to compute the $U$ matrix from the output of the prcomp() function using the mtcars built-in dataset.
To achieve this mathematically, both sides of the equation need to be multiplied by $\Sigma^{-1} \cdot V$ this will result in identity matrices for both $V$ and $\Sigma$ on the right side leaving us with:
$U = X \cdot \Sigma^{-1} \cdot {V}$
Note: I used svd() function for the sake of validating the results
My trial in R
# the svd() method
A <- as.matrix(mtcars[,c(1:7,10,11)], row = 9, byrow = T)
S <- scale(A)
svd.pca <- svd(S)
svd.pca$u # left singular eigenvector matrix U

# the prcomp() method
prcomp.pca <- prcomp(A, center = TRUE,scale. = TRUE)

# to get inverse of a matrix in R we use the solve() function
diag(prcomp.pca$sdev) %*% (solve(diag(prcomp.pca$sdev))) # identity matrix for Sigma
prcomp.pca$rotation %*% t(prcomp.pca$rotation) # identity matrix for V

# now compute the U matrix from prcomp() output per the equation above for U
prcomp.pca$u <- S %*% (solve(diag(prcomp.pca$sdev))) %*% t(prcomp.pca$rotation)
prcomp.pca$u

round(svd.pca$u, 3) == round(prcomp.pca$u, 3) # FALSE, what am I missing?

So the computed $U$ matrix eventually didn't match the $U$ matrix of the svd() function, what am I missing here to obtain the $U$ matrix from the output of prcomp()?
Comment: @whuber, you mean `stats:::prcomp.default` 3 semicolons instead of 2. I am inspecting it right now.
Comment: Why not just inspect the source?  The code is in `stats::prcomp.default` and is only a few dozen lines long.  Note that without details of how the algorithm works, you cannot expect to recover $U$ exactly because it is not uniquely defined: in particular, any of its columns may be arbitrarily negated.
Comment: @whuber, so from source code the difference was in the sigma part, now U matrix could be recovered. Thanks for the hint!
Answer: This can be achieved by computing the $\Sigma$ first from the prcomp() function to make it numerically equivalent to that of the svd()and it turned out after inspecting the source code of prcomp() this can be achieved by the following:
sigma <- prcomp.pca$sdev * sqrt(max(1, nrow(S) - 1))
round(sigma, 2) == round(svd.pca$d, 2) # TRUE

diag(sigma) %*% solve(diag(sigma)) # identity matrix of Sigma
prcomp.pca$rotation %*% t(prcomp.pca$rotation) # identity matrix of V

prcomp.pca$u <- S %*% prcomp.pca$rotation %*% solve(diag(sigma))
round(svd.pca$u, 3) == round(prcomp.pca$u, 3) # TRUE


How much rosin should I apply to my bow to get a better sound?

Question: I bought a new violin, but I have a problem when I rosin my bow. I rosin for a while until powder comes off, but when I play it does not sound good.
I observe some videos and websites that suggested I might need more rosin, So I tried that, but it keeps making the same sound. Can somebody explain what else I should do.
I don't know anyone proficient i could ask.
Comment: Do you know roughly how old the bow is?
Answer: You need a teacher, or at least an experienced violinist who can tell you whether the hair on the bow is dead, or the strings are dead, and suggest a reasonable level of rosining.  The appearance of dust is more a function of the particular rosin than of the amount on the bow.
Answer: If you are new with violin, your tone will be awful.  That's not something that rosin can fix (in fact, it will more likely than not worsen it in the amounts you appear to apply) but is due to a lack of technique.  Maintaining consistent light pressure throughout the bow length in spite of its weight and the widely varying leverage is hard, and maintaining consistent position between bridge and finger board is hard.
Rosin makes the difference between a correctly played bow slipping without making a sound and it sounding.  Beyond that, its helpfulness is moderate at best, and it's also worth making sure that the rosin is comparatively fresh and that you don't have a lot of old dusty residues on strings and bow (which will make the sound scratchier rather than smoother).
This is not chalk.
How does your instrument sound in the hands of an experienced player?
Answer: If it's a new bow it might take a while for the rosin to adhere properly. Then again I've used a new bow straight away and it was fine! Too much rosin can sound bad. Violin For Dummies recommends just 2 or 3 runs with the rosin along the full length of the bow as being sufficient. Having said that, I've seen some fiddle player friends rubbing on what I think is way too much, and then sounding great.  If you're new to violin/fiddle, it's most likely inexperience that has you sounding bad - it's a brute of an instrument to get to grips with in the early days, but it comes with time. In my case, the first 20 years were the worst! Too much rosin on the strings is bad too. About once a month I clean it off with turpentine and a rag.Slip a piece of card under the strings so you don't harm the finish on the finger board.
Comment: Turpentine is a **VeryBadIdea**.  First, as you note, it can damage the instrument.  Second, if any part of the string is nonmetallic, you'll damage the string.  Third, a wound string will retain some fluid & drip onto the instrument body later.  Clean strings **only** with a soft cloth immediately after playing, and occasionally with one of those "plastic steel wool" pads.
Comment: Just a little turps on a rag folks. I'd argue it's a good idea as it's the natural solvent for rosin. And dripping out of the string winding later? How much would it take to do that Carl?  Moderation in all things!
Comment: I've talked with luthiers and my highly experienced teachers (professional cellists).  They all agree that use of solvent is a VBI


What's the explanation for the distribution of this kind of dice roll?

Question: Consider the following type of dice roll for the attack damage in some tabletop RPG:

Roll three six-sided dice.
Pick two of them that have a sum greater six.
The remaining die is the attack damage.
If no combination of two dice has a sum greater than six then the attack damage is zero.

Naturally players want to maximize damage and thus pick the lowest possible sum of two dice that is still greater than six.
I tried to simulate that roll to see the probability distribution of the attack damage and was surprised that there is a probability of ~20% to roll the maximum damage of six.
Here is the full distribution after 1M rolls:

dmg
p

0
0.195335

1
0.153332

2
0.097448

3
0.125001

4
0.101249

5
0.115615

6
0.21202

I makes sense to me that the attack damage is biased towards higher values, because players will choose the higher one when having the choice, but I kind of expected the distribution to increase from 1 to 6 as a result of that instead of fluctuating so much.
So what's happening here?

Inspired by some of the comments I plotted the distribution with this roll/selection for different kind of dice:

The target value is always the most probable value when rolling two dice and taking the sum (so 7 for d6, 11 for d10 and 21 for d20).
Comment: I suspect there's no analytical way to do that with as small a face count as $6$. I'm curious as to what would happen if we "rolled" three uniformly distributed values from $0$ to $1$, and played the same rules, but with the pair-sum threshold set at $1$. I might try that in a bit.
Comment: I mean, I have a *general* explanation, or a guess at one, in that we progress through cases where (a) there is no pair of dice that sum to $7$ or more; (b) we have to add the largest two results to get to $7$ or more; (c) we add the minimum and maximum; and (d) we add the smallest two results. Each of those transitions is a discontinuous change in the behavior as the attack damage progresses respectively through (a) no damage; (b) smallest die damage; (c) middle die damage; and (d) largest die damage. So it's not surprising that there are fluctuations, but we still need to tally the cases.
Comment: In the continuous version (three numbers chosen uniformly in $[0, 1]$, remove two whose sum is $> 1$), it seems that (aside from the point-mass at $0$) the probability density function is proportional to  the piecewise function $\begin{cases} 3t^2 - 2t + 1/2, & t < 1/2 \\ 3t^2 - 4t + 3/2, & t > 1/2\end{cases}$, with minima at $t = 1/3$ and $t = 2/3$.
Comment: @JBL: I'll check that later against my empirical plot, but that looks approximately right, with a proportionality constant of $3$.
Comment: As @lulu states, there are $216$ possible outcomes, and the tallies from $0$ through $6$ are $[42, 33, 21, 27, 22, 25, 46]$. If you divide those by $216$, you'll get more or less the proportions you tabulated. I don't have an intuitive explanation for the fluctuations, though.
Comment: For three uniformly distributed values from $0$ to $1,$ discarding two values that sum to at least $1,$ there is exactly $1/4$ chance of zero damage. But unlike the uniform $[0,1]$ distribution, where any two values have an expected sum of $1,$ two $6$-sided dice have an expected sum greater than $6.$
Comment: @JBL Yes, plausible - the right hand part of your third chart looked linear in simulation but apparently is slightly curved
Comment: There are only $6^3=216$ possible outcomes...you can get the exact answers easily enough (at least with mechanical assistance).
Comment: This is a trivial note but *really* there are only $\left(\!\binom{6}{3}\!\right) = 56$ possible outcomes (not equally likely, of course) and so doing this by hand is not hard at all.
Comment: @JBL: I agree it's not hard, but it is a little tedious, and probably prone to error. Also, if you reduce to $56$, you also need to track how often each combination (*vice* permutation) shows up—also easy, also tedious, also prone to error. :-) ¶ I also don't think the d$6$ case is very illuminating; that's why I suggested the continuous extension.
Comment: @BrianTung: The continuous result is similar to the discrete case with many sides: (a) the probability of $0$ increases with the cuttoff in an intuitively natural way;   (b) there is a counter-intuitive $\omega$ type shape with two low areas (corresponding to the $2$ and $4$ with $6$-sided dice) though with low cuttoffs not all of the left part of this appears; and (c) with cuttoffs more than $1$ some low positive values are equally probable.
Comment: @JBL: That is consistent with my "$\omega$ type shape" comment. Is that easily extended to other cuttoffs? (I suspect there may be a constant piece with a cuttoff below $1$ and a linear piece with a cuttoff above $1$)
Comment: @Henry I found the constant piece but not the linear piece (instead another quadratic) -- plausible?
Comment: @BrianTung See my answer below.
Comment: @JBL: Well done. I lost patience with the bookkeeping long before I finished. :-)
Answer: This is an answer to the question being discussed in comments by @Brian Tung and @Henry.
Let's start with the closest analogue of the original question: three numbers $a, b, c$ are uniformly generated in $[0, 1]$, and the final score is computed by choosing two of them that add to at least $1$ and discarding them; or is equal to $0$ if no two of them sum to $1$.
As @David K observes in comments, the probability of getting score $0$ is exactly $\frac{1}{4}$: for example, we can see that the situation $a + b + c \leq 1$ forms a tetrahedron of volume $\frac{1}{6}$ in the corner of the probability space $[0, 1]^3$, while the situation $a + b + c > 1$ but $a + b < 1$, $a + c < 1$, $a + c < 1$ forms a tetrahedron with vertices $(0, 0, 1)$, $(0, 1, 0)$, $(1, 0, 0)$, and $(\frac{1}{2}, \frac{1}{2}, \frac{1}{2})$ which is exactly half as large.  So we have a point-mass of $\frac{1}{4}$ at score $0$.
The rest of the probability distribution will be continuous.  Let's compute the probability that we get final score $t$, contingent on the first die coming up $t$.  (Presumably this is where the factor of $3$ Brian Tung noted comes from, since there are three dice.)  When $0 < t < \frac{1}{2}$, the space of pairs $(b, c)$ that work consists of three triangles in $b, c$-plane: one is defined by the inequalities $b + c \geq 1$, $0 \leq b \leq t$, $1 - t \leq c \leq 1$, the second by the inequalities $b + c \geq 1$, $t \leq b \leq 1- t$, $t \leq c \leq 1 - t$, and the third by the same inequalities the first with $b, c$ switched.  This gives a probability density of $\frac{t^2}{2} + \frac{(1 - 2t)^2}{2} + \frac{t^2}{2}$, which can be written in the form in my comment above.  The situation when $ \frac{1}{2} < t < 1$ is very similar (actually you get the same pictures, just with $t$ and $1 - t$ reversed, so the PDF is symmetric across $t = \frac{1}{2}$).
$\alpha = 1$ graph" />
Now let's suppose that instead we have a cutoff of $\alpha$ (i.e., we discard two dice whose sum is at least $\alpha$, instead of whose sum is at least $1$).  Set aside the point-mass at $0$ (which in principle we could compute after the fact).  When $\alpha$ is large ($1 \leq \alpha \leq 2$) we end up with three regimes: for $t < \alpha - 1$, the event that we get score $t$ is the same event that $b + c \geq \alpha$ (since we don't have to worry about discarding $t + b$ or $t + c$ in this case), with constant probability density $\frac{(2 - \alpha)^2}{2}$ (just as @Henry observed).  When $t > \alpha - 1$, the situation is very similar to the case $\alpha = 1$: for $\alpha - 1 < t < \frac{\alpha}{2}$, the probability space in the $b,c$-plane consists of three triangles: one defined by $b + c \geq \alpha$, $\alpha - 1 \leq b \leq t$, $\alpha - t \leq c \leq 1$, a second defined by $b + c \geq 1$, $t \leq b \leq \alpha - t$, $t \leq c \leq \alpha - t$, and the third the same as the first with $b, c$ switched.  This gives density $\frac{(t - (\alpha - 1))^2 + (\alpha - 2t)^2 + (t - (\alpha - 1))^2}{2}$.  The third regime is the mirror image of the second across the line $t = \frac{\alpha}{2}$.
$\alpha = 1.5$ graph" />
When $\alpha$ is small ($0 \leq \alpha < 1$) there are again three regimes; omitting the details, if $t < \frac{\alpha}{2}$ then the probability density is (proportional to) $2 \times t \cdot \frac{(1 - \alpha) + (1 - \alpha + t)}{2} + \frac{(\alpha - 2t)^2}{2}$, if $\frac{\alpha}{2} < t < \alpha$ then the density is the mirror-image of the first case (replacing $t$ with $\alpha - t$), and if $t > \alpha$ then the density is $t^2 - \frac{\alpha^2}{2}$.
$\alpha = .5$ graph" />
Comment: Using three dice with $n \gg 6$ you get similar shapes for the discrete distribution
Answer: For the record, the exact count of ordered rolls with a given "score" is, in order from $0$ to $6$: $$\{42,33,21,27,22,25,46\}$$
which closely matches the simulation.
Perhaps it helps with intuition (or, at least, understanding...it's hard to have useful intuition here, I think) to do the count for score $2$, to see why there are so few cases.  The "problem" is that it's hard to get a $5$ or $6$ in there since $2+5>6$ and the score will probably be the other roll.
Specifically, the possible unordered rolls with score $2$ are:
$$\{2,2,6\},\{2,2,5\},\{2,4,4\},\{2,1,6\}, \{2,3,4\}$$
There are $3$ orderings for each of the first three, and $6$ for each of the last two, to get the total of $21$.
For a score of $1$, by contrast. we have:
$$\{1,1,6\},\{1,4,4\},\{1,5,5\},\{1,2,5\}, \{1,3,4\},\{1,3,5\}, \{1,4,5\}$$
And for a score of $3$ we get:
$$\{3,3,4\},\{3,3,5\},\{3,3,6\},\{3,1,6\}, \{3,2,5\},\{3,2,6\}$$
As I say, it's hard to have intuition...the selection process is a bit more subtle than it appears at first.
Comment: I do not have a problem with one of the values being less common than the others, but it is counter-intuitive to me that $2$ and $4$ are each less common than $1$ and $3$ and $5$, as I cannot see an intuitive parity issue
Comment: @Henry  I seriously tried to sort out a reason for that, but failed.  In the end, it's a weird sort of race that's hard to sort out.  Just try to guess what the pattern would be for some parallel problem with a $20$ sided die.
Comment: I would have guessed "something similar" but could not express what that means.   So I did the calculations with more sides (including with different cuttoffs), and it got stranger: (a) the probability of $0$ increases with the cuttoff in an intuitively natural way;   (b) there is a counter-intuitive $\omega$ type shape with two low areas (corresponding to the $2$ and $4$ with $6$-sided dice) though with very low cuttoffs not all of the left part of this appears; and (c) with cuttoffs more than $1$ more than the number of sides, some low positive values are equally probable.


Dynamic id for HTML element which is getting created newly

Question: I am replacing a span inside a table > td with option box.
I want to assign some unique id with dynamic value while creating the option box. How to achieve this?
Unique id is already generated , I want to set this unique id in Html while creation.

    Enabled

$("#"+spanId).replaceWith(function () {
        return "<select class='form-control' id=<<DYNAMIC ID>> style='width:200px;'><option value='0'>Enabled</option><option value='1'>Disabled</option></select>";
});

For example , I will get some value from and assign to a variable and later assign this variable to id.
var myId = "OptionId"+test;

select class='form-control' id=myId style='width:200px;'>

Thanks
Comment: Like this `"...`
Comment: try Math.random(); jQuery function
Comment: @Cobote , thanks a lot . It worked!!!
Answer: Use a variable within a string like this:
var unqiueID = "myID123", ret = "";
ret = "<select class='form-control' id='" + unqiueID +"' style='width:200px;'>";

Answer: One possible way to ensure that a unique value is assigned is to keep track of all the available id's and assign an id which isn't there in our list.
getUniqueId() is a function that will always return a unique id.
function getUniqueId() {

    //get all the ids in this document
    var ids = new Array();
    $('[id]').each(function() { //Get elements that have an id=
      ids.push($(this).attr("id")); //add id to array
    });

    //give some random value to uniqueId
    //if this value is in ids array, then assign a different id and recheck the condition
    var uniqueId;
    while(true) {
        uniqueId = 'some-prefix-' + Math.floor(Math.random() * 10000);
        if($.inArray(uniqueId , ids) == -1) {
            break;
        }
    }
    return uniqueId;
}

Comment: ..Unique id is already generated , I want to set this unique id in Html while creation.
Answer: Possible Solution:
function randomString(length) {
    return Math.round((Math.pow(36, length + 1) - Math.random() * Math.pow(36, length))).toString(36).slice(1);
}

Look into these Questions for others: link link
Comment: Unique id is already generated , I want to set this unique id in Html while creation.
Comment: @JavaUser maybe set it inside the elements onload event handler
Answer: It's been several years since this was posted, and the accepted solution didn't work for me.  Here is the syntax that did:
[id]="unqiueID"


laravel Insert or update related records

Question: I'm having trouble updating and creating related records depending on if they exist or not. I want to update the ingredient if they exist, if not insert the ingredient into the database and relate it to the current meal.
public function update($id)
{
    $meal = Meal::find($id);
    $meal->name = Input::get('name');

    // create ingredients
    $ingredients = Input::get('ingredient');
    $meal_ingredients = array();

    foreach($ingredients as $ingredient)
    {
        $meal_ingredients[] = new Ingredient(array(
            'name' => $ingredient['name'],
            'unit' => $ingredient['unit'],
            'quantity' => $ingredient['quantity']
        ));
    }

    //save  into the DB
    $meal->save();
    $meal->ingredients()->saveMany($meal_ingredients);

    // redirect
    Flash::success('Votre repas a bien été mis à jour!');
    return Redirect::to('/meals');
}

Comment: what is the error you receive? Why do you change the name if you want to change ingedients?
Answer: Step 1 : Get Meal
 $meal = Meal::find($id);

Step 2 : Get Ingredients of Meal (create relation for this)
 $ingredients = $meal->ingredients;

Step 3 : Compare Input to current and add does not exist
$new_ingredients = array();

foreach($ingredients as $ingredient)
{
    if(!in_array($ingredient->toArray(), Input::get('ingredient')) {
      $new_ingredients[] = new Ingredient(array(
        'name' => $ingredient['name'],
        'unit' => $ingredient['unit'],
        'quantity' => $ingredient['quantity']
      ));
    }
}

Step 4 Update
$meal->ingredients->saveMany($new_ingredients);

Ensure you got the relation between meal and ingredient correctly
Comment: Both work thanks ! more detailed so I will vote for this one
Answer: You can use the firstOrNew() method. You pass it an array of data, and it will return the first record that matches that data, or if no record is found, a new instance of the class with the searched fields already set.
foreach($ingredients as $ingredient)
{
    $meal_ingredients[] = Ingredient::firstOrNew(array(
            'name' => $ingredient['name'],
        ))->fill(array(
            'unit' => $ingredient['unit'],
            'quantity' => $ingredient['quantity']
        ));
}


How to limit preprocess functions base on a theme?

Question: I'm working on a theme that using hook_preprocess_node and hook_preprocess_page and everything is working fine. However, whenever I go to any admin pages, it's throwing me some errors because the array changes. So what I'm trying to achieve is to add a condition only to run this preprocess function if using my theme.
How can I limit the preprocess function base on my theme?
Answer: You can check theme active with function:
<?php

$active = \Drupal::theme()->getActiveTheme()->getName();

Get list all themes with:
<?php

$themes = \Drupal::service('theme_handler')->listInfo()

Answer: If you implement the preprocess functions in your theme's template.php file, those will only be executed on the pages where the theme is applied.
So, if your admin theme is different (which is the case almost every time), the preprocess functions from your site theme would not be executed.
Comment: mytheme.theme and mymodule.module files are run on every page load, when the corresponding theme/module is activated.
Comment: I'm on D8 so I'm not using `template.php` instead I'm using `.theme`. Which I do not think that it matters.  My admin theme is different and the process function are still been execute. =(. I will add more information about the errors that I'm getting.
Comment: Oops.. Didn't see the 8 tag on the question. The preprocess functions are technically specific to the theme. Not sure why are they executing on a different theme. It will be good if you could add the code which you are trying out.


Putting prior on a function of parameters

Question: Suppose that we have a likelihood for a conditional distribution $p(y|X,\theta)$. For clarity purposes we can consider linear regression with homescadastic errors. It is clear to me how one will put a prior on the parameters, i.e. $\pi(\theta)$.
Instead of doing that can we put a prior $\pi(\mu)$ over $\mu = g(X,\theta)$ where $g$ is an inverse link function for the mean of $p(y|\mu)$ and estimate $\theta$? Does it make sense? Is there a name for this procedure?
Comment: Maybe the g-prior is what you are looking for? https://en.m.wikipedia.org/wiki/G-prior
Comment: @hejseb - no, the g-prior is effectively over different models, not over a function of the parameters.  An example of this question (it seems to me) could be "can I put a prior on $\mu^2$ instead of directly on $\mu$?  How?", which is different than "How can I put a prior on some regression coefficients being identically equal to zero?"
Comment: @jbowman Yes, you are right - I was thinking mostly about using $X$.
Answer: Another perspective on this: Yes, of course you can do that, the only question in practice is how you do it.
There's several options:

You can work out the changes in variables etc. and explicitly define the implied priors on the untransformed variables. This is often impractical / requires a lot of work.
If you can define your model in terms of the function of the variables, you can directly apply the prior and just work with the transformed variables.
You can use software that lets you specify such a prior and deals with the rest automatically (well, for non-linear transformations, you may have to figure out the determinant of the Jacobian of the transform). One example is Stan, in which you can e.g. specify something like the following:
parameters {
  vector[4] beta;
}
model {
  sum(beta) ~ normal(0,1);
  ...

The last approach is what I would use in practice. The only downside is that it may be hard to understand the implied prior on the original parameters, but to explore that, you can sample without data (and look at the resulting prior on the parameters, as well as the prior predictive distribution).
As a side remark, this is also very useful for overparameterized models for introducing additional (soft) constraints. E.g. if you have a categorical outcome and 3 parameters $\theta_i$ and your model is $Y_j \sim \text{Categorical}(\text{softmax}(\boldsymbol{\theta}))$, then the $\theta_i$ are only identifiable up to a constant. That actually tends to result in sampling problems, that you can get rid off in this manner.
Comment: Implied prior on the $\theta$ parameters are not important, since there may be infinitely many such priors satisfying the prior on the function (due to many to one relation), no?
Comment: @cagdas-ozgenc, yes, in that case it is more a computational trick. That's why I did called that a side remark, but it is actually the #1 reason why I have in the past put priors on transformed parameters. The advantage of this vs. parameterizing the model with fewer parameters (e.g. by defining $\theta_3 := 0$), is that it remains easy to put desired priors on the $\theta_i$ (hard otherwise). It does, of course, affect the final values of the $\theta_i$ (but not of the probabilities for each category - as you say, because the $\theta_i$ are only identified up to an additive constant).
Comment: Could you please write some simple bayesian update expressions. You may choose whatever distribution you like. I am confused on how to even write such priors and combine them with likelihoods.
Answer: As I understand your question, I don't know weither this approach has a name ; expect maybe those of change-of-variable.
Indeed, by defining a prior on $g(\theta)$, you are simply defining a prior on $\theta$ (assuming $g$ is monotonic, or bijective in multidimensional setting).
More formally, using change of variable relationship gives:
$$
p(\theta|y)  \propto p(y|\theta) \cdot p_{\theta}(\theta) \\
\propto  p(y|\theta) \cdot p_{\theta}(g^{-1}(\mu)) \\
\propto  p(y|g^{-1}(\mu)) \cdot p_{\mu}(\mu) \cdot \frac{\partial}{\partial \mu}(g^{-1}(\mu))
$$
As you can see, the equivalence between the two formulations (one in $\theta$ and one in $\mu$) involves a third term that must be accounted for to pass from one formulation to another.
Finally, consider two points : first, if $g$ is not bijective, the inverse function is not defined and thus you have no way to go back from $\mu$ to $\theta$. Second, regarding your initial formulation -that included the regressors $X$- all I wrote above is still consistent if your replace $\theta$ by $\theta^{'}=[\theta,X]$.
Comment: @CagdasOzgenc You want your prior to depend on the observation ? Do you agree that this at least answers your comment question  ""can I put a prior on μ^2 instead of directly on μ? How?""
Comment: g is almost never monotonic because $\theta$ is usually vector valued such as many parameters in a regression problem.
Comment: Don't forget that X also can be random. Your answer is not relevant at the moment.
Comment: These days people are even directly regularizing posteriors in variational Bayes, so what I am asking shouldn't be as shocking as you suggest.
Comment: @CagdasOzgenc. Sorry if my question was confusing ; I am not choked by your point. I am trying to understand your motivation as best as possible, so that I can try to address your question.
Comment: Actually $x$ are you independent variable, is it ? so they are not your observation. If it is the case, I think this makes no difference just consider the same formulation with $\theta^{'}=[\theta,X]$ instead of $\theta$. What do you think about it ?
Answer: When you can not compute a posterior for $\mu$ because of missing information in the likelihood
Below is a counterexample for a case where the likelihood function $p(y\vert \mu)$ is not uniquely defined by $\mu$, but depends in a more complex way on the vector $\theta$.

Say you have the likelihoodfunction:
$$Y \vert \theta_1+\theta_2 \sim N(\theta_1+\theta_2,1) \quad \text{with} \quad\theta_1 + \theta_2 \sim N(0,1)$$
Now this is like
$$Y \vert \mu \sim N(\mu,1) \quad \text{with} \quad\mu_{prior} \sim N(0,1)$$
and after observing value $Y$ the posterior becomes:
$$\mu_{posterior \vert Y} \sim N(1/2 Y,1/2)$$

In the above you can factor out the different $\theta$ from the likelihood function in a single function $\pi (X,\theta_1, ... , \theta_n) = \pi^\prime(g (X, \theta_1, ... , \theta_n)) = \pi ^\prime(\mu)$. That works fine. But say we have now instead some more complicated likelihood function:
$$Y \vert \theta_1+\theta_2 \sim N(\theta_1+\theta_2,\theta_1^2) \quad \text{with} \quad\theta_1 + \theta_2 \sim N(0,1)$$
Now this is like
$$Y \vert \mu, \theta_1 \sim N(\mu,\theta_1) \quad \text{with} \quad\mu_{prior} \sim N(0,1)$$
Which includes an extra (meta-)parameter $\theta_1$ in the likelihood function and we can not (independent from that meta-parameter) express $\mathbb{P}(Y,\mu)$ from which we could compute the posterior for $\mu$.
After observing a value $Y$ the posterior for $\mu$ becomes*:
$$\mu_{posterior \vert Y} \sim N( cY,d)$$ with $c = \frac{1}{\theta_1^2+1}$ and $d = \frac{\theta_1^2}{\theta_1^2+1}$
So you can not solve the posterior of $\mu$ for that problem because you have this metaparameter on which it depends as well.
When you can not compute $\theta$ based on $\mu$
This problem is a bit like Is it possible to derive joint probabilities from marginals with assumptions about the conditionals? Your distribution for $\mu=g(\theta)$ is turning a joint distribution for multiple variables (if $\theta$ is a vector) into a distribution for a single variable (some 'sort' of marginal distribution). You can not invert this
Say in the first example above. You might be able to find the distribution for $\mu = \theta_1 + \theta_2$ like $$\mu_{posterior \vert Y} \sim N(1/2 Y,1/2)$$ But it is not possible to turn this into a joint distribution for $\theta_1$ and $\theta_2$ without more information.

*This can be derived by the joint distribution $f(y,\mu\vert \theta_1) = \frac{1}{2 \pi \theta_1} e^{-\frac{1}{2} \left(\frac{(y-\mu)^2}{\theta_1^2}+ \mu^2\right)}$
Comment: The problem I have with this nice example is that you made sure that $\theta$ is not identifiable. This is like running a regression with 2 independent variables which are perfectly correlated. Or am I missing something?
Comment: @CagdasOzgenc it is a counterexample (and I believe that it is not very unreasonable). It means that *in general* the method is not sufficient to solve the problem, and you may need more information.
Comment: @CagdasOzgenc maybe, if you have some more precise sketch of the problem then it may become more clear why this alternative prior might be a good idea. But I do not see it working and I do not get an idea of a good practical case where it would be applied (but I am more theorist and do not know all about practice or have no practice with it). Anyway, even if there might be practical cases where it turns out to be useful, at least there are some weak points in the method.
Comment: @CagdasOzgenc It is an example where you need a prior $\pi (\theta_1,\theta_2) $ (or two marginal ones and assume indepemdence) and can not replace it with a prior $\pi (\mu) $
Comment: What I am saying is that you didn't really need a $\theta_1 + \theta_2 \sim N(0,1)$ for it to fail. Just putting a parameter for variance where you didn't provide a prior would be the same.
Comment: @CagdasOzgenc yes, that's the same. And it is the point of my answer. You can't use $\pi (\mu) $ because it creates such hyperparameters. If you have a likelihood based on the $\theta$ then you need priors for the $\theta $ and can't do away with (only) some grouped prior on $\mu $.
Comment: So far what I understood from your answer is not towards negative but towards positive. Now I realize what I was describing was a hierarchical model with hyperparameters to be determined by empirical bayes, which is something done all the time.


Is this simple operator bounded from $L^p([1,2])$ to $L^p([0,1])$?

Question: Let $f\in L^{p}([1,2])$ with $p>1$, and define
$$Tf(x):= \int_{1<y<2}\frac{f(y)}{|x-y|}dy,\quad 0<x<1.$$
I am trying to prove/disporove that
$$\|Tf\|_{L^p([0,1])}\leq C \|f\|_{L^p([1,2])}\quad (1)$$
I did not go far enough by Minkowski's integral inequality which implies
$$\left( \int_{0}^{1}\left(\int_{1<y<2}\frac{f(y)}{|x-y|}dy\right)^{p} dx \right)^{1/p}\leq \int_{1<y<2}f(y)\left(\int_{0}^{1}\frac{dx}{(y-x)^{p}}\right)^{1/p}dy$$
One can estimate
$$\left(\int_{0}^{1}\frac{dx}{(y-x)^{p}}\right)^{1/p}=\frac{1}{p-1}\left(\frac{1}{(y-1)^{p-1}}-\frac{1}{y^{p-1}}\right)^{1/p}\leq \frac{C}{(y-1)^{1-\frac{1}{p}}}$$
for $y$ close enough to $1$.
But this is not very helpful since
$\int_{0}^{1}\frac{f(y)}{(y-1)^{1-\frac{1}{p}}} dx$
is not bounded by $\|f\|_{L^{p}([1,2])}$ considering the counterexample $g_{p}(x):=\frac{\chi_{[1,3/2]}(x)}{|\log{(x-1)}|(x-1)^{\frac{1}{p}}}$.
Comment: Yes, it seems that it going to be similar to the Hilbert transform.
Comment: Would it help to write $Tf(x)=\int^2_0\mathbb{1}_{(1-x,2-x]}(y)\frac{f(y+x)}{y}\,dy$, where $f(y)$ is define to be $0$ outside $(1,2)$?
Comment: Nice formulation, but I don't know how useful it can be.. Do you have a certain singular operator in mind ?
Comment: Not really, but it does separate differently when you apply the generalized Monkowski intequalty. That may give you some other exponent $q$ in $L_q[0,1]$
Comment: Yes, but we still end up with something like $\int_{0}^{2}y^{-1}dy$.
Comment: I really appreciate your interest. There is no room for Holder's inequality and I don't know how to build on your suggestion.
Comment: I can type an answer if you are not going to remove the question, as you did the other day.
Comment: @ Ryszard Szwarc  The question is here to stay.
Answer: Let $(Sf)(x)=f(x+1)$ and $(Rf)(x)=f(1-x).$ Then $S$ and $R$ are isometries from $L^p(1,2)$ to $L^p(0,1)$ and $L^p(0,1)$ to $L^p(0,1),$ respectively. Observe that $T=RPHS, $ where
$$(Hf)(x)=\int\limits_0^\infty {f(y)\over y+x}\,dy$$
and $P$ is the restriction operator from $L^p(0,\infty)$ to $L^p(0,1).$
It suffices to show that the operator $H$ is bounded. The operator $H$ is a continuous version of the Hilbert matrix. By substitution $y={tx}$ we get $$(Hf)(x)=\int\limits_0^\infty {f(tx)\over 1+t}\,dt$$
Let $(H_tf)(x)=f(tx).$ Then $\|H_tf\|_p=t^{-1/p}\|f\|_p.$ Hence $$\|Hf\|_p\le \int\limits_0^\infty {1\over (1+t)t^{1/p}}\,dt\ \|f\|_p$$
Therefore $$\|T\|\le \int\limits_0^\infty {1\over (1+t)t^{1/p}}\,dt$$
Comment: ELEGANT answer!  But shouldn't the restriction operator $P$ act on $f$ before the Hilbert operator  $H$ ?
Comment: No, because $Sf$ belongs to $L^p(0,1),$ so the restriction is not needed.
Comment: I was thinking of a point-wise operator that goes $Pf (x)=\chi_{[0,1]}(x)f(x)$. But, I get it now, you are restricting the operator $H$ to a subspace. Okay. Thanks
Comment: If you would like to be very formal, you can add, after $S,$ the inclusion operator from $L^p(0,1)$ to $L^p(0,\infty).$
Comment: Or do without the restriction $P$ altogether and prove the inequality for the larger operator $Tf=\int_1^\infty \frac{f(y)}{y-x}dy$, $0<x<1$ :)
Comment: Hi @Oliver It worked!! I am glad I could help.
Comment: @RyszardSzwarc: I appreciate the support, thank you!


How to collect values in a sortable PHP array with like keys?

Question: I am gathering error messages for records based on their ids, e.g. in the following code the id "2342" has two errors. After collecting these, how can I get "all errors for a specific id" without looping through all array items and testing for that id?
<code>$errorMessages = [];
$errorMessages[] = ['2342','error1'];
$errorMessages[] = ['1236','error2'];
$errorMessages[] = ['2342','error3'];
$errorMessages[] = ['6535','error4'];

//get all error messages that belong to e.g. id=2342 in an array
</code>
An alternative would be to save the array as, e.g.:
<code>$errorMessages['2342'] = 'error1';
</code>
But then the second time I add a message to the id='2342', the value is replaced instead of added, so this is not an option.
What is the best way to save multiple strings like this to an array, and then be able to retrieve all strings for a specific array quickly?
Comment: why not save it as `$errorMessages['2342'][] = 'error1';`
Comment: @MihaiIorga this is the new PHP 5.4 syntax
Comment: *"But then the second time I add a message to the id='2342', the value is replaced instead of added, so this is not an option."* So? Use an array?
Comment: That is a javascript array and not PHP.
Answer: simply use an multi dimensional array and store an array of messages of the same id
<code>$errorMessages['2342'][] = 'error1';
</code>
Answer: Make $errorMessages['2342'] array()...
<code>$errorMessages['2342'] = array();

$errorMessages['2342'][] = 'error1';
$errorMessages['2342'][] = 'error2';
</code>


Creating multiple dynamic drop down in Excel sheet

Question: I am fairly new to Excel and I would like to create multiple dynamic drop down list that are dependent on the previous Column. I have looked online and I have only come across solutions that include 2 columns but not more than 2 and I would need some assistance on how will I be able to create multiple dynamic drop down list.
As  seen from the image, there are 3 columns: Component_1, Component_2, Component_3
What I am trying to achieve is that in the first drop down.
It will have the unique values in Component_1 (Empty, A, B, C)
In the second drop down Component_2 it will depend on the previous column which is Component_1.
If the value in Component_1 is selected as A Component_2 will have (AA, AB)
If the value in Component_1 is selected as B Component_2 will have (BB)
If the value in Component_1 is selected as C Component_2 will have (CC, CD)
In the third drop down Component_3 it will depend on the previous column which is Component_2.
If the value in Component_1 is selected as A and Component_2 is selected as AA Component_3 will have (AAA)
If the value in Component_1 is selected as A and Component_2 is selected as AB Component_3 will have (ABB, ABC)
If the value in Component_1 is selected as B and Component_2 is selected as BB Component_3 will have (BBB)
If the value in Component_1 is selected as C and Component_2 is selected as CC Component_3 will have (CCC)
If the value in Component_1 is selected as C and Component_2 is selected as CD Component_3 will have (CCD, CCE)
Answer: Here's a helpful walkthrough on Ablebits.com, which I recommend.
The easiest way I know to manage this is to put your data into tables with the headers being the drop-down selection from the prior menu.
In your example the first menu is just "A","B","C" & " ", so Table 1 should have all the drop down options you want listed under those headers.
Open data validation and set your first validation to pull from your first list "A","B","C" & " ". Go to your next cell, open data validation and set it to list, type in this formula:
=INDIRECT("Table1["&A1"]")
This assumes that your first drop down is in A1 and the table is named "Table1", so change as appropriate.
Then in the cell where you want your third drop down repeat what you did for cell 2, except the formula would be updated to:
=INDIRECT("Table2["&B1&"]")
Assuming that your second drop down is in B2 and your second table is named "Table2".
Good luck, I hope this helps!


Compute conditional probabilities of dependent events

Question: We are given an outcome A and a three different events $E_{1}$, $E_{2}$ and $E_{3}$, $E_{4}$. All the events are mutually dependent.
Now, we would like to compute:
$P(A|E_1, E_2, E_3, E_4)$
Is there a way to compute this using joint probabilities? How would you express it using conditional probabilities?
Comment: "Now, we would like to compute:" ... why?  Those expressions don't seem very meaningful.  What is the motivation?
Comment: @GrahamKemp When rewriting the question I realized that I was just overcomplicating things. I think I have an answer already, but I edited the question to double check. Hope this time is more clear :)
Comment: "...three different events $E_1,E_2$ and $E_3,E_4$." [I'll come in again.](http://www.montypython.net/scripts/spanish.php)
Answer: By definition of conditional probability: $\mathsf P(A\mid E_1,E_2,E_3,E_4)=\dfrac{\mathsf P(A,E_1,E_2,E_3,E_4)}{\mathsf P(E_1,E_2,E_3,E_4)}$
And of course, $\mathsf P(E_1,E_2,E_3,E_4)=\mathsf P(A,E_1,E_2,E_3,E_4)+\mathsf P(A^\complement,E_1,E_2,E_3,E_4)$
And so on.
Comment: Just like It though. Thank you though, having to rewrite the initial question actually helped a lot. Question solved.


Não consigo passar um valor para uma variável

Question: Porque no console.log(x) o terminal me mostra o array e no console.log("Categories: " + this.categories) ele me mostra undefined?
<code>buildCategories() {

    const teste = this.categoriesService.read();

    teste.subscribe(x => {
        this.categories = x;
        console.log(x);
    }
        );

    console.log("Categories: " + this.categories);

}
</code>
Comment: Ele imprime o **x** no primeiro log, pq vc está imprimindo exatamente o x. Já no segundo log vc esta imprimindo uma variável que **teoricamente** possui o x como valor.
Comment: Mas eu atribuí o valor de x à variável categories ou eu fiz errado?
Comment: X é um array certo? A variável categories, é do tipo array??!
Answer: Esse erro tem a ver que os subscribe serem async logo ele nao fica parado nele entao o console.log que esta fora do subscrive quando e executado ainda nao tem value a var


Checking values with IF statement

Question: Very simple question. I have four columns. If the value in column 1 is False OR 0 OR N/A, then I want to check column 2. If the value in column 2 is False OR 0 OR N/A, then I want to check column 3. If the value in column 3 is False OR 0 OR N/A, then I want to print value in column 4. The formula that I have is as follows:
=IF(NOT(OR(ISNA(BJ2),BJ2=FALSE,BJ2=0)),BJ2,
IF(NOT(OR(ISNA(BK2),BK2=FALSE,BK2=0)),BK2,
IF(NOT(OR(ISNA(BL2),BL2=FALSE,BL2=0)),BL2,BM2)))

So BJ is column 1, BK column 2, BL column 3, BM column 4.
The formula works for the False and 0 errors, but when I add the ISNA part, it breaks down. In fact it simply doesn't do anything more.
The data in the columns are either Strings, FALSE (not a string), or #N/A as a value not available error. I checked one of my N/A values with ISNA and the result was True. Therefore the OR statement should come back as TRUE, then pass through the negation and be false. Therefore the If statement should jump to the next column.
What is causing this not to read?
Answer: The problem is that an expression like, say, BJ2=FALSE or BJ2=0 will evaluate to N/A if BJ2 happens to be N/A. So, if anything of this happens the OR function will answer with N/A, because OR() evaluates all its arguments! (don't know why).

Checking values with IF statement


$\ker(\phi)$ is a normal subgroup.

Question: Let $G_1$ and $G_2$ be groups and suppose $\phi: G_1\mapsto G_2$ is a homomorphism. Then $\ker (\phi)\unlhd G_1$.
Need some feedback and help proving this. I am still new to proofs, but here's my attempt.
Proof.
We want to show $\ker (\phi)$ is normal, therefore, we must show that for any $h\in \ker (\phi)$ and $g\in G_1$, then $ghg^{-1}\in \ker (\phi)$. Since $h\in \ker (\phi)$, then $\phi(h)=1$. Thus,
\begin{align}
\phi(ghg^{-1})&=\phi(g)\phi(h)\phi(g^{-1})\\
&=\phi(g)\cdot 1\cdot\phi(g^{-1})\\
&=\phi(g)\phi(g^{-1})\\
&=\phi(g\cdot g^{-1})\\
&=\phi(1)\\
&=1.
\end{align}
Hence, $ghg^{-1}\in \ker (\phi)$, which implies $\ker (\phi)$ is a normal subgroup in $G_1$.
Comment: This looks good.
Comment: must show for **any** $h \in Ker(\phi)...$; also "Therefore, since $h\in Ker(\phi), $ then $\phi(h)=1$" belongs before $\phi(g)\phi(h)\phi(g^{-1})=\phi(g)\cdot1\cdot\phi(g^{-1})$
Comment: It would not hurt to emphasize that the last step holds because
$$\phi(g)\phi(g^{-1})=\phi(g)\phi(g)^{-1}=1
\qquad\text{ or }\qquad
\phi(g)\phi(g^{-1})=\phi(gg^{-1})=\phi(1)=1,$$
whichever you prefer.
Comment: You can render $\ker \phi$ with the LaTeX `$\ker \phi$`.
Comment: Essentially correct (just have to type the latex nicely). Just need to always remember this whole trick of using the group homomorphism.
Comment: @Everiana: Thanks for your reply. I will keep that in mind.
Comment: Thanks, @J.W.Tanner!
Comment: You're welcome.  The way you have it now edited, I would leave out the word "Therefore"; it's true that since $h\in Ker(\phi), \phi(h)=1$, but that doesn't follow from "we must show"
Answer: You're right.
An alternative method, following yours right until the end, goes like this:
\begin{align}
\phi(ghg^{-1})&=\phi(g)\phi(h)\phi(g^{-1}) \\
&=\phi(g)\cdot 1\cdot \phi(g^{-1})\\
&=\phi(g)\phi(g)^{-1}\\
&=1.
\end{align}
The conclusion is, of course, the same.

$\ker(\phi)$ is a normal subgroup.


Correctly type check reducer with Flow

Question: I try to integrate Flow with a Redux codebase.
I'm pretty new to Flow but I already have played with TypeScript a little.
I want to be able to catch wrong action type inside the reducer.
type Action =
  | { type: 'sample' }
  | { type: 'django' }
  ;

type State = {
  content: string,
};

const reducer = (state: State, action: Action): State => {
  switch (action.type) {
    // OK
    case 'sample':
      return { content: '' };

    // Should raise a type error, because the action type
    // will never be equal to "error"
    case 'error':
      return { content: '' };

    default:
      return { content: '' };
  }
};

Exemple in Try Flow
Exemple in TypeScript Playground
I don't understand why Flow don't catch the error in this case.
Flow infer the type property as a string but I set explicitly the type to be 'sample' | 'django'.
Did I miss something ?
Thanks!
Answer: This seems like a bug in flow, but you can enforce a strict verification as follows:
type ActionType = 'sample' | 'django'
type Action = {type: ActionType}

type State = {
  content: string,
};

const reducer = (state: State, action: Action): State => {
  const type:ActionType = action.type;
  switch (type) {
    // Should raise a type error, because the action type
    // will never be equal to "error"
    case 'error':
      return { content: '' };
    default:
      return { content: '' };
  }
};

This gives:
13:     case 'error':
             ^ string literal `error`. This type is incompatible with
9:   const type:ActionType = action.type;
                ^ string enum

Comment: indeed a bug / work in progress - see https://github.com/facebook/flow/issues/2399

Correctly type check reducer with Flow


jQuery - Can't add a class to a button with an onClick event

Question: I am trying to add a class to a button that has an onClick event. The onClick event triggers a popup alert that tells the user to check a box. Once you check a box, it disables the onClick: $("#continue").prop('onclick',null).off('click'); Once the onClick is disabled, I want to add a class to the button once it is clicked:
//Updated JS
jQuery(function($) {
 if ($("#continue").hasClass("selected")) {
  $(this).addClass('active');
 }
 $('#button').click(function(){
  $("#continue").addClass('selected');
  $("#continue").prop('onclick',null).off('click');
 });
});

//Button HTML
Pick me
Continue

But no class gets added. Not sure whats going on.
Answer: Maybe you can trigger a function to validate if the element has the required class like this:

function validate(element) {
  if ($(element).hasClass('selected')) {
    $(element).addClass('active');
  } else  {
    alert("this is an error");
  }
}

$(function() {
  $('#button').click(function() {
    $("#continue").addClass('selected');
  });

});
.selected {
  color: red;
}
.active {
  color: green;
}

Pick me
Continue
Comment: please insert a snippet with all your code.  Be aware that alerts, props, etc stops the execution of javascripts until the user has dismissed the alert.
Comment: Here is my code http://pastebin.com/s5mKxTaA It's not a normal alert, its a custom one
Comment: This is what I see in my console: $ is not a function http://pastebin.com/pikNXrG1
Comment: You need to load jquery. Before using any jquery syntax.
Comment: Ok, I did that. Now it's showing this: validate is not defined https://gyazo.com/549b1584a899ccadc066511bc5055e39 Thank you for your help so far
Comment: Make sure validate function is defined right after you load jquery. You can't call a fubction in a script if it hasn't been defined before
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/112554/discussion-between-garrettj944-and-alfredo).
Answer: You should write $(this) instead of $this
$('#button').click(function(){
     $this.addClass("active");
});

Comment: Wrapping `this` in parenthesis made it work.  `$(this).addClass('active')`


Bidding Collusion Question: Probability of Identical Bids

Question: I was asked this question. My initial conclusion is that there isn't enough information to calculate the probability. I would appreciate it if anyone could provide provide their insight.
Scenario:
Department of Defense is looking to purchase a good. Department of Defense has determined that a fair price is 1.0000 and told vendors of this value. Eight vendors submitted independent bids to provide the desired good.
What are the odds/probability that three vendors would submit the exact same bid (see below)?
<code>0.7700
0.7999
1.1120
0.7000
1.4262
0.6840
0.7000
0.7000
</code>
Comment: Is this under "real world" assumptions or is it a word problem? Because of the way it's phrased, most of it would be an exercise in game theory.
Comment: Real world assumptions.
Comment: People often bid round numbers, or just below round numbers (to underbid people who bid round numbers); if the fair price is known and they experience similar costs (e.g. work in the same economy with similar labor and equipment costs), I'd expect a lot of them to choose similar round bids. So I'd say "pretty likely" but there's no real way to guess how likely only on the information given.
Answer: You're right: as stated, there isn't enough information in the question to calculate a probability.
However if you wanted to make assumptions, you could take one of two main routes:

As user Andy Blankterz mentioned in the comments, you could assume payoff functions for each of the bidders. This reduces the problem to a first-price auction. It might be worth mentioning here that first-price auctions are suboptimal for the seller, from what I remember of auction theory.
You could assume probability distributions over bidders' behavior. This reduces the problem to something like the birthday problem. Keep in mind that the probability of exact equality is zero in the continuous case.

You could also combine these two by assuming stochastic payoffs (e.g. bidders don't know the payoffs for certain) or otherwise incorporating randomness into the first model. This could turn out to be a nontrivial problem to solve. If you're stone-cold confident in your analysis and probability skills, the definitive book on the subject is Putting Auction Theory to Work by Paul Milgrom.


Hiding property setters while using an OR Mapper

Question: I am using Fluent-NHibernate to manage all the data persistence layer and I am overall very pleased (and grateful to the NHibernate community).  I plan on continuing to use OR mappers.  I've developed an API around the POCOs that are being mapped.  The downside is that all the properties are both gettable and settable by the UI developers; when what I really want is to hide properties from non-middle tier development and only show the provided API methods to perform operations.
Does anyone have a good strategy for this?
Overly simple example:
member.FName = "Julian";    /// Don't do this because it avoids the my checking
member.LName = "King";

member.setName("Julian", "King");   /// Yes - this will throw an error if this person already exist

Comment: What's the difference between public setters and public operations? Both yield the same result.  Maybe you want to make your types _immutable_ instead?
Comment: By operation do you mean method?  Are you suggesting use Methods instead of Properties?
Comment: Yes. No.  It sounds like you want immutable types in which case you would pass everything into a constructor.  Thus there would be no setters or methods to change state.
Comment: Truth be told I just want to hide some public properties from the autocomplete.  That would probably be 99% effective.
Comment: You can't do that when it's the same class.  You could make a 2nd class that shared state for use by say the UI tiers that didn't have the setters
Comment: You don't have to use setters at all. You use backing field and set up your mapping to use backing field. Our domain almost never exposes any setter outside of domain. All state changes are done through commands.
Comment: Do you have a brief example of a "backing" field.  I am not even sure what that is.
Answer: private string _fName;
public string FName
{
   get { return _fName;}
}

private string _lName;
public string LName
{
  get { return _lName;}
}

public void SetName(string fName, string lName){

   // check for nulls here and or validate pre-conditions

  _fName = fName;
  _ lName = lName;

// check for post conditions here

}

or better yet use value object (see definition of value object in DDD)
public void SetName(Name name){

      _fName = name.FirstName;
      _ lName = name.LastName;

    }

Comment: Thank you for the response.  You are correct that this would protect the data properties and force the use of the function to set Name.  However, maybe I didn't make this clear, I am using an OR mapper Fluent NHibernate and so having a private or no setter at all will throw a mapping error.
Comment: You might want to read up on NH little bit more. You can map to private fields columns. I do it all the time.
Comment: You can specify it even as a convetion for all classes or on case by case bassis. DefaultAccess.ReadOnlyPropertyThroughCamelCaseField(CamelCasePrefix.Underscore);
Comment: You are right.  I tried mapping with private setters and Nhibernate threw an error.  At that point I assumed that it was not something that wasn't supported.  Thank you for the correction.  I'll vote this as the right answer.
Comment: Sharing the official Fluent NHibernate document on how:  https://github.com/jagregory/fluent-nhibernate/wiki/Mapping-private-properties


simplify $3x^{3/2}-9^{1/2}+6^{-1/2}$

Question: This problem has been posted before, unfortunately I still can't understand it from the other example. What I keep getting stuck on is the middle value and factoring out the negative fractional exponent. the problem goes
$3x^{3/2}-9x^{1/2}+6x^{-1/2}$
I know I need to factor out $3x^{-1/2}$ the problem is I can't understand how to do that from the middle monomial $9x^{1/2}$ when it doesn't have the negative value.
Comment: Are you missing some $x$s?
Answer: If you aren't missing $x$s, then just simplify $9^{1/2}+6^{-1/2}$.
If you are missing $x$s, factor out the lowest exponent: $x^{-1/2}(3x^2 - 9x + 6) = 3x^{-1/2}(x^2 - 3x + 2)$
Edit:
You can think of $9x^{1/2}$ as $9x^1 \times x^{-1/2}$. This works because $x^a \times x^b = x^{ab}$.
From there you can see how I factored out $x^{-1/2}$.
Comment: I was missing "x's" but my problem is how am I pulling out a $-(1/2)$ from the $9^(1/2)$ if it doesn't have a $-(1/2)$
Answer: It is known that $a^m\cdot{a^n}=a^{m+n}$. You can write $\frac{3}{2}=2-\frac{1}{2} \ , \ \frac{1}{2}=1-\frac{1}{2}$, thus $$3x^{1.5}-9x^{0.5}+6x^{-0.5}=3x^{-0.5}[x^2-3x+2]=3x^{-0.5}(x-1)(x-2)$$
I hope it helps.
Comment: it did, I finally understand it. thank you.

simplify $3x^{3/2}-9^{1/2}+6^{-1/2}$


Radio button em gridview

Question: Bom dia pessoal.
Preciso criar um formulário online que tera questões que seram inseridas diariamente no perfil de cada usuário.  Todas as questões sao armazenadas em um banco de dados junto com as suas alternativas e resposta correta.
Ate ai consigo montar tudo certo trago as questões e monto o gridview com os radios button.  No entanto na hora de salvar as respostas preciso pegar as opções dd cad linha do grid e chegar qual rádio esta selecionado.
Segue o codigo do formulario:
<form id="form1" runat="server">

<asp:GridView ID="gridQuestoes" runat="server" AutoGenerateColumns="false">
    <Columns>
        <asp:BoundField DataField ="questao" HeaderText="questao" />
        <asp:BoundField DataField ="Prioridade" HeaderText="Prioridade" />
        <asp:TemplateField>
            <ItemTemplate>
                <asp:RadioButton ID="rbtSim" runat="server" Text="Sim" GroupName="users"/>
                <asp:RadioButton ID="rbtNao" runat="server" Text="Não" GroupName="users"/>
            </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>

    <asp:Button ID="btnGravar" runat="server" Text="GRAVAR" OnClick="btnGravar_Click" />
</form>

Codigo utilizado para o preenchimento do GridView
BancoDeDados bd = new BancoDeDados();
        List<Modelos.Questoes> lista = bd.listarQuestoes(1);
        List<Quest1> listarQuest = new List<Quest1>();

        foreach (Modelos.Questoes questoes in lista)
        {
            if (questoes.tipo == 1)
            {
                listarQuest.Add(new Quest1()
                {
                    questao = questoes.questao,
                    prioridade = questoes.prioridade
                });
            }
        }
        gridQuestoes.DataSource = listarQuest;
        gridQuestoes.DataBind();

Em algumas pesquisas fiz esse codigo para verificar mas não esta funcionando
foreach (GridViewRow row in gridQuestoes.Rows)
        {
            BancoDeDados bd = new BancoDeDados();
            RadioButton rb1 = row.FindControl("rbtSim") as RadioButton;
            RadioButton rb2 = row.FindControl("rbtNao") as RadioButton;
            if (rb1.Checked == true)
            {
                bd.gravar("Sim");
            }
            else if (rb2.Checked == true)
            {
                bd.gravar("Não");
            }
        }

Comment: @bigown tem alguma ideia de outra maneira que pode ser feito ou se esta errada esse codigo?
Comment: Não mexo com isto, mas logo aparece alguém pra te ajudar.
Comment: Acho que falta ser inserido no seu gridview OnRowDataBound, pra você manipular o que consta dentro dele...Segue um guia explicando sua função https://msdn.microsoft.com/pt-br/library/system.web.ui.webcontrols.gridview.onrowdatabound(v=vs.110).aspx
Answer: Bom dia.
Consegui resolver meu problema dessa maneira não sei se é o melhor maneira mas esta funcionando se alguem quiser utilizar ou tiver uma outra maneira
adicionei um ação para cada vez que o um dos botões for ativado.
 <asp:TemplateField>
            <ItemTemplate>
                <asp:RadioButton ID="rbtSim" runat="server" Text="Sim" GroupName="users" OnCheckedChanged="rbtSim_CheckedChanged" AutoPostBack="true"/>
                <asp:RadioButton ID="rbtNao" runat="server" Text="Não" GroupName="users" OnCheckedChanged="rbtNao_CheckedChanged" AutoPostBack="true"/>
            </ItemTemplate>
        </asp:TemplateField>

e nas ações utilizei essa função
 protected void rbtSim_CheckedChanged(object sender, EventArgs e)
    {
        RadioButton rbSim = (RadioButton)sender;
        GridViewRow row = (GridViewRow)rbSim.Parent.Parent;

        foreach (Quest1 q in listarQuest)
        {
            if (row.RowIndex == q.id)
            {
                q.resp = "Sim";
            }
        }
    }

espero que possa ajudar alguem e se alguem tiver um metodo diferente de resolução.
att

Radio button em gridview


what is the conditional density of $X$ given $Y$?

Question: If the joint p.d.f of a two-dimensional random variable $(X,Y)$ is given by:
$f(x,y) = \  \left\{
\begin{array}{ll}
      2 &s.t.~ 0<x<1;~0 <y<x \\
      0 &x <0~;~x>1 \\
\end{array}
\right. $
Then, what is the conditional density of $X$ given $Y$?
Attempt: $f_{X|Y}(x|y)= \dfrac{P_{XY}(x,y)}{P_Y(y)}$
As per given condition : $\int^0_1 (\int_0^xP_{XY}(x,y)~dy) dx=2$
How does one calculate $P_{XY}(x,y)$ from here.
Also, I have trouble visualizing a way to find out $P_Y(y) = \int_0^\infty P_{XY}(x,y)~ dx$
Thanks a lot for your help
Comment: Duplicate of [How to find density function from this joint probability density function](https://stats.stackexchange.com/questions/365715/how-to-find-density-function-from-this-joint-probability-density-function) with the minor difference that the support here is $0 < y < x < 1$ whereas in the cited question, the support is $0 < x < y < 1$.
Answer: $f_Y(y)=\int_y^1 f(x,y)dx=2\int_y^1 dx=2(1-y), 0<y<1$
$f_{X|Y}(x|y)= \dfrac{f_{X,Y}(x,y)}{f_Y(y)}=\dfrac{2}{2(1-y)}=\dfrac{1}{1-y}, 0<y<1$
Comment: No, this is wrong, The conditional pdf $f_{X\mid Y}(x\mid y)$ is a function of $x$, not of $y$ ($y$ is just a parameter in the formulas that you might come up with).


How to deny direct access to an xml file in the server

Question: I have an html file index.html (in my server say abc.com) which accesses xyz.js like
<code><script type="text/javascript" src="xyz.js"></script>
</code>
The javascript file in turn accesses data.xml file.
The files index.html,xyz.js and data.xml are in the same folder.
How can I deny direct access to xyz.js and data.xml if a user types
abc.com/xyz.js  and abc.com/data.xml in the browser.
Needless to say index.html must be able to access these files.
How can I do this(preferably with .htaccess)
Answer: I'm assuming you mean index.html refers to the .js file via a script tag, and then the js reads in the xml using XMLHttpRequest or something similar. ie: the js and xml both need to be readable by the browser, but you want to restrict this to only be in an "approved" way.
If that's right, then you can't. You could try looking at the Referer, but it's unreliable and easily spoofable. Even without spoofing, many browsers have debugging tools that make it easy to see the result of every GET that has been performed.
It's better to just get used to the fact that anything you send to the browser is potentially viewable by the user if they work hard enough at it.
I suppose for JavaScript you could use an obfuscator tool if you feel so inclined. For XML, there isn't much you can do. I suppose you could encrypt it, but that would be easy to break as your js code will necessarily contain the decryption routine and key.
Answer: If you truly need to protect the data, you need to implement the sensitive part of your program to run on the server and not in the client. Then you can keep your datasource out of the public web space completely. If the client (browser) can access the raw data, then so can the user (even if you force them to go through multiple steps to get at it).
To acheive your goal you need to split your program architecture in two:

the non-sensitive parts run, in javascript, in the browser
the sensitive parts run, in .net/java/php/ruby/python etc etc, on the server


Common preprocessor macros for all configurations of a target in XCode iPhone Project

Question: I usually have four configurations per target (Debug, Release, Distribution, Ad Hoc) for my Apps.
Is there a way to add a common macro for all 4 of them, while not destroying the macros that I have set so far (you see "multiple values" in the editor).
Thanks in advance,
Obiwahn
Answer: Define the macro in the prefix header file (will be included in all source files).
Comment: Absolutely! The only macros defined per configuration should be those that vary per configuration.
Answer: Another way do do this, which might work better for certain cases, is to use the $(inherited) macro to include the settings from the parent context. This works well with the way Xcode 4 lets you see the settings cascade.
Answer: You could have all of your targets use the same .xcconfig file; see apple documentation under the heading "Build Configuration Files".  Note that even though the screenshots are out of date, the material seems to be accurate.