The classification of and description of the root near $1/2$ of $x^d +x^\left({d-1}\right) + x^\left({d-2}\right) + \dots + x^2 + x - 1=0$

Question: In Arturas Dubickas paper "On the number of reducible polynomials of bounded naive height", manuscripta math. 144, 439–456 (2014) he discusses a bounding polynomial $x^d + x^\left({d-1}\right) + x^\left({d-2}\right) + \dots + x^2 + x - 1$ real root that is near $1/2$ called ${\theta}_{0}$ where $1/2 < {\theta}_{0} \le 1$ of this polynomial of degree $d$.  The roots are involved in the papers volume integrals.
My question is this polynomial known with possible references.  This is close to the All One Polynomials (AOP).
And the characterization of this root ${\theta}_{0}$.  I get from successive approximation $${\theta}_{0}\sim \frac{1}{2} + \frac{1}{2 (2^\left({d-1}\right)-d-2)}$$  I am looking for more detailed description of this root.  Also is it valid that when taking the limit as $d \rightarrow \infty$ that ${\theta}_{0} \rightarrow 1/2$.  This what I see numerically.
Answer: Your polynomial is $$p(x) = x^d + \ldots + x - 1 = \frac{x^{d+1}-1}{x-1} - 2 =
\frac{x^{d+1}-2x + 1}{x-1}$$
thus you are looking for a root near $1/2$ of
$$ x^{d+1} - 2 x + 1$$
More generally, consider $$Q(x,a) = a x^{d+1} - 2 x + 1$$
Using Lagrange Inversion, the root of this near $1/2$ has a very nice series expansion in powers of $a2^{-d-1}$:
$$\frac{1}{2}  +  \sum_{j=1}^\infty \frac{(a 2^{-d-1})^j}{2} \prod_{k=2}^j \left(1 + \frac{jd}{k}\right) $$
This should converge to your root at $a=1$.
Comment: I have been trying to duplicate your simple result for the Lagrange Inversion.  I am getting considerably more complicated results that are converging to the correct answer.
Answer: so we have some polynomial:
$$P(x)=-1+\sum_{i=1}^dx^i$$
We can try and use NR:
$$x_{n+1}=x_n-\frac{f(x_n)}{f'(x_n)}$$
Now we know that: $1/2<\theta_0\le1$ so we can take $x_0=1/2$ or $x_0=1$, either is valid.
If we take $x_0=1$ we get:
$$x_1=1-\frac{-1+\sum1^i}{\sum i\times 1^{i-1}}=1-\frac{2(d-1)}{d(d+1)}$$
and then continue this iterative process. I'm not sure how to evaluate the convergence of this sequence but could this be a way?
Answer: This is too long for a comment.
Starting from @Robert Israel's elegant answer, for the specific case  $a=1$, using Pochhammer symbols, the expansion write
$$x_d=\frac 12+\frac 12\sum_{j=1}^\infty \frac{ (d j+1)_j}{j!\, (d j+1)\,2^{(d+1) j}}$$ For discrete values of $d$, this reduces to hypergeometric functions
$$\left(
\begin{array}{cc}
d & 2\, x_d \\
 3 &  \,
   _3F_2\left(\frac{1}{4},\frac{2}{4},\frac{3}{4};\frac{2}{3},\frac{4}{3};\frac{16}{2
   7}\right) \\
 4 &  \,
   _4F_3\left(\frac{1}{5},\frac{2}{5},\frac{3}{5},\frac{4}{5};\frac{2}{4},\frac{3}{4}
   ,\frac{5}{4};\frac{3125}{8192}\right) \\
 5 &  \,
   _5F_4\left(\frac{1}{6},\frac{2}{6},\frac{3}{6},\frac{4}{6},\frac{5}{6};\frac{2}{5}
   ,\frac{3}{5},\frac{4}{5},\frac{6}{5};\frac{729}{3125}\right) \\
 6 &  \,
   _6F_5\left(\frac{1}{7},\frac{2}{7},\frac{3}{7},\frac{4}{7},\frac{5}{7},\frac{6}{7}
   ;\frac{2}{6},\frac{3}{6},\frac{4}{6},\frac{5}{6},\frac{7}{6};\frac{823543}{5971968
   }\right) \\
7 & \,
   _7F_6\left(\frac{1}{8},\frac{2}{8},\frac{3}{8},\frac{4}{8},\frac{5}{8},\frac{6}{8}
   ,\frac{7}{8};\frac{2}{7},\frac{3}{7},\frac{4}{7},\frac{5}{7},\frac{6}{7},\frac{8}{
   7};\frac{65536}{823543}\right) \\
 8 &  \,
   _8F_7\left(\frac{1}{9},\frac{2}{9},\frac{3}{9},\frac{4}{9},\frac{5}{9},\frac{6}{9}
   ,\frac{7}{9},\frac{8}{9};\frac{2}{8},\frac{3}{8},\frac{4}{8},\frac{5}{8},\frac{6}{
   8},\frac{7}{8},\frac{9}{8};\frac{387420489}{8589934592}\right)
\end{array}
\right)$$ where very clear patterns appear for all arguments except the last one I have not been able to identify (I would really be interested to know what it is).
Computed for $50$ significant digits, these are the exact solutions of the equation.
Comment: OK I cheated.  I matched the denominators and numerators with sequences A062206 and A085529 from OEIS and derived the final arguments to be $$\frac{\left({d+1}\right)^{d+1}}{{2}^{d+1}\, {d}^{d}}$$
Comment: Thus we now generalize this solution to $${\theta}_{d} = \frac{1}{2} {}_d{F}_{d - 1} \left({\left\{{\frac{1}{d + 1}, \frac{2}{d + 1}, \dots, \frac{d}{d + 1}}\right\}, \left\{{\frac{2}{d}, \frac{3}{d}, \dots, \frac{d - 1}{d}, \frac{d + 1}{d}}\right\}, \frac{\left({d + 1}\right)^{d + 1}}{{2}^{d + 1}\, {d}^{d}}}\right)$$
Comment: @LorenzHMenke. This is great ! Please, add this result as an edit in your post.
Comment: @LorenzHMenke. I wonder if this could not be published somewhere. Think about it.
Answer: From the posted Lagrange Inversion infinite series solution we get a further infinite series solution based on Pochhammer symbols that yield a generalized hypergeometric function solution for this root near $1/2$.  After generalizing from the posted comments we can write $${\theta}_{d} = \frac{1}{2} {}_d{F}_{d - 1} \left({\left\{{\frac{1}{d + 1}, \frac{2}{d + 1}, \dots, \frac{d}{d + 1}}\right\}, \left\{{\frac{2}{d}, \frac{3}{d}, \dots, \frac{d - 1}{d}, \frac{d + 1}{d}}\right\}, \frac{\left({d + 1}\right)^{d + 1}}{{2}^{d + 1}\, {d}^{d}}}\right)$$
I think that this is a known result of solving the trinomial ${x}^{d} + a\, x + b = 0$.  When $d = 5$ this is a well known quintic solution (later transformed into the  Bring quintic form).  I am looking for a reference of this result for degree $d$.


PDOException: SQLSTATE[HY000]: General error: 1 too many SQL variables

Question: I keep on running into the following error in my Drupal 7 installation:
PDOException: SQLSTATE[HY000]: General error: 1 too many SQL variables:
SELECT menu_links.link_path AS link_path,
       menu_links.mlid AS mlid,
       menu_links.router_path AS router_path,
       menu_links.updated AS updated
FROM {menu_links} menu_links

It is followed by hundreds of lines similar to this:
:db_condition_placeholder_994, :db_condition_placeholder_995, :db_condition_placeholder_996,

and hundreds more similar to this:
[:db_condition_placeholder_994] => admin/config/content/panelizer/%/%/list/%/clone
[:db_condition_placeholder_995] => admin/config/content/panelizer/%/%/list/%/delete
[:db_condition_placeholder_996] => admin/config/content/panelizer/%/%/list/%/disable

The current error stops at :db_condition_placeholder_1005 but I have seen :db_condition_placeholder_1018 in other errors.
If I disable installed modules it goes away but it comes back as I enable them again. It doesn't seem to be caused by any particular module, but more by how many modules are enabled. I thought it might be something to do with the admin_menu module, but disabling that has no effect.
I have googled this many times in the past 6 months, but never found a solution although I get the impression it has something to do with an SQLite limitation (999 variables in a query).
Down the line I'm quite prepared to dump SQLite and move to PostgreSQL (or MySQL), but for the time being I need to get this to work with SQLite.
Does anyone have an insight? Or even a fix?
Steve
Comment: @David Thomas: Is it a bug or is it a feature? :-) It does appear to be a limitation of SQLite.
Comment: Looks like a possible bug with the SQLite DB driver?
Answer: This is a limitation of SQLite: 999 parameters.
I posted it as an issue here and as long as we have no general solution in the db driver to overcome the limitation, i posted in comment #6 a d7 patch for the menu router.
Note that other DBs also have limits, but higher.
Answer: I solved this by going back to the root of the problem and migrating to PostgreSQL, which is a story in itself. No
PDOException: SQLSTATE[HY000]: General error: 1 too many SQL variables

since!
Steve


How can A minor key have a sharp chord in it?

