PHP SimpleXML recursive function to list children and attributes

Question: I need some help on the SimpleXML calls for a recursive function that lists the elements name and attributes. Making a XML config file system but each script will have it's own config file as well as a new naming convention. So what I need is an easy way to map out all the elements that have attributes, so like in example 1 I need a simple way to call all the processes but I don't know how to do this without hard coding the elements name is the function call. Is there a way to recursively call a function to match a child element name? I did see the xpath functionality but I don't see how to use this for attributes.
Also does the XML in the examples look correct? can I structure my XML like this?
Example 1:
<application>
  <processes>
    <process id="123" name="run batch A" />
    <process id="122" name="run batch B" />
    <process id="129" name="run batch C" />
  </processes>
  <connections>
    <databases>
      <database usr="test" pss="test" hst="test" dbn="test" />
    </databases>
    <shells>
      <ssh usr="test" pss="test" hst="test-2" />
      <ssh usr="test" pss="test" hst="test-1" />
    </shells>
  </connections>
</application>

Example 2:
<config>
  <queues>
    <queue id="1" name="test" />
    <queue id="2" name="production" />
    <queue id="3" name="error" />
  </queues>
</config>

Pseudo code:
// Would return matching process id
getProcess($process_id) {
  return the process attributes as array that are in the XML
}

// Would return matching DBN (database name)
getDatabase($database_name) {
  return the database attributes as array that are in the XML
}

// Would return matching SSH Host
getSSHHost($ssh_host) {
  return the ssh attributes as array that are in the XML
}

// Would return matching SSH User
getSSHUser($ssh_user) {
  return the ssh attributes as array that are in the XML
}

// Would return matching Queue
getQueue($queue_id) {
  return the queue attributes as array that are in the XML
}

EDIT:
Can I pass two parms? on the first method you have suggested @Gordon
I just got it, thnx, see below
public function findProcessById($id, $name)
{
    $attr = false;
    $el = $this->xml->xpath("//process[@id='$id'][@name='$name']"); // How do I also filter by the name?
    if($el && count($el) === 1) {
        $attr = (array) $el[0]->attributes();
        $attr = $attr['@attributes'];
    }
    return $attr;
}

Answer: The XML looks good to me. The only thing I wouldn't do is making name an attribute in process, because it contains spaces and should be a textnode then (in my opinion). But since SimpleXml does not complain about it, I guess it boils down to personal preference.
I'd likely approach this with a DataFinder class, encapsulating XPath queries, e.g.
class XmlFinder
{
    protected $xml;
    public function __construct($xml)
    {
        $this->xml = new SimpleXMLElement($xml);
    }
    public function findProcessById($id)
    {
        $attr = false;
        $el = $this->xml->xpath("//process[@id='$id']");
        if($el && count($el) === 1) {
            $attr = (array) $el[0]->attributes();
            $attr = $attr['@attributes'];
        }
        return $attr;
    }
    // ... other methods ...
}

and then use it with
$finder = new XmlFinder($xml);
print_r( $finder->findProcessById(122) );

Output:
Array
(
    [id] => 122
    [name] => run batch B
)

XPath tutorial:

http://www.w3schools.com/XPath/default.asp

An alternative would be to use SimpleXmlIterator to iterate over the elements. Iterators can be decorated with other Iterators, so you can do:
class XmlFilterIterator extends FilterIterator
{
    protected $filterElement;
    public function setFilterElement($name)
    {
        $this->filterElement = $name;
    }
    public function accept()
    {
        return ($this->current()->getName() === $this->filterElement);
    }
}

$sxi = new XmlFilterIterator(
           new RecursiveIteratorIterator(
               new SimpleXmlIterator($xml)));

$sxi->setFilterElement('process');

foreach($sxi as $el) {
    var_dump( $el ); // will only give process elements
}

You would have to add some more methods to have the filter work for attributes, but this is a rather trivial task.
Introduction to SplIterators:

http://www.phpro.org/tutorials/Introduction-to-SPL.html
Comment: Thanks a ton, the first solution looks great but I have an error: PHP Fatal error:  Uncaught exception 'Exception' with message 'String could not be parsed as XML'. Im passing the file like this. $xml = "/path/to/file.xml"; is this correct?
Comment: @Phill No, it expects the XML string, not the filepath. If you want to pass a filepath, you have to pass `$data_is_url` as third param. See http://de3.php.net/manual/en/simplexmlelement.construct.php
Comment: @Phill or replace the call with `simplexml_load_file`
Comment: Hmm, made the change: $this->xml = new SimpleXMLElement($xml, NULL, TRUE); but still getting error: PHP Fatal error:  Uncaught exception 'Exception' with message 'String could not be parsed as XML' I made the change in the class example you have, is this correct?
Comment: "@Phill or replace the call with simplexml_load_file" replace where? In the constructor?
Comment: @Phill change `$this->xml = new SimpleXMLElement($xml);` to `$this->xml = new simplexml_load_file($xml);` If the error keeps coming then, the path is likely incorrect. Try to verify if you can open the path with `file_get_contents()` and see what it contains.
Comment: ok thats what I did and then got this: PHP Fatal error:  Class 'simplexml_load_file' not found in
Comment: @Phill sorry. Remove the new keyword from the function call
Comment: LOL, I miss that as well. Thnx again
Comment: Hey Gordon I had one other question. See Edit
Comment: @Phill Hmm, I think so. Try "//process[@id='$id' and @name='$name']" for an XPath then
Comment: I tried the AND but no go, I did find the solution though. //process[@id='$id'][@name='$name']


I want to prove$ f(x) = \frac{x^4-9x+3}{x+1}$ is uniformly continuous on $[1,\infty)$

Question: I am having difficulty getting $|f(x)-f(x_0)| < \epsilon$ Into the lipschitz inequality.
Comment: Okay, but it still won't work, for when $x\to\infty$, $f(x)\sim x^3$, which is also not uniformly continuous on any unbounded interval. (You see that most easily by using the identity $x^3-x_0^3=(x-x_0)(x^2+xx_0+x_0^2)$.)
Comment: It isn't uniformly continuous on $[1,\infty).$ $f$ is approximately $x^3$ for large x, and $(x+\delta)^3-x^3=3 \delta x^2 + o(\delta)$ as $\delta \to 0$ (by taking the derivative). Thus for small enough $\varepsilon$, ensuring $(x+\delta)^3-x^3 < \varepsilon$ requires $\delta < \varepsilon/(3x^{2})$, which is not uniform in $x$.
Comment: Lipschitz and uniformly continuous are different (though related) concepts. The function you list is neither, thanks to its singularity at $x=-1$. No wonder you have a difficulty, then.
Comment: Oh I forgot to mention on the interval from 1 to. Infinity.
Answer: Working directly through the definition of uniform continuity on this particular example is tiresome and not very illuminating. I would prove a more general result instead:

If $f:[1,\infty)\to \mathbb R$ is uniformly continuous, then $f(x)/x$ is bounded on $[1,\infty)$

Since for your function $f(x)/x \to\infty$ as $x\to\infty$, it is not uniformly continuous.
Proof of the highlighted claim: Let $\epsilon=1$ in the definition of uniform continuity, and pick the corresponding $\delta$. Let $M=\max_{[1,1+\delta]}|f|$. Then for $x\in [1+\delta,1+2\delta]$ we have $|f(x)|\le M+1$ (why?). By induction, for  for $x\in [1+k\delta,1+(k+1)\delta]$ we have $|f(x)|\le M+k$. Therefore, on each interval  $ [1+k\delta,1+(k+1)\delta]$, $k=0,1,2,\dots$, we have:
$$\frac{|f(x)|}{x} \le \frac{M+k}{1+k\delta}\le M+\delta^{-1}$$
This latter bound is independent of $k$, thus it holds on all $[1,\infty)$.


How can I load a Store by user ID?

Question: I am building a multi-seller commerce site, where a user can register and sell their product.  I need to display a menu link if the user is anonymous to "become a seller", where they are directed to log in and a create store form.
If the user is logged in, I want to display a menu link that displays "My Store" if they previously created a store.  To determine if they have a store, how can I load a store via their user ID?
I have been unable to find an example where someone can load a user's store.
Answer: The user ID is saved on the store when it's created. Therefore you can load it with code similar to the following one.
<code>$store = \Drupal::entityTypeManager()->getStorage('commerce_store')->loadByProperties(['uid' => \Drupal::currentUser()->id()]);
</code>
That will load the store based on the currently logged-in user.

How can I load a Store by user ID?


SELECT FROM Subquery performance

Question: I am looking for more performance for my project (PHP+MySQL), have a query that seem is too slow (select 2 random users from 1 table)
id  | name |  total | img
------------------------ --
1    user1   500      1
2    user2   600      2
3    user3   650      3

__
SELECT id1, id2, name1, name2, img1, img2, total1, total2
FROM (
  SELECT
    C1.id AS id1, C1.img AS img1, C1.name AS name1,
    C2.id AS id2, C2.img AS img2, C2.name AS name2,
    C1.total AS total1, C2.total AS total2
  FROM users C1, users C2
  WHERE C1.id <> C2.id
    AND ABS(C1.total - C2.total) < 200
) as t
ORDER BY RAND()
LIMIT 1

result
id1  | id2|  name1 | name2 | img1 | img2 |  total1 | total2
------------------------ -------------------------------------
1       3    user1   user3    1      3        500      650

is any way to improve it?
Comment: add indexes, remove outer query since its useless and FYI order by rand() slows queries down as well
Comment: Just a question: why do you need the outer query?
Comment: I think it's because of that C1.total - C2.total (not that I understand why it's being done like that).
Comment: i need to get 2 random users img with conditions that the difference between total is less than 200
Comment: best solution
http://stackoverflow.com/a/15310255/2054164
Answer: Make sure that you created indexes for all columns that are in the where clause:
CREATE TABLE `users` (
`id` INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY ,
`name` VARCHAR( 255 ) NOT NULL ,
`total` INT NOT NULL ,
`img` INT NOT NULL ,
INDEX ( `total`)
);

Also note that the following query (without the sub query) will give you the same results
SELECT
  C1.id AS id1, C1.img AS img1, C1.name AS name1,
  C2.id AS id2, C2.img AS img2, C2.name AS name2,
  C1.total AS total1, C2.total AS total2
FROM users C1, users C2
WHERE C1.id <> C2.id
  AND ABS(C1.total - C2.total) < 200
ORDER BY RAND()
LIMIT 1

