How to use char* in switch instruction of LLVM IR?

Question: I am trying to use string in switch instruction. My idea is using the address of string as string's value(ConstantInt*) to pass to switch instruction, if two addresses equal, switch case should match.
But when i running below IR code(generated by my program), error occurs:
source_filename = "input/step/step1.ts"
target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-f80:128-n8:16:32:64-S128"
target triple = "x86_64-apple-darwin19.6.0"

@aa = private unnamed_addr constant [3 x i8] c"aa\00", align 1
@b = linkonce_odr global i8* getelementptr inbounds ([3 x i8], [3 x i8]* @aa, i32 0, i32 0)
@bb = private unnamed_addr constant [3 x i8] c"bb\00", align 1
define i32 @main() {
  %1 = load i8*, i8** @b
  switch i8* %1, label %4 [
    i8* getelementptr inbounds ([3 x i8], [3 x i8]* @aa, i32 0, i32 0), label %2
    i8* getelementptr inbounds ([3 x i8], [3 x i8]* @bb, i32 0, i32 0), label %3
  ]

2:                                                ; preds = %0
  br label %4

3:                                                ; preds = %0
  br label %4

4:                                                ; preds = %2, %3, %0
  ret i32 0
}

It's language code like:
var b: string = "aa";
switch (b) {
  case "aa":
    break;
  case "bb":
    break;
}

The IR code seems to be right, but when it running, error occured:
Stack dump:
0.      Program arguments: ./build/tser input/step/step1.ts
1.      Running pass 'Function Pass Manager' on module 'input/step/step1.ts'.
2.      Running pass 'X86 DAG->DAG Instruction Selection' on function '@main'
0  tser                     0x00000001073a718c llvm::sys::PrintStackTrace(llvm::raw_ostream&) + 60
1  tser                     0x00000001073a7749 PrintStackTraceSignalHandler(void*) + 25
2  tser                     0x00000001073a52b6 llvm::sys::RunSignalHandlers() + 118
3  tser                     0x00000001073ab21c SignalHandler(int) + 252
4  libsystem_platform.dylib 0x00007fff6efa65fd _sigtramp + 29
5  libsystem_platform.dylib 0x00007ffee8c53700 _sigtramp + 18446744071457919264
6  tser                     0x0000000107d22fad llvm::APInt::operator[](unsigned int) const + 141
7  tser                     0x0000000107d22e8d llvm::APInt::isNegative() const + 29
8  tser                     0x00000001071d2d92 llvm::APInt::compareSigned(llvm::APInt const&) const + 242
9  tser                     0x0000000107d2814d llvm::APInt::slt(llvm::APInt const&) const + 29
10 tser                     0x0000000108dda1ee llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1::operator()(llvm::SwitchCG::CaseCluster const&, llvm::SwitchCG::CaseCluster const&) const + 62
11 tser                     0x0000000108dd9b53 void std::__1::__sort<llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1&, llvm::SwitchCG::CaseCluster*>(llvm::SwitchCG::CaseCluster*, llvm::SwitchCG::CaseCluster*, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1&) + 147
12 tser                     0x0000000108dd9ab5 void std::__1::sort<llvm::SwitchCG::CaseCluster*, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1&>(llvm::SwitchCG::CaseCluster*, llvm::SwitchCG::CaseCluster*, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1&) + 37
13 tser                     0x0000000108dd9a86 void std::__1::sort<llvm::SwitchCG::CaseCluster, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1>(std::__1::__wrap_iter<llvm::SwitchCG::CaseCluster*>, std::__1::__wrap_iter<llvm::SwitchCG::CaseCluster*>, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1) + 54
14 tser                     0x0000000108dd99dd void llvm::sort<std::__1::__wrap_iter<llvm::SwitchCG::CaseCluster*>, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1>(std::__1::__wrap_iter<llvm::SwitchCG::CaseCluster*>, std::__1::__wrap_iter<llvm::SwitchCG::CaseCluster*>, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1) + 45
15 tser                     0x0000000108dd06f3 void llvm::sort<std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1>(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&, llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&)::$_1) + 51
16 tser                     0x0000000108dd0491 llvm::SwitchCG::sortAndRangeify(std::__1::vector<llvm::SwitchCG::CaseCluster, std::__1::allocator<llvm::SwitchCG::CaseCluster> >&) + 225
17 tser                     0x00000001084fe009 llvm::SelectionDAGBuilder::visitSwitch(llvm::SwitchInst const&) + 569
18 tser                     0x00000001084fb508 llvm::SelectionDAGBuilder::visit(unsigned int, llvm::User const&) + 152
19 tser                     0x00000001084fac9d llvm::SelectionDAGBuilder::visit(llvm::Instruction const&) + 141
20 tser                     0x00000001086002cc llvm::SelectionDAGISel::SelectBasicBlock(llvm::ilist_iterator<llvm::ilist_detail::node_options<llvm::Instruction, true, false, void>, false, true>, llvm::ilist_iterator<llvm::ilist_detail::node_options<llvm::Instruction, true, false, void>, false, true>, bool&) + 220
21 tser                     0x00000001085ffcbe llvm::SelectionDAGISel::SelectAllBasicBlocks(llvm::Function const&) + 6110
22 tser                     0x00000001085fc9f2 llvm::SelectionDAGISel::runOnMachineFunction(llvm::MachineFunction&) + 2130
23 tser                     0x0000000107a281d5 (anonymous namespace)::X86DAGToDAGISel::runOnMachineFunction(llvm::MachineFunction&) + 277
24 tser                     0x00000001089ebee6 llvm::MachineFunctionPass::runOnFunction(llvm::Function&) + 550
25 tser                     0x00000001075cb369 llvm::FPPassManager::runOnFunction(llvm::Function&) + 681
26 tser                     0x00000001075cb945 llvm::FPPassManager::runOnModule(llvm::Module&) + 117
27 tser                     0x00000001075cc0a8 (anonymous namespace)::MPPassManager::runOnModule(llvm::Module&) + 776
28 tser                     0x00000001075cbbd5 llvm::legacy::PassManagerImpl::run(llvm::Module&) + 293
29 tser                     0x00000001075cc6d1 llvm::legacy::PassManager::run(llvm::Module&) + 33
30 tser                     0x0000000107775275 llvm::orc::SimpleCompiler::operator()(llvm::Module&) + 309
31 tser                     0x000000010786ed64 decltype(std::__1::forward<llvm::orc::TMOwningSimpleCompiler&>(fp)(std::__1::forward<llvm::Module&>(fp0))) std::__1::__invoke<llvm::orc::TMOwningSimpleCompiler&, llvm::Module&>(llvm::orc::TMOwningSimpleCompiler&, llvm::Module&) + 68
32 tser                     0x000000010786ecd4 llvm::Expected<std::__1::unique_ptr<llvm::MemoryBuffer, std::__1::default_delete<llvm::MemoryBuffer> > > std::__1::__invoke_void_return_wrapper<llvm::Expected<std::__1::unique_ptr<llvm::MemoryBuffer, std::__1::default_delete<llvm::MemoryBuffer> > > >::__call<llvm::orc::TMOwningSimpleCompiler&, llvm::Module&>(llvm::orc::TMOwningSimpleCompiler&, llvm::Module&) + 68
33 tser                     0x000000010786ec84 std::__1::__function::__alloc_func<llvm::orc::TMOwningSimpleCompiler, std::__1::allocator<llvm::orc::TMOwningSimpleCompiler>, llvm::Expected<std::__1::unique_ptr<llvm::MemoryBuffer, std::__1::default_delete<llvm::MemoryBuffer> > > (llvm::Module&)>::operator()(llvm::Module&) + 68
34 tser                     0x000000010786daf3 std::__1::__function::__func<llvm::orc::TMOwningSimpleCompiler, std::__1::allocator<llvm::orc::TMOwningSimpleCompiler>, llvm::Expected<std::__1::unique_ptr<llvm::MemoryBuffer, std::__1::default_delete<llvm::MemoryBuffer> > > (llvm::Module&)>::operator()(llvm::Module&) + 67
35 tser                     0x000000010781d127 std::__1::__function::__value_func<llvm::Expected<std::__1::unique_ptr<llvm::MemoryBuffer, std::__1::default_delete<llvm::MemoryBuffer> > > (llvm::Module&)>::operator()(llvm::Module&) const + 103
36 tser                     0x000000010781d08f std::__1::function<llvm::Expected<std::__1::unique_ptr<llvm::MemoryBuffer, std::__1::default_delete<llvm::MemoryBuffer> > > (llvm::Module&)>::operator()(llvm::Module&) const + 63
37 tser                     0x000000010781bb26 decltype(fp(decltype(std::__1::__declval<llvm::Module&>(0)) std::__1::declval<llvm::Module&>()())) llvm::orc::ThreadSafeModule::withModuleDo<std::__1::function<llvm::Expected<std::__1::unique_ptr<llvm::MemoryBuffer, std::__1::default_delete<llvm::MemoryBuffer> > > (llvm::Module&)>&>(llvm::Module&) + 182
38 tser                     0x000000010781b84b llvm::orc::IRCompileLayer::emit(llvm::orc::MaterializationResponsibility, llvm::orc::ThreadSafeModule) + 187
39 tser                     0x0000000107847cc6 llvm::orc::BasicIRLayerMaterializationUnit::materialize(llvm::orc::MaterializationResponsibility) + 470
40 tser                     0x0000000107873280 llvm::orc::MaterializationUnit::doMaterialize(llvm::orc::JITDylib&) + 112
41 tser                     0x0000000107786dc0 llvm::orc::ExecutionSession::materializeOnCurrentThread(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >) + 32
42 tser                     0x00000001077931a4 decltype(std::__1::forward<void (*&)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >)>(fp)(std::__1::forward<llvm::orc::JITDylib&>(fp0), std::__1::forward<std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> > >(fp0))) std::__1::__invoke<void (*&)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >), llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> > >(void (*&)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >), llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >&&) + 84
43 tser                     0x0000000107793127 void std::__1::__invoke_void_return_wrapper<void>::__call<void (*&)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >), llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> > >(void (*&)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >), llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >&&) + 71
44 tser                     0x00000001077930d7 std::__1::__function::__alloc_func<void (*)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >), std::__1::allocator<void (*)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >)>, void (llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >)>::operator()(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >&&) + 71
45 tser                     0x0000000107791ec6 std::__1::__function::__func<void (*)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >), std::__1::allocator<void (*)(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >)>, void (llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >)>::operator()(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >&&) + 70
46 tser                     0x000000010778d01a std::__1::__function::__value_func<void (llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >)>::operator()(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >&&) const + 106
47 tser                     0x000000010778cec5 std::__1::function<void (llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >)>::operator()(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >) const + 69
48 tser                     0x0000000107783143 llvm::orc::ExecutionSession::dispatchMaterialization(llvm::orc::JITDylib&, std::__1::unique_ptr<llvm::orc::MaterializationUnit, std::__1::default_delete<llvm::orc::MaterializationUnit> >) + 163
49 tser                     0x0000000107784c50 llvm::orc::ExecutionSession::runOutstandingMUs() + 320
50 tser                     0x0000000107781f4c llvm::orc::ExecutionSession::lookup(llvm::orc::LookupKind, std::__1::vector<std::__1::pair<llvm::orc::JITDylib*, llvm::orc::JITDylibLookupFlags>, std::__1::allocator<std::__1::pair<llvm::orc::JITDylib*, llvm::orc::JITDylibLookupFlags> > > const&, llvm::orc::SymbolLookupSet, llvm::orc::SymbolState, llvm::unique_function<void (llvm::Expected<llvm::DenseMap<llvm::orc::SymbolStringPtr, llvm::JITEvaluatedSymbol, llvm::DenseMapInfo<llvm::orc::SymbolStringPtr>, llvm::detail::DenseMapPair<llvm::orc::SymbolStringPtr, llvm::JITEvaluatedSymbol> > >)>, std::__1::function<void (llvm::DenseMap<llvm::orc::JITDylib*, llvm::DenseSet<llvm::orc::SymbolStringPtr, llvm::DenseMapInfo<llvm::orc::SymbolStringPtr> >, llvm::DenseMapInfo<llvm::orc::JITDylib*>, llvm::detail::DenseMapPair<llvm::orc::JITDylib*, llvm::DenseSet<llvm::orc::SymbolStringPtr, llvm::DenseMapInfo<llvm::orc::SymbolStringPtr> > > > const&)>) + 892
51 tser                     0x0000000107787b34 llvm::orc::ExecutionSession::lookup(std::__1::vector<std::__1::pair<llvm::orc::JITDylib*, llvm::orc::JITDylibLookupFlags>, std::__1::allocator<std::__1::pair<llvm::orc::JITDylib*, llvm::orc::JITDylibLookupFlags> > > const&, llvm::orc::SymbolLookupSet const&, llvm::orc::LookupKind, llvm::orc::SymbolState, std::__1::function<void (llvm::DenseMap<llvm::orc::JITDylib*, llvm::DenseSet<llvm::orc::SymbolStringPtr, llvm::DenseMapInfo<llvm::orc::SymbolStringPtr> >, llvm::DenseMapInfo<llvm::orc::JITDylib*>, llvm::detail::DenseMapPair<llvm::orc::JITDylib*, llvm::DenseSet<llvm::orc::SymbolStringPtr, llvm::DenseMapInfo<llvm::orc::SymbolStringPtr> > > > const&)>) + 324
52 tser                     0x0000000107787dc3 llvm::orc::ExecutionSession::lookup(std::__1::vector<std::__1::pair<llvm::orc::JITDylib*, llvm::orc::JITDylibLookupFlags>, std::__1::allocator<std::__1::pair<llvm::orc::JITDylib*, llvm::orc::JITDylibLookupFlags> > > const&, llvm::orc::SymbolStringPtr) + 307
53 tser                     0x00000001078533fd llvm::orc::LLJIT::lookupLinkerMangled(llvm::orc::JITDylib&, llvm::StringRef) + 173
54 tser                     0x0000000106fcdcf9 llvm::orc::LLJIT::lookup(llvm::orc::JITDylib&, llvm::StringRef) + 169
55 tser                     0x0000000106fc1acb llvm::orc::LLJIT::lookup(llvm::StringRef) + 75
56 tser                     0x0000000106fc0888 main + 2632
57 libdyld.dylib            0x00007fff6edadcc9 start + 1
58 libdyld.dylib            0x0000000000000002 start + 18446603338656326458
make: *** [start] Segmentation fault: 11