Question: Basically I am learning piano, so I was trying to play an Indian song 'Janam Janam' in the key of A minor. 2 chords are out of scale but they don't give a dissonant sound and melody. They are A sharp major and E major which don't belong to the A minor key.
Please help.
Comment: I guess it should be called Bb major instead.
Comment: In a tonal piece in A minor, E major is the dominant chord, and so is frequently used, even though the G sharp is not in the key signature. If this was a Schubert song, I would guess that the B-flat chord is used as a "Neapolitan sixth", a kind of funky added chord that leads to the dominant and creates an extra feeling of tension. Without knowing your song, though, I can't say how the chords are used.
Comment: In classical music of the 18th and 19th century, and in a lot of popular music, a key is just a center around which the rest of the harmony is oriented, a home base from which the harmony departs and then returns. You can go just about anywhere you want on that journey (sharps, flats, even moving temporarily to other keys), as long as you return home in the end to the main key.
Comment: One can define three versions of the minor scale ([more info here](https://en.wikipedia.org/wiki/Minor_scale)). There is a G sharp if it is A minor harmonic.
Comment: I'm firmly of the belief that you can use absolutely any "guest" chord that you wish. This is doubly true if you are attempting to play songs from another musical zone on an instrument that was not intended for it. If it sounds good, do it. How would Blues have become accepted otherwise?  It did not follow "the rules"
Answer: Basically the answer to your question boils down to the relationship between chords and scales, and what "makes" a given key major or minor. In the case of the A#maj, the root is out of key (translating to a sharped octave or flat 2nd, depending on enharmonic context) but the double sharp third and fifth translate to the fourth and sixth of the natural A minor scale, so depending on what chord it resolves to there wouldn't be a big dissonance. With the E major, the G# which defines the chord as major is part of the A HARMONIC minor scale (the natural minor scale with a raised 7th) which again depending on the resolution of the chord produces a very pleasing "minor key feel".
Comment: We could also introduce the concept of the b5 substitution for the dominant which basically allows any dominant seventh type chord to be replaced by one rooted a diminished 5th higher.
But, above all, "out of scale" notes and chords are acceptable and commonplace,  There is no set of notes or chords that are "allowed" in any given key.  You can confirm this by glancing at the music copy of anything but the most simple song.
Answer: It's very likely that the mode that Janam Janam uses is very much like the West's Phrygian mode, which features a flat second degree (B♭ in this case), which acts as an upper leading tone to the tonic. It would be common to set such a leading tone with ♭II (B♭ major in this case) or ♭vii6 (G minor in first inversion). It's also quite common with minor-like modes to sharp the melodic seventh degree to act as a lower leading tone to the tonic: that is almost invariably set with V (E major in this case).
Answer: OK, let's look at the piece.  This is a very simplified version I found online, transposed into A minor (or at least with a starting chord of A minor).  But it seens to line up reasonably well with the recording.

(I was expecting something more 'Indian'.  This could have been written by Michel Legrand!)
We're in A minor.  We rapidly re-focus on C major (but the relative major is barely considered a modulation.)  The Dm chord isn't surprising in an A minor/C major environment, and the E7 run back to Am is bog-standard.   So it's just the B♭ chord that's a bit of a worry.
Well, it's got two notes in common with the preceding Dm chord.  We could explain it as an alternative colour of that chord.  What I DON'T think we can usefully do is force it into some sort of 'cycle of 5ths' dominant relationship to the E chord after it.
I take it we're OK with E7 being part of A minor now?


Custom field not showing on edit form

Question: I'm fairly new to drupal development and still trying to wrap my brain around the API.  I run an athletic based website and need to be able to store race times using a mm:ss.00 format.  I haven't seen any contributed modules that can do this, so I decided to create my own. I basically used an example field as my model and have gone through creating the field.  When I activated the code, I can add the field to the content type.  The field shows as an option when managing the display.  However, the field doesn't show up when I edit the content type.  I've gone through the code and compared it to others and I just can't figure out why.  Below is the code for my module. Any ideas?

    /**
     * Implementation of hook_field_info().
     */
     function racetime_field_info() {
        return array(
             'racetime' => array(
                 'label' => t('Time'),
                 'description' => t('Time in format mm:ss.00'),
                 'settings' => array(),
                 'instance_settings' => array('number_decimals'=>2),
                 'default_widget' => 'racetime_default_widget',
                 'default_formatter' => 'racetime_default_formatter'
             )
         );
     }

     /**
        * Implements hook_field_instance_settings_form()
        */
     function racetime_field_instance_settings_form($field,$instance) {
         return array(
             'number_decimals' => array(
                 '#type' => 'textfield',
                 '#size' => 4,
                 '#title' => t('Number of decimals'),
                 '#default_value' => $instance['settings']['number_decimals'],
                 '#description' => t('The number of decimal places to use'),
             )
         );
     }

     /**
        * Implements hook_field_widget_info()
        */
     function racetime_field_widget_info() {
            return array(
                 'racetime_default_widget' => array(
                        'label' => t('Time Field'),
                        'field types' => array('racetime')
                 ),
            );
     }

     /**
        * Implements hook_field_is_empty()
        */
     function racetime_field_is_empty($item,$field) {
            if($item['value'] === '') {
                    return TRUE;
            }
            return FALSE;
     }

     /**
        * Implements hook_field_widget_form()
        */
     function racetime_field_widget_form(&$form, &$form_state, $field, $instance, $langcode, $items, $delta, $element) {
            $value = isset($items[$delta]['value']) ? $items[$delta]['value'] : '';
            $numDecimals = $instance['settings']['number_decimals'];
            $widget = $element;
            $widget['#delta'] = $delta;

            $widget += array(
                 '#type' => 'textfield',
                 '#default_value' => $value,
                 '#size' => 8,
                 '#maxlength' => 15,
                 '#number_decimals' => $numDecimals,
                 '#value_callback' => '_racetime_widget_process_callback',
            );
            if (!isset($widget['description']) || !strlen($widget['description'])) {
                $widget['#description'] = t('Add description here');
            }
            if (!isset($widget['#process'])) {
                $widget['#process'] = array();
            }
            if (!in_array('_racetime_widget_process_callback', $widget['#process'])) {
                $widget['#process'][] = '_racetime_widget_process_callback';
            }

        $element['value'] = $widget;
        echo "\n";
        return $element;
     }

     /**
        * Implementation of hook_field_formatter_info
        */
     function racetime_field_formatter_info() {
            return array(
                 'racetime_default_formatter' => array(
                        'label' => t('Time'),
                        'field types' => array('racetime'),
                        'settings' => array(),
                        ),
                 );
     }

     /**
        *
        */
        function racetime_field_formatter_settings_form($field, $instance, $view_mode,$form, &$form_state) {
            $display = $instance['display'][$view_mode];
            $settings = $display['settings'];

            $element = array();

            if($display['type'] == 'racetime_default_formatter') {
                $element['number_decimals'] = array(
                    '#type' => 'textfield',
                    '#title' => t('Number of decimals'),
                    '#size' => 4,
                    '#description' => t('The number of decimals to use'),
                    '#default_value' => $settings['number_decimals'],
                    '#required' => TRUE,
                    );
            }
            return $element;
        }
     /**
        * Implements hook_help
        */
        function racetime_help($path, $arg) {
            switch ($path) {
                case "admin/help#racetime":
                    return '
' . t("A field for recording a race time in the format m:ss.00") . '
';
                    break;
            }
        }

        /**
         * Implements hook_field_formatter_view()
         */
        function racetime_field_formatter_view($entity_type, $entity, $field, $instance, $langcode, $items, $display) {
            $element = array();

            if($display['type'] == 'racetime_default_formatter') {
                foreach($items as $delta => $item) {
                    $element[$delta]['#theme'] = 'racetime';
                    $element[$delta]['#value'] = $item['value'];
                    $element[$delta]['#number_decimals'] = $display['settings']['number_decimals'];
                }
            }

            return $element;
        }

        /**
         * Implements hook_theme()
         */
        function racetime_theme($existing, $type, $theme, $path) {
            return array(
                'racetime' => array(
                        'variables' => array('value' => '', 'number_decimals' => 2)
                )
            );
        }

        /**
         * Theme racetime
         */
         function theme_racetime($variables) {

             $classes = array();
                $html = '';
                $html .= _racetime_integer_to_formatted($variables['value'],$variables['number_decimals']);
                $html .= '';
                return $html;
         }
        /**
         * Function to convert a string to integer
         */
        function _racetime_string_to_int($str, $numDecimals = 2) {
            //valid formats could be 16:47.17 (minutes:seconds.hundredths)
            //or 1:53:45.35 (hours:minutes:seconds.hundredths)
            //$numDecimals is the number of decimal places to carry after the seconds

            //split the string by colons, first.
            $parts = explode(":", $str);

            $numParts = count($parts);
            $hours = 0;
            $minuts = 0;
            $seconds = 0;
            if($numParts == 3) {
                $hours = $parts[0];
                $minutes = $parts[1];
                $seconds = $parts[2];
            }
            elseif($numParts == 2) {
                $minutes = $parts[0];
                $seconds = $parts[1];
            }
            else {
                $seconds = $parts[0];
            }
            //convert hours and minutes to seconds
            $sec_hours = $hours * 3600;
            $sec_minutes = $minutes * 60;
            //add all together to get the total number of seconds
            $seconds = $sec_hours + $sec_minutes + $seconds;

            /**
             * now convert the seconds to an integer value
             * here we multiple seconds by 10 to the power of number of decimals.
             * if the user wants one decimal, we'd be expecting a value like
             * 1:54.3, in which case we'd have a seconds value of 114.3.  10^1 is 10,
             * and we'd be left with an integer of 1143.  For the default of two,
             * we would expect a value of 1:54.34, which would give us 114.34 * 10^2 or
             * 114.34 * 100 = 11434.
             */
            $seconds_int = $seconds * (10^$numDecimals);

            return $seconds;
        }
        /**
         * function to convert an integer value to a time
         */
        function _racetime_integer_to_formatted($seconds, $numDecimals=2) {
            //first convert the integer value to seconds
            $sec = $seconds / (10^$numDecimals);
            if($sec < 60) {
                return number_format($sec,$numDecimals);
            }
            else {
                $hours_str = '';
                //get number of minutes
                $minutes = floor($sec / 60);
                $seconds_str = $sec - ($minutes * 60);
                //if seconds is less then 10, then add a leading 0
                if($seconds_str < 10) { $seconds_str = 0 . number_format($seconds_str,$numDecimals); }
                //if the number of minutes is greater than 60, then convert
                //minutes to hours and minutes
                if($minutes > 60) {
                    $hours = floor($minutes / 60);
                    $minutes_str = $minutes - ($hours * 60);
                    if($minutes_str < 10) {
                        $minutes_str = 0 . $minutes_str;
                    }
                    $hours_str = $hours . ':';
                }
                else {
                        $minutes_str = $minutes;
                }
                $time_string = $hours_str . $minutes_str . ":" . $seconds_str;

                return $time_string;
            }
        }
        /**
         * Widget helper to present seconds as readable formatte string
         */
        function _racetime_widget_process_callback($element, $form_state) {
            if(!isset($element['#value'])) {
                $element['#value'] = '';
            }
            $element['#value'] = _racetime_integer_to_formatted($element['#value'],$element['#number_decimals']);
        }

EDIT
It appears to have something to do with this line
 if (!in_array('_racetime_widget_process_callback', $widget['#process'])) {
     $widget['#process'][] = '_racetime_widget_process_callback';
 }

as soon as I commented it out, the form appears, even though the data doesn't get saved correctly.
Comment: Would it be possible to leverage the Date module? Times are stored in unix timestamp which goes down to the second... but you probably need those milliseconds eh?
Comment: Yup, need those hundredths of a second. Competition is generally timed to the hundredths or thousandths of a second.
Comment: There was some discussion concerning this for the HMS field module in [this issue](http://drupal.org/node/1586200). Might want to consider a contribution to that one, although I have no idea about status of things.
Comment: HMS is actually what I based the above on.  For now, I'll use what I have. I fixed the issue by fixing a bug in the value_callback value.  I was using the process_call function by mistake.
Answer: try to use this in the hook_field_widget_form()
'#default_value' => isset($items[$delta]) ? $items[$delta] : '',

Custom field not showing on edit form


Variation equations and integral invariants

Question: I am reading Whittaker's Analytical Dynamics. This is chapter 10 Hamiltonian Systems. Paragraph 112 is Variation Equations.
Let ${dx_r\over dt}=X_r(x_1,\dots,x_n,t),\quad (r=1,\dots,n)$ be a system of differential equations. Let $(x_1,\dots,x_n)$ and $(x_1+\delta x_1,\dots,x_n+\delta x_n)$ be the values of the independent variables in the moment $t$, for two neighboring solutions of the system, where $(\delta x_1,\dots,\delta x_n)$ are infinitesimal quantities.
Then $\frac{d}{dt}(x_r+\delta x_r)=X_r(x_1+\delta x_1,\dots,x_n+\delta x_n,t),\quad (r=1,\dots,n)$.
Therefore, $$\frac{d}{dt}\delta x_r = \sum_{q=1}^n\frac{\partial X_r}{\partial x_q}\delta x_q\quad (r=1,\dots,n)$$
Would anyone explain how this last equation follows?
Furthermore let $$\int \sum_r F_r(x_1,\dots,x_n,t)\delta x_r$$ be an integral invariant for the original system. How come is then $${d\over dt}F_r(x_1,\dots,x_n,t)\equiv0$$
Answer: Subtract the two differential equations:
$$
\begin{align}
\frac{d}{dt}\delta x_r &= \frac{d}{dt}(x_r+\delta x_r) - \frac d{dt}(x_r) \\
&= X_r(x_1+\delta x_1,\dots,x_n+\delta x_n,t) - X_r(x_1,\dots,x_n,t).
\end{align}
$$
This is just the change in $X_r$ when we change $x$ by $\delta x$, which is (from Taylor's theorem/the chain rule) $$\sum_q \frac{\partial X_r}{\partial x_q} \delta x_q.$$
For your second question, remember that the integral of an integral invariant over any domain is constant under the flow; so it must itself be constant along the flow. You can  see this by integrating over a tiny domain, where the integrand will be roughly constant.


Determining if a child div has content

Question: I'm working with some code that allows content editors to add content. I've found a few instances where there is a div that has children (like h5 or p) but no text. The div is taking up space and I would like to remove all of the divs that have no actual text in it.
The only thing I've found is the :empty css selector, but that checks for children, not text.

$('.col-lg-4:empty').remove();
.col-lg-4 {
  background-color: #c8c8c8;
  margin: 10px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet"/>

Test Title

This is some filler text that I have added for testing purposes.This is some filler text that I have added for testing purposes.This is some filler text that I have added for testing purposes.

This is some real content from my site that editors have added. As you can see, I have unnecessary divs with no content (the .col-lg-4 ones) that I would like to get rid of. With the :empty, it removes the last one that has no children. But what would be the best way to remove the ones that have children that have no content?
Comment: Select them, loop over, check the text length, hide it
Answer: Is that what you want to do?
I can't think of an easier way to do it!
Check the snippet:

$('.col-lg-4').each(function() {
  if (!this.innerText)  $(this).remove();
});
.col-lg-4 {
  background-color: #c8c8c8;
  margin: 10px;
}

<link href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" />

Test Title

This is some filler text that I have added for testing purposes.This is some filler text that I have added for testing purposes.This is some filler text that I have added for testing purposes.

I used innerText to get rid of all the html tags.
Hope it helps.
Comment: This is definitely a very efficient way, thanks for your help!
Answer: Iterate over them, check for empty children, remove:
$('.col-lg-4').each(function () {
  if ($(this).children().text() == '') $(this).remove();
});

Without jQuery:
Array.from(document.querySelectorAll('.col-lg-4'))
  .filter(i => !i.innerText)
  .forEach(e => e.parentNode.removeChild(e));

Determining if a child div has content


How to think about proofs of inequalities (precalculus)?

Question: I know that
$a\leq \lvert a \rvert$ and $\lvert a \rvert =\sqrt{a^2}$, so I can write
$$
a\leq \sqrt{a^2}
$$
But say something like
$$
a\leq \sqrt{a^2+b^2}
$$
Intuitively it's true. But can we really prove this or is it just intuition? I think: "we just added $b^2$ on the right side but nothing on the left side. Therefore the right side must be larger (of equal)". Is this the right way to think about it?
Comment: It's true by transitivity: $a^2\le a^2+b^2$, so $\sqrt{a^2}\le \sqrt{a^2+b^2}$, so …
Comment: The underlying idea here is that the square root function is an *increasing function*, which gives us that $m\le n\implies \sqrt{m}\le \sqrt{n}$. After that, you just have to recognize why $a^2\le a^2+b^2$, which should be fairly straightforward.
Answer: If you do not know that $x\mapsto \sqrt x$ is increasing, note that $\sqrt x\ge 0$ whenever it is defined. Therefore, $0\le x< y$ implies
$$0<y-x=\sqrt y^2-\sqrt x^2=\underbrace{(\sqrt y+\sqrt x)}_{\ge 0}(\sqrt y-\sqrt x), $$
whence
$$ \sqrt y-\sqrt x>0.$$
Now from $b^2\ge 0$, we see $a^2+b^2\ge a^2$ and so finally $\sqrt{a^2+b^2}\ge \sqrt {a^2}$.
Comment: Hagen.Very nice.+
Answer: $$a \leq \sqrt{a^2} \leq \sqrt{a^2+b^2}$$
since square root is an increasing function and we know that $b^2$ is nonnegative.
Answer: Suppose you have some inequality of the kind $a\le b$, then if you apply an increasing function to both sides the inequality holds, that is, suppose that $f$ is an increasing function, then $f(a)\le f(b)$ if and only if $a\le b$.
If $g$ would be a decreasing function then $g(a)\ge g(b)$ if and only if $a\le b$, you only need to check the definition of increasing and decreasing functions to see that these inequalities holds by definition.
In our case the function $f(x):=x^2$ is increasing for non-negative reals, thus if $a\ge 0$ and $\sqrt{a^2+b^2}\ge 0$ then we have that
$$a\le\sqrt{a^2+b^2}\iff f(a)=a^2\le f(\sqrt{a^2+b^2})=a^2+b^2\tag1$$
where the symbol $\iff$ must be read as "if and only if", and it means that if one thing in one of the sides of the $\iff$ is true (or false) the other is also true (or also false).
Then from $(1)$ we find that $a^2\le a^2+b^2\iff 0\le b^2$ what is true, thus $a\le\sqrt{a^2+b^2}$ is also true. Moreover, if $a<0$ then $-a>0$ and you can show that $-a\le\sqrt{a^2+b^2}$, and because $a<-a$ then your inequality also holds when $a<0$.


Como passar o valor de uma variável de uma classe local para outra classe (fora do seu escopo e com visibilidade pública)?

Question: Boa noite. Estou com bastante dificuldade de utilizar o valor de uma variável em uma classe local e passá-la para outra classe que irá ser carregada na intent. O valor da string está saindo nula e dá erro na aplicação. Sou iniciante, já pesquisei bastante e ainda não consegui descobrir uma forma de passar esse valor. Gostaria que me ajudassem. Desde já agradeço.
public class Carro extends AppCompatActivity {

ListView lvCarrinhoItems;
Button bFinalizar;
String url2 = "";
String parametros2 = "";
String insertUrl = "http://localhost/registrar.php";
RequestQueue requestQueue;
String result = "";
public static String idOrder = "", dta = "";
public static MeuPedido meuPedido;

@Override
protected void onCreate(Bundle savedInstanceState)  {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.shopping_carrinho);

    lvCarrinhoItems = (ListView) findViewById(R.id.tela5lv);

    LayoutInflater layoutInflater = getLayoutInflater();

    final Carrinhos carrinhos = CarrinhoHelper.getCarrinhos();
    final TextView tvTotalPrice = (TextView) findViewById(R.id.tvsoma);
    final TextView tvObspedido = (TextView) findViewById(R.id.etobscar);
    tvTotalPrice.setText((Bandeja.MOEDA+String.valueOf(carrinhos.getTotalPrice().setScale(2, BigDecimal.ROUND_HALF_UP))).replace(".",","));

    final TCartItemAdapter tcartItemAdapter = new TCartItemAdapter(this);
    tcartItemAdapter.updateCartItems(getCarrinhoItems(carrinhos));

            lvCarrinhoItems.setAdapter(tcartItemAdapter);

            bFinalizar = (Button) findViewById(R.id.button4);

            bFinalizar.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    AlertDialog.Builder alerta = new AlertDialog.Builder(Carro.this);
                    alerta.setTitle("Confirmação de pedido");
                    alerta

                            .setIcon(R.drawable.service)
                            .setMessage("Deseja confirmar o seu pedido?")
                            .setCancelable(false)
                            .setNegativeButton("Cancelar", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialogInterface, int i) {
                                }
                            })
                            .setPositiveButton("Sim", new DialogInterface.OnClickListener() {

                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                    requestQueue = Volley.newRequestQueue(getApplicationContext());

                                    ConnectivityManager connMgr = (ConnectivityManager)
                                            getSystemService(Context.CONNECTIVITY_SERVICE);
                                    NetworkInfo networkInfo = connMgr.getActiveNetworkInfo();

                                    pref = getSharedPreferences("login.conf", Context.MODE_PRIVATE);
                                    final String idcliente = pref.getString("idusuario", null);
                                    final String idrestaurante = CarrinhoHelper.getIdResta();
                                    final String valorpedido = String.valueOf(carrinhos.getTotalPrice());
                                    final String obspedido = tvObspedido.getText().toString();
                                    if (idcliente == null){
                                        Intent intent = new Intent(Carro.this, A2_1semlogin.class);
                                        startActivity(intent);
                                    }else

                                    if (networkInfo != null && networkInfo.isConnected()) {

                                        url2 = "http://localhost/registrarpedido.php";

                                        parametros2 = "idcliente=" + idcliente + "&idrestaurante=" + idrestaurante + "&valorpedido=" + valorpedido + "&obspedido=" + obspedido;

                                        new SolicitaDados2().execute(url2);

                                    } else {
                                        Toast.makeText(getApplicationContext(), "Por favor, verifique sua conexão", Toast.LENGTH_LONG).show();
                                    }

                                    Log.d("DadosRet2", parametros2);
                                    Log.d("DadosRet2", idcliente + ", " + idrestaurante + ", " + valorpedido + ", " + obspedido);

                                     class MyAsyncTaskresources extends AsyncTask<String, String, String> {

                                        @Override
                                        protected void onPreExecute() {

                                        }
                                        @Override
                                        protected String  doInBackground(String... params) {

                                            InputStream isr = null;

                                            try{
                                                String URL=params[0];
                                                java.net.URL url = new URL( URL);
                                                URLConnection urlConnection = url.openConnection();
                                                isr  = new BufferedInputStream(urlConnection.getInputStream());

                                            }

                                            catch(Exception e){

                                            }

                                            try{

                                                BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);

                                                StringBuilder sb = new StringBuilder();

                                                String line = null;

                                                while ((line = reader.readLine()) != null) {

                                                    sb.append(line + "\n");

                                                }

                                                isr.close();

                                                result=sb.toString();

                                                String s = "";

                                                JSONArray jArray = new JSONArray(result);
                                                for (int i = 0; i < jArray.length(); i++) {

                                                    final  JSONObject json = jArray.getJSONObject(i);

                                                    s = s + "login info : " + json.getString("idOrder") + " " + json.getString("idcliente") + " " + json.getString("idrestaurante") + " " + json.getString("data");

    **STRING QUE DESEJO ACESSAR = idOrder**

                                                    idOrder = json.getString("idOrder");
                                                    dta = json.getString("data");

                                                    List<CarrinhoItem> carrinhoItems = new ArrayList<CarrinhoItem>();
                                                    Log.d(TAG, "Current shopping cart: " + carrinhos);

                                                    Map<TSaleable, Integer> itemMap = carrinhos.getItemWithQuantity();

                                                    for (Map.Entry<TSaleable, Integer> entry : itemMap.entrySet()) {

                                                        final CarrinhoItem carrinhoItem = new CarrinhoItem();
                                                        carrinhoItem.setBandeja((Bandeja) entry.getKey());
                                                        carrinhoItem.setQuantidade(entry.getValue());
                                                        carrinhoItems.add(carrinhoItem);

                                                        final String idcomida = carrinhoItem.getBandeja().getIdcomida();
                                                        final String quantidade = carrinhoItem.getBandeja().getQuantidade();
                                                        final BigDecimal valorunit = carrinhoItem.getBandeja().getPreco();
                                                        final String adicional = carrinhoItem.getBandeja().getAdicional();
                                                        final String obsproduto = carrinhoItem.getBandeja().getObsproduto();

                                                        StringRequest request = new StringRequest(Request.Method.POST, insertUrl, new Response.Listener<String>() {
                                                            @Override
                                                            public void onResponse(String response) {

                                                                System.out.println(response.toString());
                                                            }
                                                        }, new Response.ErrorListener() {
                                                            @Override
                                                            public void onErrorResponse(VolleyError error) {

                                                            }
                                                        }) {

                                                            @Override
                                                            public Map<String, String> getParams() throws AuthFailureError {

                                                                Map<String, String> parameters = new HashMap<String, String>();

                                                                parameters.put("idOrder",idOrder);
                                                                parameters.put("idcomida", idcomida);
                                                                parameters.put("quantidade", quantidade);
                                                                parameters.put("valorunit", valorunit.toString());
                                                                parameters.put("adicional", adicional);
                                                                parameters.put("obsproduto", obsproduto);

                                                               final MeuPedido meupedido = new MeuPedido();
                                                                String novaId = idOrder;

                                                                meupedido.setmPedido(novaId);

                                                                return parameters;

                                                            }

                                                        };
                                                        requestQueue.add(request);

                                                    }

                                                    break;
                                                }

                                            }

                                            catch(Exception e){

                                                Log.e("log_tag", "Error  converting result " + e.toString());

                                            }

                                            return null;

                                        }

                                    }

                                    new MyAsyncTaskresources().execute("http://localhost/sel.php?idcliente="+idcliente+"&idrestaurante=" +idrestaurante);

                                }

                            });

                    AlertDialog alertaDialog = alerta.create();
                    alertaDialog.show();
                }
            });

}

