Firebase: passing data to cloudfunction results in: Object cannot be encoded in JSON

Question: I try to call a cloud function and pass some data. My data is of type Map<String, Object> and inside it has again some nested Map<String, Object>. When trying to call my function with this:
getHttpsCallable(function).call(data)...

I get this error:
Cloud Function Exception:
java.lang.IllegalArgumentException: Object cannot be encoded in JSON: [Ljava.util.Map;@42896770
 at com.google.firebase.functions.Serializer.encode(Serializer.java:136)
 at com.google.firebase.functions.Serializer.encode(Serializer.java:77)
 at com.google.firebase.functions.FirebaseFunctions.call(FirebaseFunctions.java:255)
 at com.google.firebase.functions.FirebaseFunctions.access$100(FirebaseFunctions.java:34)
 at com.google.firebase.functions.FirebaseFunctions$2.then(FirebaseFunctions.java:233)
 at com.google.firebase.functions.FirebaseFunctions$2.then(FirebaseFunctions.java:225)
 at com.google.android.gms.tasks.zzd.run(Unknown Source)
 at android.os.Handler.handleCallback(Handler.java:733)
 at android.os.Handler.dispatchMessage(Handler.java:95)
 at android.os.Looper.loop(Looper.java:146)
 at android.app.ActivityThread.main(ActivityThread.java:5653)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:515)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1291)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1107)
 at dalvik.system.NativeStart.main(Native Method)

