The Intergral of $\sin^4x$ without using reduction formula

Question: So I've been trying to compute $$\int\sin^4(x)\mathrm{d}x$$ and everywhere they use the reduction formula which we haven't learned yet so I've been wondering if theres another way to do it? Thanks in advance.
Comment: @Sebastiano Why?  What possible purpose could that serve?
Comment: are you familiar with integration by parts?
Comment: Unless the curriculum is very, very different in other parts of the world, the "reduction formula" is a basic trigonometric identity which you should have learned in a precalculus class long before ever enrolling in calculus.
Comment: Currently, it is not clear what "the reduction formula" in your question refers to. Please edit your question to be more precise about what it is.
Answer: Performing integration by parts,
$\begin{align} \int_0^x\sin^2 t\,dt&=\Big[-\cos t\sin t\Big]_0^x+\int_0^x\cos^2 t\,dt\\
&=-\cos x\sin x+\int_0^x(1-\sin^2 t)\,dt\\
&=-\cos x\sin x+\int_0^x 1\,dt-\int_0^x \sin^2 t\,dt\\
&=-\cos x\sin x+x-\int_0^x \sin^2 t\,dt\\
\end{align}$
Therefore,
$\displaystyle \int_0^x \sin^2 t\,dt=-\frac{1}{2}\cos x\sin x+\frac{1}{2}x$
$\begin{align} \int_0^x\sin^4 t\,dt&=\int_0^x(1-\cos^2)\sin^2 t\,dt
\\
&=\int_0^x\sin^2 t\,dt-\int_0^x \cos^2 t\sin^2 t\,dt\\
&=-\frac{1}{2}\cos x\sin x+\frac{1}{2}x-\int_0^x \cos^2 t\sin^2 t\,dt\\
\end{align}$
Since, for $t$ real,
$\sin(2t)=2\sin t\cos t$
then,
$\begin{align}
\int_0^x\sin^4 t\,dt&=-\frac{1}{2}\cos x\sin x+\frac{1}{2}x-\frac{1}{4}\int_0^x \sin^2(2t)\,dt\\
\end{align}$
In the latter integral perform the change of variable $y=2t$,
$\begin{align}
\int_0^x\sin^4 t\,dt&=-\frac{1}{2}\cos x\sin x+\frac{1}{2}x-\frac{1}{8}\int_0^{2x} \sin^2(y)\,dy\\
&=-\frac{1}{2}\cos x\sin x+\frac{1}{2}x-\frac{1}{8}\left(-\frac{1}{2}\cos (2x)\sin(2x)+\frac{1}{2}\times 2x\right)\\
&=-\frac{1}{4}\sin(2x)+\frac{1}{2}x+\frac{1}{32}\sin(4x)-\frac{1}{8}x\\
&=-\frac{1}{4}\sin(2x)+\frac{3}{8}x+\frac{1}{32}\sin(4x)\\
\end{align}$
Therefore,
$\displaystyle \boxed{\int \sin^4 x\,dx=\frac{3}{8}x+\frac{1}{32}\sin(4x)-\frac{1}{4}\sin(2x)+C}$
($C$ a real constant)
Comment: This appears to be the only answer that actually does what the questioner asks and performs the computation without using a power reduction formula or using other advanced techniques (such as complex integration) which are likely unfamiliar to the OP.  Congratulations.
Comment: Thank you kindly <3
Answer: Use this $$\sin^2x = \frac{1-\cos (2x)}2 \implies \sin^4x = \left( \frac{1-\cos 2x}2 \right)^2=\frac{1+\cos^2 (2x) -2 \cos 2x}{4}$$
And then,
$$\cos^2 (2x)=\frac{1+\cos (4x) }{2}$$
Answer: An alternative way might be to use the fact that
$$\sin(x)=\frac{1}{2}i \left(e^{-ix}-e^{ix}\right)$$
$$\sin^4(x)=\frac{1}{16} \left(e^{-ix}-e^{ix}\right)^4$$
And you just need to expand and integrate it.
Comment: In my opinion, this is not just an alternative way, but the **definitive** way to do it, since it immediately explains all the coefficients of the terms.


database access to databases

Question: I have a drupal with many external databases. I do the same things in all databases but I want to limit the access to the database basing on the role the logged-in user has.
I mean:

The administration user has access to all databases
Employee has access to db1 and db2
Worker has access to db1

How can I control database access per role?
Comment: I guess you mean _by role_, not _by roll_.
Answer: If you mean controlling which database Drupal uses for its own database tables (e.g. the table containing all the registered users, the active sessions, the nodes created), then it is not possible. There is no way to tell Drupal which database use basing on the user's roles.
If you are asking about your own module, then it is possible, but your module needs to handle this on its own because Drupal doesn't have my specific functions to handle your use case, except the following ones:

user_has_role() checks the user account passed as argument (or the currently logged-in user) has the role passed as argument
db_set_active() set the database used from the successive database API calls using one of the keys set in the settings.php file

Rather than using db_set_active(), I would use $options['target'] which can be used from any Drupal function necessary to query the database.

database access to databases


Duplicate camera stream not working with custom frame width and height

Question: I have been able to duplicated my webcam stream on ubuntu with
 gst-launch-1.0 v4l2src device=/dev/video0 ! tee name=t ! queue ! v4l2sink device=/dev/video2 t. ! queue ! v4l2sink device=/dev/video3

Im able to launch 2 simultaneous streams by
gst-launch-1.0 v4l2src device=/dev/video2 ! videoconvert ! ximagesink
gst-launch-1.0 v4l2src device=/dev/video3 ! videoconvert ! ximagesink

But if I try to change streams width and height it doesnt work
gst-launch-1.0 v4l2src device=/dev/video2 ! 'video/x-raw, width=640,height=480,framerate=15/1' ! videoconvert ! ximagesink

Error ---
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
ERROR: from element /GstPipeline:pipeline0/GstV4l2Src:v4l2src0: Internal data stream error.
Additional debug info:
gstbasesrc.c(3055): gst_base_src_loop (): /GstPipeline:pipeline0/GstV4l2Src:v4l2src0:
streaming stopped, reason not-negotiated (-4)
ERROR: pipeline doesn't want to preroll.
Setting pipeline to PAUSED ...
Setting pipeline to READY ...
Setting pipeline to NULL ...
Freeing pipeline ...

Even this isnt working --
gst-launch-1.0 v4l2src device=/dev/video2 ! videoconvert ! videoscale ! video/x-raw, width=640,height=480,framerate=15/1  ! ximagesink -v

UPDATE
Its working now with this command, but only with framerate =30. If I change the framerate to anything else it just doesnt work at all
gst-launch-1.0 v4l2src device=/dev/video2 ! videoconvert ! videoscale ! video/x-raw, width=640,height=480, framerate=30/1  ! ximagesink -v
Setting pipeline to PAUSED ...
Pipeline is live and does not need PREROLL ...
Setting pipeline to PLAYING ...
New clock: GstSystemClock
/GstPipeline:pipeline0/GstV4l2Src:v4l2src0.GstPad:src: caps = video/x-raw, width=(int)800, height=(int)600, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/2147483647, format=(string)YUY2, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive
/GstPipeline:pipeline0/GstVideoConvert:videoconvert0.GstPad:src: caps = video/x-raw, width=(int)800, height=(int)600, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/2147483647, interlace-mode=(string)progressive, format=(string)BGRx
/GstPipeline:pipeline0/GstVideoScale:videoscale0.GstPad:src: caps = video/x-raw, width=(int)640, height=(int)480, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/1, interlace-mode=(string)progressive, format=(string)BGRx
/GstPipeline:pipeline0/GstCapsFilter:capsfilter0.GstPad:src: caps = video/x-raw, width=(int)640, height=(int)480, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/1, interlace-mode=(string)progressive, format=(string)BGRx
/GstPipeline:pipeline0/GstXImageSink:ximagesink0.GstPad:sink: caps = video/x-raw, width=(int)640, height=(int)480, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/1, interlace-mode=(string)progressive, format=(string)BGRx
/GstPipeline:pipeline0/GstCapsFilter:capsfilter0.GstPad:sink: caps = video/x-raw, width=(int)640, height=(int)480, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/1, interlace-mode=(string)progressive, format=(string)BGRx
/GstPipeline:pipeline0/GstVideoScale:videoscale0.GstPad:sink: caps = video/x-raw, width=(int)800, height=(int)600, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/2147483647, interlace-mode=(string)progressive, format=(string)BGRx
/GstPipeline:pipeline0/GstVideoConvert:videoconvert0.GstPad:sink: caps = video/x-raw, width=(int)800, height=(int)600, framerate=(fraction)30/1, pixel-aspect-ratio=(fraction)1/2147483647, format=(string)YUY2, colorimetry=(string)2:4:7:1, interlace-mode=(string)progressive

Comment: Could  you try `videorate` after `videoscale`?  `gst-launch-1.0 v4l2src device=/dev/video2 ! videoconvert ! videoscale ! videorate ! video/x-raw, width=640,height=480, framerate=15/1  ! ximagesink -v`
Answer: Internal data stream error appears when you pass wrong height, width or another cam parameter. Check cam resolution and framerate before you. One note, you cant change framerate by pass different value, cam have fixed set resolution and framerate, if you want change framerate use videorate.
Comment: Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


Android: Fragment stack confusion with ActionBar and Tabs