public static final List<CarrinhoItem> getCarrinhoItems(Carrinhos carrinhos) {
    List<CarrinhoItem> carrinhoItems = new ArrayList<CarrinhoItem>();
    Log.d(TAG, "Current shopping cart: " + carrinhos);

    Map<TSaleable, Integer> itemMap = carrinhos.getItemWithQuantity();

    for (Map.Entry<TSaleable, Integer> entry : itemMap.entrySet()) {
       final CarrinhoItem carrinhoItem = new CarrinhoItem();
        carrinhoItem.setBandeja((Bandeja) entry.getKey());
        carrinhoItem.setQuantidade(entry.getValue());
        carrinhoItems.add(carrinhoItem);

        final String comida = carrinhoItem.getBandeja().getComida();
        final String adicional = carrinhoItem.getBandeja().getAdicional();
        final String quantidade =  carrinhoItem.getBandeja().getQuantidade();
        final BigDecimal valor = carrinhoItem.getBandeja().getPreco();

    }

        return carrinhoItems;
    }

private class SolicitaDados2 extends AsyncTask<String, Void, String> {

    @Override
    protected String doInBackground(String... urls) {

        return Conexao.postDados(urls[0], parametros2);
    }

    @Override
    protected void onPostExecute(String resultado) {

         if (resultado.contains("pedido_ok")) {

            Toast.makeText(getApplicationContext(), "Registro efetuado com sucesso", Toast.LENGTH_LONG).show();

             Intent intent = new Intent(Carro.this, Anotafiscal.class);

**  LOCAL ONDE DESEJO INSERIR A STRING**

             String  hjhj = idOrder ;
             intent.putExtra("iddopedido",hjhj);

             startActivity(intent);
             finish();

        } else {
            Toast.makeText(getApplicationContext(), "Ocorreu um erro no cadastro", Toast.LENGTH_LONG).show();
        }
    }

}

}

