Android MVVM + Room creating LiveData RecyclerViewItem objects by other LiveData objects

Question: I have Room Entity Class "Symptom" with name of Symptom and id of it.
@Entity(tableName = "symptoms")
data class Symptom(
    @PrimaryKey @NonNull val id: Int,
    val name: String) {

    override fun toString(): String {
        return "Symptom $id: $name"
    }
}

I'm getting it in the following classses:
SymptomDao
@Dao
interface SymptomDao {

    @Query("SELECT * FROM symptoms WHERE id=:id LIMIT 1")
    fun getSymptom(id: Int): Symptom

    @Query("SELECT * FROM symptoms")
    fun getAllSymptoms(): LiveData<List<Symptom>>
}

SymptomRepository
class SymptomRepository(private val symptomDao: SymptomDao) {

    fun getSymptom(id: Int) = symptomDao.getSymptom(id)

    fun getAllSymptoms() = symptomDao.getAllSymptoms()
}

SymptomsViewModel
class SymptomsViewModel(symptomRepository: SymptomRepository): ViewModel() {

    private val symptomsList = symptomRepository.getAllSymptoms()
    private val symptomsItemsList: MutableLiveData<List<SymptomItem>> = MutableLiveData()

    fun getAllSymptoms(): LiveData<List<Symptom>> {
        return symptomsList
    }

    fun getAllSymptomsItems(): LiveData<List<SymptomItem>> {
        return symptomsItemsList
    }
}

I have RecyclerView with list of SymptomItem with Checkboxes to remember which Symptoms of a list users chooses:
data class SymptomItem(
    val symptom: Symptom,
    var checked: Boolean = false)

Question
My question is how can I get LiveData<List<SymptomItem>> by LiveData<List<Symptom>>? I have just started learning MVVM and I can't find a simply answer how to do that. I have already tried to fill this list in various ways, but It loses checked variable every time I rotate my phone. I'll be grateful for any hints.
Answer: You'll need to store which items are checked by storing their Ids in a List within the ViewModel. Then you'll have combine the list of your Symptom objects and the list of which items are checked, and generate the list of SymptomItem objects.
I'm going to use Kotlin Flow to achieve this.
@Dao
interface SymptomDao {

    @Query("SELECT * FROM symptoms")
    fun flowAllSymptoms(): Flow<List<Symptom>>
}

class SymptomRepository(private val symptomDao: SymptomDao) {

    fun flowAllSymptoms() = symptomDao.flowAllSymptoms()
}

class SymptomsViewModel(
    private val symptomRepository: SymptomRepository
) : ViewModel() {

    private val symptomsListFlow = symptomRepository.flowAllSymptoms()

    private val symptomsItemsList: MutableLiveData<List<SymptomItem>> = MutableLiveData()

    private var checkedIdsFlow = MutableStateFlow(emptyList<Int>())

    init {
        viewModelScope.launch {
            collectSymptomsItems()
        }
    }

    private suspend fun collectSymptomsItems() =
        flowSymptomsItems().collect { symptomsItems ->
            symptomsItemsList.postValue(symptomsItems)
        }

    private fun flowSymptomsItems() =
        symptomsListFlow
        .combine(checkedIdsFlow) { list, checkedIds ->
            list.map { SymptomItem(it, checkedIds.contains(it.id)) }
        }

    fun checkItem(id: Int) {
        (checkedIdsFlow.value as MutableList<Int>).add(id)
        checkedIdsFlow.value = checkedIdsFlow.value
    }

    fun uncheckItem(id: Int) {
        (checkedIdsFlow.value as MutableList<Int>).remove(id)
        checkedIdsFlow.value = checkedIdsFlow.value
    }

    fun getSymptomsItems(): LiveData<List<SymptomItem>> {
        return symptomsItemsList
    }
}

In your Fragment, observe getSymptomsItems() and update your adapter data.
The code is not tested, you may have to make small adjustments to make it compile.
Comment: You're injecting your ViewModel incorrectly in the Fragment, that is most likely the problem. Replace `SymptomsViewModel by inject()` with `SymptomsViewModel by viewModel()`. Requires a gradle dependency on `org.koin:koin-androidx-viewmodel`. Koin documentation: https://doc.insert-koin.io/#/koin-android/viewmodel
Comment: To solve your other problem with RecyclerView updating the whole list each time, you'll have to implement a `DiffUtil.ItemCallback` for your Adapter. This will let RecyclerView figure out what parts of a list have changed when a change in the data has occurred. https://codelabs.developers.google.com/codelabs/kotlin-android-training-diffutil-databinding/#0
Comment: In `onBindViewHolder()` you'll have to set the checked status of the checkbox to what you have stored in the `SymptomItem`. This is for when the screen is rotated, as the view will be destroyed, you need to manually get it to visually match the data.
Comment: It worked. Thank you very much for your help, you saved me :)
Comment: Thanks for advice. Unfortunately it still forgets which SymptomsItems are chosed (after phone rotation) and it updates RecyclerView every time I click checkbox so it loads the whole list every time I click item (I'm already showing checkbox animation so I don't want to refresh the whole RecyclerView).
Comment: Then the problem is in your Fragment and ViewHolder. You should add those to your question.
Comment: Here is SymptomViewModel:
https://github.com/whycody/CatsHealth/blob/master/app/src/main/java/com/whycody/catshealth/symptoms/SymptomsViewModel.kt

Here is SymptomsFragment:
https://github.com/whycody/CatsHealth/blob/master/app/src/main/java/com/whycody/catshealth/symptoms/SymptomsFragment.kt


Divide one column of data frame by condition from another column

Question: I have a data frame with 2 columns like this:
cond  val
1      5
2      18
2      18
2      18
3      30
3      30

I want to change values in val in this way:
   cond  val
    1      5   # 5 = 5/1  (only "1" in cond column)
    2      6   # 6 = 18/3 (there are three "2" in cond column)
    2      6
    2      6
    3      15  # 15 = 30/2
    3      15

How to achieve this?
Answer: A base R solution:
# method 1:
mydf$val <- ave(mydf$val, mydf$cond, FUN = function(x) x = x/length(x))
# method 2:
mydf <- transform(mydf, val = ave(val, cond, FUN = function(x) x = x/length(x)))

which gives:
  cond val
1    1   5
2    2   6
3    2   6
4    2   6
5    3  15
6    3  15

Answer: Here's the dplyr way:
library(dplyr)
df %>%
  group_by(cond) %>%
  mutate(val = val / n())

Which gives:
#Source: local data frame [6 x 2]
#Groups: cond [3]
#
#   cond   val
#  (int) (dbl)
#1     1     5
#2     2     6
#3     2     6
#4     2     6
#5     3    15
#6     3    15

The idea is to divide val by the number of observations in the current group (cond) using n()
Answer: This seems like an appropriate situation for data.table:
library(data.table)
(dt <- data.table(df)[,val := val / .N, by = cond][])
#    cond val
# 1:    1   5
# 2:    2   6
# 3:    2   6
# 4:    2   6
# 5:    3  15
# 6:    3  15

df <- read.table(
    text = "cond  val
    1      5
    2      18
    2      18
    2      18
    3      30
    3      30",
    header = TRUE,
    colClasses = "numeric"
)

Answer: In base R
df$result = df$val / ave(df$cond, df$cond, FUN = length)

The ave() divides up the cond column by its unique values and takes the length of each subvector, i.e., the denominator you ask for.
Comment: An alternative to `ave` could be `tabulate(df$cond)[df$cond]`
Answer: Here is a base R answer that will work if cond is an ID variable:
# get length of repeats
temp <- rle(df$cond)
temp <- data.frame(cond=temp$values, lengths=temp$lengths)

# merge onto data.frame
df <- merge(df, temp, by="cond")
df$valNew <- df$val / df$lengths


Drawing in screen with finger in UITableView

Question: I am following this excellent small tutorial about drawing on screen in the layer of a UIView (subclass).
http://spritebandits.wordpress.com/
It just works.
There is just one thing. I placed this view as subview of a UITableViewCell which, naturally, is displayed as part of a UITableView.
I guess I would have the same issue when I would place it within an UIScrollView. (UITableView inherits from UIScrollView anyway)
Touches are triggered by my painting view as long as their related movement is horizontal. As soon as I move the finger kinda vertical, even partly, then the UITableView takes over and scrolls the table.
Is there any proper way of stopping the Table to taike control of the touches while the touch is actually within my view?
If it is of importance: I am using storyboard. The cell is a prototype cell with its own subclass of UITableViewCell.
Answer: I've implemented this using the same class "Canvas" you're saying and also inside a UITableViewCell. But I didn't use the entire cell for drawing, only a UIView inside of the UITableView as a subview.
I reached the whole user experience by activating and deactivating the UITableView scrolling when that UIView (subview of the cell where I allow the drawing) fires touchesBegan or touchesEnded. So when they touch/move inside the UIView, they're drawing. When it's outside, they're scrolling. So they can't scroll on the UIView because they will be drawing.
The problem in your case is that since the whole cell is the view for drawing, the user cannot scroll in this concrete cell because it's the drawing one.
Hope this will help.
Comment: My Canvas subview is only part of that cell as well. There are other lables and buttons in the cell. There will be plenty of space on all sides of the Canvas view for the user to drag for scrolling the table. And I tried the same trick. I traced when touchesBegan is fired. It is fired only when the user moves sideways. I won't notice any movement with up-down-components. Did you use a trick to come around that?
Comment: Uhm.. one thing, if you tap on the Canvas and then move the finger up & down it's scrolling or drawing? (try it slowly, first the tap on the Canvas, and then the swipe up or down a bit)
Comment: I just tried it. In touchesBegan I first climb up the superview chain until I find a UITableView and set scrollEnabled to NO. The same in touchesEnded: with YES. So, when the user starts drawing vertically it works fine. The user can change the direction and continues drawing. And when the user starts drawing but waits a moment after touching before actually moving the finger, then it works fine too. But when the user starts horzontal or diagonal or so then the table scrolls.
Comment: Then I think this is because touchesBegan is not fired since the first gesture is not recognized as a tap, is directly a swipe. Maybe you could try to capture those gestures at the UITableView and send that actions to the Canvas methods. I've not tried that, but it's an idea.
Answer: I dont have an answer for that. But there is essentially a work around.
You could get the user in to a drawing mode, where the scrolling for a UItableviewcell is disabled and then
once the user is done with drawing, you could enable scrolling again.
Inclusion of a button anywhere on the screen would help you switch modes.
Comment: Thanks. Technically that could work. But is this a good user experience? Anyway. I could try to disable the scrolling while the user actually draws something. But that will not work when the user starts drawing in a vertical direction.


jQuery hover scale from bottom