There is no any tutorials for this, and i cannot find it out, thanks a lot for anyone's help.
Comment: You cannot use strings because their value is an address, and is known too late. That is only assigned at link time, after the compiler had transformed the switch into a series of machine code instructions.
Answer: You are going to have to read the llvm documentation: https://llvm.org/docs/LangRef.html#switch-instruction. Note that using strings as you have it within a switch statement is incorrect. It has to be a integer in the parameter to the switch statement for the llvm byte code to work correctly.
You will have to convert the given switch statement (as you have shown to us) to an if..else-if..else equivalent to the switch in the llvm byte code, as passing the string directly into the switch statement will not perform as you seem to be expecting. Convert the switch to the equivalent if..else-if..else when the switch expression is not an int and it should work.
Comment: Finally i found another way, i think it's better than pure `if-else` implement. It uses index of cases instead, and combined switch instruction and `if-else` instruction. You might take a look to my answer: https://stackoverflow.com/a/63453227/11354404.
Answer: Finally i found a better way, i think it's better than pure if-else implement. It uses index of cases instead, and combined switch instruction and if-else instruction:

Convert case's string value to index of cases, which's type is ConstantInt.
Computed matched index of case value, this step uses if-else, and run before switch instruction.
Then use switch instruction (index as key).

Such as below code:
var a: number = 11;

var b: string = "aa";
switch (b) {
  case "aa":
    a = a + 100;
    break;
  case "bb":
    a = a + 200;
    break;
}

Convert it to below IR code:
@a = linkonce_odr global i32 11
@aa = private unnamed_addr constant [3 x i8] c"aa\00", align 1
@bb = private unnamed_addr constant [3 x i8] c"bb\00", align 1
@b = linkonce_odr global i8* getelementptr inbounds ([3 x i8], [3 x i8]* @aa, i32 0, i32 0)

define i32 @main() {
  %1 = alloca i32
  %2 = load i8*, i8** @b
  %3 = icmp eq i8* %2, getelementptr inbounds ([3 x i8], [3 x i8]* @aa, i32 0, i32 0)
  br i1 %3, label %4, label %5

4:                                                ; preds = %0
  store i32 0, i32* %1
  br label %5

5:                                                ; preds = %4, %0
  %6 = load i8*, i8** @b
  %7 = icmp eq i8* %6, getelementptr inbounds ([3 x i8], [3 x i8]* @bb, i32 0, i32 0)
  br i1 %7, label %8, label %9

8:                                                ; preds = %5
  store i32 1, i32* %1
  br label %9

9:                                                ; preds = %8, %5
  %10 = load i32, i32* %1
  switch i32 %10, label %17 [
    i32 0, label %11
    i32 1, label %14
  ]

11:                                               ; preds = %9
  %12 = load i32, i32* @a
  %13 = add i32 %12, 100
  store i32 %13, i32* @a
  br label %17

14:                                               ; preds = %9
  %15 = load i32, i32* @a
  %16 = add i32 %15, 200
  store i32 %16, i32* @a
  br label %17

17:                                               ; preds = %9, %11, %14
  ret i32 0
}


Should we use regression or classification for recommendation systems?

Question: Lets say that based on some user available ratings i want to predict the ratings of unrated products for some specific user. I totally understand the fact that classifier models are for categorical data and regression models for continuous but in that case should we treat ratings as categorical values? I am searching in bibliography papers and some use classification to predict ratings and others regression.
Answer: TL;DR: Use (ordinal) regression. Your problem lies somewhere between standard regression and classification, but doing standard regression is less "wrong" than doing classification.
In detail: I assume that the ratings are integers, like $\{1, 2, 3, 4, 5\}$, and that one extreme (e.g. 1) means "bad" and the other (5) "excellent". I.e. there is an order in the ratings: 5 is better than 4, 4 is better than 3 etc. Variables of that kind are called "ordinal". They differ from continuous variables in that the difference between values cannot be translated to difference in the underlying property. For example, you cannot say that the product with rating 5 is exactly as much better from the product with rating 4, as is the product with rating 4 from the product with rating 3, etc.
Applying classification here would lead to a substantial loss of information and poor performance. A standard classifier wouldn't know that ratings 4 and 5 are more similar than ratings 1 and 5. For a classifier, they are either identical or different.
A common approach to solving such problems is to assume a latent continuous variable which represents the true product quality, and the rating as an observable, rounded, and possibly non-linear function of that true quality. Something like in the figure below:

There are methods to deal explicitly with such problems, like the proportional odds model, neural networks for ordinal regression, or support vector machines. If this sounds too complicated, using ordinary regression, while suboptimal, is still better than classification.
For available software libraries, you may consult this (somewhat old) answer on StackOverflow.
Comment: So in practice can i use a random forest regressor to train and predict recommendations rather than random forest classifier?
Comment: Yes. It would be even better if you could find a random forest **ordinal** regressor, but I'm not aware of its existence.
Comment: Nice thank you for your answer. In my recommender random forest regressor works much better than classifier even though i can't find in bibliography papers anyone using random forest regressors. This fact scared me at first
Comment: I'm glad I could help.


Colinearity and scaling when using k-means

Question: I'm trying to gain a better understanding of kmeans clustering and am still unclear about colinearity and scaling of data. To explore colinearity, I made a plot of all five variables that I am considering shown in the figure below, along with a correlation calculation.