Answer: Olá,
Podes fazer algo como isto na primeira classe.
Intent intent = new Intent(getBaseContext(), SegundaClasse.class);
intent.putExtra("ID da Variavel", valorParaEnviar);
startActivity(intent);

Na outra class,
String receberValor = getIntent().getStringExtra("ID da Variavel");

Espero ter ajudado


given $y = a + bx + cx^2$ fits three given points, find and solve the matrix equation for the unknowns $a,b$, and $c$

Question:
Given $y = a + bx + cx^2$ fits three given points, find and solve the matrix equation for the unknowns $a$, $b$, and $c$.

the equation fits the points $(1,0), (-1, -4),$ and $(2, 11)$
I really don't know what I'm supposed to do here.  I tried setting it up like a normal matrix like
$$\begin{pmatrix}
1&-1&2\\
0&4&11
\end{pmatrix}
(x\quad y)=??$$
but this doesn't make any sense because the original equation has multiple x's in it and I feel like im not taking care of that.
Can you help me get started with this? I just don't get it and I'm so frustrated.
Thanks!
Comment: The point $(x,y)$ is on the graph of a function $f$ if and only if $y = f(x)$.  In other words, plug the three $x$-values into the function, and you get three equations with three unknowns.
Answer: First note that $y = a + bx + cx^2$ can also be written as
$$(1 \quad x \quad x^2) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) = y$$
You are given three points, $(x_1,y_1) = (1,0)$, $(x_2,y_2) = (-1,-4)$ and $(x_3,y_3) = (2,11)$. So you can set up three of these equations:
$$\begin{align}
(1 \quad x_1 \quad x_1^2) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) &= y_1 \\
(1 \quad x_2 \quad x_2^2) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) &= y_2 \\
(1 \quad x_3 \quad x_3^2) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) &= y_3
\end{align}$$
Or, in one matrix form:
$$\left(\begin{array}{ccc} 1 & x_1 & x_1^2 \\ 1 & x_2 & x_2^2 \\ 1 & x_3 & x_3^2 \end{array}\right) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) = \left(\begin{array}{c} y_1 \\ y_2 \\ y_3
\end{array}\right)$$
You know the values of $x_1, x_2, x_3, y_1, y_2, y_3$, so filling them in you will be left with an equation of the form $Ax = b$, with $A$ and $b$ known and $x$ unknown.
Edit: For completeness, filling in those values we get
$$\left(\begin{array}{ccc} 1 & 1 & 1 \\ 1 & -1 & 1 \\ 1 & 2 & 4 \end{array}\right) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) = \left(\begin{array}{c} 0 \\ -4 \\ 11
\end{array}\right)$$
You could do a Gaussian elimination, but this example has a simple solution which we can just calculate by hand. Subtracting the second row from the first we get
$$(0 \quad 2 \quad 0) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) = 4 \quad \Longrightarrow \quad \fbox{b = 2}$$
Subtracting the first from the last we get
$$(0 \quad 1 \quad 3) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) = 11 \quad \Longrightarrow \quad b + 3c = 11 \quad \Longrightarrow \quad \fbox{c = 3}$$
Then finally you could use the first row to get
$$(1 \quad 1 \quad 1) \left(\begin{array}{c} a \\ b \\ c
\end{array}\right) = 0 \quad \Longrightarrow \quad a + b + c = 0 \quad \Longrightarrow \quad \fbox{a = -5}$$
(For the enthusiast, note that the matrix $A$ is a Vandermonde matrix.)
Answer: If the equation fits three points, then if we assign the x-axis value and $y$-axis value to the equation, we can have a row in the matrix.
Example, assign $(1,0)$ to the equation, we have $a + b+ c = 0$.
The same for the other two points. Then you have a matrix that can be solved using a calculator or by Gaussian calculation.


Rational points on $y^2 = 12x^3 - 3$.

Question: Prove by elementary arguments that the only rational point on the title curve is $(x, y) =(1,\pm 3)$.
My attempt was the standard approach of factoring $(y+i\sqrt 3)(y - i\sqrt 3) = 12x^3$, but it seems as one proceeds in the usual manner, this doesn't yield the required result ?
Answer: hint
Consider a line L with slope $m$ that passes through the point $(1,3)$. Then L will be of the form $y=m(x-1)+3$. Now consider the intersection of this line with the curve given. To get rational points you need to have $m$ as rational.
Note: even though you get a cubic in $x$ but one of the roots is $x=1$ So using symmetric polynomials it will be easy to get other roots in terms of $m$.

Rational points on $y^2 = 12x^3 - 3$.


How can I count visitor's views of specific block?

Question: I know I can use Statistics module to get total views for specific node.
But how can I count visitor's views of specific block?
The block is not connected to some fixed path (or node) and the block can be displayed in any place of site.
I could not find any module for the task.
What hook would be better to use to count visitor's views of the block?
Comment: [hook_block_view](https://api.drupal.org/api/drupal/modules%21block%21block.api.php/function/hook_block_view/7.x)
Comment: AFAIK hook_block_view work only for custom block which created inside custom module. Still finding more universal solution.
Comment: It seems **hook_entity_view** can help me.
Answer: <code>function mymodule_entity_view($entity, $type, $view_mode, $langcode) {

    if ($type == 'node' &&  $entity->nid == 17457) {
        $entity->field_counter['und']['0')]['value']++;
        node_save($entity);
    }

}
</code>


Diagnosing high CPU waiting

Question: I have a monitoring server that is running icinga/collectd/graphite with about 50 hosts. I have noticed high load/slugging performance on the box. If you take a look at top, you'll see:
Cpu(s): 0.6%us, 0.2%sy, 0.0%ni, 7.6%id, 23.4%wa, 0.0%hi, 0.2%si, 0.0%st
Notice the HUGE %wa value, which as far as I know means a network or disk bottleneck. ifconfig shows no dropping packets and there's not a ton of bandwidth going on, so that leaves disk issues, right? There's not a lot of disk writing going on either...iotop is reporting we're only writing a little over 1 MB per second and the RAID tool reports everything is A-OK and write caching is enabled.
How do I go about trying to figure out how to fix this?
UPDATE:
iostat -x output is:
avg-cpu:  %user   %nice %system %iowait  %steal   %idle
           0.62    0.10    0.31    9.65    0.00   89.31

Device:         rrqm/s   wrqm/s     r/s     w/s   rsec/s   wsec/s avgrq-sz avgqu-sz   await  svctm  %util
sda               0.21    33.34   83.55   16.54  1599.94   399.07    19.97    43.21  416.98   3.71  37.13

Answer: i/o wait is also generated by NFS, SMB and other remote filesystems.
Use vmstat 2 to see a granular view of system performance including io wait.
Answer: High wa generally does mean the OS is either waiting for network or disk. There is quite a nifty program called iotop. This tells you what the disk is up to, might be some help.
Comment: 1mb per second is a useless indicator - like trying to find out whether the engine in a car is powerfull enough by looking at the tachometer in a city. I have a 8 disc RAID 10 Veloricaptors that at times only pulls 4-6 mb/s and is FULLY BUSY. Check something like IO wait stats if available - but MB is irrelevant, if the head moves a lot, that may be all that the disc gives you.
Comment: As I said in the post, I ran iotop and it's only doing 1 MB/s of total disk I/O.
Comment: ah sorry you did I missed that. are the drives in good health? Have you had a look at smartctl?

Also try doing a bandwidth test on the network, iperf is a good program. Make sure you have no network bottlenecks.

Diagnosing high CPU waiting


Let $V$=$P(R)$, and for $j \geqslant 1$ define $T_j(f(x))$=$f^{(j)}(x)$,where $f^{j}(x)$ is the $j^{th}$ derivative of $f(x)$

Question:

For this problem, can I construct a zero transformation and do the regular step of proving linear independence?
Answer: If $ \sum\limits_{j=1}^{n} c_jT_j=0$ then $ \sum\limits_{j=1}^{n} c_jf^{(j)}(x)=0$ for every $x$ and every $f \in P(\mathbb R)$. Put $f(x)=x$ to get $c_1=0$. Then put $f(x)=x^{2}$ to get $c_2=0$, and so on.
Comment: $L(V)$ is a vector space. Its zero element is the zero transformation. @xyz12354
Comment: so for this problem, do we have to explain why we construct a zero transformation?