Question: I'm working on an App utilizing ActionBarSherlock with navigation tabs and multiple fragments.
I have three navigation tabs each with one or more child views. I also have three option menu items with one or more child views.  Everything works fine when I drill down the views within each Tab or option menu.  Each initial subview is a ListFragment that calls a detail view or views.
I run into problems when I start switching tabs while in the child views or the option menu fragment.  My views start to overlap with the previous view underneath the new view.
Here is my TabListener:
<code>class MyTabsListener implements ActionBar.TabListener {
public SherlockListFragment fragment;

public MyTabsListener(SherlockListFragment fragment) {
    this.fragment = fragment;
}

public void onTabSelected(ActionBar.Tab tab, FragmentTransaction ft) {
    ft.replace(android.R.id.content, fragment);
}

public void onTabUnselected(ActionBar.Tab tab, FragmentTransaction ft) {
    ft.remove(fragment);
}

public void onTabReselected(ActionBar.Tab tab, FragmentTransaction ft) {
    // Don't care if a tab is reselected, no special handling required
}
</code>
Here is my option menu:
<code>   @Override
public boolean onOptionsItemSelected(MenuItem item) {

    // initialize variables
    FragmentManager fm = null;
    FragmentTransaction ft = null;
    ActionBar actionBar = getSupportActionBar();

    // check to see which action item was selected
    switch (item.getItemId()) {
    case android.R.id.home:
        // initialize variables
        fm = this.getSupportFragmentManager();
        ft = fm.beginTransaction();

        if (fm.getBackStackEntryCount() > 0) {

            fm.popBackStack();
            ft.commit();
        }else {
            actionBar = getSupportActionBar();
            actionBar.setDisplayHomeAsUpEnabled(false);
        }
        return true;
    case R.id.menuitem_search:
        onSearchRequested();
        return true;
    case R.id.menuitem_contacts:
        ContactListFragment contactListFragment = new ContactListFragment();
        ft = getSupportFragmentManager().beginTransaction();
        ft.replace(android.R.id.content, contactListFragment);
        ft.addToBackStack(null);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();
        return true;
    case R.id.menuitem_isolation:
        ISOListFragment isoListFragment = new ISOListFragment();
        ft = getSupportFragmentManager().beginTransaction();
        ft.replace(android.R.id.content, isoListFragment);
        ft.addToBackStack(null);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();
        return true;
    case R.id.menuitem_water:
        H2OListFragment h2oListFragment = new H2OListFragment();
        ft = getSupportFragmentManager().beginTransaction();
        ft.replace(android.R.id.content, h2oListFragment);
        ft.addToBackStack(null);
        ft.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE);
        ft.commit();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}
</code>
I have one MainActivity for all of the fragments.  How do you handle the backstack when dealing with drill down child views and ActionBar navigation tabs??  Any help or suggestions would be greatly appreciated!
Comment: I am interested too. Have you worked it out?
Answer: Here is the solution that worked for me:
<code>@Override
public void onBackPressed() {

    // initialize variables
    FragmentManager fm = getSupportFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();

    // check to see if stack is empty
    if (fm.getBackStackEntryCount() > 0) {
        fm.popBackStack();
        ft.commit();
    }
    else {

        super.onBackPressed();
    }
    return;
}
</code>
Comment: But if you drill down in 1 tab menu and then switch to another and then press back... You'll end up navigation in a completely different way than the user expect.


Create new \score-like context/template in Lilypond

Question: My current project is to create a number of short snippets for doumbek.  To create each snippet, I use the following \score block:
\header { piece = "Name here" }  % different for each snippet
\score {
  \new DrumStaff \with {
    instrumentName = "doumbek"
    drumStyleTable = #timbales-style
    \override StaffSymbol.line-count = #2
    \override BarLine.bar-extent = #'(-1 . 1)
  } \drummode {
    \time 2/4  % music goes here
    timl8.-> ssh16 timl8-> ssl->  % the actual music
    \bar ":|."
  }
}
\markup { "Additional performance notes here" }  % only if needed

The complications with typing this are:

Copying all that for each snippet is unacceptably duplicative.
There are about 40 of these two-bar snippets in the project.
It's all the customization of the DrumStaff that adds the majority of the bloat.

After searching (and not finding) how exactly Lilypond internally defines \drums as \new DrumStaff \drummode (so I could define some kind of \DoumbekStaff), I found a way to define a Scheme function to generate the \score blocks I want.
My code now looks like:
% define the Scheme \score template
dscore =
#(define-scheme-function
  (title ts perf-notes music)
  (markup? fraction? markup? ly:music?)
  #{
    \header { piece = $title }
    \score {
      \new DrumStaff \with {
        instrumentName = "doumbek"
        drumStyleTable = #timbales-style
        \override StaffSymbol.line-count = #2
        \override BarLine.bar-extent = #'(-1 . 1)
      } \drummode {
        \time $ts
        $music
        \bar ":|."
      }
    }
    \markup { $perf-notes }
  #})

% the actual music
#(dscore
  "Ayoub"
  (2 . 4)
  ""
  #{
    \repeat percent 3 { timl8.-> ssh16 timl8-> ssl-> } |
    timl16-> ssh ssl-> ssh timl-> ssh ssl8-> |
  #}
)

