Create a View from custom database

Question: I love the features the view provides in Drupal. Sortable tables, Filters, as well as ability to use external modules like views bulk export.
My problem is that I want to display a separate database (Call this X), using views. What would be the best way to go about it?
To get around this problem in Drupal 6, I created a content type with all fields that were in Database X, then I created view for that content type by frontend. After that I used hook_pre_render_view() to push data from X to the view. Right now I want to achieve similar results in Drupal 8. I could use this same approach but it doesn't feel very Drupally. I was wondering if there is a better way to achieve this.
Answer: You can connect a external database inorderto let Drupal Know about it:
<code>$databases['external']['default'] = array(
  'database' => 'custom_database',
  'username' => 'root',
  'password' => '',
  'prefix' => '',
  'host' => php_sapi_name() == 'cli' ? '127.0.0.1' : 'localhost',
  'port' => '3306',
  'namespace' => 'Drupal\\Core\\Database\\Driver\\mysql',
  'driver' => 'mysql',
);
</code>
Then you can connect to that database:
<code>/*
* Switch to external db
*/
\Drupal\Core\Database\Database::setActiveConnection('custom_database');

/*
* Get connection
*/
$db = \Drupal\Core\Database\Database::getConnection();
</code>
Then do you stuff and don't footgrt to switch again to the standard database:
<code>/*
* Switch back
*/
\Drupal\Core\Database\Database::setActiveConnection();
</code>
You can store your external database info into a content type programatically and the show in views.
Comment: Thank you, I am done with these steps. My biggest issue is what will be the best way to store external database into content type programatically, or if there is a way to bypass creation of content type and directly use views
Comment: Here is a simple example:
`code`$data = [
  'type' => 'my_content_type',
  'title' => 'My new title',
  'uid' => 1,
  'field_my_field' => 'my field awesome value'
];
$node = Drupal::entityTypeManager()
  ->getStorage('node')
  ->create($data);
$node->save();`code`
Comment: Thank you I ended up following the same technique I used in Drupal 6
Answer: You can by using the Views Database Connector module.

Views Database Connector is a powerful module that gives Views full
  access to external database tables found in the settings for your
  Drupal installation. With this module, you can setup a view around any
  table in any database configuration. This can be extremely useful to
  pull external data from a database to show to your users in a view.

See README.txt on how to use.
Comment: Thank you, module looks promising. I will keep it in mind when dealing with database and views in future. Right now, I just ended up doing the same thing I did in drupal 6

Create a View from custom database


Oracle Forms: alert in pre-delete trigger not working

Question: I have a table OBJECTS with 4 columns: id, type_id, type_desc, and state_id.
If the state_id is 'DELETE', I want to abort the deletion of a row and display an alert message saying "You cannot delete this row".
Here's the PRE_DELETE trigger:
begin
  if :OBJECTS.state_id = 'DELETE' then
    set_item_instance_property('OBJECTS.state_id', CURRENT_RECORD, VISUAL_ATTRIBUTE, 'ERROR');

    if show_alert('ALERT_DEL') = alert_button1 then
      null;
    end if;

    raise FORM_TRIGGER_FAILURE;
  end if;
end;

Unfortunately, the alert message won't display.
Edit:
I forgot to mention this before:
Oracle Forms returns an error FRM-40741: Unable to locate record 0 on block OBJECTS.
Edit:
I'm also trying to do a PRE-UPDATE trigger:
declare
  stateID varchar2(10);
  pressed_button number(2,0);
  info number(2,0);
begin
  stateID := get_item_property(:OBJECTS.state_id, DATABASE_VALUE);

  set_alert_property('ALERT_INFO',alert_message_text,'STATE_ID: ' || stateID);
  info := show_alert('ALERT_INFO');

  if stateID = 'DELETE' then
    set_item_instance_property('OBJECTS.state_id', CURRENT_RECORD, VISUAL_ATTRIBUTE, 'ERROR');
    pressed_button := show_alert('ALERT_EDIT');
    raise FORM_TRIGGER_FAILURE;
  end if;

end;

I get an error FRM-40105:Unable to resolve reference to item DELETE.
So I created ALERT_INFO alert to show the value of state_id stored in the database. I shows nothing. What am I doing wrong?
Answer: Don't have Forms to test but the use of SHOW_ALERT() in a IF statement looks, um , iffy. Try this instead:
declare
  pressed_button number(2,0);
begin
  if :OBJECTS.state_id = 'DELETE' then
    set_item_instance_property('OBJECTS.state_id', CURRENT_RECORD, VISUAL_ATTRIBUTE, 'ERROR');

   pressed_button := show_alert('ALERT_DEL');

    raise FORM_TRIGGER_FAILURE;
  end if;
end;

You can add a test on pressed_button to see which actual button was pressed, but it doesn't seem to make any difference in the code you posted.
Answer: Your code seems to be OK. if I try simplified code in PRE-DELETE trigger
begin
    if show_alert('ALERT_DEL') = alert_button1 then
      raise form_trigger_failure;
    end if;
end;

it works, like expected (Oracle Forms 6i).
I guess your yout :OBJECTS.state_id is not 'DELETE'.
Edit: FRM-40741 - that's it! problem is on line
set_item_instance_property('OBJECTS.state_id', CURRENT_RECORD, VISUAL_ATTRIBUTE, 'ERROR');

You try to set visual property of deleted record, CURRENT_RECORD variable is set to 0 in your case.
Don't use PRE-DELETE trigger for your task. Disable record deletion in WHEN-NEW-RECORD-INSTANCE trigger on OBJECTS block:
if :OBJECTS.state_id = 'DELETE' then
    set_block_property('OBJECTS', DELETE_ALLOWED, PROPERTY_FALSE);
else
    set_block_property('OBJECTS', DELETE_ALLOWED, PROPERTY_TRUE);
end if;


Android fragment onCreateView creating duplicate views on top of each other

Question: In my app, when I suspend, upon resume, I get duplicate views stacked on top of each other, with the topmost being the only editable ones.  My onCreateView() is below.  Any suggestions?
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
        Bundle savedInstanceState) {

    View v = super.onCreateView(inflater, container, savedInstanceState);

    Item currentItem = Global.DataManager.getItem();

    // Set the different details
    ((EditView) v.findViewById(R.id.item_title))
            .setText(currentItem.getTitle());
    ((EditView) v.findViewById(R.id.item_type))
            .setText(currentItem.getType());
    ((EditView) v.findViewById(R.id.item_details))
            .setText(currentItem.getDetails());

    return v;
}

Answer: Your problem is not in onCreateView(), most likely. Instead, I suspect that you are creating the fragment a second time. You only need to create a fragment once, even if activity is destroyed and recreated due to a configuration change (e.g., portrait -> landscape rotation).
Comment: You were absolutely right.  Sorry about the delay for accepting your answer, but your response seemed to be the cause of my issues.


jQuery UI Datepicker works on  but not on

Question: I'm trying to use jQuery UI Datepicker. In same JSF page, it works on HTML <input> tag, but not on JSF <h:inputText> tag.

    <h:inputText id="mask-date" class="form-control mask" />
    <input type="text" class="form-control mask" id="mask-date"/>
    mm/dd/yyyy

How is this caused and how can I solve it?
Comment: Code snippets are for providing runnable demo's using HTML/CSS/JS. it'll not interpret your jsf tags. I converted them to normal code blocks. That being said, please don't dump the source of entire libraries and plugins in question. Instead provide a link to their documentation, or tag it in question if a tag is available..
Answer: In most cases JSF tags not pure HTML tags but constructed from  multiple HTML tags, for example

<input ... />

And id of JSF tag not pointing to <input> tag but to outer
. You should view your outcome page code in HTML and correct your selector accordingly.
Answer: Your problem is here:
<h:inputText ... class="form-control mask" />

The class attribute isn't supported on <h:inputText>. Instead, it's named styleClass.
<h:inputText ... styleClass="form-control mask" />

This is true for all other JSF components. You should also have noticed the absence of the class attribute in the JSF-generated HTML <input> element when taking the effort to do rightclick and View Source in webbrowser.
The attribute name is different from the HTML counterpart, because class is a reserved keyword in Java and therefore it isn't possible to have a private String class; field in the UI component class.
Comment: Thanks for giving your valuable time.Actually I am new to JSF and I don't know the future scope of JSF , I have heard that it is an old framework. Is it true?
Comment: JSF is indeed an old framework. It exist almost a decade. But you're actually not working with decade-old codebase ;) Mojarra has a new release at least once a month. The JSF spec also keeps evolving and improving. See also http://stackoverflow.com/questions/3623911/what-are-the-main-disadvantages-of-java-server-faces-2-0. And as a starter looking for valuable resources you may find https://jsf.zeef.com helpful.


AsyncAppender does not wait for buffer to be full before writing

Question: I am learning about Log4j currently and the book I am using is explaining AsyncAppenders. I set a buffer size to be 128 (LoggingEvents). The book explains that no messages will be printed until the buffer size is reached, however my program prints the logging messages regardless of the buffer size.
Why is this the case? I would appreciate any other pointers about AsyncAppenders if anyone has knowledge about using them :)
Log4j.xml
    <?xml version="1.0" encoding="UTF-8"?>
    <!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

    <log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/"
    debug="true">

    <appender name="ASYNC" class="org.apache.log4j.AsyncAppender">
    <appender-ref ref="CONSOLE"/>
    <param name="BufferSize" value="128"/>
    </appender>

    <appender name="CONSOLE" class="org.apache.log4j.ConsoleAppender">
    <layout class="org.apache.log4j.PatternLayout">
    <param name="ConversionPattern" value="%d %-5p [%t] - %m%n"/>
    </layout>
    </appender>

    <logger name="org.example.christopher" additivity="false">
    <level value="debug"/>
    <appender-ref ref="ASYNC"/>
    </logger>
    <root>
    <priority value="debug"/>
    </root>
    </log4j:configuration>

Java code
package org.example.christopher;

import org.apache.log4j.*;
import org.apache.log4j.xml.DOMConfigurator;