A Circular Div for a Target

Question: I would like to make a circular button that can only be clicked in the circular part in order to execute a javascript function. It has to be made with HTML, CSS, JAVASCRIPT, any JAVASCRIPT/JQUERY plugins or any combination of them. I have given a link to a picture outlining what I mean according to this explination: The black is the outline of the entire div (695px x 695px), if the blue is clicked nothing should happen but if the red is clicked the javascript function should be called.
Picture at: http://1drv.ms/1hIPvwz (new so couldnt post picture)
Any Ideas?
Comment: Put another `` inside the outer one. Give it a `border-radius` of `100%`. Voilà.
Comment: Is this a practical problem or is it an academic excersise (homework).  If it is practical, what is the actual requirement? What do you need help with?
Comment: Two options spring to mind. The use of image maps, or svg, both of which support circular clickable areas. Are either of these an option in your case? Of the two the use of images maps would seem to satisfy the requirement to stick with HTML better.
Answer: SVG is the only solution I can think of. As an example:
your html:
<svg height="100" width="100">
  <circle id="click" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

your jquery:
$('#click').click(function() {
   alert('clicked');
});

Comment: Downvoted because this answer goes way beyond what's needed and isn't a cross-browser solution.
Comment: That doesn't make it wrong.
Comment: on the cross-browser remark; more or less just as cross-browser as border radius: http://caniuse.com/svg http://caniuse.com/border-radius
Comment: On the over the top remark: I used less code.
Comment: Agreed- not a wrong answer, but given that the author didn't think to use border-radius, do you think it's wise to introduce drawing SVG's? I also hadn't Realized how ubiquitous drawing svgs was in terms of compatibility. My mistake.
Comment: I think we can both agree that best practice would not be drawing an SVG and using that as a button.
Answer: You do not need to use an SVG for this...
Any block element can have a border-radius: 100% applied to it, creating a rendered circle. I suggest putting a circular button within a block div. This would be best practice.
HTML

    <button id="my-button">PRESS ME</button>

CSS
button {
    background-color: red;
    outline: none;
    border-radius: 100%;
    border: none;
    width: 50px;
    height: 50px;
    cursor: pointer;
}

.target {
    background-color: blue;
    width: 50px;
    height: 50px;
    border: 2px solid black;
}

JQUERY
$('#my-button').click(function() {
    alert('pressed');
});

JSfiddle: http://jsfiddle.net/9aRLp/1/
Answer: Sitting in the exact middle of the blue box.
Have a fiddle! - Fiddle Link!
HTML

CSS
.outer {
    height: 550px;
    width: 550px;
    background: #000080;
    position: relative;
}
.circle {
    display: block;
    height: 500px;
    width: 500px;
    border-radius: 100%;
    background: #F00;
    cursor: pointer;
    position: absolute;
    top: 50%;
    left: 50%;
    margin: -250px 0 0 -250px;
}

jQuery
$('.circle').click(function() {
    alert('pressed');
});

A Circular Div for a Target


Trigonometric function integration: $\int_0^{\pi/2}\frac{dx}{(a^2\cos^2x+b^2 \sin^2x)^2}$

Question: How to integrate $$\int_0^{\pi/2}\dfrac{dx}{(a^2\cos^2x+b^2 \sin^2x)^2}$$
What's  the approach to it?
Being a high school student , I don't know things like counter integration.(Atleast not taught in India in high school education ).I just know simple elementary results of definite and indefinite integration. Substitutions and all those works good. <code>:)</code>
Comment: *To get the best possible answers, you should explain what your thoughts on the problem are so far*. That way, people won't tell you things you already know, and they can write answers at an appropriate level; also, people tend to be more willing to help you if you show that you've tried the problem yourself.
Comment: @user007 There's probably a faster way, but you can handle most trigonometric integrals with this: http://en.wikipedia.org/wiki/Weierstrass_substitution
Comment: Do you know anything about contour integration? The Weierstrass substitution?
Comment: @Potato: I am a high school student . I don't know these .I'll add something  in question too.
Answer: In this case, the following trick also works: Dividing both the numerator and the denominator by $\cos^4 x$, we can use the substitution $ t = \tan x$ to obtain
\begin{align*}
\int_{0}^{\frac{\pi}{2}} \frac{dx}{(a^2 \cos^2 x + b^2 \sin^2 x)^2}
&= \int_{0}^{\frac{\pi}{2}} \frac{1 + \tan^2 x}{(a^2 + b^2 \tan^2 x)^2} \sec^2 x \, dx \\
&= \int_{0}^{\infty} \frac{1 + t^2}{(a^2 + b^2 t^2)^2} \, dt \\
&= \frac{1}{a^2}\int_{0}^{\infty} \left( \frac{1}{a^2 + b^2 t^2} + \frac{(a^2 - b^2) t^2}{(a^2 + b^2 t^2)^2} \right) \, dt.
\end{align*}
The first one can be evaluated as follows: Let $bt = a \tan\varphi$. Then
$$ \int_{0}^{\infty} \frac{dt}{a^2 + b^2 t^2} = \frac{1}{ab} \int_{0}^{\frac{\pi}{2}} d\varphi = \frac{\pi}{2ab}. $$
For the second one, we perform the integration by parts:
\begin{align*}
\int_{0}^{\infty} \frac{t^2}{(a^2 + b^2 t^2)^2} \, dt
&= \left[ - \frac{1}{b^2}\frac{1}{a^2 + b^2 t^2} \cdot \frac{t}{2} \right]_{0}^{\infty} + \int_{0}^{\infty} \frac{1}{2b^2}\frac{dt}{a^2 + b^2 t^2} \\
&= \frac{1}{2b^2} \int_{0}^{\infty} \frac{dt}{a^2 + b^2 t^2} \\
&= \frac{\pi}{4ab^3}.
\end{align*}
Putting together, the answer is
$$ \frac{(a^2 + b^2)\pi}{4(ab)^3}. $$
Comment: Seems gr8. A simplified answer always helps.
Answer: You want to integrate
$$J = \int_0^{\pi/2} \dfrac{dx}{\left(a^2 +(b^2-a^2) \sin^2(x) \right)^2} = \dfrac1{a^4}\int_0^{\pi/2} \dfrac{dx}{\left(1 +c \sin^2(x) \right)^2}$$
where $c = \dfrac{b^2-a^2}{a^2}$.
We now want to integrate $I = \displaystyle \int_0^{\pi/2} \dfrac{dx}{\left(1 +c \sin^2(x) \right)^2}$. From Taylor series, we have
$$\dfrac1{(1+cy^2)^2} = \sum_{k=0}^{\infty}(-1)^k (k+1)c^k y^{2k}$$
Hence (swapping integral and infinite summation), we get that
$$\int_0^{\pi/2}\dfrac{dx}{(1+c\sin^2(x))^2} = \sum_{k=0}^{\infty}(-1)^k (k+1)c^k \int_0^{\pi/2}\sin^{2k}(x)dx$$
From here, we have
$$\int_0^{\pi/2} \sin^{2k}(x) dx = \dbinom{2k}k \dfrac{\pi}{2^{2k+1}}$$
Hence,
$$I = \sum_{k=0}^{\infty}(-1)^k (k+1)c^k \dbinom{2k}k \dfrac{\pi}{2^{2k+1}} = \dfrac{\pi}2 \sum_{k=0}^{\infty} (k+1) \dbinom{2k}k \left(-\dfrac{c}4\right)^k$$
Now from Taylor series, we have
$$\sum_{k=0}^{\infty} (k+1) \dbinom{2k}k x^k = \dfrac{1+4x\sqrt{1-4x}-2x-\sqrt{1-4x}}{(1-4x)^{3/2}}$$
Hence,
$$J = \dfrac{\pi}2 \left(\dfrac{1-c\sqrt{1+c}+c/2-\sqrt{1+c}}{a^4(1+c)^{3/2}} \right)$$
Now plug in the value of $c$ and get the value of the original integral $J$.
Answer: Put $t=\tan x\implies dt=\sec^2x.dx$
$$
\begin{align}
&\int_0^{\pi/2}\frac{dx}{(a^2\cos^2x+b^2\sin^2x)^2}=\int_0^{\pi/2}\frac{\sec^4x.dx}{(a^2+b^2\tan^2x)^2}\\
&=\int_0^\infty\frac{1+t^2}{(a^2+b^2t^2)^2}dt=\frac{1}{b^2}\int_0^\infty\frac{dt}{a^2+b^2t^2}+\frac{b^2-a^2}{b^2}\int^\infty_0\frac{dt}{(a^2+b^2t^2)^2}=I_1+I_2
\end{align}
$$
$$
I_1=\frac{1}{b^2}\int_0^\infty\frac{dt}{a^2+b^2t^2}=\bigg[\frac{1}{b^2}.\frac{1}{ab}.\tan^{-1}\frac{bt}{a}\bigg]_0^\infty=\frac{\pi}{2ab^3}
$$
Put $t=\frac{a}{b}\tan\theta\implies dt=\frac{a}{b}\sec^2\theta.d\theta$
$$
\begin{align}
I_2&=\frac{b^2-a^2}{b^2}\int^\infty_0\frac{dt}{(a^2+b^2t^2)^2}=\frac{b^2-a^2}{b^2}\int_0^{\pi/2}\frac{\frac{a}{b}\sec^2\theta.d\theta}{(a^2+a^2\tan^2\theta)^2}\\
&=\frac{b^2-a^2}{b^2}\frac{a}{b.a^4}\int_0^{\pi/2}\frac{\sec^2\theta}{\sec^4\theta}d\theta=\frac{b^2-a^2}{a^3b^3}\int_0^{\pi/2}\cos^2\theta.d\theta\\
&=\frac{b^2-a^2}{a^3b^3}\int_0^{\pi/2}\bigg(\frac{1+\cos2\theta}{2}\bigg)d\theta=\frac{b^2-a^2}{2a^3b^3}\bigg[\theta+\frac{\sin2\theta}{2}\bigg]_0^{\pi/2}=\frac{\pi}{4}\frac{b^2-a^2}{a^3b^3}
\end{align}
$$
$$
\begin{align}
\int_0^{\pi/2}\frac{dx}{(a^2\cos^2x+b^2\sin^2x)^2}&=I_1+I_2=\frac{\pi}{2ab^3}+\frac{\pi}{4}\frac{(b^2-a^2)}{a^3b^3}\\
&=\frac{2\pi.a^2+\pi.b^2-\pi.a^2}{4a^3b^3}=\frac{\pi}{4}.\frac{a^2+b^2}{a^3b^3}
\end{align}
$$
Answer: Consider
$$
I(c)=\int_{0}^{\frac{\pi}{2}} \ln \left(a^{2} \cos ^{2} x+b^{2} \sin ^{2} x+c\right) d x, \textrm{ where } c\geq 0.
$$
Using my post, we have
$$
I(c)=\pi \ln \left(\frac{\sqrt{a^{2}+c}+\sqrt{b^{2}+c}}{2}\right)
$$
Differentiating $I(c)$ w.r.t. $c$ yields
$$
I^{\prime}(c)=\frac{\pi}{2 \sqrt{\left(a^{2}+c\right)\left(b^{2}+c\right)}}
$$
Once more gives
$$
I^{\prime \prime}(c)=-\frac{\pi}{4\left[\left(a^{2}+c\right)\left(b^{2}+c\right)\right]^{\frac{3}{2}}\left(2 c+a^{2}+b^{2}\right)}
$$
Hence
$$
\boxed{\int_{0}^{\frac{\pi}{2}} \frac{d x}{\left(a^{2} \cos ^{2} x+b^{2} \sin ^{2} x+c\right)^{2}}= \frac{\pi\left(2 c+a^{2}+b^{2}\right)}{4\left[\left(a^{2}+c\right)\left(b^{2}+c\right)\right]^{\frac{1}{2}}}}
$$
Putting $c=0$ yields the result
$$\boxed{\int_{0}^{\frac{\pi}{2}} \frac{d x}{\left(a^{2} \cos ^{2} x+b^{2} \sin ^{2} x+c\right)^{2}}= \frac{\pi\left(a^{2}+b^{2}\right)}{4 a^{3} b^{3}} }$$
Furthermore, in general,
$$
\boxed{\int_{0}^{\frac{\pi}{2}} \frac{d x}{\left(a^{2} \cos ^{2} x+b^{2} \sin ^{2} x+c\right)^{n}}=\frac{(-1)^{n} \pi}{2(n-1) !} \frac{d^{n-1}}{d c^{n-1}}\left[\left(a^{2}+c\right)\left(b^{2}+c\right) \right] ^{-\frac{1}{2}}}
$$


