Usar dados de uma classe em diversos JFrames

Question: Estou desenvolvendo uma aplicação com diversos JFrames, criei uma classe chamada Person com diversos atributos para ser usado nos JFrames da aplicação. Minha principal dúvida é: onde devo instanciar essa classe para que os atributos dela sejam acessíveis por qualquer JFrame?
Para simplificar o problema, desenvolvi um MVE para quem estiver disposto ajudar poder testar.
Main:
package teste;
public class Teste {

    public static void main(String[] args) {
        Screen1 sc1 = new Screen1();
        sc1.setVisible(true);
    }

}

Classe Person:
package teste;
public class Person {
    String name;
    String age;
    public Person(String name, String age){
        this.name = name;
        this.age = age;
    }
    public void setName(String name) {
        this.name = name;
    }
    public String getName(){
        return this.name;
     }
     public void setAge (String age) {
        this.age = age;
    }
    public String getAge(){
        return this.age;
     }
}

JFrame 1:
package teste;

public class Screen1 extends javax.swing.JFrame {

    public Screen1() {
        initComponents();
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jLabel1.setText("NAME");

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jButton1.setText("NEXT");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(113, Short.MAX_VALUE)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 189, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(98, 98, 98))
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addGap(165, 165, 165)
                        .addComponent(jLabel1))
                    .addGroup(layout.createSequentialGroup()
                        .addGap(161, 161, 161)
                        .addComponent(jButton1)))
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(63, 63, 63)
                .addComponent(jLabel1)
                .addGap(27, 27, 27)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 45, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 68, Short.MAX_VALUE)
                .addComponent(jButton1)
                .addGap(44, 44, 44))
        );

        pack();
    }// </editor-fold>

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
        Person p = new Person();
        p.setName(jTextField1.getText());
        Screen2 sc2 = new Screen2();
        sc2.setVisible(true);
    }

    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Screen1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Screen1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Screen1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Screen1.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Screen1().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}

JFrame 2:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package teste;

/**
 *
 * @author Iago
 */
public class Screen2 extends javax.swing.JFrame {

    /**
     * Creates new form Screen2
     */
    public Screen2() {
        initComponents();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jTextField1 = new javax.swing.JTextField();
        jButton1 = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setFont(new java.awt.Font("Tahoma", 0, 36)); // NOI18N
        jLabel1.setText("AGE");

        jButton1.setFont(new java.awt.Font("Tahoma", 0, 18)); // NOI18N
        jButton1.setText("NEXT");
        jButton1.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jButton1MouseClicked(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(117, 117, 117)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addGap(172, 172, 172))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jButton1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 175, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addGap(108, 108, 108))))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(51, 51, 51)
                .addComponent(jLabel1)
                .addGap(29, 29, 29)
                .addComponent(jTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 50, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 48, Short.MAX_VALUE)
                .addComponent(jButton1, javax.swing.GroupLayout.PREFERRED_SIZE, 44, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(34, 34, 34))
        );

        pack();
    }// </editor-fold>

    private void jButton1MouseClicked(java.awt.event.MouseEvent evt) {
        Person p = new Person();
        p.setAge(jTextField1.getText());
        Screen3 sc3 = new Screen3();
        sc3.setVisible(true);
    }

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Screen2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Screen2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Screen2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Screen2.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Screen2().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JButton jButton1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JTextField jTextField1;
    // End of variables declaration
}

JFrame 3:
package teste;

public class Screen3 extends javax.swing.JFrame {