You can check that at sql fiddle
Comment: If the table is already created (but the indexes are missing), use `alter table users add index idx_total(total)`
Answer: You may be able to optimize the inner SELECT, but using ORDER BY RAND() will always turn the performance to... I can't think of a better word than sh*t. Basically you're telling your DBMS to ingore all indexes and reorder the entire dataset, and once that dataset becomes anything more than 'tiny' it will be a very noticeable performance hit.
I just wrote another answer today about this which should work as long as you don't mind the results not necessarily being different every time.
edit
I just noticed that you're only selecting one row. Try this:
$rs = $dbh->query(
"SELECT COUNT(*) AS 'count'
 FROM users C1, users C2
 WHERE C1.id <> C2.id
   AND ABS(C1.total - C2.total) < 200");
$target = rand(0,$rs[0]['count']);
$rs = $dbh->query(
  "SELECT
   C1.id AS id1, C1.img AS img1, C1.name AS name1,
   C2.id AS id2, C2.img AS img2, C2.name AS name2,
   C1.total AS total1, C2.total AS total2
  FROM users C1, users C2
  WHERE C1.id <> C2.id
   AND ABS(C1.total - C2.total) < 200
  LIMIT ?,1",
array($target));

It will make use of your indexes, and won't require a re-sort of a potentially large dataset.
It's also not really a super idea to self join a table with the condition that the primary key is not equal to itself, you are essentially squaring the size of your dataset. A table with 1000 rows will yield a set with 999,000 rows. I think rolling the 'total' condition into an explicit JOIN will reduce the performance hit, but I'm not certain.
Change:
  FROM users C1, users C2
  WHERE C1.id <> C2.id
   AND ABS(C1.total - C2.total) < 200

To:
  FROM users C1 INNER JOIN users C2
   ON C1.id <> C2.id
     AND ABS(C1.total - C2.total) < 200

Comment: foreach ($rs as $row) { print $row['name1']; }  I get empty result,
what I missed --- connection is ok: $dbh = new PDO ("mysql:host=$hostname;dbname=$dbname","$username","$pw"); ---
Answer: As suggested already, you can optimize it by using indexes. However, I would recommend doing the "random" logic programmatically. Although its perfectly fine to use ORDER BY RAND() for smaller tables, its highly inefficient for larger ones (for example, if you had a table with 10,000 records, it would have to generate 10,000 random numbers and (AFAIK) choose the smallest one).
I would suggest using two queries. Select the COUNT, generate a random number from that, and then use that value in your LIMIT clause.
Example:
//get the total number of rows
$result= mysql_query(" SELECT  COUNT(*) AS total FROM `table` ");
$row = mysql_fetch_array($result);
$total=$row['total'];

//create random value from 1 to the total of rows
$randomvalue =rand(1,$total);

//get the random row
$result= mysql_query(" SELECT  * FROM `table` limit $randomvalue,1");

In your particular case, you could generate two random numbers and select two users (just make sure the random numbers aren't equal).
EDIT: similar example found here.

SELECT FROM Subquery performance


How to use concatenate function in PHPExcel

Question: <code>$objPHPExcel->getActiveSheet()->SetCellValue('L'.CONCATENATE('A','C','D','E','F','G','H','I','J','K'),'0);');
</code>
Can anyone tell how to use the concatenate function in php Excel?
Answer: If you're writing a formula in the cell, then you need to write it as you would write an Excel formula:
<code>=CONCATENATE("A","C","D","E","F","G","H","I","J","K")
</code>
if I'm reading what you're trying to do correctly
<code>$objPHPExcel->getActiveSheet()->SetCellValue('A1','=CONCATENATE("A","C","D","E","F","G","H","I","J","K")');
</code>
EDIT
Trying to interpret what you mean:
<code>$objPHPExcel->getActiveSheet()->SetCellValue('E'.($i+$j),'=CONCATENATE(A'.($i+$j).'," ",D'.($i+$j).')');
</code>
If $i+$j = 5, then this will write the formula
<code>=CONCATENATE(A5," ",D5)
</code>
in cell E5,
so if cell A5 contains

Hello

and cell D5 contains

World

then cell E5 will display the value

Hello World
Comment: Call to undefined method PHPExcel_Worksheet::CONCATENATE() in C:\wamp\www\XXXXXXXXXXXX\application\controllers\savephpexcel.php on line 111
Comment: @masterprogrammer - what are you trying to do, please explain.... the line of code I answered you with should never give that error. It stores the formula '=CONCATENATE("A","C","D","E","F","G","H","I","J","K")' in cell A1 of the current active worksheet
Comment: $insert="INSERT INTO m_productprice(m_product_id,ad_org_id)VALUES(";
$values="1000004, 1000004, 'Y',";
$created=$this->timendate->getCustomDate("%Y-%m-%d %h:%i:%s",now());
$objPHPExcel->getActiveSheet()->SetCellValue('A'.($i+$j),$insert);
$objPHPExcel->getActiveSheet()->SetCellValue('D'.($i+$j),"$values");
Comment: now i want to concatenate thse two cells i.e a & d.i have cut down the code as its long and involves more than 50 fields to insert into excel


Envio de XML para webservice

Question: Estou precisando saber como fazer envio de XML para um webservice de um cliente. Como sou bem novo nisso, dei uma pesquisada em algumas fontes e encontrei um código bem simples de java. Queria saber se está tudo correto:
<code>package Envio;

import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.StringWriter;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.MimeHeaders;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPMessage;
import javax.xml.transform.OutputKeys;
//import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import org.w3c.dom.Document;

public class ConsumirWebServicePorRequisicaoXML {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) throws SOAPException, IOException {
    // TODO code application logic here
    String requestSoap;

    requestSoap = "MEU XML";

    SOAPConnectionFactory soapConnectionFactory = SOAPConnectionFactory.newInstance();
    SOAPConnection soapConnection = soapConnectionFactory.createConnection();

    String url = "MEU LINK ASMX do WEBSERVICE"; //url do webservice

    MimeHeaders headers = new MimeHeaders();
    headers.addHeader("Content-Type", "text/xml");

    MessageFactory messageFactory = MessageFactory.newInstance();

    SOAPMessage msg = messageFactory.createMessage(headers, (new ByteArrayInputStream(requestSoap.getBytes())));

    SOAPMessage soapResponse = soapConnection.call(msg, url);
    Document xmlRespostaARequisicao=soapResponse.getSOAPBody().getOwnerDocument();

    System.out.println(passarXMLParaString(xmlRespostaARequisicao,4)); //imprime na tela o xml de retorno.
}
public static String passarXMLParaString(Document xml, int espacosIdentacao){
    try {
        //set up a transformer
        TransformerFactory transfac = TransformerFactory.newInstance();
        transfac.setAttribute("indent-number", new Integer(espacosIdentacao));
        Transformer trans = transfac.newTransformer();
        trans.setOutputProperty(OutputKeys.OMIT_XML_DECLARATION, "yes");
        trans.setOutputProperty(OutputKeys.INDENT, "yes");

        //create string from xml tree
        StringWriter sw = new StringWriter();
        StreamResult result = new StreamResult(sw);
        DOMSource source = new DOMSource(xml);
        trans.transform(source, result);
        String xmlString = sw.toString();
        return xmlString;
    }
    catch (TransformerException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
        System.exit(0);
    }
    return null;
}
}
</code>
Por razões óbvias, eu omiti o XML e o link do ASMX do webservice por conterem informações um pouco mais sigilosas. Mas eu já consegui validar o formato do XML e também possuo o link do webservice.
A ideia é que essa aplicação em JAVA seja executada uma vez ao dia ou uma vez por semana e faça o envio de vários XML pra esse webservice (depois eu mudo o código pra ele fazer o envio de mais de um XML).
Answer: Aparentemente a abordagem esta correta, basicamente você está criando uma requisição SOAP, adicionando os parametros no corpo da requisição onde um deles será o XML convertido em String e disparando a requisição.
Se efetivamente vai funcionar só testando mesmo, pois muita coisa pode variar.
Oq você pode fazer pra testar fora do Java é usar ferramentas como o SOAPUI para testar o serviço caso dê algum erro no Java, pois assim você valida se o problema é o codigo, a requisição ou o serviço.
Comment: Obrigado pela resposta, Vinicius. Sim, eu já validei com a ajuda do SOAPUI. Precisava mesmo só saber se a programação em JAVA estava correta.

Envio de XML para webservice


How to implement Facebook style Notifications for Organic Group posts?

Question: I am using Organic Groups, Drupal Commons. If someone posts in group, then all the members should be notified like in Facebook with the number of notifications. Similar to this screenprint:

How can I achieve that ?
Notes:

By Posts I mean a creating new node of Post content type (default) in Organic Group (and commenting part is not required now).
I have not implemented any rule for this, can you explain how can I achieve this using rules ?
Comment: By Posts I mean a creating new node of Post content type (default) in organic group and commenting part is not required now. I have not implemented any rule for this, can you explain how can i achieve this using rules ?
Answer: Below is a blueprint of how you can make this work. To avoid writing a manual as an answer, and to avoid repeating myself, I use some links to other answers (not all of them are mine ...).
Step 1: Get Rules involved
Use the Rules module to capture events about new nodes being created, which belong to some Organic Group. Have a look to either of the answers to  "Get organic group name in a rule?", for 2 possible alternatives to "send an eMail" to each member of the group.
With that, all that's left is to replace the Rules Action to "send an eMail" with something that shows the number of notifications (as in your question), as further explained below.
Step 2: Use Messages to create notification entities
Install/enable the Message module also. So that you replace the Rules Action from the previous step to "send an eMail" by a Rules Action to create message "entities" (which is what you get if you use the Message module). And then just use the power of Views to display those messages later on (hang on: in a format like your shiny notification button ...).
Here is a summary of what you'd need:

Define an appropriate Message type, using the Message module. Think of Message types as similar to "Content types", which will be used to create Messages, similar to Nodes.
Enhance your rule with a Rules Action "Create entity" (of type "Message"). Refer to the answer in Which user related token(s) can be used to create a Rule for setting up a message type? for some examples.
Possibly you may also want to add a Rules Action to pass any relevant tokens, via Rules, as Replacement tokens that you can use in your Message type you created with the Message module. Refer to What's the purpose of "Replacement tokens" of a Message type? for more details on this.
Use Views to display the created messages in the format you prefer.

Step 3: Transform the view in a notification icon
The Menu Badges module can be used to add such notifications to any menu item and/or menu tab of your choice. Here are some details about it (from its project page):

Provides a method for adding iOS-style badges to menu items. (see screenshot)

Adding Badges to Menus
Once enabled, go to Administration > Structure > Menus, and click "list links" next to the menu containing the target item. Click "edit" next to the item and select the badge to display with the Display Menu Badge select box.
Adding Badges to Tabs
For adding badges to menu tabs, there is a tab under Administration > Structure > Menus called "Tab Menu Badges". Search for the menu router path of the tab you want to alter, then select a badge from the corresponding select box.
Badge Types
The module includes five example badges, and new badges can be created easily with Views. Modules can also supply their own badges with a hook implementation. See the README.txt file for details.

Because of how it integrates with the Views module, you basically reduce the solution for any type of notification to something like this:

Just create an appropriate view of it, create a menu item or menu tab for that view. Obviously, the view created in Step 2 is the view you want to use.
Do a 15 seconds Menu Badges configuration to tell it which menu item/tab you used for it in your view.

Video tutorials:

Defining Menu Badges with Views in Drupal (from the module maintainer).
Drupal 7 Menu Badges Module.

Step 4: Updating the notification icon
After you completed the above steps, you'll have such shiny notification icon corresponding to the relevant messages. What's left is to implement something to get the icon (ie the counter shown in it) updated, as further explained below.
Option 1 - Make the Messages manage-able
This option allows a user to indicate which messages have been read already, and which ones are new (= unread). For that, just perform the steps explained in "How to allow users to manage their own Message Stack messages?", which can be summarized like so:

Create a flag (using the Flag module).
Create a view 'Messages by user' (= improved version of the view specifications described above).
Use Rules to flag/unflag messages.
Trigger the Rules Component to mark messages (using the VBO module).
Create notifications about Unread Messages (using the "Menu Badges" module). So that whenever a new message gets created, the user gets a notification in the format of an iOS-like (red) badge with the number of unread messages.

Option 2 - Remove the notification icon after visiting some path
This option will remove the notification icon entirely, after the user visited the dedicated path to display all messages. Refer to the answer to "How to make menu badges count disappear after the page is viewed?" for details about how to do so.
Comment: Good answer and I do very similar. I've been thinking about enhancing this by possibly using https://www.drupal.org/project/rules_link to batch process a second flag field on messages for  "Facebook functionality". When the menu item is clicked, the rule fires and all existing messages for the user are automatically flagged so the counter returns to zero. This is how Facebook does it and on my main site, there can be a lot of messages for users to flag.
Comment: It isn't a priority for me but I may have a look later today. The problem for this approach on Stack Exchange is that it probably requires some jQuery / custom module to make the rules link work seemlessly as a menu item (or whatever people use to display messages). Any thoughts?
Comment: I think this could also allow a broader range of messages to be displayed in a "wall view" and a narrower range of messages to be displayed for the user in a menu. Just like Facebook.
Comment: Hey @NiallMurphy , merci for your interesting comments. Please post an extra answer in which you integrate what you described in your comments above. Also note the "Option 2" I added in "Step 4", which IMO is "a" solution for that counter to be returned to zero (as in your first comment).
Comment: Mine is quite different and I don't use menu badges. My notifications are in a dropdown like FB. http://i.imgur.com/MRvnPew.png I have it now that when the "44" div is clicked, jQuery steals the href (link+token) from a hidden rules link and I send the $.ajax request myself. That fires the rule in the background while I remove the "44" with jQuery.
Comment: I think stealing the href of hidden JS toggles could be really useful for flags and rules.. Maybe even a small module in the future.
Comment: @NiallMurphy 2 more comments that make me really curious for your answer! Please? Whenever you have time for it.
Comment: Answered.. I'm pretty excited about this technique!
Answer: FAB, this answer won't be finished for a while but it should let you get closer to FB functionality when it's done when added to Pierre's answer.
Pierre, I'll assume you're comfortable with Rules Link.
It outputs a JS toggle like below which we can hide with CSS.

  Seen
Link executed

If our menu item has the class .menu_unread and the badge is .badge_unread, we can do the following to fire our VBO rule.
  $('.menu_unread').click( function () {
              // Get the url from the JS link
              var rules_link_url = $('.rules-link-messages_seen a').attr('href');
              $.ajax({
              type: 'POST',
              url: rules_link_url,
              dataType: 'json',
              success: function () {
              // Hide Badge.. Or you could fake set it to zero
                    $('.badge_unread').hide();
                    //So the rule fires once only
                    $(' menu Identifier ').removeClass('menu_unread');
                }
              });
        });

This should also work with flag toggles but won't let us unflag immediately like the default behavior.
Why do this? Fire rules from clicks on any element.
Comment: Wow, that sounds interesting, merci! Only 1 suggestion to further improve it "some day": don't assume only "I" am interested in learning/reading about this (so replace your 2nd parg about Rules Link with an appropriate explanation, or link to more details on that).
Comment: I will. My collarbone is still broken so typing big answers is hard.
Comment: poor Niall ... Get well soon!
Comment: Thanks. And my left-handed typing is improving dramatically :)
Comment: Oh yeah Pierre, kind of related in the FB topic. This might interest you. https://www.drupal.org/node/2856260 I have Messages pop up using the Toastr library without a page reload. I'll be working at it more in a few weeks.