I need "intuition" about fraction exponents, like $4^{1.2}$. What exactly is it meant to do with number $4$?

Question: $4^3$ is $4\cdot 4\cdot 4$
Then $4^{1.2}$ is what, $4\cdot\dotso$??
What happens to the number with a fraction exponent when we try to represent it only using numbers and basic operations (like $+$, $-$, $\div$, and $\cdot$)?
$4^{1.2} = 4*4^{0.2}$; but there's still a fractional exponent, $0.2$, there. I can't represent $4^{1.2}$ only using basic operations.

Is there a way to do that? Is it impossible fundamentally in math, or is it possible using imaginary numbers?

i checked answers form this 8 year old question but it's not giving the answer i'm looking for.
Comment: Write $1.2$ as a fraction. It is $1.2=6/5$. Then $4^{1.2}=4^{6/5}=\sqrt[5]{4^6}$.
Comment: $$4^1 = 4$$
$$4^2 = 4 \cdot 4$$
$$4^{1.5} = 4 \cdot 4\hspace{-1.mm}{\Large\color{white}\blacksquare}$$
$$4^{1.2} = 4 \cdot 4\hspace{-1.7mm}{\Large\color{white}\blacksquare}$$
etc.
Comment: interesting: the answers here are better than the answers in the post of w/c this post is supposedly a duplicate
Comment: @Jeel: You can't think of $4^{0.2}$ in terms of repeated multiplication. It's just a number that obeys the exponent law $4^a \times 4^b = 4^{a+b}$. Using this law, we can show that $4^{0.2}$ is the fifth-root of $4$.
Comment: Piggybacking off @Cornman's comment $4^{1.2}=\sqrt[5]{4^6}$ is defined to be the positive real number that, multiplied by itself five times, gives $4^6$.
Comment: @Cornman 5√4 = 4^1/5 = 4^0.2. this is not what i want, you just used some math syntax/symbol to represent 0.5th exponent. What i want is to represent 4^0.2 as some --->>> (whole number)^(optional - whole number)/(some whole number)^(optional - whole number)
Comment: I do not think that I understand what you are trying to do, or why you want to take that restriction, but it might not be possible. Maybe expressing it how you want it, and then taking a limit, but I do not see the point in doing that.
Comment: The only numbers that can be represented using whole numbers, $+, -, \div, \cdot$, (and we can even throw in integer exponents) are rational. $4^{1.2}$ is irrational (as tends to be the case for integers to fractional powers). If you allow log and antilog as basic operations, $4^{1.2} = antilog(1.2 \cdot \log(4))$
Comment: @Jeel: "(whole number)^(optional - whole number)/(some whole number)^(optional - whole number)" is a rational number. $4^{1/5}$ is not a rational number. What you want is impossible.
Comment: $4^{1.2}$ is the answer to the question: if a quantity is growing exponentially so that it quadruples every $10$ years, then what does it do in a $12$ year period? Answer: it multiplies by a factor of $4^{1.2}$. An easier example that you can figure out without a calculator: Over a $5$ year period that same quantity would multiply by a factor of $4^{0.5}=\sqrt4=2$. That makes sense: doubles in $5$ years, quadruples in $10$ years. Right?
Comment: @bof This [link](https://math.stackexchange.com/questions/250459/whats-the-intuition-behind-non-integer-exponents-powers) doesn't provide the appropriate answer i'm looking for but the question is quite same like "What's real world object equivalent of 4^1.2 or something like that...", Thanks for providing me this 8 yr old question link though.
Comment: @Cornman what if you have an irrational exponent?
Answer: Before trying to answer the question you asked let's look at another.
Clearly you know what
$$
4 \times 3
$$
means. After all; multiplication is just repeated addition, so
$$
4 \times 3 = 4 + 4 + 4 = 12.
$$
But what in the world is
$$
4 \times 1.2 ?
$$
You can't add $4$ to itself $1.2$ times. You have to extend the definition of multiplication to allow for multiplying by a fraction like $1.2 = 6/5$. That's just what you learned about in elementary  school when you struggled with fractions. Understanding exactly what $4 \times \sqrt{2}$ or $4 \times \pi$ mean is even subtler. You probably just did this with decimal approximations.
Now to your question. In order to understand $4^{1.2}$ you have to extend the definition of exponentiation. You can't just think of it as repeated multiplication. Doing that is subtle. It starts with thinking about the one half power and seeing why you want $9^{1/2}$ to be $3 = \sqrt{9}$. That's what the other answers are trying to tell you. There is no way to do it  with the kind of expression you ask for in a comment.

(whole number)^(optional - whole number)/(some whole
number)^(optional - whole number)

The best I can do for you is to think about
$$
4^{1.2} = 4 \times 4^{1/5}.
$$
Now  $4^{1/5}$ is some number. Call it $z$. Clearly $z$ is not just "$20\%$ of $4$". Whatever value $z$ is must satisfy
$$
z^5 = (4^{1/5})^5 = 4
$$
so $z$ is the fifth root of $4$, or $\sqrt[5]{4}$.
$$
$$
Comment: On logarithmic paper, $z$ is clearly 20% of 4. :D
Comment: I'm surprised no one has said this. $$1.2×4=4×1.2=1.2+1.2+1.2+1.2$$ This means, $4$ times the sum of $1.2$.
Comment: @lonestudent True. But you can't do $(1/2)\times(1/3)$ if you think of multiplication only as repeated addition.
Comment: That "$32.98\%(4)$" is just wrong, so I can't elaborate on it. I will do the best I can in the answer - but then don't ask for "more elaboration".
Comment: I got what you are saying, so here's my another question... 4*1.2 = 4 + 20%(4), 4*3.7 = (4+4+4)+ 70%(4). So i understand about the fraction multiplication. While fraction exponents looks strange. Like 4^1.2 = 4 * 32.98%(4). And the percent number looks strange number. What it is saying can you elaborate on it please.
Comment: Sure. Therefore, I expected both factors not to be integers in your answer..
Comment: @lonestudent I think that level of generality would have made it harder for the OP to follow the part of the argument that matters.
Answer: I'm going to assume you're only referring to rational powers here. Not sure if this is what you're looking for, but I think of it as an inverse operation to give you something resembling the repeated multiplication form you are looking for.
For instance, if you're trying to find the square root of $4$, you're trying to solve the following equation:
$$x=4^{0.5};$$
so instead of $4\times 4\times\cdots$ for some number of times, you're looking at $x\times x=4$. For any rational power $r=p/q$, you're solving two things:

The first is the $p$-th power, or $4\times 4\times \cdots$ for $p$ times; say this value is $k$.
Then $x\times x \times \cdots$ for $q$ times and equate that with $k$.
Answer: I think graphing the exponential function will help you come to an intuitive understanding of it.
So here's a plot of $y = 4^x$ for $x = [0, 4]$:

But how do we fill in the values in-between these whole number exponents?
Well let's try plotting some other exponential functions. Here's $y = 2^x$:

You might not be able to tell just from looking, but it's the same shape. All of the points on the first plot are there on the second plot. $4^4 = 2^8 = 256$.
We might now guess that $4^{1.5} = 4^{3/2} = 2^3$, and indeed, that's true, both equal 8. We can fill in the plot for 0.5, 1.5, 2.5 and 3.5:

Unfortunately it's not as simple as $a^{b/c} = (a/c)^b$, instead the rule works out to be
$$a^{b/c} = \sqrt[c]{a^b}$$
So it's a little more complicated to work out, but the exponential function is continuous, and all the intermediate values can be calculated. And very occasionally, they work out to be integers too. But I hope this has given you a bit of intuition into how fractional exponents work.
Answer: Seems intuitive that $p:=4^{1.2}$ should lie somewhere between $4^1=4$ and $4^2=16$. But where ?
To answer this in a consistent way only relying on integer powers, we make three remarks:

for any number $q$ and naturals $m,n$, $(q^m)^n=q^{mn}$ is always true;

it does not seem unreasonable to generalize to $m,n$ not integers;

accepting this rule, $p^5=(4^{1.2})^5=4^6=4096.$

Now we have to solve the equation
$$p^5=4096,$$ which we can do by trial and error.
For instance, we can write
$$4^5=1024,5^5=3125,6^5=7776,$$ and $p$ should lie between $5$ and $6$.
Then we refine by introducing decimals,
$$5^5=3125,5.1^5=3450.25251,5.2^5=3802.04032,5.3^5=4181.95493$$
and $p$ should lie between $5.2$ and $5.3$.
Continuing this search, we obtain (after very very lengthy computation)
$$p=5.2780316430915770374960078849186\cdots$$
It is possible to show that this number has infinitely many decimals, which never repeat periodically. It is said to be irrational. By means of this trick, we can in principle raise any number to a power that is a fraction. We can also raise to an irrational power by using a close rational approximation of that power.

In practice, computing arbitrary powers is made easy by means of the so-called logarithms and antilogarithms, using the formula
$$a^b=\text{antilog}(\log(a)\cdot b)$$
where $\log$ and $\text{antilog}$ denote two special functions that can be computed efficiently or tabulated. Observe that taking a power is now replaced by two function evaluations and a product.
(Historically, logarithms were introduced to ease the computation of products by hand, using $$a\cdot b=\text{antilog}(\log(a)+\log(b))$$ which trades a multiplication for an addition.)
Answer:
Let $a\geq0,$ and $m,n$ be positive integers.
Then, by    definition, $a^\frac mn$ equals $(a^\frac1n)^m.$

$a^\frac1n$ refers to the set of the $n$th roots of $a.$
While every $n$th root is an algebraic number, most are not rational.

This plot represents $4^{0.2}=4^\frac15$ on the complex plane:

Here, only the rightmost number (orange dot) is real. Its value $\approx1.32$ equals the circle's radius.   It is typically denoted by
$\sqrt[5]4,$ and is an irrational number, i.e., it cannot be expressed as the ratio of two integers, and as such is not expressible by merely dividing  (and/or adding, subtracting, multiplying) whole numbers.
Comment: how you come up with the graph? can you explain how to draw it so that i can clearly understand your answer...
Comment: @Jeel Every positive number $a$ has two complex square roots, three complex cube roots, five complex fifth roots, and so on. Each set of $n$th roots of $a$ lie on a circle of radius $\sqrt[n]a$ on the complex plane such that the positive root $\sqrt[n]a$ lies on the positive real axis and the resultant sectors each has angle $\frac{360^{\circ}}n.$  This portion of my above answer is peripheral to its main point (the final sentence) though.


File Encryption and Decryption using a given key

Question: I have a problem for school and I can't seem to figure it out. Basically, i'm in an intro to object oriented programming class, so I only need to complete this as basic as possible without using anything fancy that I haven't learned yet. Currently learning about dictionaries and sets, I need to use a dictionary that has a code written in it to encrypt a document that has a long string on one line.
So I need one part to read the dictionary and open the text file containing the string.
"The course Introduction to Object Oriented Programming uses the Python programming language."
I need to then use the code from this dictionary to encrypt it and write the encrypted version of the string to another text file called encrypt.txt.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
    'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
    'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '@', 'i': '2',
    'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
    'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
    'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
    'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
    'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
    'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
    '@': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
    '%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
    '*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
    ':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
    "'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
    '{': '[', '[': '{', '}': ']', ']': '}'}