I started off with a larger number of parameters, and excluded any that had a correlation higher than 0.6 (an assumption I made). The five I choose to include are shown in this diagram.
Then, I scaled the date using the R function scale(x) before applying the kmeans() function. However, I'm not sure whether center = TRUE and scale = TRUE should also be included as I don't understand the differences that these arguments make. (The scale() description is given as scale(x, center = TRUE, scale = TRUE)).
Is the process that I describe an appropriate way of identifying clusters?
Comment: @celenius I can suggest this article, [Standardizing Variables in K-means Clustering](http://www.springerlink.com/content/l438152634256311/) (Steinley, 2004) to get an idea of the effects of different kind of transformations. The utility of scaling depends on the data you have, but usually one reason to use standardized (scaled) variables is to avoid obtaining clusters that are dominated by variables having the largest amount of variation.
Comment: @celenius `center=true` just means remove the mean, and `scale=TRUE` stands for divide by SD; in other words, with both options active, you're getting standardized variables (with mean 0, unit variance, and values expressed in SD units).
Comment: @celenius It shouldn't introduce bias.  Take, for instance, the extreme of perfect collinearity in 2D: all observations are of the form $(a+t x, b+t y)$ for constants $a,b,x,y$.  K-means uses Euclidean distances and the distance between two such points given by $t$ and $s$ is just $|s-t|$: it's really a 1D problem and there's no special weighting given to any of the data.
Comment: I realize that these are two slightly different questions, but I want them to be together to give some background to what I am using the results of the `scale()` function.
Comment: @chl Ah! Thank you. That is a much clearer explanation to me than the help file. Does it make a difference how a variable is standardized for clustering with kmeans though? I would assume not, but don't know for sure.
Comment: @celenius Why is collinearity a problem?  It shouldn't affect k-means at all.
Comment: @whuber I assumed that the more collinear variables I include, the more that it biases the clustering towards those collinear dimensions.
Answer: As CHL has already explained the use of center and scale to obtain standardized variables, I'll address collinearity:
There is good reason to reduce collinear variables when clustering.
Curse of Dimensionality
The more dimensions you use, the more likely you are to fall victim of Bellman's 'curse of dimensionality'.  In brief, the greater the number of dimensions, the greater the total volume, and the greater the sparsity of your data within it.  (See the link for more detail.)
Dimension Reduction --- manually by inspecting of pairwise collinearity...
You mention that you have already reduced variables from some larger number down to 5 using pairwise collinearity measures.
While this will work, it is quite tedious, since in general you will have $n\choose 2$ number of pairs to check.  (So for example with 10 variables, you would have ${10 \choose 2} = 45$ different pairs to examine -- a few too many to do manually in my opinion!
Dimension Reduction --- automatically using Principal Components Analysis (PCA)...
One way to handle this automatically is to use the PCA (principle components analysis) algorithm.  The concept is more or less what you're doing manually -- ranking the variables by how much unique information each variable is contributing.
So you provide PCA your $n$-variable dataset as input, and PCA will rank order your variables according to the greatest variance each explains in the data -- essentially picking out the non-collinear variables.
Depending on whether you want 2-D or 3-D clusters, you would use the top 2 or 3 variables from PCA.
Principal Components in R
The PCA algorithm is available (built-in) from R.
Actually there are several functions in R that do principal components.
I've had success with prcomp().
Standard Reference available free online
One of the best references available is the classic:
Elements of Statistical Learning, by Trevor Hastie, Robert Tibshirani, and Jermoe Friedman
The authors have graciously made the entire book available (for free) as a PDF download from their Stanford website.
There are excellent chapters on Clustering, Principal Comoonents, and a great section on the curse of dimensionality.


How does $9\choose 4,3,2$ $=8$ $7\choose 4$

Question: Can someone please explain to me how $9\choose 4,3,2$$=8$$7\choose 4$?
From my understanding $9\choose 4,3,2$$ = $$9\choose 4$$5\choose 3$$2\choose 2$$=$$9\choose 4$$5\choose 3$$\cdot 1$
But for some reason my teacher is jumping to simply $8$$7\choose 4$. How?
Comment: Your notation $P(9;4,3,2)$ is not standard. Do you mean a multinomial coefficient, which is ususally written $\binom9{4,3,2}$?
Comment: Yes, sorry. I will change that
Answer: We have $\binom9{4,3,2}=\binom94*\binom53*\binom22=126*10*1=1260$ which is not the same as $8*\binom74=8*35=280$.
Comment: My teacher's answer key must have a typo then. Is there a single constant times a choose function that makes this statement true?
Comment: Given that $1260/8 = 157.5$ isn't an integer, I think it's unlikely.


Como utilizar o orderByKey e EqualTo do Firebase?

Question: Preciso buscar no meu database, qual o "FLOOR KEY" que é "main".
Os dados que eu tenho é seguinte:

this._userID = ALIANSCE
this._mapID = NOME DO MAPA QUE FOI CLICADO NO
MARKER DO GOOGLE MAPS
O que eu não tenho é o nome do "FLOOR" que eu preciso encontrar de
acordo com o que eu falei acima.

Eu recebo a seguinte notificação no console:

util.js:189 FIREBASE WARNING: Using an unspecified index. Your data
will be downloaded and filtered on the client. Consider adding
".indexOn": "floorType" at
/users/Aliansce/MAPS/ViaParqueShopping/FLOORS/B30 to your security
rules for better performance.

O meu código é o seguinte:
<code>static AsyncQueryMainFloorMap(mapID){
        const GOOGLE_MAPS_STATIC_CLASS = GoogleMaps;

        this._userID = "Aliansce";
        this._mapID = mapID;

        this._mapFloorROOT = this.FirebaseInstance.ref('users/' + this._userID + '/MAPS/' + this._mapID).child('FLOORS');
        this._mapFloorROOT.once('child_added').then((mapFloorSnapshot) => {
            this._floorROOT =  this.FirebaseInstance.ref('users/' + this._userID + '/MAPS/' + this._mapID + '/FLOORS/').child('' + mapFloorSnapshot.key + '/');
            this._floorROOT.orderByChild('floorType').equalTo('main').once('child_added').then((e) => {
                console.log(e.key)
            });

        }) .catch((error) => {
            console.warn("error: " + error);
            // TODO
        });

    };
</code>
Answer: Também gastei umas horitas a tentar perceber o que estava mal e porquê esta mensagem. Adicione a regra no teu local de regras:
<code>{
   "rules": {
   ...,
   ...,
     "nome_tabela_ou_colecao": {
       ".indexOn": "floorType"
   }
  }
}
</code>
Espero ter ajudado.


How can I submit documents to Apple as reject for use of protected 3rd party material?

Question: I've received a rejected:

8.5: Use of protected 3rd party material (trademarks, copyrights, trade secrets, otherwise proprietary content) requires a documented rights check which must be provided upon request

I've got the document now but after I upload my app, and I can not find any place to submit my document. Is there anybody that knowns how to submit it?
I knew that before I upload my app I can submit the document, but I want to know how to submit my document after I have already upload my app.
Answer: One idea: tell them you have the documentation in the review notes.  In iTunes Connect, click on your app.  Then click the View Details button.  Then click the Edit button next to "Version Information".  In the "Review Notes" text box, tell them that you have the documentation and will provide it on request.  Or put the documentation on a web server somewhere and enter the URL.
Another idea: Submit an appeal to the app review board, and tell them you have the documentation in the "Reasons for Appealing" text box.
Comment: Thanks a lot for you ideas and do you have any other way to submit my documentation directly
Comment: I gave you all the ideas I have.  There might be other ways, but unfortunately I don't know everything.


Resource Monitor Disk Usage scale

Question: I'm sure this is going to be very dependent on the harddrives and other hardware that we have in our machine, but I have no idea how to read these graphs.
This graph looks nice and low.

This one looks scary as hell.

I know that the scale is different, but how do I know when things are starting to go wrong as far as the disk actually struggling to keep up?
Comment: The attachments aren't showing up.
Comment: I'm not sure why not.  I viewed the source and they are actually coming from the web (not my local machine).  To explain, basically, when Resource Monitor uses 100KB/sec scale for disk utilization, it looks scary (stuff is pegged).  When the scale is 1MB/sec, the graph looks nice and low.  How can I tell when things are wrong?
Answer: If you only need to know if your disk is bottlenecking something, the basic parameters for disk performance are queue length (you might want to look at read and write queues separately, sometimes this is insightful), the disk idle time percentage and possibly the request service time. The queue length value tells you how many requests for disk data are outstanding but not yet serviced because the disk is busy doing other things. If you see anything there that is larger than the number of spindles (i.e. the number of disks in your disk array if you have one or simply "1" if you only have a single disk to monitor) for a prolonged period of time, your applications are certainly waiting for I/O a lot and you should look into it. You will see the disk idle time go down to 0% (or the disk busy time go up to 100%) simultaneously, because if there is always at least one request in the queue, then there is never time for the disk to be idle.
The resource monitor shows the disk's busy time percentage (blue lines in the graph) as well as the queue length and the throughput. Throughput is hardly of any value except that it is nice to look at. None of the given graphs looks "scary" in the "my system is under high load" way - the disks are mostly idle (blue line crawling at the bottom, mean disk queue length << 0.05)
Comment: There usually are [rule-of-thumb guidelines](http://blogs.technet.com/b/vipulshah/archive/2006/11/30/understanding-perfmon-counters-while-troubleshooting-sql-server-performance-issues.aspx) for different counters and different workloads. But of course nothing beats your own experience (like in "the last time I tried to work on a machine with the disk queue length of 10 it really really sucked") since you know your machine's limits best (a queue length of 10 would be unbearable to work with on a single-disk workstation, but pose a rather low load in an 80-disk SAN appliance)
Comment: Thank you.  I honestly had never noticed the blue line at the bottom of the Queue Length graph.  I'm just trained that when things get to the top, it's bad.  In this case, from what you have said, all is doing just fine.
Comment: The resource monitor uses variable scaling. No matter what you do, the graphs will always go "to the top" as the scale will be readjusted accordingly. You need to pay special attention to the scale values to get any meaning out of the graphs.
Comment: That was my point.  If the graph scale goes from 1 to 10, is that bad?  I mean, does it scale up to 100 and 1000, and THEN I should be worried?  It's no longer an issue anymore.

Resource Monitor Disk Usage scale


Term parent in node.tpl.php

Question: I have an Entity taxonomy Reference field in my content type.
I need to print parent of the term linked to my node in node.tpl.php (link to that term). How can I do it?
Thanks for your help.
Answer: Ok, I figured it out. This is my code:
<code><?php
    $term = field_get_items('node', $node, 'field_taxonomy_term');
    $parent = current(taxonomy_get_parents($field[0]['target_id']));
    print l($parent->name, 'taxonomy/term/'. $parent->tid);
?>
</code>

Term parent in node.tpl.php


Is there a way to add multiple actions to widget in Gmail apps script add-on?

Question: I'm working on Gmail add-on that allows to start new draft/reply using email template.
User can navigate to templates list and start new draft by clicking one of them (Decorated text widget).
I'm wondering is there a way to set the navigation in add-on after draft was started. I would like to close templates menu and get the user back to previous page.
Tried to combine actions on widget like:
<code>templateCard
                .setComposeAction(
                  myComposeAction,
                  CardService.ComposedEmailType.STANDALONE_DRAFT)
                .setOnClickAction(
                  myNavigationAction
                )
</code>
But it doesn't work. Only compose action is running.
Answer: This is currently not possible. Based on Google's Documentation:

A UI object can only have one of setOpenLink(openLink), setOnClickAction(action), setOnClickOpenLinkAction(action), setAuthorizationAction(action), or setComposeAction(action, composedEmailType) set.

You would need to add an additional UI element with the .setOnClickAction() method. I found this post where a similar scenario was given. I'd highly recommend you to submit a feature request outlining the limitations and your current use case, maybe this could be updated in the future.
Link to Google Workspace Add-ons Feature Requests


Show that $2\tan^{-1}(2) = \pi - \cos^{-1}(\frac{3}{5})$

Question:
Show that $2\tan^{-1}(2) = \pi - \cos^{-1}(\frac{3}{5})$

So, taking $\tan$ of both sides I get:
LHS $=\frac{2\tan(\tan^{-1}(2))}{1 - \tan^2(\tan^{-1}(2))} = -\frac{4}{3}$
and
RHS $= \tan(\pi - \cos^{-1}(\frac{3}{5})) = ~...$
I wasn't sure how to treat the RHS given the $\pi$ term. If it were just $\cos^{-1}(\frac{3}{5})$ I guess I would try to manipulate $\sin^2(\theta) + \cos^2(\theta) = 1$ to try and find something appropriate for substitution; however, I am not sure where to even start with the given $\theta$.
Comment: You know the addition formula for the tangent? Even simpler: what is the period of the tangent function?
Comment: The appearance of $3$ and $5$ in an inverse cosine should make you think of a $3-4-5$ triangle
Comment: @J.M.: I didn't know the addition formula, thanks for that. So, since the period of the tangent function is $\pi$, the $\pi$ in my problem has no affect on the output of the function, so I can just evaluate it as $\tan(-\cos^{-1}(\frac{3}{5}))$.
Answer: HINT: Formulate a general identity for $ \tan (\pi-x).$
Comment: Because the tangent function has a period $\pi$ and because it is an odd function, $\tan(\pi - x) = -\tan(x)$, right?
Comment: @stariz77 Yes that is correct. So now you need only find $ \tan(\cos^{-1} 3/5) .$ The easiest way to do that is to draw triangle with one of the angles being $\cos^{-1} (3/5).$
Answer: It's not particularly efficient, but you can work the problem using very elementary analytic geometry and no trig identities.
Let $P=\left\langle\frac35,\frac45\right\rangle$, $Q=\langle -1,0\rangle$, $R=\langle 1,0\rangle$, and $O=\langle 0,0\rangle$. Clearly angle $POR$ is $\cos^{-1}\frac35$, so angle $POQ$ is $\pi-\cos^{-1}\frac35$. Let $S=\langle x_0,y_0\rangle$ be the point on the unit circle in the upper half plane such that $OS$ bisects angle $POQ$. Then $y_0$ is the perpendicular distance from $S$ to $OQ$, which must be equal to the perpendicular distance from $S$ to $OP$. The latter is the distance from $S$ to the line $y=\frac43x$.
The perpendicular from $S$ to that line has slope $-\frac34$, so its equation is $y-y_0=-\frac34(x-x_0)$, and it intersects the line $y=\frac43x$ at the point $\langle x_1,y_1\rangle$ where $y_0-\frac34(x_1-x_0)=\frac43x_1$, i.e., where $x_1=\frac{12}{25}\left(y_0+\frac34x_0\right)$ and $y_1=\frac43x_1=\frac{16}{25}\left(y_0+\frac34x_0\right)$. The distance from $\langle x_1,y_1\rangle$ to $S$ is
$$\begin{align*}&\sqrt{\left(\frac{12}{25}\left(y_0+\frac34x_0\right)-x_0\right)^2+\left(\frac{16}{25}\left(y_0+\frac34x_0\right)-y_0\right)^2}\\
&\qquad\qquad=\sqrt{\left(\frac{12}{25}y_0-\frac{16}{25}x_0\right)^2+\left(\frac{12}{25}x_0-\frac9{25}y_0\right)^2}\\
&\qquad\qquad=\frac1{25}\sqrt{(12y_0-16x_0)^2+(12x_0-9y_0)^2}\\
&\qquad\qquad=\frac1{25}\sqrt{225y_0^2-600x_0y_0+400x_0^2}\\
&\qquad\qquad=\frac15\sqrt{9y_0^2-24x_0y_0+16x_0^2}\\
&\qquad\qquad=\frac15\sqrt{(3y_0-4x_0)^2}\\
&\qquad\qquad=\frac15|3y_0-4x_0|\\
&\qquad\qquad=\frac15(3y_0-4x_0)\;,
\end{align*}$$
since clearly $y_0>0$ and $x_0<0$.
This must be equal to $y_0$, so we have $\frac15(3y_0-4x_0)=y_0$, and hence $y_0=-2x_0$. Thus, the slope of the line $OS$ is $-2$, and it follows that the tangent of angle $SOQ$ is $2$ and hence that $2\tan^{-1}2$ equals angle $POQ$, which we already saw is $\pi-\cos^{-1}\frac35$.
Answer: $$
2\tan^{-1}(2)
$$
$$
\tan^{-1}\frac{(2*2)}{1-(2*2)}
$$
$$
\tan^{-1}\frac{4}{-3}
$$
$$
\pi-\tan^{-1}\frac{4}{3}
$$
$$
\pi-\cos^{-1}\frac{3}{5}
$$
proved..
Answer: From this or Ex$\#5$  of Page $\#276$ of this,
  $$\tan^{-1}x+\tan^{-1}y=\begin{cases} \tan^{-1}\frac{x+y}{1-xy} &\mbox{if } xy<1 \\\pi+ \tan^{-1}\frac{x+y}{1-xy} & \mbox{if } xy> 1. \end{cases} $$
$$\implies2\tan^{-1}x=\begin{cases} \tan^{-1}\frac{2x}{1-x^2} &\mbox{if } x^2<1\iff -1\le x\le1 \\\pi+ \tan^{-1}\frac{2x}{1-x^2} & \mbox{ else where } \end{cases} $$
$$\implies2\tan^{-1}2=\tan^{-1}\left(\frac{2\cdot2}{1-2^2}\right)=\pi+\tan^{-1}\left(-\frac43\right) $$
Let $\theta=\tan^{-1}\left(-\frac43\right)\implies \tan\theta=-\frac43$
Now, as the principal value of $\displaystyle\tan$ lies $\displaystyle\in\left[-\frac\pi2,\frac\pi2\right],\cos\theta=+\frac1{\sqrt{1+\tan^2\theta}}$
Now, $\cos(\pi+y)=-\cos y$
Comment: This can be derived using $$\tan^{-1}x+\cot^{-1}x=\frac\pi2\implies \tan^{-1}x=\frac\pi2-\cot^{-1}x=\frac\pi2-\tan^{-1}\frac1x$$ as well, by putting $x=2$


All repositories in Docker registry get removed after docker daemon restart (docker-for-mac)

Question: I can successfully create a docker registry v2 service using:  docker service create then I push some if my images to it using docker push.
When I check the registry by curling localhost:5000/v2/_catalog I get all my pushed repositories. I even successfully create a stack using this registry.
The problem is whenever I restart docker (directory or by restarting my mac) all my repositories get removed from registry. I checked on linux but it did not have any issue.
Am I doing something wrong? I just wanted to send this question here before opening any issue in Docker for mac github repo.
I'm using Docker for mac version 17.09.0 CE (build 19611)
Comment: Can you provide the full "docker service create" command that you are using? You may be storing the images inside the container instead of using a --mount. That means any time the service's task stops, the container's write layer will be gone with it. Use a mount for your persistent data.
Comment: @programmerq Which path in the registry conteiner should I mount my fs to in order for its images to be stored on my device?
Answer: In order for registry data to persist after service (containers) restart you should mount your filesystem to it using --mount /path/in/my/system:/var/lib/registry in your docker service create command.


Memcache do cache_pages?

Question: I have disabled Cache pages for anonymous users from Drupal admin admin/config/development/performance.
I have set my site to point on 2 domains such as www.ex1.com and www.ex2.com. One domain is for german language and one is for English. All is working fine on my localhost where there is no memcache. But on my live server front page is getting cached.
In settings.php I have settings like below:
<code>$conf['cache_backends'][] = 'sites/all/modules/memcache/memcache.inc';
$conf['lock_inc'] = 'sites/all/modules/memcache/memcache-lock.inc';
$conf['memcache_stampede_protection'] = TRUE;
$conf['cache_default_class'] = 'MemCacheDrupal';

// The 'cache_form' bin must be assigned to non-volatile storage.
$conf['cache_class_cache_form'] = 'DrupalDatabaseCache';

// Don't bootstrap the database when serving pages from the cache.
$conf['page_cache_without_database'] = TRUE;
$conf['page_cache_invoke_hooks'] = FALSE;

$conf['memcache_servers'] = array('memcached:11211' => 'default');
$conf['memcache_bins'] = array( 'cache' => 'default',
        // Any bin that goes to 'none' will fall through to database caching.
        'cache_form' => 'none', );
</code>
Do this can help like adding below line ?
<code>$conf['memcache_bins'] = array('cache' => 'default',
                                 'cache_page' => 'pages',
                                 'cache_block' => 'blocks');
</code>
setting pages cache to point cache_page.
Please suggest. That will be great if someone can explain that how we stop cache_pages when we are using memcache.
UPDATE: Its happening with only view Titles ie: titles get cache if I visit one domain first and then second. It shows title language from first domain into second domain.
Thanks!
Answer: This is what you need.
<code>// Turn off page cache
drupal_page_is_cacheable(FALSE);
// Set memcache prefix to be different for each hostname.
$conf['memcache_key_prefix'] = $_SERVER['HTTP_HOST'];
</code>
Comment: @jas I think you'd be safe then.
Comment: Thanks I will test with it and come back with details.  That will be great if you can please explain little more. What exactly this will do like I have already disabled cache_page from admin/config/development/performance.
Comment: @jas `drupal_page_is_cacheable(FALSE);` is the same as turning off caching on the performance page. `memcache_key_prefix` is how you keep the caches from the 2 sites different. If both sites use the same settings.php then you'll need to use something like `$_SERVER['HTTP_HOST']` instead of `basename(realpath(conf_path()))` (which is the location of the settings.php file).
Comment: Thanks for explanation. My case I single site i.e. Shared database and just pointing to 2 domains where I show English language on first domain and other language on second domain with help of entity translations. +1 please check in my question if my configuration need to modify or you can pls update answer. I am confused about this.
Comment: @jas Updated the answer. www.ex1.com will have it's own cache and  www.ex2.com will have its own cache. This should take care of the issues you've seen.
Comment: If both domains will have there separate cache is that will be ok to turn on page cache to improve performance as we have 1000's of visits  per day . Please suggest ?

Memcache do cache_pages?


Query takes nearly 6 secs. Is it ok?

Question: I switched on Devel logging on site (shop on Drupal Commerce), went to Shop->Orders and saw that
3818.231 views_plugin_query_default::execute P A E
SELECT commerce_order.order_id AS order_id, commerce_order.order_number AS commerce_order_order_number, commerce_order.uid AS commerce_order_uid, commerce_order.created AS commerce_order_created, users_commerce_order.name AS users_commerce_order_name, users_commerce_order.uid AS users_commerce_order_uid, commerce_order.status AS commerce_order_status, 'commerce_order' AS field_data_commerce_order_total_commerce_order_entity_type FROM commerce_order commerce_order LEFT JOIN users users_commerce_order ON commerce_order.uid = users_commerce_order.uid LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id LEFT JOIN commerce_payment_transaction commerce_payment_transaction_commerce_order ON commerce_order.order_id = commerce_payment_transaction_commerce_order.order_id WHERE (( (commerce_order.status NOT IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5)) )) ORDER BY commerce_order_created DESC LIMIT 100 OFFSET 0
default

2422.621 views_plugin_pager::execute_count_query P A E
SELECT COUNT(*) AS expression FROM (SELECT 1 AS expression FROM commerce_order commerce_order LEFT JOIN users users_commerce_order ON commerce_order.uid = users_commerce_order.uid LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id LEFT JOIN commerce_payment_transaction commerce_payment_transaction_commerce_order ON commerce_order.order_id = commerce_payment_transaction_commerce_order.order_id WHERE (( (commerce_order.status NOT IN (:db_condition_placeholder_0, :db_condition_placeholder_1, :db_condition_placeholder_2, :db_condition_placeholder_3, :db_condition_placeholder_4, :db_condition_placeholder_5)) ))) subquery

Is it normal that on site with 3000 items and 7000 orders it takes so much time to form orders view in admin interface?
Site is hosted on server, Xeon E5-2609x2 (2.4 Ghz), 16 Gb DDR-3 memory
Comment: Can you also add some details of the server your hosted on? Like the memory and cpu available for you?
Comment: Is it OK? Well, who are we to determine what's OK, what's normal et cetera? If you think it's a DB problem, you are asking in the wrong place. If you think it's a problem and want a drupal-side way to fix it, you aren't formulating your request quite right.
Answer: Just looking at the query, the obvious culprit is the recently_read module. The join that is added to the query is fully unindexed:
LEFT JOIN recently_read recently_read_commerce_order ON commerce_order.order_id = recently_read_commerce_order.entity_id

The query doesn't really make sense, so I assume the Views integration for this module needs work.
Answer: 6 second for a query, we can't say what is normal. However there are ways we can improve performance. with the server configuration you have, we can expect better performance.
There are several things you can do to solve this.
Optimize View:
In Drupal many of the performance issue are caused by views. These are mainly caused by use of Left Join in views. Use of pager, distinct feature etc.
These are things that can be solved easily.

You can alter views query to use Inner Join instead of Left Join
by disabling the distinct in query either from views ui or code.
Avoid using last in pager or use views_litepager module instead.

Here is a sample views alter code:
/**
* Implements hook_views_query_alter().
*
* This disables distinct and turns LEFT joins into INNER joins. This increases
* performance.
*/
function my_module_views_query_alter(&$view, &$query) {
if ($view->name == "my_view") {
$query->table_queue['content_type_article']['join']->type = 'INNER';
$query->distinct = 0;
}
}

There is a good post on optimizing views that you can read to understand this better here.
Other than this you should check if your mysql configuration in my.cnf is optimized as per your system resources. For this you could use mysqltuner script or mysql-tuning-primer script.
Above that use of memcached with Drupal can also increase performance to great extend.

Query takes nearly 6 secs. Is it ok?


How to add two products in one click

Question: In my Drupal Commerce site, I have a product type - an attribute which refers to another product type (via reference product).
The display is:
Type 1
Product 1-1 x
Product 1-2 x
Product 1-3 x
Add to Cart
Type 2
Product 2-1 x
Product 2-2 x
x produces 2-3
Add to Cart
I would like only one "add  to cart" button to be visible, and that clicking it should add  two products which were selected at the same time.
How can this be accomplished?
Answer: I would do this with rules:
Event
After adding a product to the cart
Action
Add a product to the cart

Parameter: User: [site:current-user],
Product SKU: [other product
sku] Provides variables: Added product line item
(product_add_line_item)
Answer: You can alter add to cart form and insert there your own submit.
<code>$form['#submit'][] = 'my_own_submit';
</code>
Than in your submit you can do anything you want.
E.g. you can get your product from $form_state. Than you can load related product and add it to cart by drupal commerce API. Example of adding product to cart is here

How to add two products in one click


predict category by using K-NN algorithm having text features

Question: I would like to predict the category of the provided data by using K-NN algorithm. Here is an example of the training data set
<code>category sex      age
1        male     19-20-21
5        female   40-41-42
x        male     18        <- provided data
</code>
the features of the training data set could be numbers such as age but especially additionally text data. How could you suggest me to calculate distance since I have not data numbers but text data. By using hamming distance perhaps?
Answer: The minimal approach for text based features is to used bag of words. Basically the whole data set allows you to define the vocabulary of term used and then each item has a 1/0 value for the presence/absence of each term. This lead to pretty large sparse vector of 0/1 but it's then easy to compute distance using any kind of cosine similarity approach.
To improve over the bag of words, you can refine the 0/1 using term frequency (or even better tf/idf).
At the end, you will still need to aggregate the distance computed over the text data with the other features. Since the range and dynamic might be very different over these feature distances, it might be tricky. Try to start with basic linear combination (weighted sum). If not to clumsy, the weights night be easy to fix. If not, then you can try optimization approach to approximate good values.
Comment: I have a question. In the example above I have only two features. What about when I have more features let suppose more than twenty. Is it still possible to use this algorithm?
Comment: Aren't confusing "date fields" with "features"? If I understand well, you have few text fields that will be converted into features using bag of words. If you have more text fields, you can choose to mix them or have separated bags of words.
Then for the combination, of course it can be extended to more features. You will have more weights to define which might be longer but sometimes, basic values (every weights at 1) just to the trick.


Hub and spoke peered VNETs and Loadbalancer

Question: I have a hub and spoke topology of peered vnets. I wanted to place a loadbalancer in the hub and have all outbound traffic from each VM via a single public IP.
The portal and API suggest that load balancer doesnt support multiple peered vnets.
Has anybody solved this problem?
Answer: You cannot put a VM in a peered vNet behind a load balancer in another vNet. If your aim is to get a consistent private IP across all vNet's then at the moment the only solution (native, not third party) that will allow you to do this is Azure Firewall. With this you can route all outbound traffic to the firewall and use its public IP for the outbound address.
Azure vNet NAT is a new service that may help eventually, but at the moment it cannot be used across multiple vNets.


A Markov Regime-Switching GARCH with Time-Varying Transition Matrix Package in R

Question: Does anyone know if there exists any Markov regime-switching GARCH with time-varying transition matrix package or tutorial in R? I know of the "MSGARCH" package by D. Ardia et al. but the transition matrix is constant. Thanks in advance!
Answer: For the purpose of my thesis I created a fork of the R-package MSGARCH that incorporates time-varying transition probabilities. The probabilities are estimated through a multinomial logistic functional form. I am sorry for the late answer - maybe someone else finds this useful. You can check it out at https://github.com/mkaywins/MSGARCH


Type I and Type II negative binomial distribution in zero inflated negative binomial (ZINB) model

Question: When is it appropriate to use a Type I versus Type II negative binomial distribution in a zero-inflated negative binomial distribution?
I've found a Similar question, but without an answer I can comprehend or determine if it relates to zero-inflated negative binomial distributions
In my dataset using R code, I have determined using AIC values that the zero-inflated negative binomial (ZINB) distribution provides the best fit compared with other distribution models.
Using the R package glmmTMBi have specified ZINB models with both Type I and Type II:
library(glmmTMB);library(MuMIn)
m1 <- glmmTMB(dv ~ iv1 + iv2 + iv2,ziformula=~.,data=df,family=nbinom1)
m2 <- glmmTMB(dv ~ iv1 + iv2 + iv2,ziformula=~.,data=df,family=nbinom2)

When testing the models' AIC values, the model with Type II provides a better fit
AICc(m1,m2)
   df     AICc
m1  9 528.3359
m2  9 527.7481

When using the zeroinfl function from the pscl
zm2 <-  zeroinfl(dv ~ iv1 + iv2 + iv2,data=df,dist="negbin")
> AICc(m2,zm2)
    df     AICc
m2   9 527.7481
zm2  9 527.7481

It yields the same AIC value as Type 2 NB (and the estimtes and p-values are nearly identical), So it seems that Type 2 is assumed in the zeroinfl function.
My data set models the use of drugs (as the dv) over the past 30 days.
Is it appropriate to use a Type II negative binomial distribution and why?.
Is it reasonable to justify this decision with AIC values?
Answer: The difference between these two model families is the relationship between mean and variance.
nbinom1 (also called quasi-poisson)
variance = µ * phi
where µ is the mean and phi is the over-dispersion parameter
nbinom2 (the default negative binomial in most packages)
variance = µ(1+µ/k) also written µ + (µ^2)/k
where µ is the mean and k is the over-dispersion parameter
When choosing between these the paper by VerHoef, J.M. & Boveng is very helpful as are pages 16 and 17 of Bolker et al 2012.
VerHoef, J.M. & Boveng say that AIC doesn't necessarily apply to quasi poisson models (nbinom1) and they are skeptical about comparing AIC and qAIC (an information criteria developed for quasi models) although you do see it done.
Instead they recommend plotting the observed values against the squared residuals. This plot can be very noisy so grouping samples with similar observed values together and making the equivalent plot for the groups is recommended. If this plot follows a linear trend it suggests quasi-poisson (nbinom1) is best whereas a quadratic trend argues for a negative binomial model (nbinom2).
If you have a decent number of samples and a finite number of possible combinations of explanatory variables you could form groups not based on response variables but on treatment combinations. This plot is demonstrated in Bolker et al 2012 (link in the references) along with code to generate the plot in R.
Ben Bolker, Mollie Brooks, Beth Gardner, Cleridy Lennert, Mihoko Minami, October 23, 2012, Owls example: a zero-inflated, generalized linear mixed model for count data. https://groups.nceas.ucsb.edu/non-linear-modeling/projects/owls/WRITEUP/owls.pdf
VerHoef, J.M. & Boveng, P.L., 2007. Quasi-Poisson Vs. Negative Binomial Regression: How Should We Model Overdispersed Count Data? Ecology, 88(11), pp.2766–2772.
Answer: Users of binomial and Poisson models are often surprised to learn that semiparametric models work extremely well for count data while making no assumptions about the distribution of counts for any one type of observation.  The question about how one can model an entire distribution empirically, which may require thousands of intercepts when there are thousands of distinct $Y$ values, comes up frequently.
Consider the special case where there are no covariates (predictors), and no ties in the data ($n$ observations).  The empirical cumulative distribution function (ECDF) estimates the $Y$ distribution unbiasedly, without assumptions.  It is a nonparametric estimator with $n-1$ parameters.  In ordinal semiparametric models such as the proportional odds model, the ECDF is just the estimated cumulative probabilities when there are no covariates.  If there are $k$ distinct $Y$ values there are $k-1$ intercepts (here $n-1$ if there are no ties in the data).  The intercepts are exactly the logits of the ECDF values.  The effective number of parameters in this model is low because of the order restrictions in the intercepts, and because the ECDF has effectively about 3-5 degrees of freedom.  This can been seen by comparing widths of confidence bands from the ECDF for the unknown cumulative distribution with widths from fitting 2-, 3-, 4-, and 5-parameter parametric distributions.
Now consider covariates.  You can easily estimate more parameters than there are observations without problem, as intercepts are order-restricted so effectively only have a few degrees of freedom.  Computationally thousands of intercepts are handled (in R rms::orm and SAS JMP only) by respecting the sparse nature of the information matrix, which is tri-band diagonal).  Intercepts are like covariate-adjusted ECDF values.  Interestingly, Bayesian ordinal models do not need to invert information matrices so they automatically handle lots of intercepts without special programming (see R rmsb::blrm).
Intercepts encode the whole ECDF so distribution assumptions are gone.  Ordinal models can handle extreme ties in the data (the limiting case is the binary logistic model which is a special case of the proportional odds model) so they handle zero inflation as well as ceiling effects and upper limits of detection.
Comment: Yes I always use ordinal models now for continuous Y because of those major advantages.  Otherwise there is too much uncertainty in how to transform continuous Y, and Y with heavy ties doesn't work with standard models.  I like the logit link because of interpretability and not having mathematical constraints.  Choose between that one and one much different from it - the log-log link (Cox proportional hazards model).  No reason to use probit which is too similar to logit but hard to interpret.  For a case study looking a multiple link functions for continuous Y see hbiostat.org/rmsc
Comment: That's quite incredible. So for even continuous variables we can use ordinal models, making less restrictive distributional assumptions, with little loss in efficiency. That would solve a lot of modelling problems that I have worked on (cognitive measurements with ceilings). Do you prefer a particular link function for ordinal models? If so, why?
Comment: @FrankHarrell does the same property apply for the continuation ratio model or only for the proportional odds one? Also, what is the coefficients' interpretation for the proportional odds model (with a logit link) for a continuous outcome? Is it how covariates relate to the CDF of this outcome?
Comment: I'm 2/3 sure it doesn't apply to the CR model unless you transform it in to log-log link form (there is a paper about that equivalence).  In its usual form the intercepts can bounce around.  The easy properties I mention apply to any member of the cumulative probability class of semiparametric models.
Answer: It is appropriate to use both Type I and Type II negative binominal distributions, as their AIC values are very close to each other. Internally, they differ by different likelihood function construction, where each observation's probability mass formula is given by the assumed distribution. If one formula leads to a larger log likelihood value that corresponds to a smaller AIC, then it is more likely the data generation process followed this chosen formula.
Compared with choosing a family that minimizes AIC, more important questions are what I listed in this answer https://stats.stackexchange.com/a/627172/284766. A zero-inflated negative binominal model makes sense here if your participants include both nondrug users (who caused zero inflation) and drug users (who may use no drugs during your study window) IF you don't know who is drug user and who is not. In your case, modeling the dispersion is particularly important through glmmTMB(..., disp = ~ ...) if you want to stress that one drug use induces more drug use on the same person and examine how this self-reinforcement mechanism is related to any predictors, as positively correlated event occurrence is a common reason for overdispersion.
If you do know who are drug users and nonusers among your participants, which appears more plausible a case to me, you may want to use other modeling techniques, such as Heckman sample selection model that is very popular in criminology studies, in which it is not meaningful to discuss the count of drug usage among nonusers. You can present both zero-inflated count models and Heckman sample selection models and compare whether substantive conclusions differ between them.
Comment: I find it hard to make the assumptions in any of the binomial models when [semiparametric models](https://fharrell.com/post/rpo) work well and don't make any distributional assumptions.
Comment: @FrankHarrell, it's amazing from your web page where it claims that `lrm` and `orm` can fit thousands of distinct values in the response. Is it done through penalization of coefficients or by binning intervals of response values into larger groups? An ordinal regression model estimates (k - 1) intercepts (thresholds) if there are k different levels in the response. If data record k unique response values across k observations, I fail to see how a model of (k - 1) intercepts can be any useful, as there will be no more observation left for estimating coefficients of any predictor.
Comment: I've expanded on this in a new answer.
Comment: Hi @FrankHarrell, are you suggesting to use instead an ordinal regression to predict the frequency of drug use? It is a good choice if the observed integer values are very limited, such as only 0, 1, 2, 3 are recorded in the response variable. By the way, I came across your 1990 paper on partial proportional odds model, that I referred to in my dissertation before expanding the technique when specifying threshold-specific coefficients. There is still some distributional assumption in the error term in the latent-response formulation (e.g. logistic distribution in partial PO).
Comment: Cool.  Yes that is what I suggest.  It's better to formulate it without latent variables as then the assumptions are easier to see.  More about assumptions [here](https://fharrell.com/post/impactpo).
Comment: I think the assumption is much easier to comprehend from a latent-response formulation, where the distributional assumption of errors gives the probability mass function and thus the likelihood function. I agree that ordinal regression can be a very good choice to predict drug use frequency, especially if it was measured in bins, often done in frequency questions, instead of all nonnegative integers.
Comment: I find the opposite to be true, prefering to stick with observables.  But I can see how others will disagree.


Invalid Token 'String' in class, struct or interface member declaration

Question: I'm having error with my code "Invalid Token 'String' in class, struct or interface member declaration" please help.
private void string InsertRecords(TextBox textboxname, string qryname, string parametername)
{
    string msg;

    if (textboxname.Text != "")
    {
        ConnString conn = new ConnString();
        string MyConn = conn.GetConn(); // Get Connection String

        using (SqlConnection sqlconn = new SqlConnection(MyConn))
        {
            try
            {
                SqlCommand cmd = new SqlCommand();
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.CommandText = qryname;
                cmd.Parameters.AddWithValue("@" + parametername, SqlDbType.VarChar).Value = textboxname.Text;
                cmd.Connection = sqlconn;
                sqlconn.Open();
                cmd.ExecuteNonQuery();

                msg = $"Record Successfully Added!";
                return msg;
            }
            catch (Exception ex)
            {
                if (ex.HResult == -2146232060)
                {
                    msg = $"Record already exist in the database!";
                    return msg;
                }
                else
                {
                    msg = $"Error Message: {ex.HResult}";
                    return msg;
                }
            }
        }
    }
    else
    {
        msg = $"Please complete required fields";
        return msg;
    }
}

I'm trying to just return the message string and grab that message once called. thank you!
Comment: Remove 'void' from the method definition: instead of 'private void string InsertRecords' just 'private string InsertRecords'
Comment: thank you that works perfect!
Answer: You can't return string and have no return value (void) at the same time. Since you want to return a value remove void
private string InsertRecords(TextBox textboxname, string qryname, string parametername) { }


WPF Binding to variable / DependencyProperty

Question: I'm playing around with WPF Binding and variables. Apparently one can only bind DependencyProperties. I have come up with the following, which works perfectly fine:
The code-behind file:
public partial class MainWindow : Window
{
    public MainWindow()
    {
        InitializeComponent();
    }

    public string Test
    {
        get { return (string)this.GetValue(TestProperty); }
        set { this.SetValue(TestProperty, value); }
        //set { this.SetValue(TestProperty, "BBB"); }
    }
    public static readonly DependencyProperty TestProperty = DependencyProperty.Register(
      "Test", typeof(string), typeof(MainWindow), new PropertyMetadata("CCC"));

    private void button1_Click(object sender, RoutedEventArgs e)
    {
        MessageBox.Show(Test);
        Test = "AAA";
        MessageBox.Show(Test);
    }
}

XAML:
<Window x:Class="WpfApplication3.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:diag="clr-namespace:System.Diagnostics;assembly=WindowsBase"
    Title="MainWindow" Height="350" Width="525"
    DataContext="{Binding RelativeSource={RelativeSource Self}}">
<Grid>
    <TextBox Height="31" HorizontalAlignment="Left" Margin="84,86,0,0" Name="textBox1" VerticalAlignment="Top" Width="152"
             Text="{Binding Test, Mode=TwoWay, diag:PresentationTraceSources.TraceLevel=High}"/>
    <Button Content="Button" Height="23" HorizontalAlignment="Left" Margin="320,85,0,0" Name="button1" VerticalAlignment="Top" Width="75" Click="button1_Click" />
    <TextBox Height="31" HorizontalAlignment="Left" Margin="84,138,0,0" Name="textBox2" Text="{Binding Test, Mode=TwoWay}" VerticalAlignment="Top" Width="152" />
</Grid>

The two TextBoxes update one an other. And the Button sets them to "AAA".
But now I replaced the Setter function with the one that is commented out (simulating some manipulation of the given value). I would expect that whenever the property value is changed it will be reset to "BBB". It does so when you press the button, that is when you set the property in code. But it does for some reason not affect the WPF Bindings, that is you can change the TextBox contents and thus the property, but apparently the Setter is never called.
I wonder why that is so, and how one would go about to achive the expected behaviour.
Comment: possible duplicate of [WPF: XAML property declarations not being set via Setters?](http://stackoverflow.com/questions/3836076/wpf-xaml-property-declarations-not-being-set-via-setters)
Answer: The CLR Property wrapper for a Dependency Property is never guaranteed to be called and therefore, you should never place any additional logic there. Whenever you need additional logic when a DP is changed, you should use the property changed callback.
In your case..
public string Test
{
    get { return (string)this.GetValue(TestProperty); }
    set { this.SetValue(TestProperty, value); }
}

public static readonly DependencyProperty TestProperty =
    DependencyProperty.Register("Test",
    typeof(string),
    typeof(MainWindow),
    new PropertyMetadata("CCC", TestPropertyChanged));

private static void TestPropertyChanged(DependencyObject source, DependencyPropertyChangedEventArgs e)
{
    MainWindow mainWindow = source as MainWindow;
    string newValue = e.NewValue as string;
    // Do additional logic
}

Answer: Your change will not affect the binding because the XAML will call SetValue directly, instead of calling your property setter.That is how the dependency property system works.When a dependency property is registered a default value can be specified.This value is returned from GetValue and is the default value for your property.
Check the link below and read through to Robert Rossney's post to get a fair overview
WPF: What distinguishes a Dependency Property from a regular CLR Property?
also don't miss
http://msdn.microsoft.com/en-us/library/ms753358.aspx
and
http://msdn.microsoft.com/en-us/library/ms752914.aspx
Also note that unlike in normal CLR properties any custom logic you write in the setter will not be executed in Dependency Properties,instead you have to use the PropertyChangedCallback mechanism
http://blogs.msdn.com/b/delay/archive/2010/03/23/do-one-thing-and-do-it-well-tip-the-clr-wrapper-for-a-dependencyproperty-should-do-its-job-and-nothing-more.aspx


Matplotlib Legend Guide basic examples

Question: I am trying to understand how to use the legend() better, specifically how to use proxy artists. I find the Legend guide to be severely lacking. This post is somewhat similar to this one.
I am using Python 2.7.5 on Windows 7, matplotlib version 1.2.1. I wrote this code which is essentially a combination of the examples in the legend guide:
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                      markersize=15, label='Blue stars')
red_patch = mpatches.Patch(color='red', label='The red data')
plt.legend([red_patch,blue_line])

plt.show()

The legend label colors are not those assigned in the handles, nor are they a patch and a line with stars. I have tried removing and adding the lines, adding and removing the commas after the lines, etc. Are they any better references for using legend()? Any other tips for using proxy artists? I don't understand why the examples give me totally different results...
Answer: The Legend Guide was rewritten to be compatible with matplotlib version 1.4.0 or newer. Your version of matplotlib (1.2.1) is over two years old. Don't be surprised if everything shown in the docs does not work with such an old version.
If you upgrade your version, then using
plt.legend(handles=[red_patch,blue_line])

(as is shown in the Legend Guide) instead of
plt.legend([red_patch,blue_line])

yields
Comment: I get the following error when I do this, "TypeError: __init__() got multiple values for keyword argument 'handles'", and no figure. I was following the instructions in the linked post above.
Answer: I'm still using matplotlib 1.2.1 so I'll tell you what works for me. I find that if I pass the line objects to legend(), I also have to pass the labels separately. [This is also consistent with the matplotlib documentation on legened()]. I've modified your example slightly to do this, and it seems to work:
import matplotlib.patches as mpatches
import matplotlib.lines as mlines
import matplotlib.pyplot as plt

line_up, = plt.plot([1,2,3], label='Line 2')
line_down, = plt.plot([3,2,1], label='Line 1')

blue_line = mlines.Line2D([], [], color='blue', marker='*',
                  markersize=15, label='Blue stars')
red_patch = mpatches.Patch(color='red', label='The red data')

lines = [blue_line, red_patch]
labels = [line.get_label() for line in lines]
plt.legend(lines, labels)

plt.show()

Matplotlib Legend Guide basic examples


Samples in decision trees

Question: I am trying to do some binary decision trees with Python (scikit-learn), but my sample has a bad repartition : I have something like 100 000 data points with label 0 and 800 000 with the label 1.
So when I get the tree, I don't have a lot of leaves with class 0, and I don't even have any before reaching a depth of 5. And in that node, there are very few points.
I also tried trees with other variables (still the same labels) and I get more data with label 0 ; the problem is that I am not sure this makes sense.
What could I do ? Should I take a sample of my data with 50% of each label? I am afraid doing that won't really be representative of my data, especially if I put new data in the tree afterwhat. Does anyone know what are the requirements for samples for decision trees? I didn't find any information anywhere about it.
Comment: Could you clarify why this is a problem to begin with?
Comment: How many features do you have?
Comment: What about using other algorithms, e.g. logistic regression, do they give similar results?
Answer: You can solve this problem by going for Stratified K Fold cross validation.
K-Folds cross-validator provides train/test indices to split data in train/test sets. Split dataset into k consecutive folds (without shuffling by default).
Each fold is then used once as a validation while the k - 1 remaining folds form the training set.

Stratified K-Folds cross-validator provides train/test indices to
  split data in train/test sets.This cross-validation object is a
  variation of KFold that returns stratified folds. The folds are made
  by preserving the percentage of samples for each class.

You can refer here for the documentation and examples.
Answer: I don't see why cross-validation (see answer by @phanny) would make things any better in this case. What you may want to look at is an oversampling/undersampling technique. Generally, "plain old oversampling" the minority class leads to overfitting, so I would recommend to either go for SMOTE https://www.cs.cmu.edu/afs/cs/project/jair/pub/volume16/chawla02a-html/chawla2002.html or for combining undersampling and cross-validation (perform each round of cross-validation training with an equal number of cases from each label, so, basically, what you suggested in the final paragraph of your question, but with cross-validation involved) For more info, check https://en.wikipedia.org/wiki/Oversampling_and_undersampling_in_data_analysis
Anyway, don't expect any miracles! Unbalanced data is one of the major problems in classification problem, specially in "harder" ones (in the sense of there not being a simple separation between the classes) This compensating techniques always risk to overestimate the chance of any individual being in the minority class, which is OK (compared to the opposite case) in some problems like medical diagnose, but may not be in your particular problem.
Finally, consider usgin a Random Forest (or AdaBoost) to increase the performance of your trees. Also, don't use overall accuracy as a validation metric for problems with unbalanced data. Try a precision-recall compromise instead.
Answer: 100k samples per class is a lot, even for quite high dimensional inputs. So I suggest undersampling and use 100k of each class. The samples must be drawn randomly to avoid introducing bias.
To control the tree depths (and the tendency to overfit), use min_samples_leaf. It decides the minimum samples in a single leaf node.
To find the appropriate setting for this hyperparameter, use cross validation. Maybe try values in the range 1-1000, log-spaced.
Using a RandomForest instead of a single DecisionTree will greatly reduce the risk of overfitting.
To see how well your model generalized to new data you must use a test set.

Samples in decision trees


code to check logged in user has both roles in tpl file?

Question: I want to print in a page--node--17.tpl.php a code to check for roles from the logged in user and then determine what should be shown, so basically a user must have BOTH roles A and C and if they do i print xxx
If they have roles A and B i write yyy
if they have roles B and C i print zzz
So the code below can check for one role, but how do i do both.. its important that BOTH roles need to be there, a user with just one of the roles will not qualify.
thank u
<?php
  global $user;
  // Check to see if $user has the administrator user role.
  if (in_array('administrator', array_values($user->roles))) {
    // Do something.
  }
?>

also i have this code but i think this is only checking one of the roles, so it checks for either A or B
<?php
global $user;
$check = array_intersect(array('moderator', 'administrator'), array_values($user->roles));
    if (empty($check) ? FALSE : TRUE) {
    // is admin
    } else {
    // is not admin
    }
?>

Answer: Create a reusable function
<?php
function _mytheme_check_for_all_roles_present($roles) {
  global $user;
  foreach($roles as $key => $role) {
    if (in_array($role, array_values($user->roles))) {
      unset($roles[$key]);
    }
  }

  return empty($roles);
}

Use it to check if the user has the roles.
<?php

$roles = array('role_1_to_be_checked', 'role_2_to_be_checked');

if(_mytheme_check_for_all_roles_present($roles) {
  echo "the thing you want to show";
}

you can also do,
<?php

if(_mytheme_check_for_all_roles_present(array('role_1_to_be_checked', 'role_2_to_be_checked')) {
  echo "the thing you want to show";
}

Answer: to check if two conditions are true, you need an AND (&&) operator.
In your exemple I would do this:
<?php
//Load the current user
global $user;

// Check to see if $user has the A, B or C user role.
$as_A_role = in_array('A', array_values($user->roles));
$as_B_role = in_array('B', array_values($user->roles));
$as_C_role = in_array('C', array_values($user->roles));
?>

<?php if ($as_A_role && $as_B_role): ?>

  // Do something.

<?php elseif ($as_A_role && $as_C_role): ?>

  // Do something else

<?php endif; ?>


Catch an AsyncCallback

Question: As you can see in the code below I'm calling connect with an IP and port.
s.EndConnect(ar) is throwing ObjectDisposedException if the server is not running. Now if this happens I want to wait 5 seconds and retry. The problem is catching it in the ConnectCallback and calling itself doesn't work since the object IAsyncResult ar is disposed? I'm not storing the IP and port globally.
Now obviously I can store them globally and fix it that way, but I'm wondering if there's something else to fix this. Since I don't need the IP and port anywhere else storing them globally seems unnecessary.
Socket s;
public ClientSettings()
{
    s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
}
public void Connect(string IP, int port)
{
    /* Simple connection method */
    try
    {
        IPEndPoint ep = new IPEndPoint(IPAddress.Parse(IP), port);
        s.BeginConnect(ep, new AsyncCallback(ConnectCallback), s);
    }
    catch { }
}

void ConnectCallback(IAsyncResult ar)
{
    s.EndConnect(ar);
    connected = true;
    byte[] buffer = new byte[8192];
    s.BeginReceive(buffer, 0, buffer.Length, SocketFlags.None, new AsyncCallback(ReadCallback), buffer);
}

Answer: You're using outdated APIs. Use await with Socket and the problem goes away at much better code quality.
Or, use synchronous IO. This is appropriate if there will only be a few dozen connections at a time. This results in even easier code.
Alternatively, make IP and port instance variables. No need for globals.
Comment: There might be a lot of connections, so if synchronous IO is better for that I'll try to find some more info about that. Do you maybe have a simple preview or anything on this? Also since I'm remaking it anyways now I'll work more with instance variables.
Comment: Synchronous IO is worse with many connections because each thread consumes 1MB of stack memory. If that memory consumption is OK for then go ahead and use the more simple synchronous IO.
Comment: Okay so I won't use that then. What exactly that I'm using is outdated? Got some up to date examples / documentation?
Comment: I don't have anything handy. Search for ".net socket await". http://blogs.msdn.com/b/pfxteam/archive/2011/12/15/10248293.aspx looks good. You can then write code that looks like sync code but is async.

Catch an AsyncCallback


lebesgue integral

Question: let $f\ge 0$ be a measurable function s.t. $\int_R fdm=\infty$, show that for any M>0 there is a real measurable function g, and $0\le g \le f$ and the following hold: $\int_R g dm \ge M$ and g is bounded and m(x:g(x) $\ne$ 0)< $\infty$.
I think g is just a simple function s, such that 2M > $\int_R s dm$ > M. s is bounded since s(x)=$\sum_{i=1}^n c_iI_{E_i}$ <$\sum_{i=1}^n ci$.
Would this be correct?
Answer: Yes, the integral is the limit of the integrals of simple functions smaller than $f$. Therefore, if the integral in infinite, there should be arbitrary large integrals of simple functions smaller than $f$. Take one that is larger than $M$.

lebesgue integral


A graph has no bridge when all its vertices have an even degree : is my proof correct?

Question: Q) I have to show that if every vertex in  graph $G$ has an even degree , then
$G$ has no bridge.
So by contradiction , If every vertex in  graph $G$ has an even degree , then
$G$ has a bridge , which means $G - e$ will result in a disconnected graph.
We know that in this graph, 1 vertex is adjacent to at least 2  other vertices.
So if we remove 1 edge from this graph , the vertices will still be connected resulting in a connected graph and $G$ will have atleast 1 vertex with an odd degree.(For eg , a graph with 4 vertices, each having an even degree , if we remove an edge , $G$ will still be connected .)
which makes my contradiction false.
Is this enough to prove this question or am I missing something ?
Thankyou.
Comment: Please, try to make the titles of your questions more informative. You can find more tips for choosing a good title [here](https://math.meta.stackexchange.com/a/10144/).
Comment: Indeed "Graph Theoryyyyy 1)"  is by no means a good title.  I have proposed one.
Comment: @JMoravitz, One solution to the dilemma would be to improve the title oneself, and then upvote.
Comment: I apologize that my title wasn't informative and lame. :( @SimplyBeautifulArt
Answer: When beginning your proof by contradiction, what you should have rather than "If every vertex has even degree then $G$ has a bridge" is:

Suppose every vertex in $G$ has even degree and $G$ has a bridge.

We then look at what happens to the graph $G$ after having removed that bridge like you suggest.  Unlike how you suggest though, removing the bridge will not have implied our graph will still be connected, it will be a disconnected graph and only a disconnected graph.  Just because the ends of the removed bridge will be adjacent to something doesn't mean that the part of the graph on the one end of the bridge will be connected to the other part of the graph.  We will in fact be guaranteed to be left with at least two separate connected components.
To continue, recognize that each connected component that used to be adjacent to the bridge should be able to form its own graph by itself.
Can you describe the degrees of the vertices in each of those connected components?  For the one connected component, how many vertices of odd degree are there?  Have you heard of something called the handshaking lemma?  How might that be useful here?
Answer: Your proof is wrong in two ways:

It isn't necessarily true that all vertices are connected to at least two others. A vertex could have no edges connected to it, because zero is an even number.
You don't actually use the "even" property except to assert that each vertex has at least two edges. In fact, it is possible for every vertex in a graph $G$ to have at least two edges, and yet $G$ still has a bridge.


Setting field attribute as read only in hook_form_alter?

Question: I'm trying to create a simple custom module to stop the Title of a specific node being edited.
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'nodetitle_node_form') {
    unset($form['title']);
  }
}

Currently it just removes any reference to the Title from the edit pages. Does anyone know how I can set the Title field attribute read only?
Answer: You can use the #disabled attribute:
function mymodule_form_alter(&$form, &$form_state, $form_id) {
  if ($form_id == 'nodetitle_node_form' && $form['nid']['#value']) {
    $form['title']['#disabled'] = TRUE;
  }
}

I made the assumption that you want this when editing nodes only (not when they are being added) which is what the && $form['nid']['#value'] part is for.
Comment: The problem with #disabled is that it prevents submission of the disabled field as the drupal form api says...


How do you dynamically redirect a user's role?

Question: This is a two parted question that deals with two different Modules "User" (or even possibly "triggers and actions") and Profile2. The main task is to have a user dynamically placed within a user role based on the information they submit within the user registration form fields. Presently, I have the form set up with a taxonomy button list. What happens next is the user should then be given a profile type that they can edit after the account creation is complete. Can you help?
Answer: Checkout Auto Assign Role module.
You might need some customization or might have to play with the rules module as well.
Comment: I am playing with the rules module now. What's perplexing me is I can't get the rules to associate with a the specific taxonomy term that they select to assign the roles type. I don't know how to add the term to the data selection...
Comment: I got it to work by using rules with the terms data selection under comparison.
Comment: Good to hear that rules worked for you.
Comment: Yeah thanx.... auto assign just doesn't have enough functionality
Answer: One of the easiest ways with the UI is to use Rules. Create a new rule that is set on either when a user creates saves a new account or saves a new profile (or what ever the instance is that prompts for role change). Then you set up a condition of a matching data comparison. Then have it change the user role.


SQL query to copy column contingent on contents

Question: Currently I have an SQL query that looks like this:
INSERT INTO my_table
(Date, Name, Age, City)
SELECT
DATE_ADD (Date, INTERVAL 7 DAY), Name, Age, City
FROM my_table

This allows me to carry forward to new weeks with an incrimenting "Date" column, while copying over consistent columns (I have other numerical columns that don't copy over).  However I also have a column called "Status" which I want to copy forward only if the status is "Hold" or "Pending".  If the status is either of those, I want it to carry forward as "Needs Examining".
I know I need some type of if function within my SQL code, but I am uncertain how exactly to accomplish this.
Answer: You can do it by the CASE, if the Status is not matching you can add as empty string.
INSERT INTO my_table (Date, Name, Age, City, Status)
SELECT DATE_ADD (Date, INTERVAL 7 DAY), Name, Age, City,
       CASE WHEN Status IN ('Hold', 'Pending') THEN 'Needs Examining'
       ELSE '' END AS Status
FROM my_table

Or, if you want to INSERT only for the Hold, Pending status you need to add the condition in the WHERE clause and in the SELECT you can place your required content:
INSERT INTO my_table (Date, Name, Age, City, Status)
SELECT DATE_ADD (Date, INTERVAL 7 DAY), Name, Age, City, 'Needs Examining' AS Status
FROM my_table
WHERE Status IN ('Hold', 'Pending')

Comment: Perfect!  Exactly what I needed.  Thanks


Durbin-Watson test for first order autocorrelation when interaction effects are present

Question: I have a multiple linear regression model (OLS) that has a constant, 5 variables, and an interaction term between two of the dummy variables.
I need to perform the Durbin-Watson test for first-order correlation, and in order to find the critical values, I need to know the number of explanatory variables (not taking into account the constant).
Is the interaction term an explanatory variable in itself for these purposes (so I have 6 explanatory vars), or do I find the critical values for 5 explanatory vars?
Thanks!
Answer: The interaction counts as an explanatory variable. If there is a factor involved in the interaction, all of the levels after the first count (so an interaction between two factors can count as many terms in this situation).


AbpUserRequestCultureProvider returned the following unsupported cultures

Question: When I check my logs on my Angular ASP.NET application, I'm repeatedly getting this error message:
WARN  2018-07-19 05:43:09,596 [42   ] calization.RequestLocalizationMiddleware - AbpUserRequestCultureProvider returned the following unsupported cultures 'null'.
WARN  2018-07-19 05:43:09,596 [42   ] calization.RequestLocalizationMiddleware - AbpUserRequestCultureProvider returned the following unsupported UI Cultures 'null'.
WARN  2018-07-19 05:43:09,596 [42   ] calization.RequestLocalizationMiddleware - AbpLocalizationHeaderRequestCultureProvider returned the following unsupported cultures 'null'
Has anyone had any experience with this, or what could be causing the issue?
Any help would be appreciated.
Answer: It means ABP couldn't get user's language from header of the request.
Normally it checks the header .AspNetCore.Culture and returns null if not found.
Check your request headers...
A sample header value is below;
.AspNetCore.Culture=c=en|uic=en

c:Culture
uic: Ui Culture
Answer: I'm failure with header: .AspNetCore.Culture,
This one works on my project: header: Accept-Language value: "en-US".
Comment: Hi Akira, see my answer.
Answer: 'null' culture issue was fixed in Prevent null being saved into user's DefaultLanguage (ABP 4.9, Sep 2019).

Another issue is that Nginx as a reverse proxy will not pass headers that contain a period.
In this case, the ".AspNetCore.Culture" header.
Related: Cannot get header that contains a period from NGINX for the "Abp.TenantId" header (ABP 4.4, Mar 2019).
ABP 6.0+
AbpLocalizationHeaderRequestCultureProvider.HeaderName is configurable.

In Startup.cs#L132, get AbpLocalizationHeaderRequestCultureProvider and set its HeaderName:

// app.UseAbpRequestLocalization();
   app.UseAbpRequestLocalization(options =>
   {
       var headerProvider = options.RequestCultureProviders.OfType<AbpLocalizationHeaderRequestCultureProvider>().First();
       headerProvider.HeaderName = "AspNetCore-Culture";
   });

In app-initializer.ts#L122, replace '.AspNetCore.Culture' with 'AspNetCore-Culture':

// '.AspNetCore.Culture': `c=${cookieLangValue}|uic=${cookieLangValue}`,
    'AspNetCore-Culture': `c=${cookieLangValue}|uic=${cookieLangValue}`,

Below ABP 6.0

Copy AbpLocalizationHeaderRequestCultureProvider with the patch to your project as MyLocalizationHeaderRequestCultureProvider.
In Startup.cs#L132, insert an instance of MyLocalizationHeaderRequestCultureProvider into RequestCultureProviders after setting its HeaderName.

// app.UseAbpRequestLocalization();
   app.UseAbpRequestLocalization(options =>
   {
       var headerProvider = new MyLocalizationHeaderRequestCultureProvider();
       headerProvider.HeaderName = "AspNetCore-Culture";
       options.RequestCultureProviders.Insert(2, headerProvider);
   });

In app-initializer.ts#L122, replace '.AspNetCore.Culture' with 'AspNetCore-Culture'.

Alternative
You can turn off ignore "invalid" headers in Nginx.


No transactional EntityManager available when Persisting an object

Question: I have got No transactional EntityManager available exception when I tried to persist an object.
I have a Spring project with the following configuration class:
@Configuration
@ComponentScan
@EnableTransactionManagement
@EnableJpaRepositories
public class SpringConfiguration {
@Bean(name = "entityManagerFactory")
public LocalContainerEntityManagerFactoryBean emf(DataSource dataSource) {
    LocalContainerEntityManagerFactoryBean emf =new LocalContainerEntityManagerFactoryBean();
    emf.setDataSource(dataSource);
    Properties jpaProperties = new Properties();
    jpaProperties.put("hibernate.hbm2ddl.auto", "create-drop");
    jpaProperties.put("hibernate.show_sql", "true");
    emf.setJpaProperties(jpaProperties);
    emf.setPackagesToScan(
        new String[] {"ds.core.entity"});
    emf.setJpaVendorAdapter(
        new HibernateJpaVendorAdapter());
    return emf;
}
@Bean(name = "transactionManager")
public PlatformTransactionManager transactionManager(EntityManagerFactory emf,DataSource dataSource) {
    JpaTransactionManager tm =
        new JpaTransactionManager();
        tm.setEntityManagerFactory(emf);
        tm.setDataSource(dataSource);
    return tm;
}

And an entity class:
@Entity
public class Type {
@Id @GeneratedValue
private Long id;
private String name;
}

and Jpa implementation class :
@Repository
public class JpaTypeRepo implements TypeRepo {
@PersistenceContext
private EntityManager em;
@Override
public Type insertRecord(Type data) {
    em.persist(data);
    return data;
}
}

And finally a Service Class with Init():
@Transactional
@Service
public class InitDbService {
@Autowired
private TypeRepo typeRepo;
@PostConstruct
public void init() {
        Type type=new Type();
        type.setName("newName");
        typeRepo.insertRecord(type);
    }}

Answer: just add @Transactional annotation to the class :JpaTypeRepo
as following:
@Transactional
@Repository
public class JpaTypeRepo implements TypeRepo {
  @PersistenceContext
  private EntityManager em;
  @Override
  public Type insertRecord(Type data) {
    em.persist(data);
    return data;
  }
}


How to get a default zero double value in PHP?

Question: My question sounds simple, but the solution seems to be hard/tricky:
var_dump(0.0);

returns me
float 0

But why? Also the tries with doubleval or a double cast doesn´t solve the problem. I need this for setting a default value to a double table column in the database to zero through mysql pdo driver.
Comment: `0` is equivalent to `0.0` is equivalent to `000000.00000000`. They all represent the exact same value, there's no problem here. What do you *think* is the problem?
Comment: What?  That is float `0` but doesn't display the unnecessary `.0`  If your DB column is double then sending string, int or float 0 will result in the same value in the DB.  What is the actual problem that you are seeing?
Comment: Upvoter, care to explain?
Answer: As far as I know, doubles and floats are the same thing in PHP.
Have you tried inserting 0.0 into that table and gotten an error?


Make the previous line of the text shorter than the next

Question: Is there any way to make the previous line of the text always shorter than the next if the text's length is unknown?
Somethig like this:
Lorem ipsum dolor sit amet, consectetur adipiscing
et libero posuere pellentesque. Vivamus quis nulla justo.
vel lacinia sapien scelerisque eget. Vivamus ut velit elit. Donec

There is only a paragraph in HTML.
I have tried to do this with text-indent or :first-line or playing around with padding and width of a paragraph but none of them is working (as expected I think...).
Also have tried to somehow calculate the width of line using Calculating text width
but also with no result (I'm not very good in jquery...).
I can't add extra markup on the html (well, not directly, I can add it with scripts if necessary).
Preferably with css but I can add jquery too.
Please help.
Comment: You could add a `` tag with jQuery after a certain number of characters (count the characters, then after X number, insert the tag). Then simply add 10 (for example) characters to the counter for each iteration?
Comment: @robooneus That's a good idea, thanks. I will try to write this code.
Answer: Yes, you can just use the selector p and attribute it to the section of there sentence where you want this paragraph to end for and use line-height to adjust its leading for instance http://jsfiddle.net/AMmYR/4/
    p {
        font:14px nor Futura, sans-serif;
        line-height:20px;
        color:#333;
    }

This is my first sentence.

This is a very, very, very, long sentence

This sentence is longer than the last, I don't know why.

Comment: Then you will need to use the  selector within different parts of where you want to separate the paragraph. fiddle/code updated.