Question: This is certainly going to be an easy one but I can't get my head around what I am doing wrong...
I am trying to do a hover effect on a UL that affects a link within one of the UL LI's.
My current code looks like this:
<code>$("ul.punchlines").hover(function () {
    $(this).find("li a.light-grey-gradient").animate({'width' : '60%','top':'-65px'});
});
$("ul.punchlines").mouseleave(function () {
    $(this).find("li a.light-grey-gradient").animate({'width' : '30%','top':'0px'});
});
</code>
This technically works as it gives the effect that the base of the element to be scaled remains in place and scales up from the bottom however it does it in two stages, I am trying to get this effect to happen all in one motion so it is a seamless scale and move.
I can do this easily with basic CSS3 transitions but as it is not supported in IE9 I am trying to use jQuery to allow for maximum browser support.
Can anyone offer a little support firstly about how I get the animation to happen in one motion (not staggered) and secondly if this is the right approach? I am new to jquery and only just getting my hands dirty with it  :-)
Comment: Have you tried positioning absolute the `light-grey-gradient` and setting `bottom` to `0` but positioning relative the parent container? If you could prepare a fiddle it would help a lot.
Answer: Please see JQuery hover api:
http://api.jquery.com/hover/
also make sure that your "li" have absolute position.
<code>$("ul.punchlines").hover(function () {
    $(this).find("li a.light-grey-gradient").animate({'width' : '60%','top':'-65px'});
}, function () {
    $(this).find("li a.light-grey-gradient").animate({'width' : '30%','top':'0px'});
});
</code>
Comment: Thank you for the much cleaner code, I got there thanks to this.

jQuery hover scale from bottom


How to put inline functions in the C++ source file?

Question: How can I force the inlining of a function, but define it in a C++ file ?
This is a question that's been asked in the past, for example here: Moving inline methods from a header file to a .cpp files
The answers there, in short, go as follows: "inline used to mean [remove function call overhead at the expense of .text size], now it means [relax ODR], so don't use inline for anything that's not ODR related, the compiler knows better".
I'm aware of that, however in my somewhat exotic case, I don't care about performance.
I'm programming an embedded device and, should someone break through the other layers of security, I want to make it as obnoxious as possible to reverse engineer this part of the code, and one thing this implies is that I don't want function calls (that aren't called numerous times anyway) to expose the function boundaries, which are natural delimitations of pieces of code that achieve something on their own.
However, I would also like to keep my code orderly and not have code in my header files.
I see that I can use __attribute((force_inline)) to force inlining, but then I get warnings if those functions don't have an inline attribute too: warning: always_inline function might not be inlinable [-Wattributes]
Suppressing the attributes warning is an option, but I'd rather only take it once I'm sure there are no clean way to do this.
Hence the question: how can I have a forcibly inlined function whose declaration is in a header, but definition is in a source file, without suppressing all attributes warnings ? Is that impossible ?
Comment: You can only inline a function whose source is defined. If the C++ compiler does not know what the actual function is, how can it inline it? And if the source of the function is put into a C++ file, how could the compiler know it when it's compiling a completely different C++ file? Can you explain how you expect this to work?
Comment: An inline function can be in a .cpp file, but it must be the same file that calls it.
Comment: @SamVarshavchik With link time optimizations
Comment: It sounds like you can put the definition into another header file
Comment: Which can only happen after everything is compiled, and it's too late for the compiler to reject anything. Like the actual function turning out to be recursive, making it non-inlinable.
Comment: You do have a point... The compiler doesn't exactly pass the linker a call graph... I didn't think this through. Anyway yeah I can just make multiple header files, good point. Thanks all for your replies.
Comment: @JulienBERNARD I was using LTO at one time, but I have to admit I don't know its limitations.  I gave up on it because of extended link times and humungous additional (discardable) build products.
Answer: Inlining can only be asked. Sometimes a bit forcefully. But you can never guarantee that the function WILL be inlined finally - because reasons, sometimes quite obscure ones.
Here what's MSVC documentation says (I've highlighted the important parts):

The compiler treats the inline expansion options and keywords as suggestions. There's no guarantee that functions will be inlined. You can't force the compiler to inline a particular function, even with the __forceinline keyword. When compiling with /clr, the compiler won't inline a function if there are security attributes applied to the function.

C++ standard says:

No matter how you designate a function as inline, it is a request that the compiler is allowed to ignore: the compiler might inline-expand some, all, or none of the places where you call a function designated as inline.

GCC documentation is a bit less crystal-clear about non-inlinable functions, but cases exists anyway.
The only "real" way to force inlining is quite ugly, since it rely on inlining it before compilation... Yeah, old-style preprocessor macros. The Evil Itself. Or by using a dirty hack with a #include replacing the function call (and inserting C++ code instead)... It may be a bit safer than a macro, regarding double evaluations, but other side-effects can be even worse since it must rely on "global" variables to work.
Does it worth the pain? Probably not. In particular for "obfuscation", because it won't be as "secure" as you think it will be. Yes, an explicit function call is easier to trace. But it won't change anything: reverse engineering don't rely on that to be done. In fact, obfuscation is near never a good (or even working...) solution. I used to think that... a long, very long time ago. I proved to myself that it was near useless. On my own "secured" code. Breaking the code took me much less time than it took me to "protect" it...


What is more appropriate model - Additive or Multiplicative

Question: I have a data set consisting of 3 variables - distance, day, factor.
day : day of the week
factor : before/after
My data has weekly seasonality, ie, if I aggregate distances, then weekends are greater than weekdays etc. From Sunday to Saturday, it would be an U shape.
I am interested in comparing before and after effect of an experiment. For that I am planning to do ANOVA.
My question is whether I should consider an additive model or an multiplicative model? How should I use the data to determine that?
Comment: You should state your real problem, in terms of that problem!  Without that you cannot expect a useful answer.
Answer: I assume you want to know the effect of the factor on distance, controlling for day of week.
Multiplicative Interpretation
If you think that the factor changes distances by a proportion i.e. increases/decreases by 25 percent rather than by 25 meters, then you'd probably want to set it up as a count data regression e.g. Poisson regression or one of it's overdispersed variants, which would be implicitly multiplicative i.e. multiplicative by virtue of having a log link function.  But that would be primarily your choice rather than the data's.
ANOVA?
A badly fitting ANOVA model would be a sign you might have jumped the wrong way on the function form (although it might be a sign of lots of other things too).  But in any case, ANOVA is a model that assumes with various levels of strictness, Normally and homoskedastically distributed cell values, so a priori it's an odd choice for zero bounded things like distance.
Learning an appropriate transformation
You could, I suppose, also 'learn' that a multiplicative transformation would fit the Normality constraints by using a Box-Cox transformation and discovering that its preferred parameter transformation is one that amounts to logging the data.  Interpretation will be a little bit harder, and you will have forced the data into the model rather than matching the model to the data.  But that would work, if you're wedded to using ANOVA.


Why table gets distracted in the following scenario?

Question: I am having a from in which table is there.
In table there are 3 columns.
I want to fadeIn and fadeOut the textbox in third column depending on enabling and disabling of checkbox.
When i enable the check box text box fadeIn is done but the table column width gets changed.
So how to overcome this issue.
http://jsfiddle.net/7gbNK/60/
Code is as follows:
<form action="" method="POST">

             <input name="chk_surname" id="chk_surname" type="checkbox" onclick="enable(this.id,'surname','td_surname')">
             Surname
             <input type="text" name="surname" id="surname" />

</form>

Javascript Code is as follows:

Screenshot:
Comment: Your table cell is `display: none`, therefore it's not rendered. Hide the content of the cell instead, not the cell itself.
Answer: FadeIn and FadeOut the input box instead of the td.
Try this:
HTML:
<form action="" method="POST">

             <input name="chk_surname" id="chk_surname" type="checkbox" onclick="enable(this.id,'surname','td_surname')">
             Surname
             <input style="display:none;" type="text" name="surname" id="surname" />

</form>

JS:
function enable(id,name,className)
{
        //Commented lines below are not required. These are present in your code
        //$(document).on('change','#'+id, function()
        //{
            var el = '#'+id;
            var checked = $(el).is(":checked");

            var index = $(el).parent().index();

            if(checked) {
                $('#'+name).fadeIn(100);
            }
            else {
                $('#'+name).fadeOut(100);
            }
        //});
    }

Demo: http://jsfiddle.net/W2wQF/
Reason why the original code is behaving that way is because when the third column is removed from display then the remaining two columns expand to fill its space. In the fixed code, third column is never removed (only its contents are removed/displayed).


Bottom OverFlowed

Question: import 'package:flutter/material.dart';
//import 'package:font_awesome_flutter/font_awesome_flutter.dart';
//import 'package:flutter/widgets.dart';
//import 'package:typicons_flutter/typicons_flutter.dart';

void main() async {
  runApp(MaterialApp(
    home: Home(),
    theme: new ThemeData(
      hintColor: Colors.white,
      primaryColor: Colors.black,
    ),
  ));
}

class Home extends StatefulWidget {
  Home({Key key}) : super(key: key);