This is the code I have so far. Any help would be greatly appreciated and an explanation in layman's terms would also be greatly appreciated.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
    'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
    'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '@', 'i': '2',
    'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
    'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
    'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
    'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
    'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
    'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
    '@': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
    '%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
    '*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
    ':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
    "'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
    '{': '[', '[': '{', '}': ']', ']': '}'}

def main():
    #Open the file you want to encrypt.
    infile = str(input('Enter the name of the input file: '))
    #read its contents
    dtext = open(infile, 'r')
    #read the line from the file
    dtext = dtext.readlines()

    #strip the newline
    #dtext = dtext.rstrip('\n')

    #call the encryptText function
    encryptText(dtext)

def encryptText(dtext):
    #enter the name of the file to write to
    outfile = str(input('Enter the name of the output file: '))
    #open the file to send encrypted text to
    etext = open(outfile, 'w')
    #set accumulator value
    count = 0
    #create a for loop to read each separate character
    for line in dtext:
        wordList = line.split()
        print(dtext, CODE[dtext])
    count += 1

main()

Comment: What went wrong? I got `TypeError: unhashable type: 'list'` ... is that what you see?
Comment: Yeah, but I think I figured out that part, but now i'm getting a new error... KeyError: ' '
Comment: In my soltion I used `dict.get(c,c)` which tries to get the mapped c but otherwise passes the original through. For ascii text, it not encode things like tabs and newlines.
Comment: Side-note: This is a *perfect* case for `str.translate`. Just preprocess `CODE = str.maketrans(CODE)` (to fix up the key definitions), then converting through your table is just `cipher = plain.translate(CODE)`.
Answer: Strings are immutable. That means you cannot edit them after creation, in direct contrast to arrays. You will have to build a new string in order to encrypt your text. You will also likely need to do this one character at a time. Since you have the text of the file in dtext as a string, you can loop through the chars in the original string like so:
for i in range (0, len(dtext)):
    # add new character to string

(I'm breaking this apart so you cannot just copy and paste)
You must create a new string to put the encrypted text in outside of that for loop.
enc = ""

In order to encrypt the value by making a substitution you can add character one at a time to the encrypted string in that for loop if they are in the dictionary you defined. Something to the effect of
if (dtext[i] in CODE.keys()):
    enc += CODE[dtext[i]]

Then write the new string to a file and you're good to go.
A dictionary in python is effectively an array that is indexable by a key. This key maps to a given value just like an array index maps to some value. See https://www.tutorialspoint.com/python/python_dictionary.htm for more details.
Comment: Ahhh, I think I understand that! I will try and see if I can get it now. I was using this and started to get somewhere, but your method makes more sense.                              for line in dtext:
                                              for ch in line:
                                                   print(ch, CODE[ch])
Answer: You need to encrypt character by character and you need to take the result and build it back into a string. str.join turns a sequence of characters into a string and a generator can be written to encrypt each character... put them together and you have your solution.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
    'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
    'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '@', 'i': '2',
    'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
    'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
    'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
    'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
    'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
    'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
    '@': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
    '%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
    '*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
    ':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
    "'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
    '{': '[', '[': '{', '}': ']', ']': '}'}

def main():
    #Open the file you want to encrypt.
    infile = str(input('Enter the name of the input file: '))
    #read its contents
    dtext = open(infile, 'r')
    #read the line from the file
    dtext = dtext.readlines()

    #strip the newline
    #dtext = dtext.rstrip('\n')

    #call the encryptText function
    encryptText(dtext)

def encryptText(dtext):
    #enter the name of the file to write to
    outfile = str(input('Enter the name of the output file: '))
    #open the file to send encrypted text to
    etext = open(outfile, 'w')
    #set accumulator value

    #create a for loop to read each separate character
    for line in dtext:
        # encrypt character by character then join to a string
        encrypted = ''.join(CODE.get(c, c) for c in line)
        print(repr(line), repr(encrypted))
        etext.write(encrypted)
    etext.close()

main()

Comment: For the record, given this appears to be Python 3, you could simplify dramatically. After defining `CODE`, add the line `CODE = str.maketrans(CODE)` to convert it to a `str.translate` friendly `dict`, then replace the genexpr and `join` with just `encrypted = line.translate(CODE)`. Should be *much* faster, and you're using the most straightforward tool for the job.
Comment: @ShadowRanger - I agree there are better ways and ways this code could be cleaner but since this is for a newbie programming class, I wanted to disturb it as little as possible. If I was teaching a beginner class and got your solution I'd consider an F for cheating!
Comment: Really? I mean, if you look up `str` methods, `str.translate` is basically describing how you'd use a `dict` of exactly the form given (well, okay, it needs to be fixed up by `maketrans` to use the ordinals as keys, but close enough). It's actually more likely to be found by a newbie looking blindly than by a moderately experienced programmer who already knows "the right way to do it" but never encountered that specific method before.
Comment: I'm with tdelaney, I'm trying to to keep it as simple as possible because we haven't learned that much yet. As I do really appreciate learning more than i'm being taught, I need to learn it the easiest way possible at first for these labs! don't want to cheat haha
Comment: But your code worked tdelaney, except I don't think I have learned how to use join yet which is the only problem.
Comment: @DillonFornaro - shadowranger has a point. Python has a robust help system and part of learning is learning how to use it. `help(str)` is an interesting read.
Comment: If you were able to get it to work in a way you understand use that. Your take on playing safe for your class is a good choice.
Answer: tdelaney's answer was correct, but I took it and made it a more simpler version. I changed it a bit. This is what I did:
Instead of joining to an empty string, I just removed that part completely. I just iterated over the entire string character by character and then as tdelaney did, used the get method to use the key in the code dictionary.
CODE = {'A': ')', 'a': '0', 'B': '(', 'b': '9', 'C': '*', 'c': '8',
    'D': '&', 'd': '7', 'E': '^', 'e': '6', 'F': '%', 'f': '5',
    'G': '$', 'g': '4', 'H': '#', 'h': '3', 'I': '@', 'i': '2',
    'J': '!', 'j': '1', 'K': 'Z', 'k': 'z', 'L': 'Y', 'l': 'y',
    'M': 'X', 'm': 'x', 'N': 'W', 'n': 'w', 'O': 'V', 'o': 'v',
    'P': 'U', 'p': 'u', 'Q': 'T', 'q': 't', 'R': 'S', 'r': 's',
    'S': 'R', 's': 'r', 'T': 'Q', 't': 'q', 'U': 'P', 'u': 'p',
    'V': 'O', 'v': 'o', 'W': 'N', 'w': 'n', 'X': 'M', 'x': 'm',
    'Y': 'L', 'y': 'l', 'Z': 'K', 'z': 'k', '!': 'J', '1': 'j',
    '@': 'I', '2': 'i', '#': 'H', '3': 'h', '$': 'G', '4': 'g',
    '%': 'F', '5': 'f', '^': 'E', '6': 'e', '&': 'D', '7': 'd',
    '*': 'C', '8': 'c', '(': 'B', '9': 'b', ')': 'A', '0': 'a',
    ':': ',', ',': ':', '?': '.', '.': '?', '<': '>', '>': '<',
    "'": '"', '"': "'", '+': '-', '-': '+', '=': ';', ';': '=',
    '{': '[', '[': '{', '}': ']', ']': '}'}

def main():
    #Open the file you want to encrypt.
    infile = str(input('Enter the name of the input file: '))
    #read its contents
    dtext = open(infile, 'r')
    #read the line from the file
    dtext = dtext.readlines()

    #call the encryptText function
    encryptText(dtext)

def encryptText(dtext):
    #enter the name of the file to write to
    outfile = str(input('Enter the name of the output file: '))
    #open the file to send encrypted text to
    etext = open(outfile, 'w')
    #create a for loop to read each separate character
    for line in dtext:
        # encrypt character by character then join to a string
        for c in line:
            encrypted = (CODE.get(c, c))
            etext.write(encrypted)
    #close the file
    etext.close()

main()

Comment: Just so you know, it's not convention to answer your own question. The last time i did, i was heavily downvoted and lost quite a bit of rep. I'm not going to do anything about it, b/c i think it makes sense. I thought i'd warn you though.
Comment: Oh really? Sorry, I'm new to all of this and this website. I appreciate the feedback though.
Comment: @thedevelop3r It's perfectly fine to answer your own question. You only need to understand that it needs to be a full answer to the question asked. That includes some code and a description of what was wrong. Also, copying somebody else's answer is also a no-go.
Comment: @Classicalclown Please try to be more careful about how you post code. I indented your code properly, but you will have to learn how to do it yourself like marking the code in question and hitting Ctrl+K. Also, you can edit your own answer. You don't have to delete an answer and post a new one.
Comment: Why was i down voted for answering my question on decreasing tripples then? Was it b/c i answered it as if i wasn't the ome who asked it? http://stackoverflow.com/q/36818054/3281844


confusion matrix - how to determine values of TN and FN

Question: Given is a problem statement -
Let there be 10 balls of which 6 are white and 4 are red. Let it be required to pick up the red balls from them. Suppose, we pick up 7 balls as the red balls of which only 2 are actually red balls. What are the values of precision and recall in picking red balls?
For the given problem, in the solution I found at the confusion matrix values are given accordingly:
TP = 2, FP = 5, FN = 2, TN = 1
I understand how TP and FP are the values mentioned above, but can someone explain how FN and TN is 2 and 1 respectively?
Comment: $1$ of the remaining balls left are white ($TN$), and $2$ of the remaining balls are red ($FN$)
Answer: Total $10$ balls
Predicted $7$ balls are red ($TP+FP$), $2$ are actually red ($TP$), $5$ are not red ($FP$)
This implies that $3$ were predicted to be not red ($TN+FN$), $1$ is actually not red ($TN$), $2$ are red ($FN$).
$recall=\frac{TP}{TP+FP}=\frac{2}{7}$
$precision=\frac{TP}{TP+FN}=\frac{2}{2+2}=0.5$
Answer: The question states that $7$ balls are chosen as red balls, implying that it predicted $3$ as not red. Furthermore, the question states that there are actually $2$ red balls among the predicted red balls. This means that one of the balls is white and the other $2$ are red among the three predicted as not red. This means that just one of the three balls predicted to be not red is truly not red, so $TN=1$, and likewise, the other $2$ red balls are falsely predicted to be red, so $FN=2$.
Thus $TP = 2, FP = 5, TN = 2,$ and $FN = 2$.