Describing class relationships in ruby

Question: I've never done any straight ruby coding - only worked with the Rails framework.
I am not sure how to describe the relationships between Classes, other than inheritance relationships.
For example, a School object may have many Student objects.
I would like to be able to make calls like "myschool.student[2].first_name" and "mystudent.school.address"
It may be that I am confusing OOP with elements of relational databasing, so sorry if I'm way off.
Answer: I'm not 100% sure what the question is here...
For the first example, myschool.students[2].first_name, your School class needs an accessor for a students field, which needs to be an array (or something else that supports subscripts) e.g.
class School
  attr_reader :students

  def initialize()
    @students = []
  end
end

The above allows myschool.students[2] to return something. Assuming that students contains instances of a Student class, that class might be something like this:
class Student
  attr_reader :first_name, :last_name

  def initialize(first, last)
    @first_name = first
    @last_name = last
  end
end

Now your example, myschool.students[2].first_name, should work.
For the second example, mystudent.school.address, you need to have a school field in the Student class and an address field in the School class.
The tricky bit is that the School and Student instances point to each other, so you need to set up those references at some point. This would be a simple way:
class School
  def add_student(student)
    @students << student
    student.school = self
  end
end

class Student
  attr_accessor :school
end

You still need to add the address field and possibly some other stuff that I missed, but that should be easy enough to do.
Comment: Excellent reply! I didn't realise that it was this simple.
Thanks very much.
Answer: Generally, in most OO languages, class members are not exposed to the outside world by default. Even if it is (as in some languages), it is considered bad practice to directly access class members.
When add members to a class (say, add Student classes to School), you need to add accessor functions to provide the outside world access to those members.
Here's are some useful resources if you want to learn more (found by googling: ruby accessors):
http://juixe.com/techknow/index.php/2007/01/22/ruby-class-tutorial/
http://www.rubyist.net/~slagell/ruby/accessors.html
Comment: Thanks. I am using attr_accessor to access the attributes of both Schools and Students, but I do not know how to tell the program that a school has many students.

Describing class relationships in ruby


Pandas percentage of two columns

Question: I have a data frame that looks like this:
    Vendor  GRDate  Pass/Fail
0   204177  2022-22 1.0
1   204177  2022-22 0.0
2   204177  2022-22 0.0
3   204177  2022-22 1.0
4   204177  2022-22 1.0
5   204177  2022-22 1.0
7   201645  2022-22 0.0
8   201645  2022-22 0.0
9   201645  2022-22 1.0
10  201645  2022-22 1.0

I am trying to work out the percentage of where Pass/Fail equals 1 for each week for each vendor and put it in a new df (Number of pass = 1 / total number of lines per vendor & week)
which would look like this:
    Vendor  GRDate  Performance
0   204177  2022-22 0.6
1   201645  2022-22 0.5

I'm trying to do this with .groupby() and .count() but i can't work out how to get this into a new df along with the Vendor and GRDate columns. The code I have here returns the percentage of pass fail but drops the other two columns.
sdp_percent = sdp.groupby(['GRDate','Vendor'])['Pass/Fail'].apply(lambda x: x[x == 1].count()) / sdp.groupby(['GRDate','Vendor'])['Pass/Fail'].count()

But then if I add .reset_index() to keep them I get this error: unsupported operand type(s) for /: 'str' and 'str'
Please can someone explain what i'm doing wrong?
Answer: Try:
x = (
    df.groupby(["GRDate", "Vendor"])["Pass/Fail"]
    .mean()
    .reset_index()
    .rename(columns={"Pass/Fail": "Performance"})
)
print(x)

Prints:
    GRDate  Vendor  Performance
0  2022-22  201645     0.500000
1  2022-22  204177     0.666667

Answer: As you have 0/1, you can use a groupby.mean:
(df.groupby(['Vendor', 'GRDate'], as_index=False, sort=False)
   .agg(Performance=('Pass/Fail', 'mean'))
)

If you had a specific arbitrary value X:
(df.assign(val=df['Pass/Fail'].eq(X))
   .groupby(['Vendor', 'GRDate'], as_index=False, sort=False)
   .agg(Performance=('val', 'mean'))
)

Output:
   Vendor   GRDate  Performance
0  204177  2022-22     0.666667
1  201645  2022-22     0.500000

Pandas percentage of two columns


IEnumerable - foreach - The result of a query cannot be enumerated more than once

Question: I have the following code:
public static string ConvertParamToHTMLString(
                            IEnumerable<GetParm_Result> paramList)
{
    foreach (GetParm_Result result in paramList.ToList())
    {
      ...
      ...
    }
}

I am getting the following message when it tries to execute the foreach:

The result of a query cannot be enumerated more than once.