When printing my data object it looks like this:
{items=[Ljava.util.Map;@42896770, element1=OzNGHzHeq6av03hRmMJ6, time=Sun May 05 04:40:00 MEZ 3918}

I tried the following:
I tried packing an array instead of a Map inside my data-object. => Did not work.
I tried to convert my data into a json myself and send it, this also didn't work.
I did the follwoing:
Gson gson = new Gson();
String dataJSON = gson.toJson(data);

which restulted in a nice formatted JSON:
{"items":[{"count":1,"itemId":"94To3bKnxoWzayLdy55I"},{"count":3,"itemId":"fkNtIUxbfg5GhLJy2Dma"},{"count":1,"itemId":"sDYTp7cpQTRfWuI6CSaK"},{"count":1,"itemId":"qGGl5U0qihHnMzhBMjyb","options":["2.0","1.0","1.1","0.0"]},{"count":1,"itemId":"qGGl5U0qihHnMzhBMjyb","options":["2.0","1.0","1.1","0.1"]},{"count":1,"itemId":"qGGl5U0qihHnMzhBMjyb","options":["2.0","1.0","1.1","0.2"]},{"count":1,"itemId":"qGGl5U0qihHnMzhBMjyb","options":["2.3","1.0","1.1","0.1"]}],"storeId":"OzNGHzHeq6av03hRmMJ6","pickupTime":"May 5, 3918 4:40:00 AM"}

But I also tried to call my function with a hardcoded JSON which did not work either.
I can't figure out what I am doing wrong. Does anyone know?
Comment: Maybe use the Gson library https://www.mkyong.com/java/how-do-convert-java-object-to-from-json-format-gson-api/ or https://github.com/google/gson
Comment: @RenaudTarnec I did. I used it in my approach to send a prebuild json.
Comment: `{items=[Ljava.util.Map;@42896770,...` does not look at JSON...
Comment: yes. It looks like this, when just trying what I am talking about in my initial question-text. I just told in my question that I also tried some other stuff, including generating a json with gson.
Comment: Can you share the code you have written with Gson to transform your java object in JSON?
Comment: @RenaudTarnec: Please see my edit
Comment: Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/170232/discussion-between-renaud-tarnec-and-prognewbie).
Answer: The problem is you are actually passing array of Map objects.
As Frederik Byl shows the source code of Functions SDK for Android, it won't accept array type. It accepts Map or List Java Collection object.
So you must change your [Ljava.util.Map; to List<Map> type.
Plus, actully Firestore uses Protobuf for core dataset. You can find more information at here how they encode or decode json with Protobuf data.
Answer: I think you should create and pass a JSONObject out of your data object. Not a string or the data object:
like this:
 Gson gson = new Gson();
    String jsonString = gson.toJson(data);
    JSONObject jsonObj = null;
    try {
         jsonObj = new JSONObject(jsonString);
    } catch (JSONException e) {
        e.printStackTrace();
    }

because:
  public Object encode(Object obj) {
    if (obj != null && obj != JSONObject.NULL) {
        JSONObject result;
        if (obj instanceof Long) {
            result = new JSONObject();

            try {
                result.put("@type", "type.googleapis.com/google.protobuf.Int64Value");
                result.put("value", obj.toString());
                return result;
            } catch (JSONException var9) {
                throw new RuntimeException("Error encoding Long.", var9);
            }
        } else if (obj instanceof Number) {
            return obj;
        } else if (obj instanceof String) {
            return obj;
        } else if (obj instanceof Boolean) {
            return obj;
        } else if (obj instanceof JSONObject) {
            return obj;
        } else if (obj instanceof JSONArray) {
            return obj;
        } else {
            Object o;
            String key;
            Object value;
            Iterator keys;
            if (obj instanceof Map) {
                result = new JSONObject();
                Map<?, ?> m = (Map)obj;
                keys = m.keySet().iterator();

                while(keys.hasNext()) {
                    o = keys.next();
                    if (!(o instanceof String)) {
                        throw new IllegalArgumentException("Object keys must be strings.");
                    }

                    key = (String)o;
                    value = this.encode(m.get(o));

                    try {
                        result.put(key, value);
                    } catch (JSONException var10) {
                        throw new RuntimeException(var10);
                    }
                }

                return result;
            } else {
                JSONArray result;
                if (obj instanceof List) {
                    result = new JSONArray();
                    List<?> l = (List)obj;
                    keys = l.iterator();

                    while(keys.hasNext()) {
                        o = keys.next();
                        result.put(this.encode(o));
                    }

                    return result;
                } else {
                    JSONObject wrapped;
                    if (obj instanceof JSONObject) {
                        result = new JSONObject();
                        wrapped = (JSONObject)obj;
                        keys = wrapped.keys();

                        while(keys.hasNext()) {
                            String k = (String)keys.next();
                            if (!(k instanceof String)) {
                                throw new IllegalArgumentException("Object keys must be strings.");
                            }

                            key = k;
                            value = this.encode(wrapped.opt(k));

                            try {
                                result.put(key, value);
                            } catch (JSONException var11) {
                                throw new RuntimeException(var11);
                            }
                        }

                        return result;
                    } else if (!(obj instanceof JSONArray)) {
                        if (obj instanceof Date) {
                            String utc = this.dateFormat.format((Date)obj);
                            wrapped = new JSONObject();

                            try {
                                wrapped.put("@type", "type.googleapis.com/google.protobuf.Timestamp");
                                wrapped.put("value", utc);
                                return wrapped;
                            } catch (JSONException var12) {
                                throw new RuntimeException("Error encoding Date.", var12);
                            }
                        } else {
                            throw new IllegalArgumentException("Object cannot be encoded in JSON: " + obj);
                        }
                    } else {
                        result = new JSONArray();
                        JSONArray l = (JSONArray)obj;

                        for(int i = 0; i < l.length(); ++i) {
                            o = l.opt(i);
                            result.put(this.encode(o));
                        }

                        return result;
                    }
                }
            }

Answer: Passing a org.json.JSONObject instead of the com.google.gson.JsonObject works just fine.
You don't need to use Maps on the firebase functions.


Relação entre Python Arrays

Question: sou iniciante em Python e estou com muita dificuldade em fazer o seguinte:
Possuo 1 vetor com os seguintes valores:

posição = [34.53, 32.64, 44.20, 43.41]

Estes valores são dados pela distância Euclidiana das seguintes coordenadas:

coordenadas = [29, 83, 61, 70, 29, 83, 50, 58, 29, 83, 64, 56, 29, 83, 71, 72]

A cada 4 índices do vetor coordenadas, corresponde a 1 índice do vetor posição.

Por exemplo: O valor [34.53] do vetor posição, corresponde aos valores [29, 83, 61, 70] do vetor coordenadas.

==================
O que eu desejo fazer é o seguinte:
Quando um valor do meu vetor posição for maior que 40.00, devo modificar as coordenadas correspondentes no vetor coordenadas por outros valores definidos de forma aleatória.
Por exemplo:

Possuo os seguintes vetores:

posição = [40.51, 30.52, 30.31]
coordenadas = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]

Localizei um valor maior que 40.00 no vetor posição.

posição = [40.51, 30.52, 30.31]

Que correspondem a esses 4 índices do vetor coordenadas.

coordenadas = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]

Devo substituir os valores do vetor coordenadas, por esses:

coordenadas = [200, 130, 67, 31, 50, 60, 70, 80, 90, 100, 110, 120]
=================
Desculpem-me caso ainda não esteja muito claro, tentei ser o mais didático possível.
Peço que me ajudem, realmente não sei como posso resolver isso. Me parece simples, mas ainda sou iniciante.
Fico muito agradecido aos que se dispuserem em me ajudar.
Answer: Para conseguir isso pode percorrer o primeiro array através da posição e testar se o valor é acima de 40 com um if. Caso seja acede ao segundo array multiplicando a posição por 4 e acedendo 4 elementos de cada vez. Para cada um dos elementos acedidos gera um novo utilizando o randrange do python:
import random

posicao = [40.51, 30.52, 30.31]
coordenadas = [10, 20, 30, 40, 50, 60, 70, 80, 90, 100, 110, 120]

for indice in range(0, len(posicao)):
    if posicao[indice]>40: #se maior que 40
         for indice2 in range(indice*4, indice*4+4): #aceder aos correspondentes
            coordenadas[indice2] = random.randrange(0,200) #gerar os aleatorios entre 0 e 200

print(coordenadas)

Exemplo a funcionar no Ideone para testar
Comment: Isac, estou realmente agradecido pela sua ajuda.

Muito Obrigado por disponibilizar um pouco do seu tempo para me ajudar.

muito, muito obrigado!
Comment: @Danilo Sem problema, resto de bom desenvolvimento.

Relação entre Python Arrays


Workflow with MVC 4 - EF 5 - SimpleMembershipProvider

Question: So I want to build an application with MVC 4 and Entity Framework 5. I've build simple applications before, but now I need some security around my current effort... I have some confusion / questions that I was hoping someone could answer;
First... Using the MVC 4 Internet Application Template it implements SimpleMembershipProvider. I have read every primary article about modification, implementation... However, this uses a Code-First implementation...
Problem: I have an existing database that I would like to import the scheme for to an EDMX database first approach... How do I implement the MVC 4 Simple membership provider when my database ties tightly and directly  into the user table (userid)?... I know I can use my own user table as long as i designate the userid and username fields as documented... Will this affect the provider, or the existing "AccountController" code? Will these need to be modified?
Second, what I am looking for is a workflow with this architecture... I am "old school" mostly database first approach... My project is a huge WIP (work in progress). I have a foundation, but will need to expand as needed... Can someone provide some insight into database first vs other approaches when there will be quite a bit of change management occurring?
Answer: you can still use Code First to map to an existing database. You may need to explicitly map properties to table columns because the mappings do not follow the default conventions, but that doesn't prevent you from using Code First.
When transitioning from DB first to another mindset. Focus on how the objects interact with each other. then, at some point you will save the state of the objects after they interacted. This is where the ORM comes into play. detects changes and executes the necessary SQL statements to persist the current state of the objects.
Think of the database as just another storage container. In theory it could be replaced by another persistent storage mechanism (document db, file, persistent hash table, in memory list, etc.). In reality it's not that simple, but the idea of treating the DB as just a simple storage container helps to break away from the monolithic database concept that is/was ingrained into most devs.
But don't loose perspective of the design either. If it's a simple forms-over-data app where you will be adding features in the future than keep the design simple. than don't try to totally abstract the DB away. you know it's there and the relationship to the UI is almost 1:1, so take advantage of that.
In it's simplest form separation of concerns can be achieved by using the MVC controller to manage the interaction between the model (mapped to the DB via ORM) and the view (razor templates) my personal preference is to keep ORM out of the views so I typically query the database, map the domain model to a viewmodel and then pass the viewmodel to the view.
Again if it's a simple application and screens map directly to the database than viewmodel are probably overkill.


obter entidades HTML originais com javascript

Question: Preciso de todas as entidades HTML originais de um parágrafo, principalmente os acentos, os métodos que conheço recuperam somente algumas entidades, conforme o exemplo abaixo onde ">" é codificado corretamente mas o "ç" não.
É importante que o código possa diferenciar acentos gerados ou não por entidades (como em çã) pois o conteúdo vem de uma fonte externa e pode vir sem um padrão definido

alert(document.querySelector('p').innerHTML);

situação > ativo

Notas: conforme a resposta aceita do @mgibsonbr não é possível, a solução adotada foi utilizar a função DOMDocument::saveHTML, ela interpreta as entidades da mesma maneira que o navegador, de forma que os dados ficam iguais no servidor e no cliente.
Comment: Essa é uma ótima pergunta! Eu não sei em que momento do *parsing* as entidades HTML são resolvidas, nem se isso é preservado em algum lugar ou descartado. Verificando os filhos do `p`, vejo que há apenas um nó `Text`, cujo `data` (de `CharacterData`) é a string com todas as suas entidades resolvidas (inclusive o `>`). Sendo assim, me parece que a informação que quer não existe mais após a página ser carregada, de modo que você precisaria obter esse conteúdo dessa fonte externa (seja no lado servidor, ou talvez via ajax se aplicável) e tratá-lo antes do *browser* interpretar seu HTML.
Answer: As entidades HTML originais não são preservadas quando o markup do documento é interpretado (parsed) pelo browser, de modo que não estão disponíveis para você consultá-las via JavaScript ou de qualquer outra maneira. Segundo a especificação, durante a etapa de tokenization (leitura do texto "cru" e produção de "peçados" - ou tokens - para subsequente análise) as entidades HTML (aqui chamadas de Character Reference) produzem um único caractere quando consumidas:

184.108.40.206 Tokenizing character references
...
O comportamento depende da identidade do próximo caractere (aquele imediatamente depois do U+0026 AMPERSAND), da seguinte forma:
...
"#" (U+0023)
Consuma o U+0023 NUMBER SIGN.
...
Consuma todos os caracteres que casam o intervalo de caracteres listados acima (dígitos hexadecimais ASCII ou dígitos ASCII).
...
Caso contrário, se o próximo caractere é um U+003B SEMICOLON, consuma-o também. Se não for, é um erro de parsing.
...
Caso contrário, retorne um token de caractere para o caractere Unicode cujo ponto de código é aquele número.
Qualquer outra coisa
Consuma o máximo número de caracteres possíveis, desde que os caracteres consumidos casem com um dos identificadores na primeira coluna da tabela de referência de caracteres nomeados (diferenciando maiúsculas e minúsculas).
...
Retorne um ou dois tokens de caracteres para o(s) caractere(s) correspondente(s) ao nome do caractere na referência (dado pela segunda coluna da tabela de referência de caracteres nomeados).

(tradução livre, ênfase minha)
Ou seja, após o documento HTML ter sido "parseado" e o HTML resultante formado (bem como sua representação no DOM) a informação sobre as entidades HTML utilizadas não estão mais lá - foram substituídas pelos seus caracteres correspondentes. O fato do innerHTML (e outerHTML) devolverem o texto com o > escapado se deve ao fato dele "reescapá-lo" pra você, independentemente da forma como ele estava originalmente no markup:

alert(document.querySelector('p').innerHTML);

situação > ativo

Portanto, se você realmente precisa dessa informação terá de obtê-la antes do texto do documento chegar ao browser como HTML: no lado servidor, por exemplo, ou - se estiver obtendo o texto via Ajax - analisando o texto antes de criar elementos com ele. Infelizmente isso implica em analisar o texto do HTML você mesmo, o que não é nada trivial... Talvez alguma biblioteca de parsing seja capaz de ao mesmo tempo tratar das entidades (de preferência reconhecendo todas que compõem a especificação) e preservar o conteúdo original das mesmas, mas de cabeça não conheço nenhuma (nem sei que em ambiente você está trabalhando).
Comment: ótima resposta, muito obrigado! estou usando PHP no servidor, como preciso que o comprimento das *strings* seja igual no servidor e cliente talvez a solução seja utilizar `html_entity_decode()` e `.textContent / .innerText`
Answer: apenas complementando, já que o conteúdo é obtido externamente, você pode requerer ele através de uma requisição ajax

var external = document.getElementById("external");
var innerHTML = document.getElementById("innerHTML");
var responseText = document.getElementById("responseText");

var blob = new Blob(["
situação > ativo
"], { type: "text/html" });
var url = URL.createObjectURL(blob);

var xmlHttp = new XMLHttpRequest();
xmlHttp.onreadystatechange=function()
{
    if (xmlHttp.readyState==4 && xmlHttp.status==200)
    {
        external.innerHTML = xmlHttp.responseText;
        innerHTML.value = external.innerHTML;
        responseText.value = xmlHttp.responseText;
    }
}

xmlHttp.open("GET", url, true);
xmlHttp.send("");
div {
    margin-bottom: 5px;
}

label {
    display: inline-block;
    width: 100px;
    text-align: right;
}

input {
    width: 400px;
}

    innerHTML:
    <input id="innerHTML" type="text" readonly />

    responseText:
    <input id="responseText" type="text" readonly />


System.Diagnostics.Debug.WriteLine in production code

Question: I should probably know this already, but I'm not sure and I don't see it documented.
I use System.Diagnostics.Debug.WriteLine quite often during the development process to be able to track changes to variables or exceptions as I'm debugging the code.  This is meant to make development and understanding what's happening easier only during development.  I normally either comment out the code or delete it when I go to production.
I'm wondering what happens if I forget to comment the code out.  Say, for example, that during the development cycle, I'm tracking error information that may log a connection sting to the output window using Debug.Write Line.  This is obviously OK while developing, but I'm wondering if when I go live, if there is a risk here.  Can someone attach a debugger to my live executable and trap this output?  Or is it something that only produces output in Visual Studio?
And what about when we switch from debug to release?  Does this code get ignored by the compiler if we compile for release?
Comment: Thank you all who answered.  @Phil Devaney, @Mitch Wheat, and @Agent_9191 all gave pretty much the same answer in different wording, so I'm voting you all up, but I can only accept one answer.  I'd go with who answered first, but that looks to be a tie betwee nMitch and Phil, so no offense, Mitch, but I'm going to give it to Phil, whose points are lower.
Comment: For others searching the following [Debug.WriteLine in release build](http://stackoverflow.com/questions/5419534/debug-writeline-in-release-build) may also prove interesting.
Answer: All the members in the Debug class are marked with ConditionalAttribute, so the call sites won't be compiled into a Release build.
Comment: I wish I had a dollar for every time a co-worker sent out a production installer with the Debug build in it.
Answer: System.Diagnostics.Debug method calls are only present when the "DEBUG" conditional compilation symbol is defined. By default, the "DEBUG" symbol is defined only for debug builds.

Compilers that support
  ConditionalAttribute ignore calls to
  these methods unless "DEBUG" is
  defined as a conditional compilation
  symbol.
Answer: Since the Debug methods all have the [Conditional("DEBUG")] attribute on them, if you switch from Debug to Release you will have not have to worry about it as the calls to those methods will be removed (along with the other optimizations of a Release build).
Comment: More specifically, don't define `DEBUG`. If you create a "Release" build (minimal symbols, optimized code, etc.) but define `DEBUG`, the `Debug` methods will still be called, right?
Answer: Debug information is only visible when you're running in Debug mode. In Release mode no Debug statements will be visible (you can use Trace instead of Debug if you want these statements to be visible in Release mode).
http://support.microsoft.com/kb/815788
Answer: Providing you compile without the /d:DEBUG option or #define DEBUG, your WriteLine calls will not physically present in your release code; there is no way for any third party to recover any information from these calls, as they literally not there in the release version.
More details here: Debug Class (System.Diagnostics) on MSDN
Answer: Almost all members of Debug are marked with ConditionalAttribute. Such compilers as C# will skip calls to those methods during Release build, so you are on the safe side.
Mode info here:
http://msdn.microsoft.com/en-us/library/system.diagnostics.debug.aspx


Webform Message / Custom Module

Question: I'm trying to create a custom module which will display a message after my webform. I know that in order to display a message, I could use the following code:
<code>$message = "Message here";
drupal_set_message(t($message));
</code>
But rather than having a specific message, I want to have a conditional message based on PHP if statements. E.g.,
<code>    if($class == A) {
    print "Correct!";
}
</code>
So, my question is how can I get the results of this PHP code to display on my webform? I'm not familiar with PHP code, so I don't know if I can combine the $message code with the if statement somehow. (I've tried variations of this with no success.)
Thanks for your help.
Comment: Please post more details to the question like what does your correct code looks like and are you able to show the static message using the above code? You can put the $message variable in the inside if block and change it based on the conditions and then put that $message in the drupal_set_message.
Comment: For your information, the proper way to pass a variable inside the `t()` function is to use a place holder. Ex: `drupal_set_message(t(@message', array('@message' => $message)));` For more info on how to properly use the `t()` function, see [DRUPAL CODE STANDARDS: THE T() FUNCTION](https://chromatichq.com/blog/drupal-code-standards-t-function)
Comment: `which will display a message after my webform` Are you referring to after the webform is submitted? or do you reefer to literally after (below) the webform?
Answer: One of the features and APIs of the Webform module for Drupal 8 that I personally enjoy using is support for inline messages using the WebformMessage element
The WebformMessage element supports dismissal messages and #states API.
Here is the YAML version of a Message element
<code>message:
  '#type': webform_message
  '#message_type': warning
  '#message_close': true,
  '#message_storage': user,
  '#message_message': 'This message can be dismissed by a user'
</code>
Here is the PHP syntax, which can be used in your custom code.
<code>$build['message'] = [
  '#type' => 'webform_message',
  '#message_id' => 'custom_message_id',
  '#message_type' => 'warning',
  '#message_close' => TRUE,
  '#message_storage' => WebformMessage::STORAGE_USER,
  '#message_message' => $this->t('This message can be dismissed by a user'),
];
</code>

Webform Message / Custom Module


Rewrite CCK field output without using templates

Question: The Views module has the nice option to rewrite the output of a field. This allows to adapt the output of CCK fields using Tokens without having to create a template for that view.
Is there a module that would allow a similar functionality for the "Display Fields" tab of a content type? I need to slightly modify the field output for teaser and body, but don't want to create a full template.
I'm currently using Contemplate for that, but that is more complicated than I need and unnecessary difficult if you're not familiar with the Drupal PHP API. It is also annoying that I need to modify the template every time I add an additional field to the content type, I really only need to rewrite a few fields, not the whole body or teaser.
So, what I would like to have is a simple way to rewrite each CCK field output using any token available for that content type. Does something like that exist?
Comment: You might be looking for the [Display Suite module](http://drupal.org/project/ds) which will give you the most control of formatting in D6. Here is a [demonstration video](http://www.vimeo.com/9214091).
Comment: The [Token Field](http://drupal.org/project/token_field) module lets you combine fields using their tokens.
Comment: I would use the [Token Filter](https://www.drupal.org/project/token_filter) module, to specify token values in CCK fields with input filters. Here is an excerpt about it from the module's project page: > ... a very simple module to make token values available as an input filter.
Answer: Sounds like you're looking for the Custom Formatters module, very similar to Contemplate, but specifically for create Field Formatters to be used via the Display Settings page or Views.
Custom Formatters can be built with both Tokens or pure PHP code.
Additionally, Custom Formatters can be exported as native Drupal Hooks or in a custom Features exportable format.
Answer: If you're just looking to tweak the markup, Semantic CCK is worth a try.

Semantic CCK was created to give users the means of customizing the HTML output of CCK fields. It was inspired in part by the highly recommended module Semantic Views which provides the same functionality for Views.
Drupal 7
A Drupal 7 version of Semantic CCK is currently under development: Semantic Fields.
Answer: Using the Contemplate module is not recommended, since it puts PHP code into the database, which is generally considered a security vulnerability and non-performant.
You may consider defining your own field formatters using hook_field_formatter_info(). This allows you to define custom callbacks that can handle each field.
Browse other modules' implementation of hook_field_formatter_info() to see how it works. In Drupal 6, it ties in directly with hook_theme() while Drupal 7 uses hook_field_formatter_view().
Answer: I've been fighting with this same issue for some time now too.
I can't / don't want to use...

Contemplate for mediocre architecture reasons.
Display Suite, which is awesome but overkill and doesn't actually allow simple alterations to fields.
Custom formatters, as it again ends up with PHP in the database for multiple value fields.
Field template because I'm just adding a line of text with the item.
Semantic CCK because that only alters the elements and classes.
hook_preprocess or another code based solutions because I need it configurable.

It's a real bummer, when all I need to do is add a CCK field description to display output. This should actually be rather simple.
Sounds like you needed Custom Formatters.
Comment: n/m this functionality was added to Semantic CCK 1.4
Comment: did you find a easy to handle solution that has a good performance? in drupal6 the good solution was often to use the ['view'] of the node object and combine it with some node template formatting. very clean output and comfortable because of the use of ['view'] in 90% of all use cases. in drupal 7 we have again the divities, because render() produces a lot of overhead ...
Comment: Sounds like Display Suite then http://drupal.org/project/ds
Comment: Custom Formatters does store information in the database, but the module is simply a utility, so once you've created the Formatter in the database you export it and you no longer have the issue of code in the database :)


Statistically comparing 3 groups - Test for statistical difference

Question: I will like to perform and statistical comparison between 3 groups, in order to determine if statistically they are different or not. My data for all of the 3 groups follows a normal distribution. I am aware that in order to test for statistical significance, one can use the t.test function in r; however, that only allows to compare two groups. So, I was wondering if there is test to test such statistical difference in these 3 groups that I have.
So far my code is the following:
groups<- read.csv("...",header=TRUE)
head(groups)
str(groups)
t.test(groups$ï..Group.A,groups$Group.B)

Output of str(groups)
> str(groups)
'data.frame':   20 obs. of  3 variables:
 $ ï..Group.A: num  0.16 -1.32 -0.409 0.128 0.844 ...
 $ Group.B   : num  0.1673 -0.1368 1.3216 -0.0506 0.1097 ...
 $ Group.C   : num  1.852 0.707 0.338 -0.327 1.109 ...

Thank you
Comment: See [this guide](http://www.sthda.com/english/wiki/comparing-means-in-r) and links within. You can use _e.g._`anova`, `kruskal.test`, `pairwise.t.test`.
Comment: No doubt there are many more duplicates on site
Comment: Just to point out , the question was asked first in Stack Overflow, then it was migrated to here. As my profile indicates, I am not a regular user of Cross Validated; however, I appreciate the answer. @Glen_b
Comment: The reference to more duplicates indicate that you can use the search feature to find additional information.
Answer: As mentioned by neilfws in the comments, you can use an ANOVA. Put the data in standard format, that is all the values in one columns, and create one variable which determines the group.
> summary(aov(mpg~factor(gear),data=mtcars))
             Df Sum Sq Mean Sq F value   Pr(>F)
factor(gear)  2  483.2  241.62    10.9 0.000295 ***
Residuals    29  642.8   22.17
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1


Can I find a good approximation of this function?

Question: I am wondering, if I can find a good approximant for this function
$$f(z)=\log \left[
\frac{1-z^2}{z \left(3-z^2\right)}\sinh \left\{\frac{z \left(3-z^2\right)}{1-z^2}\right\}\right]$$
assuming $z \in [0,1)$. A first naive approach would be to take the Taylor expension. But as this function has a pole at one I would have to take more and more terms into account as z takes values closer to one. Is there a suitable method to approximate this function over the whole interval?
EDIT: I add this plot to show the proposed assymptotics down below

But the basic question remains. Can I find a single function, that is a good approximant of $f$?
EDIT: Changed the plot to account for the small mistake.
Comment: What do you mean by "good" approximant -i.e. How many terms do you need? Have you tried splitting the expression up using laws of logs?
Comment: I have something like a Pade approximant in the back of my mind. A "good" approximant would be something that for no value of $z \in [0,1)$ returns a relative error of more than 5%and that most impotantly shows all the limiting features of the original function (for small z defined by the first Taylor expansion term and for z close to 1 defined by a diverging rational function ). To answer your question, I have not yet tried to split the logarithm.
Answer: For $z \rightarrow 0$ a taylor approximation is fine.
I leave this part to you.
For $z\rightarrow 1$ we may observe that the relevant contributions arise from the terms containing a $1-z^2$. The other contributions will only give finite corrections in this limit and can be approximated by their values at $z=1$ . Furthermore we observe that $\sinh(x)\sim \frac{e^x}{\bf2} $ as $x\rightarrow \infty$. Taken all this into account we may write
$$
\lim_{z\rightarrow 1_-}f(z)\sim \log\left(\frac{1-z^2}{2}\frac{e^{\frac{2}{1-z^2}}}{{\bf2}}\right)=\frac{2}{1-z^2}+\log(1-z^2)-\log(4)
$$
Edit:
A forgotten $\frac{1}{\bf2}$ was inserted. Now the graph looks even better!
Comment: Thank you very much, this is a great explanation of the assymptotics. Can I derive from it a simple closed form of an approximant that is valid over the whole interval $[0,1)$? Let me add the first taylor expansion terms: $$f(z)=\frac{3}{2}z^2+\frac{31}{20}z^4+\mathcal{O}(z^6)$$
Comment: I added a plot to the original post showing the two limiting behavior, but also stated that my acceptance of the answer may have been premature.
Comment: The last comment I don't understand: $$\frac{3-z^2}{1-z^2}+\log \left(1-z^2\right)-\log (4)$$ does not give a good approximation when I plot it against $f(z)$. Am I missing something?
Comment: Unfortunatly plotting this it does not match the original functions graph very well.
Comment: Sorry i'm a little bit unconcentrated today. I will work out this part correctly when i feel better
Comment: Because so far we only have the limiting behaviors. I would like to find one function (probably a rational function), that approximates the whole function $f$ over the intervall $(0;1)$.


Create varies string vectors, and using iterator to change those strings to uppercase

Question: I'm new to C++. I'm trying to solve a problem which goes something like this:

Q: create varies string vectors, and using iterator to change those strings to uppercase.

Below is the code I came up with. However, the IDE always output error. Because I'm new to C++, I don't have enough knowledge to fix the problem.
#include <iostream>
#include <string>
#include <vector>
#include <iterator>
using namespace std;

void checkAndPrint(vector<string> &vec) {
    cout << "content: [";
    for (auto it = vec.begin(); it != vec.end(); ++it) {
        for (char c : it) {
            c = toupper(c);
            cout << c;
        }
    }
    cout << "]\n" << endl;
}

int main() {

    vector<string> s1;
    vector<string> s2(10);
    vector<string> s3(10, "hello");
    vector<string> s4{10, "world"};
    vector<string> s5{"good", "morning"};
    vector<string> s6{10, "10"};

    checkAndPrint(s1);
    checkAndPrint(s2);
    checkAndPrint(s3);
    checkAndPrint(s4);
    checkAndPrint(s5);
    checkAndPrint(s6);
}

Error:
error: invalid range expression of type 'std::__1::__wrap_iter<std::__1::basic_string<char> *>'; did you mean to dereference it with '*'?
        for (char c : it) {
                      ^
                      *

Comment: P.P.S: *did you mean to dereference it with '*'?* listen to your compiler.
Comment: It would be great if you gave us the actual error and indicated which line its from... (P.S: I'm curious as to why you used a foreach loop on the string, but a "regular" for loop on the vector)
Comment: That is an impressively clear error message, compared to what [gcc produces](http://coliru.stacked-crooked.com/a/bebfe741c5f7312d).
Answer: You need to dereference the iterator:
for (char c : *it)

or use a second range for loop:
for (auto &v : vec) {
    for (char c : v) { ...

Also note that currently you are not modifying the original vectors as
for (char c : *it)

operates on copies of the original chars. To fix that, iterate over references instead, i.e.
for (char &c : *it)

Lastly, note that you should add a cast as in Do I need to cast to unsigned char before calling toupper? You also forgot to #include <cctype> which provides toupper.
Answer: it is the iterator, not the string itself. It's essentially a pointer to a string that changes which string it points to for each iteration, so you have to dereference it before you can access each character in the for loop:
for (char c : it) {

should become:
for (char c : *it) {

Additionally, if you want the strings themselves to be updated so that they're uppercased, you need to use a char reference in the second for loop, like so:
for (char& c : *it) {

The way you have it right now, you're changing a new variable c (a copy, essentially) that won't be reflected in the original string. Using a char reference will let you mutate the characters in the original string.
Comment: @dzjustinli, it's only through pain that we mortals can hope to become familiar enough with them to not make mistakes -- it gets better with time. I will second Baum mit Augen's suggestion here to use a non-iterator loop for your first `for` loop. It lets you get away with not having to deal with pointers at all, and only references.
Comment: Thank you so much for your help!! pointers and reference are so confusing lol


Dot product angles greater than 180

Question: Am I correct in saying that the angle in a dot product can't exceed or be 180 because the angle is based on the law of cosines?
Comment: Dot product doesn't have much to do with laws of cosines. The angle between two vectors can take any value from zero to 360°. It is just convenient to take value less than 180°.
Comment: "The angle in the dot product" What angle is that? The angle between two vectors is almost always measured as angle angle from $0$ to $\pi$ radians (0 to 180 degrees) but it could be any value, including negative.
Answer: Ah, the situation is that the dot product unambiguously computes the cosine of the angle between the vectors. It does not at all directly compute the angle itself... for which there would indeed be ambiguity or an issue of definition/convention, as you speculate. That is, the dot product computes
a value $c$, and it's up to you to decide how to determine an angle $\theta$ such that $\cos \theta = c$. (Yes, I know, many textbooks authoritatively declare that $\cos^{-1}$ takes values in a certain range, but that's just convention, not a mathematical fact: $\cos^{-1}$ is multi-valued...)
Answer: Let's take two vectors, $a,b \in \mathbb{R^2}$, as you've pointed out:
$a\cdot b = b\cdot a= a_1b_1+a_2b_2 = |a||b|\cos \theta \implies \theta = \arccos \left(\frac{a\cdot b}{ |a||b|}\right) \in [0,\pi]$
Concretely, if $a=[1,0],\;b=[1,1]$ then $|a|=1,\;|b|=\sqrt{2}\;$ and we get
$a\cdot b = 1 \implies \theta = \arccos\left(\frac{1}{\sqrt{2}}\right) = \frac{\pi}{4} \text{rad}$ or $45\deg$ -- this is the smaller of the two possible angles, with the other being $\frac{7\pi}{4}$ or $315 \deg$.
So we can see that the above formula for $\theta$ will give us the smallest unsigned angle between the vectors. As given by the other answer, this a bit of convention.
Answer: One common approach:
First, define $\arccos$ to be the inverse of $\cos|_{[0,\pi]}=\cos|_{[0,180^\circ]}$ (the restriction of $\cos$ to $[0,\pi]=[0,180^\circ]$, i.e. the function that is the same as $\cos$ but with that domain).
Next, define the angle between two vectors $\mathbf u$ and $\mathbf v$ to be $\arccos \frac{\mathbf u \cdot \mathbf v}{|\mathbf u||\mathbf v|}$. (This definition can indeed be motivated by the Law of Cosines.)
Now, so defined, any angle will indeed be in $[0,\pi]=[0,180^\circ]$.

Dot product angles greater than 180


Did Eric Moussambani go to the semi-finals in Sydney?

Question: In the 2000 Summer Olympics in Sydney, Eric Moussambani, from Equatorial Guinea, was invited to the games under an IOC program that allows smaller countries to compete without meeting qualifying standards. He swam his 100m Freestyle heat in a heroic 1:52.72, and won, due to false starts from his competitors. Why didn't he go on to compete in the semi-finals? Did he opt out, or was this program essentially for exhibition only?
Answer: As you can see from the results, there was no "winner of every heat qualifies" rule; it was simply the fastest 16 swimmers which went through to the semi-finals - note how all the semi-final qualifiers came from heats 7, 8, 9 and 10 (which were loaded to have the fastest swimmers).
You could view this as being a exhibition heat, as there was no realistic chance that anyone from it was going to get into the semi-finals - however, you could also argue that it was better for the sport to have Moussambani competing against swimmers closer to his skill level, rather than tailing in very, very last against some of the best swimmers in the world.


code crashes after exit?

Question: for whatever reason my code crashes but only AFTER I exit out of the program (by hitting "X") anyone know why it is doing this? here is my code.
#include <iostream>
#include <cstring>
#include <cstdlib>
#include <windows.h>
#include <time.h>

#include <SDL/SDL.h>
#include <GL/gl.h>
#include <GL/glu.h>
#include <GL/glext.h>
using namespace std;

/*
const int AIR = 0;
const int STONE = 1;
const int DIRT = 3;
const int GRASS = 4;
*/

float SCALE = .5;
const int chunkSize = 16;
const int chunkSizeY = 256;
const int blocksTotal = 4;
int chunk[chunkSize][chunkSizeY][chunkSize];
time_t seconds;
int seed = 0;
int quads;

struct block {
  bool Solid;
  int DepthMAX;
  int DepthMIN;
  int R;
  int G;
  int B;
  int id;
} AIR, STONE, DIRT, GRASS;

    block * blockType = new block[3];

void buildChunk();
void renderChunk();
void countFaces();
void render();
void logic();

void drawCube(float size,int x,int y,int z,float redValue,float greenValue,float blueValue)
{

    float halfSize = size / 2;
    float xSize = x * size;
    float ySize = y * size;
    float zSize = z * size;

    glBegin(GL_QUADS);
glColor3f(redValue,greenValue,blueValue);

///     front face
    if(z+1 < chunkSize)
    {
        if(chunk[x][y][z+1] == AIR.id)
        {
            // front face
            glNormal3f(0.0,0.0,1.0);
    //glColor3f(0,200,255);
    glTexCoord2f(1.0,1.0);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
    glTexCoord2f(0.0,1.0);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
    glTexCoord2f(0.0,0.0);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
    glTexCoord2f(1.0,0.0);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
                quads++;

        }
    }
    else
    {
        //glColor3f(1,0,0);
        if(z+1 >= chunkSize)
        {
            glNormal3f(0.0,0.0,1.0);
    //glColor3f(0,200,255);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
                quads++;
        }
    }

    // left face
    if(x-1 > -1)
    {
        if(chunk[x-1][y][z] == AIR.id)
        {
            //glColor3f(0.0,1.0,0.0);
            glNormal3f(-1.0,0.0,0.0);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
            quads++;
        }
    }
    else
    {
        //glColor3f(1,1,1);
        if(x-1 < 0)
        {
            glNormal3f(-1.0,0.0,0.0);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
            quads++;
        }
    }

    // back face

    if(z-1 > -1)
    {
        if(chunk[x][y][z-1] == AIR.id)
        {
            //glColor3f(0.0,0.0,1.0);
            glNormal3f(0.0,0.0,-1.0);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
            quads++;
        }
    }
    else
    {
        //glColor3f(0,1,1);
        if(z-1 < 0)
        {
            glNormal3f(0.0,0.0,-1.0);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
            glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
            quads++;
        }
    }

    // right face
    if(x+1 < chunkSize)
    {
        if(chunk[x+1][y][z] == AIR.id)
        {
            //glColor3f(1.0,1.0,0.0);
            glNormal3f(1.0,0.0,0.0);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
            quads++;
        }
    }
    else
    {
        //glColor3f(0,1,0);
        if(x+1 >= chunkSize)
        {
            glNormal3f(1.0,0.0,0.0);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
            glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
            glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
            quads++;      }
    }

    // top face
    if(y+1 < chunkSizeY)
    {
        if(chunk[x][y+1][z] == AIR.id)
        {
    //glColor3f(1.0,0.0,1.0);
    glNormal3f(0.0,1.0,0.0);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
    quads++;
        }
    }else
    {
        //glColor3f(0,1,0);
        if(y+1 >= chunkSizeY)
        {
glNormal3f(0.0,1.0,0.0);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize + halfSize, zSize - halfSize);
    glVertex3f(xSize + halfSize, ySize + halfSize, zSize - halfSize);
    quads++;
        }
    }
    // bottom face
    if(y-1 > -1)
    {
        if(chunk[x][y-1][z] == AIR.id)
        {
    //glColor3f(0.0,1.0,1.0);
    glNormal3f(0.0,-1.0,0.0);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
    quads++;
        }
    }else
    {
        //glColor3f(1,1,1);
        if(y-1 < 0)
        {
    glNormal3f(0.0,-1.0,0.0);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize + halfSize);
    glVertex3f(xSize - halfSize, ySize - halfSize, zSize - halfSize);
    glVertex3f(xSize + halfSize, ySize - halfSize, zSize - halfSize);
    quads++;
        }
    }

    glEnd();
}
float angle = 0.0;
const int triangle = 1;

void init()
{
    //AIR
blockType[0].id = 0;
blockType[0].R = 0;
blockType[0].G = 0;
blockType[0].B = 0;
    //STONE
blockType[1].id = 1;
blockType[1].R = 0;
blockType[1].G = 0;
blockType[1].B = 1;
blockType[1].DepthMAX = 5;
blockType[1].DepthMIN = 0;
    //DIRT
blockType[2].id = 2;
blockType[2].R = 1;
blockType[2].G = 0;
blockType[2].B = 0;
blockType[2].DepthMAX = 10;
blockType[2].DepthMIN = 6;
    //GRASS
blockType[3].id = 3;
blockType[3].R = 0;
blockType[3].G = 1;
blockType[3].B = 0;
blockType[3].DepthMAX = 20;
blockType[3].DepthMIN = 11;

AIR.Solid = false;
AIR.id = 0;
STONE.id = 1;
DIRT.id = 2;
GRASS.id = 3;

    seconds = time (NULL);
    seed = seconds;
    srand(seed);
    /* Seed the random number generator with the specified seed */

    glClearColor(0.0,0.0,0.0,1.0);  //background color and alpha
    glMatrixMode(GL_PROJECTION);
    glLoadIdentity();
    gluPerspective(45,640.0/480.0,1.0,500.0);
    glMatrixMode(GL_MODELVIEW);
    glEnable(GL_DEPTH_TEST);
    glEnable(GL_COLOR_MATERIAL);
        glEnable(GL_LIGHTING);
        glEnable(GL_LIGHT0);
        float dif[] = {1.0,1.0,1.0,1.0};
        glLightfv(GL_LIGHT0, GL_DIFFUSE, dif);
        float amb[] = {0.2,0.2,0.2,1.0};
        glLightfv(GL_LIGHT0, GL_AMBIENT, amb);

    buildChunk();
}

void render()
{

    glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
    glLoadIdentity();
        float pos[] = {-2.0,2.0,-3.0,1.0};
        glLightfv(GL_LIGHT0, GL_POSITION, pos);
    glTranslatef(0.0,0.0,-40.0);
    glRotatef(angle,1.0,0.0,0.0);   // angle, x-axis, y-axis, z-axis
    renderChunk();

}

int main(int argc, char** argv)
{
    SDL_Init(SDL_INIT_EVERYTHING);
    SDL_Surface *screen;
    screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE|SDL_OPENGL);
//     screen = SDL_SetVideoMode(640, 480, 8, SDL_SWSURFACE|SDL_FULLSCREEN);
    bool running = true;
    const int FPS = 30;
    Uint32 start;
    SDL_Event event;
    init();
    while(running)
    {
        start = SDL_GetTicks();
        while(SDL_PollEvent(&event))
        {
            switch(event.type)
            {
            case SDL_QUIT:
                running = false;
                break;
            }
        }

        logic();
        quads = 0;
        render();

        SDL_GL_SwapBuffers();
        angle += 0.5;
        if(angle > 360)
            angle -= 360;
        if(1000/FPS > SDL_GetTicks()-start)
            SDL_Delay(1000/FPS-(SDL_GetTicks()-start));
    }

    countFaces();
    cout << "QUADS: " << quads << endl;
    cout<<"vertics: " << quads * 4 << endl;

delete [] blockType;
    SDL_Quit();
    return 0;
}

void buildChunk()
{

    int x;
    int y;
    int z;

    for(x=0; x < chunkSize; x++)
    {
        for(y=0; y < chunkSizeY; y++)
        {
            for(z=0; z < chunkSize; z++)
            {

                /* 50% chance for a cell to be alive */
                if(rand() % 100 < 50)
                {
                    chunk[x][y][z] = AIR.id;
                }
                else
                {
                    for(int i=1; i < blocksTotal; i++){
                    if(y <= blockType[i].DepthMAX && y >= blockType[i].DepthMIN){
                            chunk[x][y][z] = blockType[i].id;
                        }

                    }
                }
                cout<< "chunk[" << x << "][" << y << "][" << z << "]  state: " << chunk[x][y][z]<<endl;
            }
        }
    }
}

void renderChunk()
{
    int x;
    int y;
    int z;

    for(x=0; x < chunkSize; x++)
    {
        for(y=0; y < chunkSizeY; y++)
        {
            for(z=0; z < chunkSize; z++)
            {

                if(chunk[x][y][z] != blockType[0].id)
                {
                    for(int i=1; i < blocksTotal; i++){
                    if(chunk[x][y][z] == blockType[i].id)
                    {
                        drawCube(SCALE,x,y,z,blockType[i].R,blockType[i].G,blockType[i].B);

                        }
                    }
                }

            }
        }
    }
}

void logic()
{

}

void countFaces()
{

}

I think it might have something to do with the struct array I added and deleted?
Comment: 1. Way too much code for us to debug on your behalf. 2. Use `valgrind`.
Comment: Narrow the problem down to a small reproducible case, and post that.
Comment: And you tried running the program in a debugger?
Comment: Global variables are evil
Answer: You allocate space for three elements:
block * blockType = new block[3];

but then access four:
    //AIR
blockType[0].id = 0;
...
    //STONE
blockType[1].id = 1;
...
    //DIRT
blockType[2].id = 2;
...
    //GRASS
blockType[3].id = 3;
...

This results in memory corruption (technically, undefined behaviour).
The new should read
block * blockType = new block[4];

code crashes after exit?


Documentation file is not copied on tfs build server

Question: I have an xml file that is created from code documentation. Xml file is in source control and it is in root of my project. This is .csproj:
<code>    <Project Sdk="Microsoft.NET.Sdk.Web">

  <PropertyGroup Label="Globals">
    <SccProjectName>SAK</SccProjectName>
    <SccProvider>SAK</SccProvider>
    <SccAuxPath>SAK</SccAuxPath>
    <SccLocalPath>SAK</SccLocalPath>
  </PropertyGroup>

  <PropertyGroup>
    <TargetFramework>netcoreapp1.1</TargetFramework>
    <PreserveCompilationContext>true</PreserveCompilationContext>
    <PackageTargetFallback>portable-net45+win8</PackageTargetFallback>
  </PropertyGroup>

  <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|AnyCPU'">
    <DocumentationFile>bin\Debug\netcoreapp1.1\Api.xml</DocumentationFile>
  </PropertyGroup>

  <Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <ItemGroup>
      <DocFile Include="bin\*\*\Api.xml" />
    </ItemGroup>

    <Copy SourceFiles="@(DocFile)" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="false" />
  </Target>

  <ItemGroup>
    <Compile Remove="wwwroot\**" />
    <Content Remove="wwwroot\**" />
    <EmbeddedResource Remove="wwwroot\**" />
    <None Remove="wwwroot\**" />
  </ItemGroup>

  <ItemGroup>
    <None Remove="identityserver4_log.txt" />
  </ItemGroup>

  <ItemGroup>
    <Content Include="Api.xml">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
    </Content>
  </ItemGroup>
  <ItemGroup>
    <PackageReference Include="AutoMapper" Version="6.0.2" />
    <PackageReference Include="AutoMapper.Extensions.Microsoft.DependencyInjection" Version="2.0.1" />
    <PackageReference Include="Carable.Swashbuckle.AspNetCore.DocumentWithCode" Version="0.0.4" />
    <PackageReference Include="Castle.Core" Version="4.1.1" />
    <PackageReference Include="FluentValidation.AspNetCore" Version="7.0.2" />
    <PackageReference Include="IdentityServer4" Version="1.5.2" />
    <PackageReference Include="IdentityServer4.AccessTokenValidation" Version="1.2.1" />
    <PackageReference Include="Microsoft.ApplicationInsights.AspNetCore" Version="2.0.0" />
    <PackageReference Include="Microsoft.AspNetCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Identity" Version="1.1.2" />
    <PackageReference Include="Microsoft.AspNetCore.Mvc" Version="1.1.3" />
    <PackageReference Include="Microsoft.AspNetCore.StaticFiles" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.SqlServer.Design" Version="1.1.2" />
    <PackageReference Include="Microsoft.EntityFrameworkCore.Tools" Version="1.1.1" />
    <PackageReference Include="Microsoft.Extensions.Logging" Version="1.1.2" />
    <PackageReference Include="Microsoft.Extensions.Logging.Debug" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.BrowserLink" Version="1.1.2" />
    <PackageReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Design" Version="1.1.1" />
    <PackageReference Include="Serilog.Extensions.Logging" Version="1.4.0" />
    <PackageReference Include="Serilog.Extensions.Logging.ApplicationInsights" Version="1.1.0" />
    <PackageReference Include="StructureMap.Microsoft.DependencyInjection" Version="1.3.0" />
  </ItemGroup>
  <ItemGroup>
    <DotNetCliToolReference Include="Microsoft.VisualStudio.Web.CodeGeneration.Tools" Version="1.0.0" />
    <DotNetCliToolReference Include="Microsoft.EntityFrameworkCore.Tools.DotNet" Version="1.0.0" />
  </ItemGroup>
  <ItemGroup>
    <WCFMetadata Include="Connected Services" />
  </ItemGroup>
  <ItemGroup>
    <Folder Include="Views\Default\" />
  </ItemGroup>
  <ItemGroup>
    <ProjectReference Include="..\Api.Business\Api.Business.csproj" />
  </ItemGroup>

</Project>
</code>
The file is not copied to wwwroot on my azure webapp. What do I have to set up?
Answer: In the main section, ensure the documentation file gets generated:
<code>  <GenerateDocumentationFile>true</GenerateDocumentationFile>
</code>
You can try to specify the absolute path for the documentation file.
Reference below sample:
<code><Target Name="PrepublishScript" BeforeTargets="PrepareForPublish">
    <ItemGroup>
      <DocFile Include="bin\$(Configuration)\$(TargetFramework)\Api.xml" />
    </ItemGroup>
    <Copy SourceFiles="@(DocFile)" DestinationFolder="$(PublishDir)" SkipUnchangedFiles="false" />
  </Target>
</code>
More information please refer to this GitHub discussions: https://github.com/dotnet/sdk/issues/795
You can also try the solutions mentioned in this copydocfile-example.
Comment: net core throws an error for GenerateDocumentationFile in .csproj.
Comment: @AmelSalibasic What kind of the error? Could you please share the error messages here for further troubleshooting?
Comment: It says element not recognised
Comment: @AmelSalibasic Could you share the details steps to reproduce the issue? then we can do further troubleshoot accordingly.


Scrapy não consegue selecionar um form usando xpath

Question: Olá, estou utilizando o scrapy para fazer um crawler para conseguir pegar questões de concuros e etc do site gabarite.com.br, eu consigo pegar a descrição da pergunta a alternativa correta, porém não consigo pegar a alternativas sempre que executo no terminal o retorno das alternativas e nulo, não sei como proceder poderiam me ajudar?
        # -*- coding: utf-8 -*-
        import scrapy
        import re
        from enemGrabData.items import EnemgrabdataItem
        class MultipleSpider(scrapy.Spider):
            name = 'multiple'
            allowed_domains = ['www.gabarite.com.br']
            start_urls = ['http://www.gabarite.com.br/questoes-de-concursos/disciplina/1-portugues']
            # html body div.site div#content
            def parse(self, response):

                conteudo = response.xpath('//*[@id="content_questoes_conteudo"]')
                item = EnemgrabdataItem();
                for questao in conteudo.xpath('ul'):
                    item['pergunta'] = questao.xpath('li[4]/text()').extract()
                    item['alternativa_A'] = questao.xpath('form/li/fieldset').extract()
                    # //*[@id="content_questoes_conteudo"]/ul[10]/form/li/fieldset
                    item['alternativa_B'] = questao.xpath('/form/li/fieldset/label[2]/text()').extract()
                    item['alternativa_C'] = questao.xpath('/form/li/fieldset/label[3]/text()').extract()
                    item['alternativa_D'] = questao.xpath('/form/li/fieldset/label[4]/text()').extract()
                    item['alternativa_E'] = questao.xpath('/form/li/fieldset/label[5]/text()').extract()
                    item['alternativaCorreta'] = questao.xpath('//form/button/@onclick').extract()
                    inputString = str(item['alternativaCorreta']).split("checaquestao",1)[1]
                    item['alternativaCorreta'] = str(inputString).split(',')[1]

                    # re.findall(r"\(u'(.*?)',\)", inputString)[0]
                       yield item

Questão 5104.   Português - Nível Superior - Polícia Militar GO - UEG - 2013

 Texto anexado à questão

A expressão "tais como" (linha 3) tem, no texto, a função de introduzir uma

            <form name="form-questoes">

                    <fieldset>
                    <input id="a5104" type="radio" name="radio5104" value="a">a) concessão
                    <input id="b5104" type="radio" name="radio5104" value="b">b) exemplificação
                    <input id="c5104" type="radio" name="radio5104" value="c">c) conclusão
                    <input id="d5104" type="radio" name="radio5104" value="d">d) exceção

                    </fieldset>

                <button title="Gabarito com resposta certa." name="botao5104" class="btn" type="button" onclick="checaquestao(5104,'b','mult-escolha')">Resolver questão</button>

            </form>

Comentar questão

0 comentários

Notificar erro

Answer: Creio que este exemplo seja útil para você. Não abordei todos os casos possíveis. Há questões de certo e errado que não cheguei a testar. Mas como o seu problema era pegar as alternativas, este exemplo deve lhe dar uma boa idéia de como prosseguir. A identificação da última página está baseada na não existência do botão 'Última'. É uma verificação meio fraca mas serve como exemplo.
# -*- coding: utf-8 -*-
from lxml import html

def parse(tree):
    conteudo = tree.xpath('//*[@id="content_questoes_conteudo"]')[0]
    forms = conteudo.xpath('form')
    for idx, questao in enumerate(conteudo.xpath('ul')):
        item = {}
        if len(questao.xpath('li[@class="numero"]')):
            item['questao'] = questao.xpath('li[@class="numero"]')[0].text_content()

        if len(questao.xpath('li[@class="texto"]')):
            item['texto'] = questao.xpath('li[@class="texto"]')[0].text_content()

        if len(questao.xpath('li[@class="pergunta"]')):
            item['pergunta'] = questao.xpath('li[@class="pergunta"]')[0].text_content()

        alternativas = forms[idx].xpath('li/fieldset/label')

        item['alternativa_A'] = alternativas[0].text if len(alternativas) > 0 else ''
        item['alternativa_B'] = alternativas[1].text if len(alternativas) > 1 else ''
        item['alternativa_C'] = alternativas[2].text if len(alternativas) > 2 else ''
        item['alternativa_D'] = alternativas[3].text if len(alternativas) > 3 else ''
        item['alternativa_E'] = alternativas[4].text if len(alternativas) > 4 else ''

        item['alternativaCorreta'] = forms[idx].xpath('button/@onclick')[0]
        inputString = str(item['alternativaCorreta']).split("checaquestao", 1)[1]
        item['alternativaCorreta'] = str(inputString).split(',')[1]

        yield item

template_url = "http://www.gabarite.com.br/questoes-de-concursos/?id_materia={}&id_categoria=&nivel=&orgao=&assunto=&pagina={}"

possui_mais_paginas = True
pagina_atual = 1
id_materia = 1  # portugues

while possui_mais_paginas:
    possui_mais_paginas = False  # chuta que é a ultima pagina

    tree = html.parse(template_url.format(id_materia, pagina_atual))

    for item in parse(tree):
        print(item['alternativa_A'].strip())

    encontrou_botao_ultima = False
    for link in tree.xpath('//*[@id="content_paginacao"]/a'):
        if 'Última' in link.text:
            possui_mais_paginas = True  # se não é a ultima página vai para a proxima
            pagina_atual += 1

Comment: Como eu poderia dizer ao agoritimo para ir a proxima página, no scrapy e feito com duas linhas, tentei nesse código que você me passou importando as libs mas não deu certo ate agora
Comment: Editei para incluir a paginação e a passagem de parâmetros como, matéria. Espero que ajude. De qualquer forma, você também pode editar seu código no scrapy e incluir as consultas xpath que utillizei no meu. Deve funcionar talvez com pequenas adaptações.
Comment: Consegui através do seu exemplo deu para fazer usando o scrapy, obrigado pela ajuda, se quiser ver como ficou deixo o link https://github.com/jpaulo789b/Crawler-Quest-es-Enem/blob/master/indo/spiders/spiderquestoes.py


Trigger cascade DELETE without deleting record

Question: I would like to perform a sort of factory reset of a User record. Is there some way of triggering the cascading delete without actually deleting the user record?
Answer: Copy the record to a temporary table, delete the original record, then copy the record back from the temporary.
<code>CREATE TEMPORARY TABLE tempUser
AS SELECT * FROM User WHERE id = :idToReset;

DELETE FROM User WHERE id = :idToReset;

INSERT INTO User
SELECT * FROM tempUser;
</code>
Comment: This seems to be a great solution. I live on the API/front-end world and the concept of a temporary table slipped my mind. I think that I'll put this into a stored proc and execute it with a single RESTful call.  Thanks for the help!


Estimate Poisson mean with partial data?

Question: I would like to estimate Poisson means from data sets where means are usually in the range 0.5 to 10.  0 (zeros) in the data are unambiguous; estimates of higher-event numbers degrade in rough proportion to the number of events.
This R code is a reasonable data simulator:
<code>data<-rpois(100, 1.5)
datasim <- function (x, upto = 6) {
 counts <- matrix(nrow = (upto+1), ncol = 2)
 for (i in 1:(upto+1)) {
    counts[i,1] <- i-1
    counts[i,2] <- length(which(x==i-1))
 }
return(counts)
}
simdata<-datasim(data, upto=3)

> simdata
     [,1] [,2]
[1,]    0   19
[2,]    1   42
[3,]    2   19
[4,]    3   10
</code>
In general: if I have a subset of event counts, how can I estimate the Poisson mean and CI?  I've looked at 'fitdistr', glm's, Poisson.exact, etc. but I haven't found a solution to this problem - I'd like to assure myself that the solution explicitly recognizes that some events are excluded from the data, and that the number of excluded data are known - that n=100 in the example.
Comment: To restate the question somewhat, in an attempt to make sure I understand it, you have a bunch of Poisson data that's censored at some number (either known or unknown), and you know how many observations were censored, and you'd like to estimate the mean taking the censorship into account?
Comment: If you don't know how many observations are 'lost' you move from censoring to truncation. But "estimates of higher event numbers degrade" sounds different from both censoring and truncation.
Comment: The number of observations are known; what is uncertain is whether an observation is, say, 4 events or 5 events, and the distinction is more uncertain at the higher event number.  For the simulated data in the example, it would be feasible to use the given data as observed as well as specify 10 observations at greater than or equal to 4 events.  So I think censored, not truncated, is appropriate.  Thanks for terminological clarification.
Answer: For a censored Poisson you can use the UWSE. In particular, for your example, the vector of sets $ (\left\{0\right\},\left\{1\right\},\left\{2\right\},\left\{3\right\}) $ generates a unique weight vector. So, according to the explanation  here: https://paradsp.wordpress.com/ (bottom of site), a consistent estimate is:
$$ \hat{\lambda_{UWSE}} = \min_{\lambda > 0}||(e^{-\lambda},\lambda e^{-\lambda},\frac{\lambda^2e^{-\lambda}}{2},\frac{\lambda^3e^{-\lambda}}{6} ) - (\hat{w_{0}},\hat{w_{1}} ,\hat{w_{2}},\hat{w_{3}})||_2 $$
where $\hat{w_{0}},\hat{w_{1}} ,\hat{w_{2}},\hat{w_{3}} $ are the relative frequencies of the obervations $ 0,1,2,3 $ respectively. For the data given in the example: $\hat{w_{0}}= 0.19,\hat{w_{1}} = 0.42 ,\hat{w_{2}} = 0.19,\hat{w_{3}} = 0.10 $. Computing this numerically in R, I get:
$$ \hat{\lambda_{UWSE}} = 1.47$$
which is quite close to the true value of $ 1.5 $.
If you want a quick closed form solution ,but trading off for some accuracy, choosing the set $\left\{0\right\} $ is enough to generate a unique weight. Then:
$$ \hat{\lambda_{UWSE}} = -ln(\hat{w_{0}}) = 1.66 $$
which is a bit further off.


Inverse of a non-negative matrix

Question: Under what conditions, if all elements of a positive definite matrix are non-negative implies that its inverse also only has non-negative elements.
How do you approach this?
Comment: Hint: for $2\times 2$ matrices, it is easily seen to be equivalent to $A$ diagonal.
Answer: Hint: If a non-negative matrix $A$ has $a_{ij} > 0$ with
$i \ne j$, and a non-negative matrix $B$ has all its diagonal
elements strictly positive, then $(AB)_{ij} \ge a_{ij} b_{jj} > 0$.

Inverse of a non-negative matrix


How to interpret intercept in linear mixed effects with two categorical predictors with three levels?

Question: I'm having a bit of a hard time interpreting the results of this linear mixed-effects model:
happy_prob ~ height_shuffle * height_original + (1 | template)

Where height_shuffle and height_original are two categorical variables with three levels (high, mid, low) referring to vowel height (e.g., /i/ is high while /a/ is low).
Fixed effects:
                                       Estimate Std. Error         df t value Pr(>|t|)
(Intercept)                           4.993e-02  5.475e-03  8.349e+02   9.119   <2e-16
height_shufflelow                    -2.762e-03  3.203e-03  4.692e+03  -0.863   0.3885
height_shufflemid                    -9.682e-04  5.184e-03  4.727e+03  -0.187   0.8519
height_originallow                   -3.693e-03  7.857e-03  5.312e+02  -0.470   0.6386
height_originalmid                    8.528e-04  5.643e-03  3.857e+02   0.151   0.8800
height_shufflemid:height_originallow  1.273e-02  7.346e-03  4.737e+03   1.733   0.0831

I'm not really getting how to interpret the intercept. What I am trying to understand is whether shuffling a vowel in a name predicts happiness as a function of the original vowel. Now given that the shuffling follows a logic, if this is the case, then it means that vowel height plays a role. In addition to that, I am considering the template of the word as a random effect.
What I am not getting is how I should interpret the reference group since there are three levels in both categorical variables. For example, is it my intercept height_shuffle_high:height_original_high?
Answer: The intercept is the expected value when both categorical variables are set at their 'reference' level. The choice of reference level is done by your stats program if you don't specify it. R chooses it based on alphabetical order, so 'high' is the reference level for both variables because h(igh) comes before l(ow) and m(id). It's possible to change this reference to anything you desire but it doesn't really matter (especially if you plot your model output to understand it, which I recommend).
In this case, the intercept therefore represents the expected value when height_shuffle = high and height_original = high.
Note that there's nothing specific to mixed models here, this applies to standard regression as well.
Comment: Yes, you're right. I will add a separate question. I was thinking that maybe I could start by showing only some templates to get an idea. Let's see if someone has a better idea. Thanks again!
Comment: Thank you for your answer! I am struggling a bit with visualizing the results since I have 258 nested groups (the template). Do you recommend anything?
Comment: @MarcoB That does sound tricky, and I'm not sure there is a great solution. I would start by visualising the fixed effects and random effects separately.
Comment: @MarcoB But that sounds like a worthwhile question in itself - why don't you post it as a new one? Ideally with a reproducible example.


Google traslate API request sample for did you mean

Question: When I select a input language and type some word (as it pronounce). It gives a 'Did you mean' options. How can I get this option as a response from Google cloud translate API?

Please take a look on below image.
https://i.stack.imgur.com/I29AP.png
Comment: Possible duplicate of [Does google allow businesses to use "Did you Mean" feature as an api?? I would like to use it but I am not getting anything](https://stackoverflow.com/questions/40260655/does-google-allow-businesses-to-use-did-you-mean-feature-as-an-api-i-would-l)
Comment: Have you checked the documentation to see if its supported?
Answer: Not for Google Translate, but you can use SerpApi Spell Check API. It extract Google "Did you mean?" from regular searches.
JSON should be structured that way. Assuming a search for "Coffeee":
<code>  "search_information":
    {
      ...
      "query_displayed": "coffeee",
      "spelling_fix": "coffee",
      "showing_results_for": "coffee"
    },
  ...
</code>
Documentation: https://serpapi.com/spell-check


Display Youtube videos in a gallery of thumbnails with a primary player

Question: I'd like to be able to display a gallery of youtube video thumbnails underneath a primary Youtube video "player" area. When a thumbnail is clicked, that video would play in the main player area without the user being taken to any other page. Is there a way I can accomplish this with existing modules and/or Views?
Thanks!
Answer: I have make something like this using views slideshow.

Added youtube thumbnail in the views
Added youtube video in the views
Add slideshow as style format of the view
Set youtube thumbnail in pager of the slideshow

Its working for me.
Comment: Perfect! I used the Youtube module, as mentioned by develkar below, since it includes the Youtube thumbnail. Thanks!
Answer: I make something like that using javascript

I make a block view that display all youtube thumbnail I need
I will rewrite the results of the image and make a rel attribute
that contains the youtube url
make a block view that display the first youtube video
using javascript change the src of the youtube object to the rel attribute in the image when I click on it
Comment: That sounds like it would work really well. Would it be possible for you to share an example of your Javascript code that does this for you? Thanks!
Comment: just I make onclick javascript function and replace the youtube object (All the object ) with a new object with the new src,The code I made is more complicated I was replaced video sometimes with image and sometimes with uploaded video ,your case is simple than that
Answer:
Install a module named youtube in your drupal website and other modules required to upload a video.
create a VIEW-BLOCK.
in the FIELDS tag,add the TITLE of the VIDEO, and also the content-name of the field which has video "VIDEO".
4.in the FILTER CRITERIA ,add the content type which you want to be displayed.
place the BLOCK in the region where you want the list of vides.


Time scaled polynomial Brownian Motion

Question: I want to choose constants $a$ and $b$ such that the process $$X_t = t^aP\left(\frac{B_t}{t^b}\right)$$ is a martingale, where $B_t$ is a Brownian Motion and $P(y)$ is a polynomial of degree n.
Thus far, I have used Ito's lemma to determine that the following equation must be true for $X_t$ to be a martingale (This expression is that associated with the drift term):
$$a\cdot P\left(\frac{B_t}{t^b}\right) - b\cdot \frac{B_t}{t^b}\cdot P'\left(\frac{B_t}{t^b}\right) + \frac{1}{2}\cdot \frac{t}{t^{2b}}\cdot P''\left(\frac{B_t}{t^b}\right) = 0 $$
This implies $$a\cdot P(y) - by\cdot P'(y) + \frac{1}{2}\cdot \frac{t}{t^{2b}}\cdot P''(y) = 0$$ where $y = \frac{B_t}{t^b}$.
From there, I realized that this equation must hold for all values of y, which can only happen if $\frac{t}{t^{2b}} = 1 \Longrightarrow b = \frac{1}{2} $. I am, thus, left with   the following ODE:
$$ aP(y) - \frac{1}{2}yP'(y)+\frac{1}{2}P''(y) = 0$$
However, I do not know how I should proceed from here to solve for $a$. I know that it should be $\frac{1}{2}$, but I don't understand why. I just know that it has something to do with the highest degree term. I'd appreciate any guidance and explanations.
Also, once I find the ODE with which I have to work, I need to look specifically at a polynomial of degree 2 and determine what its coefficients must be. I tried to do this by setting $P(x)=c_1x^2 + c_2x + c_3$. Then $P'(x) = 2c_1x+c_2$ and $P''(x) = 2c_1$. I plugged this into the tentative ODE above and got:
\begin{align*} (c_1x^2 +  c_2x + c_3) -x(2c_1x+c_2) + 2c_1 &=0 \\
-c_1x^2 + (2c_1 + c_3) &= 0
\end{align*}
Thus, to make the left hand side of the equation equal 0, I thought that I should make all the coefficients also equate to 0. However, if $c_1 = 0$, it's no longer a second-degree polynomial. Am I not thinking about this the right way?
Thus, to summarize my questions are: (1) How do I solve for a? (2) How do I find the coefficients for a polynomial of degree 2?
Answer: (1) Let $P$ be an $n$-th degree polynomial, say the highest degree term is $c_n y^n$. Then the $n$-th degree term of $yP'(y)$ is $nc_ny^{n}$ and $P''(y)$ does not have an $n$-th degree term. So the $n$-th term of
$$ aP(y) - \frac 12 yP'(y) + \frac 12 P''(y) = 0 $$
is $$ ac_n y^n - \frac 12 n c_n y^n  = 0 $$
which gives $a = \frac n2$.
(2) For $n = 2$, $a = 1$, hence the ode reads
$$ 0 = (c_2x^2 + c_1x + c_0) - \frac 12x(2c_2x + c_1) + c_2
     = \frac 12 c_1 x + (c_0 + c_2) $$
So we must have $c_1 = 0$ and $c_0 = -c_2$, hence
$$ P(y) = c_2(y^2 - 1). $$
Comment: For the ODE, why are we only concerned with making the n-th degree coefficient equate to 0?

Time scaled polynomial Brownian Motion


Is Nagios "monitoring" over WAN ideal?

Question: Just started at a new company and one my first assignments is to look for alternatives to their inhouse monitoring system.
Their current solution is a .Net application that checks various devices over the WAN (since they are an IT-consulting firm that provides 24/7 support/"maintenance"). Devices range from routers/switches/printers to MS servers and services.
After reading countless posts on the site and googling extensively it seems the consensus is that some sort of Nagios/Munin mix is the way to go.
Which brings me to my question(s):
A) Is it possible to have a Nagios server running locally at the company and monitor various external sites over WAN?
(They dont want a local Nagios server on each site as most sites are relatively small (10-25 hosts) and the number of sites is quite large (75-100)).
B) If so how would the agents contact the Nagios backend ? Through SSH? HTTP?
C) Aside from the fact that it would be susceptible for WAN-link failures, what would the immediate drawbacks of such a solution be?
Any feedback is appreciated, and I apologize in advance for any misconceptions as im quite new to the industry.
Answer: Monitoring over a WAN is possible, but is generally not ideal. This is because if the WAN link goes down or blips all checks will fail and you are blind to what is happening in the remote location. You also have increased latency making it less useful for LAN View performance measurements. That being said if you are going this way you probably want to set up dependencies so you don't get flooded with alerts when the WAN link has issues.
The most common way I have seen communication between a monitoring system and its monitored services is to have a site-to-site VPN tunnel. Then communication is no different from the local network. Also, Nagios is often Pull based (although it doesn't have to be). So Nagios contacts the services and servers it monitors, not the other way around.
Lastly, a more ideal solution is to use a distributed monitoring setup, with Nagios one option is described in http://nagios.sourceforge.net/docs/3_0/distributed.html .
Comment: Definitely a case for running local servers and do have a long hard look at NRPE. As for protocol? It's up to you - probably should be secured, but there's ssh, stunnel as well as conventional VPNs
Comment: Thanks alot, some great info in the distributed article that will definately come in handy.
Answer: It kind of depends what you are going to be monitoring over the wan. For the most part if you are only doing ping checks, services checks, disk checks etc and stick to nagios's default 5 min checking time i cant see it causing you an issue.
Again, depending on what you are checking depends on what it is going to talk over. If you are checking windows hosts you can just use WMI queries and not even need an agent running on the box.
Answer: This is certainly possible, via several different methods.
If the "distributed setup" is out of the question, then you need to do at least one of the following:

Have every box at the remote site push check results to Nagios (see NSCA)
Poke firewall holes so that Nagios can reach every box at every remote site
Designate a single box at each site to be a sort of "Nagios proxy"

I would suggest #3, because it requires the least firewall hole-poking, and also simplifies configuation. It's sort of a slimmed-down version of the distributed setup, in that it doesn't require a full Nagios instance at each site.
To do this, you can set up NRPE (or use check_by_ssh) and have this "proxy" run all of the other checks against the other hosts on the network. This has the added benefit of the performance data that you get back being relative to the proxy, so it won't be affected by WAN lag.
Also, you can then use parent/child setups to make every host at the remote site a child of its proxy, to reduce false-positive notifications. You might also want to make all of the services dependent on a check_nrpe (or check_ssh) service of the proxy. See the network reachability docs for more info.
No matter which method you go with, it's very important that you adjust default timeouts appropriately, to account for the added lag of going across the WAN links.

Is Nagios "monitoring" over WAN ideal?


Vertical Align Center in Bootstrap 4

Question: I am trying to center my Container in the middle of the page using Bootstrap 4. I have been unsuccessful thus far. Any help would be appreciated.
I have built it at Codepen.io so you guys can play with it and let me know what works as I am about out of ideas...

var currentAuthor = "";
var currentQuote  = "";
function randomQuote() {
  $.ajax({
      url: "https://api.forismatic.com/api/1.0/?",
      dataType: "jsonp",
      data: "method=getQuote&format=jsonp&lang=en&jsonp=?",
      success: function( response ) {
        $("#quote-content").html('
 ' + response.quoteText + '
');
        $("#quote-author").html('
' + response.quoteAuthor + '
');

        currentAuthor = response.quoteAuthor;
        currentQuote  = response.quoteText
      }
  });
}

function openURL(url){
  window.open(url,'Share', 'width=550, height=400, toolbar=0, scrollbars=1 ,location=0 ,statusbar=0,menubar=0, resizable=0');
}

function tweetQuote(){
      openURL('https://twitter.com/intent/tweet?hashtags=quotes,freecodecamp&related=freecodecamp&text=' + encodeURIComponent('"' + currentQuote + '" - ' + currentAuthor));
}

$(document).ready(function () {
    randomQuote();

    $("#get-another-quote-button").click(function(){
        randomQuote();
    });

   $('#tweet').on('click', function() {
       tweetQuote();
   });
});
html, body {
  background-image: url("https://www.mylinea.com/wp-content/uploads/beautiful-trees-stock-photo-055.jpg");
    background-color: #17234E;
    margin-bottom: 0;
    min-height: 30%;
    background-repeat: no-repeat;
    background-position: center;
    -webkit-background-size: cover;
    background-size: cover;
}

.btn-new-quote {
    color: #0C0C0D;
    background-color: transparent;
    border-color: #414147;
}

.btn-new-quote:hover {
    color: #0C0C0D;
    background-color: #9A989E;
    border-color: #0C0C0D;
}

#tweet {
    color: RGB(100, 100, 100);
}

#tweet:hover {
    color: RGB(50, 50, 50);
}

.jumbotron {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
    opacity: .85;
    border-color:  RGB(50, 50, 50);
    padding-bottom: 8px;
}

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.6/css/bootstrap.min.css">

                        <button id="get-another-quote-button" type="button" class="btn btn-outline-secondary  btn-new-quote">Don't Quote Me on This...</button>

Answer: Important! Vertical center is relative to the height of the parent

If the parent of the element you're trying to center has no defined
height, none of the vertical centering solutions will work!

Now, onto vertical centering...
Bootstrap 5 (Updated 2021)
Bootstrap 5 is still flexbox based so vertical centering works the same way as Bootstrap 4. For example, align-items-center, justify-content-center or auto margins can used on the flexbox parent (row or d-flex).

use align-items-center on a flexbox row parent (row or d-flex)
use justify-content-center on a flexbox column parent (d-flex flex-column)
use my-auto on a flexbox parent

Vertical Center in Bootstrap 5

Bootstrap 4
You can use the new flexbox & size utilities to make the container full-height and display: flex. These options don't require extra CSS (except that the height of the container (ie:html,body) must be 100%).
Option 1 align-self-center on flexbox child

     I'm vertically centered

https://codeply.com/go/fFqaDe5Oey
Option 2 align-items-center on flexbox parent (.row is display:flex; flex-direction:row)

                I'm vertically centered

https://codeply.com/go/BumdFnmLuk
Option 3 justify-content-center on flexbox parent (.card is display:flex;flex-direction:column)

                    ...card content...

https://codeply.com/go/3gySSEe7nd

More on Bootstrap 4 Vertical Centering
Now that Bootstrap 4 offers flexbox and other utilities, there are many approaches to vertical
alignment. http://www.codeply.com/go/WG15ZWC4lf
1 - Vertical Center Using Auto Margins:
Another way to vertically center is to use my-auto. This will center the element within it's container. For example, h-100 makes the row full height, and my-auto will vertically center the col-sm-12 column.

Card

Vertical Center Using Auto Margins Demo
my-auto represents margins on the vertical y-axis and is equivalent to:
margin-top: auto;
margin-bottom: auto;

2 - Vertical Center with Flexbox:

Since Bootstrap 4 .row is now display:flex you can simply use align-self-center on any column to vertically center it...

                 Center

                    Taller

or, use align-items-center on the entire .row to vertically center align all col-* in the row...

                 Center

                    Taller

Vertical Center Different Height Columns Demo
See this Q/A to center, but maintain equal height

3 - Vertical Center Using Display Utils:
Bootstrap 4 has display utils that can be used for display:table, display:table-cell, display:inline, etc.. These can be used with the vertical alignment utils to align inline, inline-block or table cell elements.

            I am centered vertically

Vertical Center Using Display Utils Demo
More examples
Vertical center image in

Vertical center .row in .container
Vertical center and bottom in

Vertical center child inside parent
Vertical center full screen jumbotron

Important! Did I mention height?
Remember vertical centering is relative to the height of the parent element. If you want to center on the entire page, in most cases, this should be your CSS...
body,html {
  height: 100%;
}

Or use min-height: 100vh (min-vh-100 in Bootstrap 4.1+) on the parent/container. If you want to center a child element inside the parent. The parent must have a defined height.
Also see:
Vertical alignment in bootstrap 4
Bootstrap Center Vertical and Horizontal Alignment
Comment: When using above on a page with a navbar I'm getting a scrollbar. I think it's adding 100% height below the navbar and centering across it. How can I fix that?
Comment: I prepared a codepen currently showing 3 ways of centering based on the ways shown here: https://codepen.io/yigith/pen/oNjmGEL
Comment: I am trying to align multiple rows to centre with flex box. I want to align all buttons in centre.
 https://www.codeply.com/go/5abdqC33cU
Comment: Option 1 only worked for me when `` was changed to ``
Comment: That's correct since `h-100` is 100% of its parent container while `vh-100` is height of the viewport. At the time the question was asked,`vh-100` didn't exist in Bootstrap.
Comment: @Zim can you please check this my issue. if you can help me - https://stackoverflow.com/questions/71031318/how-to-append-the-bootstrap-5-dropdown-menu-to-a-specific-element-when-the-drop Thanks zim.
Answer: Using bootstrap version 5 or later, use the code below to center the content horizontally and vertically.

Centered horizontally and vertically!

Comment: You're the real MVP.
Comment: What about v5? This only centers it horizontally.
Comment: This should be the approved answer.
Comment: This is the best way!  Works in BS4 as well
Answer: you can vertically align your container by making the parent container flex and adding align-items:center:
body {
  display:flex;
  align-items:center;
}

Updated Pen
Comment: your answer doesnt solve the problem in the asked way (using bootstrap)
Comment: ohhh lol, I missed the link in the description... you also added `html, body {height:100%}` ... adding that made it work! Thanks!
Comment: im totaly not agree with you, you propose to workaround despite of the question was about how do it with Bootstrap classes.
Comment: @AlexNikonov no where in the OP question does it say they are limited to using bootstrap only - this is an alternative for other people who may land on this page looking to vertically align things without the use of bootstrap classes.  Just move along - there are plenty of other answers here for you to use.  I don't see why you're getting hung up about this - this is a forum for all ideas that will help - not just single minded answers.  It is users like you spoiling this site by downvoting answers that offer a solution to the problem but just because you don't like it
Comment: Or with BS4: some text
Comment: @AlexNikonov also if you read the original unedited post (when I added my answer), you will also see OP was trying to centre without using bootstrap classes so at the time of answering, this was correct
Comment: Didn't work for me under Bootstrap 5. CSS has too many interactions with itself.
Answer: Following bootstrap 4 classes helped me solve this

Comment: That didn't centered my div vertically though.
Comment: Can you please elaborate on your css code. share a snippet of it, I would look into the issue you are facing.
Answer: Because none of the above worked for me, I am adding another answer.
Goal: To vertically and horizontally align a div on a page using bootstrap 4 flexbox classes.
Step 1: Set your outermost div to a height of 100vh. This sets the height to 100% of the Veiwport Height. If you don't do this, nothing else will work.  Setting it to a height of 100% is only relative to the parent, so if the parent is not the full height of the viewport, nothing will work.  In the example below, I set the Body to 100vh.
Step 2: Set the container div to be the flexbox container with the d-flex class.
Step 3: Center div horizontally with the justify-content-center class.
Step 4: Center div vertically with the align-items-center
Step 5: Run page, view your vertically and horizontally centered div.
Note that there is no special class that needs to be set on the centered div itself (the child div)

Comment: @AjayKumar, Would you like to share your modifications?
Comment: Thanks, especially the `100vh` trick helped me a lot. Bootstrap also provides the `vh-100` class for this.
Answer: I did it this way with Bootstrap 4.3.1:

    I'm in the middle

Comment: at last, something that works
Answer: .jumbotron {
    position: relative;
    top: 50%;
    transform: translateY(-50%);
}

Answer:

Heading

Some text.

This line is where the magic happens
, the my-auto will center the content of the column. This works great with situations like the code sample above where you might have a variable sized image and need to have the text in the column to the right line up with it.
Answer: I've tried all the answers herefrom, but found out here is the difference between h-100 and  vh-100
Here is my solution:

             ...

Answer:

                Our Offer

Today's Special

One morning, when Gregor Samsa woke from troubled dreams, he found himself transformed in his bed into vermin. He lay on his armour-like back, and if he lifted his head a little he could see his brown belly.

Comment: your pics made me thik the stackoverflow got started the advs :D
Answer: In Bootstrap 4 (beta), use align-middle. Refer to Bootstrap 4 Documentation on Vertical alignment:

Change the alignment of elements with the vertical-alignment
  utilities. Please note that vertical-align only affects inline,
  inline-block, inline-table, and table cell elements.
Choose from .align-baseline, .align-top, .align-middle, .align-bottom,
  .align-text-bottom, and .align-text-top as needed.
Answer: <!DOCTYPE html>

  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.2.1/css/bootstrap.min.css">

Center Div Here

Comment: @AjayKumar Adding the `flex-grow-1` class to the card prevents it from shrinking.
Answer: Vertical align Using this bootstrap 4 classes:
Method1:

parent: d-table
AND
child: d-table-cell & align-middle & text-center

eg:

and if you want parent be circle:

which two custom css classes are as follow:
.tab-icon-holder {
  width: 3.5rem;
  height: 3.5rem;
 }
.rounded-circle {
  border-radius: 50% !important
}

Final usage can be like for example:

     ...

Method2:
You can use following:

parent: h-100 d-table mx-auto
AND
child: d-table-cell align-middle

Method3:
You can use following:

parent: d-flext align-items-center

also if you want content be center horisontally too:

parent: d-flext align-items-center justify-content-center
Comment: align-middle is what I've been looking for, very simple and correct, thanks!
Answer: bootstrap 5 and blazor web assembly:

<button class="btn btn-outline-success mx-2">Register</button>
<button class="btn btn-outline-primary mx-2" style="width:123.44px">Login</button>

Answer: /*You have to add height 100vh */

            Center

Answer: use .my-auto (bootsrap4) css class on yor div
Answer: Place your content within a flexbox container that is 100% high i.e h-100. Then justify the content centrally by using justify-content-center class.

Hello, Malawi!

Answer: in Bootstrap 5 we can do it easily. Below is an example to align card. We just have to set the card width, then the rest setting are using bootstrap 5 class.

I'am centered vertically and horizontally

Answer: For all Bootstrap versions 2, 3, 4 and 5 with only two custom classes suitable with any height and width.

.d_tbl{
  display:table;
  width:100%;
  height:200px;
}

.d_tblCel{
  vertical-align: middle;
  display: table-cell;
  text-align: center;
}
<!DOCTYPE html>

  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">

Centered horizontally and vertically

for all bootstrap versions with only two custom classes

Comment: this is not the bootstrap way to do it
Answer: In Bootstrap 4.1.3:
This worked for me when I was trying to center a bootstrap badge inside of a container > row > column next to a h1 title.
What did work was some simple css:
.my-valign-center {
  vertical-align: 50%;
}

or
My Badge

Vertical Align Center in Bootstrap 4