Precision $= \dfrac{TP}{TP + FP}= \dfrac{2}{ 7}= 0.28$
Recall $= \dfrac{TP}{TP+FN} =\dfrac 24 = 0.5$


$P = I − uu^T$ when $u$ is a normalized vector (subtraction of scalar from matrix)

Question: I have a vector $u$ that is normalized (i.e., $||u||_2=1)$. This means that
$$
uu^T = ||u||_2^2 = 1
$$
Does it make sense to define $P=I-uu^T$ given that $uu^T$ is a scalar.
What does it mean to subtract a scalar from a matrix?
Comment: The usual convention is that $u^T u$ is a scalar, $uu^T$ is an $n \times n$ matrix with components $u_i u_j$.
Comment: If you did mean $P = I - u^T u$, then a "matrix minus a scalar" really intends for that scalar to be multiplying the appropriate identity matrix, so $P = I - u^T u = I - u^T u I = (1- u^T u)I$.
Answer: $uu^T$ is a matrix. Looks like you've confused it with $u^Tu$, which is scalar.
Answer: If $u$ is a column vector with $n$ columns, then $\|u\|^2_2=u^Tu$, but $$uu^T = \begin{pmatrix}u_1\\u_2\\ \vdots\\ u_n\end{pmatrix}\begin{pmatrix}u_1&u_2& \dots& u_n\end{pmatrix}$$ is a matrix whose $ij-$th entry is $u_iu_j$.
Consequently, $I-uu^T$ has $1-u_i^2$ on the diagonal and $-u_iu_j$ as $ij$-th entry if $i\neq j$.


Homework question: Let $\psi$ be a binary predicate. Prove ⊢ $(\forall x)(\forall y)\psi(x, y) \rightarrow (\forall y)\psi(y, y) $

Question: I know I can use deduction theorem to make the formula into: $(\forall x)(\forall y)\psi(x, y) ⊢ (\forall y)\psi(y, y)$ which can also be written as $(\forall x)(\forall y)\psi(x, y) \iff (\forall y)ψ(y, y)$. For my hypothesis, I can use the left-hand side:
1) $(\forall x)(\forall y)\psi(x, y)$ (hyp)
But I don't know how to proceed from the hypothesis to get the proof. Any help is appreciated.
Comment: Intuitively, this should be pretty straightforward, since for $x$ and $y$ you just pick the very same object.  However, what an actual formal proof for this looks like depends on exactly what rules were given to you. Can you post those?
Comment: @Bram28 No rules were given other than to use a Hilbert style or equation proof. I posted a picture with some logic rules and such for some help.
Comment: Hmm, those are all propositional logic rules, and what you need here are rules involving quantifiers.  You weren't even given any example proofs?
Comment: @Bram28 Unfourtanetly not. Other than knowing the obvious which is the negation of ∀ or ∃ yields the opposite symbol.
Comment: Well, that stinks!  OK, I did post a proof as an Answer. It's a proof in the Fitch system ... not sure if that works for you ....
Comment: @Bram28 I'll take what I can get and verify it. Thanks.
Comment: Clearly, your textbook have also axioms and rules for quantifiers; otherwise how do you think to address problems with them ?
Comment: We need at least $(\forall x) A \to  A[x := t]$ (see page 139) followed by the **Generalization Th** (page 155).
Answer: $\def\fitch#1#2{\begin{array}{|l}#1 \\ \hline #2\end{array}}$
$\fitch{
\forall x \forall y \ \psi(x,y)}{
\fitch{
a}{
\forall y \ \psi(a,y)\\
\psi(a,a)} \\
\forall y \ \psi(y,y)}$


How to detect deletion of image in UITextView

Question: If I add an image into a UITextView like this:
NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
textAttachment.image = image;

NSAttributedString *attrStringWithImage = [NSAttributedString attributedStringWithAttachment:textAttachment];
[myString appendAttributedString:attrStringWithImage];

self.inputTextView.attributedText = myString;

How can I then later detect that the image has been deleted via the user hitting the back button on the keyboard?
Would I use the below?
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text

If so, how?
Answer: I did this:
- (BOOL)textView:(UITextView *)textView shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
[self.textView.attributedText enumerateAttribute:NSAttachmentAttributeName
                        inRange:NSMakeRange(0, self.textView.attributedText.length)
                        options:0
                     usingBlock:^(id value, NSRange imageRange, BOOL *stop){
     if (NSEqualRanges(range, imageRange) && [text isEqualToString:@""]){
         //Wants to delete attached image
     }else{
         //Wants to delete text
     }

  }];
return YES;
}

Hope, can help you!
Answer: Using swift, here's how I removed images (added as NSTextAttachment) from UITextView:
func textView(textView: UITextView, shouldChangeTextInRange range: NSRange, replacementText text: String) -> Bool {

    // empty text means backspace
    if text.isEmpty {
        textView.attributedText.enumerateAttribute(NSAttachmentAttributeName, inRange: NSMakeRange(0, textView.attributedText.length), options: NSAttributedStringEnumerationOptions(rawValue: 0)) { [weak self] (object, imageRange, stop) in

            if NSEqualRanges(range, imageRange) {
                self?.attributedText.replaceCharactersInRange(imageRange, withString: "")
            }
        }
    }

    return true
}


Is it safe to cache Gmail API message results?

Question: I am iterating over a Gmail account with many thousands of messages. To save resources I am caching the results of users.messages.get. Is it safe to cache this data indefinitely? Will the data it returns ever change? I assume that it will not but so far I am unable to find anything definitive in the docs or otherwise to confirm this.
Answer: It can change - though it might not necessarily change in a way that you care about.
The API itself lets you change the labels on a Message and delete messages.
Comment: Thanks - I overlooked that. Since my application queries based the message id, you're correct in your suspicion that I only concerned about the message content in this case.


Deleting a row based on a float column in Mysql/PHP?

Question: This
DELETE FROM `z_ratings`
WHERE `score` = '5.4'
  AND `media_id` = '242'
  AND `user_id` = '1'

will not delete the following row:

Can anybody explain why?
(I'm assuming the issue is with the float since both other columns are integers)
Comment: @Abdulla This is the query generated by active records in Codeigniter though. I'll check if there is a way to remove those single quotes
Comment: Can you switch type to decimal? http://stackoverflow.com/questions/2567434
Comment: Share table  `z_ratings` creation script
Comment: @lad2025 user_id INT, media_id INT, score FLOAT
Answer: The problem is the floating point column.  You can review the issues with this representation and comparisons.  One place to start is the documentation.
Great, we know it doesn't work.  More importantly, what can you do?
Probably the most accurate solution is to switch to decimal, say decimal(5, 1) for the column.  Then, this shouldn't be a problem.
Alternatively, use abs() and difference for a fuzzy comparison:
abs(score - 3.4) < 0.0001

Comment: Looks like this is the issue. I'm going to see if that works.
Comment: @gordon-lindoff and that is in fact correct. thanks for the help


ManyToMany jpa - Spring Salvar dados entidade de relacionamento

Question: Boa noite galera!
Tenho 2 classes: Serviços e Pedido.
Serviços contem nome e valor/hora.
Pedido contem  os atributos: valorBruto, valorLiquido, percentualImposto , usuario e uma lista de serviços.
fiz uma relação many to many gerando uma 3° tabela pedido_servicos;
estou fazendo com base nesse exercicio:

O sistema deverá ter uma página para cadastramento dos Serviços (nome do serviço e valor de hora para venda);
O sistema deverá ter uma página para cadastramento do Pedido de Serviço, onde deverá ser informado: (s) serviço(s) a ser(em) comercializado(s); quantidade de horas de cada serviço;
O profissional que será alocado para execução desse Pedido de Serviço;
O % de imposto da venda que será adicionado ao valor final do pedido.
Ao salvar o Pedido, exibir em uma caixa de diálogo mostrando o valor total do pedido e o % de lucro desse pedido para a empresa.

a dúvida é, como faço para adicionar mais campos na tabela pedido_servicos para pesistir quando salvar um pedido?
Exemplo: objeto que imagino pra salvar é parecido com algo assim:
<code>{
   valorBruto: 50,
   valorLiquido: 40,
   percentualImposto: 10,
   usuario: "teste",
   imposto: 10,
   servicos: [{
        idServico: 1,
        qtdHora: 40
   }]
}
</code>
O problema é que quando tento salvar o pedido, ele tenta salvar o relacionamento pedido_servico que tem o atributo qtde_hora e esta nulo e ocorre o erro.
Segue o código das classes.
Pedido
<code>@Data
@Entity
@Table(name = "pedido")
public class Pedido {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_pedido")
    private Long idPedido;
    @Column(name = "valor_total_bruto", nullable = false)
    private double valorTotalBruto;
    @Column(name = "valor_total_liquido", nullable = false)
    private double valorTotalLiquido;
    @Column(name = "perc_imposto", nullable = false)
    private double percentualImposto;
    @Column(name = "usuario", length = 100, nullable = false)
    private String usuario;

    @ManyToMany
    @JoinTable(name = "pedido_servico", joinColumns = { @JoinColumn(name = "id_pedido") },
         inverseJoinColumns = {@JoinColumn(name = "id_servico") })
    private List<Servico> servicos;
}
</code>
Serviço
<code>@Data
@Entity
@Table(name = "servico")
public class Servico {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_servico")
    private long idServico;
    @Column(name = "nome_servico", length = 100, nullable = false)
    private String nomeServico;
    @Column(name = "valor_hora", nullable = false)
    private double valorHora;
}
</code>
PedidoServico
<code>@Data
@Entity
@Table(name = "pedido_servico")
public class PedidoServico {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(name = "id_pedido_servico")
    private long idPedidoServico;
    @Column(name = "qtd_hora", nullable = false)
    private int qtdHora;
    @Column(name = "id_servico", nullable = false)
    private long idServico;
}
</code>
Answer: Boa noite Fabio ! Pelo que entendi do problema neste caso você não precisa desta terceira classe "PedidoServico". Outra detalhe no caso seria um pedido ter varios serviço ne ? no caso deve usar o @OneToMany
<code>@OneToMany
@JoinColumn(name="servicos_id", nullable=false)
private List<Servico> servicos;
</code>
Um ultimo detalhe na classe Serviços o campo nomeServiço esta como nulllable=false, então você deve passar um valor, ou alterar para nullable=true
Comment: Opa Renan, muito obrigado pela resposta, no fim era exatamente isso, obrigado mesmo :D


How to set and keep language syntax type on .babelrc file

Question: In Atom 1.18 every time I open the editor my .babelrc file defaults to the JSON file type, which makes syntax highlighting look way off. And I have to keep changing it back to the Babel type.

How to fix (temporarily):

Have to reset it every time I close and open the .babelrc file.
Now I realize this is a file that will be rarely touched, but would be helpful to know how to fix this for other file type.
Answer: There is a very specific way to set this up in the config.cson
https://discuss.atom.io/t/how-do-i-make-atom-recognize-a-file-with-extension-x-as-language-y/26539
http://flight-manual.atom.io/using-atom/sections/basic-customization/#configuring-with-cson
"*":
  core:
    customFileTypes:
      "source.js.jsx": [
        "js"
        "es6"
        "es"
        "babel"
        "babelrc"
        "jsx"
      ]

Answer: The way I removed these errors was to just make the file JSON compatible.
Not the perfect solution but works.
//.babelrc
{
  "plugins": [
    "transform-class-properties"
  ],
  "presets": [
    ["es2015", { "modules": false}],
    "react",
  ],
}