I thought that the ToList() would resolve this issue..
Comment: Are you perhaps calling `ToList` (or any other method that would iterate the query) somewhere else in that method, or are you iterating that sequence before even passing it into the method?
Comment: Where did `paramList` come from? Did you already evaluate it before passing it to the function?
Comment: Yes, I already evaluted it.
Comment: Why even convert to a list to begin with? You can iterate over the `IEnumerable` so to me, it looks like the `ToList()` is just a needless operation.
Comment: @evanmcdonnal If it's a sequence that can't be iterated multiple times a valid solution is to convert it to a list and then iterate that list multiple times.
Comment: @NatePet `ToList()` has to evaluate the IEnumerable in order to convert it to a list. You need to make `ToList` your first and only evaluation, then pass the List around instead.
Comment: @Servy yeah but he doesn't assign it to a local variable. I could be wrong but I'm pretty sure the only thing his `ToList()` call is doing is making his code perform worse.
Comment: @evanmcdonnal That is correct.  [Hence my original clarifying question](http://stackoverflow.com/questions/18090223/ienumerable-foreach-the-result-of-a-query-cannot-be-enumerated-more-than-onc/18090293?noredirect=1#comment26479576_18090223)
Comment: Are you sure the message actually comes from this code? It doesn't seem possible. What happens in the foreach loop? Do you access the IEnumerable there?
Answer: Call paramList.ToList() once and put it in a variable, then enumerate on the variable:
var list = paramList.ToList();
foreach(var result in list) ...
foreach(var result in list) ...   // No error here

Comment: I noticed it doesn't, it was just to demonstrate how this will work.
Comment: note that the code in the question doesn't have two foreach loops.  This may be the problem (in which case the question needs to be changed) or it could be a different problem that this wouldn't address.
Answer: Since you only show one execution, I'm assuming you're executing the query (using ToList, AsEnumerable, or implicitly using foreach) before you call ConvertParamToHTMLString.  If that is the case, then you can just save the result in a variable and use it multiple times.  In fact, since your function already accepts an IEnumerable<T> you don't need to change that code at all!


Can we Integrate Gulp or Grunt with Magento 22.214.171.124? Trying to Optimize css, js and images

Question: Can we Integrate Gulp or Grunt with Magento 188.8.131.52? Trying to Optimize css, js and images. There is no plugin in Magento 18.104.22.168 version but could there be any other ways to integrate it.
Appreciate your help and suggestions!
Answer: If you need to build a theme from scratch with grunt capabilities, then you can easily build it using a yeoman through npm. Yeoman is a web scaffolding tool so you don't have to do the hard work of installing all details.
Step 1:
install node js see link
Step 2:
npm install -g yo

Step 3:
npm install -g generator-grunt-magento

Step 4:
yo grunt-magento

More Details from here.
Another possible solution is to create the grunt structure on an existing theme. This is something that we cannot generalize so it really depends on the theme you have and how you wan't it to be implemented.

Can we Integrate Gulp or Grunt with Magento 1.13.1.0? Trying to Optimize css, js and images


String contain specific characters

Question: If I have the following:
name="paula"

list=["l", "p"]

for x in list:
    print name.count(x)

>>>
1
1

Which If I understand correctly, is taking the string: "paula" and confirming that it has one "l" and one "p" character.
But what if I wanted to do this:
#**if name has both Letters, l and p, then it is a mouse**

name="paula"

list_1=["l"]
list_2=["p"]
list_3=["l", "p"]

for y in list_3:
    if name.count(y):

   print "%s contains the letters %s and %s. %s is a mouse." % (name,w,x,name)

#assume w and x are already defined

>>>

paula contains the letters l and p. paula is a mouse.
paula contains the letters l and p. paula is a mouse.

Obviously, this doesn't work. I realized that in this code, it would check the string "paula" for the letter "l". And then it runs again to see if it contains "p". Thus two outputs instead of one.
I believe the for loop probably needs to be discarded.
Any help is appreciated guys!
@  Two-Bit Alchemist- Reason for 3 lists:
#cat, dog, mouse
#if name contains the letter "L", then it is a cat
#if name contains the Letter "P", then it is a dog
#if Name has both Letters, L and P, then it is a mouse
#if Name has no L or P, then loop the question

name="lily"
name_2="patrick"
name_3="paula"

list_1=["l"]
list_2=["p"]
list_3=["l", "p"]

for w in list_1:
    if name.count(w):
        print "%s contains the letter %s. %s is a cat." %(name,w,name)

for x in list_2:
    if name_2.count(x):
        print "%s contains the letter %s. %s is a dog." %(name_2,x,name_2)

for y in list_3:
    if name_3.count(y):
        print "%s contains the letters %s and %s. %s is a mouse." %(name_3,w,x,name_3)

Comment: The bottom half of your question makes no sense and is making the whole thing unclear. Why do you want 3 lists all of a sudden? What is `y`? Assume `w` and `x` are defined _as what_?
Comment: I have edited the OP to clarify
Answer: I think your best bet is to use sets.
name = 'paula'
seek = 'pl'

if set(seek).issubset(set(name)):
    print "{0} contains the letters '{1}'. {0} is a mouse.".format(name, seek)

>>> paula contains the letters 'pl'. paula is a mouse.

Comment: +1, but note that `set(seek).issubset(set(name))` can be reduced to `set(seek).issubset(name)` since `issubset` works with any iterable
Answer: If I'm understanding correctly, you want to check whether a list of strings can all be found inside another string?
If so, you could do something like this:
list3 = ["l", "p"]
name = "paula"
if all(char in name for char in list3):
    print "{0} is a mouse.".format(name)

Essentially, how the code works is that it uses a generator combined with the 'all' operator.
The segment of code char in name for char in list3 will iterate through each item in list3 and will report a true or false value whether or not the character exists inside the name. This syntax is called a generator comprehension, which is pretty similar to list comprehensions, which you can learn more about here.
In a nutshell, char in name for char in list3 is doing something similar to the following:
temp = []
for char in list3:
    temp.append(char in name)
print temp

>>> [True, True]

Next, the all function is a builtin that takes a list of bools, and returns True only when every element in the list is also True.
Taken all together, the expression all(char in name for char in list3) will evaluate to True only when every character in the list can be found inside name.
Comment: If you really need three lists, please don't name them `list1`, `list2`, ... `listN`. Just use a list of lists, or individuate the identifier names.
Comment: @Two-Bit Alchemist  Can you elaborate?
Comment: You are saying I should make the lists more distinguishing?
Comment: I am saying you should never end up in a situation where you have `var1`, `var2`, ... `varN`. You should either switch to a list (`var[0]`, `var[1]`, ... `var[n-1]`) or your variable names should be more descriptive.
Answer: Use any() to check if the contents of the list exist in the string:
name = "paula"
list_1 = ["l", "p"]
if any(word in name for word in list_1):
    print 'paula is a mouse'

String contain specific characters


Show that the function $u(x)=\arctan(\frac{1}{x})$ is in $L^p(0,+\infty)$ $ \ \forall p>1$

Question: I need to show that $||u(x)||_{L^p}$ is finite.
$$||u(x)||_{L^p}^p=\int_0^{+\infty}|u(x)|^pdx=\int_0^{+\infty}|\arctan\bigg(\frac{1}{x}\bigg)|^pdx=\int_0^{+\infty}\arctan^p\bigg(\frac{1}{x}\bigg)dx$$
At this point I thought a substitution: $t=\frac{1}{x}$, so $dx=-\frac{1}{t^2}dt$ and the integral become
$$-\int_{+\infty}^0\bigg(\frac{\arctan(t)}{t^2}\bigg)^pdt=\int_0^{+\infty}\bigg(\frac{\arctan(t)}{t^2}\bigg)^pdt\le\bigg(\frac{\pi}{2}\bigg)^p\int_0^{+\infty}\frac{dt}{t^2}=\bigg(\frac{\pi}{2}\bigg)^p\bigg[-\frac{1}{t}\bigg]_0^{+\infty}$$
but it diverges, I can't understand how to bound above this thing. Someone could help me?
Answer: $$
\text{arctan}^p\left(\frac{1}{x}\right) \underset{(+\infty)}{\sim}\frac{1}{x^p}
$$
and the function $\displaystyle x \mapsto \frac{1}{x^p}$ is integrable on $\left[1,+\infty\right[$. Then
$$
\text{arctan}^p\left(\frac{1}{x}\right) \underset{(0^{+})}{\sim}\left(\frac{\pi}{2}\right)^p
$$
So $\displaystyle x \mapsto \text{arctan}^p\left(\frac{1}{x}\right)$ is continuous on $\left[0,1\right]$, so it is integrable on $\left]0,1\right]$.
Hence it is integrable on $\left]0,+\infty\right[$.
Comment: It might be better to start with $\arctan u \sim u$ for small positive $u$ which translates to $\arctan (1/x) \sim 1/x$ for large $x$ and then on to what you said.
Comment: But i precised it was around infinity
Comment: In a easy way, I use the fact that $\arctan^p(\frac{1}{x})\sim(\frac{\pi}{2})^p$ on $[0,1]$, and then I use the fact that $\arctan^p\bigg({\frac{1}{x}}\sim\frac{1}{x^p}\bigg)$ on $[1,+\infty]$. Then I think I can divide the integral in $$\int_0^1\bigg(\frac{\pi}{2}\bigg)^pdx+\int_1^{+\infty}\frac{1}{x^p}dx$$
Right?
Comment: That s it. That s why i have done


Derivation of the formula for the area of a regular polygon given the side length.

Question: There are many formulas for finding the area of a regular polygon- but this is the one I am interested in:
$$A=\frac{S^2n}{4\tan(\frac{\pi}{n})}$$
where $n$ is the number of sides, and $S$ is the length of each side. Like I said, I would like to know how it is derived.
Comment: This is explained quite nicely here:
http://www.mathsisfun.com/geometry/regular-polygons.html
Comment: Damn, this was actually really easy in hindsight. If only I had known about radian measure at the time- I figured out division into triangles- that was not what limited me.
Answer: Hint: "Triangulate" your polygon, i.e. decompose it in $n$ triangles and measure the area of one of them (they are all same). Note that they are all isosceles (because the polygon is regular) and you can easily compute their angles. So you may take the altitude of it passing through the center of the polygon and then apply basic trigonometric formulas.
Comment: For an even quicker version of this, cut each of these sectors in half to get $2n$ right triangles and compute their area.
Answer: Well, it's $n$ times the area of a single "wedge" of the polygon. So I just need to show the wedge has area $S^2/(4 \tan (\pi/n))$.
For that, consider a circle of radius $R$, with a wedge going from $-\pi/n$ to $\pi/n$. The area of that wedge is twice the area of the half-wedge, from $0$ to $\pi/n$. That area in turn is half the base times the height, i.e., it's $\frac{1}{2} R \sin (\pi/n) R \cos(\pi/n)$. So one wedge has area
\begin{align}
W &= R \sin (\pi/n) R\cos(\pi/n)\\
& = R^2 \sin^2 (\pi/n) \frac{\cos(\pi/n)}{\sin(\pi/n)}\\
\end{align}
Now $R \sin(\pi/n)$ is half the length of a side of the polygon, i.e. it's $S/2$, so this becomes
\begin{align}
W &= R \sin (\pi/n) R\cos(\pi/n)\\
& = R^2 \sin^2 (\pi/n) \frac{\cos(\pi/n)}{\sin(\pi/n)}\\
&= (S/2)^2 \frac{\cos(\pi/n)}{\sin(\pi/n)}\\
&= (S^2/4) \frac{1}{\tan(\pi/n)}.
\end{align}
Thus the total area is $n$ times this, i.e.,
$$
(S^2/4)n \frac{1}{\tan(\pi/n)}.
$$


How to modify a core theme and what is the correct way to do this?

Question: I modified the core's Bartik theme file, node.tpl.php.  I simply added
<code>echo "Last updated by $name on " . format_date($node->changed);
</code>
The problem is that when there is a new core update, my change will be overwritten.  Is there a way to create a module that will easily add this simple line in the node.tpl.php of Bartik's node.tpl.php theme file so that future updates will not overwrite my change?
Answer: What you want to do is create a subtheme of Bartik, and make your modifications to node.tpl.php there instead. Themes support the notion of inheritance, so this can be leveraged to tweak core themes without actually hacking core. As a rule, it is best practice not to hack core for the reasons you mentioned and a slew of others, security not the least among them.
Comment: Thanks, this got me 95% of the way there.  Unfortunately I am not able to use the color picker preview to change my theme's colors.  It only works if I start to copy over the Bartik 'color' and 'css' folders.  This means I am essentially just copying file for file Bartik's code, which I don't want to do.  I just want to overwrite that one file. Nonetheless, without copying over the 'color' and 'css' folder, my node.tpl.php is overriding Bartik's node.tpl.php, which is good enough for me.  I will hand set my colors or do custom CSS.


why tomcat server not start properly in eclipse?

Question: Mar 13, 2015 1:32:59 PM org.apache.catalina.core.AprLifecycleListener init
INFO: The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: C:\Program Files\Java\jdk1.6.0\bin;.;C:\Windows\Sun\Java\bin;C:\Windows\system32;C:\Windows;C:/Program Files/Java/jdk1.6.0/bin/../jre/bin/client;C:/Program Files/Java/jdk1.6.0/bin/../jre/bin;C:/Program Files/Java/jdk1.6.0/bin/../jre/lib/i386;C:\Program Files\Java\jdk1.6.0\bin;C:\Program Files\TortoiseSVN\bin;C:\Program Files\nodejs\;C:\Users\nksharma\AppData\Roaming\npm;F:\software\eclipse;
Mar 13, 2015 1:32:59 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["http-bio-8080"]
Mar 13, 2015 1:32:59 PM org.apache.coyote.AbstractProtocol init
INFO: Initializing ProtocolHandler ["ajp-bio-8009"]
Mar 13, 2015 1:32:59 PM org.apache.catalina.startup.Catalina load
INFO: Initialization processed in 331 ms
Mar 13, 2015 1:32:59 PM org.apache.catalina.core.StandardService startInternal
INFO: Starting service Catalina
Mar 13, 2015 1:32:59 PM org.apache.catalina.core.StandardEngine startInternal
INFO: Starting Servlet Engine: Apache Tomcat/7.0.55
Mar 13, 2015 1:32:59 PM org.apache.tomcat.websocket.server.WsSci onStartup
INFO: JSR 356 WebSocket (Java WebSocket 1.0) support is not available when running on Java 6. To suppress this message, run Tomcat on Java 7, remove the WebSocket JARs from $CATALINA_HOME/lib or add the WebSocket JARs to the tomcat.util.scan.DefaultJarScanner.jarsToSkip property in $CATALINA_BASE/conf/catalina.properties. Note that the deprecated Tomcat 7 WebSocket API will be available.
Mar 13, 2015 1:32:59 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["http-bio-8080"]
Mar 13, 2015 1:32:59 PM org.apache.coyote.AbstractProtocol start
INFO: Starting ProtocolHandler ["ajp-bio-8009"]
Mar 13, 2015 1:32:59 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 267 ms

Hello
I am trying to install the tomcat in eclipse. I am not able to install properly. When I check on browser it not started. I checked like that http://localhost:8080/, but page not found on browser. Could you please help me where i am doing wrong?
Comment: "INFO: Server startup in 267 ms"
Answer: have you deployed tour application on tomcat?
have you tried to run tomcat independently to eclipse?: try startup.bat command (in bin directory of tomcat) and try to launch  http://localhost:8080/
what's happen?
Answer: If you not getting any error in Tomcat log than your server is started properly without any error and application in that tomcat should run without any problem.
But from you question and log It may happen that your tomcat doesn't have root folder in you webapps directory or root application which is default application open when you type http://localhost:8080/
You may checked with deploying at least one application and open that application to check if problem still exist.


"Mixed" Feature Reduction (with Random Grouping Factors)

Question: I have a dataset that contains 6 continuous variables (V1-V6), reported by participants in two conditions (A and B). For each participant, I have two lines of observations of the 6 features, corresponding to each condition (each participant has two observations of the same variable, one for each condition).
I would like to reduce these 6 features into 1 (or more) variable that best represents my data. However, I have the intuition that it is important that the algorithm "knows" about the Condition grouping factor ("random factor" in the mixed-modelling framework).
Are there any feature reduction techniques that can deal with such hierarchically nested data and take into account a grouping structure?
I've looked for "mixed principal component analysis" but didn't find much :(
Comment: Isn't that the question of nonhomogeneity (such as Simpson's paradox od similar)? Results of PCA done on each condition separately might drastically differ from results of PCA done on the combined dataset.
Comment: Why cannot you do PCA on all the 12 features (v1a, v1b, v2a, v2b...)?
Comment: I could indeed... Thanks for the suggestion. However, as I have relatively small sample, doesn't it decrease the robustness of the estimates (as it increases the number of reatures and decreases the number of observations?). Moreover, I would like, further, to do a regression with, let's say, the condition factor as predictor (or any other variable) and the principal component. That seems only possible if I keep the grouping structure instead of "spreading" the grouping factor... right?
Comment: Do I understand correctly that you record your target variable twice for each participant (once for each of 2 conditions)? Or it is recorded only once for each respondent?
Comment: Dear David, indeed each variable is recorder twice (for example, the emotional arousal in two conditions, negative and neutral)...
Answer: There are different ways how to deal with this data structure. Which one is best depends on what your aim of the analysis is. From your comments, it would be to run a regression of a response variable on "condition" and further covariables $X$ derived from the original data.

Run a PCA on $X$ to reduce the number of dimensions, ignoring the grouping structure implied by "condition". The more similar the distribution of $X$ across different conditions, the better this would work. How could you check this? Try to predict "condition" by $X$, e.g. using a mixed effects logistic regression. It the model is bad, then it means the distributions of $X$ across condition is not too different and the PCA approach could be fine.
Run separate PCAs per condition. No. Don't do it...
No PCA, but regularized mixed-effects regression, e.g. mixed effects Lasso. While elegant, it will be quite impossible to get valid inference from a model like this.
Be creative (A). Maybe dimension reduction is not necessary at all. Just run your mixed effects model with $X$ and "condition" as covariables. If the $X$ are strongly correlated, you can still transform them smartly, like considering ratios etc.
Be creative (B). Compress the two lines per object to one: Take the difference in the model response variable (Condition 1 minus Condition 2). Take average and difference in each $X$ variable (across conditions). Run PCA on the derived variables from $X$ and use the first few to explain your new response by OLS or so.
Be creative (C)
Be creative (D)


Python Jogo advinhação

Question: Tô com o seguinte problema: a cada tentativa do usuário, o código não acusa se está frio, quente, morno, fervendo. Ou seja, não dá as dicas pro jogador. Se alguém puder me ajudar eu agradeço!
print('Você tem 10 chances de acertar o número que eu estou pensando.')
print('Trata-se de um valor entre 1 e 100. Então, vamos lá!')
print()
import random

n = random.randrange(1, 101)
nrepete = []
estado1 = 7  # início
estado2 = 7

def SetStatus(tentativa):
    if abs(n - palpite) == 1:
        estado2 = 6  # fervendo
    if abs(n - palpite) == 2 or abs(n - palpite) == 3:
        estado2 = 5  # muito quente
    if abs(n - palpite) >= 4 and abs(n - palpite) <= 6:
        estado2 = 4  # quente
    if abs(n - palpite) >= 7 and abs(n - palpite) <= 9:
        estado2 = 3  # morno
    if abs(n - palpite) >= 10 and abs(n - palpite) <= 15:
        estado2 = 2  # frio
    if abs(n - palpite) >= 16 and abs(n - palpite) <= 25:
        estado2 = 1  # muito frio
    if abs(n - palpite) >= 26:
        estado2 = 0  # congelando

def FornecerPista():
    if status1 == 7:
        if estado2 == 0:
            print('Está congelando!')
        if estado2 == 1:
            print('Está muito frio!')
        if estado2 == 2:
            print('Está frio!')
        if estado2 == 3:
            print('Está morno!')
        if estado2 == 4:
            print('Está quente!')
        if estado2 == 5:
            print('Está muito quente!')
        if estado2 == 6:
            print('Está fervendo!')
    if estado1 - estado2 == 0:
        if estado2 == 0:
            print('Seu palpite continua congelando!')
        if estado2 == 1:
            print('Seu palpite continua muito frio!')
        if estado2 == 2:
            print('Seu palpite continua frio!')
        if estado2 == 3:
            print('Seu palpite continua morno!')
        if estado2 == 4:
            print('Seu palpite continua quente!')
        if estado2 == 5:
            print('Seu palpite continua muito quente!')
        if estado2 == 6:
            print('Seu palpite continua fervendo!')
    if estado1 - estado2 > 0:
        if estado2 == 0:
            print('Ops, seu palpite deu uma esfriada e agora está congelando!')
        if estado2 == 1:
            print('Ops, seu palpite deu uma esfriada e agora está muito frio!')
        if estado2 == 2:
            print('Ops, seu palpite deu uma esfriada e agora está frio!')
        if estado2 == 3:
            print('Ops, seu palpite deu uma esfriada e agora está morno!')
        if estado2 == 4:
            print('Ops, seu palpite deu uma esfriada e agora está quente!')
        if estado2 == 5:
            print('Ops, seu palpite deu uma esfriada e agora está muito quente!')
    if estado1 - estado2 < 0:
        if estado2 == 1:
            print('Ops, seu palpite deu uma esquentada e agora está muito frio!')
        if estado2 == 2:
            print('Ops, seu palpite deu uma esquentada e agora está frio!')
        if estado2 == 3:
            print('Ops, seu palpite deu uma esquentada e agora está morno!')
        if estado2 == 4:
            print('Ops, seu palpite deu uma esquentada e agora está quente!')
        if estado2 == 5:
            print('Ops, seu palpite deu uma esquentada e agora está muito quente!')
        if estado2 == 6:
            print('Ops, seu palpite deu uma esquentada e agora está fervendo!')

for tentativa in range(1, 11):
    while True:
        try:
            palpite = input('Tentativa' + str(tentativa) + ':')
            palpite = int(palpite)
            nrepete.append(palpite)
            if (palpite < 1) or (palpite > 100):
                raise ValueError
            if nrepete.count(palpite) >= 2:
                raise NameError
            else:
                break
        except NameError:
            print('Esse valor já foi testado! Tente de novo.')
        except ValueError:
            print('Valor inválido! Tente de novo.')

    if palpite == n:
        print('\nParabéns !')
        print('\nVocê acertou o número', n, 'após', tentativa, 'tentativa(s)!')
        break
    if tentativa == 1:
        SetStatus(tentativa)
    if tentativa > 1:
        estado1 = estado2
        SetStatus(tentativa)
    FornecerPista()

    if tentativa == 10 and palpite != n:
        print('\nLamento, mas após', tentativa, 'tentativas')
        print('Você não conseguiu acertar o número', n, 'que eu estava pensando!')

Answer: Há 2 problemas com o código.
O primeiro é um erro de sintaxe na função FornecerPista():
def FornecerPista():
    # AQUI: o nome correto da variável é estado1, não status1
    if estado1 == 7:
        if estado2 == 0:
            print('Está congelando!')
    ...

O segundo é na função SetStatus(), onde você atualiza a variável estado2.
Essa variável é declarada no escopo global e, caso você não indique isso para o Python, ele considera que a variável dentro da função é "outra", declarada localmente e diferente da global, o que impede a atualização do estado do jogo.
A solução é indicar que se trata da variável global estado2:
def SetStatus(tentativa):
    # AQUI: declara estado2 como global
    global estado2

    if abs(n - palpite) == 1:
        estado2 = 6  # fervendo
    if abs(n - palpite) == 2 or abs(n - palpite) == 3:
    ...

Python Jogo advinhação


smallest possible value of $\alpha$

Question:
Let $(x^3+\alpha x^2+2x-5)^{19}(x^2+\beta x-41)^8(x^4-x^3+x-7)^6=x^{97}+391x^{96}+95x^{95}+a_{94}x^{94}+\cdots+a_{1}x+a_{0}$ be an identity.where $\alpha,\beta,a_{95},a_{94},\cdots\cdots,a_{1},a_{0}$ are integers. If $\alpha+\beta<10.$ Then the possible value of $\alpha$ is

what i try
put $x=0,$ Then $(-5)^{19}\cdot (-41)^{8}\cdot (-7)^6=a_{0}$
put $x=1,$ Then $$(\alpha-2)^{19}\cdot (\beta-40)^8\cdot (-6)^6=1+391+95+a_{94}+\cdots \cdots +a_{1}+a_{0}$$
How do i solve it Help me please Thanks
Comment: You have to compare coefficients of $x^{96}$ and $x^{95}$, Calculating the coeff of $x^{95}$ is a tiresome slog.
Comment: Are you sure the coefficient of $x^{95}$ is not $a_{95}$; you mention $a_{95}$ in "where ...".
Answer: Hint: The sum of the roots is $-391=-19\alpha-8\beta+6$.
Solution:
The integer solutions of the equation above are given by $\alpha = 8 n + 7$, $\beta = 33 - 19 n$, with $n \in \mathbb Z$. Requiring that $\alpha+\beta<10$ gives $n\ge3$. Therefore, the smallest possible value of $\alpha$ comes from $n=3$ and so is $\alpha=31$.
(I think the coefficient of $x^{95}$ is $a_{95}$, not $95$.)
Comment: Great. Except it gives the wrong coefficient of $x^{95}$. Check with WolframAlpha.
Comment: Many values of $\alpha,\beta$ give the right coefficient of $x^{96}$ and satisfy $\alpha+\beta<10$. You need one which also gives the right coefficient of $x^{95}$
Comment: @almagest, there are no integer solutions then. See [WA](https://www.wolframalpha.com/input/?i=171+a%5E2+%2B+8+%2819+a+-+6%29+b+-+114+a+%2B+28+b%5E2+-+275%3D95%2C+19+a+%2B+8+b+-+6%3D391). I think $95$ is $a_{95}$.

smallest possible value of $\alpha$


Show that a specific $w$ cannot be the root of an quadratic with integer coefficients.

Question: Let $w$ be the only real root of $x^3-x-1=0$. Show that
 $w$  cannot satisfy the quadratic $ax^2 + bx + c$ ,where $a,b,c\in \Bbb Z$.
I have written
$$w^3=w+1$$
but I can't go any further than this. Thank you.
Comment: I think a really neat question hides here behind a language barrier.
Comment: What do you mean by "w is no possible $ax^2 + bx + c = 0$ roots"?
Comment: I assume s/he means that w with above properties cannot satisfy the quadratic.
Comment: I have attempted to interpret this question. Feel free to roll it back if I made any mistakes.
Comment: See [plastic number](http://en.wikipedia.org/wiki/Plastic_number).
Answer: Note that, by Euclidien division
$$x^3-x-1=Q(x)(ax^2+bx+c)+x \left(\frac{b^2}{a^2}-\frac{c}{a}-1\right)+\frac{b c}{a^2}-1$$
So, if $w$ is a root of both $x^3-x-1=0$ and $ax^2+bx+c=0~$, then we would have
$$
w \left(\frac{b^2}{a^2}-\frac{c}{a}-1\right)+\frac{b c}{a^2}-1=0
$$
So if $a^2+a c-b^2\ne0~$ then
$$
w=\frac{b c-a^2}{a^2+a c-b^2}\in\mathbb{Q}
$$
which is absurd since $x^3-x-1=0~$ has no rational solutions.
Now what happens if $a^2+a c-b^2 =0~$?
In this cas we must also have
$a^2=bc$. Without loss of generality we may suppose that $\gcd(a,b,c)=1$. From
$a^2=bc$ we conclude that $\gcd(b,c)=1$, because otherwise any common prime divisor would also divide $a$.
From $\gcd(b,c)=1$ and $a^2=bc$ we conclude that
$$b=\epsilon\beta^2, c=\epsilon\gamma^2, a=\epsilon'\beta\gamma,\qquad\hbox{with $\gcd(\beta,\gamma)=1,~(\epsilon,\epsilon)'\in\{+1,-1\}^2$}$$
Replacing in $a^2+a c-b^2 =0$ we get $\gamma^2(\beta+\epsilon\epsilon'\gamma)=\beta^3$, so $\gamma|\beta^3$, but $\gcd(\beta,\gamma)=1$ so,
$\gamma=1$ and consequently $ \beta+\epsilon\epsilon'=\beta^3$. This implies that $\beta $ is an integer solution of  $x^3-x-1=0$ or $x^3-x+1=0$ which is clearly absurd. So, this case cannot happen.
Comment: You have ommitted the case when $ax^{2} + bx + c$ divides $x^{3} - x - 1$ i.e. we may have both $bc - a^{2} = 0$ and $a^{2} + ac - b^{2} = 0$.
Answer: $p(x)=x^3-x-1$ is an irreducible polynomial over $\mathbb{Q}$, since it is irreducible over $\mathbb{F}_2$ (since it is a third-degree polynomial, proving that it is irreducible over a finite field is equivalent to proving that it has no roots in the field. But $p(x)$ is a trinomial, so $p(0)=p(1)=1$ in $\mathbb{F}_2$) . This gives that any root of $p(x)$ is an algebraic number of degree $3$ over $\mathbb{Q}$, so it cannot be the root of any quadratic polynomial with integer coefficients.
Comment: Your irreducibility proof after the edit is so cool. +1
Comment: The question from OP essentially asks us to prove that $p(x)=x^3-x-1$ is irreducible over $\mathbb{Q}$ and an elementary proof of the same is desired.
Answer: Suppose that $w \in \mathbb{R}$ is a root of $x^{3} - x - 1 = 0$ and $ax^{2} + bx + c = 0$ with $a, b, c \in \mathbb{Q}$ and $a \neq 0 \neq c$. It is easy to establish that the only real root $w$ of $x^{3} - x - 1 = 0$ is irrational. Also Note that in this case $ax^{2} + bx + c = 0$ has two roots and these must be unequal otherwise $w$ will be rational. If both these roots are also the roots of $x^{3} - x - 1 = 0$ then it follows that $ax^{2} + bx + c$ divides $x^{3} - x - 1$ and thus the remaining factor must be linear with rational coefficients leading to a rational root of $x^{3} - x - 1 = 0$ which is not possible. It follows that both $x^{3} - x - 1$ and $ax^{2} + bx + c$ have only one common factor of type $(x - w)$. It therefore follows that GCD of these polynomials $ax^{2} + bx + c$ and $x^{3} - x - 1$ is a linear polynomial. The GCD of these two polynomials however must have rational coefficients which will imply that $w$ is rational.
The above contradiction shows that there can't be any polynomial $ax^{2} + bx + c$ with rational coefficients having $w$ as its root. The proof shows that if an irrational number $\alpha$ is the only real root of a cubic polynomial $P(x)$ with rational coefficients, then $P(x)$ is irreducible over rationals.


Proper Setup of WebSite/WebApplication Deployment on IIS

Question: I have inherited a project which is currently in the middle of migrating from some older ASP.NET technologies (a mixture of ASP, .NET 2 WebForms, etc.) to MVC, .NET 4. Quite a bit of the site is ported over, which is great. At this point, the MVC site is going to take full, front-and-center, with the older site pages being available from links within the site.
The way I am attempting to set this up is to have the new, MVC code be the site (e.g. Default Web Application, for example) and the various, older projects to be web applications underneath that site.
The first part has been deployed and works - the MVC site works great. But, I am having some difficulty with the older pages. For example, I setup a web application underneath the site called with the path GenerateReports and pointing to the appropriate directory (C:/OldProjects/GenerateReports/). When I browse to that part of the site (http://www.example.com/GenerateReports/BrowseReports.aspx), I receive an error that says:

Configuration Error Description: An error occurred during the
  processing of a configuration file required to service the request.
  Please review the specific error details below and modify your
  configuration file appropriately.
[-snip-]
< compilation debug="true" targetFramework="4.0"> ...

The strange thing is - that line is in my MVC's Web.config (which is built using .NET 4.0) - not in the older, web app's web.config (which is .NET 2.0). That is if I have the AppPool for the old web application set to .NET 2.0.
If I set the AppPool to .NET 4.0 (for the older web application), then I receive this error:

The value for the 'compilerVersion' attribute in the provider options
  must be 'v4.0' or later if you are compiling for version 4.0 or later
  of the .NET Framework. [-snip-]

The first problem seems "closer to correct," but I can't find anything on Google that really describes what the problem is and, more importantly, how to fix it. I would appreciate any help.
Comment: Are the subsites setup in IIS as applications?
Comment: Yes. They are web applications underneath the main site.
Answer: Okay. I think I figured this out...
I setup the server so that the site is the MVC site. Everything within that MVC site works/starts correctly, so that was a success.
I then began adding Web Applications underneath the site with each application being one of the ASP, WebForms applications. I had to do a little bit of configuration - specifically, I had to use the information found on Scott Hanselman's blog on mixing child applications - to prevent the settings from "trickling down" into the web applications.
Finally, for the classic ASP pages (of which there are a few left), I had to provide virtual folders to those locations (again, underneath the site) and I had to enable ASP on my server (not ASP.NET which was already enabled for everything else). I also had to enable parent paths in the ASP settings for the top-level site in order for the ASP pages to work correctly. Of course, I will be working to convert the rest of the ASP pages to MVC ASAP and I can then completely remove support for it.
Hopefully this helps someone else!


How do I get the position of a node made from the DrawNode function?

Question: I have drawn a circle using the DrawNode function.
Then I am checking to see if the user is clicking the circle or not
Here I am creating the circle
DrawNode *drawnode = DrawNode::create();
drawnode->drawDot(ccp(10, Director::sharedDirector()->getVisibleSize().height / 5 ), 10, Color4F(2, 99, 2, 2));
drawnode->setPosition(Point(winSize.width / 2.1 + origin.x, winSize.height / 5 + origin.y));
this->addChild(drawnode);

Here is where I am checking to if the user is clicking the Circle
  if(Level::drawnode->getPosition() == touch->getLocation()) {  CCLOG("Circle has been clicked"); } else {  CCLOG("Circle has not been clicked"); }

The problem is this if statement keeps going to the else statement.
How do I get the circles position on the screen so that when the circle is clicked correctly
Answer: A DrawNode doesn't provide such functionality. It's basically a simple node which draws shapes without no knowledge about the contained shapes. It's just a graphical node which enqueues all the draw primitives.
To do what you need to do you need to keep your logic informations somewhere, eg:
struct Circle
{
  Position position;
  float radius;

  bool isInside(const Position& location) {
    // return distance beween location and position < radius
  }
}

std::vector<Circle> circles;

// do it the when circles vector changes
void rebuildDrawNode()
{
  drawNode.clear();
  for (const Circle& circle : circles) {
    drawNode->drawDot(...)
}

void checkIfTouches(const Position& position) {
  for (const Circle& circle : circles) {
    if (circle.isInside(position)) {
      // do what you need
    }
  }
}

As a side node, never use operator== to compare Position, always test if difference between coordinates is lesser than a specified amount.


Is there any way to cancel Panels' overlay edit windows?

Question: I don't want to edit Panel panes via overlay edit-windows and therefore I tried to disable the core "Overlay" module at admin/modules but it seems to effect everything except the overlay of the Panels module.
Note: The reason I want to disable Panels' overlay is because it's slow to me (especially in Dev periods when I disable cache, and that it sometimes stuck and loads "Forever")... Besides, it cannot be open in a new tab, as I would prefer.
Do you know how to disable it?
Answer: I did some research and looked into Panels 3 code so far I don't see any nojs fallbacks. You can also check if there are fallbacks when you try to disable Javascript in the browser.
This may not be the answer on how to disable Panels modals but you may increase PHP, MySQL and or Apache settings and increase memory to your local host.
Comment: Node.JS? Fallbacks?...
Comment: No, I meant the AJAX Graceful Degradation coding way of coding (https://api.drupal.org/api/examples/ajax_example%21ajax_example_graceful_degradation.inc/group/ajax_degradation_example/7) where code checks if JS is off and if it is then it will give you a normal page where it doesn't need and JS for it to run like the modal popup.


Proving that $f|\mathbb R \times \{0\}$ having a minimum and $\frac{\partial f}{\partial y}(0,0) > 0$ leads to $f$ having a minimum

Question: I am given a function $f\in C^1(\mathbb R  \times \mathbb R_0^+)$ and I know that the restricted function $f|\mathbb R \times \{0\}$ has a local minimum at $(0,0)$. I also know that $\frac{\partial f}{\partial y}(0,0) > 0$. I would now like to show that $f$ itself has a local minimum in $(0,0)$. I already toyed around with the hint that suggests to compare $f(x,y)$ with $f(x,0)$ and $f(x,0)$ with $f(0,0)$.
I started off by saying that $\nabla f(x_0,0) = \nabla f|[\mathbb R \times \{0\}](x_0,0)$, so if I am not totally wrong, then I can conclude that $ \frac{\partial f}{\partial x}(0,0) = 0$. What kind of irritates me though, is that I do not quite understand how $f$ can have an extremum at $(0,0)$, if  $\frac{\partial f}{\partial y}(0,0) > 0$. Doesn't it have to be zero as well? If not, how would I prove this statement?
Any help is greatly appreciated!
Answer: First note that $f$ is limited (there is a wall) on the negative values of $y$, so it is not mandatory to have $\frac{\partial f}{\partial y}(0,0)=0$.
For instance let consider $g(x)=x$ in the plane on the interval $[2,3]$. Clearly $g$'s minimum is in $x=2$, yet $g'(2)=1\neq 0$.
As an example let's look at $f(x,y)=(y+1)(x^2+1)$ on $\mathbb R\times\mathbb R^+$, it verifies your hypothesis and I'm sure you can easily visualize that $f$ has a local minimum in $(0,0)$ (it is even global in that case). But it would not be so if $y$ was allowed to be negative.

Another example, this time on the restriction in $\{0\}$, note that in your hypothesis $f$ is $C^1$ only for $y\neq 0$. [I assume the notation $\mathbb R_0$ stands for the usual $\mathbb R^*$ or $\mathbb R\setminus\{0\}$].
For instance let's take $g(x)=|x|$, we have $g'(x)=\pm 1\neq 0$ yet the minimum of $g$ is reached in $x=0$.
Thus $f(x,y)=(|y|+1)(x^2+1)$ on $\mathbb R\times\mathbb R$ this time would also have a global minimum in $(0,0)$ despite $\frac{\partial f}{\partial y}(0,0)\neq0$.
Intuitively your hypothesis says that $f(x,0)$ has a local minimum in $x=0$, and that locally $f(\cdot,y)$ is increasing in $y$ so $(0,0)$ is necessarily a local minimum for $f$.

Note that despite $f\in C^1(\mathbb R\times\mathbb R^{*+})$ where $y=0$ is excluded, since $\frac{\partial f}{\partial y}(0,0)$ exists we can extend $f$ into a function $\tilde f$ behaving as expected in a neighborhood of
$(0,0)$ and write :
$\tilde f(x,y)=\underbrace{f(0,0)}_{\tilde f(0,0)}+x\;\underbrace{\frac{\partial f}{\partial x}(0,0)}_{0}+y\;\underbrace{\frac{\partial f}{\partial y}(0,0)}_{>0}+o(x,y)\ge \tilde f(0,0)\quad$ for $y>0$, thus realizing a local minimum of $\tilde f$.


Send parameter to another page

Question: I want to build a page that will be my player.
That page.tpl.php will include code like the following one:
<object bla bla ... idmedia="**the parameter that i want to get**"></object>.

I want to call this page with various parameters that play other videos.
I can I do it?
Answer: you can your page with a GET variable appended in the url, something like
www.mysite.com/node/1?videoId=123

then inside your template you use a GET variable like this
$videoId = $_GET['VideoId'];

then you could do this
<object bla bla ... idmedia=" $videoId "></object>.

Answer: If you are looking to have a block that provides links to other related content you would do it like this:

Create a content type to contain your player and whatever other information you want.
Add fields to contain any sorting categories that you want to use to relate the content such as subject categories, media author etc.  These fields can me created as Taxonomy fields which will provide the list of options you wish as input in the fields.
Create a View definition using the Views module to select the content type along with any other filtering or sorting criteria you want to apply to the main page for your media content.
Add a contextual filter to the view and apply it to a block so that the block will provide a list of the related content available for the contextual filter.

This sounds simple, but is not to someone new to Drupal.  There are excellent videos and other information on using Views at Nodeone.se

Send parameter to another page


Determining if a linear transformation across abstract vector spaces is surjective given a non-square coefficient matrix

Question: I have been having a bit of trouble with this problem. It can be viewed here, at the very bottom, question C23, the answer is provided but obviously not in enough detail. Here is the definition of the linear transformation. I understand that I must get $\vec{v}$ in terms of $\vec{u}$ but I am unsure of how to do that.
$$
T:\mathbb{C}^5 \longrightarrow P_3 \qquad
T\left(
\begin{bmatrix}
a \\ b \\ c \\ d \\ e
\end{bmatrix}
\right) =
a + (b+c)x + (c+d)x^2 + (d+e)x^3
$$
All of the other examples, namely "Example SAV" (see link), have just involved taking the inverse of a coefficient matrix when the equation is of the form $A\vec{u}=\vec{v}$. However, the coefficient matrix in this example is not square, it is rectangular provided below. How do I prove that this transformation is surjective?
$$
\begin{bmatrix}
1&0&0&0&0\\
0&1&1&0&0\\
0&0&1&1&0\\
0&0&0&1&1
\end{bmatrix}
$$
Comment: Surjective means that the image of the transformation (also called the *range*) is all of the target vector space. In coordinates (meaning that you have explicitly chosen a basis for the domain $\mathbb{C}^5$ and the codomain $P_3$), you want the column space (span of columns of the matrix) to be all of $\mathbb{C}^4$.
Comment: @Sammy Black is that all I need? A "proper" answer would be greatly, greatly appreciated. This has stumped me for some time.
Comment: Sure, I will copy and expound upon the hint.
Comment: @Sammy Black thank you, if you could a worked solution would be greatly appreciated so I can really piece it together, but of course it's your time. Your comment is greatly appreciated.
Comment: If you can get a basis out of this, you're done. A basis for $P_3$ is $1, x, x^2 + x^3, x^3$ and generating those suffices -- so for example, pick $a = 1$ and all the others to be 0 to get 1. Similarly pick $b=1$ and all the others to be 0 to get $x$. Picking $d = 1$ and all others 0 gets you $x^2 + x^3$ and picking $e = 1$ and all others 0 gets you $x^3$.
Answer: Surjective means that the image of the transformation $T$ (also called the range) is all of the target vector space. In coordinates (meaning that you have explicitly chosen a basis for the domain $\mathbb{C}^5$ and the codomain $P_3$), you want the column space (span of columns of the matrix) to be all of $\mathbb{C}^4$.
In order to verify the latter, we apply the Gaussian elimination algorithm, which converts
$$
A =
\begin{bmatrix}
1&0&0&0&0\\
0&1&1&0&0\\
0&0&1&1&0\\
0&0&0&1&1
\end{bmatrix}
$$
to the reduced row-echelon form
$$
B =
\begin{bmatrix}
1&0&0&0&0\\
0&1&0&0&1\\
0&0&1&0&-1\\
0&0&0&1&1
\end{bmatrix}.
$$
Since $B$ has a pivot in each row, the transformation is onto. In fact, we can say more: the columns with pivots, namely $\{1, 2, 3, 4\}$, are the same columns in the original matrix who span the image of the transformation. In other words, with the notation $\mathbf{e}_j \in \mathbb{C}^5$ for the standard basis vector with $1$ in coordinate $j$ and $0$ elsewhere,
$$
\bigl\{ T(\mathbf{e}_1), T(\mathbf{e}_2), T(\mathbf{e}_3), T(\mathbf{e}_4) \bigr\}
= \bigl\{ 1, x, x + x^2, x^2 + x^3 \bigr\}
$$
spans $P_3$.

Edited to respond to comments.
Working directly from the definition of surjective, given the transformation $T: \mathbb{C}^5 \to P_3$ and arbitrary $p \in P_3$, we must find $\mathbf{v} \in \mathbb{C}^5$ such that $T(\mathbf{v}) = p$. Start by naming coefficients for $p$:
$$
p = q + rx + sx^2 + tx^3.
$$
Since
$$
T \left( \begin{bmatrix} a\\b\\c\\d\\e \end{bmatrix} \right)
= a + (b+c)\, x + (c+d)\, x^2 + (d+e)\, x^3,
$$
by equating coefficients, we have the system of linear equations
$$
\left\{
\begin{array}{rcrcrcrcrcr}
a &  &  &  &  &  &  &  &  &= &q \\
  &  &b &+ &c &  &  &  &  &= &r \\
  &  &  &  &c &+ &d &  &  &= &s \\
  &  &  &  &  &  &d &+ &e &= &t
\end{array}
\right.
$$
which can be represented as the augmented linear system
$$
\left[
\begin{matrix}
1&0&0&0&0\\
0&1&1&0&0\\
0&0&1&1&0\\
0&0&0&1&1
\end{matrix}
\;\middle|\;
\begin{matrix}
q\\r\\s\\t
\end{matrix}
\right].
$$
Row reduction yields
$$
\left[
\begin{matrix}
1&0&0&0&0\\
0&1&0&0&1\\
0&0&1&0&-1\\
0&0&0&1&1
\end{matrix}
\;\middle|\;
\begin{matrix}
q\\r-s+t\\s-t\\t
\end{matrix}
\right].
$$
Since the $5$th column has no pivot, the variable $e$ is free. Thus, we have
$$
\begin{bmatrix} a\\b\\c\\d\\e \end{bmatrix}
= \begin{bmatrix} q\\r-s+t-e\\s-t+e\\t-e\\e \end{bmatrix}
= \begin{bmatrix} q\\r-s+t\\s-t\\t\\0 \end{bmatrix}
+ e \begin{bmatrix} 0\\-1\\1\\-1\\1 \end{bmatrix},
$$
for any $e \in \mathbb{C}$. All we need to establish surjectivity is at least one solution. Here we've parametrized an (infinite) $1$-dimensional family of solutions to the equation $T(\mathbf{v}) = p$.
You should plug this $\mathbf{v}$ into $T$ and check that it always produces $p$.
Comment: Is there anyway to find out how they generated their particular example solution provided in the link I originally posted? In the other example, "Example SAV" (see link) they gave a way to determine the original $\vec{u}$. Is it as simple as just solving $A\vec{u}=\vec{v}$?
Comment: Yes. In your example, because the transformation maps from a $5$-dimensional space onto a $4$-dimensional space, there's $1$ degree of freedom in the choice of a preimage of any vector in the image of $T$. In other words, for an arbitrary polynomial $p \in P_3$, you can't find *the* vector $\mathbf{v}$ such that $T(\mathbf{v}) = p$, but you can find *a* vector, and its span (i.e. all of its scalar multiples) will work as well.


Algorithm to find an approximation for a common factor of a set

Question: Given a set of positive real numbers $X=\{x_1,...,x_n \}$ and let $\varepsilon>0$, how could one find the smallest $z>0$ such that $$\mid(z\cdot x_i)-f(z\cdot x_i) \mid<\varepsilon $$ for $i \leq n $, where $f(x)$ is the closest natural to $x$, and if two naturals are at the same distance of $x$, $f$ maps it to the even integer.
Thanks in advance
Also, by natural I mean a positive (non-zero integer), i.e. $f(0.002)=f(-32)=1$.
Comment: Note there's no *smallest* $z \gt 0$ which would work since as $z \to 0$, you have $z \cdot x_i \to 0$ for all $i \le n$, so $\left|(z\cdot x_i)-f(z\cdot x_i)\right| \to 0$ and, thus, would be $\lt \varepsilon$. Did you perhaps mean the largest $z \gt 0$ instead? Also, do you want your result to be true for at least one $i \le n$, or for all $i \le n$?
Comment: Thanks for the comment, I edited my question to be more clear about what I need
Comment: Again, sorry about that. I thought  that I had changed the word integer.
Comment: If $x_i < 0$ for some $i$, $|(z \cdot x_i) - f(z \cdot x_i)|$ is a linear function with positive slope passing through $(0,1)$.  If $\varepsilon < 1$, then there is no $z>0$ that satisfies your condition.
Answer: Not an answer:
The condition may be unsatisfiable for most $\varepsilon < 1/2$.  As a random example, set
$$  X = \{8.44045, 7.62664, 3.16536, 8.96804, \\
5.16923, 1.63361, 8.11436, 4.27568, \\
3.11587, 1.10181\}  \text{.}  $$
Then simultaneously plotting $|z x_i - f(z x_i)|$ as $z$ ranges over $(0,1]$ yields

While there may be a surprise coincidence allowing a solution in $z$ for a small value of $\varepsilon$, expect these to be rare.


Angularjs json ng-repeat displays items properties only with manual iterator

Question: I'm getting json from some web service and displaying it with ng-repeat but i can't seem to display item properties.

{{item}}

This works and will display all json

{{item.name}}

This doesnt work.

{{item[0].name}}

This works but will only display 1 item.
I just started working with angular and i feel i'm missing something becouse of it, if needed i'll try to post a jfiddle of a sample.
UPDATE
I'm trying to get twitch.tv stream info
https://github.com/justintv/Twitch-API/blob/master/v2_resources/streams.md#get-streams
raw json from 2 streams, what i get from the first example
http://pastebin.com/bQLqu9BR
UPDATE 2
my code
http://plnkr.co/edit/3eOZ598zt2hkrJcsOLhP
Comment: Show us the raw json data
Comment: updated with json data
Answer: Hmmm... I seem to be able to work with the sample data you provided.
See the following:
http://plnkr.co/edit/M3TQ4qI1DJPtgv6jCQLy?p=preview
Snippet:

Comment: Oh and here's another plunk in case you have to build up `srcData`. Use `concat` instead of `push`. http://plnkr.co/edit/DXZSQQi5qjGQXXBsVkWD
Comment: Ahh ok.  So in your updated plunk you're pushing `list.streams` into `srcData`, which is initialized to an array.  So what you're effectively doing is adding the array elements of `list.streams` as the first element of `srcData`.  Here's another plunk where I just replace `srcData` with `list.streams`.  Not sure if this approach could work for you. http://plnkr.co/edit/8iMBFZPK3lqmyoPl7Tob
Answer: You don't need to include an index for each item to display its properties, every item knows its index number and you can access it using the $index variable.
Check this out:
http://plnkr.co/edit/ECyyFYVupVG7mKqwsGaB

    {{$index}}

      Game: {{item.game}}

      Channel Name: {{item.channel.name}}

Comment: can you check out my plnkr code under update 2 and say whats wrong.
Comment: You are pushing `list.streams` array inside `$scope.srcData`array, so although the `list.streams`contains 3 elements the `$scope.srcData`array only have 1 (which is the other array) and that's why ng-repeat only displays 1 element. You can just assign `$scope.srcData = list.streams` instead of pushing it.


What does the notation $h \ll 1$ mean?

Question: The following screenshot is taken from some lecture notes on actuarial mathematics:

As you can see, the notation $h \ll 1$ is used here (in the first line of the proof).
Does anyone know what this is supposed to denote? I first suspected that it was a typo and was instead supposed to be $h < 1$ or $h \leq 1$, but the same notation is used on several occasions (leading me to believe that its use must be intentional).
Comment: I am amazed to learn that whoever typed the lecture notes does not know $\ll$ and used $<<$ instead.
Comment: https://en.wikipedia.org/wiki/Inequality_(mathematics)
Answer: It means "sufficiently smaller than". So, $h\ll1$ means that $h$ is sufficiently smaller than $1$ (but still greater than $0$).
Answer: It means $h$ is much smaller than $1$.  It can be an informal way of working with powers, where you say you can neglect terms with a higher power of $h$ because they are even smaller.  For example, we know $(1+h)^3= 1 + 3 h + 3 h ^ 2 + h ^ 3 $. If $h\ll1$ the terms with $h^2$ and $h^3$ are even smaller, so we may be able to neglect them.

What does the notation $h \ll 1$ mean?


How to get last modified text files by date from remote FTP location

Question: I am stuck on atomization of an process to download last modified text files on date wise or today. Here is my code.
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
$contents = ftp_nlist($conn_id, '-rt .');
reset($contents);

function is_txt($file) {
    return preg_match('/.*\.txt/', $file) > 0;
}

$filtered = array_filter($contents, is_txt);

// download all files in downloaded directory
while (list($key, $value) = each($filtered )) {

    if (ftp_get($conn_id, $dir.'\\downloaded\\'.$value, $value, FTP_BINARY))   {
        echo "Successfully written to $value\n";
    } else {
        echo "There was a problem\n";
    }
}

I got success in getting text files, but not selecting the last modified files, filemtime is not helping me nor curl.
Answer: Since PHP 7.2, you can use ftp_mlsd function to retrieve list of files including their timestamps. Check the "modify" entry. You can then easily identify the latest file.

With older versions of PHP, you will need to use the ftp_mdtm function to retrieve the modification time of files.
But you have to call it individually for every file, what is pretty inefficient. See Downloading only new images from FTP server in PHP.
You can also try an implementation of the MLSD in user comments of the ftp_rawlist command:
https://www.php.net/manual/en/function.ftp-rawlist.php#101071
First check if your FTP server supports MLSD before taking this approach, as not all FTP servers do (particularly IIS and vsftpd don't).

The only other way is to use the ftp_rawlist function. But its returns a ls-like line for every file with no pre-defined format. If you connect to one specific server, you can use it; and hard-code the parsing based on the specifics of the server. But it's not reliable, if you need to connect to an arbitrary server.
Typical listing on a *nix server is like:
drwxr-x---   3 vincent  vincent      4096 Jul 12 12:16 public_ftp
drwxr-x---  15 vincent  vincent      4096 Nov  3 21:31 public_html
-rwxrwxrwx   1 vincent  vincent        11 Jul 12 12:16 file.txt

For some basic code, see PHP FTP recursive directory listing – That that does not include the timestamp parsing.
Answer: Thanks @Martin With your help i was able to solve above problem
$conn_id = ftp_connect($ftp_server);
$login_result = ftp_login($conn_id, $ftp_user_name, $ftp_user_pass);
$contents = ftp_nlist($conn_id, '-rt .');
reset($contents);

function is_txt($file) {
 return preg_match('/.*\.txt/', $file) > 0;
}

$filtered = array_filter($contents, is_txt);
$array = array();
//download all files in downloaded directory
while (list($key, $value) = each($filtered )) {
    $buff = ftp_mdtm($conn_id, $value);

    if ($buff != -1) {
        array_push($array,date("F d Y", $buff));
    }

}
$lmdate = array_pop($array);

$key="";
$value="";
reset($filtered);
while (list($key, $value) = each($filtered ))
 {

    $buff1 = ftp_mdtm($conn_id, $value);
    $cdate=date("F d Y", $buff1);

    if (($buff1 != -1) and ($cdate == $lmdate)){

        if (ftp_get($conn_id, $dir.'\\downloaded\\'.$value, $value, FTP_BINARY)) {

            echo "Successfully written to $value\n";
            } else {
            echo "There was a problem\n";
        }
    }

}


Exception message empty

Question: I have an exception class as follows:
class FileNotFoundException : public std::exception
{
public:
    FileNotFoundException(const char* message) : errorMessage(message){ }
    const char* what() const throw() override
    {
        return this->errorMessage;
    }
private:
    const char* errorMessage;
};

And I throw this exception like this:
std::string message = "Message";
throw ::FileNotFoundException(message.c_str());

But when I try to handle it using:
try
{
    // the code that throws
}
catch(::FileNotFoundException& ex)
{
    std::string message = ex.what();
}

The string is empty.
If anyone can help, I would gladly appreciate it.
Comment: Undefined behavior. When you `throw`, your `std::string message` goes out of scope, and is destroyed, and your `errorMessage` points to deallocated memory.
Comment: thank you, you are both correct. Stupid that I didnt think of anything this simple.
Answer: You can't just store a pointer to the message. Try either storing it in std::string, or, better, pass it to the parent constructor. Perhaps it's better to inherit from std::runtime_error in that case.
Here's a complete example:
#include <iostream>
#include <string>
#include <stdexcept>

class FileNotFoundException : public std::runtime_error
{
public:
  FileNotFoundException(const char* message) : std::runtime_error(message)
  {
  }
};

int main()
{
  try {
    throw ::FileNotFoundException("oops, something happened");
  }
  catch(const ::FileNotFoundException& ex) {
    std::cout << "Exception: '" << ex.what() << "'" << std::endl;
  }
}

Compiling and running:
$ g++ -W -Wall --std=gnu++11 a.cpp -oa
$ ./a
Exception: 'oops, something happened'

In short (and without details): The class std::exception doesn't have any constructors. It's just a parent class used by all other exceptions. On the other hand, std::runtime_error has a constructor that stores the message for you properly. A complete explanation can be found in Difference: std::runtime_error vs std::exception()
I think this approach is better than to define what() and using std::string to store the message yourself. That is, if you don't have special needs for the exception class.
You should also check out the C++ exception hierarchy.
Comment: Seems true - I checked here now: http://en.cppreference.com/w/cpp/error/runtime_error
`std::runtime_error` seems to copy the constructor argument. Did not expect this.
Comment: Thank you, this is the solution. Also thanks for the example, I am going to accept this as the answer as soon as I can.
Comment: Your example only fixes it because you pass a real constant string to the exception constructor, instead of having a seperate `std::string` variable on the stack whose pointer is passed. Passing that pointer to the parent constructor doesn't fix the behavior, the string will still not get copied.
Comment: @Matthias247 I don't know what the standard says about it, but GCC definitely copies the string (I've double checked). Worth looking into.
Comment: It *may* be that most standard library authors just copy it anyway, because otherwise it would be very dangerous (you're jumping up the stack). So it could be a case where everyone does it, but it could also be the standard doesn't explicitly require it.
Answer: Your problem is here:
throw ::FileNotFoundException(message.c_str());

You are storing a pointer to memory owned by message in the exception. When message goes out of scope (which happens during the throw) the data will no longer be valid. Which means this->errorMessage returns some undefined memory. To fix it you can either pass some really constant string to your exception or you need the exception to own the string, e.g. by making errorMessage a std::string.

Exception message empty


Alterar classe com javascript ao redimensionar a tela

Question: Preciso de um código javascript que altere a classe menu para a classe responsivemenu quando a resolução da tela for menor que 750px.
Comment: Não podes fazer isso com CSS (media query?)
Comment: Acredito ser a melhor opção também.
Verifique se você não pode realizar essa operação diretamente no CSS.
Aqui tem um exemplo pra você dar uma estudada: http://goo.gl/LJFKRp
Answer: Utilizando JavaScript
Note que estou verificando o tamanho dentro do bloco window.addEventListener('resize', function() {..});, a função será chamada toda vez em que a resolução da tela for alterada.
window.addEventListener('resize', function () {
    //var altura = window.innerHeight;
    var largura = window.innerWidth;

    if (largura < 750)
        document.getElementsByClassName('menu')[0].className = 'responsivemenu';
});

Utilizando CSS Media Query
A maneira mais simples utilizando Media Query é definir folhas de estilos especificas para cada tipo de dispositivo, para isso basta adicionar a propriedade media para definir para que tipo de dispositivo seu css será usado.
Utilize handheld para dispositivos de mão, celulares e outros dispositivos deste perfil. Normalmente com telas pequenas e banda limitada.
<link rel="stylesheet" href="estilo.css" type="text/css" media="handheld">

Agora a forma que acredito ser mais correta, no seu arquivo de estilos você utilizará condicionais para definir o estilo para cada resolução que desejar.
/* Estilo padrão */
menu {
  color: blue;
}

/* Estilo para resolução menor que 750 pixels */
@media screen and (max-width: 750) {
  menu {
    color: green;
  }
}

Dentro do bloco você irá definir o estilo específico para a resolução.
Fonte: Introdução sobre Media Queries
Comment: Deveria ter sido essa a escolhida
Comment: Essa é a solução correta!
Comment: ótima resposta!
Passarei a usar mais o js sem jquery.
Comment: ótima resposta, você poderia incluir uma alternativa usando `media query`, talvez o AP desconheça este recurso e isto poderia beneficiar a ele (assim como a comunidade).
Comment: Bah @TobyMosque `media query` só sei que existe. Vou dar uma lida sobre e qualquer coisa edito a resposta.
Answer: Há diversas maneiras de se fazer isto.
Com Jquery, por exemplo, pode ser feito assim:

if ($(window).width() <= 750)
  $('.menu').removeClass('menu').addClass('responsivemenu');
  // ou
  $('.menu').attr('class','responsivemenu');

Há diversas formas para fazer esta operação.
Caso queira se aprofundar nesse método que apresentei, dê uma olhada em: http://goo.gl/F26YSx
Answer: Amigão, tenta da seguinte form.
if(window.screen.availWidth<750){
  $('.menu').addClass('responsivemenu').removeClass('menu');
}

Comment: O if no começo do codigo já garante que o script vai rodar apenas abaixo de 750px.
pq me deu ponto negativo? o codigo ta correto
Comment: Muito obrigado pelo tempo e gentileza, pode deixar! ;)
Comment: Não estou querendo abrir uma discussão conturbada a respeito, mas podemos ver no debate do do link(este do META) que no geral, mesmo que o AP tenha colocado Javascript no titulo, apresentar soluções com jquery ainda poderia ser válido, já que a "solução" esperada também pode ser feita com a tal lib em questão. De qualquer forma, é inegável que a resposta do Pedro seja a escolhida como "melhor resposta", que alem de simples, soluciona muito bem o problema e ainda é em JS purão. Mas convenhamos que é relativa negar a "conveniência" em usar Jquery. O que acham? [vamos ser amigáveis, please,rs]
Comment: stackoverflow brasil é mais mimimi que tecnologia, infelizmente.
Comment: Mas preciso que isso seja executado só com resolução menor que 750px por exemplo.
Comment: Não dei ponto negativo @RBoschini. Dei ponto positivo, não sei quem deu ponto negativo. Inclusive usei seu código e deu certo.
Comment: Maravilha então, que bom que deu certo! precisando de ajuda é so chamar! abracos
Comment: o `-1` possivelmente se deve ao `Amigão, usa o jquery.`, para entender veja o seguinte topico: [When is "use jQuery" not a valid answer to a JavaScript question?](http://meta.stackexchange.com/questions/45176/when-is-use-jquery-not-a-valid-answer-to-a-javascript-question)
Comment: TobyMosque obrigado, vou prestar mais atenção. ;)