public class AsyncLogging{

private static Logger logger = Logger.getLogger(AsyncLogging.class.getPackage().getName());
private AsyncAppender asyncAppender = null;
private ConsoleAppender consoleAppender = null;

public AsyncLogging(){

try{
logger.setAdditivity(false);
asyncAppender = (AsyncAppender) logger.getAppender("ASYNC");
asyncAppender.setBufferSize(128);
}
catch (Exception e){
System.out.println("error: " + e.toString());
}

}

public void doLogging(){
logger.debug("Debug 1");
logger.debug("Debug 2");
logger.debug("Debug 3");
//logger.debug("Debug 4");
//logger.debug("Debug 5");
}

public static void main(String ... args){
AsyncLogging asyncLogging = new AsyncLogging();
asyncLogging.doLogging();
}

}

Answer: Neither the javadocs or the source code of AsyncAppender say that no messages will be printed until the buffer is full.  Indeed, according to my reading of the code:

The AsyncAppender.Dispatcher thread that does the writing will be woken whenever an event is appended and the buffer is empty.
Once woken, it won't go to sleep until the buffer is empty.

That is pretty much the opposite of what the book you are reading says.  (Assuming that you have read it correctly.)
Comment: In that case, the book is plainly incorrect.  If it had said *"... it is not specified ..."* that would have been correct.  But the source code plainly contradicts the book, and the source code is definitive.
Comment: "This example simply sets the buffer size to 4 for the AsyncAppender
being used. The AsyncAppender will not print any message so long as the number of logging
events is less than the buffer size. Once the number of logging events exceeds the buffer size,
the buffer is flushed and all the messages will be printed." Pro Apache Log4J second edition
Comment: The only possible explanation that might make the book sort of correct would be that early versions of `AsyncAppender` might have worked like that.  However, the intended behavior in the code has been "eager" async flushing since v1.2.8 ... which is the earliest version for which source code is easily accessible.  (It is all in the Grepcode link above.)


Verificar se uma data é anterior a outra data

Question: Bom dia, gostaria de saber se existe um jeito de verificar se uma data é anterior ou superior a outra, no meu código tem 2 inputs tipo date, que enviam seus valores ao banco de dados, porém uma data irá iniciar algo e a outra finalizara, gostaria de fazer um verificação antes de enviar ao banco que não permita que a primeira data seja maior que a segunda, tem como fazer isso?
FORM:

    Data de Inicio:
    <input type="date" class="form-control input-sm" name="Data_Inicio" required>

    Data de Encerramento:
    <input type="date" class="form-control input-sm" name="Data_fim" required>

PHP:
$Data01 = explode("-", $Data_in);
$Data02 = explode("-", $Data_fim);
$Ndata_in = $Data01[0] . '/' . $Data01[1] . '/' . $Data01[2];
$Ndata_fim = $Data02[0] . '/' . $Data02[1] . '/' . $Data02[2];

$sql = 'INSERT INTO walldata VALUES ("' . $Ndata_in . '", "' . $Ndata_fim . '")';

Comment: Você está fazendo do jeito mais difícil. Vou tentar te ajudar
Comment: Okay Wallace Obrigado :D
Answer: A forma mais correta é:
$data1 = new DateTime( '2016-06-06' );
$data2 = new DateTime( '2016-06-15' );

echo ($data1 < $data2) ? "Está Ok!" : "Data de encerramento errada";

Na query você pode usar só a string da data pura mesmo nesse formato 1996-12-10 (aaaa-mm-dd)
Comment: Ok, obrigado mas isso ai vai servir para verificar as datas, para saber qual é se são válidas, ex: $data_in = 19/01/2000 , $data_fim = 18/01/2000, erro a data de encerramento deve ser maior do que a de inicio, espero ter explicado bem :D
Comment: Não entendi muito bem kk o código da resposta verifica se uma data é menor que a outra, onde `$data1` é o inicio e `$data2` é o final. Já para verificar se uma data é válida não é necessário, pois o html5 faz isso. Caso queira validar se a data é maior que a data atual é só usar `$data1 = new DateTime( date() );`
Comment: Entendi oque você quis dizer obrigado
Answer: O colega @lvcs já deu um exemplo bom do uso do Datetime, mas eu não poderia deixar de dizer que se as datas forem strings no formato já usado pelo MySQL, no formato AAAA-MM-DD, é desnecessário instanciar dois objetos DateTime.
Muito mais simples e eficiente fazer a comparação diretamente:
$data_menor = '2016-06-01';
$data_maior = '2016-02-31';

echo ( $data_menor  < $data_maior ) ? "Está Ok!" : "Data de encerramento errada";

Se quiser inverter automaticamente também é simples:
$data_menor = '2016-06-01';
$data_maior = '2016-02-31';

if( $data_menor > $data_maior ) {
   $tmp = $data_maior ;
   $data_maior = $data_menor ;
   $data_menor = $tmp;
}

$sql = 'INSERT INTO walldata VALUES ("' . $data_menor . '", "' . $data_maior . '")';

PS: a troca de variáveis acima é muito mais veloz do que fazer list($x,$y) = array($y,$x);
Answer: "fazer um verificação antes de enviar ao banco que não permita que a primeira data seja maior que a segunda"
Vc pode fazer isso de duas maneiras diferentes:

Back end - php
Front end - javascript

Eu geralmente uso javascript para evitar código em php.
Dito isso, usando JS, existem ao menos 2 possibilidades para essa tarefa.

Usando javascript puro
Usando algum das várias bibliotecas JS. Eu uso datepicker do jquery.

Essa aplicação permite várias configurações do campo de data de maneira bem simples.
Eu tenho um código que uso nas minhas aplicações. Ele é bi direcional.
No cenário seguinte existe uma data para entregar produtos e uma data para relaizar a festa. Então o usuário escolhe a data prevista para receber o produto. Quando essa data é escolhida, a data da festa só pode ser maior ou igual a data de chegada. Existe tbm a possibilidade do usuário escolher primeiro a data da festa. Entáo a data máxima de entrega do produto só pode ser a data do evento.
Espero que ajude, tenta adequar para suas necessidades.
    //Validar datas:

    //Quando abre o datapicker seleciona a menor data para ser o dia de hoje now().
    var now = new Date(),
    minDateJS = now.toISOString().substring(0,10);

    //Seleciona a data de entrega do produto.
    //Aplica a data now (hoje) para ser a menor data selecionavel para a entrega do produto
    //Aplica a data de entrega do produto para ser a menor data possivel do evento
    $('#dt_entregaProd').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
        minDate: minDateJS,
        inline: true,
        onClose: function( selectedDate ) {//Passa a data selecionada neste objeto para ser a menor data possivel para realizar o evento
          $( "#dt_Event" ).datepicker( "option", "minDate", selectedDate );
        }

    });

    //Seleciona a data do evento.
    //Evento bidirecional. Se a data do evento for selecionada primeiro, entã a data máxima de entrega do produto será limitada automaticamente
    $('#dt_Event').datepicker({
        dateFormat: 'yy-mm-dd',
        changeMonth: true,
        changeYear: true,
        minDate: minDateJS,
        inline: true,
        onClose: function( selectedDate ) {
          $( "#dt_entregaProd" ).datepicker( "option", "maxDate", selectedDate );
        }
     });


SpriteKit Camera position correction in iOS10?

Question: When converting my App, which has a SpriteKit scene in it, to iOS 10 I have had to convert my scene's original camera position from:
cameraNode.position = CGPoint(x: self.size.width/2, y: self.size.height/2)

to account for iOS10 with:
if #available(iOS 10, *) {
    cameraNode.position = CGPoint(x: self.size.width/2, y: (self.size.height + voidSize)/2)
}
else {
    cameraNode.position = CGPoint(x: self.size.width/2, y: self.size.height/2)
}

The iOS10 version actually makes more sense as I do have part of the scene off-screen (where sprites are first created before being 'revealed' to the user) and 'voidSize' represents this. So having to add an offset to account for the off screen portion makes sense.
The question is, what has changed in SpriteKit in iOS 10 to make me correct my camera position like this that was not there before?
The app now works fine, on both iOS 9 and iOS 10 - just curious about what has caused this.
Comment: IMHO my personal rule of thumb is: When Apple brings a new feature e.g. in iOS 8, then don't use it until iOS 10, otherwise you'll just run into troubles ;-)
Answer: There was a bug with SKCameraNode where it would not centre correctly. It now works correctly with ios 10 so DO NOT use the ios 9 check, just use the new setting which you said makes a lot more sense anyway.
My games on the app store that have not been updated for ios 10 yet now look wrong. So this must be a general fix and not an iOS version specific fix.
I even made a bug report about this which have apple responded to and confirmed to be fixed (27171076)
The main gist was this
Summary:
Using the default SpriteKit template with SKCameraNode and putting it right in the centre of the screen cause the camera to be offset on iPhones.
On iPads it is centred as expected.
Steps to Reproduce:
- Create new sprite kit default template
- Add SKCamera Node and Centre in middle of screen (in code or using visual level editor)
Expected Results:
That camera is centred on iPhone as it does on iPads.
Actual Results:
Camera is offCenter on iPhones. In portrait HelloWorld labels is shifted to the left and in landscape it is shifted to the bottom."


Maintain email timestamp when transferring between email servers using an email client