  _HomeState createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
        title: Text(
          "Calcular Cerveja",
          style: TextStyle(color: Colors.white),
        ),
        backgroundColor: Colors.orange,
        centerTitle: true,
      ),
      body: Container(
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.stretch,
          children: <Widget>[
            Image.asset(
              'assets/ber2.png',
              width: 250.0,
              height: 250.0,
            ),
            Container(
              padding: EdgeInsets.all(15.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.stretch,
                children: <Widget>[
                  Divider(),
                  TextField(
                    decoration: InputDecoration(
                      hintText: "Teste",
                      labelText: "teste",
                      border: OutlineInputBorder(),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
}

Por que está dando bottom overflowed pessoal?
Answer: Está dando Bottom Overflowed ao clicar no TextField e abrir o teclado, certo?
Isso ocorre porque ao clicar no TextField a árvore de widgets é atualizada com o teclado aparecendo ao topo, com isso, o espaço que antes estava livre para renderizar o body do Scaffold foi alterado.
Para ilustrar, coloque o body dentro de um LayoutBuilder, esse builder é chamado sempre que as constraints (basicamente o tamanho disponível) do layout forem alteradas:
body: LayoutBuilder(
    builder:
        (BuildContext context, BoxConstraints constraints) {
      print('Height ${constraints.maxHeight}');
      print('Width ${constraints.maxWidth}');

      return Column(
        crossAxisAlignment: CrossAxisAlignment.stretch,
        children: <Widget>[
          Image.asset(
            'assets/Y.png',
            width: 250.0,
            height: 250.0,
          ),
          Container(
            padding: EdgeInsets.all(15.0),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.stretch,
              children: <Widget>[
                Divider(),
                TextField(
                  decoration: InputDecoration(
                    hintText: "Teste",
                    labelText: "teste",
                    border: OutlineInputBorder(),
                  ),
                ),
              ],
            ),
          ),
        ],
      );
    },
  )

Ao rodar você verá algo no log como:

I/flutter (18148): Height 560.0
I/flutter (18148): Width 360.0

E ao clicar no TextField:

I/flutter (18148): Height 278.0
I/flutter (18148): Width 360.0

Ou seja, a 'altura' disponível para renderizar o body foi alterada. Por conta disso, já não cabe mais o TextField na tela, ocorrendo um famoso erro de 'Overflowed'.
Para corrigir isso é simples, você precisa avisar o layout que ele deve se ajustar sem que ocorra erro, no seu caso, a solução mais simples é colocar o body dentro de um SingleChildScrollView, que irá se ajustar com um scroll para telas menores ou espaços menores.
body: SingleChildScrollView(
    child: Column(
      crossAxisAlignment: CrossAxisAlignment.stretch,
      children: <Widget>[
        Image.asset(
          'assets/Y.png',
          width: 250.0,
          height: 250.0,
        ),
        Container(
          padding: EdgeInsets.all(15.0),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.stretch,
            children: <Widget>[
              Divider(),
              TextField(
                decoration: InputDecoration(
                  hintText: "Teste",
                  labelText: "teste",
                  border: OutlineInputBorder(),
                ),
              ),
            ],
          ),
        ),
      ],
    ),
  ),

Bottom OverFlowed


How do I add dynamic content in the HTML part of my Elm file without getting a "Type mismatch error"?

Question: I have an Elm file with some HTML content in a function called view.
Part of the HTML content is dynamically generated via a map function that extracts data from a record.
Below is the code from that file.
module PhotoGroove exposing (main)
import Html exposing (div,h1,img,text)
import Html.Attributes exposing (..)

--model
initialModel : { photos : List { url : String }, selectedPhoto : String }
initialModel =
    { photos =
        [ { url = "1.jpeg" }
        , { url = "2.jpeg" }
        , { url = "3.jpeg" }
        ]
    , selectedPhoto = "1.jpeg"
    }

--view
urlPrefix : String
urlPrefix = "http://elm-in-action.com/"
viewThumbnail : String -> { a | url : String } -> Html.Html msg
viewThumbnail selectedPhoto thumb =
    if selectedPhoto == thumb.url
        then img [src (urlPrefix ++ thumb.url), class "selected"] []
        else img [src (urlPrefix ++ thumb.url)] []

view : List { a | url : String } -> Html.Html msg
view model =
    div [class "context"]
        [h1 [] [text "Photo Groove"]
        ,div [id "tumbnail"] (List.map viewThumbnail model) -- error message on "model"
        ]

--main
main = view initialModel -- error message on "initialModel"

However, I got error messages on the words "model" and "initialModel".
Below is the error message for "model":
TYPE MISMATCH - The 2nd argument to `div` is not what I expect:
29|         ,div [id "tumbnail"] (List.map viewThumbnail model)
                                  #^^^^^^^^^^^^^^^^^^^^^^^^^^^^#
This `map` call produces:
    List #({ a | url : String } -> Html.Html msg)#
But `div` needs the 2nd argument to be:
    List #(Html.Html msg)#
#Hint#: I always figure out the argument types from left to right. If an argument
is acceptable, I assume it is "correct" and move on. So the problem may actually
be in one of the previous arguments!

And for initialModel:
TYPE MISMATCH - The 1st argument to `view` is not what I expect:
35| main = view initialModel
                #^^^^^^^^^^^^#
This `initialModel` value is a:
    #{ photos : List { url : String }, selectedPhoto : String }#
But `view` needs the 1st argument to be:
    #List { a | url : String }#

I got that I need to somehow convert the objects directly into HTML msg types, but I don't know how.
I even tried to change the type for view, but that did not work either.
How do I fix this problem?
Answer: This is a great example of Elm's type system (or a good static type system in general) helping you figure out logical errors in your code.
The problems here are all due to your view function, and in particular with faulty assumptions it makes about what is in your model.
You are trying to map a function over the model argument, which assumes model is a list - but it isn't, it's a record containing both a list of all photos and a string identifying the selected photo. That makes logical sense as a model to use in this situation, so rather than changing the model type (which would otherwise be a sensible option) I would suggest changing view so that it works with your actual model type.
Another problem, which is highlighted in the first of the 2 error messages you quote, is that viewThumbnail can't be mapped over a list of photos anyway because it actually takes 2 arguments, the first of which isn't a list. You do want to use this function to produce the list of images in view's output - but you also need to provide it with the selectedPhoto, which of course comes from the other field in your model that you've ignored so far.
So the only changes needed to your original code to get this to compile are:

change the type signature of view to actually match your model's type. (This is what the second of the two error messages is about). It should be view : { photos : List { url : String }, selectedPhoto : String } -> Html.Html msg (You probably want to make a type alias for this model type, at least if you expand this app to any much greater size.)

inside the function body,

change this
List.map viewThumbnail model

to
List.map (\photo -> viewThumbnail model.selectedPhoto photo) model.photos

Hopefully you can see what the above is doing - the \ is for an anonymous function, that takes one of the photos and calls viewThumbnail with that as second argument and model.selectedPhoto always as the first argument.
And note finally that you can simplify the above by taking advantage of Elm's built-in function currying, to just
List.map (viewThumbnail model.selectedPhoto) model.photos

which I and probably most others familiar with functional programming find much cleaner and easy to read.


ERROR 1452: Cannot add or update a child row for A3ENROLL

Question: I have created the following tables:
A3STUDENT
CREATE TABLE A3STUNDENT(
STD_ID INTEGER NOT NULL,
STD_NAME VARCHAR(30),
STD_MAJOR CHAR(4),
STD_RANK CHAR(2),
CONSTRAINT PK_A3STUDENT PRIMARY KEY (STD_ID)
);

CREATE TABLE A3COURSE(
CRS_TIME VARCHAR(10),
CRS_ROOM CHAR(5),
CRS_ID CHAR(7) NOT NULL,
CONSTRAINT PK_A3COURSE PRIMARY KEY (CRS_ID)
);

CREATE TABLE A3ENROLL(
ENR_GRADE CHAR(1),
STD_ID INTEGER NOT NULL,
CRS_ID CHAR(7) NOT NULL,
CONSTRAINT PK_A3ENROLL PRIMARY KEY (STD_ID, CRS_ID),
CONSTRAINT FK_STD_ENR FOREIGN KEY (STD_ID) REFERENCES A3STUDENT(STD_ID),
CONSTRAINT FK_CRS_ENR FOREIGN KEY (CRS_ID) REFERENCES A3COURSE(CRS_ID)
);

When I go to insert values such as this:
INSERT INTO  A3ENROLL VALUES ('A', 100, 'MGMT445');

I receive this error:

#1452 - Cannot add or update a child row: a foreign key constraint fails (Hess.A3ENROLL, CONSTRAINT FK_CRS_ENR FOREIGN KEY
  (CRS_ID) REFERENCES A3COURSE (CRS_ID))

I have can't seem to understand why my data won't insert.  What am I overlooking?
Answer: This usually happens because have not data in the A3STUNDENT andA3COURSE tables.
The foreign key relationships means that a primary table that contains the central data values and a child table with identical values pointing to the parent, any INSERT or UPDATE operation that attempts to create a foreign key value in a child table is rejected if there is no matching candidate key value in the parent table.
The table A3ENROLL is taking as reference100 and MGMT445 that does not exist in the tables mentioned above.
Before inserting data in the A3ENROLL table, you must be sure that there are data in the other tables A3STUNDENT and A3COURSE, because the tableA3ENROLL has a foreign key of A3STUNDENT andA3COURSE, this means that you must have these data in those tables, for example:
Select * from A3STUNDENT;

STD_ID | STD_NAME | STD_MAJOR | STD_RANK
100    | 'Zack'   | ...       | ....

Select * from A3COURSE;

CRS_ID  | CRS_ROOM | CRS_TIME
MGMT445 | ...      | ....

You can try to insert data in the previous tables and then insert in the table A3ENROLL.
Here you have more info: https://dev.mysql.com/doc/refman/5.6/en/create-table-foreign-keys.html


Object cannot be cast from DBNull to other types

Question: Estou tendo um problema no return "Object cannot be cast from DBNull to other types", como proceder?
<code>        Public Function RetornaValorTotalPremiacao(ByVal strCodigoProposta As String) As Decimal
        Try
            Dim objApoioConexao As New ApoioConexao

            objApoioConexao.AdicionaParametro(strCodigoProposta, "@CD_PROP")

            Return Convert.ToDecimal(objDMConexao.ExecutaComando(My.Settings.ConexaoAtiva, "[dbo].[usp_sel_valor_total_premiacao]", CommandType.StoredProcedure, objApoioConexao.RetornaArrayParametros))

        Catch ex As Exception
            Throw
        End Try
    End Function
</code>
Answer: Dentro do código
<code>bjDMConexao.ExecutaComando(My.Settings.ConexaoAtiva, "[dbo].[usp_sel_valor_total_premiacao]", CommandType.StoredProcedure, objApoioConexao.RetornaArrayParametros)
</code>
O valor retornado é DBNull, e você está tentando dar um cast para Decimal, faça  uma verificação antes de tentar dar um cast para decimal.
Comment: Resolvido ISNULL(SUM(PRO.VALOR_CUSTA),0)!
Comment: Coloca como resposta para ajudar os próximos humanos com o mesmo problema.


After updating to user_restrictions-7.x-1.0 in drupal7, I can no longer run cron from another host

Question: I've been updating several drupal7 installations from one browser on the same host as ONE of them.  I just did this, updating to user_restrictions-7.x-1.0 on both machines.  This caused no problems on the host where my browser was running, but on the other host drupal will no longer run cron manually at my request, and clicking on the "To run cron from outside the site, go to http:///drupal/cron.php?cron_key=..." link yields an "Access Denied" message.
Under the circumstances, I must conclude that something significant has changed in user_restrictions-7.x-1.0 that enforces some exclusion on the basis of IP address that didn't exist before or was not previously being enforced.
How do I grant my other host permission to use the cron_key in question?
Answer: The User restrictions module just restricts which users can log in basing on their username and email address; if the username or the email address matches a regular expression set in the module settings, the user is not allowed to log in. At the same time, the module doesn't allow users to change their usernames or email addresses to values that match those regular expressions.
The modules doesn't restrict user access basing on their IP, since that functionality is still present in Drupal 7 core, although Drupal core just allows you to set an IP address, not a range of IPs to ban.
If you are experiencing what you reported, then it could a module bug. Report it in the project queue, once you verified there isn't a issue already opened for that, and that the module is really the responsible for that behavior.
Disclaimer
I am the maintainer of the module, although I didn't change the module code recently. I don't plan to develop any Drupal 7 module, since I am focusing on Drupal 8 development.


dhcp-server + iptables: Can't share ppp internet connection

Question: I had this configuration before, and it used to work well, but now I got a new server and I can't setup it to share the internet connection from ppp0. I'm on Debian testing.
The client connects directly on eth0 through a dhcp server, and it can get an IP just fine. The problem seems only to appear when I set this rule:
iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
Just after that, the client won't be able to receive an IP from the server anymore. Here's the configuration files:
Interfaces configuration:
iface eth0 inet static
    address 192.168.0.1
    netmask 255.255.255.0

The /etc/dhcp/dhcpd.conf file:
ddns-update-style none;
default-lease-time 600;
max-lease-time 7200;
log-facility local7;
subnet 192.168.0.0 netmask 255.255.255.0 {
   option routers 192.168.0.1;
   option domain-name "onix";
   range 192.168.0.2 192.168.0.10;
   option domain-name-servers 18.104.22.168, 18.104.22.168;
   option ip-forwarding on;
}

The connection script:
#!/bin/bash

ifdown eth0
ifup eth0
/etc/init.d/isc-dhcp-server stop
/etc/init.d/isc-dhcp-server start

iptables -F
iptables -t nat -F
iptables -t mangle -F
iptables -X

iptables -A INPUT -i lo -j ACCEPT
iptables -A INPUT -m state --state ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i ppp0 -o eth0 -m state --state
ESTABLISHED,RELATED -j ACCEPT
iptables -A FORWARD -i eth0 -o ppp0 -j ACCEPT
iptables -t nat -A POSTROUTING -o ppp0 -j MASQUERADE
iptables -A FORWARD -i ppp0 -o ppp0 -j REJECT

echo 1 > /proc/sys/net/ipv4/ip_forward

Edit: After the problem appears, these are the client's syslog:
Aug 21 04:52:13 amendoa dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
Aug 21 04:52:20 amendoa dhclient: DHCPREQUEST on eth0 to 255.255.255.255 port 67
Aug 21 04:52:41 amendoa dhclient: DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 3
Aug 21 04:52:44 amendoa dhclient: DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 7
Aug 21 04:52:51 amendoa dhclient: DHCPDISCOVER on eth0 to 255.255.255.255 port 67 interval 13

And the server's one:
Aug 21 04:52:13 onix dhcpd: DHCPREQUEST for 192.168.0.2 from 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:13 onix dhcpd: DHCPACK on 192.168.0.2 to 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:20 onix dhcpd: DHCPREQUEST for 192.168.0.2 from 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:20 onix dhcpd: DHCPACK on 192.168.0.2 to 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:41 onix dhcpd: DHCPDISCOVER from 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:41 onix dhcpd: DHCPOFFER on 192.168.0.2 to 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:44 onix dhcpd: DHCPDISCOVER from 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:44 onix dhcpd: DHCPOFFER on 192.168.0.2 to 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:51 onix dhcpd: DHCPDISCOVER from 00:16:36:96:2b:15 (amendoa) via eth0
Aug 21 04:52:51 onix dhcpd: DHCPOFFER on 192.168.0.2 to 00:16:36:96:2b:15 (amendoa) via eth0

Client tcpdump:
listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
17:32:10.848029 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:16.000175 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:30.004579 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:37.005508 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:49.007886 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:56.000168 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300

Server tcpdump:
listening on eth0, link-type EN10MB (Ethernet), capture size 65535 bytes
17:32:10.533386 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:10.536878 ARP, Request who-has 192.168.0.2 tell onix.local, length 28
17:32:11.000641 IP onix.local.bootps > 192.168.0.2.bootpc: BOOTP/DHCP, Reply, length 300
17:32:11.535919 ARP, Request who-has 192.168.0.2 tell onix.local, length 28
17:32:12.535882 ARP, Request who-has 192.168.0.2 tell onix.local, length 28
17:32:15.685847 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:15.686038 IP onix.local.bootps > 192.168.0.2.bootpc: BOOTP/DHCP, Reply, length 300
17:32:36.692468 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:36.692678 IP onix.local.bootps > 192.168.0.2.bootpc: BOOTP/DHCP, Reply, length 300
17:32:48.695611 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:48.695863 IP onix.local.bootps > 192.168.0.2.bootpc: BOOTP/DHCP, Reply, length 300
17:32:55.688296 IP 0.0.0.0.bootpc > 255.255.255.255.bootps: BOOTP/DHCP, Request from 00:16:36:96:2b:15 (oui Unknown), length 300
17:32:55.688546 IP onix.local.bootps > 192.168.0.2.bootpc: BOOTP/DHCP, Reply, length 300

Comment: As I said, this configuration "was working before". The new server I'm working has the following ethernet card: 13:00.0 Ethernet controller: Atheros Communications AR8152 v2.0 Fast Ethernet (rev c1) After testing things again and again experiencing this odd network behavior, I didn't realize that my kernel version was really old: 2.6.32. This kernel version has a [Debian bug](http://bugs.debian.org/cgi-bin/bugreport.cgi?bug=610474) that describes exactly what was happening. All I had to do was upgrade to 3.0.0, that has a fixed driver for AR8152. Everything works fine now. I'm really sorry for
Answer: I'll bet that this line:
/sbin/ifconfig eth0 192.168.0.1 netmask 255.255.255.0 broadcast 192.168.0.1

isn't doing you any favours (I seriously doubt that's actually your broadcast address, and we stopped having to specify them manually years ago -- for that matter, why are you even manually scripting your interface configuration?).
I seriously doubt that the MASQUERADE rule you identify as being the problem is actually the source of the issue -- it shouldn't have any effect on the DHCP server's desire to serve addresses (although a misconfigured PPP connection could cause issues, it should cause those issues regardless of whether you're masquerading).
Without knowing what the DHCP server is actually doing with the packets it receives, it's hard to diagnose what's actually going on.  Relevant syslog entries will be enlightening; at worst, an strace of the DHCP server will show whether the packets are getting to the DHCP server and (roughly) what it's doing with the responses.
Comment: Replaced the tcpdump thing with the syslog entries. Also, using the interfaces file for setting eth0 configuration gives me the same results. Thanks for the help.
Comment: Removing the broadcast entry from the dhcpd.conf and interfaces file also gives me the same results.


How do I show related content?

Question: Using Drupal 7 and Views 3 I am trying to setup a block to show related content based on taxonomy terms.I have read numerous articles and threads on how to do this but none seem to work, this might be due to using a view and custom path rather than displaying the node directly.I have done the following.

Created nodes and added Taxonomy terms to each.
Created a view for each node, the views have a custom path.
Created a block view, added contextual filter on "Has Taxonomy Term ID". I have set default value "Taxonomy term ID from URL" and clicked the LOad Default from node page checkbox.
Added the block to sidebar.

My URL are of the format www/example.com/name , there is only 1 argument, I am struggling to understand how the filter can pick up the term from that URL and would like to know if there is a simple way around this. The problem seems to either lie with my URL or that I'm displaying the  node through a view, I would have thought these were both common scenarios that wouldnt require any coding, any help on how to workaround this would be much appreciated. I am leaning towards using mini panels but having spent some hours with them would rather just use views if possible.
Thanks
EDIT
I think this is very likely view/path related, going to the content page directly displays the block with the related content, its on the View pages with their own paths this is not working. My views are simply Page views with normal filters on the content type and on a taxonomy term (which is different to the term on the contextual filter).
Answer: Creating a related content view in Drupal 7:
Show related content based on shared Term-pages (from any given vocabularies).
Each term page will be recognized by the term ID (TID) hidden in the pages' URL.
The process:
Basic stages:

Create a "Content" view-block.
Add a contextual filter: "Has taxonomy term ID".
Choose "provide a fixed value".
(From type): "Taxonomy term ID from URL".

Checking:
•   Uncheck "Load default filter from the term page".
•   Check "Load default filter from node page, that's good for related taxonomy blocks".
•   Check "Limit terms by a vocabulary".
•   Check your desired vocabulary.

Select "Filter to items that share any term".
Go down and check "Reduce duplicates": This will several terms that relate to the same page – To appear. Only one will of them will.

https://www.daymuse.com/blogs/drupal-guide-related-content-term-views
Optional:
If you would like that the current node won't appear in the list:

Go to the view and add another, extra Contexutal filter.
Give it content: NID.
Select "Provide default value".
Set the "Type" to "Content ID from URL".
Go down in that window, click on "More", and there check "Exclude".

Note that this will exclude the current node in which the related is shown – From that very list.
It will do so by using the content ID which is a (hidden) part of the URL.
Comment: Benia, this is pretty much what I have been doing. In Step 2 you mean add the contextual filter to the Block display? In my case this is a separate view, or should this be a separate display that is part of the same view?
Comment: Yes, it belongs to the view-block. I did all in one single view --- A view-block.
Answer: I guess the problem was using a view with a custom url with a contextual filter to display a block that gets its data from another view with a custom URL, this doesn't appear to be possible without custom code. In the end I used the panelizer module to display my node, added a sidebar in panelizer and added the content as block, on the block I was able to use the method described by Benia to add the contextual filter.
Answer: Why don't you try Views Related Content Module. Install this module and follow:

Create a View block with content type
Add "Related Content: Term" as Content Filter Criteria
Select the vocabulary you want to short by
Save the view and place the view block from drupal block administration page

That's it.
There's a step by step tutorial available on drupal forum.

How do I show related content?


Notation: operations with one-hot matrices

Question: I have a matrix formed by one-hot encoding, e.g.
$$X = \begin{pmatrix} 1 & 0 \\ 1 & 0 \\ 0 & 1 \end{pmatrix} $$
I can use it to "expand" diagonal matrices
$$ D= \begin{pmatrix} a & 0 \\ 0 & b \end{pmatrix} \mapsto \begin{pmatrix} a & 0 & 0 \\ 0 & a & 0 \\ 0 & 0 & b \end{pmatrix} = D_{\exp} $$
What's the best way to denote this operation for the purposes of deriving identities with it?
So far all I have is
$$ X D = D_{\exp} X $$
Comment: Would be good if you would be able to provide a more general principle of what you expect. IMHO, a single example may not represent what you have in mind. Up to now, we're forced to only guess what you expect.
Answer: IMO, you have $X \in \{0, 1\}^{n \times c}$, where $n$ is the number of items and $c$ is the number of classes, $D \in \mathcal{R}^{c \times c}$ that is a diagonal matrix representing the classes.
Specifically, $X_{ij} = 1$ iff item-$i$ is in class $j$, and $D_{jj}$ is the "symbol" of class-$j$.
Therefore, $XD$ has the same size as $X$ and the positions of non-zero entries are the same as in $X$, where each non-zero $XD_{ij} = D_{jj}$.
You want to expand $D$ to $D_{exp} \in \mathcal{R}^{n \times n}$ that is a diagonal matrix too.
If I understand it correctly, the diagonal of $D_{exp}$ should just be the array of the classes of the $n$ items.
Specifically, for each $i$, ${D_{exp}}_{ii} = D_{jj}$ such that $X_{ij} = 1$.


Bash list comprehension or map

Question: Say I have a string in bash -
NAMES="file1 file2 file3"

How do I map it to the following string which I will then use as part of a command?
MAPPED="-i file1.txt -i file2.txt -i file3.txt"

For an example of exactly what I mean, here's the equivalent python code -
names = "file1 file2 file3"
mapped = ' '.join("-i " + x + ".txt" for x in names.split())

Answer: You should use arrays instead of strings:
names=(file1 file2 file3)

# Add suffix
names=("${names[@]/%/.txt}")

# Build new array with "-i" elements
for name in "${names[@]}"; do
    mapped+=(-i "$name")
done

# Show result
declare -p mapped

resulting in this output:
declare -a mapped=([0]="-i" [1]="file1.txt" [2]="-i" [3]="file2.txt" [4]="-i" [5]="file3.txt")

This can now be used in commands like this:
cmd "${mapped[@]}"

See BashFAQ/050 regarding the rationale behind putting commands into strings vs. arrays.
Comment: I don't write `'ls' '-l'` because I know `ls` and `-l` are safe to leave unquoted. Same thing here with `-i` and `file1`/`file2`/`file3`. That's what I was getting at.
Comment: @johnkugelmann They can be written unquoted, but only because they don't contain special characters – the general safe way is to quote them. No religiously strong opinion, though.

Bash list comprehension or map


University-level books focusing on intuition?

Question: I help some students with difficulties in Mathematics and Physics (especially math, physics, and engineering majors).
While in high school they usually don't study, or are not interested, etc., in university they seem to lack intuition, or simply they are taught to smother their own intuition with formalities they don't really understand.
I can occasionally come up with intuitive ideas, examples, pictures. Sometimes they come up with their own ideas, and ask me to check "if they got right what is behind". But this does not happen often, because they (and me) don't have much time to waste (or invest) in such "games".
A full book which focuses on the intuitive aspects, in addition to their own official text, sometimes is exactly what we need. I am particularly fond of the book "Visual Complex Analysis" by T. Needham, for example.
Are there any other books you know which focus on intuition, visualization, and understanding, rather than rigor and formalism?
Topics that would "call" for such a treatment are, in me and my students' opinion:

Differential forms and de Rham cohomology
Linear Algebra
Differential Geometry of Curves and Surfaces
Riemannian Geometry
Lie groups and Lie algebras (maybe with a focus on their applications to Mechanics, for physicists and engineers)
Relativity (special and general)
Probability and random processes.

Other topics are very welcome, too! (Also more advanced, if they exist.)
We could rephrase the question as: What are the introductory books you wish you had known before?
Thanks.
Comment: A Primer of Infinitesimal Analysis, J L Bell
Comment: I think Gilbert Strang's books have great intuition.  For example,  Linear Algebra and its Applications, and also his book Introduction to Applied Mathematics.
Comment: I think there is a way to give an intuition for the truth which is at first unintuitive. When I was 21, I discovered that the axiom of choice wasn't provable. I got a feel for how it's possible for the axiom of choice to be false. I was fascinated by it. I'm planning to make a ripoff of the Coraline movie for giving an intuition for the negation of the axiom of choice. In that movie, a hypercomputing robot computes that the axiom of choice for real numbers is false. I'm planning to come up with a long detailed explanation for the possible negation of the axiom of choice explaining so much of
Comment: what's going on. One thing good about the movie is the viewers aren't forced to agree and say what goes against their intuition so they don't feel pressure. Then they will naturally develop some connections for sort of seeing what the movie is saying and it's not necessary to supress the connections for the feel for the axiom of choice to near nothingness in order develop connections for the negation. Still, that doesn't disprove the axiom of choice and only explains why it's possible that the axiom of choice isn't true.
Answer: For Differential Geometry a combination of Elements of Differential Geometry by Millmann and Parker and Elementary Differential Geometry by Andrew Pressley is very good for developing geometric intuition. Similarly for Riemannian Geometry DoCarmo's book on Riemannian Geometry is very good (one need to do a lot of exercises to extract concepts). For Abstract Algebra $Topics\ in \ Algebra$ by Herstein is the best (though good for a second reading). For topology, apart from standard Munkres' Topology I liked $Topology$ by Klaus Janich.
Answer: I personally think Doug West's Graph Theory text is a great introduction to the subject. Godsil and Royle's Algebraic Graph Theory is a nice text as well, I think. It's quite an easy read for undergraduates with some linear and abstract algebra, as well as a bit of graph theory. I personally like Dummit and Foote for Abstract Algebra, but it's a bit sophisticated. Durbin is perhaps an easier read for those who are having some trouble.
Regarding linear algebra, I find graph theory and combinatorics to be an excellent precursor to explaining the concepts. Linear independence is analogous to acyclicity in a graph, if you consider Matroids. This makes it easy to visualize bases as spanning trees, which I think are less abstract. When talking about linear transformations, I find combinatorial intuition quite helpful. When seeing isomorphisms, teaching students to "see" the bijection can be helpful. It's also useful to use combinatorial insights for non-bijective transformations, such as $T: \mathcal{P}_{3}(\mathbb{R}) \to \mathcal{P}_{2}(\mathbb{R})$ by $T(v) = \frac{dv}{dx}$. When seeing the difference in dimension, it is easier to visualize combinatorially why such a transformation can be at most onto, but never one-to-one. Sorry if this is a bit off-topic, but I figured I'd share!
Answer: The following might be helpful:
All the Mathematics You Missed: But Need to Know for Graduate School by Thomas A. Garrity and Lori Pedersen
Lectures in Mathematical Physics Vol. 1 and Vol. 2 by Robert Hermann (and other books by him)
However, I can't help but wonder about someone studying things like differential forms and de Rham cohomology who "didn't bother with mathematics in high school". I'd almost say that such people don't exist, except I've encountered a few. But only a very few. Almost always, in my experience, anyone that makes it to mid-level graduate mathematics was either a standout in mathematics throughout high school (unless they attended a very elite and/or special admissisons high school) or they had sufficient interest in mathematics to overcome a lack of top-level ability.
Comment: Thanks for the answer. I have been a little unclear. With "while in high school..." I didn't mean *the same students* that I help in university. The people I help with differential forms, as you said, were quite good in high school, enough to choose such a major.
Comment: @geodude: I encourage you to look at the Robert Hermann books, both those I cited (which I actually own copies of) and some of his (very) many other books. I personally don't like his style, but the books are intended for those outside of mathematics who want to learn about certain aspects of differential geometry. Most university libraries (in the U.S., at least) have many of his books. As for the Garrity/Pedersen book, that's sufficiently recent and well known that you can easily google up information about it.
Answer: I'm too an student that you have mentioned who lacked intuition for mathematics in school and came aware after I reached college that the maths I learned was maths to pass an exam but not more than that.So I'm ready to help you as I can.
I'm also in a run to get into the intuitive world of Mathematics but don't know when will I complete the race.
Here are the books and links that I would suggest to get an intuition about Mathematics:

Christopher Cooper's Mathematics Notes by Christopher Cooper
Notes from Trigonometry by Steven Butler
Calculus made easy by Silvanus P. Thomspon
Statistics Online Learning by Penn State
Linear Algebra by Joshua
Cool Math(where you might get intuition about algebra and lines-within the section of algebra,which gives you line + algebra = linear algebra)
Last but not the least Math is Fun maintained by Rod Pierce(don't know much more) where you get intuition about basic mathematics.

Not to mention you could mail me if you want the offline versions of (4) and (7).Also don't worry about Copyright issues because all are free.


How to load block on link click with AJAX framework?

Question: I have tried in my custom module:
Declaring a path for Ajax callback
function custom_menu() {

  $items['ajax-block/%'] = array(
    'title' => 'Ajax test callback',
    'type' => MENU_CALLBACK,
    'page callback' => 'ajax_link_callback',
    'page arguments' => array(1),
    'delivery callback' => 'ajax_deliver',
    'access arguments' => array('access content'),
  );

  return $items;
}

now the callback itself
/**
 * Callback ajax
 */
function ajax_link_callback($from_cid, $mode = NULL) {

  if ($mode != 'ajax') {
    drupal_set_message('Turn Javascript');
    drupal_goto(isset($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '<front>');
  }

  $commands[] = ajax_command_html('.region-content', some_func());

  return array('#type' => 'ajax', '#commands' => $commands);
}

I have a few manually created links:
link1
link2
link3

Now I need such functionality - when I press link1 - block1 loads content in to .region-content, when I click link2 - block2 and etc.
How can I do this?
Answer: Looks like your missing the ajax_deliver command
$commands[] = ajax_command_html('.region-content', some_func());
$page = array('#type' => 'ajax', '#commands' => $commands);
ajax_deliver($page);

Comment: The call to `ajax_deliver()` is not necessary, since that is set as delivery callback; this means Drupal will call it automatically, before returning the page to the browser.
Comment: How can i show different content on different links?
Comment: You will need to create functions to return HTML loading a block or whatever, it would replace with some_func()


ChartJS - Draw chart with label by month, data by day

Question: I'd like to draw a line chart by Chartjs with data by day, but label by month.
If label is displayed by day, then there are a lot of points. So, I'd like to display label by month instead of by day. For example:

Someone could teach me how to do that?
Thank you.
Comment: https://jsfiddle.net/WebJedi/bfu2bp1a/
Answer: Just config your xAxes->time property as:
unit: 'month'
xAxes: [{
  type: 'time',
  position: 'bottom',
  time: {
    displayFormats: {'day': 'MM/YY'},
    tooltipFormat: 'DD/MM/YY',
    unit: 'month',
   }
}],

Answer: The labels array and the data array have to match.
Therefore what you will need to do is calculate your values to be hold in data array in to match your labels
data: {
    labels: ["Jan", "Feb", "March", ...],
    datasets: [{
        label: '# of Votes',
        data: [01, 02, 03, ...],
        backgroundColor: [
            'rgba(255, 99, 132, 0.2)',
            'rgba(54, 162, 235, 0.2)',
            ...
        ],
        borderColor: [
            'rgba(255,99,132,1)',
            'rgba(54, 162, 235, 1)',
            'rgba(255, 206, 86, 1)',
            ...
        ],
        borderWidth: 1
    }]
},

Does that solve your doubt?
Answer: This question is quite old now, but I have found a workaround using the afterTickToLabelConversion functionnality. I formatted the date, and left only one label for every month (the rest of the labels are transformed to empty quotes).
Here is the snippet to put in your graph option :
scales: {
        xAxes: [{
            type: 'time',
            position: 'bottom',
            time: {
                displayFormats: {
                    'day': 'MM/YY'
                },
                tooltipFormat: 'DD/MM/YY',
                unit: 'day',
            },
            // leave only one label per month
            afterTickToLabelConversion: function (data) {
                var xLabels = data.ticks;
                var oldLabel = "";
                xLabels.forEach(function (labels, i) {
                    if(xLabels[i] == oldLabel){
                        xLabels[i] = "";
                    } else {
                        oldLabel = xLabels[i];
                    }
                });
            }
        }]
    }


mod_wsgi daemon mode not working in Apache

Question: I have problems getting mod_wsgi to run in daemon mode on my Debian / Apache 2.2.16 / Python 2.6.6 / mod_wsgi 3.3 / Django 1.3 setup. Everything works OK in embedded mode, but when I try to switch to daemon mode like described in so many HOWTO's, it is simply not activated (environ['mod_wsgi.process_group'] always returns the empty string, but no errors are output).
Furthermore, setting the python path with neither the WSGIPythonPath directive nor the python-path option for WSGIDaemonProcess seems to work - outputting sys.path in the wsgi script always returns the original system python path.
I read up on configuring and debugging mod_wsgi, but I just seem stuck here so any help would be appreciated!
In my virtual host config file I have
<VirtualHost *:80>

  ServerName mysite.com

  WSGIDaemonProcess mysite.com processes=2 threads=15
  WSGIProcessGroup mysite.com

  WSGIScriptAlias / /path/to/mysite/wsgi/django.wsgi

  <Directory /path/to/mysite/wsgi/>
    Order deny,allow
    Allow from all
  </Directory>

</VirtualHost>

set up. To test activation of daemon mode, I use this wsgi script:
import sys
import os

os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings')

def application(environ, start_response):
    print >> sys.stderr, 'mod_wsgi.process_group = %s' % repr(environ['mod_wsgi.process_group'])

    from django.core.handlers.wsgi import WSGIHandler
    _application = WSGIHandler()

    return _application(environ, start_response)

and the resulting log file always says:
mod_wsgi.process_group = ''

which, accroding to the documentation, indicates that daemon mode is not being used. I checked my setup multiple times, the versions of Apache, mod_wsgi and Python are matching and my setup is correct according to all the HOWTO's I've read out there. What could I be missing?
Answer: It turned out that a symlink wasn't set correctly so my config changes never loaded in Apache. Sorry for wasting your time, I thought I checked everything thoroughly before posting.


Javascript - Page slow to show after not being the active tab

Question: So I have developed a webpage containing some javascript and a couple of HighChart charts.
The page generally works great, every few seconds data is fetched from the server using an ajax request, and the chart is updated.
The issue happens when I have switched to a different tab for a few minutes and then want to go back. The page can take a very long time to show up. This happens on both Chrome and Firefox.
I couldn't really find out how the browser is handling javascript and page updates in non-active tabs, but it seems to be related at least.
Any ideas on how to improve the time it takes for the page to show?
To be perfectly clear, the page has no visible performance issues while it is the active tab.
Comment: Take a look at these issues from highcharts Github: https://github.com/highcharts/highcharts/issues/9749, https://github.com/highcharts/highcharts/issues/9074.
Comment: It seems like 9749 is relevant, but this issue happens in firefox as well, and the comments on 9749 say it doesn't happen on browsers other then chrome.
Comment: Could you try to overwrite `Highcharts.SVGElement.animate` and remove the added piece of code from this commit: https://github.com/highcharts/highcharts/commit/25506e537597352ed5a2fa5cd69ef029c3d1c60e? If it doesn't help you could you reproduce this issue in online code editor like jsfiddle?
Comment: This piece of code is not present in my highcharts code. Could that be the issue? this piece of code seems to handle the exact case I am referring to...
Anyway, I will try to create a jsfiddle for that.
Comment: Oh, I see. Yes, it can be the issue. Could you try to add it to your code and check if it solves it?
Answer: So it turns out we froze highcharts just a couple of versions before this fix went in.
When we upgraded the version, everything worked great!
Many thanks to @WojciechChmiel for pointing me in the right direction.


How to derive the asymptotic distribution of t-statistic?

Question: Let ${X_n}$ be an IID sample such that ${X_i} \sim N(\mu,\sigma^2)$. When both $\mu$ and $\sigma$ are unknown, we construct $t(\hat{\mu},s)=\dfrac{\sqrt{n}(\hat{\mu}-\mu)}{s}$, where $s$ is the sample standard deviation.
The statistic $t(\hat{\mu},s)$ follows t-distribution exactly. I wish to know the asymptotic distribution of $t(\hat{\mu},s)$.
I understand that by Continuous Mapping theorem under certain conditions, if $\hat{\mu} \xrightarrow{d} X \sim N(\mu,\sigma^2/n)$ then $h(\hat{\mu}) \xrightarrow{d} h(X)$. However, in case of $t(\hat{\mu},s)$, it is a function of two random variables. So how to derive its asymptotic distribution?
I also checked Slutsky's theorem. That also requires that at least one of $\hat{\mu}$ and $s$ should converge to a constant. Now by CLT, both converges in distribution to a random variable with normal distribution. However, by combining LLN we may say that $s \xrightarrow{p} \sigma$. Would it be the right way to go?
EDIT: As pointed out in the second comment this is not a duplicate of this. Seemingly $s$ converged in probability to a constant but to a random variable in distribution. This was the main doubt that whether it was okay to ignore the convergence in distribution.
Comment: Possible duplicate of [Is there a theorem that says that $\sqrt{n}\frac{\bar{X} - \mu}{S}$ converges in distribution to a normal as $n$ goes to infinity?](https://stats.stackexchange.com/questions/97268/is-there-a-theorem-that-says-that-sqrtn-frac-barx-mus-converges-in)
Comment: @StubbornAtom : I don't agree that this is a duplicate, since this question asks where the gaps are in a proposed argument, rather than just asking what the argument is.
Comment: What is the difference between $\hat \sigma$ and $s$?
Comment: No difference. Used $\hat{\sigma}$ by mistake. Corrected now.
Answer: It is not correct that $\widehat\mu$ and $s$ fail to converge in distribution to constants, nor that CLT implies that.
Rather, what CLT says is:
\begin{align}
& \frac{\widehat\mu - \mu}{\sigma/\sqrt n} \overset d \longrightarrow \operatorname N(0,1) \\[8pt]
\text{and } & \sqrt{n-1} \left. \left(\dfrac{s^2}{\sigma^2}-1\right) \right/\!\!\sqrt 2 \overset d \longrightarrow \operatorname N(0,1).
\end{align}
It can be shown to follow that $\widehat\mu$ and $s$ converge in distribution to $\mu$ and $\sigma$ respectively.
And convergence in distribution to a constant entails convergence in probability to that constant.
Comment: In a more general case, if say neither converged to a constant then is there a way to get the asymptoptic distribution of their function?


How to display a customized button on a single form only?

Question: I have created a reset button by adding a customized module (Reset) for webform. But this button gets displayed all over the site. I just want to display this button on a single webform.
Below is my Reset module code:
<?php
/*
 *
 *  creating  hook_form_alter()
 *
 */
function custom_example_form_alter(&$form,&$form_state,$form_id) {
            $form['webform_client_form_34'] = array(
            '#weight' => 1001,
            '#markup' =>'<input class="form-button" type="reset" value="Reset"/>',
            );
            return $form;
}

How should the if condition look like that I should be adding to it ?
Answer: Find the form id first.
Assume your form id is 50 than,
function <module>_form_alter(&$form, $form_state, $form_id) {
  if (strpos($form_id, 'webform_client_form_50') === 0) {
    $form['actions']['reset'] = array(
      '#type' => 'button',
      '#value' => t('Reset'),
      '#weight' => 100,
      '#validate' => array(),
      '#attributes' => array('onclick' => 'this.form.reset(); return false;'),
    );
  }
}

OR
 if ($form_id == 'my_webform_client_form_id') {

Your code

}

Another method :-
In Drupal 7, you can either use hook_form_alter() or hook_form__alter(), which ever you prefer. Just make sure you get the naming and parameters right. Drupal 6 only supports hook_form_alter() however.
When you create these functions, also remember that Drupal may not always pick up on them until you've flushed the cache.
function mymodule_form_webform_client_form_44_alter(&$form, &$form_state) {
// code here;
}

Please remember to clear your cache also and try to disable/enable your module also
Answer: If you're using hook_form_alter() to do this, you need to have a if statement that looks at the form id that corresponds with your node. For example....
if ($form_id == 'webform_client_form_34') {
  $form['webform_client_form_34'] = array(
    '#weight' => 1001,
    '#markup' =>'<input class="form-button" type="reset" value="Reset"/>',
  );
}

Comment: Not working ,the button still displaying all over other locations throughout the site .
Answer: To further complete/complement Shawn's answer (and the comment like "not working"), make sure you use the correct value for the $form_id.
To actually find this correct value, there are a few options, like:

insert a line like dpm($form_id); in front of the if statement.

use the Get Form ID module to easily find out form id of any form in Drupal, for which a video demo is available also. Here is a quote about it from its project page:

By hovering over any form you will see a contextual link available. By expanding the link you will see the form ID. Click on the link and you will see a modal window with copyable form id and hook_form_FORM_ID_alter() hook suggestion.

Use the improved and rebranded version of the (deprecated) Get Form ID module, which is the Devel form debug module, and for which a video demo is available. Here is a quote about it from its project page:

By hovering over any form you will see a contextual link available. By expanding the link you will see the form ID. Click on the link and you will see a modal window with copyable form id and hook_form_FORM_ID_alter() hook suggestion.

After finding out the (for sure) correct value, I'd be curious if combining it with Shawn's answer you can get it to work ...


Clarification on SQL Syntax

Question: Clarification on my SQL Syntax
Does the WHERE condition look for INSURANCECODE only with CASH or ''
and PLANNAME = NULL ?
select *
from report rpt
left join InsurancePlan Ip on IP.PlanName  = rpt.PrimaryPlanName
where
   (rpt.InsuranceCode in ('CASH', '') or Ip.PlanName is null)

Comment: Unsure what you're asking here. Can you clarify, explain more?
Answer: The OR takes priority, meaning you will effectively get any row that has either or both of the two conditions, ie.

If rpt.InsuranceCode has the value CASH or an empty string
If Ip.PlanName is null

if either, or both conditions are met, you will get a row in your resultset.
You could think of the query as the following as well:
WHERE
    rpt.InsuranceCode = 'CASH'
 OR rpt.InsuranceCode = ''
 OR Ip.PlanName IS NULL

In the following example table, the rows that would end up in the resultset is marked with a * to the right:
InsuranceCode    PlanName    ResultSet    Why?
'CASH'           'Whatever'      *        rpt.InsuranceCode = 'CASH'
''               'Whatever'      *        rpt.InsuranceCode = ''
'Whatever'       NULL            *        Ip.PlanName IS NULL
'CASH'           NULL            *        Both
''               NULL            *        Both
'Whatever'       'Whatever'               Neither

Answer: Basically your query will return rows that have an InsuranceCode equal to 'CASH' or '', as well as rows that have a NULL value for PlanName
Answer: The way you have it now you will get insuranceCode = cash AND insuranceCode = ''  OR the planName is null. So all planeName = null will show regardless of insCode and planName will have values for codes that are '' or cash.
If you want all rows to have a null planName change the OR to AND
Comment: That answer doesn't do much in clarifying anything. For starters, there's no way InsuranceCode can be both cash and an empty string, so the "AND" in there is misplaced.

Clarification on SQL Syntax


How to Connect to CRM Dynamics Online Odata endpoint LinqPad?

Question: I'm able to connect to self-hosted CRM sites just fine with the default Odata driver within LinqPad.  The URI I use in the "WCF Data Services (OData) Connection" dialog for self-hosted is in the format http://MyServer.com/MyOrgName/xrmservices/2011/OrganizationData.svc. The user name is in the format "domain\username".
When I attempt to follow the same format for an CRM Online instance, it doesn't work.

I'm guessing it's either because of the https, or the windows live credentials, but don't know what steps to take to fix the problem...
Please note, I want to use the odata provider, not the CRM 2011 provider.  The odata provider gives me the URL to retrieve the data which is extremely helpful for javascript.  The CRM 2011 provider gives the fetch XML, which isn't what I want to use in this case...
Answer: I contacted LinqPad and they said they don't currently support Windows Live Authentication.  I'm guessing that one would have to write a plugin and use the logic from this page to handle the authentication issues.


PHP e API - Como conectar com em que usa chave de api autenticaçao via header Breare

Question: Pessoal alguem poderia me ajudar, estou precisando consumir uma API que tem forma de autenticaçao via Breare, alguem teria algum exemplo de uma API que faz essa implantaçao?
https://docs.questor.com.br/docs/api
Link da API que deseja me comunicar.
Comment: Por favor, edite a pergunta para limitá-la a um problema específico com detalhes suficientes para identificar uma resposta adequada.
Answer: Tente assim:
<code>   <?php
$curl = curl_init();

curl_setopt_array($curl, array(
    CURLOPT_URL => 'url-api',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
    CURLOPT_CUSTOMREQUEST => 'GET',
    CURLOPT_HTTPHEADER => array(
        'Authorization: Bearer seu-token-aqui'
    ),
));

$response = curl_exec($curl);

curl_close($curl);
echo $response;
</code>
Comment: Sua resposta pode ser melhorada adicionando informações fundamentais. Basta [edit] para adicionar mais detalhes, como citações ou documentação para que outras pessoas possam confirmar que sua resposta está correta. Você pode encontrar mais informações sobre como escrever boas respostas [na Central de Ajuda](/help/how-to-answer).


Marginal Probability of Stochastic Process

Question: I have a wide sense stationary stochastic process x(t)=asin(2πf0t)+bcos(2πf0t) where a & b are independent gaussian random variables. How can I find the Marginal probability of x(t)?
I am confused even about the very meaning of it. How can I find marginal probability of x(t) if I don't have any other function to find its joint probability distribution with? Does it automatically imply that the other function is x(t+τ) ?
Should I just substitute x(t) as 'x' in the usual marginal gaussian probability distribution equation shown below?

The mean and variance for a,b were given as zero and 1 respectively so I calculated the autocorrelation function for x(t). Does that have any use in such scenario?
Comment: Hi how x(t) is a stochastic process when it is constant for all t ? Best regards
Comment: Sorry about that. Edited.
Answer: If $a$ and $b$ are independent gaussian random variables and if $a$ and $b$ are centered with the same variance $\sigma^2$ then, for every $t$, $x(t)=a\sin(2πf_0t)+b\cos(2πf_0t)$ is gaussian centered with variance $\sigma^2\sin^2(2πf_0t)+\sigma^2\cos^2(2πf_0t)=\sigma^2$. If $a$ and $b$ are centered with different variances, then $x(t)$ is gaussian centered with variance $\sigma_a^2\sin^2(2πf_0t)+\sigma_b^2\cos^2(2πf_0t)$, depending on $t$.
Comment: This helps because then x(t) is *standard normal* N(0,1).
Comment: Yes, a and b have same variance = 1, but how does that help with the marginal PDF of x(t)?


spinner1 cannot be resolved or is not a field

Question: I am not able to understand why i am getting an error here.The error is spinner1 cannot be resolved.Plz help me out fast.I am new to java and android development so explain accordingly.
This is my java code
package com.example.dailyexpenses;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.Toast;
import android.widget.ImageView;
import android.widget.TextView;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
  import android.view.ViewGroup;

    public class GamesFragment extends Fragment {
    String[] Languages = { "Select a Language", "C# Language", "HTML Language",
        "XML Language", "PHP Language" };
        // Declaring the Integer Array with resourse Id's of Images for the Spinners
        Integer[] images = { 0, R.drawable.icon, R.drawable.petrol,
        R.drawable.books, R.drawable.recharge};
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View rootView = inflater.inflate(R.layout.fragment_games, container, false);

    Spinner mySpinner = (Spinner) findViewById(R.id.spinner1);

    return rootView;
}

 }

This is fragment_games.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#ff8400" >

<TextView
    android:id="@+id/textView1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_alignParentTop="true"
    android:layout_marginTop="15dp"
    android:text="choose from the categories below"
    android:textAppearance="?android:attr/textAppearanceMedium" />

 <Spinner
  android:drawSelectorOnTop="true"
  android:id="@+id/spinner1"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:prompt="@string/select">
</Spinner>

 </RelativeLayout>

Comment: did my solution/answer worked for you/your app?
Answer: You need to call
rootView.findViewById

since android does not yet to know where to search.
For more explanation:
Probably (not to judge ofc) you are familiar to call findViewById in the method onCreate of an Activity, but before that you did call setContentView. After setting the content by setContentView android knows where to search for the id when you call findViewById. That is for the case when you are using activity. On the other hand, with fragments it is a different case. You won't be setting the content by setContentView, instead you have to prepare a view and return it on onCreateView and let the android set the content as it wishes. Be careful, on lines you are calling findViewById above there, you haven't return the view yet, so android does not know where to search as you call findViewById. So you have to make your searches not on not-set-yet-content, but on the rootView you are just about to return. So above the code is the solution to this well described problem.


Load .dat file and read

Question: I have text .dat file and I load this file from my main class and read in my DataReader class. but I get errors that i have to change my modifier to static. I can't do that because it is required to be non-static.
I am stuck here and not sue if my problem is here or somewhere else. will you check my codes and let me know if it is okay or not?
next line also does not store in vehicle and shows null!!
this code gets the error:
if(DataReader.loadData(args[0])) {   // i get errors here

and ask me to change this to: public static boolean loadData(String VehicleData) { /// but this code has to be non-static... ( required by my professor)
Main class:
public class Project3 {

private static Vehicle[] vehicles;
static int x;

public static void main(String[] args) {
    // Display program information

    DataReader reader = new DataReader(); // The reader is used to read data from a file

    // Load data from the file
    **if(DataReader.loadData(args[0]))** {   // i get errors here

        vehicles= reader.getVehicleData(); // this line also shows null

        // Display how many shapes were read from the file
        System.out.println("Successfully loaded " + vehicles[0].getCount() +
                           " vehicles from the selected data file!");
        displayMenu();
    }
}

DataReader Class:
ublic boolean loadData(String VehicleData) {
    boolean validData = false;
    String line;

try{
// Open the file
    BufferedReader reader = new BufferedReader(new FileReader("VehicleData.dat"));
//Read File Line by line

        while((line=reader.readLine()) !=null) {
            addVehicle(line.split(","));
        }
        reader.close();
        vehicles = Array.resizeArray(vehicles, vehicleCount);
        validData = true;
    }

Comment: *"I can't do that bcoz.."*  I can't read that *because* it is slang.  Other people might have trouble with it as well.  Please spell words properly, no slang on SO.
Comment: Change `DataReader.loadData(args[0])` to `reader.loadData(args[0])` (you need to use your instance object, not the class.
Answer: You should probably use the DataReader instance (reader) you create the line before:
    DataReader reader = new DataReader(); // The reader is used to read data from a file

    // Load data from the file
    if(reader.loadData(args[0])) {

Answer: As loadData is an instance method you should use:
if (reader.loadData(args[0])) {

Answer: You've create an instance of the reader but then chosen not to use it...
DataReader reader = new DataReader(); // The reader is used to read data from a file
if(DataReader.loadData(args[0]))

You should just use the instance you have available
DataReader reader = new DataReader(); // The reader is used to read data from a file
if(reader.loadData(args[0]))

Comment: and also next line suppose to store my array in vehicle , but doesn't and shows it null... do you know why?
Answer: Yes, change DataReader to reader. You have created the DataReader object named reader but you are calling loadData() method on the class DataReader and not on the object reader. If you don't have an instance of the object and are calling the method it will have to be a static method. You can call static methods whenever you want, they do not have to be on a specific object.

Load .dat file and read


$\det\left(6(A^3+B^3+C^3)+I_{2}\right)\ge 5^2\det(A^2+B^2+C^2)$ for $2 \times 2$ matrices

Question: Motivated by this question I propose a simplification:

Question Let matrices $A,B,C\in M_{2}(\mathbb{C})$ be Hermitian and positive definite, such that:$$A+B+C=I_2$$
  Show that:
  $$\det\left(6(A^3+B^3+C^3)+I_{2}\right)\ge 5^2\det(A^2+B^2+C^2)$$
  where $I_{2}$ is the identity matrix.

The original question is of unknown origin and I am hoping for a substantial simplification in the $2 \times 2$ case where the following expansion holds:
$$\left[ \begin{array}{cc} x_1 & y + iz \\ y - iz & x_2\end{array}\right]
= \left[ \begin{array}{cc} x_1 & 0 \\ 0 & x_2\end{array}\right]
+ y\left[ \begin{array}{cc} 0 & 1  \\ 1  & 0\end{array}\right]
+ z\left[ \begin{array}{rc} 0 &  i \\  - i & 0\end{array}\right]$$
maybe with expansion to Pauli spin matrices this is solvable.

There is a nice article by Knutson and Tao on Honeycombs that might be of assistnce:

http://www.ams.org/journals/jams/1999-12-04/S0894-0347-99-00299-4/
Comment: In some of the (upvoted) comments accompanying the following question _numerical_ evidence is presented by user1551, confirming that the statement is true for $10000$ of such random $2\times 2$ matrices: [How to construct symmetric and positive definite $A,B,C$ such that $A+B+C=I$?](http://math.stackexchange.com/questions/2084573/how-to-construct-symmetric-and-positive-definite-a-b-c-such-that-abc-i)
Comment: Nice (+1) attempt to settle the problem, though! I'm breathlessly awaiting, really.
Comment: @HandeBruijn contest problems and university exams can be tricky, it seems that discussion has gone down the wrong track and never recovered.  I am hoping for a solution that emaphasizes general principles.  I think this problem could be solved using convexity or matrix norms, for example.
Comment: Considering the difficulties with proving such _inequalities_ for real numbers, I doubt that someone would come up with a solution even for _symmetric_ instead of Hermitian $2\times 2$ matrices. Thus it seems that the "power of mathematics" is somewhat unevenly distributed among its areas of interest.
Comment: For the question here, the 2 by 2 case, a hermitian matrix can be thought of as an element of Minkowski 4-dimensional spacetime, with the determinant giving the Minkowski product of the vector with itself. The conditions that the matrix is positive definite amounts to the condition that the vector be timelike and future-pointing.
Answer: Let $L=\{(A,B,C)\in M_2(\mathbb{C})^3; A,B,C\text{ are hermitian }\geq 0,A+B+C=I_2\}$ and
$res:L\rightarrow \det(6(A^3 +B^3+C^3)+I_2)-25\det(A^2
+B^2+C^2)$.
Since we seek $\min_L res$, we may assume that $A$ is a diagonal matrix and that $res$ is defined on the set $K$ parameterized by
$A=diag(u,v),B=\begin{pmatrix}p&r+is\\r-is&q\end{pmatrix},C=\begin{pmatrix}1-u-p&-r-is\\-r+is&1-v-q\end{pmatrix}$, where
$u,v,p,q,1-u-p,1-v-q,pq-r^2-s^2,(1-u-p)(1-v-q)-r^2-s^2\geq 0$.
Note that $K$ is a compact convex subset of $\mathbb{R}^6$. The edge of $K$, $\partial K$ is the set of points of $K$ s.t. at least one of the $8$ terms above is zero and $K\setminus \partial K$ is the interior of $K$.
Of course, $\min_K res$ is reached in at least one point of $K$. We know that $\min_K res\leq 0$ and that, if $AB=BA$, then $res(A,B,C)\geq 0$.
We want to show
$\textbf{Theorem}.$ One has $\min_K res=0$ and this bound is reached only by commuting triplets of matrices.
$\bullet$ In the sequel, we assume that $AB\not= BA$.
An essential tool will be the Grobner basis theory on $\mathbb{C}$ and on $\mathbb{R}$. Since the theory over $\mathbb{R}$ is much less powerful, the idea is to reduce our problem to a polynomial system on $\mathbb{C}$ constituted by polynomials simpler than $res$ and to show that this system has no real solutions satisfying the $8$ conditions above.
$\textbf{Lemma}.$ We may assume $v>u\geq 0$ and $p,q,1-u-p,1-v-q>0$.
$\textbf{Proof}$. For example, if $pq=0$, then $r=s=0$ and $AB=BA$. $\square$
$\textbf{Proposition 1.}$ If $u>0,pq>r^2+s^2,(1-u-p)(1-v-q)>r^2+s^2$ (that is, $\det(A),\det(B),\det(C)>0$), then $(A,B,C)$ does not realize $\min_K res$.
$\textbf{Proof}$. Here $(A,B,C)\in K\setminus\partial K$; if it reaches $\min_K res$, then it must cancel the partial derivatives of $res$.
Step 1. We use the Maple library FGb (working over $\mathbb{C}$) to study the $3$ systems
$\dfrac{\partial res}{\partial u}=\dfrac{\partial res}{\partial v}=\dfrac{\partial res}{\partial p}=\dfrac{\partial res}{\partial q}=\dfrac{\partial res}{\partial r}=\dfrac{\partial res}{\partial s}=0,u-v\not= 0$, AND
$[(rs\not=0)$ OR $(r\not=0,s=0)$ OR $(r=0,s\not=0)]$,
asking (among other polynomials) for relations between $u,v$.
We obtain, in each case, a Grobner basis containing (in particular) $3$ polynomials $P,Q,R$ which only depend on $u,v$.
Step 2. We use the Maple library RAG (working over $\mathbb{R}$) to study the system
$P=Q=R=0,u,v-u,1-u,1-v>0$.
We obtain that there are no solutions in each of the $3$ cases. $\square$
$\textbf{Proposition 2}$. If $\det(A)$ or $\det(B)$ or $\det(C)=0$, then $(A,B,C)$ does not realize $\min_K res$.
$\textbf{Proof}$. We may assume that $\det(A)=0$, that is, $u=0$. If we put $a=r^2+s^2$ (with $a>0$ because $AB\not= BA$), then (Maple form)
$$res(0,v,p,q,r,s)=f(v,p,q,a)=-36*a*p^2*v^2-144*a*p*q*v^2-72*a*p*v^3-36*a*q^2*v^2-36*a*q*v^3-36*a*v^4-324*p^2*q^2*v-324*p^2*q*v^2+72*a^2*v^2+648*a*p*q*v+432*a*p*v^2+108*a*q*v^2+108*a*v^3+224*p^2*q^2+548*p^2*q*v+224*p^2*v^2+324*p*q^2*v+324*p*q*v^2-324*a^2*v-448*a*p*q-548*a*p*v-324*a*q*v-183*a*v^2-224*p^2*q-224*p^2*v-224*p*q^2-548*p*q*v-224*p*v^2-126*q^2*v-126*q*v^2+224*a^2+224*a*p+224*a*q+198*a*v+76*p^2+224*p*q+224*p*v+76*q^2+202*q*v+76*v^2-72*a-76*p-76*q-76*v+24.$$
We use the Maple library RAG (working over $\mathbb{R}$) to study the system
$f=0,v > 0, p > 0, q > 0, 1-p > 0, 1-v-q > 0, a > 0, a < 1$.
We obtain that there are no solutions.
Remark that $U=\{(v,p,q,a);v > 0, p > 0, q > 0, 1-p > 0, 1-v-q > 0, a > 0, a < 1\}$
is an open convex subset of $\mathbb{R}^4$ and that $f(0.1,0.3,0.4,0.1)\approx 5.6>0$.
We conclude that $f>0$ on $U$ and that $\min_K res$ is not reached on $U$.  $\square$
$\textbf{Proof of Theorem.}$ According to Propositions 1 and 2, $\min_K res$ is reached only by triplets $(A,B,C)$ s.t. $AB=BA$; therefore $\min_k res=0$ and is  reached only (up to simultaneous similarity) by the triplets
i) $diag(1/2,1/2),diag(1/2,0),diag(0,1/2)$
ii) $A=B=C=1/3.I_2$
iii) $A=B=0.5.I_2,C=0_2$
iv) $A=diag(1/3,1/2),B=diag(1/3,0),C=diag(1/3,1/2)$.


Reference request: generalized linear (mixed) model for Dirichlet distribution

Question: Plenty of books about on GLMs for exponential families, but any good books or papers which study the Dirichlet distribution in particular?
Comment: Possible duplicate of [Why Beta/Dirichlet Regression are not considered Generalized Linear Models?](https://stats.stackexchange.com/questions/304538/why-beta-dirichlet-regression-are-not-considered-generalized-linear-models)
Comment: Ng, Tian and Tang, *Dirichlet and Related Distributions: Theory, Methods and Applications*
Comment: So why is it the Dirichlet distribution that is needed? Why not to estimate the parameters of a multinomial distribution?
Comment: `"The response variable is a discrete probability distribution."` Discrete as in the result of Bionomial experiments? If that's the case, then you actually want the Multinomial GLM.
Comment: Tell us why you are using the Dirichlet distribution.
Comment: The response variable is a discrete probability distribution.
Answer: The book by Ludwig Fahrmeir
Gerhard Tutz:  "Multivariate Statistical
Modelling Based on
Generalized Linear Models
(Second Edition)" contain some references, but it seems to be mostly to use of the dirichlet distribution as a prior distribution in multinomial logistic models. There are many papers on Dirichlet regression, see https://www.researchgate.net/profile/Rafiq_Hijazi/publication/228576713_Modelling_compositional_data_using_Dirichlet_regression_models/links/02e7e52e9cab9696f5000000.pdf  or  https://www.researchgate.net/profile/Rafiq_Hijazi/publication/265165887_Residuals_and_Diagnostics_in_Dirichlet_Regression/links/54054b8c0cf2c48563b13827.pdf .   But are these models GLM's?  see for instance Why Beta/Dirichlet Regression are not considered Generalized Linear Models?
Comment: What is the profit of using the Dirichlet distribution? Why are you not using, say, multinomial linear regression for the parameters of a categorical distribution itself?
Comment: Do the categorical distributions of the response seem to be irregular? Why are Poisson regression or binomial regression or something alike not suitable?
Comment: Please look through https://en.wikipedia.org/wiki/Multinomial_logistic_regression This is what I would start from.


Problemas na criação de arquivo em C

Question: Boa noite! Estou tentando criar um arquivo txt de uma lista de clientes, para isto criei um looping a fim de armazenar 2 clientes e espero que o arquivo criado guarde estes dados no txt, todavia ele só está guardando um cliente a cada execução! Podem me explicar o que está acontecendo? Comecei a aprender sobre ponteiros agora, então provavelmente é algo muito simples e, apesar de estar consultando meus materiais ainda não consigo encontrar o erro.
<code>#include <stdio.h>
#include <locale.h>
 struct lista_clientes
{
    char nome[50];
    int idade;
    int telefone;
    char endereco[100];
};

main()
{
    FILE *arqu_file; /*declaração do ponteiro para criação do arquivo*/
    arqu_file= fopen("Clientes.txt","a+"); /*abertura do arquivo*/
    if (arqu_file == NULL) /*teste do arquivo*/
    {
        printf("Houve um ERRO!");
    }
    int i;
     struct lista_clientes Clientes[2];
        for (i=0;i<2;i++)       /*laço de repetição a priori para 20 clientes*/
        {
            printf("Nome do cliente: "); scanf(" %s",Clientes[i].nome);
            printf("Idade do cliente: "); scanf("%i",&Clientes[i].idade);
            printf("Telefone do cliente: "); scanf("%i",&Clientes[i].telefone);
            fflush(stdin);          /* necessario para o buffer*/
            printf("Endereco do cliente: "); gets(Clientes[i].endereco);
            fprintf(arqu_file,"%s %i %s %i",Clientes[i].endereco,Clientes[i].idade,Clientes[i].nome,Clientes[i].telefone);
            fclose(arqu_file);
            getc(arqu_file);
        }
}

</code>
Answer: Acredito que o problema seja o fato que você fechou o arquivo dentro do for, aí quando ele executa pela 2ª vez não é mais possível escrever.

Problemas na criação de arquivo em C


HP - BIOS - Invalid Opcode Exception

Question: I have an HP DL360 Gen9. It is running Windows Server 2019, but after I restarted it, I'm not able to boot again after "Loading System Firmware Modules - Complete" it just dies with an "Invalid Opcode Exception" ass can be seen below.
("Loading System Firmware Modules - Start" POST Code: 2500 -> "Loading System Firmware Modules - Complete" POST Code: 2600, then the "Invalid Opcode Exception" POST Code still: 2600)
I have tried to update the BIOS to the latest version, but that is not working either.
BIOS / System ROM: P89 v2.90 (04/29/2021)
LO Firmware Version: 2.78 Apr 28 2021
TPM Status - Present: Enabled
Module Type: TPM 2.0
Error part 1 of 2
Error part 2 of 2
Windows is booting from a local RAID 1 from the "Smart Array P440ar Controller"
I hope someone can help me out understand what the problem is so that I can fix it.
Answer: Those POST codes are not in the public list of HPE Proliant Gen9 POST codes: https://techlibrary.hpe.com/docs/iss/shared/error_gen9/GUID-F4913264-0358-4A71-9914-59199912055D.html
"Invalid Opcode Exception" would indicate that the processor was trying to execute an machine code instruction and found it was not a valid one. Since the previous step was loading the system firmware modules, my guess would be that the next step would have to be execution of some code from one or more of those firmware modules. So the error message might indicate that some piece of firmware is corrupted.
Do you know the last time the system was booted successfully before this problem appeared? Has the system received any firmware updates since then?
The next piece of firmware to execute might actually be the firmware of the Smart Array P440ar Controller. The iLO firmware version has already been displayed, so the firmware module related to the initialization of the iLO functionality is probably already successfully executed.
You might try temporarily unplugging the Smart Array controller from its slot. If that makes the Invalid Opcode Exception not appear, then the problem could be that the Smart Array firmware has been corrupted. Unfortunately I have no suggestions on how you might recover from that.
Comment: Thanks I will try that Monday as the server is out of reach this moment. The only thing updated since last boot of firmware is the iLO, I do not think i updated the raid controller, but i will check. I can live with losing the data on the RAIDs controller.
Answer: I got in contact with HP and got this information.

You have to try clearing NVRAM once. https://support.hpe.com/hpesc/public/docDisplay?docId=c04441985      -- Page 92, Switch 6 to get a dip, boot server and put it in same state to boot again.
Swapping CPUs
Checking if it is not a slot issue
Perform minimum configuration to narrow down if any hardware fault
In case the issue persists - it could be a system board issue and replacement would be needed
You can also try re-installing a different windows image.

I only had to clear the NVRAM, that worked. No need for the other steps if the NVRAM clearing did not work, but now other have them.
A little bonus info: The boot drive was a RAID 1 on the RAID controller, I had to reenable that logic disk.

HP - BIOS - Invalid Opcode Exception