Running this as written simply doesn't work.  Guile signals an error for the expression beginning with #(dscore because "Wrong number of arguments to 2".  Changing the time signature from 2/4 to 5/4 for testing changes the error to "Wrong number of arguments to 5", so the current problem is with the time signature.  fraction? is supposed to be a fraction represented by a pair but neither my (2 . 4) nor my (5 . 4) has been accepted.
Quoting the pair '(2 . 4) makes that error go away but then I am assaulted with numerous complaints that my \drummode notes are not, in fact, notes.  It seems to attempt to evaluate the music expression before expanding the dscore function and entering the \drummmode that is in the function.
Commenting out the drum music and replacing it with normal note name notation, like a2 b4 c, to see if it works at all gives me a fatal error of "unexpected \score, expecting end of input".
Finally, there are almost certainly numerous other mistakes in the above code.  Although the time signature being uncooperative is my current blocking issue, pointers about other mistakes I made would be much appreciated, as I cannot make any further progress until this template works.
Answer: First a little remark: You can call the scheme function directly by \dscore.
Then you need to enter your music in drummode, so you need to use \drummode in the argument instead of the score. Then your scheme function cannot return multiple objects, such as a score and a markup. Instead you should directly register these objects from your scheme function. Also the score header should go into the \score block, not in front of it.
This is a corrected version of your example:
% define the Scheme \score template
dscore =
#(define-scheme-function
  (title ts perf-notes music)
  (markup? fraction? markup? ly:music?)
  (let ((score
         #{
            \score {
              \header { piece = $title }
              \new DrumStaff \with {
                instrumentName = "doumbek"
                drumStyleTable = #timbales-style
                \override StaffSymbol.line-count = #2
                \override BarLine.bar-extent = #'(-1 . 1)
              } {
                \time $ts
                $music
                \bar ":|."
              }
            }
         #}))
    (add-score score)
    (add-text perf-notes)))

% the actual music
\dscore
  "Ayoub"
  #'(2 . 4)
  "test test test"
  \drummode {
    \repeat percent 3 { timl8.-> ssh16 timl8-> ssl-> } |
    timl16-> ssh ssl-> ssh timl-> ssh ssl8-> |
  }

EDIT:
Addressing your comments this is a version that allows creation of different staves, including some optional arguments for Staff type, line count and bar height.
\version "2.22"

% define the Scheme \score template

#(define (music-has-drums? m)
   (if (ly:music? m)
       (if (not (null? (ly:music-property m 'drum-type))) #t
           (or (music-has-drums? (ly:music-property m 'element))
               (any music-has-drums? (ly:music-property m 'elements))))
       #f))

dscore =
#(define-scheme-function
  (title staff-type line-count bar-line-height ts perf-notes music)
  (markup? (symbol? 'default) (number? -1) (number? -1) fraction? markup? ly:music?)
  (let* ((has-drums? (music-has-drums? music))
         (actual-staff-type
          (if (equal? staff-type 'default)
              (if has-drums? 'DrumStaff 'Staff)
              staff-type))
         (actual-line-count
          (if (= line-count -1)
              (case actual-staff-type
                ((DrumStaff) 2)
                (else 5))
              line-count))
         (actual-bar-line-height
          (if (= bar-line-height -1)
              (case actual-staff-type
                ((DrumStaff) 2)
                ((TabStaff) 7.5)
                (else 4))
              bar-line-height))
         (bar-extent (if (null? actual-bar-line-height)
                         '()
                         (cons (- (/ actual-bar-line-height 2)) (/ actual-bar-line-height 2))))
         (score
          #{
             \score {
               \header { piece = $title }
               \new #actual-staff-type \with {
                 instrumentName = "doumbek"
                 drumStyleTable = #timbales-style
                 \override StaffSymbol.line-count = #actual-line-count
                 \override BarLine.bar-extent = #bar-extent
               } {
                 \time $ts
                 $music
                 \bar ":|."
               }
             }
          #}))
    (add-score score)
    (add-text perf-notes)))

% the actual music

%automatic with drums
\dscore
  "Ayoub"
  2/4
  "test test test"
  \drummode {
    \repeat percent 3 { timl8.-> ssh16 timl8-> ssl-> } |
    timl16-> ssh ssl-> ssh timl-> ssh ssl8-> |
  }

%automatic with normal music
\dscore
  "Ayoub"
  2/4
  "test test test"
  {
    c d e f
  }

%automatic with 3 bar lines
\dscore
  "Ayoub"
  default 3 3
  2/4
  "test test test"
  \drummode {
    \repeat percent 3 { timl8.-> ssh16 timl8-> ssl-> } |
    timl16-> ssh ssl-> ssh timl-> ssh ssl8-> |
  }

% TabStaff
\dscore
  "Ayoub"
  TabStaff
  2/4
  "test test test"
  {
    c d e f
  }

Comment: @cjm Yes. ´\drummode´ is a keyword reserved by the parser that tells the parser to interpret the argument as drums. So without it Lilypond would try to interpret the music as regular music and will fail as timl is not a valid note name.
Comment: Will I need to enter `\drummode` for each snippet, then?
Comment: With `\drummode` in each snippet, it also means that I could add normal melodic snippets if I wanted while using the same macro.  I just tested your revision to my function with multiple snippets and it works like a charm.
Comment: @cjm That is indeed possible but will need additional work. See the edit to my answer.


Python Wildcard Import Vs Named Import

Question: Ok, I have some rather odd behavior in one of my Projects and I'm hoping someone can tell me why.  My file structure looks like this:
MainApp.py
res/
  __init__.py
  elements/
    __init__.py
    MainFrame.py

Inside of MainFrame.py I've defined a class named RPMWindow which extends wx.Frame.
In MainApp.py this works:
from res.elements.MainFrame import *

And this does not:
from res.elements.MainFrame import RPMWindow

I realize that the wild card import won't hurt anything, but I'm more interested in understanding why the named import is failing when the wild card succeeds.
When using the class name I get this traceback:
Traceback (most recent call last):
  File "C:\myApps\eclipse\plugins\org.python.pydev.debug_18.104.22.1680033101\pysrc\pydevd.py", line 953, in <module>
    debugger.run(setup['file'], None, None)
  File "C:\myApps\eclipse\plugins\org.python.pydev.debug_126.96.36.1990033101\pysrc\pydevd.py", line 780, in run
    execfile(file, globals, locals) #execute the script
  File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module>
    from res.elements.MainFrame import RPMWindow
  File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MainFrame.py", line 2, in <module>
    from res.elements.MenuBar import MenuBarBuilder
  File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\res\elements\MenuBar.py", line 2, in <module>
    from MainApp import _, DataCache
  File "C:\Documents and Settings\Daniel\workspace\RPM UI - V2\src\MainApp.py", line 2, in <module>
    from res.elements.MainFrame import RPMWindow
ImportError: cannot import name RPMWindow

When using the wild card import I don't receive a traceback and my application opens.
Comment: Can you provide the actual traceback that you get when using the named import?
Comment: Please, indicate what 'this doesnt work' means. Are you actually importing RPMWindow in the first case?
Answer: You have circular imports:
MainFrame.py is indirectly importing MainApp.py, and MainApp.py is importing MainFrame.py. As a result, when MainApp.py is importing MainFrame.py, the RPMWindow class hasn't been defined yet and you get the ImportError.
Comment: I found this as you pointed it out.  I think I've got it resolved.  Thanks.
Answer: i don't have time to look into why the wildcard is working for you, but what i can say about your failure with the direct name import is that you have an import cycle in your code:
you are trying to import res.elements.MainFrame, but part of that code is trying to import res.elements.MenuBar which tries to import res.elements.MainFrame again. IOW, your first attempt to import res.elements.MainFrame has not completed yet before you try it again.
Answer: You have circular imports in your code: the same module is both required by and requires the use of a certain other module, which when you think of it like that, it clearly precarious.  Most of the problems can be cleared up by using import a and later referring to a.b  instead of from a import b or from a import *.
In particular, never use from a import *. Wildcard imports clutter your namespace and makes your code less maintainable, readable, sane, and predictable. The difference between import a and from a import * is the difference between dragging a box into a room and pouring its contents all over the floor.
It would be better if you could move shared code off to its own module or somehow refactor out the need for a circular import. Circular imports always indicate a design problem.

Python Wildcard Import Vs Named Import


Does the slope of a regression between observed and predicted values always equal the $R^2$ of the original model?

Question: As the title to my question says, I am confused as to when the $R^2$ of a model fit does not equal the slope of the regression between observed and predicted values.
I am trying to present model prediction statistics in a similar way to those presented in the summary figures of the Globcolor validation report (link) - (e.g. figure from page 53 of the .pdf):

Here we see that they present the plot of observed versus predicted Chlorophyll concentrations, as well as statistics relating to its regression (e.g. the dashed line: $R^2$, $RMS$, $\alpha$ - intercept, and $\beta$ - slope).
My issue is that in my comparisons, I always get exactly the same value for the overall model fit $R^2$ and $\beta$-slope of the observed versus predicted regression.
Basic question: When (if ever) can these be different?
I have included a basic example of my problem in the following R script:
set.seed(1)
n <- 100
x <- runif(n)
e <- rnorm(n)
a <- 3
b <- 5
y <- a + x*b + e

#fit model
fit <- lm( y ~ x )

#plot regression
plot(x,y)
abline(fit)

#plot predicted versus observed
png("plot.png", units="in", width=5, height=5, res=400)
par(mar=c(5,5,1,1))
pred <- predict(fit)
plot(y, pred, xlim=range(c(y,pred)), ylim=range(c(y,pred)), xlab="observed", ylab="predicted")
abline(0,1, lwd=2, col=8)

#add regression
fit2 <- lm(pred ~ y)
lgd <- c(
    paste("R^2 =", round(summary(fit2)$r.squared,3)),
    paste("Offset =", round(coef(fit2)[1],3)),
    paste("Slope =", round(coef(fit2)[2],3))
)
legend("topleft", legend=lgd)
abline(fit2, lwd=2)
legend("bottomright", legend=c("predicted ~ observed", "1:1"), col=c(1,8), lty=1, lwd=2)

dev.off()

cor(pred, y)^2 # also the same

Answer:
I always get exactly the same value for the overall model fit $R^2$ and slope of the observed versus predicted regression.

This will be true provided a constant term is included in the overall model.  Why?

$R^2$ measures the variance of the fit $\hat Y$ relative to the variance of $Y$ (provided the model includes a constant).
Regressing $\hat Y$ against $Y$ or $Y$ against $\hat Y$ must produce identical standardized slopes $\hat\beta_{\hat{Y}Y} = \hat\beta_{Y\hat{Y}}$.  This is because the standardized slope in a univariate regression of $Y$ against any $X$ is their correlation coefficient $\rho_{XY}$, which is symmetric in $X$ and $Y$.
The standardized slope $\hat \beta_{XY}$ in any univariate regression of $Y$ against any $X$ is related to the slope $\hat b_{XY}$ via
$$\hat \beta_{XY} = \hat b_{XY} \frac{\text{SD}(X)}{\text{SD}(Y)}.$$
Regressing $Y$ against $\hat Y$ must have a unit slope $\hat b_{\hat{Y}Y}$.  Geometrically, $\hat Y$ is the projection of $Y$ onto the column space of the design matrix and the regression of $Y$ against $\hat Y$ is $1$ times the component of $Y$ on that projection.

Putting these all together (in order) yields
$$R^2 = \rho^2_{\hat{Y}Y} = \hat\beta_{\hat{Y}Y}\hat\beta_{Y\hat{Y}} = \left(\hat b_{Y\hat{Y}} \frac{\text{SD}(Y)}{\text{SD}(\hat{Y})}\right)\left(\hat b_{\hat{Y}Y} \frac{\text{SD}(\hat{Y})}{\text{SD}(Y)}\right) = \hat b_{Y\hat{Y}}\hat b_{\hat{Y}Y} = \hat b_{Y\hat{Y}},$$
QED.
The result is not necessarily true when the model does not include a constant: just about any random simulation, as shown below, will give a counterexample.
n <- 10; d <- 2
x <- matrix(rnorm(n*d), ncol=d)
y <- x %*% (1:d) + rnorm(n, 3)
fit <- lm(y ~ x)
y.hat <- predict(fit)
#
# Look for the appearances of R^2 in the output.
#
var(y.hat) / var(y) # R^2
with(summary(lm(y.hat ~ y)), c(coefficients["y", 1], r.squared))
with(summary(lm(y ~ y.hat)), c(coefficients["y.hat", 1], r.squared))
#
# Repeat without a constant term: the same consistency among
# the output occurs, *but the slopes are not equal to R^2*.
#
with(summary(lm(y.hat ~ y - 1)), c(coefficients["y", 1], r.squared))
with(summary(lm(y ~ y.hat - 1)), c(coefficients["y.hat", 1], r.squared))

Comment: @Roland Believe it or not, I learned every one of these facts by *teaching* a beginning statistics class at the university level. It's all in books like *Statistics* by Freedman, Pisani, & Purves.  (Consult any edition.)  I am not trying to imply that graduates of this class would be expected to come up with (1) through (4) and put them together to solve this problem, but it is of interest that all the pieces of the puzzle are completely elementary (and, with a bit of practice in such thinking, somewhat intuitive).
Comment: Seeing proofs like this sometimes makes me wish I had studied statistics in university. :) It looks so easy, but would have taken me hours.
Comment: @whuber - Really great answer as usual. Thanks a lot for taking the time to explain this to me. I'm going to stop banging my head against the wall now...
Comment: btw - I think this particular ocean color algorithm (i.e. model) uses a summation of reflectance spectra signatures (e.g. baseline water + chlorophyll) to estimate chl concentrations; thus, it's very possible that there is not an intercept. I'll have to look into that. Cheers and thanks!
Comment: Since it appears to be a log-log model, the intercept would correspond to a multiplicative term on the original scale--and this would appear to be essential if only to make units of measurement commensurate (between predicted values, which are combinations of spectral intensities, and actual values, which are concentrations).
Comment: I can believe @whuber : it has also been my experience that teaching is a much more effective way of learning than being teached.
Answer: $R^2$ doesn't have to be equal to $\beta$. you either have a rare coincidence, or reading the same field from the fit object somehow.
Comment: You do not seem to be addressing the question concerning $R^2$ of the regression of predicted against observed values.
Comment: right, missed that
Comment: I don't think this is a coincidence. `all.equal(cor(y,x)^2, unname(coef(lm(predict(fit)~y))[2]))` is `TRUE` for different parameters and random seeds. I believe if someone sits down and does the maths this could be proven analytically.
Comment: @Roland - Yes, this seems to be the case for every model fit that I have done. So, perhaps the error is in the Globcolour analyses - How they calculated their summary statistics is not well documented...
Comment: actually, the graph from the Globcolour report doesn't seem to be of predicted vs. observed. i think they're regressing some data on another set, which they call "in-situ"
Comment: @Aksakal - "in situ" usually refers to observed or measured data.
Comment: @Marcinthebox, that's not the impression you get when reading p.52 "matchup analyses" section. it reads as if the y-axis data was obtained from a different source than x-axis data, but you know this better, so I guess you're right
Comment: @Aksakal - No, no.. I could be wrong. I'll look at it again. It would be untypical (and confusing!) if that was the case.


Weak convergence problem without a condition

Question: I have a problem that I am not sure so I need your help.
If we have ${X_n} \Rightarrow X$ and $P(X=0)=0$ then we can show $X_n^{-1} \Rightarrow X^{-1}$ ($0^{-1}$ is defined as $0$) but can we prove it without the condition $P(X=0)=0$? Any comments would be appreciated!
Answer: Clearly false without the condition $P(X=0)=0$. Take $X_n =\frac 1 n, X=0$ for a counter-example.
Comment: So you mean without this condition, ${X_n}$ will never converge weakly to $X=0$ even if $n$ go to infinity? Can you explain a bit more detail? Thank you very much!
Comment: Just think of the corresponding question for sequences of real numbers.
Comment: Thanks for your explanation! I will check it.


Pidgin script with Python/ Get Focus Signal

Question: I am creating a script in Python to integrate Pidgin with Unity (Ubuntu 12.04), I've managed to do the counting notifications system using the Unity API, but i dont know what event or signal that is activated when the conversation window gains focus(To clear the message counter)...
I've tried some of the signals available on the documentation of Pidgin (https://developer.pidgin.im/wiki/DbusHowto) but none of them worked, is there any GTK(or anything) event that is triggered when the window chat gets focus?
Comment: All of Pidgin's DBus signals can be found [here](https://developer.pidgin.im/doxygen/dev2.x.y/html/conversation-signals.html#receiving-chat-msg). It doesn't look like there's a signal for that event.
Comment: I've tried to use some of them but they end up overwriting the signal "received-im-msg" used to update the counter... So when I add, they end up wiping the counter instantly
Answer: Conversation UI signals are listed here those might be more helpful for what you are trying to do.
Though I don't know that I understand what you meant by your comment about the counter being wiped instantly when you tried some of the other signals. That sounds like it might be a coding error to me.


How do I deploy an Angular.js app?

Question: This may be a stupid question, but I'm wondering what platform I should use to deploy my Angular.js app? I tried using Heroku but got a "no Cedar-supported app detected" error. Any thoughts?
UPDATE
I'm trying to serve this to heorku as a Node.js application, but still can't seem to get it working. There's a web-server.js file in the root directory of my application and I reference it in my Procfile here:
web: node web-server.js

And here's my package.json file, also in the root directory:
{
"name": "medicare-data",
"version": "0.0.1",
"dependencies": {
},
"engines": {
    "node": "0.10.x",
    "npm": "1.2.x"
},
"respository": "medicare-data",
"author": "sararob"
}

I'm getting a "slug compilation error" in my heroku logs. Thoughts on why this might not be working?
Comment: Angular is pure javascript and should be platform independent.  This Q/A may help: http://stackoverflow.com/questions/13926419/heroku-for-node-heroku-push-rejected-no-cedar-supported-app-detected
Comment: The title of the question should be: "How do I upload any file to Heroku" ;-)
Answer: You can run an Angular app on heroku if it is served as a node.js application. Usually, when you start working with Angular seed, there is already a node webserver script in the project. I believe if there is a package.json file in the root, heroku will detect and run it as a node.js application. I'll come back and update this answer with more detail shortly.
UPDATE
From the Heroku docs (and I am no expert), it has this passage after the deploy section: https://devcenter.heroku.com/articles/nodejs#visit-your-application
which basically tells you to make sure you have one dyno running. You can do that either through the web app under the settings of your app or you can run this:
$ heroku ps:scale web=1

To see if the process is running, do
$ heroku ps
=== web: `node web.js`
web.1: up for 10s

Comment: Thanks Sam, I'm trying to serve it as a node.js application on heroku now but am still getting some errors. See my update above. Any thoughts?
Answer: I bet if you look at your logs you'll see something like this:
2013-08-26T12:51:18.257006+00:00 heroku[web.1]: Starting process with command `node scripts/web-server.js`
2013-08-26T12:51:19.109974+00:00 app[web.1]: Http Server running at http://localhost:8000/
2013-08-26T12:51:34.369092+00:00 heroku[router]: at=error code=H20 desc="App boot timeout" method=GET path=/ host=cmwidget.herokuapp.com fwd="188.8.131.52" dyno= connect= service= status=503 bytes=
2013-08-26T12:52:19.445974+00:00 heroku[web.1]: Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch

It means that your Angular seed app is using it's own port (8000), and Heroku doesn't allow this. You need to relinquish the assignment of the port number to Heroku.
Easily fixed. Modify scripts/web-server.js, and change this:
this.server.listen(port);

...to this:
this.server.listen(process.env.PORT || port);

Answer: I changed this line
   var DEFAULT_PORT = 8000;
into:
   var DEFAULT_PORT = process.env.PORT || 8000;
..and then it worked.
So I believe the reason is that heroku doesn't like your app running on port 8000.
Comment: Heroku wants to automatically assign the port for each instance, so changing it to `process.env.PORT` allows you to to that.  Your local machine will auto-assign a port this way too, so testing local will work the same.

How do I deploy an Angular.js app?


How many ordered triples $(x,y,z)$ of positive integers satisfy $xyz=4000$

Question: How would I find this out? Is there an equation or summation?
Comment: Do you know what the fundamental theorem of arithmetic is?
Answer: Try decomposing 4000 into its prime factors and looking at what combinations you can have when splitting them into three groups.


How do I find all *.resx file that have an action type of integrate or edited from a Perforce change list?

Question: I wish to do some checks on the results of a large merge, I know merges often get incorrect results with WinFrom UIs, so I wish to get a list of the files that need checking…
I can't find a "report" option on any of the Perforce menus, the change list dlg also does not have an "expert" button, so I can't get the data into excel.
Answer:
p4 describe -s 47773 | find /V "branch" | find "resx"

On the windows command line got me a useful list.  (Where 4773 is the change list number)


Why isn't CFStream using TLS 1.3?

Question: I'm trying to figure out why an iPhone running iOS 14 isn't using TLS 1.3 to connect to a compatible web server.
Relevant code is:
- (void) streamOpened:(NSStream *)stream {
    NSDictionary *settings = @{
                               (__bridge NSString *)kCFStreamSSLValidatesCertificateChain: (__bridge NSNumber *)kCFBooleanFalse
                               };
    CFReadStreamSetProperty((CFReadStreamRef)inputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
    CFWriteStreamSetProperty((CFWriteStreamRef)outputStream, kCFStreamPropertySSLSettings, (CFTypeRef)settings);
}

The full source can be seen here: https://github.com/tls-inspector/tls-inspector/blob/2.0.0/CertificateKit/Getters/CKAppleCertificateChainGetter.m
I've tried specifying the SSL Level with kCFStreamSSLLevel set to kCFStreamSocketSecurityLevelTLSv1_3 but that didn't do anything.
If I use OpenSSL to connect it uses TLS 1.3 and I can verify that with a packet capture, but using CFStream it sticks to 1.2.
Answer: The short answer is that you end up using a deprecated API that does not support TLS 1.3.
The long answer, which details a potential solution, is given below.
I tried to solve this using CFStream but did not succeed.
It might be possible. The problem is that you end up, as you do, at a low level using SSLConnectionRef and friends and at a higher level using NSInputStream and NSOutputStream and friends and at some point you run into this https://developer.apple.com/documentation/security/secure_transport?language=objc legacy API.
On that page it mentions that that API was replaced by the Network framework and really this is what I am suggesting you should use. I was hoping to also implement a solution quickly but it needs a bit more rework than what SO is for so I leave it at that.
However, herewith some suggestions, basically the ideas I was hoping to implement.
As before, there are two levels.
At the lower level you end up using the nw_ and family but I would say do not go that way. It might be required for some specialised needs and your app might be in that category, but still, just take note that the higher level is built on top of this.
At the higher level, and this is where I think your solution lies, you end up using NSURL and friends. Your goto guy here is probably NSURLSession but the implementation will dictate that. I tried to give an outline and you can look at my code to get more detail but I think you will be in a much better position to implement from here onwards.
In that I was hoping to connect your legacy stream code to NSURLSession but when that failed I stopped. That is perhaps a bit optimistic and I think it requires a more serious rework, but the various delegates (NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionStreamDelegate and so on) seem to be ready and waiting for your solution and I don't think it is a lot of work actually.
The most relevant snippet of code from my attempt is below. This switches on TLS 1.3 and I tried to implement around this.
    // Some configuration
    NSURLSessionConfiguration * config = NSURLSessionConfiguration.ephemeralSessionConfiguration;

    // Note this one!!!
    config.TLSMaximumSupportedProtocol = kTLSProtocolMaxSupported;

    NSURLSession * urlSession = [NSURLSession sessionWithConfiguration:config
                                  delegate:self
                                 delegateQueue:NSOperationQueue.currentQueue];

From this point onwards I tried to reuse your stream code but to be honest I think the final solution may not even use streams any more, and in stead just rely on using the correct delegate. Forgive me for getting excited at this point, but I suspect you will be able to greatly simplify your code as a result.
I enjoyed your app - it is pretty polished and I look forward to you solving this problem. I also enjoyed toying with it but for now that is my contribution.
First attempt
I eyeballed your code - it needs some reworking for TLS 1.3. I tried to do it but I am now rewriting that class so I stopped. You can do it, but, I can not guarantee that it will work!
Anyhow, here are some thoughts.
First on the existing code. Just some - ahem - observations, nothing serious ...
Note that your streamOpened will apply the settings no matter which stream was triggered. The delegate will message that twice I believe, once for the input and once for the output stream. Although here it seems it does not matter you should be careful as that could introduce some serious bugs in another situation.
Also, I think you need to configure the streams before they are opened but this did not make any difference. If you configure the streams before they are opened in your performTaskForURL or afterwards in the streamOpened it did not matter.
I played with the configuration a bit. You need not set one on the output stream, only on the input. And the only key that is required is the one you already set. I could not get any difference no matter what I did.
Second, the solution I - ahem - think will work here.
You need to configure the URL session. So what I did was the following
- (void) performTaskForURL:(NSURL *)url{

    queryURL = url;

    // Some configuration
    NSURLSessionConfiguration * config = NSURLSessionConfiguration.ephemeralSessionConfiguration;

    // Note this one!!!
    config.TLSMaximumSupportedProtocol = kTLSProtocolMaxSupported;

    NSURLSession * urlSession = [NSURLSession sessionWithConfiguration:config
                                  delegate:self
                                 delegateQueue:NSOperationQueue.currentQueue];

    // Just code to test the idea, not production ready I know
    NSURLSessionStreamTask * streamTask = [urlSession streamTaskWithHostName:url.host
                                        port:443];
    [streamTask captureStreams];
}

- (void)URLSession:(NSURLSession *)session
    streamTask:(NSURLSessionStreamTask *)streamTask
didBecomeInputStream:(NSInputStream *)inputStreamUrl
      outputStream:(NSOutputStream *)outputStreamUrl
{
    // I was hoping to get away with this,
    // just setting your streams equal to the
    // URL stream task streams but it did not
    // work ... problem is you need more of the
    // stream task delegate methods I believe
    inputStream = inputStreamUrl;
    outputStream = outputStreamUrl;

    // This is some left over code from your performTaskForURL message
    // Here you can see how I toyed with the stream configuration

    // Configure here before it is opened
    // Pretty much your current streamOpened message
    // Note only input needs be configured (fwiw)
    [self configureStream:inputStream];

    inputStream.delegate = self;
    outputStream.delegate = self;

    [outputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];
    [inputStream scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSDefaultRunLoopMode];

    [outputStream open];
    [inputStream open];

    // I was hoping this would just work but I think it needs more work
}

The idea here is to configure a URL session with kTLSProtocolMaxSupported and then to create a stream task off that. Now this is where I want to stop and think you are much better at going further. I was hoping I can just get the streams and throw them back to your code, but it did not work and for now I'm not going further.
I could not test my idea as I need to hook up a few more things to the NSURLSessionStreamDelegate that your class now also implements. I think you do the same in the class already, but for streams.
Now, again, I may be wrong, and wanted to test before I posted, but either see if this might work and then I think you need to e.g. implement delegate methods such as URLSession:task:didReceiveChallenge:completionHandler:.
I think you already do that sort of thing in your code, but this is why I am stopping here, as I think you will be a much better judge of this idea.
I've toyed with it some more but no success - but I think you need to use NSURLSession here, maybe even in stead of sockets.
Comment: You are very generous! Thank you. I noted that as well, but, at the same time, you should also note that NSURLSession is where the action is now. You could drop down to a lower level using e.g. nw_ to access FTPS etc but yes nowadays you get all of that via NSURL... . So here I think we are in full agreement - I'll summarise that in my edit.
Comment: Ok - phew. I edited and edited and re-edited my answer. Not as concise as I hoped but by now I am so excited I think the solution is really within easy reach.
Comment: And even more edits ... a concise response to the OP and a detailed one outlining a possible solution.
Comment: Hi @skaak, thank you for the detailed answer. I originally used NSURLSession's a long time ago but eventually moved away to sockets as the app must be able to connect to any TLS server, not strictly just HTTPS (so things like FTPS, SMTPS, LDAPS, etc...). I will try to see if I can get things to work using `NSURLSessionStreamTask` since it might not matter as i'm not actually doing anything with the remote server, just focusing on the handshake.
Comment: I also just discovered that the entire SecureTransport API is deprecated: https://developer.apple.com/documentation/security/secure_transport?language=objc - which is why it doesn't support TLS 1.3 as they want you to use the new Network API instead.
Comment: It's pretty much clear at this point that the answer to my question is "Because the API you're using is deprecated and does not support anything beyond TLS 1.3" - if you want to reword your answer to be that I will happily award you the bounty.

Why isn't CFStream using TLS 1.3?


Struct size in C

Question: I've made a doubly linked structure in C, and need to know how to calculate the size of custom made structures.  I understand the size of certain data types, and that pointers are 8 bytes on my machine.
However when I create this data type
struct doublylinked {
    int data;
    struct doublylinked *next;
    struct doublylinked *prev;
};

I get that all the values inside add up to 20 bytes in total.
size of data = 4
size of next = 8
size of prev = 8
However when I print out the size of this data type it equals 24.
size of doublylinked = 24
Where are these extra 4 bytes coming from?
Thanks
Comment: Please remove the C++ tag. The extra 4 bytes might come from alignment. Which compiler are you using?
Comment: http://en.wikipedia.org/wiki/Data_structure_alignment
Comment: Compiler is GCC.  Checking the size using sizeof(struct doublylinked)... Thanks will check structure alignment
Answer: The extra space come from the padding added by the compiler, which make access faster on some CPU.
It might actually look like this in memory:
data     [4 bytes]
padding  [4 bytes] <- That way, next is aligned on a multiple of his own size
next     [8 bytes]
prev     [8 bytes]

Answer: The 8-byte next and prev variables need to have an 8-byte alignment.
In other words, they need to be located in memory addresses divisible by 8.
So the compiler adds a 4-byte padding before or after the 4-byte data variable.
Please note that this is generally platform-dependent (i.e., some processors may support unaligned load/store operations, in which case, the compiler may choose to avoid the padding).

Struct size in C


Negative dimension size caused by subtracting 3 from 1 for 'Conv2D'

Question: I'm using Keras with Tensorflow as backend , here is my code:
import numpy as np
np.random.seed(1373)
import tensorflow as tf
tf.python.control_flow_ops = tf

import os
from keras.datasets import mnist
from keras.models import Sequential
from keras.layers.core import Dense, Dropout, Activation, Flatten
from keras.layers.convolutional import Convolution2D, MaxPooling2D
from keras.utils import np_utils

batch_size = 128
nb_classes = 10
nb_epoch = 12

img_rows, img_cols = 28, 28

nb_filters = 32

nb_pool = 2

nb_conv = 3

(X_train, y_train), (X_test, y_test) = mnist.load_data()

print(X_train.shape[0])

X_train = X_train.reshape(X_train.shape[0], 1, img_rows, img_cols)
X_test = X_test.reshape(X_test.shape[0], 1, img_rows, img_cols)

X_train = X_train.astype('float32')
X_test = X_test.astype('float32')
X_train /= 255
X_test /= 255

print('X_train shape:', X_train.shape)
print(X_train.shape[0], 'train samples')
print(X_test.shape[0], 'test samples')

Y_train = np_utils.to_categorical(y_train, nb_classes)
Y_test = np_utils.to_categorical(y_test, nb_classes)

model = Sequential()

model.add(Convolution2D(nb_filters, nb_conv, nb_conv,
border_mode='valid',
input_shape=(1, img_rows, img_cols)))
model.add(Activation('relu'))
model.add(Convolution2D(nb_filters, nb_conv, nb_conv))
model.add(Activation('relu'))

model.add(MaxPooling2D(pool_size=(nb_pool, nb_pool)))
model.add(Dropout(0.25))

model.add(Flatten())
model.add(Dense(128))
model.add(Activation('relu'))
model.add(Dropout(0.5))
model.add(Dense(nb_classes))
model.add(Activation('softmax'))

model.compile(loss='categorical_crossentropy', optimizer='adadelta', metrics=["accuracy"])

model.fit(X_train, Y_train, batch_size=batch_size, nb_epoch=nb_epoch,
verbose=1, validation_data=(X_test, Y_test))

score = model.evaluate(X_test, Y_test, verbose=0)

print('Test score:', score[0])
print('Test accuracy:', score[1])

and Trackback error:
Using TensorFlow backend.
60000
('X_train shape:', (60000, 1, 28, 28))
(60000, 'train samples')
(10000, 'test samples')
Traceback (most recent call last):
  File "mnist.py", line 154, in <module>
    input_shape=(1, img_rows, img_cols)))
  File "/usr/local/lib/python2.7/dist-packages/keras/models.py", line 276, in add
    layer.create_input_layer(batch_input_shape, input_dtype)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 370, in create_input_layer
    self(x)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 514, in __call__
    self.add_inbound_node(inbound_layers, node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 572, in add_inbound_node
    Node.create_node(self, inbound_layers, node_indices, tensor_indices)
  File "/usr/local/lib/python2.7/dist-packages/keras/engine/topology.py", line 149, in create_node
    output_tensors = to_list(outbound_layer.call(input_tensors[0], mask=input_masks[0]))
  File "/usr/local/lib/python2.7/dist-packages/keras/layers/convolutional.py", line 466, in call
    filter_shape=self.W_shape)
  File "/usr/local/lib/python2.7/dist-packages/keras/backend/tensorflow_backend.py", line 1579, in conv2d
    x = tf.nn.conv2d(x, kernel, strides, padding=padding)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/ops/gen_nn_ops.py", line 396, in conv2d
    data_format=data_format, name=name)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/op_def_library.py", line 759, in apply_op
    op_def=op_def)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 2242, in create_op
    set_shapes_for_outputs(ret)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1617, in set_shapes_for_outputs
    shapes = shape_func(op)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/ops.py", line 1568, in call_with_requiring
    return call_cpp_shape_fn(op, require_shape_fn=True)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.py", line 610, in call_cpp_shape_fn
    debug_python_shape_fn, require_shape_fn)
  File "/usr/local/lib/python2.7/dist-packages/tensorflow/python/framework/common_shapes.py", line 675, in _call_cpp_shape_fn_impl
    raise ValueError(err.message)
ValueError: Negative dimension size caused by subtracting 3 from 1 for 'Conv2D' (op: 'Conv2D') with input shapes: [?,1,28,28], [3,3,28,32].

First I saw some answers that problem is with Tensorflow version so I upgrade Tensorflow to 0.12.0, but still exist , is that problem with network or I missing something, what should input_shape looks like?
Update
Here is ./keras/keras.json:
{
    "image_dim_ordering": "tf",
    "epsilon": 1e-07,
    "floatx": "float32",
    "backend": "tensorflow"
}

Comment: @Arman Ajoooo nice question! ^_^
Comment: It may be problem with your keras input shape order setting. If you change `input_shape=(1, img_rows, img_cols)` to `input_shape=(img_rows, img_cols, 1)`, does it work?
Comment: @pyan , no it doesn't , `Exception: Error when checking model input: expected convolution2d_input_1 to have shape (None, 28, 28, 1) but got array with shape (60000, 1, 28, 28)`
Comment: Can you check what is the content in the file of `.keras/keras.json`, especially the value of "image_dim_ordering"
Answer: Your issue comes from the image_ordering_dim in keras.json.
From Keras Image Processing doc:

dim_ordering: One of {"th", "tf"}. "tf" mode means that the images should have shape (samples, height, width, channels), "th" mode means that the images should have shape (samples, channels, height, width). It defaults to the image_dim_ordering value found in your Keras config file at ~/.keras/keras.json. If you never set it, then it will be "tf".

Keras maps the convolution operation to the chosen backend (theano or tensorflow). However, both backends have made different choices for the ordering of the dimensions. If your image batch is of N images of HxW size with C channels, theano uses the NCHW ordering while tensorflow uses the NHWC ordering.
Keras allows you to choose which ordering you prefer and will do the conversion to map to the backends behind. But if you choose image_ordering_dim="th" it expects Theano-style ordering (NCHW, the one you have in your code) and if image_ordering_dim="tf" it expects tensorflow-style ordering (NHWC).
Since your image_ordering_dim is set to "tf", if you reshape your data to the tensorflow style it should work:
X_train = X_train.reshape(X_train.shape[0], img_cols, img_rows, 1)
X_test = X_test.reshape(X_test.shape[0], img_cols, img_rows, 1)

and
input_shape=(img_cols, img_rows, 1)

Comment: Using this script: https://elitedatascience.com/keras-tutorial-deep-learning-in-python#step-1

and making the 2 changes to lines 15,16&29 worked for me. Thank you!
Comment: Additional info: You can check which format is used (NHWC vs NCHW) at runtime using `if K.image_data_format() == 'channels_first':` (with `from keras import backend as K`).
Comment: I ise `if K.image_data_format() == 'channels_first':
    input_shape = (3, img_width, img_height)
else:
    input_shape = (img_width, img_height, 3)` and still get the error. Adding `padding="same"` helps in so far that my skript runs, but it seems to only mask rather than solve the issue... It is not clear to me what the actual problem is...
Answer: FWIW, I got this error repeatedly with some values of strides or kernel_size but not all, with the backend and image_ordering already set as tensorflow's, and they all disappeared when I added padding="same"
Comment: This should be the answer
Comment: Using `padding="same"` does not solve problem, it just hides it. `same` padding works because it adds zero padding such that the conv or pool kernel achieves an integer number of strides over the input tensor. This is different, and produces different results, from `valid` padding. I too have not yet figured out how to get `valid` to work consistently.
Comment: Thanks, I had three layers and the third conv2d gave me this error. This fixed it.
Comment: @user2939212 where exactly should I add the line `padding="same"`
Comment: I had trouble with a multi-layer network for a week, where everything worked fine until I reached a certain number of layers and then I would get the dimension error. I tried all the other answers and everything I found on Google, but nothing helped. This fixed it, no idea why.
Comment: @JeruLuke In the arguments list when you instantiate `Convolution2D`
Comment: @Jacquot Thanks for mentioning it. I also checked out the docs!
Comment: Well this should be an answer!
Answer: Just add this:
from keras import backend as K
K.set_image_dim_ordering('th')

Comment: and this is better than padding="same" cause not needed to be added to each layer
Comment: @user271077, re-read my answer ; this is not "better" or "worse", these are most definitely answers for different errors that give the same error message
Comment: AttributeError: module 'keras.backend' has no attribute 'set_image_dim_ordering'
Answer: I am also having the same problem. However, each Conv3D layer, I am using, is reducing size of the input. So, including one parameter padding='same' during declaring the Conv2D/3D layer solved the problem. Here is the demo code
model.add(Conv3D(32,kernel_size=(3,3,3),activation='relu',padding='same'))

Reducing the size of the filter can also solve the problem.
Actually, Conv3D or Conv2D layer reduces the input data. But when your next layer does not recieve any input or input of size which is not appropriate for that layer, then this error occurs. By padding we are making the output of Conv3Dor2D remain same size of input so that next layer will get its desired input
Comment: Actually, Conv3D or Conv2D layer reduces the input data. But when your next layer does not recieve any input or input of size which is not appropriate for that layer, then this error occurs. By padding we are making the output of Conv3Dor2D remain same size of input so that next layer will get its desired input. Hope that helps. Let me know if you are happy with the answer. I will add this to my question then.
Comment: Hey, I know it has been a while since you answered this, but can you explain a bit why this error occurs? Thanks!
Answer: I faced the same problem, but it was solved by changing the conv2d function:
if K.image_data_format=='channels_first':
    x_train = x_train.reshape(x_train.shape[0], 1,img_cols,img_rows)
    x_test = x_test.reshape(x_test.shape[0], 1,img_cols,img_rows)
    input_shape = (1,img_cols,img_rows)
else:
    x_train = x_train.reshape(x_train.shape[0],img_cols,img_rows,1)
    x_test = x_test.reshape(x_test.shape[0],img_cols,img_rows,1)
    input_shape = (img_cols,img_rows,1)
model.add(Convolution2D(32,(3, 3), input_shape = input_shape, activation="relu"))

Answer: Another solution can help is change:
from keras.layers import Convolution2D, MaxPooling2D

to
from keras.layers import Conv2D, MaxPooling2D

After that, to run preprocess input data, I change:
X_train = X_train.reshape(X_train.shape[0], 1, 28, 28)
X_test = X_test.reshape(X_test.shape[0], 1, 28, 28)

to
X_train = X_train.reshape(X_train.shape[0], 28, 28, 1)
X_test.reshape(X_test.shape[0], 28, 28, 1)

Finally, I change:
model.add(Convolution2D(32, 3, 3, activation='relu',input_shape=(1,28,28)))
model.add(Convolution2D(32, 3, 3,activation='relu'))

to
model.add(Conv2D(32, (3, 3), activation='relu',input_shape=(28,28,1)))
model.add(Conv2D(32, (3, 3), activation='relu'))

Answer: Provide size of filter using parenthesis like:
model.add(Convolution2D(nb_filters,( nb_conv, nb_conv) ,border_mode='valid',
input_shape=(1, img_rows, img_cols)))

It will work in my case and also change the X_train , X_test as this:
X_train = X_train.reshape(X_train.shape[0], img_cols, img_rows, 1)
X_test = X_test.reshape(X_test.shape[0], img_cols, img_rows, 1)

Answer: Just had this problem. The bellow is the solution to work with the new API.
K.set_image_dim_ordering('tf') --> K.set_image_data_format('channels_last')
K.set_image_dim_ordering('th') --> K.set_image_data_format('channels_first')
K.image_dim_ordering() == 'tf' --> K.image_data_format() == 'channels_last'
K.image_dim_ordering() == 'th' --> K.image_data_format() == 'channels_first'

See more here
Answer:    %store -r le
   %store -r x_train
   %store -r x_test
   %store -r y_train
   %store -r y_test
   %store -r yy
    import numpy as np
    import keras
    from keras.models import Sequential
    from keras.layers import Dense, Dropout, Activation, Flatten
    from keras.layers import Conv2D, MaxPooling2D, GlobalAveragePooling2D
    from keras.optimizers import Adam
    from keras.utils import np_utils
    from sklearn import metrics
    num_rows = 40
    num_columns = 174
    num_channels = 1
    x_train = x_train.reshape(x_train.shape[0],num_rows , num_columns, num_channels)
    x_test = x_test.reshape(x_test.shape[0], num_rows, num_columns,num_channels )
num_labels = yy.shape[1]
filter_size = 2
# Construct model
model = Sequential()

model.add(Conv2D(filters=16, kernel_size=2, activation='relu',input_shape=(
40,174,1)))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))

model.add(Conv2D(filters=32, kernel_size=2, activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))

model.add(Conv2D(filters=64, kernel_size=2, activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))

model.add(Conv2D(filters=128, kernel_size=2, activation='relu'))
model.add(MaxPooling2D(pool_size=2))
model.add(Dropout(0.2))
model.add(GlobalAveragePooling2D())

model.add(Dense(num_labels, activation='softmax'))


Duvida de execução javac no cmd

Question: Olá, estou começando agora em Java e queria saber como compilar o .java em .class de uma maneira direta.
Sei executar o javac no cmd mas faço assim:
cd C:\Local\

javac HelloWorld.java

Mas eu gostaria de saber se existe uma maneira de fazer isso em uma linha só.
Vou usar isso em um projeto que vai fazer isso automaticamente.
Answer: cd C:\Local\ && javac HelloWorld.java

Duvida de execução javac no cmd


Calculate Points Between Two Points

Question: I have two points $(A, B)$, both with longitude and latitude. For each point I have a speed in $km/h$, I assume a car drives from point $A$ to point $B$.
I already have a function to calculate the distance between the two points.
What I want to calculate in the end is the points between this two points in a distance of $100$ milliseconds (every $100ms$ I want to calculate a point)
The way between the points does not have any curves in it, it is a straight line.
Thanks for your help
Matthias
Answer: Assuming that $A=[x_A ~ y_A]$ and $B = [x_B ~ y_B]$, a point between $A$ and $B$ can be described as
$$C = \alpha(B-A) + A$$
for $\alpha \in [0, 1]$
When $\alpha = 1$, the you arrive to $B$. If you travel with a constant velocity $v$ and the distance between $A$ and $B$ is $d$, then
$$\alpha = \frac{vt}{d}$$
The point after $100$ ms $= 0.1$s is
$$C(0.1s) = \frac{0.1v}{d}(B-A)+A$$
The point after $0.2s$ is
$$C(0.2s) = \frac{0.2v}{d}(B-A)+A$$
and so on...
Notice that $v$ must be expressed in [km]/[s] if $d$ is [km] or [m]/[s] if $d$ is [m].
Comment: Thx, but I don't think that this is correct, cause it means that I would need always 1 second to reach point B. Waht one need is: a) The acceleration b) the distance (what I have) and then you need to calculate the time you need to reach point B. Then you can calculate how many points you have if the distance is 100ms for each point (e.g. 10 seconds = 100 points). each points gets then it's own speed you need to calculate... any ides on how to do this?
Comment: Any other ideas? First of all I have to findout the time I need to travel from A to B. Then I can findout how many points O have in between and then I can use the formula above.

Calculate Points Between Two Points


geocoder not working for iOS in Xamarin.Forms

Question: So I have an iOS problem.
I have a method that is supposed to get the location from an address. I use the geocoder method from xamarin.forms.maps, and it works fine on android, it gives me the correct location, does what it is supposed to do, but on iOS it is not working.
for some reason, after i run this line of code:
<code>var geoPositions = await geocoder.GetPositionsForAddressAsync(tuple.address);
</code>
the rest of the code in the method does not execute, it just skips to the end of the method and doesn't do anything else.
i don't get an error or an exception or anything, it just exits the method and continue doing other stuff.
I have tried to use different addresses to see if that was the problem, but the same same thing happened, and it also happened when i tried to use the GetAddressForPositionAsync method with coordinates.
I am using a real device to test the app, an iPhone 6 with iOS version 11.2.6, and yes, I have added all required permissions in info.plist
Any insight into why this is happening would be greatly appreciated, thanks.
Comment: Please can you provided the version of iOS , is real device or Simulator ?
Comment: Have you add additional keys in `info.plist`?   Refer to :https://learn.microsoft.com/en-us/xamarin/xamarin-forms/user-interface/map#Platform_Configuration
Comment: I am using a real device yes, an iPhone 6 with iOS version 11.2.6, and yes, I have added all required permissions in info.plist
Answer: So I figured out the problem.
Apparently I was getting an exception that I for some reason couldn't see.
System.InvalidOperationException: You MUST call Xamarin.FormsMaps.Init (); prior to using it. at Xamarin.Forms.Maps.Geocoder.GetPositionsForAddressAsync.
Once I noticed that, I saw that
Xamarin.FormsMaps.Init ();
had only been added to the main activity in android, and not in iOS.
I added that, and now it is working correctly.


Why does my while loop never end

Question: I've been trying to present my data from my database using PHP. My while loops keep running.
  function makeCollection(){
    $images = mysql_query("select file_id from images where collection_id = 1");
     //returns file_id

     $fileIds = mysql_fetch_array($images, MYSQL_NUM );
     //get file ids from $images into array

     while($fileIds != false){
      echo($fileIds[0]);
     }
  }

I have three objects that fit with id = 1, 2, and 3 (it's on auto-increment). Shouldn't the loop iterate through then stop after the third? It just write '1' for infinity.
Answer: You need to call the function within the loop condition so it can be evaluated multiple times. Right now you just call it only once, that's going to tell PHP to fetch only the first row. If it's not false (i.e. MySQL returned at least one row), your while loop will be infinite.
while (($fileIds = mysql_fetch_array($images, MYSQL_NUM )) !== false) {
  echo $fileIds[0];
}

By calling it every time the loop condition is checked, PHP internally advances the result set pointer so it can cover all rows in the result set. Eventually this function will return false and terminate the loop.
Comment: @Spudley: Thanks. I should probably delete my post and let you have the votes since I've maxed out my daily rep :)
Answer:  while($fileIds != false){
  echo($fileIds[0]);
 }

You're not doing anything to advance the loop field inside the loop. You have a line immediately before the loop which sets $fileIds, but as things stand, it only ever gets called once because it is outside the loop.
What you need is to put that inside the loop, probably inside the while() itself, as follows:
while(($fileIds = mysql_fetch_array($images, MYSQL_NUM)) !== false) {
 ....
}

Hope that helps.

Why does my while loop never end


SerialPort communication in C# splitting frames

Question: I need to write a program, that will listen to communication in ModBus network through RS485.
I am connected to the network with RS485 <> USB dongle.
I can read some data using SerialPort.DataReceived event, but it gives strange results.
Data is often split, when it should come in one piece. (Modbus Master transmits every 100ms).
<code>class Serial
{
    private SerialPort port;
    Queue<byte[]> buffer;

    public Serial()
    {
        buffer = new Queue<byte[]>();
        port = new SerialPort("COM3", 19200, Parity.Even, 8, StopBits.One);
        port.DataReceived += port_DataReceived;
    }

    public void Open()
    {
        if (port.IsOpen)
        {
            port.Close();
        }

        port.Open();
    }

    void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
    {
        byte[] buff = new byte[port.BytesToRead];
        port.Read(buff, 0, port.BytesToRead);
        buffer.Enqueue(buff);
    }
}
</code>
I don't have any start sign in transmission.
Delay between frames is min. 3.5 chars, and max delay between chars is 1.5 chars.
Comment: Serial ports don't have any concept of packets.  They are totally byte-oriented, so it's wrong for you to expect that "they should come in one piece".  Your reading code must deal with reading any number of bytes and finding packet boundaries.
Answer: This is entirely normal, serial ports are very slow devices.  The DataReceived event is fired as soon as one byte was received.  You'll need to call Read() and pay attention to the value it returns, the number of bytes it was able to retrieve from the input buffer.  Which might be more than one but is only very rarely equal to the number of bytes in a "packet", that could only happen if the machine got very slow for some reason.
Beware that the debugger is one way to make it that slow, a breakpoint or single-stepping the event handler code gives the driver enough time to receive all the bytes in a packet.  So that the Read() call returns them all.  But that stops working as soon as you stop debugging that code.
You could use the ReceivedBytesThreshold property to delay the event but that can only work when a packet has a fixed size.  Simply append the bytes you get into byte[], using the 2nd argument of the Read() call.  And don't process the packet until you have them all.
Comment: It is not very hard to deduce how many bytes you should receive. Most MODBUS frames provide clues such as the function code and the number of requested/transmitted data. And you can (must?) check the consistency of the CRC, which delimitates the end of the frame. Example: if you receive a "read multiple registers" request, the frame has a fixed size. If you receive a "write multiple registers" request, the length of the frame (in bytes) is embedded in the frame itself.
Comment: But I don't know how many bytes will be in a frame.
DataReceived works almost fine, but it doesn't always return full frame, sometimes it's split in two.
Comment: ModBus is kinda primitive.  Hopefully you've got TCP frames and can use the Length field in the frame.  If not then you'll have to figure out the length of the frame from the Function code.  Maybe you ought to go shopping for somebody else's solution, contact your reseller from references.
Comment: Well, in fact it's RTU, not TCP.
And I can't buy a solution, since this is my (my group's) academic project.


Is there any Namespace or Package in Any Language that Check English Grammar Check

Question: I want to make many large software systems which requires the functions that have features like English Grammar Check and all other validations/manipulations that can be done in English. Is there any package available in any programming language that gives me these resources? Just imagine I am making a software like MSword, and I want to add Grammar Validations in my software same as in MSword, is there anything available or I have to code everything from scratch? How hard it would be according to you? How much time would it take?
Answer: There is LanguageTool for Java. It supports many languages including English and you can add your own rules. Just don't expect the check to be perfect; Word's isn't either.


Replace urllib.request urlopen in PHP

Question: I have a URL which can not download using video file using PHP. I have to run it ones in browser so that code can start downloading videos from it.
I have tried using curl, it fails to download video on first hit to url through code.
I have tried using Ajax call by creating video blob, it works however because of cron job, javascript can not work.
I need solution in PHP.
Answer: Use Guzzle in PHP
<code>   require_once('guzzle/vendor/autoload.php');

   use GuzzleHttp\Client;
   use GuzzleHttp\Exception\RequestException;

   $client = new Client();
   $url = 'video url'; // URL of the file to download
   $file_name = 'filename.mp4';
   $saveTo = $save_file_loc = __DIR__."/".$file_name; // Local path to save the file

   try {
       $response = $client->request('GET', $url, ['sink' => $saveTo]);
       echo "File downloaded successfully to " . $saveTo;
   } catch (RequestException $e) {
       echo "Error: " . $e->getMessage();
       if ($e->hasResponse()) {
           echo "\nHTTP Status Code: " . $e->getResponse()->getStatusCode();
       }
   }
</code>
Comment: I suggest you to use $url like this: $response = $client->request('GET', "".$url."", ['sink' => $save_file_loc]);
Comment: This code is working correctly when run independently, however when I put it in PHP file with rest of the code, then Guzzle related codes start giving errors. Any idea how it can be fixed? I am using latest version of Guzzle with correct version of PHP 8.1 as needed by Guzzle. Current error showing: Fatal error: "Uncaught InvalidArgumentException: URI must be a string or UriInterface in vendor/guzzlehttp/psr7/src/Utils.php:461"

Replace urllib.request urlopen in PHP


Firebird - Select com data menor que 10 dias

Question: Pesquisei mas não entendi como usar a função DATEDIFF() no FIREBIRD o que eu preciso é que a consulta me retorne registros com datas até 10 dias anteriores a partir da data atual.
Obs: Entenda data atual pelo dia em que a consulta for feita.
Vou colocar um exemplo que funcionaria no mysql onde tenho melhor dominio, mas o que eu preciso é um exemplo de como ficaria em FIREBIRD.
select
pag_id as ID,
pag_data_emissao as EMISSAO,
pag_valor AS VALOR,
pag_historico AS HISTORICO,
pag_saldo AS SALDO,
pag_debito_credito as deb_cred
from tab_banco_lanc where pag_data_emissao >= DATE_SUB(curdate(),INTERVAL 10 DAY)

Answer: A função DATEDIFF do Firebird retorna a diferença entre uma data e outra, de acordo com o primeiro parâmetro da função, que podem ser:

day : diferença em dias;
month : diferença em meses;
year : diferença em anos.

Sintaxe:
DATEDIFF( <YEAR | MONTH | DAY>, DATA_1, DATA_2 )

Fica assim, a resposta para a sua questão:
SELECT * FROM DOCUMENTO WHERE datediff(day, :DATA, DATAHORA_INICIO) < 10;

Compare o resultado do DATEDIFF com o numero de dias que você deseja. Neste caso irá retornar todos os documentos da tabela onde a diferença em dias entre a DATAHORA_INICIO, e a data do parâmetro, :DATA, for menor que 10;
Comment: Obrigado, consegui testar com a sua resposta, tive só que mudar os parametros e nome da tabela, mas rodou certinho !
Comment: Ah sim.. esqueci de mudar o exemplo de acordo com a sua tabela!
Comment: Estou com um problema parecido http://pt.stackoverflow.com/questions/120596/como-fazer-um-sql-que-consulte-apenas-o-dia-de-uma-data
Answer: Consegui usando o DATEADD e negativando o parametro, achei mais simples:
select
    CONTROLE as ID,
    DATA as EMISSAO,
    VALOR AS VALOR,
    HISTORICO AS HISTORICO,
    SALDO AS SALDO,
    DEBITOCREDITO as deb_cred
from BTR06
where DATA >= DATEADD( - 5 DAY TO CURRENT_DATE ) and CODIGO=7


Playing the trombone: what does "in stand" mean?

Question: I play in a jazz band and we are playing some Latin pieces. In "One Note Samba" there is written "in stand". What does that mean? How to play that with the trombone?
Answer: you literally just point your bell into the stand, not directly touching it, but the sound should be muted by the stand
Answer: You put your bell about 6-8 inches from the stand, so it gives the trombone a muted effect.
Answer: If your worried about catching your bell on the stand, try a bucket mute for a similar effect. It may be about keeping control of volume, or it could be a stylistic effect.
Answer: I think the 'Stand' in the mind of the arranger is the dance band type, a substantial wooden structure used to front the band and bear a logo as well as merely support music.   Pointing the instrument into this would have rather more effect than into the lightweight tripod stands we commonly use.


Error in passing the hidden values to JavaScript in asp.net

Question: Problem with passing values to Javascript, am I going wrong in passing the value pls help.
var percentage= parseInt(document.getElementById("<%=hid_Percentage.ClientID%>").value);
        var color = document.getElementById("<%=hid_Color.ClientID%>").value;
        var progress1 = new RGraph.VProgress('progress1', percentage, 100);
                    progress1.Set('chart.colors', [color]);
                    progress1.Set('chart.tickmarks', false);
                    progress1.Draw();

I have 2 hidden fields
  <asp:HiddenField ID="hid_Percentage" runat="server" />
                <asp:HiddenField ID="hid_Color" runat="server" />

And this is how I pass value to the hidden field in code behind in asp.net
        double value = (read * 100 / count);
        string vProgressColor = "'#e01600'";
        hid_Percentage.Value = Convert.ToString(value);
        hid_Color.Value = vProgressColor;

The value for percentage is passed correclty as the graph is drawn using that value. But the color is emply. it is not getting the color.,
Answer: There is nothing wrong with your code. I would put an alert(color); to double check. If you get the colour printed out, it means the problem is in the RGraph.VProgress.
Answer: I doubt here:
string vProgressColor = "'#e01600'";
try removing ' ' from your string value
string vProgressColor = "#e01600";


Find the sum of real roots of a biquadratic equation

Question: Given the following biquadratic equation:
$$x^4-3x^3-2x^2-3x+1=0$$
Find the sum of its real roots.
Let $$f(x)=x^4-3x^3-2x^2-3x+1$$
By observing the behaviour of $f^{'}(x)$, I was able to deduce that the equation has only two real roots, both of then being positive.
Also, using a graphing calculator, the sum is found to be approximately $4$. The answer ia 4.
By Vieta's theorem the sum of roots comes out to be 3. So the sum of the non real roots must be -1.
One potentially useful representation of the equation(I have no idea how it is actually useful) was
$$(x^2-1)^2=3(x^2+1)$$, which clearly shows x cannot be negative, if it is to be a solution.
How do I proceed, without referring to the results found by the graphing calculator.
Answer: You can have
$$x^4-3x^3-2x^2-3x+1=(x^2-4x+1)(x^2+x+1)$$
with
$$x^2+x+1=\left(x+\frac 12\right)^2+\frac 34\gt 0.$$
Comment: Thanks, the hint was more than enough!
Comment: @Shubham: You are welcome. BTW, is there any reason not to accept any answer in the following question?: http://math.stackexchange.com/questions/886993/finding-the-range-of-values-of-frac-sqrt1x2-1x
Comment: No specific reason, it's just difficult to decide which one is the best. I upvoted all of them!
Comment: @Shubham: Fine. I just ask:)


Botão submit fechando modal

Question: Olá!
Criei uma modal para chamar os inputs de login.
Porém quando clico em "Login" no botão submit, caso esteja vazio ou com informações incorretas, ele fecha a modal e não me exibe mensagem de erro como esperado...
Eu estou começando a aprender php e javascript, então não sei o que estou fazendo de errado, se puderem me ajudar eu agradeço!
Código que estou utilizando na minha index.php para chamar a modal:

<button type="button" class="btn btn-primary" data-toggle="modal" data-target="#loginmodal">Login</button>

Login

        <button type="button" class="close" data-dismiss="modal" aria-label="Close">
          ×
        </button>

      <?php include 'loginform.php';?>

Minha página de login "loginform.php":
<?php
session_start();
?>

<!DOCTYPE html>

    <meta charset="UTF-8">

<?php
                    if(isset($_SESSION['nao_autenticado'])):
                    ?>

ERRO: Usuário ou senha inválidos.

                    <?php
                    endif;
                    unset($_SESSION['nao_autenticado']);

?>

    <form action="login.php" method="POST">

                <input name="usuario" name="text" class="input is-large" placeholder="Seu usuário" autofocus="">

                <input name="senha" class="input is-large" type="password" placeholder="Sua senha">

        <button type="submit" name="login" class="button btn btn-secondary" >Login</button>
        <button type="button" class="btn btn-secondary" data-dismiss="modal">Fechar</button>

    </form>

Comment: Esqueci de mencionar que a modal apenas fecha quando tem alguma informação de login incorreta. Quando dá certo ele me redireciona para a página desejada.
Depois de dar submit e abrir a modal outra vez, o erro está lá aparecendo...
Comment: Esqueceu de informar onde que você está criando $_SESSION['nao_autenticado']
Comment: Qual a diferença entre login.php e loginform.php? O que faz a login.php?
Answer: Vai ter que usar Ajax. O problema é que quando Clica no botão de Submit a propriedade action do formulário redireciona o submit para mesma pagina, O que da a impressão que fechou o modal. Mais na verdade não.
usa assim:
$("form#CriaUmIDparaEle").submit(function(){
let obj = {
url:"login.php",
method: "post",
data: this.serialize(),
complete: function(retorno){
//retorno pode ser echo "1" ou echo json_e();
},
error: function(){
//404, 503 entre outro erros do servidor
}
}
$.ajax(obj);
});

Comment: Obrigado!
Consegui resolver

Botão submit fechando modal


Whats wrong with the following code? It's not compiling

Question: #include <iostream>
#include <vector>
using namespace std;

class Base
{
public:
      void Display( void )
      {
            cout<<"Base display"<<endl;
      }

      int Display( int a )
      {
            cout<<"Base int display"<<endl;
            return 0;
      }

};

class Derived : public Base
{
public:

      void Display( void )
      {
            cout<<"Derived display"<<endl;
      }
};

void main()
{
   Derived obj;
   obj.Display();
   obj.Display( 10 );
}

$test1.cpp: In function 'int main()':
test1.cpp:35: error: no matching function for call to 'Derived::Display(int)'
test1.cpp:24: note: candidates are: void Derived::Display()

On commenting out obj.Display(10), it works.
Comment: What compiler are you using ? It looks like `gcc` but is this the most recent code ? Why you get `$test1.cpp: In function 'int main()':` even though you have defined main as `void main()` ?
Comment: tried with gcc and vc++. Copied code from the vc++ editor, pasted gcc output.
Answer: You need to use the using declaration. A member function named f in a class X hides all other members named f in the base classes of X.
Why?
Read this explanation by AndreyT
You can bring in those hidden names by using a using declaration:
using Base::Display is what you need to include in the derived class.
Furthermore void main() is non-standard. Use int main()
Comment: @Muggen: It's illegal to declare `main` as having a return type of anything other than `int`. This particular implementation seems to just ignore this error and treat the code as if it declared `main` correctly.
Comment: He has defined main as `void main()` but how come he gets `$test1.cpp: In function 'int main()':` ?
Answer: You need to place -
using Base::Display ; // in Derived class

If a method name is matched in the Derived class, compiler will not look in to the Base class. So, to avoid this behavior, place using Base::Display;. Then the compiler will look into the Base class if there is any method that can actually take int as argument for Display.
class Derived : public Base
{
    public:
    using Base::Display ;
    void Display( void )
    {
        cout<<"Derived display"<<endl;
    }
};

Comment: is this something compiler-specific?
Comment: It works with the using. Could you please explain me whats happening without the using?
Comment: @Gunner : For historical reasons. Read my answer.
Comment: Shouldn't int Display(int) get derived anyway as it's declared as public.
Comment: @Gunner : Its gets derived but is hidden in the derived class.
Comment: @Gunner - It gets derived. But the problem is both the base and derived class has a method bearing same name. So, it is hidden.
Comment: @Prasoon: Why is it kept hidden if it got derived. What is the notion behind that?
Comment: @Mahesh: The name maybe same, but signature is different. It should be possible to invoke it without any ambiguity of redefinition.
Comment: @Gunner - In `void Display( void );` - **Display** is the method name, right ?
Comment: @Mahesh,Prasoon Saurav: I read the historical reason and now it's clear to me. Thanks all for the clarification.
Answer: You are masking the original function definition by creating a function in the derived class with the same name: http://www.parashift.com/c++-faq-lite/strange-inheritance.html#faq-23.8


Webview not properly sized Jetpack compose (Autosizing Webview Composable)

Question: I need to use WebView in place of Text composable (to display complex text and maths). Size of the WebView will depend on amount of content(text). But currently it only works when a fixed size modifier is applied. Without fixed size; WebView stutters while loading and many times it wont even show up.
I am loading content using loadWithBaseUrl() method.
I have tried using WebView composable from Accompanist library; Also tried my custom implementation; but it still wont work.
// implementation 'com.google.accompanist:accompanist-webview:0.24.3-alpha'

    LazyColumn(){
        item {
            val webViewState = rememberWebViewStateWithHTMLData(data = FakeData.HTML_DOC)
            Surface(
                modifier = Modifier.padding(8.dp, 8.dp).height(IntrinsicSize.Min)
            ) {
                WebView(
                    state = webViewState,
                    modifier = Modifier
//                        .size(400.dp, 200.dp)  // When fixed size applied problem disappears
                )
            }
        }

    }

Comment: I have a similar issue when trying to fit the WebView into a column with some other Composables. I made some progress on this by using `Modifier.height(IntrinsicSize.Max)` but it's still flaky. Have you filed an issue in the Accompanist GitHub?
Comment: Hello @Paul T. I have filed the issue just now. Feel free to suggest an improvement. here's the link: https://github.com/google/accompanist/issues/1224
Answer: Use custom AccompanistWebViewClient, override onPageFinished, you can get webPage height by evaluateJavascript.
val jsWebHeight = "(function() {\n" +
                        "\tvar body = document.body,\n" +
                        "\thtml = document.documentElement;\n" +
                        "\tvar height = Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight);\n" +
                        "\tvar width = html.scrollWidth;\n" +
                        "\tif (width > 0) return height;\n" +
                        "\telse return 0;\n" +
                        "})();"
override fun onPageFinished(view: WebView?, url: String?) {
     super.onPageFinished(view, url)

     view?.let{ webView ->
          val width = webView.width
          if (width > 0) {
               webView.evaluateJavascript(jsWebHeight) { result ->
                    result?.toIntOrNull()?.let { height ->
                         if (height > 0) {
                              // set webView height here, height is dp unit
                         }
                    }
               }
          }
     }
}


Looking for a good way to split a string on all-capital words

Question: For example I have an arbitrary string:
var = 'I have a string I want GE and APPLES but nothing else'
What's the best way to split the string in python so that I can obtain just 'GE' and 'APPLES'. In Java I'd split on spaces and then check each array element for two or more consecutive letters and grab the ones that do.
Is there a better way to do it in Python, I'm not particularly well versed in Python's regex?
Answer: Using str.isupper, str.split and a list comprehension:
>>> var = 'I have a string I want GE and APPLES but nothing else'
>>> [x for x in var.split() if x.isupper() and len(x) > 1 ]
['GE', 'APPLES']

Using regex:
>>> import re
>>> re.findall(r'\b[A-Z]{2,}\b', var)
['GE', 'APPLES']

Timing comparison:
>>> var = 'I have a string I want GE and APPLES but nothing else'*10**5
>>> %timeit [x for x in var.split() if x.isupper() and len(x) > 1 ]
1 loops, best of 3: 773 ms per loop
>>> %timeit re.findall(r'\b[A-Z]{2,}\b', var)
1 loops, best of 3: 491 ms per loop

#Input with huge words:
>>> var = ' '.join(['FOO'*1000, 'bar'*1000, 'SPAM'*1000]*1000)
>>> %timeit [x for x in var.split() if x.isupper() and len(x) > 1 ]
1 loops, best of 3: 224 ms per loop
>>> %timeit re.findall(r'\b[A-Z]{2,}\b', var)
1 loops, best of 3: 483 ms per loop

Comment: @Matt That depends on the word size I guess, tested both solutions with huge words and this time regex solution came out to be slower. See my updated answer for results.
Comment: @sreya I think the list comprehension version will work as is, and you need to change the regex to `r'\b[A-Z4]{2,}\b'`. Include any character that you want to match inside the character class.
Comment: Wow that's awesome, would you mind a quick explanation of `\b` or where a good link to learn `re` I tried looking up the `re` package before but it was a tad overwhelming
Comment: @sreya Docs: http://docs.python.org/2/library/re.html, `\b` is used for word-boundaries.
Comment: Just out of curiosity: Which of these would be more efficient in a large text file?
Comment: @Matt Regex version is fast.
Comment: Interesting results. Thanks for the test output!
Comment: Last question, if I were to modify it to include strings such as `'GE'` *or* strings that are capital and may include numbers `'G4'` how would you modify it?


How to force node.status=0

Question: I need to force the status value of a node=0 when the user has a certain role.
I've made
 function mymodule_node_save($node){
    if($node->type=="mytype") {
        global $user;
        if(in_array("simple",$user->roles)) {
            $node->status=0;
        }

    }
}

But the status is always saved as 1. What am i doing wrong?
Comment: You might also want to use constants NODE_PUBLISHED and NODE_NOT_PUBLISHED instead of 1 and 0.
Answer: @redhatlab is correct about Drupal 7 not invoking hook_node_save(). If you need to be sure the status is effectively set to 0, without other modules to alter it, I would use code similar to the following one.
function mymodule_node_insert($node) {
  mymodule_update_status($node);
}

function mymodule_node_update($node) {
  mymodule_update_status($node);
}

function mymodule_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'node_insert' || $hook == 'node_update') {
    $group = $implementations['mymodule'];
    unset($implementations['mymodule']);
    $implementations['mymodule'] = $group;
  }
}

function mymodule_update_status($node){
  if ($node->type == 'mytype' && in_array('simple', $GLOBALS['user']->roles)) {
    $node->status = 0;
  }
}

The code checks the roles assigned to the currently logged-in user. If you want to check the roles assigned to the node author, you should use $node->uid to load the user object of the node author. It is then generally preferable to check the user has a specific permission, rather then checking which roles are assigned to the user.
node_save() first invokes hook_node_presave(), and then hook_node_insert(), or hook_node_update(). The code I wrote would allow your module to be the last one changing the node status.
References

node_save()
hook_module_implements_alter()
Answer: There is not hook_node_save() in Drupal 7, but there is a hook_node_presave() that is fire when saving or updating content. So your code should look like:
function mymodule_node_presave($node){
    if($node->type=="mytype") {
        global $user;
        if(in_array("simple",$user->roles)) {
            $node->status=0;
        }

    }
}

How to force node.status=0


Double precision quotient?

Question: I ran into the following problem in a quiz I had the other day.

Consider the code fragment (assumed to be in a program in which all variables are legally defined):
int num1, num2;
double answer;

// program gets num1 and num2 from user, and values received
// are always non-zero ints between -100 and +100 (code not shown)

...

// compute precise quotient:
answer = (double) ( num1 / num2 );

After the assignment statement the variable answer, will hold the most precise quotient possible, accurate to several digits to the right of the decimal point  ...

So the choices are always, never, and sometimes. I choose never due to how the bracket works in this case, however my teacher said it's sometimes. I am a bit lost, so I hope someone can explain it.
Comment: Let's say `num1 = 25;` and `num2 = 5;`, then answer will be `5.0` ... so it's:  sometimes.
Answer: Since (num1 / num2) is parenthesized, and both num1 and num2 are integers, it will result in integer division, which discards the fractional part. If the expression had been (double) num1 / num2, num1 would have been casted to double first, and the result would always be accurate to multiple decimal points.
An example where the result is accurate: (double) (4 / 2) is the same as (double) (2)
An example where the result is not accurate: (double) (3 / 2) is the same as (double) (1)
Comment: Ok I get it now, for some reason I always thought (double) (4 / 2) would get me 2.0 instead of just 2.
Comment: @Michael: It does. But `2.0` is the same as `(double) 2`.

Double precision quotient?


Prove that If λ is an eigenvalue of A, then m(λ) = 0

Question: Prove that If $λ$ is an eigenvalue of $A$ and $m(x)$ is the minimal polynomial of $A$, then $m(λ) = 0$.
I've been advised to use the fact that $m(A) = m_0 I + m_1 A + \dots + m_rA_r$, and use that $(A^i)x = (λ^i)x$.
How would I go about proving this?
Comment: It is unclear to me what the facts you are advised to use actually mean (and I would say that $m[A]=0$ by definition of $m$). On the other hand this is one of those occasions where "on the eigenspace of $A$ for $\lambda$, a polynomial $P[A]$ of $A$ acts by the scalar $P[\lambda]$" immediately does the job.
Answer: Let $v$ be an eigenvector of $A$ associated to the eigenvalue $\lambda$. Then
$$ m(A)v = (A^n + m_{n-1}A^{n-1} + \dots + m_0 I)v = \lambda^n v + m_{n-1}\lambda^{n-1}v + \dots + m_0 v = m(\lambda)v. $$
Thus, we see that $m(\lambda)v = 0$ and since $v \neq 0$, we must have $m(\lambda) = 0$.
Answer: By definition, $m(A)=0_{n \times n}$. Then if $x$ is a $\lambda$-eigenvector,
\begin{align}
0 &= m(A)x\\
&= m_0 x + m_1 Ax + \cdots + m_r A^r x\\
&= (m_0 + m_1 \lambda + \cdots + m_r \lambda^r) x\\
&= m(\lambda) x.
\end{align}


inversely proportional term in task

Question: let us consider following problem:
The amount of time taken to paint a wall is inversely proportional to the number of painters working on the job. If it takes 3 painters 5 days to complete such a job, how many days longer will it take if there are only 2 painters working?
so let us  recall terminology of inversely proportional,if   one  number is inversely proportional to  another number it means  that
$k=c*1/x$  where  $k$ is number which is inversely proportional of number $c$ and $1/x$ is inversely proportional coefficient,so in our case
$5=3*1/x$   so $x=3/5$ ,it means that one painter paints wall in $3/5=0.6$ days right? and $2$  painter will paint $2/0.6=3.3$ days right?so  longer day would be $5-3.3=1.7$,but here
http://www.majortests.com/gre/numeric_entry_expl.php?exp=473031322437243236
answer is $2.5$,pleas help me
Answer: Let $d(n)$ be the number of days required when there are $n$ painters. We're told that $d(n)$ is inversely proportional to $n$, so there is a constant $c$ such that $$d(n)=\frac{c}n\;.$$ We're also told that $d(3)=5$, so $$5=d(3)=\frac{c}3\;,$$ and therefore $c=3\cdot5=15$. Therefore $$d(2)=\frac{15}2=7.5\;.$$ Thus, two painters will require $7.5-5=2.5$ more days than $3$ painters.
Another way to look at inverse proportionality is this: if $d$ and $n$ are inversely proportional, then multiplying $n$ by some factor $a$ causes $d$ to be multiplied by $\frac1a$. When we reduce the number of painters from $3$ to $2$, we're multiplying $n$ by $\frac23$; $\frac1{2/3}=\frac32$, so the effect is to multiply $d$ by $\frac32$. And $\frac32\cdot5=\frac{15}2=7.5$, so once again we see that the increase in time required is $2.5$ days.
Comment: @dato: No, the *inversely* part of *inversely proportional* ensures that the two quantities move in opposite directions: if the number of painters goes up, the number of days goes down, and *vice versa*.
Comment: @dato: I think that you're doing very well, and I wish you the best of luck on the GRE.
Comment: i was thinking that because it is inversely proportional,then many  painter will take more time
Comment: @dato: You're very welcome. (It must be difficult reading mathematics in a language as different as English is from Kartuli, which I'm guessing is your first language.)
Comment: yes yes it is,i am preparing for  GRE,it is in 15 august,in this center http://www.americancouncils.ge/ge/
Comment: thanks wish you everything best also

inversely proportional term in task