Question: I am running two different email servers using Postfix and Dovecot. Some of my users have accounts on both servers and sometimes transfer emails from one to the other through their email client. When they do so, the email is showing up on the new server with the time stamp of when it was transferred instead of the original time.
I assume this is because the email is going back into the Postfix queue like it is a new message. Is there a way I can have it maintain the original timestamp?
This is using IMAP and emails are stored in the Maildir format on both servers.
Answer: Here is a Perl script that sets the file date to the value in the Date: line in the message header.  http://www.athensfbc.com/public/fix_msg_dates
Usage:  fix_msg_dates.pl <path to message directory>
-Rick
Comment: Thank you for this. I did use a similar script to fix the time stamps on the emails but it doesn't fix the ongoing issue unless I set it up as a cron job. I believe I would also need to delete dovecot's cache files. Even so, most mail clients will download the message and not recheck the date of emails each time it connects to the server so the date would still be wrong in the client that moved the email or downloaded the message before the cron job ran.
Comment: Just in case someone else experiences this, I had to move the file out of the `Maildir` folder hierarchy and then move it back in for the date change to take effect on my Mail client (Apple Mail).
Answer: Are you using Maildir storage with IMAP?  If so, it should possible to just move the messages into the new folders.  It should also be possible to use a mail client to copy between the two IMAP folders.
It is important the the messages have a Date header, as this is usually the preferred date.  Some clients will prefer the Delivery-date instead.  If all else fails, they may used the date the message appeared in the folder. As long the messages have a Date header, then the dates should remain the same.
Emailing between the two servers will reinject the messages into the mail stream and result in the Date headers being replaced.
EDIT: My experience with Dovecot and Thuderbird indicates that as long as the Date headers exist, the date doesn't change when a file is moved using IMAP. If the Date headers are absent, then the date is set to the date the file shows up in Thunderbird. IMap internal date value is specified in RFC-3501 Internet Message Access Protocol section 2.3.3.  Based on my reading of the RFC, I would expect the Delivery-date header to be the significant header.
If you are moving files using IMap, Postfix is irrelevant as it is not involved. Postfix will only be involved if the messages are being mailed between servers.
Comment: Both of the servers are indeed using Maildir with IMAP. (I added that information to my original question). So are you basically saying that this is not possible because the mail client is in effect "emailing between the two servers"?
Comment: @drewag Due to your inclusion of Postfix it is not clear how the messages are being moved.  I have update my response and included a pointer to the relevant RFC if the messages are moved using IMAP
Comment: The email itself is not getting modified (the date sent header is still correct). If I set my email client to use date sent instead of date received, everything works great. It is when using the date received that the date seems to get reset. If I am not mistaken, the date received is part of the IMAP protocol and therefore it is Dovecot that is causing the issue. On the other hand, I don't see how Dovecot could know the original received time so I'm not sure this is possible.
Comment: @drewag Their are two headers which can be used to get the original recieved time: Date-delivered or the Received headers.  Date-delivered is added by Exim, but I don't know if Postfix does the same.  Each server which receives the message should add a Received header.  This is described in the RFCs.
Comment: Thank you for the help so far. All of the received headers are still correct and no header has the date the the mail client is displaying. The only place I can find that references that date with the email is the epoch in the email's file name on the server and the timestamp of the file. That leads me to believe that there is something in the IMAP protocol that is telling the client the received date and dovecot is using either the file name or the timestamp of the file to decide what time it was received.
Comment: @drewag I have run some tests on my system and it appears Dovecot uses only the Date header to determine the date.  If it is missing, it uses the date the file is processed (now).
Comment: I did my own tests and Dovecot uses the date header for the "sent" date and the timestamp on the email file for the "received" date. I think I found my answer on the dovecot lists http://www.dovecot.org/list/dovecot/2008-July/032165.html and described more in detail what I inferred from it. I still gave you an up-vote because your feedback helped me figure out what to search for, but I think my answer more succinctly answers the actual issue.
Answer: I discovered my answer here: http://www.dovecot.org/list/dovecot/2008-July/032165.html
When transferring email from one server to another, an IMAP client must use the APPEND command. This command has an optional date parameter that communicates the "internal" or "received" to the new server. However, this being an optional parameters, clients are not required to send it, and if left out, the specification states that it should default to the current time. That is what happened in my case, the mail client did not report the original internal time.
The discussion also clarifies that Dovecot uses the timestamp on the file to report the internal time. So if I want to correct the received time after the fact, I could set the timestamp on the file and then delete the cache files.


How to check with Rules if a new element has been added to a list in a node?

Question: I'm using the Rules module and I would like to make a rule to check wheter a new element has been added to a list in a node.
First I have tried "List Count comparison" but it can only compare a list to an integer, then I have tried with a custom php code condition but I have troubles with getting the right data. i don't understand if i'm missing something and there is a simple way or it can be done only with custom php code (in which case i'd like to know how to correctly do it, it's worth telling that the list is an entity reference)
This is the PHP code i have tried. The event is "After the update of an existing content of type Q&A", so I have $node and $node_unchanged available. The field is called field_lista_gestori and contains a list of users.
$gestoriCount=count($node->field_lista_gestori)>count($node_unchanged->field_lista_gestori);
return $gestoriCount;

But then I have discovered that field_lista_gestori just contains a number (which I think is the reference ID) and I haven't made any other attempts after this.
Comment: to get a better answer, post the code you have tried, as well as information relating to field names. This will allow us to evaluate the problem better
Answer: You're counting the wrong thing...item data is a bit further down the rabbit hole (inside the language array):
$count_new = count($node->field_lista_gestori[$node->language]);
$count_orig = count($node_unchanged->field_lista_gestori[$node->language]);