    public Screen3() {
        initComponents();
        Person p = new Person();
        jLabel1.setText(p.getName());
        jLabel2.setText(p.getAge());

    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        jLabel1.setText("jLabel1");

        jLabel2.setText("jLabel2");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap(147, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 131, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(122, 122, 122))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(89, 89, 89)
                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addGap(18, 18, 18)
                .addComponent(jLabel2)
                .addContainerGap(133, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Screen3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Screen3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Screen3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Screen3.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the form */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new Screen3().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration
}

PS.: Ja tentei utilizar varáveis estáticas, porém sem sucesso.
Answer: Bom vamos la, uma JFrame nada mais é doque uma classe. Sabendo disso sabemos também que objetos instanciados dentro de um escopo ficam visíveis somente nesse escopo.. ou seja:
    public class Screen3 extends javax.swing.JFrame {
        public Screen3() {
            initComponents();
//essa Classe instanciada aqui morre aqui, só serve para setar as label's mesmo..
            Person p = new Person();
            jLabel1.setText(p.getName());
            jLabel2.setText(p.getAge());

        }
    }

caso essa classe instanciada fosse necessário mante-la durante todo o processo teria que ser declarada fora do escopo e instanciada no construtor..
        public class Screen3 extends javax.swing.JFrame {
            private Person p;
            public Screen3() {
                initComponents();
                p = new Person();
                jLabel1.setText(p.getName());
                jLabel2.setText(p.getAge());

            }
        }

outro modo seria criar um Person em uma classe que possua metodo main, e a partir dela passar o Person na instanciação dos jFrames.. mas isso faria com que todos os JFrames estivessem exatamente o mesmo objeto de Person.


How to get teaser break to work with WYSIWYG + CKEDITOR?

Question: I have Drupal 7.7 + WYSIWYG 7.x-2.1 + CKEDITOR 3.6.1 installed.
My goal is to be able to insert a teaser break into my blog posts (blog post content type - body field), in order to specify what goes into the teaser and what goes into the full node view.
When I click the "Separate the teaser and body of this content" button in the CK EDITOR menu bar, the text  is automatically inserted into my body field. However, this break is not having any effect on the text that remains in the teaser view vs. on the full node view. It simply doesn't seem to be working. I tried using TinyMCE and I had the same problem
Can anybody please advise on how can I get this function working?
Thanks!
---More details about my current setup: ----------------
In the CK editor profile for "Filtered HTML" - in the "CLEANUP AND OUTPUT OPTIONS", the following options are enabled:
- Verify HTML
- Convert  tags to styles
- Remove linebreaks
These options are not enabled:
- Preformatted
- Apply source formatting
- Force cleanup on standard paste
Comment: HTML comments get removed, and this is a comment. There's a patch at http://drupal.org/node/881006#comment-5628078 that will result in the `` content coming through, although there are then other issues with CKEditor at least in that it sticks the break inside a  leaving a hanging open . Humph
Comment: In case it suits your needs just to have one WYSIWYG editor, you should definitely try the regular [CKEditor](https://drupal.org/project/ckeditor) module too. With it, you can define different profiles for different text formats, and enable a teaser break button in the text editor, and there's no problem with the Filtered HTML text format, teaser break does its job correctly.
Answer: Adding  (in addition to whatever set of HTML tags you already have).
Save configuration.
Comment: Please review the improvement I added to your answer (by adding the steps to be performed, and improving the formatting of the actual string). If you don't like my edit at all, just perform a rollback. BTW, I think this answer is the best possible answer to the question asked here (just a rather standard configuration change, no patching or whatever needed, and of course it works).
Comment: This answer should be marked as the correct answer as OP is asking for a solution using the filtered HTML, which is the case. Indeed using Full HTML solves this problem, but is not always opportune.
Answer: Have you considered just putting your desired teaser into the Summary (under Edit Summary) instead? It may be a more convenient workaround than trying to set up the Teaser Break.
Comment: But in case you change the teaser, and you want it to appear in both the teaser and the full content, you have to change it in both places, in the Summary and in the full content editing area too, so it's definitely NOT an answer.
Answer: Switch to Full HTML.  I don't believe Teaser Breaks are allowed in Filtered HTML.
More info in link http://old.nabble.com/Wysiwyg-Frustrations%3A-My-Approach%2C-What-is-Yours-to31984379.html#a31984379
Comment: Full HTML has security risks (as your link says) :-( There's no reason Teasers Breaks aren't allowed in Filtered HTML, although some users [have reported](http://redhotchilliproject.com/blog/using-the-drupal-teaser-break-with-filtered-html-in-drupal-7) having to enable comments in the HTML filter.
Answer: Apply the patch at http://drupal.org/node/881006#comment-5628078. This makes sure the  comment is not stripped out along with any other comments.
Aside(?): I'm using Display Suite and I found my teasers weren't working, even with this patch applied and the break comment in my HTML. I solved this by enabling a custom display for Teaser, and then choosing "Summary or trimmed" as the format at admin/structure/types/manage/page/display/teaser.
Answer: I know this is an old question but thought I'd share this anyway. I ran into the same problem but managed to solve it with a module called "Smart Trim"
I had a view display fields and I couldn't get the summary or trimmed values of my node body field to display, but with this module it gives me another display option which seems to work perfectly.


Override the body field with another field in hook_node_view

Question: I have a node type that can be scheduled. Before the start time the page will redirect to another. This is all custom functionality and is currently working.
Now I need to create a coming soon page to allow the page to be active before the start time but not show any of the details.
I've created a coming soon field in the node and I have the logic set up correctly but I am struggling with the render array.
function MODULE_node_view($node, $view_mode, $langcode) {
  if ($node->type == 'TYPE') {

    // admins see the page no matter what
    if (!user_access('administer site configuration')) {

      // if not started, show coming soon page
      $coming_soon = FALSE;
      if (!STARTED) {
        $coming_soon = field_get_items('node', $node, 'field_coming_soon_body');
        if ($coming_soon) {
          $node->content['body']['#object']->body[$node->language][0]['value'] = $coming_soon[0]['value'];
        }
      }
    }
  }
}

This however still shows the actual body of the page and not the coming soon page. I really want to do this in hook_node_view as well.
How can I go about replacing the content of the page with this single field?
Comment: Instead of reassigning the body's field value, can't you just hide it and show the field_coming_soon_body?
Comment: how do I hide a field in this hook?
Answer: Just hide your body field, if there's a value in your field_coming_soon_body:
    if ($coming_soon) {
      $node->content['body']['#access'] = 0;
    }

Comment: Sure! Glad to help, Scott!


Apache doesn't match rewritten URL as regular file

Question: I've setup a .htaccess to redirect requests against the containing directory /htdocs/foo to the file bar.php.
1st of all: I know how to achieve this in general, but for reasons out of my control the .htaccess also wants to check if the URL resolves to a regular file and redirects if not.
Doesn't sound too complicated, but I can't work this out. :[
This is my .htaccess:
RewriteRule ^$ http://www.example.com/foo/bar.php

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* doh.php

These rules don't redirect www.example.com/foo to bar.php but doh.php instead.
I checked the error.log and for some reason the Rewrite Condition is matched although the file bar.php is present.
RewriteCond: input='http://www.example.com/foo/bar.php' pattern='!-f' => matched

Apparently Apache doesn't consider bar.php as regular file if a rewritten URL points to it. www.example.com/foo/bar.php works as expected.
Any ideas why?
Edit #1:
For clarification, this is the file structure:
/ (File system root)
|
+ htdocs (Document root)
  |
  + foo
    |
    + .htaccess
    + bar.php
    + doh.php

Edit #2:
I'm running Apache 2.4.
Solution:
The RewriteCond expects REQUEST_FILENAME to contain a local path. Due the missing L flag the RewriteRule sets REQUEST_FILENAME to a URL which obviously is not a local path, so the test for !-f matches.
Ultimately, attaching the L flag to the RewriteRule produces the desired behavior:
RewriteRule ^$ http://www.example.com/foo/bar.php [L]

RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule .* doh.php

After the URL is rewritten to http://www.example.com/foo/bar.php a new process loop is initiated, remapping the rewritten URL to the local path /htdocs/foo/bar.php which doesn't match the RewriteCond's !-f test. And /htdocs/foo/bar.php is passed through. :)
Comment: What version of Apache are you using?
Comment: @MrWhite: I'm running Apache 2.4, good sir.
Comment: "After the URL is rewritten to `http://www.example.com/foo/bar.php` a new process loop is initiated, remapping the rewritten URL..." - not exactly. After the URL is "rewritten" to an absolute URL, an _external redirect_ is triggered (not an _internal rewrite_). A 302 response is sent back to the browser and the browser makes an entirely new request to `http://www.example.com/foo/bar.php` - it's at the start of this 2nd (entirely separate) request that Apache maps the requested URL to the filesystem (ie. `/htdocs/foo/bar.php`).
Answer:
RewriteCond: input='/htdocs/foo/bar.php' pattern='!-f' => matched

Not sure if this has been over-exemplified, but unless there is "something else" going on, this is not as expected, given the above directives.
Since your initial (implied) redirect is missing the L flag, processing immediately continues onto the next directive. At this point I would expect to see something like the following in the logs:
RewriteCond: input='http://www.example.com/foo/bar.php' pattern='!-f' => matched

Immediately after the first RewriteRule, the REQUEST_FILENAME directive is updated as-is to the output of the last RewriteRule ie. http://www.example.com/foo/bar.php. It is not remapped to the filesystem at this stage. (Unless you had specified a relative path substitution, in which case the directory-prefix would be prepended - which appears to be what you are seeing in the logs - but that does not correspond to the directive in the question.)
So, the above condition is indeed "matched" - the "absolute URL" cannot possibly exist as a file on the filesystem.
You then get a corrupted 302 "rewrite" to doh.php. The request is internally rewritten to doh.php, but the HTTP status is set to 302 from the earlier "redirect", but there is no Location header, so there is no external redirect. (Although you seem to imply there is a "redirect" to doh.php?)

RewriteRule ^$ http://www.example.com/foo/bar.php

In order to trigger an external redirect (given the later rewrite), you need to include the L (last) flag to stop the current round of processing.
You should also be explicit and include the R flag. A 302 redirect is implied here because you have explicitly included a scheme + hostname in the RewriteRule.
For example:
RewriteRule ^$ http://www.example.com/foo/bar.php [R,L]

Aside:

These rules don't redirect www.example.com/foo

Note that if you request /foo, without a trailing slash, and /foo is a physical directory then mod_dir will first implicitly 301 redirect to /foo/ in order to "fix" the URL by appending the trailing slash.
Comment: Thank you for your elaborate answer! You are right about the log entry. The input for the rewrite condition is indeed `http://www.example.com/foo/bar.php`. Do you care to explain why the rewritten URL isn't mapped to the file system? Looks like this is the crucial part I'm missing.
Comment: Ah, now I get it: The `RewriteCond` expects `REQUEST_FILENAME` to contain a **local path**. And due the missing `L` flag the `RewriteRule` sets `REQUEST_FILENAME` to a URL which obviously is not a local path, so the test for `!-f` matches.
Comment: "...why the rewritten URL isn't mapped to the file system?" - The issue here is that you are "rewritting" to an _absolute URL_. AFAIK, this is only mapped to the filesystem at the start of the request. But an absolute URL here results in an external redirect (unless overridden by a later rewrite - as would is happening here) so will not ordinarily result in a second phase of rewriting. A 302 redirect response is sent to the client instead.
Comment: If instead, you had `RewriteRule ^$ bar.php` then it would _rewrite_ the request (no _redirect_) and the following filesystem check would be evaluated correctly. However, including the `L` flag is preferable in both cases.
Comment: "The `RewriteCond` expects `REQUEST_FILENAME` to contain a **local path**" - Strictly speaking it's the `-f` function that requires an absolute filesystem path in order to check the existence of a regular file. This cannot be determined from a URL.


Derivative of a definite integral (FTIC)

Question: $\displaystyle \left.\frac{d}{dx}\right|_{x=\pi} \int_{t=0}^{x} \frac{\cos 3t}{\sqrt{1+t}} \,dt$
What would be the correct way to solve this? I'd really like to understand the reasoning behind it as well please?
Would something like this be going in the correct direction?:
$\displaystyle \int_0^{\pi} \frac{d}{dt}\!\left( \frac{\cos 3t}{\sqrt{1+t}} \right) dt$
Answer: The notation
$$
\frac{d}{dx}f\,\Bigr|_{x=a}\text{ means }f'(a),
$$
that is, derivate and then evaluate at $x=a$.
The fundamental theorem of calculus tells you that
$$
\frac{d}{dx}\int_{0}^{x} \frac{\cos 3\,t}{\sqrt{1+t}} \,dt=\frac{\cos 3\,x}{\sqrt{1+x}}.
$$
Then
$$
\frac{d}{dx}\Bigr|_{x=\pi}\int_{0}^{x} \frac{\cos 3\,t}{\sqrt{1+t}} \,dt=\frac{\cos 3\,\pi}{\sqrt{1+\pi}}=-\frac{1}{\sqrt{1+\pi}}.$$
Comment: Thank you, it's simple once you explain it! I need to refresh my knowledge on the fundamental theorem of calculus.


How do we find the derivative of a multivariate expression wrt another multivariate expression?

Question: I have $f(\theta,b) = 1 - \theta x - b$.  I want to find $$\frac{df(\theta,b)}{d[\frac{1-b}{\theta}]}$$
i.e. the change in $f$ wrt $\frac{1-b}{\theta}$.  In the language of limits,
$$
\lim_{h \to 0, a \to 0} \frac{f(\theta + h, b + a) - f(\theta, b)}{\frac{1 - b - a}{\theta + h} - \frac{1 - b}{\theta}}
$$
I saw this How to find the derivative of one expression with respect to another expression
which made me think I could try
$$\frac{df(\theta,b)}{d[\frac{1-b}{\theta}]} = \frac{\frac{df(\theta,b)}{d\theta}}{\frac{d[\frac{1-b}{\theta}]}{d\theta}} = \frac{\theta^2 x}{1 - b}$$
But if I do the same strategy wrt the other variable, I get
$$\frac{df(\theta,b)}{d[\frac{1-b}{\theta}]} = \frac{\frac{df(\theta,b)}{db}}{\frac{d[\frac{1-b}{\theta}]}{db}} = \theta$$ which is a contradiction.
Comment: What does the expression $df(\theta,b)/dg(\theta,b)$ even *mean*?!? What exactly is it that you want to compute, and why?
Comment: Ah, I see the issue.  If f isn't shown to be a function of $(1-b)/\theta$ then this expression has no meaning.
Comment: I believe I got the right answer below, but I want the derivative of f wrt infinitesimal changes in $\frac{1-b}{\theta}$.  Is this not well-defined?
Comment: Apologies if my notation was nonstandard or unclear.
Comment: As I recall, I think that I always solved this sort of thing via differentials and Jacobians.  If you want I will try to write it up.  It leads to obvious results but requires setup.  There are pitfalls but can usually be done.
Answer: The thing about decomposing $\frac{df(\theta,b)}{dg(\theta,b)}$ into two separate expressions, and then calculate the product is a fundamentally flawed way to calculate multivariate derivatives. It does often work, but not all the time. This article goes into more detail about it.
To respond to your question, with
$$g(\theta,b)=\frac{1-b}{\theta}$$
we know that
$$\theta=\frac{1-b}{g(\theta,b)}$$
Therefore, we plug it into $f$ and get
$$f(\theta,b)=1-\frac{1-b}{g(\theta,b)} x-b$$
And so,
$$\frac{df(\theta,b)}{dg(\theta,b)} = \frac{(1-b)x}{g(\theta,b)^2}$$
which when plugging in for $g(\theta,b)$, gets us the answer you found first,
$$\frac{\theta^2 x}{1-b}$$
Comment: Sorry, I don't understand this solution.  How come you can do a substitution for $\theta$ but not for $b$?  Intuitively if $(1-b)/\theta$ is changing, then so is $b$, right?
Comment: One of the requirements of using the method you have proposed, is that the function is invertible. Because your functions use two variables, the functions need to be invertible for both variables for it to work for both variables. If you take the derivative with respect to $b$, you are losing information, as $\theta^2$, is non-invertible ($\sqrt(\theta) = \theta, -\theta$). When taking the derivative with respect to $\theta$, because no information is lost (i.e. $b$ has no even power), you get the desired outcome.


Passing array to -FilePath parameter in PowerShell

Question: I'm using invoke-command to execute a list of scripts on remote servers.  I'm using a variable array to specify the scripts.
<code>$Modules = Get-Content "Modules\Modules.txt"
$ModulePath = "Modules\" + $Module
Invoke-Command server -FilePath $ModulePath
</code>
This gives me an error:
Invoke-Command : The value of the FilePath parameter must be a Windows PowerShell script file. Enter the path to a file with a .ps1 file name extension and try the command again.
Parameter name: filePath
If I replace the array with the absolute path to an individual script file, it works without issue.
Thanks!
Comment: Have you tried outputting $ModulePath to see exactly what it is you're sending to that parameter?
Comment: I have.  The string output is the full path to the script file.
Answer: No, it takes a single string only
<code>-FilePath <String>
</code>
http://technet.microsoft.com/en-us/library/hh849719.aspx
Answer: Maybe try something like this:
Get-Content "Modules\Modules.txt" | foreach { invoke-Command "Modules\$_" }
Comment: Ok, that's right.  My bad there.  PowerShell will attempt to run from either its program folder or System32 (if in admin mode) if you don't specify the current dir.  Glad it's working for you.
Comment: Tried that with same results.  Interesting to note.  If I change $ModulePath to the full path of a single script it works. For example: $ModulePath = ".\Modules\Test.ps1"


Create a calculated array based on limits

Question: OK time to pick the hive mind brain.
I am creating a dropdown (well 2 of them) and I need them to do the following
Height from 4'0" to 7'0"
Weight from 100lb to 400lb in 5lb incraments.
What would be the best/easiest way to create this array without having to manually create an array
It just needs to be as simple as
const heights = [
    { id: '', name: '' },
]

I just to not know how to best create it in as few Lines of code or manually creating the array
Same with height in 5lb increments
EDIT: SO people know WHY I am asking this - try doing a google search and enjoy the frustration.
Comment: height just goes 4'0" up to 7'0"
weight needs to go 100lb to 400lb (100, 105, 110)
When I google search for "Create Vue Array of height in feet" it just gives you div height stuff so its frustrating
Comment: Actually I have solved it in a complicated way - well 2 ways - one pulling a list from a DB, and the other was creating the list then ripping out the data I do not require. The fact people want to sit here and come at me thinking I do not know what I am doing is laughable at best. I am just looking for a more streamlined solution
Answer: For the weights, you can use the Array.fill function as seen in this answer.

// https://stackoverflow.com/questions/3895478/does-javascript-have-a-method-like-range-to-generate-a-range-within-the-supp

const range = (start, stop, step = 1) =>
  Array(Math.ceil((stop - start) / step) + 1).fill(start).map((x, y) => x + y * step)

const weights = range(100, 500, 5).map((x, index) => ({
  id: index,
  name: x
}))

console.log(weights)

// or with one line of code

const w = Array(Math.ceil((500 - 100) / 5) + 1).fill(100).map((x, index) => ({
    name: x + index * 5, id: index
}))
console.log(w)

For the heights, you can use a simple algorithm as a while loop with a condition for the increment

const start = {
  integer: 4,
  fractionnal: 0
}
const end = {
  integer: 7,
  fractionnal: 0
}

const heights = []

let index = 1
while (start.integer < end.integer || start.fractionnal <= end.fractionnal) {
  heights.push({
    id: index,
    name: `${start.integer}.${start.fractionnal}`
  })

  if (start.fractionnal < 11) start.fractionnal += 1
  else {
    start.integer += 1
    start.fractionnal = 0
  }
}

console.log(heights)
Comment: With some edits as i did, you can do it in one line of code. But do not forget that sometimes, bigger code are easier to maintain and read ;)
Comment: Completely agree, the one thing I was struggling with was my logic in my head. I agree your "non one line" is more readable and the one I will work with, however, when you look at the eight, I started to look at that and think "there has to be a cleaner way" - so knowing you came up with the same solution means I am not losing my mind - thank you!
Comment: THANK YOU - The height is similar to mine, ill clean up your code in a few here to account for ' and " in the array. The weight one was the one I was having an issue with and yours is a LOT smaller than mine is and easy enough to add lb to.

THANK YOU


Can an IGCSE problem be this complex?

Question: Following diagram has the plan view of 4 sector-shaped tiles placed in a parallelogram-shaped box.  C and F are the midpoints of the arcs AB and OG respectively.  Length OB is given to be 10 cm.  How do we find

angle OCF,
length CE,
length and breadth of the underlying box.

Four Tiles Inside a parallelogram box

Here's what I've tried.
First of all, I assumed that all tiles are equal.
Since C is given to be the midpoint of the arc, angle COB is 20 degrees.  Due to the above assumption (all tiles are equal), OBF also is 20 degrees.  Thus, I establish that OC and BF are parallel.
From this point onwards, things seem pretty confusing to me.  I can find line length BC, and angle OCB using sine rule.  But, I'm interested in angle OCF, which is part of OCB.  Can anyone help with this?
NOTE: This question is based on an IGCSE math problem.
Comment: I just made an edit to the question.  The radius of the sector is given as 10 cm.
Answer: you did good on the first angle OCB is 20°
to find Length CE first find midpoint of OB Which is 5cm label it M then find length of CM
since you have Angle MOC as 20° and OCM As 20° and line OM as 5cm use the Sin A/ a= SinB/b formula to find line CM. After that find line EM use sine rule since you have angle ABO as 50° and line BM as 5cm after that subtract line CM from line EM to get CE
you can figure out the rest once you done the above part it becomes simple
Comment: How did you establish that midpoint M of OB will lie on CF too?  I mean, prove that these lines intersect at M?

Can an IGCSE problem be this complex?


X13 Arima with negative values

Question: I'm running x13 Arima analysis on a US GDP series to get the "trend" component.
<code>2008-12-31  -8.2
2009-03-31  -5.4
2009-06-30  -0.5
2009-09-30  1.3
2009-12-31  3.9
2010-03-31  1.7
2010-06-30  3.9
2010-09-30  2.7
2010-12-31  2.5
2011-03-31  -1.5
2011-06-30  2.9
2011-09-30  0.8
</code>
As you can see the data has negative values and when trying to run the model on the data it complains:

X13Error: WARNING: Automatic transformation selection cannot be done
  on a series with zero or negative values.

What is the right way to run X13 when you have negative values in your series?
(This question is related to https://stackoverflow.com/questions/38000059/statsmodels-x13error-warning-automatic-transformation-selection-cannot-be-do where I asked about the specific program settings. I asked this question first in Quantitative Finance beta, but was redirected to this community.)
Answer: I don't recall US GDP going negative per se, so I assume you are working with growth rates, which can indeed go negative (and do so during recessions, pretty much by definition).
ARIMA as such can deal with negative values, so this would not be a problem for plain ARIMA. The problem is that X13-ARIMA uses Box-Cox (and logistical) transformations, and these are simply not defined for negative values.
I have never heard of X13-ARIMA being used for growth rates (or differenced series, which would have the same problem). In my experience, it is always used on the original macroeconomic series, and these cannot go negative. If ARMA dynamics are only present in rates of change of the original series, X13-ARIMA will happily difference your series for you.
Comment: thanks Stephan, they are indeed growth rates, but shouldn't this work if one is able to specify the model as "additive" instead of "mutliplicative" (Not that I know how to do that here).
Comment: The problem is not a multiplicative model - it's the [Box-Cox transformation](https://en.wikipedia.org/wiki/Power_transform), as per your error message. Perhaps you can turn the automatic transformation off in the modeling software, which I'm not familiar with.

X13 Arima with negative values


Given multiple polynomial equations find a basis.

Question: I have read several other threads on Math.SE, including the similarly titled:
basis of the polynomial vector space
I've also checked out a video lecture on Youtube by njwildberger, but I simply have not found the right analogy to grasp what a polynomial space is. As such I am not understanding how to find a basis for it. I.e. if given 4 polynomial equations in P3, how does one find a basis?
$P_1 = x^2 + x - 2$
$P_2 = x^3 + 2x^2 + x + 2$
$P_3 = -x^3 - x^2 +2x$
I tried converting each polynomial to a column vector and then finding a basis for the column space, but I don't see that method used on the internet (in various sources). Somehow I think the basis should be reduced to {a0, a1, a2, a3} where each is the coefficient of a different degree of x.
Bonus marks if you can explain what it means (geometrically or visually) to be in the polynomial space of something. (If a function stretches from -inf on the y to +inf on the y, doesn't that mean everything is in the polynomial space?)
Answer: Write the coefficients of the elements as linear combination of the standard bases $\{1,x,x^2,x^3\}$ as rows in a matrix, then apply the elementary operations on the rows to get the matrix in row echelon form. Then you can read the rank of the matrix, which is equal to the number of independent elements in your set of polynomials. These elements correspond to the rows which are not zero in your final matrix. Let $Y$ be the set of independent elements in the given set. Then to extend $Y$ to a basis of $P_3(\mathbb{R})$ use the final matrix you got from elementary operations, delete the zero rows and add rows so that you make the rank $4$. Then add the correspondent elements of the added rows to Y. For example if you add the row $(0,0,0,1)$ to the matrix, then you should add the element $x^3$ to $Y$.
Answer: A slight modification to your problem (adding the $\color{gray}{gray \ polynomial}$ term) will make the example a bit easier.
Start with the monomial bases
$$
\mathcal{M} = \left\{ 1, x, x^{2}, x^{3} \right\},
$$
and the polynomial basis
$$
\mathcal{P} = \left\{
-2+x+x^{2}, 2+x+2x^{2}+x^{3}, -x^3 - x^2 + 2 x, \color{gray}{-1 + 2 x - 4 x^2 + 8 x^3}
\right\}
$$
How do we toggle between these bases?
Polynomial function to monomial function
The polynomial basis function $\mathcal{P}_{1}=-2+x+x^{2}$ has the state vector $\mathcal{P}_{1} = \left[ \begin{array}{cccc} 1 & 0 & 0 & 0 \end{array} \right]_{\mathcal{P}}^{T}$. In terms of the monomial basis, $\mathcal{P}_{1} = \left[ \begin{array}{cccc} -2 & 1 & 1 & 0 \end{array} \right]_{\mathcal{M}}^{T}$. That is
$$
\mathcal{P}_{1}(x) =
\left[ \begin{array}{r} -2 \\ 1 \\ 1 \\ 0 \end{array} \right]_{\mathcal{M}}
\cdot
\left[ \begin{array}{c} 1 \\ x \\ x^{2} \\ x^{3} \end{array} \right]
=-2+x+x^{2}
$$
The column vectors of the transformation basis $\mathcal{P}\to\mathcal{M}$ are the coordinates of the basis functions $\mathcal{P}$ in the monomial basis.
$$
\left[
\begin{array}{r|r|r|r}
 -2 & 2 & 0 & -1 \\
 1 & 1 & 2 & 2 \\
 1 & 2 & -1 & -4 \\
 0 & 1 & -1 & 8 \\
\end{array}
\right]_{\mathcal{P}\to\mathcal{M}}
%
\left[
\begin{array}{rrrr}
 1 \\
 0 \\
 0 \\
 0 \\
\end{array}
\right]_{\mathcal{P}}
=
\left[
\begin{array}{rrrr}
 -2 \\
  1 \\
  1 \\
  0 \\
\end{array}
\right]_{\mathcal{M}}
$$
Monomial function to polynomial function
The reverse mapping is handled by the inverse of the transformation matrix. The example shows how the constant term in the monomial basis $\mathcal{M}_{1} = \left[ \begin{array}{cccc} 1 & 0 & 0 & 0 \end{array} \right]_{\mathcal{M}}^{T}$ is mapped to the linear combination $\frac{1}{85} \left[ \begin{array}{cccc} -27 & 15 & 7 & -1 \end{array} \right]_{\mathcal{P}}^{T}$.
$$
\frac{1}{170}
\left[
\begin{array}{rrrr}
 -54 & 23 & 39 & 7 \\
 30 & 25 & 35 & 15 \\
 14 & 57 & -29 & -27 \\
 -2 & 4 & -8 & 16 \\
\end{array}
\right]_{\mathcal{M}\to\mathcal{P}}
%
\left[
\begin{array}{rrrr}
 1 \\
 0 \\
 0 \\
 0 \\
\end{array}
\right]_{\mathcal{M}}
=
\frac{1}{85}
\left[
\begin{array}{rrrr}
 -27 \\
  15 \\
   7 \\
  -1
\end{array}
\right]_{\mathcal{P}}
$$
Explicitly,
$$
\begin{align}
1 &= \frac{1}{85}
\left[
\begin{array}{rrrr}
 -27 \\
  15 \\
   7 \\
  -1
\end{array}
\right]_{\mathcal{P}}
%
\cdot
%
\left[
\begin{array}{rrrr}
  \mathcal{P}_{1}(x) \\
  \mathcal{P}_{2}(x) \\
  \mathcal{P}_{3}(x) \\
  \mathcal{P}_{4}(x)
\end{array}
\right] \\[3pt]
%
&=
-\frac{27}{85} \mathcal{P}_{1}(x)
+\frac{3}{17}  \mathcal{P}_{2}(x)
+\frac{7}{85}  \mathcal{P}_{3}(x)
-\frac{1}{85}  \mathcal{P}_{4}(x)
%
\end{align}
$$


Form hook not found through module_hook_info in module subdirectory

Question: Context:
In my Drupal 7 project, I have a module with several submodules. Because the module's root directory got crowded, I moved the submodule files to their own directories within the root.
My module's structure is like this:
mymodule
├── mymodule.info
├── mymodule.module
├── mymodule1
│   ├── mymodule1.block.inc
│   ├── mymodule1.form.inc
│   ├── mymodule1.info
│   ├── mymodule1.module
│   ├── mymodule1.page.inc
│   └── pages
│       └── foo.tpl.php
└── mymodule2
    ├── classes
    │   └── foo
    │       └── Bar.php
    ├── mymodule2.form.inc
    ├── mymodule2.info
    ├── mymodule2.install
    ├── mymodule2.module
    ├── mymodule2.page.inc
    └── pages
        ├── foo.tpl.php
        └── bar.tpl.php

Before "the big move", files that are now in the subdirectories mymodule1 and mymodule2, were located in their parent directory (the module's root directory).

The problem:
Ever since moving the files, my custom forms are not loading anymore. I have a form in mymodule1.form.inc, which used to load and render perfectly before. Now, when I use drupal_get_form() to load the form, I only get an empty form with a hidden build ID input.
Keep in the mind that the only thing that has changed here, is that the .inc files have been moved to the subdirectory, along with the module file. Also, drupal_get_path('module', 'mymodule1') returns the correct path to the module in the subdirectory.
Strangely, there are also block hooks, located in mymodule1.block.inc, which work perfectly fine, even after clearing all caches.
This is the first time I'm working with separate directories per submodule within a module. I got the inspiration from the module i18n, which uses the same construction. I searched in the Drupal documentation and the code of i18n, but could not find where I'm going wrong.
Does anyone know where I could possibly have gone wrong, or if I need to add data to mymodule1.module or mymodule1.info to make this work? Thank you.

Some details:
Caches were cleared through <path to project>/admin_menu/flush-cache multiple times.
I use module1_hook_info() to direct the hooks for blocks and forms to separate files. This is the return value:
array (size=9)
  'block_info' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_configure' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_save' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'block_view' =>
    array (size=1)
      'group' => string 'block' (length=5)
  'forms' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_validate' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_submit' =>
    array (size=1)
      'group' => string 'form' (length=4)
  'form_alter' =>
    array (size=1)
      'group' => string 'form' (length=4)

My form functions are called:

mymodule1_foobar_form
mymodule1_foobar_form_validate
mymodule1_foobar_form_submit
Comment: Have you updated the code that includes `mymodule1.form.inc` to include the new path?
Comment: @Clive I'm not including this file anywhere, since it worked without include before (and I didn't see similar includes in other modules) in neither .module or .info. Do you mean a `require_once`, `module_load_include()`? I got the impression that `require_once` is bad practice.
Comment: I mean `module_load_include()` - I reckon your original code worked because of an unintended side effect, more details in the answer
Answer: Thanks to Clive I found module_load_include(), which is used to load files when working with a form. I moved hook_forms() back to my main module's file and now load the mymodule1.form.inc through there, like so:
/**
 * Implements hook_forms().
 */
function mymodule1_forms($form_id, $args)
{
    module_load_include('inc', 'mymodule1', 'mymodule1.form');
    $forms = array();

    $forms['mymodule1_foo_form'] = array(
        'callback' => 'mymodule1_foo_form',
    );

    return $forms;
}

Now all my forms are loading correctly (again), over both mymodule1 and mymodule2.
The one thing I'm not sure about, that whether this could have been achieved without redundantly declaring the form callbacks to their same-named form IDs.
Answer: I'm going to take a stab at what happened here, I might be wrong.
hook_form() isn't a normal hook, it's only invoked for modules that define node types (you haven't indicated any of yours do). It isn't invoked when you arbitrarily invoke drupal_get_form(). Same goes for hook_form_validate() and hook_form_submit().
Some of the hooks in your hook_hook_info() implementation are called for all modules, though. e.g. hook_forms() and hook_form_alter().
I would surmise that mymodule contained an implementation of hook_form_alter() or hook_forms(), which was coincidentally invoked on the same page(s) as the forms that you've now moved to mymodule1 were displayed. Those hooks being invoked implicitly result in mymodule.form.inc being included, and the functions were available.
Now that you've moved the code into mymodule1, I'm guessing you haven't implemented either of the hooks that would have resulted in that coincidental behaviour. So Drupal now can't find your form function, and fails silently.
To fix, include the file manually:
module_include('inc', 'mymodule1', 'mymodule1.form');

Comment: It wouldn't - `files[]` is for autoloading classes
Comment: `mymodule` contains no code other than a theme registry function. The form hooks have been always been part of `mymodule1`. Before moving the files, the form was displayed. I do have an identical hook_info in `mymodule2`, which also has its own forms (which are also not loading now).
Comment: I put `module_load_include('inc', 'mymodule1', 'mymodule1.form');` on top of `mymodule1.module` and cleared my cache. This made no difference for me.
Comment: Worth a shot I guess, I don't know the answer then. I do know that using `hook_hook_info()` won't work to auto-include `MODULE.form.inc`, though, as you can see from the explanation about `hook_form()`, so I guess the quirk is elsewhere
Comment: I've tried including the file through `module1.info` (using `files[]`), but this did not make any difference either.


puppet propagate variable from node to erb template?

Question: Is it possible to declare variable in node and than propage it way down to the erb template?
Example:
node basenode {
  $myvar = "bar" # default
  include myclass
}

node mynode extends basenode {
  $myvar = "foo"
}

class myclass {
  file { "/root/myfile":
    content => template("myclass/mytemplate.erb")
    ensure  => present,
  }
}

Source of mytemplate.erb:
myvar has value: <%= myvar %>

I know that my example might be complicated. But I'm trying to propagate file on (almost) all my nodes and I want its content to be altered depending on the node which requests the file. The $myvar = "bar" statement should be default when node does not override its value.
Is there a solution to my problem? I'm using puppet 0.24.5
Edit: The problem here is probably variable inheritance order. This $myvar variable won't have foo value in mynode node. The solution here would be to include myclass directly in mynode. But I really don't want to do that.
Is there an option to override class variable value after the class has been included?
Comment: Darn: http://email@example.com/2010-06/msg00666.html Seems like this approach will never work ...
Comment: More precisely: http://docs.puppetlabs.com/guides/troubleshooting.html#common-misconceptions
Comment: That's kind of what I assumed was happening. Too bad, the idea of node inheritance is neat.
Answer: Puppet node inheritance is not the same as inheritance in most other programming languages . Included classes are evaluated immediatelly when the child is evaluated. And the parent node is evaluated after that. Therefore my example will never work. If you want to know recommended solution for this, read puppet - common misconceptions. I did it this way and it works.
Although I have to admit that I'm pretty disappointed right now, because complex puppet syntax might be confusing for starters.
Comment: I'm being pedantic, but declarative languages like Puppet's DSL are programming languages every bit as much as procedural programming languages (which is what you probably meant) like C.
Comment: Changed my statement so it does not sound like I don't accept puppet language as programming langugage :)
Answer: Other answers have already pointed out the scoping problem. What you probably want to do is use the base node only for variable definitions, and separate out the actual logic (including your base class definitions) into a separate class that's included by all of your nodes. This preserves the scoping the way that you want, and only adds a single extra line to all of your node definitions.
node basenode {
  $myvar = "bar" # default
}

node mynode extends basenode {
  $myvar = "foo"
  include baseclass
}

class baseclass {
  include myclass
}

class myclass {
  file { "/root/myfile":
    content => template("myclass/mytemplate.erb"),
    ensure  => present
  }
}

Answer: Instead of declaring the default value within basenode, I would declare the default within the template itself.  Since ERB
is largely based on ruby, you can get away with some fairly extensive logic.  Here is an example from the template I use
for managing the snort config file.
var DNS_SERVERS <% if has_variable?("dns_servers") then %>[<%= dns_servers.flatten.join(',') %>]<% else %>$HOME_NET<% end %>

In this case I am using an array that, if it exists, gets turned into a comma separated list for inclusion.  Otherwise the default $HOME_NET
gets used.  If we simplify it to your example we could use:
myvar has value <% if has_variable?("myvar") %><% then %><%= myvar %><% else %>bar<% end %>

Again, if the variable myvar has been set then that will be expanded, otherwise the string "bar" will be printed. This way the variable myvar can be set, or not, in your node definitions with impunity.
Comment: This is probably a good point. But my main point here is that I'm not able to use variables from node definition within erb templates (which are used inside classes). Is there something bad in my example? My real situation is much more complicated than this, but I think that main point is here. Are there any limits of the scope in which the variable will be propagated?
Comment: Ah, sorry, I didn't realize you meant that you tried it, but didn't work. I am doing exactly what you are, and it works fine. It could be that your ERB syntax is wonky, or you've run into an ordering problem. I'll have to do some more testing.


Load balancing in Tomcat in 64-bit OS

Question: Sorry about double post. Actually I want to move my question on StackOverflow to ServerFault but it seems like I can't do it. Below is my question:
I have a web application and required load balancing in Tomcat. My hardware spec is 5 unit of 32 GB RAM quad-core processors 64 bit OS.
Should I have

5 Tomcats, one in each machine with
-Xmx around 30GB and higher maxThreads
A bigger number of Tomcats with
lower -Xmx, e.g. 25 Tomcats, 5 in
each machine with -Xmx around 6GB
and default maxThreads

I have load balancer using mod_proxy_balancer before Tomcats. Let assume there is no bottle neck at database layer to simplify the situation.
For suggestion #1, the author for http://www.theserverside.com/news/1363681/Scaling-Your-Java-EE-Applications said 12GB max ram cause high pause time during gc and recommend to use only 3GB. He did not share his gc setting so I am not sure can it be fine-tuned further.
Let me know if you need more info.
Thanks.
Answer: All other things being equal, a larger heap size in your JVM will only defer the cost of reference issues created by the container and/or your code. Your pauses may take longer to manifest, but when they arrive they will almost certainly stop the world for a (much) longer time.
So long as you are load-balancing in this manner, I generally prefer to bind each Tomcat instance to a subset of processors, measure the heap demand of my applications in testing, then allow for some kind of headroom. Better to monitor and manage your memory demand on an ongoing than try to factor it out with the maximum possible space.

Load balancing in Tomcat in 64-bit OS


Dual space of vector space

Question: I am trying to prove the following theorem and I am getting stuck. Please take a look at this theorem what I have try so far.
Theorem: Let $V$ be a finite dimensional vector space over field F. Prove there is a ring isomorphism of $End(V)$ to $End(V^{*})$, where $End(V)$ denotes the linear transformation of $V$ to itself and $V^{*}$ is the dual space of $V$, i.e $V^{*}= Hom(V, F)$.
Proof:
Define the map $\Phi$: $End(V)$ $\to$ $End(V^{*})$ : $\Phi (\varphi) (f)= f \circ \varphi$ where $\varphi$ is an element of $End(V)$ and $f$ is an element of $V^{*}$.
Let $\varphi _1$ and $\varphi_2$ in $End(V)$
-Addition preserving :$\Phi (\varphi_1 + \varphi_1) (f)=f \circ (\varphi_1 + \varphi_2)= f \circ \varphi_1 + f \circ \varphi_2= \Phi (\varphi_1) (f) + \Phi (\varphi_2) (f)$.
-Multiplication preserving: $\Phi (\varphi_1 \varphi_2) (f)=f \circ (\varphi_1 \varphi_2)= f \circ \varphi_1 \circ \varphi_2 = f \circ (\varphi_1 \circ \varphi_2)= \Phi(\varphi_1 \varphi_2(f))$.
-Unit preserving: $\Phi(i)(f)= f \circ i =f$ $\Rightarrow$ $\Phi(i)$ is the identity in $End(V^{*})$.
-Injectivity: $\Phi(\varphi)=0 \Rightarrow f \circ \varphi =0$ for all $f \in End(V^{*}) \Rightarrow \varphi =0$. Hence $ker \Phi =0 \Rightarrow \Phi$ is injective.
This is what I have tried so far, I can not prove $\Phi$ is subjective. Can anybody give me the solutions for this ? Altarnative proof is also very helpful for me.
Thanks in advance!
Comment: When you proof your statement End$(V) \simeq F$ you say that $\Gamma(g(1)) = g$. But what is $g(1)$? $g$ is a map on $V$ and we don't necessarily have an element $1$ in the vector space $V$. You don't even need that statement for your proof.
For the surjectivity of $\Phi$ you could use a dimension argument, namely that dim$(V)=$ dim$(V^*)$.
Comment: @Lukas You are right. I made a mistake, let me fix it.
Comment: @Lukas By the way, is $End(V) \cong F$ in general ?
Comment: As vector spaces this is definitely not true, because dim$(F)=1$ and dim$(\text{End}(V)) = (\text{dim}(V))^2$ which will not be the same if dim$(V)>1$. I also think that they are not isomorphic as rings. But I am not 100% sure about that.
Answer: Question: "Theorem: Let V be a finite dimensional vector space over field F. Prove there is a ring isomorphism of End(V) to End(V∗), where End(V) denotes the linear transformation of V to itself and V∗ is the dual space of V, i.e V∗=Hom(V,F)."
Answer: If $dim(V):=n$ and $V:=k\{e_1,..,e_n\}$ with $V^*:=k\{x_1,..,x_n\}$
with $x_i:=e_i^*$ the dual basis you get an isomorphism
$$\phi: V^*\otimes_k V \cong End_k(V)$$
defined by $\phi(x_i\otimes e_j)(u):=x_i(u)e_j$. This map sends the element $z:=\sum_i x_i \otimes e_i$ to the identity endomorphism $Id_V\in End_k(V)$.
Hence you may use the ring structure on $End_k(V)$ to construct an associative product on $V^*\otimes_k V$:
$$f_1  \otimes v_1 \bullet f_2 \otimes v_2:=f_2 \otimes f_1(v_2)v_1.$$
With this definition it follows $V^*\otimes_k V$ is an associative unital $k$-algebra with the element $z$ as a multiplicative unit, inducing an isomorphism
$$V^*\otimes_k V\cong End_k(V)$$
of associative $k$-algebras.
It follows there are canonical isomorphisms (of vector spaces)
$$\rho: End_k(V) \cong V^*\otimes_k V \cong V\otimes_k V^* \cong V^{**}\otimes_k V^* \cong End_k(V^*).$$
You must check if this isomorphism is a ring isomorphism. It could be (since the rings are non-commutative) you must change the order of the product:
If $f_i\otimes v_i \in V^*\otimes V$ you get
$$f_1\otimes v_1 \bullet f_2 \otimes v_2:= f_2\otimes f_1(v_2)v_1$$
and
$$\rho(f_1\otimes v_1 \bullet f_2 \otimes v_2)= f_1(v_2) v_1 \otimes f_2 \in V\otimes V^*.$$
You moreover get
$$\rho(f_1\otimes v_1)\bullet \rho(f_2\otimes v_2)=v_2 \otimes f_2(v_1)f_1.$$
You also get
$$\rho(f_2\otimes v_2) \bullet \rho(f_1 \otimes v_1):= v_1\otimes f_1(v_2)f_2= \rho(f_1\otimes v_1 \bullet f_2 \otimes v_2).$$
Hence it seems the canonical map "switches" the order of the multiplication, giving a canonical isomorphism of rings
$$End_k(V) \cong End_k(V^*)^{op}$$
Answer: You almost done with that last attempt, but let me make some observations about your solution:

Finish the addition-preserving argument: since you already prove that $$\Phi(\varphi_1+\varphi_2)(f) = \Phi(\varphi_1)(f) + \Phi(\varphi_2)(f)$$ holds for every $f \in V^*$, and $\Phi(\varphi_1)(f) + \Phi(\varphi_2)(f)$ is the map $\Phi(\varphi_1)+\Phi(\varphi_2)$ evaluated at $f$, it follows that $\Phi(\varphi_1+\varphi_2)$ and $\Phi(\varphi_1)+\Phi(\varphi_2)$ coincide at every point, meaning that they are equal.
What is $\Phi(\varphi_1\varphi_2(f))$? To start, $\Phi$ is not multiplication preserving: since for any $f \in V^*$ we have $$\begin{align} \Phi(\varphi_1 \circ \varphi_2)(f) &= f \circ (\varphi_1 \circ \varphi_2) \\ &= (f \circ \varphi_1) \circ \varphi_2 \\ &= \Phi(\varphi_2)(f \circ \varphi_1) \\ &= \Phi(\varphi_2)(\Phi(\varphi_1)(f)) =
\big( \Phi(\varphi_2) \circ \Phi(\varphi_1) \big)(f) \end{align}$$ it follows that $\Phi(\varphi_1 \circ \varphi_2) = \Phi(\varphi_2) \circ \Phi(\varphi_1)$. So, what you are defining here is a ring homomorphism $\Phi: \operatorname{End}(V)^{\rm op} \to \operatorname{End}(V^*)$, that is, a ring anti-homomorphism $\Phi: \operatorname{End}(V) \to \operatorname{End}(V^*)$.
It would be nice if you write that $i$ is the identity map in $V$, and by the way, $\Phi(i)$ is not the identity map in $\operatorname{End}(V^*)$, it is the identity map in $V^*$ because $\Phi(i)(f) = f$ for every $f \in V^*$.
If you already know $\bigcap_{f \in V^*} \ker f = 0$ (why the injectivity of $\Phi$ follows from this?), then the injectivity argument is fine, except that it should be "for all $f \in V^*$" instead of "for all $f \in \operatorname{End}(V^*)$".

Also:

In finite dimensions, any injective linear map between two vector spaces of the same dimension is an isomorphism, so, it is enough to show that $\Phi$ is also a linear map, since $$\dim V = \dim V^* \implies \dim \operatorname{End}(V) = (\dim V)^2 = (\dim V^*)^2 = \dim \operatorname{End}(V^*).$$
No, in general, $\operatorname{End}(V)$ and $F$ are not isomorphic. What is true is that $\operatorname{Hom}(F,V) \cong V$ via $\varphi \mapsto \varphi(1)$. I think this is the reason about your confusion.
Comment: Thank you for a great answer !

Dual space of vector space


How to prove $\log n \leq \sqrt n$ over natural numbers?

Question: It seems like $$\log n \leq \sqrt n \quad \forall n \in \mathbb{N} .$$ I've tried to prove this by induction where I use $$ \log p + \log q \leq \sqrt p \sqrt q $$ when $n=pq$, but this fails for prime numbers. Does anyone know a proof?
Comment: What are you "allowed" to use? (Actually, how are you defining $\log$? I assume you mean the natural log there, and a usual definition is as $\log x = \int_1^x \frac{1}{y} \mathrm{d}y$, so some calculus is used.)
Comment: Does it suffice to note that $f(x)=\log x - \sqrt{x}$ satisfies $f'(x)\leq 0$ for $x\geq 4$ and note that the inequality is satisfied for $n=1,2,3,4$?
Answer: Consider the function $f(x)=\log x-\sqrt{x}$. Then $f'(x)=(1-(1/2)\sqrt{x})/x$, and you can easily see this is negative when $x\geq 4$. So this means that if $f(1),f(2),f(3)<0$ and $f(4)<0$, then so is $f(n)$ for all $n>4$. But it's easy to verify that $f(1),f(2),f(3),f(4)<0$, so you're done.
Comment: You need to special case $x=1$ since $f'(x)>0$ for $1\sqrt{2}$, $f'(x)<0$, and your argument works for x\ge2.
Comment: @robjohn, thanks. I rushed my answer since others were being published as I was writing.
Comment: I, too, was being sloppy. $1-(1/2)\sqrt{x}\;\begin{array}{c}<\\=\\>\end{array}\;0$ when $x\;\begin{array}{c}>\\=\\<\end{array}\;4$
Comment: @robjohn: :) Ha. That's too funny. I will correct.
Answer: I would use calculus to show $\sqrt{x} - \log x$ is increasing, together with the observation that $\sqrt{1}-\log 1 > 0$.
Comment: I was typing up that proof right when you posted this. :)
Answer: Here is a proof of a somewhat weaker inequality that does not use calculus:
Put $m:=\lceil\sqrt{n}\>\rceil$. The set $\{2^0,2^1,\ldots,2^{m-1}\}$ is a subset of the set $\{1,2,\ldots,2^{m-1}\}$; therefore we have the inequality $m\leq 2^{m-1}$ for all $m\geq1$. It follows that
$$\log n=2\log\sqrt{n}\leq 2\log m\leq 2(m-1)\log2\leq 2\log2\>\sqrt{n}\ ,$$
where $2\log2\doteq1.386$.
Answer: That's the same as $n \le e^{\sqrt n}$ or $n^2 \le e^n$.
If we allow the power series for $e^x$,
$e^n > n^3/6$ so $e^n > n^2$ for $n \ge 6$.
If we don't allow the power series, we can instead prove by induction that
$n^2 < 2^n$ (which, of course, is better) for $n \ge 5$:
True for $n = 5$; if true for $n \ge 5$,
$$\frac{(n+1)^2}{2^{n+1}} = \frac{n^2}{2^n}\frac{(1+1/n)^2}{2} \le (6/5)^2/2 = 36/50 < 1.$$
Comment: I am substituting $n^2$ for $n$, not squaring each side. Upon thinking about this, we have to consider what happens between $n^2$ and $(n+1)^2$, but that takes a little more work.
Comment: $\bigl(e^{\sqrt{n}}\bigr)^2=e^{2\sqrt{n}}$.
Answer: Bigger by a Factor
Using $e^x\ge1+x$, and substituting $e^x=\sqrt{u}$ and $e^2u=n$, we get
$$
\begin{align}
e^x\ge1+x
&\implies\sqrt{u}\ge1+\frac12\log(u)=\frac12\log(e^2u)\\
&\implies\frac2e\sqrt{n}\ge\log(n)
\end{align}
$$
which is stronger than $\sqrt{n}\ge\log(n)$.

Bigger by an Offset
we could also set $4u=n$, which gives
$$
\sqrt{u}\ge1+\frac12\log(u)
\implies\sqrt{n}\ge2(1-\log(2))+\log(n)
$$
which is also stronger than $\sqrt{n}\ge\log(n)$.
Answer: Here's a different way to look at this problem. Let $f, g : \mathbb{R} \rightrightarrows \mathbb{R}$ be functions such that

$f$ is monotonically increasing.
$f(x) > g(x)$ for all $x$.

I claim that this implies $f^{-1}(x) < g^{-1}(x)$ for all $x$.
Proof: Suppose toward a contradiction that there is some $x \in \mathbb{R}$ such that $f^{-1}(x) \geq g^{-1}(x)$. By (1), we have
$$
\tag{*}
x = f(f^{-1}(x)) \geq f(g^{-1}(x)).
$$
And by (2), we have
$$
\tag{**}
f(g^{-1}(x)) > g(g^{-1}(x)) = x.
$$
Combining (*) and (**), we get that $x > x$, which is a contradiction.

Applying this fact to $e^x$ and $x^2$, we can show that

$e^x$ is monotonically increasing.
$e^x > x^2$ for all $x$.

This would imply that $\ln x < \sqrt x$ for all $x$. These statements should be simpler to prove. At the very least, it's more intuitive (in my opinion) than working with $\ln x$ and $\sqrt x$.


Generalized Mechanism Design, Stanley Reiter diagram and Vickrey Auction

Question: I am trying to learn this new topic, Mechanism Design and stumbled upon the "Stanley Reiter" diagram (see the top-right side on the page).
I have also learned that the Second Price Sealed Bid auction (or Vickrey Auction) implements such design. My question is, in the case for Vickrey acution, how do we interpret the $\Theta$, $\theta$, $f(\theta)$, $X$, $\xi(\cdot)$, $M$ and $g$? Please also note that I am a total noob (Econ/Math is not my major).
What I understood --

$\Theta$: All possible valuation values in a particular bidding.
$\theta$: Bidders' true valuation
$M$: Agents' report, that can distort $\theta$. if so, then why we don't say like $M = \phi(\theta)$? where $\phi(\cdot)$ distorts $\theta$?

Now, how do we interpret $f(\cdot) \in X$, $\xi(\cdot)$ and $g$? Strictly in terms of Vickrey auction?
Answer: I will answer as informally as possible. What you want to achieve with the auction is allocate a good (say, a painting) to one of $n$ bidders.
In auctions (or economics more generally) we are interested in efficient allocations. This basically means you want to give the painting to the guy who values it the most. The valuation of the good for bidder $i$ is denoted by $\theta_i$ (this is his actual valuation), but since only the bidder himself knows his valuation of the painting, all we (as auctioneers) know is the range of possible values for $\theta_i$, which is $\Theta_i$ as you correctly stated. Since we have many bidders, all possible combinations of $\theta$ are $\Theta=\Theta_1\times \Theta_2\times\ldots\times\Theta_n$, while the vector of actual valuations is $\theta=(\theta_1,\theta_2,\ldots)$.
Now the $f(\theta)$ function basically is a rule that tells you who of the $n$ bidders receives the painting, depending on their valuations. That is, $x$ could be a vector $(1,0,0,0\ldots)$, which indicates that the first bidder receives the painting (1), and the others don't (0). This was the two upper squares in the diagram and their connecting line.
The problem is that we don't know the actual $\theta_i$'s of the $n$ bidders, and if you ask "Who has the highest valuation?" ("Who wants the painting?") then everybody shouts "ME!". In other words, these bidders may lie about their valuations. This is why we bother with the auction: lying here means you might have to pay more, thus discouraging lying. The auction specifies rules (who can bid, when, who receives the painting in the end..). The bids are the messages $M$ in the diagram - they communicate your willingness to pay (valuation). The auction rules are $g$ - they specify who, as a function of all bids, receives the painting (the highest bidder), and what he has to pay for it.
$\xi(M,g,\theta)$ now means that, given the auction rules $g$, the valuations of all bidders $\theta$ and the bids $M$ of all bidders, the auction outcome (Bayesian Nash equilibrium) is as if we asked "Who has the highest valuation?", and everybody answered truthfully. That is, in the auction outcome we learn $\theta$ through the bids, because lying in the auction means you bid more than what your valuation is, but this implies you might have to pay more than you are willing to pay --- hence you don't do it. Consequently, the auction with its rules implements the allocation $x$ that $f(\theta)$ would have implemented ($f(\theta)=x$) if everybody could have been relied upon not to lie.
In short, the auction is the mechanism that extracts $\theta_i$ from all bidders and allows us to implement the social choice $f(\theta$). Without the auction, that may not work because bidders may lie about $\theta_i$. With the auction, it may work, because overstating one's true valuation is discouraged, since it may imply higher payments if you are allocated the good. [You cannot just specify some $\phi(\theta_i)$, because you have no idea how they are going to lie as a function of their valuation (double the true valuation, three times the true valuation?). Granted, if you knew how they lied, you could infer the true $\theta_i$ from their lies, but then bidders would anticipate this and lie differently. The only situation where this works is if bidders have no incentive to lie differently once you use some function $\phi(\theta_i)$ to infer $\theta_i$. This would be an equilibrium, and $\phi$ would be the equilibrium bid strategy, and so here we see why the auction helps to reveal the true $\theta_i$ for all bidders.]
Comment: VCG actually implements more than Bayesian Nash.
Comment: Yes, VCG is a specific mechanism that has a pure strategy equilibrium in dominant strategies. But mechanism design more generally is not confined to a specific equilibrium concept. The introduction in Mas-Colell, Whinston, Greene (1995) for example, says that a mechanism implements a social choice function if the mechanism has *some* equilibrium, where the outcome is that of the social choice function.


Determine if the following ideals are prime.

Question:
Determine if the following ideals are prime.

$I=\langle x^2+2\rangle\subseteq \mathbb{Z}[x]$
$I=\langle x^2+2\rangle\subseteq \mathbb{Z}_3[x].$

By the definition, a proper ideal $I$ of $R$ is prime if whenever $a,b\in R$ such that $ab\in I,$ then either $a\in I$ or $b\in I.$
1) I know $I$ is a proper subset of $\mathbb{Z}[x]$ as $1\in \mathbb{Z}[x]$ but $1\not\in I.$ But I can't find values $a,b\in \mathbb{Z}[x]$ such that if $ab\in I,$ then $a\in I$ or $b\in I.$ Is this one prime?
2) Is this not prime? I'm having a hard time thinking of an example. How is $x^2+2$ even factorable?
Answer: We claim that $I=\langle x^2+2\rangle\subseteq \mathbb{Z}[x]$ is prime. Suppose $a,b\in\mathbb{Z}[x]$ such that $ab\in I.$ Then $ab = r(x^2+2), r\in\mathbb{Z}[x].$ We have $\deg (ab) \geq 2$ or $ab=0\Rightarrow 0=a\in I\vee 0=b\in I,$ so we just need to consider when $\deg(ab)\geq 2.$ We show that $x^2+2$ is irreducible in $\mathbb{Z}[x].$ Suppose $\exists a,b\in\mathbb{Z}[x]$ such that $ab = x^2+2$ and $a$ and $b$ are not units of $\mathbb{Z}[x].$ Note that since $ab\neq 0, 0<\deg(a),\deg(b)<2.$ Then since the leading coefficient is $1,$ $a=x+c$ and $b=x+d,$ where $c,d\in\mathbb{Z}.$ But then, $ab=(x+c)(x+d)=x^2+(c+d)x+cd.$ This means $c+d=0\Rightarrow c=-d$ and $cd = 2\Rightarrow -d^2=2.$ The latter equation is unsolvable in $\mathbb{Z}[x];$ hence either $a$ or $b$ are units of $\mathbb{Z}[x]$. Thus, since $x^2+2$ is irreducible, either $a$ or $b$ is a multiple of $x^2+2.$ Thus $a\in I$ or $b\in I.$
We claim that $I=\langle x^2+2\rangle\subseteq \mathbb{Z}_3[x]$ is not prime. Consider $x+2,x+1\in \mathbb{Z}[x].$ We have $(x+2)(x+1)=x^2+2\in\mathbb{Z}_3[x],$ but $x+1,x+2\not\in I.$ Thus, this ideal is not prime.


Should I manually upload these large files?

Question: I have about 10 large zip files (20Mb) which need to be uploaded to a site once, and once only.  I then want to be able to download them from a block in a sidebar (i.e. not from the main content).
I was thinking that the easiest way to do this would be manually upload them to the site (via ftp), then hardcode links in the blocks to reference the file location.  Does this sound OK?  Does it violate any drupal rules?
The reasons I wanted to do it this way, rather than through the file UI or another module, are that I don't have to worry about the php.ini upload_max_filesize and post_max_size.  Also, I won't have to work out how to use the drupal UI to put a link in a block.
What do you think?
Answer: Manually uploading the files and hardcoding the links into a block, Shouldnt be a problem.
You Could also check this module out :) Download File Module
Comment: I agree with Vic, seems to upload the files manually would be appropriate in this situation.


How did Feynman do this approximation $\sqrt{A^2 + \mu^2\varepsilon^2} =A\biggl( 1+\frac{1}{2}\,\frac{\mu^2\varepsilon ^2}{A^2}\biggr)$?

Question: I was reading the 9th lecture of Feynman; here is the excerpt of my concern:

Let's go back now to our particular example of the ammonia molecule in an electric field. Using the values for H11, H22, and H12 given in (9.14) and (9.15), we get for the energies of the two stationary states
  $$E_{I}=E_0+\sqrt{A^2+\mu^2 \varepsilon^2},\quad
E_{II}=E_0-\sqrt{A^2+\mu^2\varepsilon^2} \tag{9.30}$$
  [...] When the electric field is zero, the two energies are, of course, just $E_0±A.$ When an electric field is applied, the splitting between the two levels increases. The splitting increases at first slowly with $E$, but eventually becomes proportional to $E$. (The curve is a hyperbola.) For enormously strong fields, the energies are just
  $$E_I=E_0+μ\varepsilon =H_{11}\;,\;E_{II}=E_0−μ\varepsilon=H_{22}.$$
[...]How can we separate the two molecular states? One method is as follows. The ammonia gas is let out of a little jet and passed through a pair of slits to give a narrow beam.The beam is then sent through a region in which there is a large transverse electric field. The electrodes to produce the field are shaped so that the electric field varies rapidly across the beam. Then the square of the electric field $\mathbf{\varepsilon}\cdot \mathbf{\varepsilon}$ will have a large gradient perpendicular to the beam. Now a molecule in state $|I⟩$ has an energy which increases with $\varepsilon^2$, and therefore this part of the beam will be deflected toward the region of lower $\varepsilon^2.$ A molecule in state $|II⟩$ will, on the other hand, be deflected toward the region of larger $\varepsilon^2$, since its energy decreases as $\varepsilon^2$ increases.
Incidentally, with the electric fields which can be generated in the laboratory, the energy $\varepsilon$ is always much smaller than $A.$ In such cases, the square root in Eqs. (9.30) can be approximated by $$A\biggl(
1+\frac{1}{2}\,\frac{\mu^2\varepsilon ^2}{A^2}
\biggr). \tag{9.32}$$ So the energy levels are, for all practical purposes, $$E_{I} =E_0+A+\frac{\mu^2\varepsilon^2}{2A} \; \\ \& \\ E_{II} =E_0-A-\frac{\mu^2\varepsilon^2}{2A}$$

I'm not understanding how Feynman made the square-root term of $(9.30)$ that is, $\sqrt{A^2 + \mu^2\varepsilon^2}$ equal to $(9.32)$ that is, $A\biggl(
1+\dfrac{1}{2}\,\dfrac{\mu^2\varepsilon ^2}{A^2}\biggr)$ ? How did he make the approximation?
Comment: In general, $(1+x)^a\simeq1+ax$ for small values of *x*. See [binomial series](https://en.wikipedia.org/wiki/Binomial_series).
Comment: It's the first two terms of the Taylor expansion. He approximates the square root by these first two terms, since $\mu \epsilon / A$ is small. See the series expansion here: wolframalpha.com/input/?i=series+sqrt%281%2Bx^2%29
Answer: Since for positive $x$ we have $\left(1+\frac{x}{2}\right)^2>1+x$, it follows that $\sqrt{1+x}<1+\frac{x}{2}$.
On the other hand,
$$ 1+\frac{x}{2}-\sqrt{1+x} = \frac{\frac{x^2}{4}}{1+\frac{x}{2}+\sqrt{1+x}} < \frac{x^2}{8\sqrt{1+x}}$$
hence for small $x$ we have that $1+\frac{x}{2}$ is an excellent approximation for $\sqrt{1+x}$, and obviously:
$$ \sqrt{A^2+\mu^2\varepsilon^2} = A\cdot \sqrt{1+\frac{\mu^2\varepsilon^2}{A^2}}\approx A+\frac{\mu^2 \varepsilon^2}{2A^2} $$
if $A^2$ is large compared to $\mu^2\varepsilon^2$.
Answer: Since $A > 0$,
$$\sqrt{A^2 + \mu^2 \epsilon^2} = A \sqrt{1 + \frac{\mu^2 \epsilon^2}{A^2}}.$$
Then use the linear approximation to $\sqrt{x}$ near $1$:
$$\sqrt{x} \approx 1 + \frac{1}{2} (x - 1),$$
when $x$ is close to $1$.  (This comes from calculus; one of the most important reasons why the subject is so useful is the ability to use it to approximate functions.)
Here, you must assume that $\mu \epsilon$ is considerably smaller than $A$, so that $x = 1 + \frac{\mu^2 \epsilon^2}{A^2}$ is close to $1$. Then the approximation follows.
Answer: There is an extension of the binomial theorem that applies to a binomial
raised to a non-integer power. As is mentioned in another question, the formula is
$$(a+x)^n = a^n + na^{n-1}x + \frac{n(n-1)}{2!}a^{n-2}x^2
 + \frac{n(n-1)(n-2)}{3!}a^{n-3}x^3
 + \ldots .$$
Setting $n = \frac12$, we get
\begin{align}
\sqrt{a+x}
 = (a+x)^{1/2} &= a^{1/2} + \frac12 a^{-1/2}x + \frac{\frac12(-\frac12)}{2!}a^{-3/2}x^2  + \ldots  \\
 &= a^{1/2} + \frac{x}{2 a^{1/2}} - \frac{x^2}{8 a^{3/2}}  + \ldots .
\end{align}
If you also set $a = A^2$ and $x =\mu^2 \varepsilon^2$, you get
\begin{align}
\sqrt{A^2+\mu^2 \varepsilon^2}
 &= A + \frac{\mu^2 \varepsilon^2}{2 A}
 - \frac{\mu^4 \varepsilon^4}{8 A^3}  + \ldots \\
 &= A \left(1 + \frac{\mu^2 \varepsilon^2}{2 A^2}
 - \frac{\mu^4 \varepsilon^4}{8 A^4}  + \ldots \right).\\
\end{align}
If $\mu^2 \varepsilon^2$ is small compared to $A^2$, the first two terms
of the series are a good approximation for the entire series, so
we ignore $\frac{\mu^4 \varepsilon^4}{8 A^4}$ and all the terms after it.
This is a useful series to know about in physics, because it works
just as well for $(a+x)^{-1/2}$ as for $(a+x)^{1/2}$;
also, I seem to recall at some point (although I do not recall exactly
for what; something in special relativity, I think),
the third term became significant as well,
which you would not likely guess if you did not know about the series.
Comment: The third term is where all the good physics hides. And by good physics, I mean anomalies. And by anomalies, I mean Nobel Prizes.
Comment: That must explain why Feynman never won one.
Comment: @Simon S: Didn't he won one? But history says otherwise:P
Comment: I mean that zahbaz's comment in this context is slightly ridiculous. If Feynman here says that this approximation is good enough for his purposes, then it almost certainly is!


Failed to Get Objects from Json List without Title Names

Question: I want to get the objects  list of time stated in JSON list:
["09:30","11:25","00:00"]

This the C# code:
public IEnumerable<string> GetAlarmList()
{
    return (from t in _connection.Table<Medication>()
            select t.alarm_time).ToList();
}

var r = db.GetAlarmList();
var alarm_result = JsonConvert.DeserializeObject(r);
ObservableCollection<> t = new ObservableCollection<>(alarm_result);

It has not title like Time but it's just like that how can i get them into an ObservableCollection or List
Comment: I don't understand what failed and what you want. Please show also the code
Comment: I have provided it @GiladGreen
Comment: Please show value of `r` (the entire value) so we can replicate the problem
Comment: do you want to convert a JSON to c# list ??
Comment: But you do not have a json. You have an `IEnumerable`.. What is the content of each item in the `IEnumerable`
Comment: Ok , what i want is to get the Items in a GetAlarmList() , so i first made it json serialized then i deserialized again , but i dont know how to get each time separately
Comment: @IdrisStack - still, the given data example - is it of a single item of the `IEnumerable` or of all of it. Basically - can you show what you have in a given row under the `alarm_time` column
Comment: So the is the time stored in the Sqlite table , i want it to be in an ObservableCollection or List
Comment: It is of a single item
Answer: To get the separate values of the items use Split:
_connection.Table<Medication>().Select(r => r.alarm_time)
           .AsEnumerable()
           .Select(r => r.Substring(1, r.Length - 2).Split(','));

If you want to flatten the collection (and not have an IEnumerable<IEnumerable<string>> use SelectMany instead
Comment: How can i return it , because i want to return it as a string to attach it to a Label
Comment: @IdrisStack - your question is not clear.. what is the desired output? A single string? or a collection of strings?
Comment: ok dont worry i got it thanks , but of you dont mind can you give me you mail or skype id thanks.
Comment: @IdrisStack - I prefer not... All SO communication should only take place through SO
Comment: Ok no problem just wanted you to guide me sometimes


Laravel Validation Unique

Question: Estou com um formulário de cadastro, e nele existem informações para popular duas tabelas:

Usuário(User);
Embarcador(Sender).

Criei o Request do Laravel para isolar a regra de validação do formulário do controller. Cloquei unique em dois lugares, sendo o primeiro no campo email do usuário, e o segundo no document da pessoa.
Problema
A validação somente funciona pro primeiro caso, enquanto ele não aplica pra segunda. O resultado é levar um exception na cara se o CPF do cara for igual e tentar cadastrar.
https://image.ibb.co/kaTRBK/img.png
Controller
class RegisterSenderPersonController extends Controller
{
    public function store(SenderPersonUserStoreRequest $request)
    {
        $sender = Sender::create([
            'document' => $request['document'],
            'zipcode' => $request['zipcode'],
            'telephone' => $request['telephone'],
            'birthday' => $request['birthday'],
            'gender' => $request['gender'],
            'city_id' => $city->id,
        ]);

        if($sender->id) {
            $user = User::create([
                'name' => $request['name'],
                'email' => $request['email'],
                'sender_id' => $sender->id,
                'password' => $request['password'],
            ]);

            return 'gravou';
        }

        return 'deu ruim';
    }
}

SenderRequest
return [
            'birthday' => 'nullable|date',
            'document' => ['unique:sender', 'required', 'min:11','max:14', new Cpf],
            'email' => 'unique:user|required|min:4|max:35',
            'gender' => 'nullable|boolean',
            'name' => 'required|min:4|max:30',
            'password' => 'required|min:8|max:20',
            'telephone' => 'required|min:11|max:14',
            'zipcode' => 'required|min:8|max:9',
        ];

SenderMigration
Schema::create('sender', function (Blueprint $table) {
            $table->increments('id');
            $table->string('company_name', 60)->nullable()->unique();
            $table->string('exhibition_name', 25)->nullable();
            $table->string('document', 14)->unique();
            $table->date('birthday')->nullable();
            $table->boolean('gender')->nullable();
            $table->string('zipcode', 8);
            $table->string('telephone', 11);
            $table->boolean('active')->default(true);
            $table->timestamps();
        });

Comment: você está fazendo `unique` em tabelas diferentes, qual é a tela de erro?
Comment: @VirgilioNovic Atualzado !
Comment: Você pode também colocar a parte do controle? Talvez o erro seja no código do controler
Comment: O que `new Cpf` faz?
Comment: Ele valida o CPF. Essa função funciona, pq se digitar o cpf inválido ele retorna uma mensagem de erro pro form.
Answer: De acordo com a documentação do laravel, é necessário passar mais um parâmetro de coluna nas rules

unique:table,column,except,idColumn
The field under validation must be unique in a given database table. If the column option is not specified, the field name will be used.

Tente isso:
return [
        'birthday' => 'nullable|date',
        'document' => ['unique:sender,document', 'required', 'min:11','max:14', new Cpf],
        'email' => 'unique:user,email|required|min:4|max:35',
        'gender' => 'nullable|boolean',
        'name' => 'required|min:4|max:30',
        'password' => 'required|min:8|max:20',
        'telephone' => 'required|min:11|max:14',
        'zipcode' => 'required|min:8|max:9',
    ];

Comment: Eu mudei, mas permanece com o mesmo comportamento

Laravel Validation Unique


Spring Boot Not Able to Resolve Static Content

Question: So after adding Spring Security (not sure if it is the cause) it appears not only are the default Static Content resolution path null and void, but also any subsequent attempts to map URLs to static content
For example, a vanilla Spring Boot Application without a WebSecurityConfigurerAdapter would map /GET localhost:8080/index.html to ResourceHttpRequestHandler with default configured static content locations such as classpath:META-INF/resources and classpath:static/
Thus index.html located in one of these classpath locations are automatically served.
With a WebSecurityConfigurerAdapter however, I get 405s ... and no matter what I do ... it appears the handler registry will not contain a mapping to the aforementioned ResourceHttpRequestHandler locations
For example
Attempt to Add mapping explicitly
Use ResourceHandlerRegistry
@Configuration
public class ServletConfiguration extends WebMvcConfigurerAdapter {
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/index.html").addResourceLocations("classpath:statc/index.html");
        super.addResourceHandlers(registry);
    }
}

Here are the TRACE logs
2017-07-17 12:12:21.742 DEBUG 23566 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet        : DispatcherServlet with name 'dispatcherServlet' processing GET request for [/]
2017-07-17 12:12:21.755 DEBUG 23566 --- [nio-8080-exec-1] s.w.s.m.m.a.RequestMappingHandlerMapping : Looking up handler method for path /
2017-07-17 12:12:21.760 DEBUG 23566 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Resolving exception from handler [null]: org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' not supported
2017-07-17 12:12:21.768 DEBUG 23566 --- [nio-8080-exec-1] .m.m.a.ExceptionHandlerExceptionResolver : Invoking @ExceptionHandler method: public final org.springframework.http.ResponseEntity<java.lang.Object> org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler.handleException(java.lang.Exception,org.springframework.web.context.request.WebRequest)

Is this a known and frequently encountered issue when dealing with Spring Security?
Or maybe this is not expected and unrelated to Spring Security? I've gotten the entire setup to work many times before, the only thing new is Spring Security
Here is the SecurityConfiguration
@Configuration
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Autowired
    private UserDetailService userDetailsService;

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        final DaoAuthenticationProvider daoAuthenticationProvider = new DaoAuthenticationProvider();
        daoAuthenticationProvider.setPasswordEncoder(new StandardPasswordEncoder());
        daoAuthenticationProvider.setUserDetailsService(userDetailsService);
        /*
        it is important to set the default userDetailsService on AuthenticationManagerBuilder
         */
        auth.authenticationProvider(daoAuthenticationProvider).userDetailsService(userDetailsService);
    }

    @Override
    protected void configure(HttpSecurity http) throws Exception {
        org.springframework.security.web.authentication.AuthenticationSuccessHandler authenticationSuccessHandler = new AuthenticationSuccessHandler();
        http
                .csrf()
                .disable()
                .exceptionHandling()
                .authenticationEntryPoint(new HttpStatusEntryPoint(HttpStatus.UNAUTHORIZED))
                .and()
                .authorizeRequests()
                .antMatchers("/index.html").permitAll()
                .antMatchers("/api/security/**")
                .hasAuthority("ADMIN")
                .antMatchers("/api/portfolios/**", "/api/trades/**", "/api/user/**", "/api/init")
                .authenticated()
                .and()
                .formLogin()
                .successHandler(authenticationSuccessHandler)
                .failureHandler(new SimpleUrlAuthenticationFailureHandler())
                .and()
                .rememberMe()
                .and()
                .logout()
                .logoutSuccessHandler(new HttpStatusReturningLogoutSuccessHandler(HttpStatus.OK));
    }
}

Note that the start-up logs show both the default static content handler mapping and my explicit mapping to be both present and configured ... they are just not there when the actual request is made:
2017-07-17 12:25:57.088 DEBUG 23702 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**/favicon.ico", locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/], class path resource []], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@23707d5d]
2017-07-17 12:25:57.089 DEBUG 23702 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/index.html", locations=[class path resource [statc/index.html]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@5fa49615]
2017-07-17 12:25:57.089 DEBUG 23702 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/webjars/**", locations=[class path resource [META-INF/resources/webjars/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@7921eb37]
2017-07-17 12:25:57.089 DEBUG 23702 --- [           main] o.s.w.s.resource.ResourceUrlProvider     : Found resource handler mapping: URL pattern="/**", locations=[ServletContext resource [/], class path resource [META-INF/resources/], class path resource [resources/], class path resource [static/], class path resource [public/]], resolvers=[org.springframework.web.servlet.resource.PathResourceResolver@3fdb9c55]

EDIT
Digging Deeper
It appears there is a PartialMatchHelper in RequestMappingInfoHandlerMapping.java:195 on URL:[], method: PUT which will match every single request!
Comment: `statc/index.html`?
Comment: yes ... the issue as I am iterating through `DispatcherServlet` line-by-line is that `RequestMappingHandlerMapping` is short circuiting the entire `HandlerExecutionChain` by prematuring throwing a 405 ...

so if one look at `DispatcherServlet.java:1154` we see that the framework is trying to find a handler for a given request by seeing who among `this.handlerMappings` is willing to take the request .... I can see my custom configured handler `SimpleUrlHandlerMapping` and even the SpringBoot default mapping inside `this.handlerMappings`

the for loop short circuits before reaching it
Comment: Ah, now *that* can be a problem, and I've run into it in relation to Spring Data REST. I don't think that's the issue *here* though; it looks like a typo in your mapping.
Comment: @chrylis sorry I may have missed the typo ... where is the typo?
Comment: Ok I figured it out ... really random mistake on my part in a somewhat unrelated part of the App ... I am going to put out an self-answer
Answer: Kind of small mistake on my part - but has huge implications (after learning how Spring MVC framework works internally)
I had accidentally added a controller like this
@RestController("registration")
public class RegistrationController { ... }

When I meant
@RestController
@RequestMapping("registration")
public class RegistrationController {...}

so my registration REST end point would not have worked ... clearly BUT ... the former configuration also unwitting affected static content resolution by placing an empty URL:[], METHOD: PUT/POST or whatever into RequestMappingHandlerMapping which is one of the handler mappings that can take precedence over static Resource mappings
So the moral of the story is:
debug DispatcherServlet.java to see which handler mapping is truly being used
Comment: https://stackoverflow.com/questions/24661289/spring-boot-not-serving-static-content/33852040#33852040


Confusion regarding derivation of triangle inequality from Schwarz' inequality

Question: I was going through the proof of triangle inequality as a consequence of Schwarz inequality here:   http://en.wikipedia.org/wiki/Triangle_inequality#Example_norms  I find somethinng odd in the third step (the expansion of the inner product) . I learnt of the following properties of inner product:

$\langle a,b \rangle=\langle b,a \rangle^*$
$\langle a,zb+kc \rangle =z \langle a,b \rangle +k \langle a,c \rangle$
$ \langle za+kb,c \rangle =z^* \langle a,c \rangle + k^* \langle b,c \rangle$
$\langle za,kb \rangle = z^*k \langle a,b\rangle $

where $a,b,c$ are in general complex vectors, and $z,k$ are in general complex scalars. But I think the third step is wrong, due to rule (1). We should have got $\langle y,x \rangle =\langle x,y \rangle^*$, and not $\langle y,x \rangle = \langle x,y \rangle$, unless both $x,y$ are taken to be real vectors. But should I think of it in this way: that the vectors involved in proving the triangle-inequality must be real, and can not at all possess an imaginary part?
Comment: Seems like you might be overlooking the absolute value in that third step.
Answer: It appears you want to know why $\langle x, y \rangle + \langle y, x \rangle \leq 2 | \langle x, y \rangle |$.  This is a general property of complex numbers.  Let $z = \langle x, y \rangle$.  Using property $(1)$ in the definition of an inner product, your desired inequality follows from the fact that $z + z^* \leq 2 |z|$.  (As you'll see from the calculation that follows, both $z + z^*$ and $2 |z|$ are real numbers, so we can compare them.)  To prove this, let $z = a + bi$ with $a, b$ real.  Then $z + z^* = 2a$, while $|z| = \sqrt{a^2 + b^2}$.  It follows immediately that $z + z^* \leq 2 |z|$.
Comment: okay.this helps. And as Quinn Culver mentioned, I did miss the abs. value sign in the third step. Thanks.
Comment: Glad you got it sorted out!  Cheers.