Comment: doing some "print_r" i managed to find the parameter to get to the data. It's "und" which i guess means "undefined", probably the entity references are language independent so even though the node language is italian, they use "und" as field.
Comment: It does indeed, you can use the `LANGUAGE_NONE` constant to refer it so you don't have magic vars in your code
Comment: In the logs i get this error: "Notice: Undefined index: it in eval() (line 5 di /home/lineamicadev/sito/sites/all/modules/rules/modules/php.eval.inc(146) : eval()'d code)." "it" is the language (italian)
Comment: You just need to find out what the right language code both nodes is, and replace both instances of `$node->language` above with the appropriate string
Comment: If i go on the content page, it says the language for the node i tested the rule on is "Italian". I don't know if this changes things but as i said in the question the field is made as an "entity reference" (using the "entity reference" module)
Comment: Maybe the field was empty to start with?
Answer: Sure you can do this "without custom code" (and more important: without the need to enable the dangerous PHP filter ...). Read on for more details about how to get this to work ... and not only to discover new items added to the list (as in your question), but also to discover items removed from the list.
To process a multi-value field with Rules, I think you should use a completed different approach, which is related to the Rules Condition "List contains item" (and the negations of it).
Have a look at this rules example (in Rules export format), which processes a multi-value field also, in my case it is a list of eMail Ids (replace "eMail ID" by whatever matches your case):
{ "rules_verify_updates_to_selected_email_ids" : {
    "LABEL" : "Verify updates to selected eMail IDs",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "rules_conditional", "rules" ],
    "ON" : { "node_update--article" : { "bundle" : "article" } },
    "DO" : [
      { "LOOP" : {
          "USING" : { "list" : [ "node-unchanged:field-email-addresses" ] },
          "ITEM" : { "previous_email_id" : "Previous eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node:field-email-addresses" ],
                      "item" : [ "previous-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [previous-email-id:value] was removed from the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      },
      { "LOOP" : {
          "USING" : { "list" : [ "node:field-email-addresses" ] },
          "ITEM" : { "current_email_id" : "Current eMail ID" },
          "DO" : [
            { "CONDITIONAL" : [
                {
                  "IF" : { "NOT list_contains" : {
                      "list" : [ "node-unchanged:field-email-addresses" ],
                      "item" : [ "current-email-id" ]
                    }
                  },
                  "DO" : [
                    { "drupal_message" : { "message" : "Value [current-email-id:value] was added to the multi value field." } }
                  ]
                }
              ]
            }
          ]
        }
      }
    ]
  }
}

If you just replace the machine name "field-email-addresses" by the machine name of your field (prior to import), you should be able to experiment with this rule in your own site to see it at work (for nodes of content type "Article", adapt this type to fit your needs).
Here is a sample of the messages I get when I update an article, and while doing so I add 1 more eMail ID and at the same time I remove an existing eMail Id:
Value email@example.com was removed from the multi value field.
Value email@example.com was added to the multi value field.

So the clue to make this work is:

first iterate over all field values of your field of the unchanged node (to find the removed values).
then also iterate over all field values of your field of the changed node (to find the inserted values).

Note: As an alternative to using the Conditional Rules module (which is required for this rule to work), you can also rework the relevant part of my Rules example into performing equivalent Rules Component. For more details on using Rules Components instead of Conditional Rules, refer to the answer to "What's the alternative to using the Conditional Rules module?".
PS: I'm assuming this question is about D7.


How to change Visual Studio 2012 Quick Info Font and Color?

Question: I use Visual Studio 2012 Color Theme Editor (http://visualstudiogallery.msdn.microsoft.com/366ad100-0003-4c9a-81a8-337d4e7ace05) "light with dark editor" theme and I have a problem with the quick info color. I want to change the colors because I cannot see it with the current settings.
Which property is for that under Tools->Environment->Fonts and Colors->... ?

Thanks.
Answer: Go to Tools > Options > Environment > Fonts and Colors, select "Editor tooltips" and then change the Plain text foreground color.


delete and modify properties in array inside json object

Question: Given the following JSON:
const myJson = {
    id: 8,
    active: true,
    invoice: "2022/1001",
    invoiceDate: "2022-02-02",
    clientId: 1,
    storeId: 1,
    total: 76.95,
    itens: [
        {
            id: 11,
            quantity: 2,
            price: 12.10,
            total: 24.20,
            productId: 1,
            invoiceId: 8
        },
        {
            id: 12,
            quantity: 5,
            price: 10.55,
            total: 52.75,
            productId: 2,
            invoiceId: 8
        }
    ]
};

I need a simple way to remove two attributes from the each item inside the 'itens' array, the properties are 'id' and 'invoiceId'. I also need to recalculate the 'total', coz I do not trust totally the source of the information, I rather multiply 'quantity' by 'price' myself.
I've produced this rather naive code:
myJson.itens.forEach(item => {

  item.total =
     item.quantity *
     item.price;

     delete item.id;
     delete item.invoiceId;
});

And it works rather fine, however, no way that it must be it. Looks too lame and laborious  to me. I'm exhausted googling for better ways of doing it.
Can it be done better?
Comment: Perfect is the enemy of good. let sleeping dogs lie
Answer: Rather than mutating the original data, you could map it to a new object

const myJson = {"id":8,"active":true,"invoice":"2022/1001","invoiceDate":"2022-02-02","clientId":1,"storeId":1,"total":76.95,"itens":[{"id":11,"quantity":2,"price":12.1,"total":24.2,"productId":1,"invoiceId":8},{"id":12,"quantity":5,"price":10.55,"total":52.75,"productId":2,"invoiceId":8}]}

const newObject = {
  ...myJson, // keep the rest but map "itens"
  itens: myJson.itens.map(({ id, invoiceId, ...iten }) => ({
    ...iten, // everything except "id" and "invoiceId"
    total: iten.quantity * iten.price // recalc total
  }))
}

console.log("newObject:", newObject)
.as-console-wrapper { max-height: 100% !important; }


Unformated page

Question: I'm not sure if this is intended, but a got following message on unformated white page:
You have too many pending edits. Further edits cannot be submitted until prior edits have been approved.
Just wanted to add some missing "version" tags to make it easier to filter questions.
Comment: More info on this feature: https://meta.stackexchange.com/a/281202/
Answer: The message is intended. But I think it should have appeared as a tooltip in the form. So due to some JavaScript glitch your browser submitted the form regularly instead of making an AJAX request.
Comment: The message itself is OK. I will try it again later - may really an browser/AJAX problem. Thanks.
Answer: It's not brwoser related. Steps to reproduce ...

open X tabs, where you want to edit something
make your edits ...

If your edit limit is reached and you hit (a not greyed out and clickable) "edit" link in another tab, you'll see that white page.

Unformated page


Adding a webapp "alias" to Tomcat 7 on Linux

Question: I have a Tomcat 7 running on CentOS.
Given is a configuration where I have my webapp "foo" placed in webapps/foo.war. I can access it without any problems using http://host.name/foo.
Now I want to get access to the same webapp using a 2nd URL - "http://host.name/bar".
Setting up a webserver in front of my Tomcat is not an option so I need something like mod_rewrite for Tomcat.
What I have tried so far is to setup another context like this:
<Context path="/bar" docBase="foo"/>

At first it seems to work, but at the second look it shows that this isn't actually an "alias" - it is a second instance from my webapp which really is not a valid option for me.
So... does anybody know how to get some kind of aliasing or URL rewriting for Tomcat?
Answer: There is something similar to mod_rewrite for servlet containers called URL Rewrite. Taken from SO.
Comment: Same problem. Using this config I have two seperate instances from my webapp (and so I have 2 different instance from my cache...)
Comment: @pascal-schmiel I've updated my answer.
Comment: I've put all the stuff in my ROOT webapp, added my rewrite rule and it's working perfect - thanks!
Answer: In your special case, what about setting a symlink in your webapps directory?
Asume your directory looks like this:
ls webapps/
foo  foo.war

Just add a symlink to foo with the name bar:
ln -s foo bar

Getting this:
ls webapps/
foo  bar  foo.war

Comment: looks like a great idea.
sad news: with a symlink in my webapps directory I get a second webapp instance too ("bar" directory in work/Catalina/localhost/)
Answer: You might be able to find (a few exist) or write a small Java web app that reverse proxies from one URL pattern to another. See https://github.com/ahabra/reverse-proxy.


Getting 400 bad request when trying to redirect to main page

Question: I want to create a simple crud app for employee management system. When I click on add button in the browser i get redirected to localhost:9090/employees/new, however when I click on submit button instead of redirecting back to localhost:9090/employees I get an error (bad request-400) what might be the issue?
This is my employee controller
package com.example.crudempdep.controller;

import com.example.crudempdep.model.Employee;
import com.example.crudempdep.service.EmployeeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class EmployeeController {
    @Autowired
    private EmployeeService employeeService;
    @GetMapping("/employees")
    public String getAllEmployees(Model model) {
        List<Employee> employees = employeeService.getAllEmployees();
        model.addAttribute("employees", employees);
        return "employees";
    }
    @GetMapping("/employees/new")
    public String createEmployee(Model model) {
        model.addAttribute("employee", new Employee());
        return "create_employee";
    }

    @PostMapping("/employees")
    public String addEmployee(@ModelAttribute("employee") Employee employee) {
        employeeService.saveEmployee(employee);
        return "redirect:http://localhost:9090/employees";
    }

    @PutMapping("/employees/{id}")
    public void updateEmployeeById(@PathVariable Long id, @RequestBody Employee employee) {
        Employee e = employeeService.getEmployeeById(id);
        if (e != null) {
            e.setFname(employee.getFname());
            e.setLname(employee.getLname());
            e.setDepartment(employee.getDepartment());
            employeeService.saveEmployee(e);
        }
    }
    @DeleteMapping("/employees/{id}")
    public void deleteEmployeeById(@PathVariable Long id) {
        employeeService.deleteEmployeeById(id);
    }

}

This is the employees.html
<!DOCTYPE html>

  <meta charset="ISO-8859-1">
  <title>Employee Management System</title>
  <link rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
        crossorigin="anonymous">

  Employee Management System

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

  </button>

        Employee Management

        Department Management

 List Students

       Add Student

       Employee First Name
       Employee Last Name
       Employee Department
       Actions

        Update

        Delete

this is the create_employee.html

<!DOCTYPE html>

  <meta charset="ISO-8859-1">
  <title>Employee Management System</title>
  <link rel="stylesheet"
        href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css"
        integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm"
        crossorigin="anonymous">

  Employee Management System

  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#collapsibleNavbar">

  </button>

        Employee Management

 Create New Employee

        <form th:action="@{/employees}" th:object="${employee}" method="POST">

             Employee First Name

                  <input
                          type = "text"
                          name = "fname"
                          th:field = "*{fname}"
                          class = "form-control"
                          placeholder="Enter Employee First Name"
                  />

             Employee Last Name

                  <input
                          type = "text"
                          name = "lname"
                          th:field = "*{lname}"
                          class = "form-control"
                          placeholder="Enter Employee Last Name"
                  />

             Employee Department

                  <input
                          type = "text"
                          name = "department"
                          th:field = "*{department}"
                          class = "form-control"
                          placeholder="Enter Employee Department"
                  />

            <button type="submit" class = "btn btn-primary">
              Submit
            </button>

        </form>

Note that I set server port to 9090 so that is why I hardcoded the redirection, but it still does not work
Answer: You should use:
return "redirect:/employees";

instead of
return "redirect:http://localhost:9090/employees";

in the post method for employees


Add an argument to nginx redirect, only if it's not already defined

Question: I am redirecting users based on their location, using nginx. I want to add an argument to the query string only if that argument isn't already defined -- if it is defined, I don't want to change it. The argument is called tag.
This was my first attempt. I was hoping that it would fall to the second location if it had the tag= string in the URL anywhere, fall to the third if it had a querystring but was missing tag, and fall to the first if there was no querystring at all.
location / {
        return 302 https://$local_site$request_uri?tag=mytag;
}
location /tag=/g {
        return 302 https://$local_site$request_uri;
}
location /\?/ {
        return 302 http://$local_site$request_uri&tag=mytag;
}

Then I learned that you can't see the querystring when drilling down by location. And I've also learned that if is evil.
Is there a way to do this without using if?
Answer: nginx location entries match only URI part of the URL, not the query strings. You might achieve what you are looking after with map. The following needs to be in http block:
EDIT: My original answer had an issue with duplicate tag entries in resulting URL. The original solution is at the end of the post, this is a fixed version
map $args $newargs {
    default $args&tag=mytag;
    ~ ^(.*)(tag=[^&]+)(.*)$ $1$2$3;
}

And then you would have the following location block:
location / {
    rewrite (.*) $1?$newargs temporary;
}

We use the map feature to define $newargs from $args variable, which contains the query string in the URL. The default option is to append &tag=mytag to the string.
If the query string contains tag=something string, then we simply copy the query string to a new request.
Finally, we use the $newargs variable as the query string in the rewrite destination.
This is the original answer:
map $arg_tag $tag {
    default $arg_tag;

    ~ ^$ mytag;
}

And then you would have the following location block:
location / {
    return 302 https://$local_site$request_uri?tag=$tag;
}

Here we first make a mapping from tag query argument into $tag variable. First line sets the default to the query argument value. The second line tests if the argument is empty, and sets $mytag as the value if it is.
Then you can use the $tag variable anywhere with the values mapped like you described.
Comment: But there will be two `tag` arguments
Comment: Do you mean like `https://example.com/uri?tag=1&tag=2`?
Comment: yes. Also, I'm not sure that `return` will replace `?` with `&`
Comment: What confuses me about this answer is that it doesn't seem to deal with any of the ?/& stuff. And does it drop all the query keys other than tag, or does it keep them all and duplicate the tag key?
Comment: I updated the answer with an alternative approach that should not have the issue with duplicate `tag` key. nginx generates `$arg_` variable for every variable in the query string, so one does not need to take care of `?` / `&` characters here. The original answer preserved all query string variables, as those are included in `$request_uri`.
Answer: Basically if should be avoided, but that doesn't mean you must not use it.
location / {
    if ($arg_tag) {
        return 302 https://$local_site$request_uri;
    }
    rewrite ^(.*) https://$local_site$1?tag=mytag;
}

Comment: Okay, thank you. Two followup questions: Is this an okay place to use `if`, and why use a rewrite instead of a return the second time?
Comment: One further thing -- does this drop all the arguments other than tag?
Comment: `rewrite` preserves query args.
Comment: Here we don't use any other directives except rewrite module ones (`rewrite` and `return`) so it's safe to use `if`. We just send redirect and stop processing request.


How is working multiple loss layer using caffe?

Question: Make some networks like that
<code>Conv(1-1)-Conv(1-2)-Loss1-Conv(2-1)-Conv(2-2)-Loss2
</code>
When I train this networks using caffe, How is working?
Conv(2-1) and Conv(2-2) are updated using Loss2. I can get it.
But how is updating weights in the Conv(1-1) and Conv(1-2)?
Only using Loss1? or Using summations both gradient from Conv(2-1) and gradient from Loss1?
Answer: Caffe (like other SGD based solvers) uses the chain rule to compute derivatives. The loss of your net is the sum of both loss layers and the gradients estimated are the gradients of the overall loss. The derivative of loss1 w.r.t conv2's parameters is zero, thus loss1 has no effect on the update of conv2's params, as expected.
Comment: Thanks for your kind.
Comment: Yes, loss1 has no effect to conv2's weights. How about conv1's weight?? You mean just all of conv layers updated by overall loss(sum of both loss layers)?
Comment: @HotaekHan computing the gradients of the net is quite simple thanks to the chain rule: it allows to "break" the computation to a layer-by-layer product. If you look at a loss which is a sum of two terms, then the gradient is a sum of two derivatives, accordingly.


Black Scholes options pricing

Question: I am investigating how involved creating a very simple options trading platform will be(not for profit but for learning purposed). Can someone please explain the process flow of how Black Scholes option pricing is used within trading platforms, the below is my understanding please correct me if i am mistaken:
1) in memory prices of options derived from Black Scholes formula.
2) an incoming buy order for an option in FIX protocol format.
3) trading platform compares the price of buy order with the price derived from Black Scholes and decides to buy accordingly.
please correct me if i am mistaken anywhere thanks in advance
Answer:
1) in memory prices of options derived from Black Scholes formula.

That is the job of the user application, Quickfix will not help in any matter regarding this.

2) an incoming buy order for an option in FIX protocol format.

You take the message, parse it and store the rwquired information for yourself.

3) trading platform compares the price of buy order with the price derived from Black Scholes and decides to buy accordingly.

This again is the job of the user application. Inforamtion collected from Step 2 will help you in this.
FIX is a message format for communicating, which should be kept away from your programming logic. Else it will slow down the messaging unnecessarily for no apparent gain.

Black Scholes options pricing


java API for google Authenticator

Question: I wanna add two factor authentication using Google Authenticator and was wondering if google provides with java api's. I tried searching for it but din't find any.
Can anyone point me to the java api if there are any.
If not how can i go about using Google Authenticator in my web based java application.
I am using Spring framework for my existing application
Answer: In fact, Google Authenticator has nothing to do with Google services. What you need to look for is TOTP. Research again using TOTP and rfc6238 as keywords and you will find lots of resources.
Answer: Java library for google authenticator was implemented and can be found here,
https://github.com/wstrange/GoogleAuth
Answer: Sorry if this is too much of a necro-post, but I found this library on GitHub - maybe it can help you (and others looking for the same). :)
Note:  this is not an official Google library, but it follows the RFC 6238 spec for Time-based One-time Password (TOTP), and the author looked at the C code for Google Authenticator for reference.

java API for google Authenticator


Erro cadastrar dados na ViewModel

Question: Tenho essa pergunta onde onde fiz de acordo com as repostas, minha lógica... Só que agora, ao cadastrar os dados, um erro foi gerado. Esse erro se refere a propriedade de uma view que não pode ser nula, que é o ID. Ou seja, pelo que entendi, os dados não foram cadastrados, e por algum motivo isso ocorreu não gerando nenhum registro na tabela, ou não está reconhecendo a lógica...
Bem, o meu controller esta dessa forma:
 // GET: Controller/Create
    public ActionResult Create()
    {
        return View(new AnamineseViewModel
        {
            CliCliente = new CliCliente(),
            Tabela2= new Tabela2(),
            Tabela3 = new Tabela3(),
            Tabela4 = new Tabela4(),
            Tabela5 = new Tabela5(),
        });
    }

    // POST: Controller/Create
    [HttpPost]
    public ActionResult Create(AnamineseViewModel anaminese)
    {
        // TODO: Add insert logic here
        if (ModelState.IsValid)
        {
            db.CliCliente.Add(anaminese.CliCliente);
            db.Tabela2.Add(anaminese.Tabela2);
            db.Tabela3.Add(anaminese.Tabela3);
            db.Tabela4.Add(anaminese.Tabela4);
            db.Tabela5.Add(anaminese.Tabela5);

            db.SaveChanges();
            return RedirectToAction("Index");
        }

        return View(anaminese);
    }

Tem alguma coisa errada com isso?
EDIT
A view correspondente:
@model MeuProjeto.Models.AnamineseViewModel

@{
    ViewBag.Title = "Create";
}

@using (Html.BeginForm())
{
    @Html.AntiForgeryToken()

Create

@Html.Partial("_PartialCliente", Model.CliCliente)
@Html.Partial("_PartialTabela2", Model.Tabela2)
@Html.Partial("_PartialTabela3", Model.Tabela3)
@Html.Partial("_PartialTabela4", Model.Tabela4)
@Html.Partial("_PartialTabela5", Model.Tabela5)

        <input type="submit" value="Create" class="btn btn-default" />

}

Tabela2
@model NutriSport.Models.AnaAnamineseAlimentar

@*@using (Html.BeginForm())
{
@Html.AntiForgeryToken()*@

AnaAnamineseAlimentar

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaObjetivosMetas, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.AnaObjetivosMetas, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AnaObjetivosMetas, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaRotina, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.AnaRotina, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AnaRotina, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaDisposicao, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.AnaDisposicao)
                @Html.ValidationMessageFor(model => model.AnaDisposicao, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaComorbidades, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.AnaComorbidades, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AnaComorbidades, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaResfriado, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.AnaResfriado)
                @Html.ValidationMessageFor(model => model.AnaResfriado, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaMedicamentos, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.AnaMedicamentos, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AnaMedicamentos, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaConsumoAgua, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.AnaConsumoAgua, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AnaConsumoAgua, "", new { @class = "text-danger" })

            @Html.LabelFor(model => model.CliId, "CliId", htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.Hidden("CliId", null, htmlAttributes: new { @class = "form-control" })
                @Html.ValidationMessageFor(model => model.CliId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RecId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.HiddenFor(model => model.RecId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RecId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RefId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.HiddenFor(model => model.RefId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RefId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.HiddenFor(model => model.QfaId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QfaId, "", new { @class = "text-danger" })

    @*

            <input type="submit" value="Create" class="btn btn-default" />

*@

@*  }*@

    @Html.ActionLink("Back to List", "Index")

CliCLiente
@model NutriSport.Models.CliCliente

@*@using (Html.BeginForm())
{
@Html.AntiForgeryToken()*@

CliCliente

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CliNome, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.CliNome, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CliNome, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CliDataNascimento, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.CliDataNascimento, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CliDataNascimento, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CliEmail, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.CliEmail, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CliEmail, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CliSexo, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.CliSexo, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CliSexo, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CliCidade, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.CliCidade, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CliCidade, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CliTelefone, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.CliTelefone, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CliTelefone, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CliCelular, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.CliCelular, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CliCelular, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.CliOcupacao, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.CliOcupacao, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.CliOcupacao, "", new { @class = "text-danger" })

    @*

            <input type="submit" value="Create" class="btn btn-default" />

*@

@* }*@

    @Html.ActionLink("Back to List", "Index")

Tabela3
@model NutriSport.Models.RecRecordatorio

@*@using (Html.BeginForm())
{
@Html.AntiForgeryToken()*@

RecRecordatorio

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RecId, "RecId", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.Hidden("RecId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.RecId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RecHoraDorme, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.RecHoraDorme, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RecHoraDorme, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RecHoraAcorda, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.RecHoraAcorda, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RecHoraAcorda, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.HiddenFor(model => model.AnaId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AnaId, "", new { @class = "text-danger" })

    @*

            <input type="submit" value="Create" class="btn btn-default" />

*@

@*  }*@

    @Html.ActionLink("Back to List", "Index")

Tabela4
@model NutriSport.Models.RefRefeicao

@*@using (Html.BeginForm())
{
@Html.AntiForgeryToken()*@

RefRefeicao

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RefId, "RefId", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.Hidden("RefId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.RefId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RefTipo, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.RefTipo, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RefTipo, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RefHorarioLocal, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.RefHorarioLocal, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RefHorarioLocal, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.RefAlimentosQuantidades, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.RefAlimentosQuantidades, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.RefAlimentosQuantidades, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.HiddenFor(model => model.AnaId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AnaId, "", new { @class = "text-danger" })

    @*

            <input type="submit" value="Create" class="btn btn-default" />

*@

@*  }*@

    @Html.ActionLink("Back to List", "Index")

Tabela5
@model NutriSport.Models.QfaQuestionarioFrequenciaAlimentar

@*@using (Html.BeginForm())
{
@Html.AntiForgeryToken()*@

QfaQuestionarioFrequenciaAlimentar

    @Html.ValidationSummary(true, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaId, "QfaId", htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.Hidden("QfaId", null, htmlAttributes: new { @class = "form-control" })
            @Html.ValidationMessageFor(model => model.QfaId, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaGrupoAlimentar, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.QfaGrupoAlimentar, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QfaGrupoAlimentar, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaDia, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.QfaDia, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QfaDia, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaSemana, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.QfaSemana, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QfaSemana, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaMes, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.QfaMes, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QfaMes, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaNunca, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.QfaNunca)
                @Html.ValidationMessageFor(model => model.QfaNunca, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaRaramente, htmlAttributes: new { @class = "control-label col-md-2" })

                @Html.EditorFor(model => model.QfaRaramente)
                @Html.ValidationMessageFor(model => model.QfaRaramente, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.QfaObservacao, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.EditorFor(model => model.QfaObservacao, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.QfaObservacao, "", new { @class = "text-danger" })

        @Html.LabelFor(model => model.AnaId, htmlAttributes: new { @class = "control-label col-md-2" })

            @Html.HiddenFor(model => model.AnaId, new { htmlAttributes = new { @class = "form-control" } })
            @Html.ValidationMessageFor(model => model.AnaId, "", new { @class = "text-danger" })

    @*

            <input type="submit" value="Create" class="btn btn-default" />

*@

@*  }*@

    @Html.ActionLink("Back to List", "Index")

Comment: Qual o erro que aparece?
Comment: An exception of type 'System.ArgumentNullException' occurred in EntityFramework.dll but was not handled in user code

Additional information: Valor não pode ser nulo. No trecho db.CliCliente.Add(anaminese.Cliente)
Comment: Poste na sua pergunta como estão suas *Views*, por favor.
Comment: As *Partials* também.
Comment: São bem grandes... Tem algum problema?
Comment: Não. Problema não tem.
Comment: Coloquei as partials
Comment: @João entendi sim... Só que nos campos de Id não preciso que sejam editorfor... O editorfor irá criar um campo de texto, isso pode confundir o usuário e induzi-lo a preencher esse campo, já que não é para preencher.... E eu tentei tipo as view com o meu ViewModel, só que eles não conseguem acessa-lo... Mas vou tentar aqui pra ver!
Answer: Tem alguns problemas aí. Como todas as relações são de N para 1 (e não de 1 para N), as Partials terão que ser chamadas assim:
@Html.Partial("_PartialCliente", Model)
@Html.Partial("_PartialTabela2", Model)
@Html.Partial("_PartialTabela3", Model)
@Html.Partial("_PartialTabela4", Model)
@Html.Partial("_PartialTabela5", Model)

Isto porque, ao criar os campos do formulário, o Helper não especifica de qual entidade o campo vem. Por exemplo:

    @Html.LabelFor(model => model.AnaRotina, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.AnaRotina, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.AnaRotina, "", new { @class = "text-danger" })

Vai criar:

    Rotina

        <input type="text" name="AnaRotina" id="AnaRotina" class="form-control" />

O certo seria:

    Rotina

        <input type="text" name="Tabela2.AnaRotina" id="Tabela2_AnaRotina" class="form-control" />

Então temos que mudar @model de todas as Partials para:
@model MeuProjeto.Models.AnamineseViewModel

E os campos:

    @Html.LabelFor(model => model.Tabela2.AnaRotina, htmlAttributes: new { @class = "control-label col-md-2" })

        @Html.EditorFor(model => model.Tabela2.AnaRotina, new { htmlAttributes = new { @class = "form-control" } })
        @Html.ValidationMessageFor(model => model.Tabela2.AnaRotina, "", new { @class = "text-danger" })

Outra coisa é que você está criando @Html.BeginForm em todas as Partials. Isto está errado. @Html.BeginForm fica na View principal (o que já está feito corretamente). Apague os @Html.BeginForm das Partials.
Comment: Mas eu tentei dessa forma, só que a View não consegue mudar e acessar dessa forma... Mas vou tentar aqui então!
Comment: Outra coisa, com relação aos campos de Id, eles são necessários? Ou seja, quando criei o scaffolding, campos do tipo dropdown foram criados e referentes aos Ids... Eles são necessários nas views?
Comment: Cara deu certo! Mas agora estou tendo um outro problema.. Ao salvar no banco, alguns relacionamentos não estão sendo respeitados e salvos no banco.... Fiz até [essa pergunta](http://pt.stackoverflow.com/questions/131105/relacionamentos-n%C3%A3o-salvos).

Erro cadastrar dados na ViewModel


Creating a custom date in smarty, using the year from a variable and the month and day of my choosing?

Question: I'm brand new to this, so go easy on me. I'm trying to pull just the date from the trip start date, use it in a custom date, so that each year, the date I am using in my IF statements doesn't have to be updated.
{$trip->start|date_format:'%Y'}

Will give me the year the trip is taking place. I only want certain information to be included in an email if it is being sent before April 15th of that same year.
{if $smarty.now <= strtotime(INSERT DATE HERE 0415)}

This is where I need help. How do I get it to pull the year from the trip, then use it to create April 15th of that year, then convert it using strtotime, so I can use it to limit what is sent?
I have tried this:
{assign var="tripyear" value="$trip->start|date_format:'%Y'"}
{if strtotime($trip->start) >= strtotime("$tripyear"0415)}
{if $smarty.now <= strtotime("$tripyear"0415)}

But I have no idea what I'm doing.
Answer: The code below assigns the year of the trip to 'tripyear'. It's like you said, but some brackets were missing:
{assign var="tripyear" value="{$trip->start|date_format:'%Y'}"}

If you type this, you will display today's date:
{$smarty.now|date_format}

If you type this, it will display the date of April 15 in the year of $tripyear:
{strtotime("{$tripyear}-04-15")|date_format}

By typing the code below, you will only display the text "hello" if today ($smarty.now) is earlier or on the same date as April 15 in the year of $tripyear.
{if $smarty.now <= strtotime("{$tripyear}-04-15")}
    hello
{/if}


Non parametric cointegration test in R

Question: I am not very comfortable with the (parametric) assumptions made in cointegration analysis. I have recently found that there is a way to carry out nonparametric conintegration analysis (a google search with the term 'nonparametric cointegration' yields several results).
Is anyone aware of an R package that allows for nonparametric cointegration analysis?
Comment: Perhaps of some interest: [Link](http://cran.r-project.org/web/packages/urca/index.html)
Answer: The original question is quite old, but ranks pretty high on Google search.
A good library with plenty of non-parametric or semi-parametric test for cointegration is LongMemoryTS. Full documentation of its function is here in its reference manual.

Non parametric cointegration test in R


How can grunt extract the JSON object when the file assigns the object to a variable

Question: I am trying to process the JSON objects cleanly but the JSON is assigned to a variable like this:
var test = { "foo" : "bar" };

I can use a file structures like this:
{ "foo" : "bar" }

And grab the JSON like this:
var jsonfile = grunt.file.readJSON(source)

But I need to automate this and preserve the current file structure.
Comment: You can `require` any file you like as long as it exports something. Grunt is just a library running on Node. You can do whatever Node can do.
Comment: Well, `var test = { "foo" : "bar" };` is not JSON, it's JavaScript. I'm not sure what you are trying to achieve.
Comment: I'm trying to read the objects into my custom grunt task.
Comment: When I remove the variable assignment it is compatible with grunt.file.readJSON so I would consider the syntax very close here. I just want to make the import work when there is a variable assignment to the object rather than manually removing the variable assignments.
Comment: Seems like `var jsonfile = grunt.file.readJSON(source)` does that. *edit:* So the issue that you don't want to manually edit your files? You could write a one time script which edits your files.
Comment: You get this error if the source file has a variable assignment and you try to readJSON `file (Unexpected token v). Use --force to continue.`
Comment: Well, sure, as I said, you have JavaScript. JavaScript is not JSON, so you cannot use `readJSON` to read that file. If you want to use `readJSON`, make sure you have JSON, not JavaScript. It seems like you want to use `readJSON` without changing the files, but that's not possible.
Comment: I think you are missing my point I know that. I am trying to read a javascript object into my custom grunt script. I can read JSON if I edit the source. I need to automate a process that reads the file and processes the Javascript Object. It becomes a JSON compatible parse if I manually edit but that is not what I want to do. I want the grunt script to read the file as either a library or parse out the object.
Comment: So you are looking for something like `var str = fs.readFileSync('...', 'utf-8'); var data = JSON.parse(str.substr(str.indexOf('{'), str.lastIndexOf(';')));` ? Assuming of course the object literal would also be valid JSON.
Comment: great I knew it had some syntax related to filesystem
Comment: That's node, not grunt: https://nodejs.org/api/fs.html. I would advice against doing this though. It's error prone and harder to maintain.
Comment: so no way to include external javascripts into a grunt task?
Comment: Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/80710/discussion-between-jack-shultz-and-felix-kling).
Answer: The problem is I could not find a way to include the javascript file into my grunt task. So what I did instead was read the file as a literal string.
Then using regex I removed the parts of the string representing a variable assignment. Finally I could parse the string as an object
  var test = grunt.file.read(source),
  re = new RegExp('var?.test?.=|;','gi'),
  test = JSON.parse(test.replace(re, ""));

Comment: Felix King had the best solution - just make sure your JS file exports something and then `require` your JS file at the top of your grunt file, just like you've `require`'d all of your other grunt plugins.
Comment: Well it did not work when I tried that. This did the trick however.
Answer: FelixKing's solution realized:
//somefile.js
var someJSONObject = {
    SOME_KEY: "VALUE";
};

module.exports = someJSONObject;

//Gruntfile.js
var json = require('somefile');
console.log(json.SOME_KEY); //logs "VALUE"

module.exports = function(grunt) {
  //...rest of grunt file
}

Way more maintainable (and way more flexible) than parsing "var =" out of a raw string with RegEx. You're not limited to just JSON anymore, but any JavaScript.
Just to pre-empt any concerns you have about re-using a JS file for multiple purposes (so module might not be defined in somefile.js when it's not in a node environment), you can do this:
    //somefile.js
    var someJSONObject = {
        SOME_KEY: "VALUE";
    };

    //CommonJS export syntax
    //don't do anything if module.exports is not in scope
    if ( typeof module === "object" && typeof module.exports === "object" ) {
        module.exports = someJSONObject;
    }

Comment: I agree this looks more maintainable, I don't know what I did differently, but when I tried that, the variable I assigned the 'someJSONObject' only had null.
Comment: @JackShultz - my bad, the line in the Gruntfile.js should have read: `require('somefile');`


Asterisk realtime include dialplans

Question: I noticed that when creating a dialplan in asterisk on realtime, I cannot inlcude contexts.
So to be clear, I want to do the following:
<code>[context1]
switch => Realtime

[context2]
include => context1
switch => Realtime
</code>
Or
<code>[context1]
switch => Realtime/context1

[context2]
switch => Realtime/context1
switch => Realtime/context2
</code>
But none of the above seems to work. Is there any way to get this working? I need to use this in realtime.
Thanks in advance.
Comment: What error do you get on the CLI when you try this?
Comment: None, but I already figured it out. See my answer.
Answer: Realtime doesnt support inlcudes within realtime. Thereby you can tweak a little with the Goto function.
If you do this in your extensions.conf
<code>[context1]
switch => Realtime

[context2]
switch => Realtime
</code>
And then in the database do this:
<code>[context1]
exten => _XXXXXXXXX,1,Goto(context2,${EXTEN},1)
</code>
The above needs to translated to a query, I think you know how you need to do that since you are using Realtime.

Asterisk realtime include dialplans


kernel density estimation for more than one attribute

Question: Consider the Iris dataset, which has 4 attributes. KDE(kernel density estimation) is univariate analysis then how can we get overall kernel density estimation of the iris dataset
Answer: With multivariate data, you need to use multivariate kernel density estimation, that differs from univariate case by either using product of univariate kernels, or multivariate kernels (e.g. instead of univariate Gaussian, multivariate normal density as kernel).
Comment: A density estimate for any other purpose could be useful, but at the same time it would hard to know how far to trust it if you can't see it. I wouldn't trust a univariate estimate I couldn't see.
Comment: That's surely right in principle. In practice, good luck visualizing a surface over all the variables based on just 150 observations for the _Iris_ data. I would focus on univariate and bivariate density estimation at most.
Comment: @NickCox it doesn't say that the point is plotting it, otherwise agree.


Checking Available Update data - AJAX error

Question: I'm having problems with a local site that I imported to Acquia Dev desktop from one of my live sites.  Everytime I try to Check for Available Update data, I get an Ajax error

Error Checking Update Data Please Continue to error page An AJAX HTTP
  request terminated abnormally. Debugging information follows. Path:
  /batch?id=676&op=do StatusText: ResponseText: ReadyState: 4

Clicking the error page link, drupal returns me to the available updates page with a message

An error occurred trying to get available update data.

Any ideas?
Thanks
Sharon
Answer: It turns out the problem was with Cron, It was not running due to some custom php code.  Remove the code and everything seems fine now.


Check the following inequalities with the Chebyshev inequality

Question: Let $X \sim Poi(\lambda).$ Use the Chebyshev inequality to check the next inequalities:

$\mathbb{P}[X\leq{\frac{\lambda}{2}}] $ $\leq{\frac{4}{\lambda}}.$

$\mathbb{P}[X\geq{\frac{2}{\lambda}}] $ $\leq{\frac{1}{\lambda}}.$

I assumed that $X$ is non-negative, then as $\mathbb{E}(X) = \mathbb{V}ar(X) = \lambda$, I got $\mathbb{E}(X^2)$ and substituted in Chebyshev inequality but my inequalities weren't met. Help!
Answer: For any random variable $X$ with $\operatorname{E}[X^2]<\infty $ and $c< \operatorname{E}[X]$ we have that
$$
\begin{align*}
\Pr [X\leqslant c]&=\Pr [-X\geqslant -c]\\
&=\Pr [\operatorname{E}[X] -X\geqslant \operatorname{E}[X] -c]\\
&\leqslant \Pr [|X-\operatorname{E}[X]|\geqslant \operatorname{E}[X] -c]\\
&\leqslant \frac{\operatorname{Var[X]}}{(\operatorname{E}[X] -c)^2}
\end{align*}
$$
Then if $X\sim\operatorname{Poisson}(\lambda )$ and $c=\lambda /2$ we find that $\Pr [X\leqslant \lambda /2]\leqslant 4/\lambda $, as desired. For the second case it seems that there is a typo, it probably must be $\Pr [X\geqslant 2\lambda ]\leqslant 1/\lambda $ instead of the given inequality (by example taking $\lambda =2$ we can see that the given inequality doesn't hold as $\Pr [X\geqslant 1]>3/4$).


Is there any subset of Complex numbers that is algebraically closed?

Question: That any polynomial that is allowed to have coefficients from that subset has also a root in that subset
Comment: The set of algebraic numbers. Many others.
Comment: $\mathbb{C}$ and $\{0\}$ come to mind
Answer: The set of algebraic numbers is algebraically closed. It is countably infinite, so it is a very small subset of the set of complex numbers.
Note that an algebraic number is a zero of a non-constant polynomial with integer coefficients. The set of algebraic numbers is the smallest algebraically closed subset of $\mathbb{C}$.
There are many other proper subsets of the complex numbers that are algebraically closed.
Answer: the algebraic numbers, say $Q_0$ are the algebraic closure of the rationals. if $\alpha_1$ is transcendental then set $Q_1$ to be the algebraic closure of $Q(\alpha_1)$. this can be continued quite far, modulo the availability of a choice function


p-value approach - clarify teacher's solution?

Question: So I have a question with my teacher's solution below and I'm confused about one of the steps in their solution. I would appreciate some clarification.
Two brands of coffee were compared. Two independent random samples of 50 people each were asked to taste either Brand A or Brand B coffee, and indicate whether they liked it or not. Eighty four percent of the people who tasted Brand A liked it; the analogous sample proportion for Brand B was ninety percent.
(A) At α = 0.01, is there a significant difference in the proportions of individuals who like the two coffees? Use the p-value approach.
So I circled in blue a step where I'm confused about in the teacher's solution. I don't understand why P(Z<-0.89) = 0.2061.
On the z-score table -0.89 is equal to 0.1867 so shouldn't it be that value instead? where did 0.2061 come from? Is it possible that the teacher made an error or am I not understanding something?
Comment: The P-value for a 2-sided test should be $P(|Z| \le 0.89) = P(Z \le -0.89) + P(Z \ge 0.89) = 2P(Z \le -0.89),$ which can be found from printed tables of the standard normal distribution or by using software. In R statistical software, code `2*pnorm(-.89)` returns 0.3734659.
Answer: Minitab output for this problem is as follows:
<code>Test and CI for Two Proportions

Sample   X   N  Sample p
1       42  50  0.840000
2       45  50  0.900000

Difference = p (1) - p (2)
Estimate for difference:  -0.06
99% CI for difference:  (-0.232561, 0.112561)
Test for difference = 0 (vs ≠ 0):
    Z = -0.89  P-Value = 0.372
</code>
Notes: (1) The major issue is in doubling the tail probability to get the P-value for a two-sided test. (2) Minitab may be computing the $Z$-statistic to more places than printed. (I think the value to three places is $-0.892).$ If so, that
accounts for the small difference in P-values between R and Minitab.


Facebook login doesn't work even with right site url

Question: I have my web application deployed in tomcat. Application loads fine with the URL:
http://domain.com/portal-app/ (domain.com=10.124.23.33:8081 i couldn't enter ip:port in url.) i have also pasted the same URL in my app settings page.
But still i get the error on console while loading the home page. I don't get js alerts too. When i click on "login" button and enter username and pwd, it just throws the same message in the facebook pop-up window. Any help on this would be much appreciated.

"Given URL is not allowed by the Application configuration.: One or more of the given URLs >>is not allowed by the App's settings.  It must match the Website URL or Canvas URL, or >>>the domain must be a subdomain of one of the App's domains."

I had several times verified the URL in app settings. Both the application url that i use in browser and Facebook are same. Rather i just copy pasted the url.
Here is the code

    <fb:login-button show-faces="true" width="200" max-rows="1"></fb:login-button>

Answer: It looks like channelUrl is missing the .com and should be http://domain.com/portal-app/channel.html in your init function.
Comment: nope, the actual channel url is 10.124.23.33:8081 since the editor doesn't allow me to enter the full address (http://IP) i had it as 'domain'. please read through my 2nd line.


Resolution in rhythm

Question: People talk a lot about harmonic function (such as harmonic resolution). I don't really understand it and I understand that there are debates about correct analyses, developments, crazes, etc, but there's some kind of discourse, which goes on its merry way here and elsewhere.
Is there an equivalent for rhythm?
Take something like Shave and A Haircut. Ok, so that one is so familiar that there's a cultural expectation, but does much remain beyond that? It's in a call and response pattern, with the rest providing tension. Do aspects of the form of rhythm, beyond the inevitable cultural anticipation, provide tension and resolution in rhythm?
Can rhythm (probably localised to some cultural context) be analysed with a complex, informative, formal body of work, as harmony sometimes is? Does "functional rhythm" exist?
I'm not looking for a full tutorial, just confirmation (or otherwise) of the existence of such and maybe some pointers for further reading.
Comment: I'm thinking there must be some kind of functional rhythm concept out there. Otherwise, why would we compose so many drum cadences, and why would we consider some drum solos to be more effective than others?
Answer: I'd consider the equivalent of the tonic in rhythm to be the downbeat, or 1's and 3's.
In terms of resolution, 2's and 4's lead to 3's and 1's, and syncopated rhythms in general lead to the next major beat.
There are also grace notes in the form of the flam/drag rudiments which are single and doubled grace notes before an accented or normal-volume note, which is like an unmetered form of rhythmic leading.
In my experience though, these aspects of rhythm are just inherent to the way music uses the concept of timekeeping and subdivision, so they're not formally theorized about to the extent of melodic harmony/resolution. Maybe the meter/notation alone makes it clear enough.
Answer: In trying to interpret this question, I think partly it's asking whether there exists detailed music theory of rhythm, beyond just the basics of rhythmic notation and meter that one would encounter in a class on the fundamentals of music.  And yes, there is a huge amount of scholarship out there about various theories of rhythm and meter (some of which dates back centuries).
Yes, there are patterns of rhythm, and there are various functions ascribed to it.  For example, one can begin with discussion of the origin of accent, the differentiation of accent into various categories (e.g., metric -- produced by regularity in rhythmic patterns -- vs. agogic -- produced by length of a note -- vs. articulation -- produced by attack and/or volume).  Accent influences creation of meter, as well as divergences from it.  Just as melodic and harmonic composition consists of creating patterns and fulfilling expectations at times, while diverging from and denying expectations at other times, rhythm and meter require a similar interplay.
Take, for example, the opening phrase of the show tune "Anything Goes": it begins by a pattern of regular rhythms that generate a steady beat and set up the expectation for a metric regularity, then the rhythm begins to use syncopation and subvert that metric regularity, until eventually the rhythm of the melody stops suddenly, pauses, and then provides a regular succession of short notes followed by a long note (agogic accent) that is not syncopated, confirms the metric regularity, and thus concludes the phrase.
For another obvious example of rhythm taking on an active functional role in music, think of the closing bars of major classical symphonies, where there are often repeated long chords on strong beats, often followed by a very long note on the tonic, effectively an extreme agogic accent.  The confirmation of the standard pulse of the piece, followed by slowing and longer notes on strong beats helps to give a rhythmic feeling of "closure."
Anyhow, there are lots of more detailed theories of rhythm out there.  There are plenty of historical ones, but I assume you may be most interested in theories that are still actively discussed today.  The first of these is probably Cooper and Meyer's The Rhythmic Structure of Music (1960), which built on Meyer's theories of musical expectation and related it to rhythmic structure, giving a sort of architectonic approach to meter building up from basic patterns.  Lerdahl and Jackendoff in A Generative Theory of Tonal Music (1983) develop more hierarchical relationships of meter and rhythm happening on multiple levels and large spans of music, while Lawrence Kramer (The Time of Music, 1988) finds interest in the structure of the rhythm building up to tiny musical moments.  Theorists such as Thomas Clifton (Music as Heard, 1983) and Chris Hasty (Meter as Rhythm, 1997) come from various philosophical perspectives on how notions of rhythm and experience of music give rise to meter and other emergent phenomena of musical structure in the first place, while other theorists like Justin London (Hearing in Time, 2001) begin from a psychological and cognitive perspective on musical perception of rhythm and meter.
There's a lot more that's happened in the past couple decades, but that lays out some of the major perspectives on theories of rhythm developed in the late 20th century and can serve as a jumping off point.  Recently, interest has turned back to questions of how larger sensations of rhythmic units impact things like form.  Anyhow, there's a lot out there.  There are definitely plenty of theories about how rhythm can be "functional" and have lots of nuance, though I think there's less consistency about what approach is standard, unlike with harmony, where Roman numeral analysis and related notions of function have become dominant (no pun intended) in Anglo-American music theory.

Resolution in rhythm


Permutation confusion

Question: Five boys and five girls form a line with the boys and girls alternating. Find the ways of making the line.
The way I solved this problem was:
First, let's place the boys standing in line.
<code> _    B    _    B    _    B    _    B    _    B   _
</code>
So there are six gap places left where the girls can stand in $_6P_5$ ways and the boys can be arranged in $5!$ ways.
So according to me the answer should be $5!$ ($_6P_5$). But the answer was $2(5!)^2$.
I don't understand where did I go wrong.
Comment: Yes.now I get it .Thanks
Comment: @MorganRodgers: That seems like a complete answer. I doubt that anyone will add to it -- it should be posted as an answer so the question can be marked as answered.
Answer: The boys aren't identical first of all, so you need to take that into account. Secondly you can't choose those six places for the girls to line up; some of those choices will leave two boys next to each other. Thirdly, $(_{6}P_{5})$ is not equal to 5!. I'm not sure $(_{6}P_{5})$ would be what you want in this situation anyway; it would mean you have 6 objects placed into 5 places without repetition.
(I think I misunderstood some things in the original version of the question. But the main problem remains that the five girls cannot be arbitrarily placed into the six positions you have for them without sometimes leaving boys next to each other.)

Permutation confusion


Problema ao tentar pegar o $scope do form com Ionic

Question: Tenho o seguinte form que fica dentro de um modal:
<form name="usuarioForm"  novalidate="">

No final desse form tenho um botão onde passo o objeto que foi preenchido para uma função, e nessa função eu tento limpar o form dessa forma:
$scope.usuarioForm.$setPristine();

Porém recebo esse erro:

Error: $scope.usuarioForm is undefined

Outra coisa que notei, quando tento limpar o objeto dessa forma: $scope.usuario = ""; após salvar os dados nada acontece também. Ou seja, dá a impressão que esse modal não está dentro do controller.
Eu coloquei esse modal dentro da minha página que possui o controller: loginCtrl dessa forma:

Controller:
  $scope.salvar = function(usuario) {
    usuarioAPI.saveUsuario(usuario).success(function(data) {
      console.log("Salvar!");
      delete $scope.usuario;
      $scope.usuarioForm.$setPristine();
      $scope.closeModal();

    })
    .error(function(response, status) {
      console.log("erro " + status);

    });

  }

Código de abertura do modal:
$ionicModal.fromTemplateUrl('my-modal.html', {
    scope: $scope,
    animation: 'slide-in-up'
  }).then(function(modal) {
    $scope.modal = modal;
  });

  $scope.openModal = function() {
    $scope.modal.show();
  };

  $scope.closeModal = function() {
    $scope.modal.hide();
  };

Comment: como está o código do seu controller?
Comment: Vou editar a pergunta e colocar o código da função salvar que fica no controller
Comment: Poderia incluir também o código de abertura da modal? Creio que será importante para definir o problema.
Comment: Adicionei na pergunta @RicardoRodriguesdeFaria
Comment: @Techies cara, não consegui ti ajudar, me parece tudo ok, o form deveria ter sido atribuido para o scope.
Comment: Sim, ta estranho no Angular funciona, outra coisa que não está funcionando também é quando eu tento pega rum objeto, por exemplo: `$scope.usuario.nome` da erro
Answer: Seu problema parece ser a modal criando um novo scope.
O correto seria debugar no chrome, setar breakpoints e analisar a variável $scope e tal.
Já que você setou o scope da modal, você pode tentar acessar o scope pai assim:
$scope.$parent.usuarioForm.$setPristine();

Answer: Eu tive esse problema, resolvi da seguinte forma:
 - No seu button você pode passar o form dessa forma: ng-click="salvar(usuario, usuarioForm)".
 - Troque a chamada da function por  $scope.salvar = function(usuario, form)
 - Na hora do pristine você coloca form.$setPristine();
Para mim resolveu, sempre reseta o form que esta trabalhando.


Filtering for a column for all rows that have a specific string in it

Question: I am trying to get all unique values in a column that have a specific word in it,
for example if I want to find all values that have the word bird in it, regardless of Capitalization of first letter or not, how can I filter for that?
df.animal.unique() would give me all unique values in the column but I want only the ones that have Bird in the string or name if that makes sense, Thanks!
DF
 | Animal |
Eagle Bird
PigeonBird
Whale Fish
Dolphinfish
peacockbird
hawkBird
Falc Bird

Comment: Can you add some data sample?
Comment: Sorry I dnt have sample currently but I added a example of dataset df
Answer: Because need:

I want to find all values that have the word bird in it, regardless of Capitalization of first letter or not

use Series.str.contains with both words:
df = df[df.Animal.str.contains('bird|Bird')]

Or:
df = df[df.Animal.str.contains('[bB]ird')]

print (df)
        Animal
0   Eagle Bird
1   PigeonBird
4  peacockbird
5     hawkBird
6    Falc Bird

Comment: @Chris90 - not sure if understand, do you need only words with space, like `Eagle Bird` and `Falc Bird` ?
Comment: No sorry for confusion, I want all strings or rows where Bird or bird appears regardless if it has that space inbetween other words or not @jezrael
Comment: @Chris90 - Can you add expected output? Do you need unique words contains `bird` word?
Comment: @Chris90 - yop, if need all rows then answer working, but if need `['Bird', 'PigeonBird', 'peacockbird', 'hawkBird']` answer should be changed
Comment: thanks! If some values have a space between other words or not like in sample data set that is fine correct? Like Eagle Bird and PigeonBird @jezrael
Comment: Yes! I think your answer is correct because it returns all cells that contain Bird or bird,  as I wanted just all words in the column that contain the word bird anywhere in that column value whether starts with capital letter or not and has spaces between other words or not @jezrael
Comment: No just all rows that contain the Bird or bird anywhere in the cell @jezrael
Answer: Try using str.contains
df[df.animal.str.contains('bird', case=False)]

Comment: OP need `Capitalization of first letter`
Comment: Well it's not clear from `regardless of Capitalization of first letter or not`. Maybe data contains other letter also in caps.


Floating right on :after psuedo element breaks to new line when there is a space in HTML

Question: Here's a codepen that illustrates the issue that I'm having:
http://codepen.io/pcostanz/pen/ukzIf
I'm adding sort indicators as psuedo elements to a grid of inline-block elements, I'm using the :after psuedo element to do this. The problem is that the template can occasionally have comments or spaces within the cell content, and when the :after psuedo element is floated to the right of the cell this causes the psuedo element to break to a new line.
The width of the cells is generated via an Angular directive, so setting it in the CSS isn't an option.
.cell {
  border: 1px solid red;
  display: inline-block;
}
.cell:after {
  content: ">";
  display: block;
  float: right;
}

 Input

I don't quite understand why the two solutions I've come up with are working:

Change the element from :after to :before (http://codepen.io/pcostanz/pen/vwfkg)
Add margin-left: -100% to the psuedo element (http://codepen.io/pcostanz/pen/HqDhA)

Any insight or alternative solutions would be appreciated.
Comment: have you tried removing the `float: right` and setting `display: inline-block` on `.cell:after`?
Comment: Yeah, the `float:right` is necessary for the layout, `display: inline-block` also didn't help. I also tried using absolute positioning for the psuedo element but the grid won't allow for that due to the way it is generated. [see preview](http://codepen.io/pcostanz/pen/btxov)
Comment: Just to clarify, removing `float:right` 'fixes' this issue, but the problem is that I need to be able to have the :after psuedo element on the right side of the container element and absolute positioning isn't an option.
Comment: have you considered using an image instead of inserting content after? That way you could control where the "arrow" sits and not worry about new lines...
Comment: Yeah, restricted to using an icon font here, unfortunately.
Answer: This is a Chrome bug; it doesn't happen in Firefox. The extra spaces at the ends are hidden, that's just how HTML works for block-level elements. So the width of the box is set to the width of the text "Input", without spaces. But they are still there in the DOM. When you use :after, the > is, in effect, just appended to the content already there as if it's a . It's after the invisible space, which now comes into effect because it isn't last anymore, pushing the >. And floating it doesn't change the parent's width, so it snaps onto a new line.
That's the reason why it happens (bug! in Chrome only). Your first solution works because :before literally inserts the imaginary  before the content, so the invisible space isn't expanded. The second solution most likely works because the margin counteracts the right-pushing effect of the space, but don't quote me on that, I'm not sure.
The simplest solution would be to use :before. Semantically incorrect but hey, this works. Hope this answer helped you, I felt a little uncertain writing it ...
Comment: It looks like you're right, thanks for letting me know this is a bug with chrome. It looks like this bug isn't specifically related to psuedo elements, and can manifest itself with just a regular span. For now we're going to stick with the :before solution, if you have a link to the official bug report with google that would be great to include in the stylesheet comments.
Comment: @PatrickC Hmm, no I don't have a bug report link. In fact, I just discovered this today. I'll do some searching around if I get time.