text:
Q: Nested \if in align environment not working I have the two following macros that I use to add some kind of "revision" to my latex files:
\newcommand\rem[2][1]{
  \ifdefined\revision
    \ifnum \revision = 0
      \textcolor{red}{\sout{#2}}
    \else
      \ifnum \revision < #1 #2 \fi
      \ifnum \revision = #1 \textcolor{red}{\sout{#2}} \fi
    \fi
  \fi
}

\newcommand\remb[2][1]{
  \ifdefined\revision
    \ifnum \revision = #1 #2 \fi
    \ifnum \revision < #1 #2 \fi
  \fi
}

Basically, \rem is used to indicate stuff that has been removed and \remb is used to remove block of code that cannot be removed with \rem, a typical use (that works):
 % Code that works
\remb[2]{ % In revision 2, the whole list was removed.
  \begin{itemize}
  \item \rem[2]{A}
    \remb[1]{ % In revision 1, the two last items were removed.
    \item \rem[1]{B}
    \item \rem[1]{C}
    }
  \end{itemize}
}

I want to use the above in an align environment to remove part of equations, but it does not work:
\begin{subequations}
  \begin{align}
    \remb{A & B\\} % Small code that does not work
            & G
  \end{align}
\end{subequations}

\begin{subequations} % "Complete" code
  \begin{align}
    \remb{
    \rem{A} & \rem{B}\\
    \rem{C}
    } & D\\
    \remb{
      & \rem{E}\\
      & \rem{F}\\
    }
    & G
  \end{align}
\end{subequations}

Without the \ifdefined and \ifnum inside the \rem and \remb macro (e.g. by conditionally defining the macro), it works. Is there a way to make it work with the conditional statement inside?
Error I get with the above code:
! Incomplete \ifnum; all text was ignored after line 51.
<inserted text>
                \fi
l.51   \end{align}

Full code:
\documentclass{article}

\usepackage{amsmath,amsthm,amsfonts,amssymb}

% Works only if revision is 1
\def\revision{2}

\newcommand\remb[2][1]{
  \ifdefined\revision
  \ifnum\revision=#1 #2\fi
  \ifnum\revision<#1 #2\fi
  \fi
}

\begin{document}

\begin{subequations}
  \begin{align}
    \remb{A & B\\}
            & G
  \end{align}
\end{subequations}

\end{document}

A: Using conditionals that way in conditionals is always risky and usually doesn't work, because conditionals cannot straddle cells.
Hide the conditionals until the last moment.
\documentclass{article}

\usepackage{amsmath,amsthm,amsfonts,amssymb}

\makeatletter
\newcommand{\revisionTF}[2]{%
  \ifdefined\revision
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {#1}{#2}%
}
\newcommand{\revisionT}[1]{\revisionTF{#1}{}}
\newcommand{\revisionF}[1]{\revisionTF{}{#1}}

\newcommand{\revisioncompareTF}[3]{%
  \ifnum\revision#1\relax
    \expandafter\@firstoftwo
  \else
    \expandafter\@secondoftwo
  \fi
  {#2}{#3}%
}

\newcommand\remb[2][1]{%
  \revisionTF
    {%
     \revisioncompareTF{=#1}
       {EQUAL #2}
       {\revisioncompareTF{<#1}{LESS #2}{}%
     }%
    }%
    {NO REV}
}

\begin{document}

Revision is undefined:
\begin{align}
\remb{A & B\\}
  & G
\end{align}

\def\revision{1}
Revision is 1:
\begin{align}
\remb{A & B\\}
  & G
\end{align}

\def\revision{2}
Revision is 2:
\begin{align}
\remb{A & B\\}
  & G
\end{align}

\def\revision{2}
Revision is 2:
\begin{align}
\remb[3]{A & B\\}
  & G
\end{align}

\end{document}


text:
Q: Should I use Liouville thm or continuity? Make an examples $f:\Bbb{C}\to\Bbb{C}$ holomorph (If it exists) with the properties:(Justify your answer)
$|f(z)|\leq \frac{1}{100}$ if $|z|\leq 1$ and
$|f(z)-1|\leq \frac{1}{100}$ if $|z-3|\leq 1$.
My attemp: I confuesd to   use Liouville thm or continuity?
Please guide me how should I think about it!

A: Let us define $g(z)=0$ on $|z|\le 1$ and $g(z)=1$ on $|z-3|\le 1$. Then $g$ is analytic on a neigoborhood of $K=\{|z|\le 1\}\cup \{|z-3|\le 1\}$. Note that $\Bbb C\setminus K$ is connected. By Runge's theorem, for every $\epsilon>0$, there exists a polynomial $p(z)$ such that
$$
|g(z)-p(z)|\le\epsilon,\quad\forall z\in K.
$$ If we let $\epsilon =\frac{1}{100}$, then $p$ is a function we are looking for.

A: You want an entire function satisfying the given two properties.
What about the constant function $f(z)=1/200$ ?

redpajama_set_name: RedPajamaStackExchange


text:
Q: Where to store the images and fetch them from there URL I have written a code, it switches some ImageView using ViewPager. I can't save the images in the drawable folders as they take a lot of space. I want to fetch them from URLs.
The only confusion I have is about image storage. Where should I store all these images so that they could be fetched easily from their URLs ?
Here is my code.
public class ImageAdapter extends PagerAdapter {

    ImageView imageView;

    Context context;
    private String[] GalImages = new String[] {
        "URLs","URLs"
        };

    ImageAdapter(Context context){
        this.context=context;
    }
    @Override
    public int getCount() {
      return GalImages.length;
    }

    @Override
    public boolean isViewFromObject(View view, Object object) {
      return view == ((ImageView) object);
    }

    @Override
    public Object instantiateItem(ViewGroup container, int position) {
      imageView = new ImageView(context);
      int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
      imageView.setPadding(padding, padding, padding, padding);
      imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
      Picasso.with(context).load(GalImages[position]).into(imageView);
      ((ViewPager) container).addView(imageView, 0);
      return imageView;
    }

    @Override
    public void destroyItem(ViewGroup container, int position, Object object) {
      ((ViewPager) container).removeView((ImageView) object);
    }
}

A: Do you intend to upload the images to a remote server? Then any image storage service with permalink to the image will do.


text:
Q: Python: Getting all Urls from every open Google Chrome Tab I need to get all the urls from all open Google Chrome tabs in python 3 without intefering with the user. Im on Windows 10 using Microsoft Visual Studio Python3
Ive tried:
Opening it directly with open(path to current tabs)-- doesnt work because i have no permission- i think its locked because chrome activly writes to it.
Current_Tabs_Source = open(r"C:\Users\Beni\AppData\Local\Google\Chrome\User
Data\Default\Current Tabs", "r")
Current_Tabs_Raw = Current_Tabs_Source.read()
print(Current_Tabs_Raw) #just for checking

PermissionError: [Errno 13] Permission denied
Opening through sglite3 -- doesnt work because its locked. And i cant find a password anywhere. Ive tried to open the History for the urls but it doesnt work anyways.
import sqlite3
from os import path

data_path = path.expanduser('~') + r"\AppData\Local\Google\Chrome\User
Data\Default"
files = listdir(data_path)
history_db = path.join(data_path, 'history')

c = sqlite3.connect(history_db)
cursor = c.cursor()
select_statement = "SELECT urls.url, urls.visit_count FROM urls, visits
WHERE urls.id = visits.url;"
cursor.execute(select_statement)

results = cursor.fetchall()

print(results) #just for checking

sqlite3.OperationalError: database is locked
Using selenium and a 3rd party chrome extension to copy all urls to the clipboard -- doesnt work because these extensions only work in the active selenium window. So the Windows with the tabs in it that i want dont get copied.
Ive considered hacking together a chrome extension that copys the urls every 30 sec to a temp file. But i only know minimal Javascript so this thing is driving me mad.
So does anyone know a way to do this in Python ? Any other solution is greatly appreciated.

A: If you want to access the database, you should close all browsers.
(Source)

A: When we're accessing the SQLite database of any browser, we have to close that particular browser first.
Moreover, the SQL command being used here will fetch all the duplicate rows.
Need to change `select_statement'
select_statement = "SELECT distinct urls.url, urls.visit_count FROM urls, visits WHERE urls.id = visits.url;"

Further, we need to add a loop to print all the 'urls' from history database of chrome.
for url, count in results:
    print(url)  # print urls line by line

However, this will give us the whole history of the Chrome browser but not the required URLs of all the presently opened tabs.

A: You can use windows shadow copy service to make copy of locked sqlite database. And then read it normally.
There is python module for that https://github.com/sblosser/pyshadowcopy


text:
Q: Module build failed (from ./node_modules/react-scripts/node_modules/babel-loader/lib/index.js)
Tried running all of them:
npm install @babel/core @babel/preset-env
npm install -D babel-loader @babel/core @babel/preset-env webpack
npm install -D babel-loader @babel/core @babel/preset-env @babel/preset-react webpack
npm install -D babel-loader@7 babel-core babel-preset-env babel-preset-react webpack
npm install @babel/cli @babel/core @babel/node @babel/preset-env

A: Error seems clear, TinderCards is already declared. What is TinderCards.css exporting that you are importing?
-import ./TinderCards.css maybe interpreted as importing TinderCards and so the babel parsing error.
-Also, could you share contents of ur TinderCards.css file.
npmjs.com/package/Babel#methods
This shows how Babel can help with different file formats, and your error shows that error is @babel/parser/lib... so there's error in parsing. I don't know more details of your files on all this but this may help.


text:
Q: "let" vs "const" vs "var" vs "state" in JS I'm learning React.js recently,
and I have some questions,

*

*As we know setState is asynchrony, if we don't use js framework, we will use let const or var to setting variable, it's synchrony, but why we should much more use state instead of let const var to setting variable in React.js?

*Some scenario I use state but it cannot work very well to my WebApp, so that I try to use let to set my variable, and it can work very well, but I think if I use let rather than state, is it not a good idea because I wasted React.js advantage?
thank you for your help :>

A: Simply, in most cases we use state if we will use it in the UI ( in the JSX mockups ), as when it updates with setState the UI updates, this doesn't happen with normal javascript variables as it re-initializes when the component updates.
That's besides that other hooks, just updates regard to stateful dependencies only, like useEffect, useMemo, useCallback.


text:
Q: DVCS - How often and when to commit changes There is another thread here on StackOverflow, dealing wih how often to commit changes to source control. I want to put that in the context of using a DVCS like git or mercurial.

*

*How often and when do you commit?

*Do you only commit changes when they
build correctly?

*How often and when do you push your changes (or file a pull request or similar)?

*How do you approac developing a complex feature / doing a complex refactoring requiring many places to be touched? Are "private commits" that won't build ok? When finished, do you push them also to the master repository or do you bundle all your changes into a single changeset before pushing?

A: I'd commit changes to my DVCS (my own topic or task branch) very, very often, this way I can use it not only for "delivering changes" but also to help me while I work: like "why this was working 5 minutes ago and it's not working anymore?" If you commit often you can just run a diff.
Also, a technique I found very, very good is using it to "self-document refactors". Let me explain: if you've to do a big refactor on a topic branch and then review the change as a whole (having modified a nice set of files), you'd probably get lost. But, suppose you checkin on every "intermediate step" and document it with a comment, then you're creating some sort of "movie" of your own changes helping to describe what you've done! Huge for reviewers.

A: I commit a lot; when adding functions or even reformatting my sources.
I use git and do most of my work on non-shared branches. And when I've added enough little changes that count as a block, I use git rebase to collect the smaller related changes into larger chunks and commit that to the main branches.
This way, I have all the advantages of committed code that I can go backwards or forwards in, but I don't have to commit all my mistakes, and bactracks to the main history.

A: It depends on the nature of the branch ("line of development") you are working on.
The main advantage with those DVCS (git or mercurial) is the ease you can:

*

*branch

*merge

So:

1/ How often and when do you commit?
  2/ Do you only commit changes when they build correctly?

As many time as necessary on a private branch (for instance, if it compiles).
The practice to only commit if unit tests pass is a good one, but should only apply to an "official" (as in "could be published or 'pushed'") branch: in your private branch, you merge a gazillon times if you need to.
The only thing is: do some merge --interactive to reorganize your many commits on your private branch, before replaying them on your main development branch, where you can pass some tests.

3/ How often and when do you push your changes (or file a pull request or similar)?

Publication is another matter and should be done with a "clear" history (coherent merges, representing a content which compile and pass some tests).
The branch you publish should be one where the history is never rewritten, always updated.
The pace of the publications depends on the nature of the remote branch and of the population pulling that branch. For instance, if it is for another team, you could push quite often. If it is for a system-wide integration testing team, you will push a lot less often.

4/ How do you approach developing a complex feature / doing a complex refactoring requiring many places to be touched? Are "private commits" that won't build ok? When finished, do you push them also to the master repository or do you bundle all your changes into a single changeset before pushing?

See 1. and 2.: patch first in your own private branch, then reorganize your commits on an official (published) patch branch. One single commit is not always the best option if the patch involves several different "activities" (or bug fix).

A:
How often and when do you commit?

Very frequently.  It could be as much as a few times in a hour, if the changes I've made work and make up a nice patch.  Or it could be every few hours, depending on whether I am spending longer debugging things, or experimenting with risky changes.

Do you only commit changes when they build correctly?

Yes, almost always.  I can't think of a reason right to check in code that didn't build correctly.  There's plenty of reasons you might check in code that doesn't run correctly (in a branch) though.

How often and when do you push your changes (or file a pull request or similar)?

Normally only when a feature is complete and ready for integration testing.  That means it has passed unit tests and other relevant tests, and the code/patch is clean enough that I consider it ready for review.

How do you approac developing a complex feature / doing a complex refactoring requiring many places to be touched? Are "private commits" that won't build ok? When finished, do you push them also to the master repository or do you bundle all your changes into a single changeset before pushing?

I would create a named branch for the feature (which would have traceability across design docs and Issue Tracking system).  Commits that don't build would only really be ok on a private branch as an intermediate step, but would still be exceptional.  Currently I don't rebase and merge the entire feature branch into a single changeset, though it is something I'm looking at doing in future.  Changes are only pushed when appropriate tests are all passed.

A: I follow this kind of flow
alt text http://img121.imageshack.us/img121/3272/versioncontrolsysbestpr.png
(Here is the original image url)
I guess this says pretty everything. Basically I would do a check-in after implementing a full working use case / user story (depends on your software process). The major important thing is that you check-in things that work in the sense that they compile. Never break the build!
Doing a commit after each user story/use case has the advantage that you have a better tracking of past versions and undoing changes is much easier.


text:
Q: Setting focus to an embedded Flash movie/HTML embed element using Javascript/jQuery Is there a way to set focus to the embed HTML element using JavaScript? Test case: embedded YouTube videos on a page.
I have no control over the embedded Flash element. So, is there a way to set focus on it by using only JavaScript?
I read somewhere that calling the element.focus() method works only in IE. I need a browser-independent way that works in Chrome/Firefox.
Thanks!

A: This only works in Internet Explorer.
http://kb2.adobe.com/cps/155/tn_15586.html

A: I've tried to do this too, and ended up to a nice solution using jquery:
var gotoflash=jQuery("#flash_file").offset().top;jQuery("html:not(:animated),body:not(:animated)").animate({ scrollTop: gotoflash}, 1000);
where: <div id="flash_file"> flash object code here </div>

A: It can be done by adding flash content dynamically, for example with swfobject.

A: I haven't confirmed this, but you could try:
function thisMovie(movieName) {
    if (navigator.appName.indexOf("Microsoft") != -1) {
         return window[movieName];
    } else {
         return document[movieName];
    }
}

    // Call from within another function:
    thisMovie("FlashObjectID").focus();
    thisMovie("FlashObjectID").showFlash();
    // showFlash() is an AS3 ExternalInterface call from JS to .swf which establishes the TextInput.setFocus(); method

source: http://www.htmlforums.com/archive/index.php/t-64150.html


text:
Q: Laravel - Image does not show up syntax error, unexpected '}', expecting ',' or ')' (View: C:\xampp\htdocs\ramashoes\resources\views\admin\show.blade.php)
i got that message
after wrote this code
brand}}/{{$shoes->gambar}}')}}" class="card-img-top">
i write this before
brand}/{$shoes->gambar}')}}" class="card-img-top">
but that result is
enter image description here

A: In this line
brand}/{$shoes->gambar}')}}" class="card-img-top">

replace single quote with double quote:
brand}/{$shoes->gambar}")}}" class="card-img-top">

I think you can omit the single curley braces too:
brand/$shoes->gambar")}}" class="card-img-top">

A: brand.'/'.$shoes->gambar.')}}" class="card-img-top">


text:
Q: Issues creating cloudformation resource I've been playing around with creating a test Cloudformation resources and it's not been so straight forward.
I've hit a stumbling block and not sure  how to resolve it.
As part of my test application I want to have my resource create a lambda.  But when I put the following into my code.
def create_lambda(session:SessionProxy,identifier:str):
 ARCHIVE = './lambdas/Hello.zip'
 BUCKET_NAME = 'hello-function-910283989807'
 ZIP_NAME = 'Hello.zip'
 REGION = 'us-east-2'
 s3_client = session.client("s3", region_name=REGION)
 s3_client.create_bucket(Bucket=BUCKET_NAME,CreateBucketConfiguration={'LocationConstraint': REGION})
 s3_client.put_object(Body=ARCHIVE, Bucket=BUCKET_NAME, Key=ZIP_NAME)

Even if I don't run this function, after submitting the resource and upon creating a test stack using this resource I get the following error appear in the cloudformation stack events.
Lambda function handler threw an uncaught exception: Unable to import module 'xxxxx_notifications_app.handlers': No module named 'xxxxxx_notifications_app'

I can't make sense of this.  It seems that just having the put_object in my code causes this to occur?


text:
Q: Back button to two different JSPs I had two JSP pages, say page A and page C.
Clicking on a particular hyperlink on A causes C to load. There is a back button on C which always goes back to page A.
Also, now I added another page B and when a particular link is clicked on it, page C loads again.
Now, if I click the "back" button, it still goes back to page A. How can I make the back button function in a way that it takes me back to the calling JSP?
Thanks in advance.

A: You should not hard code the back button link in page C. Instead, send the caller page as a parameter to the page C. And set that parameter in the back button link.
Here is how the pages look like:
Page A
Page C

Page B
Page C

Page C
Back


text:
Q: What is the fastest way to add hyperlinks to worksheet? As the title says.
Adding values first to array and then to worksheet works really fast (15ms for 8000 cells, compared to 350ms when looping on to worksheet). But is there a similar way to add hyperlinks very qickly? Looping direcly on worksheet each cell takes its tool really hard.
I would like to keep same visible value for all cells with custom hyperlinks.
Edit:
                        With Me.RangeTarget(2, mvaln).Resize(rowi + 1)
                        Select Case qcolumn.Preprocess
                        Case 1
                            For i = 0 To UBound(rsrows, 2)
                                localcol(i, 0) = Application.WorksheetFunction.Trim(rsrows(j, i))
                            Next
                            .Value2 = localcol
                        Case 2
                            For i = 0 To UBound(rsrows, 2)
                                localcol(i, 0) = Application.WorksheetFunction.Degrees(rsrows(j, i))
                            Next
                            .Value2 = localcol
                        Case 3
                             For i = 0 To UBound(rsrows, 2)
                                localcol(i, 0) = Application.WorksheetFunction.Radians(rsrows(j, i))
                            Next
                            .Value2 = localcol
                        Case 4
                            For i = 0 To UBound(rsrows, 2)
                                If LenB(rsrows(j, i)) > 0 Then
                                    Me.RangeTarget(2 + i, mvaln).Hyperlinks.Add Anchor:=Me.RangeTarget(2 + i, mvaln), Address:=rsrows(j, i), TextToDisplay:="Link"
                                Else
                                    Me.RangeTarget(2 + i, mvaln).ClearContents
                                End If
                            Next
                        Case 5
               ... ... ...

This is my current code... at 'case 4' I'd like to avoid looping. rsrows(j, i) is value that needs to be put into sheet. At case 1 to case 3 you can see I put all in temporary array and then on worksheet... but can't do the same with hyperlinks to speed things up.

A: I'm not sure what value rsrows(j, i) contains.  Whether it is a URL/File Path or an internal cell reference.  Either way, just use the =HYPERLINK() formula with either .Value2 = or .Formula =
For i = 0 To UBound(rsrows, 2)
    If LenB(rsrows(j, i)) > 0 Then
        localcol(i, 0) = "=HYPERLINK(" & rsrows(j, i) & "," & "Link" & ")"
    Else
        localcol(i, 0) = vbNullString
    End If
Next
.Formula = localcol
'.Value2 = localcol

P.S. If you need some help linking to cells within the file take a look this post:
Excel hyperlink to a specific cell


text:
Q: XSLT How to split string into multiple elements? Im facing a problem which Im struggling with right now for approx 2 days trying to find a solution. I found solutions to every possible choice but not for mine.
I have an XML file on Input consisting of this:
<Data>
    <AFU abc="r20r50" def="r14r105" />
    <AFU abc="r201r7" def="r4r165" />
    <AFU abc="r147r502" def="r44r10" />
</Data>

for the transform I am using XSLT 1.0 I cannot use the new one thats why Im struggling.
the problem is I need to store values from attributes but I need to split them first. Basically what I need is to separate numbers from letters... I mean something like this:
How output XML should look like:
<Data>
    <element>20</element>
    <element>50</element>
    <element>201</element>
    <element>7</element>
    <element>147</element>
    <element>502</element>
    <element>14</element>
    <element>105</element>
    <element>4</element>
    <element>165</element>
    <element>44</element>
    <element>10</element>
</Data>

You know what I mean? Basically I need to get rid of those R's and store numbers in each element. I find it pretty hard with XSLT 1.0
can someone help?

A: Perhaps you could do simply:
XSLT 1.0
<xsl:stylesheet version="1.0"
xmlns:xsl="http://www.w3.org/1999/XSL/Transform">
<xsl:output method="xml" version="1.0" encoding="UTF-8" indent="yes"/>

<xsl:template match="/Data">
    <xsl:copy>
        <xsl:for-each select="AFU/@*">
            <element>
                <xsl:value-of select="substring-before(substring-after(., 'r'), 'r')" />
            </element>
            <element>
                <xsl:value-of select="substring-after(substring-after(., 'r'), 'r')" />
            </element>
        </xsl:for-each>
    </xsl:copy>
</xsl:template>

</xsl:stylesheet>


text:
Q: Catch POST response from API with 302 status I am trying to catch POST response send to me by external API.
The problem is that POST array is completely empty while I can check in firebug that browser recieved it but with codes 302 FOUND and second (with same body) with code 307 TEMPORARY REDIRECT:

Is there any way to grab this data inside my script or is this something wrong with server re-directions?

A: If you are using the CURL library, there are two options that help with your case:
curl_setopt($curl,CURLOPT_HEADER,1);

This returns the response header including the status code. You can see whether 302 is returned.
Or you can simply follow the redirect
curl_setopt($curl,CURLOPT_FOLLOWLOCATION,1);

Edit: sorry just saw you were doing this on the client side.
If this is an AJAX call, you can get the status code in the raw XHR object.


text:
Q: How to catch information for Qt designer I have created a Qdialog box using the Qt creator designer as shown below:

When I need to display it, I'm instantiate the class dialogoverwrite (.cpp, .h and .ui)
DialogOverwrite *OverwriteDialog = new DialogOverwrite;
OverwriteDialog->exec();
OverwriteOption = OverwriteDialog->result()

My issue is that I want to get the QDialogButtonBox result but I do not know how. the current code, returning the result of the OverwriteDialog but it's not returning any QDialogButtonBox::Yes, QDialogButtonBox::YesToAll ...
How to catch the QButtonGroup result and not the QDialog result.
In the same way, If I want to change the label value from "File(s) and/or Folder(s)" to another label, how to access to this QLabel ?
Thanks for your help

A: When you pressed QDialogButton it was emit signal clicked(QAbstractButton*) by catching this signal you can identify which action button pressed.
Please go through following link it would be help you.
Qt: How to implement QDialogButtonBox with QSignalMapper for non-standard button ??

A: Well the standard way to do this is to handle the result by connecting it. So you could do:
connect(this, SIGNAL(clickedDialogButton(QAbstractButton*)),
    SLOT(dialogButton(QAbstractButton* aButton)));

Next you would create a function in your class called dialogButton (for example) and have that handle the result:
void MyUI::dialogButton(QAbstractButton* aButton) {
    // Obtain the standard button
    StandardButton button = buttonBox−>standardButton(button);

    // Switch on the type of button
    switch (button) {
    case QDialogButtonBox::YesToAll:
        // Do the thing you would like to do here
        break;
    // add some more cases?
    }
}

You could also check for the signal given by the QButtonGroup. Something like: void QGroupButton::buttonClicked(QAbstractButton* button) would work in the same way.


text:
Q: Show that $(\log |x|)^2\notin \text{BMO}([-1,1])$. I am trying to show that $u(x)\equiv (\log |x|)^2\notin \text{BMO}([-1, 1])$ by showing that it doesn't satisfy the John-Nirenberg inequality. If $u\in\text{BMO}[-1, 1])$ then this inequality says that there exists a $c_1, c_2>0$ such that for all cubes $Q\subset [-1, 1]$ and for all $t>0$ we have
\begin{equation}
|\{x\in Q\ |\ |u(x)-u_Q|>t\}|\leq c_1\exp\left(-\frac{c_2t}{|u|_{\ast}}\right)|Q|,
\end{equation} where $|u|_{\ast}$ is the supremum of mean oscillations over all cubes in $[-1, 1]$ and $u_Q$ is the average of $u$ in the cube $Q$.
So I began by assuming that $u\in\text{BMO}([-1, 1])$, and consequently, the above inequality holds for all cubes in $[-1, 1]$ and $t>0$. Then I tried to construct a sequence of cubes $Q_n\subset [-1, 1]$ and a sequence $t_n>0$ such that $t_n\rightarrow \infty$ but
\begin{equation*}
|x\in Q_n\ |\  |u(x)-u_{Q_n}|>t_n\}|\nrightarrow 0
\end{equation*} to get a contradiction. However, I kept getting stuck.
I would like to know how to obtain a proof using the John-Nirenberg approach and also if my proof below is correct. It does not use the John-Nirenberg inequality but the definition of BMO.
Working
For each $n\in\mathbb{N}$ and $n\geq 3$ define
\begin{equation*}
Q_n\equiv\left[\frac{1}{n}, 1-\frac{1}{n}\right].
\end{equation*} We have that
\begin{align}
u_{Q_n}&=\frac{1}{|Q_n|}\int_{Q_n}[\log x]^2\ \mathrm{d}x\\
&=\frac{n}{n-2}\left(\left[x(\log x)^2\right]^{1-1/n}_{1/n}-\int_{1/n}^{1-1/n}2 \log x\ \mathrm{d}x\right)\\
&=\frac{n}{n-2}\left(\left[x(\log x)^2\right]^{1-1/n}_{1/n}-2\left[x\log x\right]^{1-1/n}_{1/n} +2\left(1-\frac{2}{n}\right) \mathrm{d}x\right)\\
&= \frac{n-1}{n-2}\left(\log\frac{n-1}{n}\right)^2-\frac{1}{(n-2)}[\log n]^2+2\frac{n-1}{n-2}\log n +2
\end{align} and observe that $u_{Q_n}\rightarrow\infty$ as $n\rightarrow\infty$.
Since $u$ is monotone decreasing and continuous function on $Q_n$, there exists a unique element $\tau_n\in Q_n$ such that $u(\tau_n)=u_{Q_n}$, namely $\tau_n\equiv \exp(-\sqrt{u_{Q_n}})$. By construction, we have that $\tau_n\rightarrow 0$ as $n\rightarrow \infty$.
Next we compute
\begin{align}
\frac{1}{|Q_n|}\int_{Q_n}|u(x)-u_{Q_n}|\ \mathrm{d}x &\geq\frac{n}{n-2}\int_{\tau_n}^{1-\frac{1}{n}}u_{Q_n}-[\log x]^2\ \mathrm{d}x\\
&\geq \int_{\tau_n}^{1-\frac{1}{n}}u_{Q_n}-[\log x]^2\ \mathrm{d}x\\
&=\left(1-\frac{1}{n}-\tau_n\right)u_{Q_n}-\int_{\tau_n}^{1-\frac{1}{n}}[\log x]^2 \ \mathrm{d}x\\
&\equiv \mathcal{I}_n+\mathcal{II}_n.
\end{align}
Similar to earlier calculations, we have
\begin{equation}
\mathcal{II}_n=-\left[x(\log x)^2\right]^{1-1/n}_{\tau_n}+2\left[x\log x\right]^{1-1/n}_{\tau_n} -2\left(1-\frac{1}{n}-\tau_n\right),
\end{equation}and consequently, $\mathcal{II}_n\rightarrow -2$ as $n\rightarrow\infty$. At the same time $\mathcal{I}_n\rightarrow\infty$ as $n\rightarrow\infty$ so we have that
\begin{equation}
\frac{1}{|Q_n|}\int_{Q_n} |u(x)-u_{Q_n}|\ \mathrm{d}x\rightarrow \infty\Rightarrow u\notin\text{BMO}([-1, 1]).
\end{equation}

A: I suggest focusing more on estimation than on precise integration. You should not have to integrate $\log^2 x$, or to find $u_Q$ exactly. Estimates are good enough.
First, a solution using the John-Nirenberg lemma. Fix $Q=[-1,1]$. For $t>2|u_Q|$ we have
$$
\{x\in Q\ |\ |u(x)|>t\} \subset
\{x\in Q\ |\ |u(x)-u_Q|>t/2\}
$$
If $u$ was in BMO, the measure $|\{x\in Q\ |\ |u(x)|>t\}|$ would decay exponentially in $t$. But in fact
$$|\{x\in Q\ |\ |u(x)|>t\}| = 2\exp(-\sqrt{t})$$
which decays slower.

Next, an approach directly from the definition. You made some mistakes in integration: in fact, the average of $u$ over $\left[\frac{1}{n}, 1-\frac{1}{n}\right]$ does not tend to infinity; it tends to the average of $u$ on $[0,1]$. The mean oscillation also tends to a finite number, namely the mean oscillation on $[0,1]$. Simply put, you picked a wrong kind of interval as $Q_n$.
Since the function is integrable, the only way to make the mean oscillation large is to make $Q_n$ small.
I will use the following estimate:
Claim Let $Q$ be a measurable set. If $c>0$  and $a<b$ are   such that
$$|\{x\in Q : u(x)\le a\}|\ge c|Q| \quad \text{ and }\quad
|\{x\in Q : u(x)\ge b\}|\ge c|Q| $$
then
$$
\frac{1}{|Q|}\int_Q |u-u_Q| \ge \frac{(b-a)c}{2}
\tag1 $$
Proof. If $u_Q\le \frac{a+b}{2}$, then
$$
\int_Q |u-u_Q| \ge \int_{\{x\in Q : u(x)\ge b\}}
\left(u-\frac{a+b}{2}\right)  \ge c|Q|\frac{b-a}{2}
$$
Otherwise,
$$
\int_Q |u-u_Q| \ge \int_{\{x\in Q : u(x)\le a\}}
\left( \frac{a+b}{2} - u \right) \ge c|Q|\frac{b-a}{2}
$$
Either way, the claim holds. $\quad \Box$
I would use the above claim with $Q_n = [e^{-n-3},e^{-n}]$,
$a=(n+1)^2$ and $b=(n+2)^2$. Since
$$
|\{x\in Q : u(x)\le a\}| = |e^{-n}-e^{-n-1}|
= \frac{1-e^{-1}}{1-e^{-3}} |Q_n|$$
and
$$
|\{x\in Q : u(x)\ge a\}| = |e^{-n-2}-e^{-n-3}|
= \frac{e^{-2}-e^{-3}}{1-e^{-3}} |Q_n|$$
we can use $c>0$ independent of $n$. The quantity $b-a$
grows indefinitely as $n\to\infty$, which by (1) implies that $u$ is not in BMO.


text:
Q: How to append multiple items to pandas df? I have hundreds of excel files and I want to create a df that has the name of the excel file in one column and then the name of each tab in the second column. My script will iterate through each file name but the way I am appending is not right, and I'm not having much luck finding a solution.
os.chdir(r'C:\Users\mbobak\Documents\\')
FileList = glob.glob('*.xlsx')

tabs= pd.DataFrame(columns=['filename','tabs'])

for filename in FileList:
    xl = pd.ExcelFile(filename).sheet_names
    tabs= tabs.append([filename,xl])

desired output:
filename    tabs
doc1.xlsx   tab1
doc1.xlsx   tab2
doc1.xlsx   tab3
doc1.xlsx   tab4
doc2.xlsx   tab1
doc2.xlsx   tab2
doc2.xlsx   tab3

A: Here is one way. It is good practice, and efficient, to create your dataframe in a single step. This is because appending to a list is cheaper than appending to a dataframe.
FileList = glob.glob('*.xlsx')

def return_files_tabs(FileList):
    for filename in FileList:
        for sheet in pd.ExcelFile(filename).sheet_names:
            yield [filename, sheet]

df = pd.DataFrame(list(return_files_tabs(FileList)),
                  columns=['Filename', 'Tab'])

Explanation

*

*Cycle through each file and each sheet within sheet_names attribute.

*Yield filename and sheet via a generator.

*Build dataframe from list of exhausted generator, name columns.

A: I like @jpp's answer but if you don't want to use a generator this is how I would do it:
FileList = glob.glob('*.xlsx')

filenames = []
sheets = []

for filename in FileList:
    for sheet in pd.ExcelFile(filename).sheet_names:
        filenames.append(filename)
        sheets.append(sheet)

df = pd.DataFrame(
    {'Filename': filenames, 'Tab': sheets}
)


text:
Q: С# задача по удалению кратных Всем привет,не подскажите как сделать на языке С# так,чтобы метод принимал текст в которым бы удалялись все кратные рядом стоящие символы,оставив по одному.Пример:ПППОООГГГООООДДДААА >>> ПОГОДА.

A: Простой алгоритм
private static string RemoveDupl(string text)
{
    if (string.IsNullOrEmpty(text)) return text;
    var sb = new StringBuilder(text.Length);
    sb.Append(text[0]);
    for (var i = 1; i < text.Length; i++)
        if (text[i] != text[i - 1]) sb.Append(text[i]);
    return sb.ToString();
}

Как использовать
Console.WriteLine(RemoveDupl("ПППОООГГГООООДДДААА"));

вывод
ПОГОДА


text:
Q: Query about a proof of Riemann integrability of step/simple functions Let $f:[a,b]\to\Bbb{R}$ be a step function is of the form $$f=a_11_{[a,t_1]}+\sum\limits_{i=2}^n a_{i} 1_{(t_{i-1},t_{i}]}$$ i.e. in simple words $f(x)=a_1$ for all $x\in [a,t_1]$ and $f(x)=a_{i}$ for all $x\in(t_{i-1},t_{i}]\ \forall i\ge 2$.
I write $E_1=[a,t_1],E_{i}=(t_{i-1},t_i]\ \forall i\ge 2$, then $$f=\sum\limits_{i=1}^n a_{i} 1_{E_{i}}$$
Define
$$
\mathcal{CI}(f)=\sum\limits_{i=1}^n a_{i}(t_i-t_{i-1})
$$
We have to prove that for all $\epsilon >0$, there exists $\delta>0$ such that
$$
\left|\mathcal{CI}(f)-\sum\limits_{j=1}^k f(\xi_j)(s_j-s_{j-1})\right|<\epsilon
$$
for any portion $\mathcal{P}=\{a=s_0<\cdots<s_k=b\}$ with $\lVert \mathcal{P}\rVert(:=\text{max}\{s_j-s_{j-1}|\ j=1,\ldots,n\})<\delta$ and for any choice of $\xi_j\in(s_j,s_{j-1})$
I have tried to prove it in the following manner-
Let $\mathcal{P}=\{a=s_0<\cdots<s_k=b\}$ be a partition of $[a,b]$ and choose any $\xi_j\in (s_{j-1},s_j)$. Define a step function $g:[a,b]\to\mathbb{R}$ as follows-
$$g=\sum\limits_{j=1}^k f(\xi_j)1_{F_j}\text{ where } F_1=[a,s_1],F_j=(s_{j-1},s_j]\ \forall j\ge 2$$
Then as per our notation $\mathcal{CI}(g)=\sum\limits_{j=1}^k f(\xi_j)(s_j-s_{j-1})$
We have to approximate $|\mathcal{CI}(f)-\mathcal{CI}(g)|$. I have tried in the following manner-
$\mathcal{CI}(f)=\sum\limits_{i=1}^n a_i\lambda(E_i)$
$=\sum\limits_{i=1}^n a_i\lambda(E_i\cap [a,b])$
$=\sum\limits_{i=1}^n a_i\lambda(E_i\cap\bigsqcup\limits_{j=1}^k F_j)$
$=\sum\limits_{i=1}^n\sum\limits_{j=1}^k a_i\lambda(E_i\cap F_j)$
Similarly, $\mathcal{CI}(g)=\sum\limits_{i=1}^n\sum\limits_{j=1}^k f(\xi_j)\lambda(E_i\cap F_j)$
Then $|\mathcal{CI}(f)-\mathcal{CI}(g)|=|\sum\limits_{i,j} x_i-f(\xi_j)\lambda(E_i\cap F_j)|\le \sum\limits_{i,j}(|x_i|+|f(\xi_j)|)|\lVert \mathcal{P}\rVert\le 2nk \lVert f\rVert_{\infty} \lVert P\rVert$
Where $\lVert f\rVert_\infty=\text{sup}|f|$.
Here $n,\lVert f\rVert_\infty$ is fixed, but $k$ could vary. So I am unable to give approximation $|\mathcal{CI}(f)-\mathcal{CI}(g)|<\epsilon$.
There is a hint provided in the book that is-
Show that,
$$
\left|\mathcal{CI}(f)-\sum\limits_{j=1}^k f(\xi_j)(s_j-s_{j-1})\right|<(n-1)\lVert P\rVert \underset{i}{\text{max}}{|a_i|}
$$
But I'm unable to prove that. Can anyone help me in this regard? Thanks for help in advance.

A: Form the partition $Q$ with points $a = x_0 < x_1  < \ldots  < x_m = b$ where
$$\{x_0,x_1, \ldots x_m\} = \{t_0,t_1, \ldots, t_n\}\cup\{s_0,s_1, \ldots, s_k\}$$
Note that $Q$ has at most $n-1$ more points and subintervals than  the partition $P = (s_0,s_1,\ldots, s_k)$. The maximum difference in the number of points occurs when  $\{t_1, \ldots, t_{n-1}\}\cap\{s_1, \ldots, s_{k-1}\}= \emptyset. $
We can write $\mathcal{CI}(f)$ and  $\mathcal{CI}(g)$ as sums of the form
$$\mathcal{CI}(f) = \sum_{p=1}^m\alpha_p(x_p-x_{p-1}),\quad\mathcal{CI}(g) = \sum_{p=1}^m\beta_p(x_p-x_{p-1}),$$
where $\alpha_p, \beta_p \in \{a_0,a_1,\ldots, a_n\}$ and $\alpha_p$ and $\beta_p$ are different on at most $n-1$ new subintervals introduced by forming partition $Q$.  We must have $|\alpha_p - \beta_p| \leqslant 2M$ where $M = \max(|a_0|,|a_1|,\ldots,|a_n|)$, and, thus
$$\left|\mathcal{CI}(f)- \mathcal{CI}(g) \right|< (n-1)\cdot \|Q\|\cdot 2M < (n-1) \cdot \|P\|\cdot 2M $$
Choose a partition $P$ such that $\delta = \|P\| < \frac{\epsilon}{2(n-1)M}$ to finish.


text:
Q: What is a good relation between seeds given to srand48_r In a multithreaded program where each thread has its own state of the rand48 PRNG, what is a good relation between the seeds.
Obviously, I cannot use the same seed since then they generate the same sequences. How uncorrelated will they be for seeds {0,1,2,3} or {1,2,3,4} or whatever. I do want a fixed seed so I can repeat simulations.


text:
Q: How do I configure Juju to use Amazon Web Services (AWS)? I'd like to deploy services on AWS, how can I configure Juju to do this?

A: First install Juju:
sudo add-apt-repository ppa:juju/stable
sudo apt-get update && sudo apt-get -y install juju-core

Do a juju generate-config -w to generate a config for AWS that you can customize for your needs. This will create the file ~/.juju/environments.yaml.
Which is a sample environment configured to run with EC2 machines and S3 permanent storage.
To make this environment actually useful, you will need to tell juju about an AWS access key and secret key. To do this, you can either set the AWS_ACCESS_KEY_ID and AWS_SECRET_ACCESS_KEY environment variables (as usual for other EC2 tools) or you can add access-key and secret-key options to your environments.yaml. These are already in place in the generated config, you just need to uncomment them out. For example:
default: sample
environments:
  sample:
    type: ec2
    access-key: YOUR-ACCESS-KEY-GOES-HERE
    secret-key: YOUR-SECRET-KEY-GOES-HERE
    control-bucket: juju-faefb490d69a41f0a3616a4808e0766b
    admin-secret: 81a1e7429e6847c4941fda7591246594
    default-series: precise
    ssl-hostname-verification: true

See the EC2 provider documentation for more options. The S3 bucket does not need to exist already.
Note If you already have an AWS account, you can determine your access key by visiting your account page, clicking "Security Credentials" and then clicking "Access Credentials". You'll be taken to a table that lists your access keys and has a "show" link for each access key that will reveal the associated secret key.
And that's it, you're ready to go!

*

*https://juju.ubuntu.com/docs/getting-started.html

*https://juju.ubuntu.com/docs/provider-configuration-ec2.html


text:
Q: Missing adActivity with android:configChanges in AndroidManifest.xml I am trying to an admob banner to my application but unfortunately after doing all the steps of the Google documentation I still receive this warning in the logcat "could not find com.google.android.gms.ads.adactivity" and this message in the banner of the admob "Missing adActivity with Android: configChanges in AndroidManifest.xml" ALTHOUGH I added the Android: configChanges in AndroidManifest.xml
here is my manifest.xml
<activity android:name="com.google.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>

I really need your help

A: com.google.ads.AdActivity is declared when using the admob sdk jar in the "libs" folder. It seems you're using admob via the google play services library so change:
activity android:name="com.google.ads.AdActivity"
To activity android:name="com.google.android.gms.ads.AdActivity"
Also make sure you add the meta-data tag:
<meta-data android:name="com.google.android.gms.version"
           android:value="@integer/google_play_services_version"/>

A: Add this activity to your manifest file
 <activity android:name="com.google.android.gms.ads.AdActivity" android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"/>


text:
Q: torque of locked gear motor vs gearless motor Do gears increase the torque of locked/stalled motor ?. I understand that in case of rotation of shaft the gears will increase the torque because of transmission to slow rpm. But what makes difference in case of stalled/locked shaft?

A: A reducing gear box can be modeled as a lever: the small force of the stalled motor is multiplied by the reduction factor, to appear as a much larger force at the output shaft.


text:
Q: How to parse "2022-02-04T12:20:47,398000+01" into SimpleDateFormat? My date string looks like this "2022-02-04T12:20:47,398000+01".
I tried this format SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss,SSSSSSZ") but it throws an exception.
Minimum API level that I need to support is 23, so I can't use 'X' symbols in the format like "yyyy-MM-dd'T'HH:mm:ss,SSSSSSX".
Is there a safe way to parse the date string I have on android?

A: use the following
String inputDate = "2022-02-04T12:20:47,398000+01";
            String result;

            SimpleDateFormat inputformat = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
            SimpleDateFormat outputformat = new SimpleDateFormat("yyyy-MM-dd", Locale.ENGLISH);
            try {
                Date convertDate  = inputformat.parse(inputDate);

                result = outputformat.format(convertDate);
                tvResult.setText(result);
            }catch (Exception e){
                e.printStackTrace();
            }


text:
Q: Pocketsphinx for android install on windows Where can I find a step-by-step solution for my problem? I saw the demo, I checked the tutorial. I couldn't find find jar or aar file. I've downloaded tar folder, I cannot run any files in there with my visual studio, so what should I do?

A: I got it. Jar file can be imported in the Android Studio. Aar can be downloaded from github. Also found good articles:

*

*https://www.guidearea.com/pocketsphinx-continuous-speech-recognition-android-tutorial/

*http://swathiep.blogspot.com/2011/02/offline-speech-recognition-with.html


text:
Q: Trying to find the lowest number in my array, used the same line for highest number Basically what I am trying to do is get the lowest number, but the program is feeding me back garbage, but I use the same line of code to get the highest value, only change I made was > to <, the program gives me back the highest value no problem put not the lowest. And I have tried everything I can think of from making the lowest= x[0], lowest=101( user is suppose to enter in grades on scale of 0-100, thought made it had something to do with the value. ) and lowest =highest and it still give me back a number like -9.255596e...., any help or suggestion or greatly appreciated, or maybe a point in the right direction just really trying to understand why it works for one set of numbers and not the others.
 #include "stdafx.h"
 #include <iostream>

 using std::cout;
 using std::endl;
 using std::cin;

 double average(double,int);
 double sum1(double[],int);
 double highest(double[], int);
 double lowest(double[], int);

 int _tmain(int argc, _TCHAR* argv[])
{

    double gradeBook[1000];
    char x;
    int count = 0;
    cout << "Do you wish to start the program if so enter y to stop enter q" << endl;
    cin >> x;
    while (x != 'q')
    {
        cout << "Enter in test grade on a scale of 0 to 100" << endl;
        cin >> gradeBook[count];
        if (gradeBook[count]<0 || gradeBook[count]>100)
        {
            cout << " Please try again ";
            count--;
        }
        else
            cout << "valid answer" << endl;
        count++;
         cout << "Do you wish to continue entering in grades? If so enter y to      stop enter q" << endl;
        cin >> x;
     }

         highest(gradeBook, count);
     cout << "The highest grade enter is " << highest(gradeBook, count) << endl;
     lowest(gradeBook, count);
     cout << "The lowest grade enter is " << lowest(gradeBook, count) << endl;

    cout << lowest <<endl;

    return 0;
}

    double highest(double x[], int y)

    {
     double highest = 0;
    for (int i = 0; i<= y; i++)
    {
    if (x[i]>highest)
    highest = x[i];
    }
    return highest;

    }
    double lowest(double x[], int y)
    {
    double lowest = 100;

    for (int i = 0; i<= y; i++)
    {
        if (x[i]< lowest)
            lowest = x[i];
    }
    return lowest;
}

A: A way to resolve your question is to use code already tested.
In your case you can use min_element and max_element to find min and max element of your code:
    cout << "The highest grade enter is " << *max_element(gradeBook,
gradeBook+count) << endl;


text:
Q: Установка нескольких ОС на VirtualBox Поставил на VirtualBox Windows 7, еще хочу поставить вдобавок Linux, это реально? Или посоветуете оставить одну ОС на VirtualBox?

A: Можешь ставить сколько душе угодно.


text:
Q: What does a "standard formula interface to a data.frame" mean in R? The documentation for aggregate states:

'aggregate.formula' is a standard formula interface to 'aggregate.data.frame'.

I am new to R, and I don't understand what this means.  Please explain!
Thanks!
Uri

A: Jump to the middle of the examples section of help(aggregate) and you will see this:
 ## Formulas, one ~ one, one ~ many, many ~ one, and many ~ many:
 aggregate(weight ~ feed, data = chickwts, mean)
 aggregate(breaks ~ wool + tension, data = warpbreaks, mean)
 aggregate(cbind(Ozone, Temp) ~ Month, data = airquality, mean)
 aggregate(cbind(ncases, ncontrols) ~ alcgp + tobgp, data = esoph, sum)

Four different calls to aggregate(), all using the formula interface.  The way it is written above in what you quote has to do with method dispatching mechanism used throughout R.
Consider the first example:
R> class(weight ~ feed)
[1] "formula"
R> class(chickwts)
[1] "data.frame"

so aggregate dispatches on it first argument (of class formula). The way a formula gets resolved in R typically revolves around a model.matrix, I presume something similar happens here and an equivalent call is eventually execucted by aggregate.data.frame, using the second argument chickwts, a data.frame.
R> aggregate(weight ~ feed, data = chickwts, mean)
       feed  weight
1    casein 323.583
2 horsebean 160.200
3   linseed 218.750
4  meatmeal 276.909
5   soybean 246.429
6 sunflower 328.917
R>

What you asked isn't the easiest beginner question, I'd recommend a good thorough look at some of the documentation and a decent R book if you have one handy. (And other SO questions give recommendation as to what to read next.)
Edit: I had to dig a little as aggregate.formula() is not exported from stats namespace, but you can look at it by typing stats:::aggregate.formula at the prompt -- which then clearly shows that it does, in fact, dispatch to aggregate.data.frame():
 [.... some code omitted ...]
    if (is.matrix(mf[[1L]])) {
        lhs <- as.data.frame(mf[[1L]])
        names(lhs) <- as.character(m[[2L]][[2L]])[-1L]
        aggregate.data.frame(lhs, mf[-1L], FUN = FUN, ...)
    }
    else aggregate.data.frame(mf[1L], mf[-1L], FUN = FUN, ...)
}
<environment: namespace:stats>
R>


text:
Q: Why it is faster writing a file which is freopened with stdout? When executed on Windows, this test code:
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <time.h>
#include <assert.h>

int main() {
    // The clock() function returns an approximation of processor time used by the program.
    // The  value  returned is the CPU time used so far as a clock_t;
    // to get the number of seconds used, divide by CLOCKS_PER_SEC.
    auto buf = new char[1048576]; // 1MB
    auto cache = new char[512 * 1024];

    // initialize the buffer
    for (int i = 0; i < 1048576; ++i)
        buf[i] = i;

    auto fp_reopen = freopen("data_freopen.bin", "wb", stdout);
    assert(fp_reopen != nullptr);
    setvbuf(fp_reopen, cache, _IOLBF, 512 * 1024);
    auto clock_begin = clock();
    for (int i = 0; i < 1000; ++i) {
        auto n = fwrite(buf, 1048576, 1, fp_reopen);
        assert(n == 1);
    }
    fflush(fp_reopen);
    auto clock_end = clock();

#ifdef _WIN32
    freopen("CONOUT$", "w", stdout);
#else
    freopen("/dev/tty", "w", stdout);
#endif

    printf("write with freopen clocks elapsed: %zu\n", clock_end - clock_begin);

    auto fp = fopen("data_fopen.bin", "wb");
    assert(fp != nullptr);
    setvbuf(fp, cache, _IOLBF, 512 * 1024);
    clock_begin = clock();
    for (int i = 0; i < 1000; ++i) {
        auto n = fwrite(buf, 1048576, 1, fp);
        assert(n == 1);
    }
    fflush(fp);
    clock_end = clock();
    fclose(fp);

    printf("write with fopen clocks elapsed: %zu\n", clock_end - clock_begin);
    delete[] buf;
    delete[] cache;
    getchar();
}

Generates these results:

*

*write with freopen clocks elapsed: 2767

*write with fopen clocks elapsed: 8337
Why?

A: Your question is interesting, but highly system specific:

*

*on Linux with gcc and the Glibc, I get very similar timings for both runs

*on OS/X, with clang and the Apple Libc, the fopen timings seem consistently a little faster than the freopen ones.

*you are running your test on Windows, as the final call to getchar() suggests... I unfortunately cannot test this system to try and cross check your observations.

It is possible that Microsoft did something weird in their runtime library, but more likely you are really benchmarking the creation of 2 separate 1GB files. It is possible that the second file takes longer to create than the first one, due to the state of your file system, its cache or other OS specific causes. You should try and remove this potential side effect by removing each file after closing it, or try running the tests in a different order.


text:
Q: Proof of Isserlis' theorem for $n=4$ I have been trying very hard to prove Isserlis' theorem for n=4 case, i.e when we have 4 random variables that are jointly Gaussian variables with zero-means.
$E[X_1X_2X_3X_4]=E[X_1X_2]E[X_3X_4]+E[X_1X_3]E[X_2X_4]+E[X_1X_4]E[X_2X_3]$
Where $X_1,X_2,X_3$ and $X_4$ are jointly Gaussian random variables. Can anyone help me in proving this. If you can provide me a material for proving this theorem for higher moments I will be really grateful.
Thanks in advance

A: Let $X=(X_i)$ and $C=\mathrm{Cov}(X,X)$, then $X$ is centered hence its Laplace transform is such that $$E(\mathrm e^{s'X})=\exp\left(\tfrac12s'Cs\right),$$ for every $s=(s_i)$. The homogenous terms of degree $4$ with respect to $s$ from both sides coincide, hence $$E((s'X)^4)=\frac{4!}{2!2^2}(s'Cs)^2=3(s'Cs)^2.$$
Note that $$(s'Cs)^2=\left(\sum_{ij}C_{ij}s_is_j\right)^2=\sum_{ijk\ell}C_{ij}C_{k\ell}s_is_js_ks_\ell.$$
The product $s_1s_2s_3s_4$ appears on the RHS for every $(i,j,k,\ell)$ such that $\{i,j,k,\ell\}=\{1,2,3,4\}$. For example, $C_{12}C_{34}s_1s_2s_3s_4$ appears once for each $(i,j,k,\ell)$ in the collection $$(1,2,3,4),\ (1,2,4,3),\ (2,1,3,4),\ (2,1,4,3),\ (3,4,1,2),\ (4,3,1,2),\ (3,4,2,1),\ (4,3,2,1),$$ that is, $8$ times. Thus, the contribution of $s_1s_2s_3s_4$ to $3(s'Cs)^2$ is $$
24(C_{12}C_{34}+C_{13}C_{24}+C_{14}C_{23})s_1s_2s_3s_4.$$
On the other hand,  $$E((s'X)^4)=\sum_{ijk\ell}E(X_iX_jX_kX_\ell)s_is_js_ks_\ell.$$
 hence $E(X_1X_2X_3X_4)s_1s_2s_3s_4$ appears once for every $(i,j,k,\ell)$ such that $\{i,j,k,\ell\}=\{1,2,3,4\}$, that is, $4!=24$ times. To sum up, $$
24E(X_1X_2X_3X_4)=24(C_{12}C_{34}+C_{13}C_{24}+C_{14}C_{23}),$$
which proves the desired result since $C_{ij}=E(X_iX_j)$ for every $(i,j)$.
More generally, by the same approach, for every $n\geqslant1$, $$\frac1{(2n)!}E((s'X)^{2n})=\frac1{n!2^n}(s'Cs)^n,$$
hence
$$E\left(\prod_{k=1}^{2n}X_k\right)=\sum_\tau C^{(\tau)},$$
where the sum on the RHS is over every partition $\tau$ of $\{1,2,\ldots,2n\}$ into $n$ disjoint pairs $(\tau(2k-1),\tau(2k))$ such that $\tau(2k-1)\lt\tau(2k)$ for every $1\leqslant k\leqslant n$ and $\tau(2k-1)\lt\tau(2k+1)$ for every $1\leqslant k\leqslant n-1$, and, for every such partition, $$C^{(\tau)}=\prod_{k=1}^nC_{\tau(2k-1)\tau(2k)}.
$$


text:
Q: How can I set columns of a dataframe as x-axes? I have a dataframe that looks like the below.
                  Time  Volume
Index
0      16:18:40.505530       1
1      16:18:40.510560       1
2      16:18:40.524660       1
3      16:18:40.693910       1
4      16:18:40.900390       2
5      16:18:40.902290       1
6      16:18:41.296110       4
7      16:18:41.898610       1
8      16:18:42.099940       1
9      16:18:42.303210       3
10     16:18:42.497490       1
11     16:18:43.095560       1
.....

>> df.Time
....
Name: Time, Length: 103248, dtype: timedelta64[ns]

My goal is to plot this data and set the index and Time column as x-axes.
I can easily plot it if it's only with the index as x-axis, like this.
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.scatter(df.index,df.Volume, marker='+', s=1 )

but I don't know how I can add another x-axis using Time column.

A: What does it mean to have a double x-axis?
If you want to present them both  - try concatenating the value.
If you wish that the time will be the x-axis just run:
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)
ax1.scatter(df.Time,df.Volume, marker='+', s=1 )


text:
Q: How to convert multiple, different-sized PostScript files to a single PDF? I'm using a command similar to this:
gswin32c.exe -dNOPAUSE -dBATCH -q -dSAFER -sDEVICE=pdfwrite -dPDFSETTINGS=/prepress -sOutputFile="path/output.pdf" <PSfiles>

This gives me a single pdf document with each PS document represented as a page. However, the page sizes do not translate well. The original PS files are all different sizes and each resulting pdf page is cutoff to the same size, which looks like landscape A4.
When I convert a single PS file with the exact same command, the page size is preserved. So it seems like since all the PS files are being sent to the same pdf, they must all have the same page size and I lose content. Is there anyway to preserve the document sizes while still using a single command?
Update: I was originally using GS 8.63, but I downloaded 9.06 and have the same issue.
Additionally, I've narrowed the problem down. It seems like there is one specific PS file (call it problemFile.ps) that causes the problem, as I can run the command successfully as long as I disclude problemFile.ps. And it only causes a problem if it is the last file included on the command line. I can't post the entire file, but are there any potential problem areas I should look at?
Update2: Okay I was wrong in saying there is one specifc problem file. It appears that the page size of the last file included on the command line sets the maximum page size for all the resultant pages.

A: As long as each PostScript file (or indeed each page) actually requests a different media size then the resulting PDF file will honour the requests. I know this at least used to work, I've tested it.
However there are some things in your command line which you might want to reconsider:
1) When investigating problems with GS, don't use -q, this will prevent Ghostscript telling you potentially useful things.
2) DON'T use -dPDFSETTINGS unless you have read the relevant documentation and understand the implications of each parameter setting.
3) You may want to turn off AutoRotatePages, or at least set it to /PageByPage
My guess is that your PostScript files don't request a media size and therefore use the default media. Of course I can't tell without seeing an example.
NB you also don't say what version of Ghostscript you are using.


text:
Q: JavaFX : Adapt component height to its children height? I'm trying to develop a desktop app using javaFX (2.2), and I'm experiencing some difficulties to really get it to behave like I would like it to. Being a new user of the framework, I might not be using it as it should be...
What I want is a kind of dashbord, with several JavaFX or custom controls inside a ScrollPane. I currently have several views that look like this :
<AnchorPane id="userContent" xmlns:fx="http://javafx.com/fxml" fx:controller="squalp.view.OrgViewController">
    <children>
        <ScrollPane fx:id="scrollPane" styleClass="transparent" hbarPolicy="NEVER" vbarPolicy="AS_NEEDED" AnchorPane.bottomAnchor="0.0" AnchorPane.leftAnchor="0.0" AnchorPane.rightAnchor="0.0" AnchorPane.topAnchor="0.0">
            <content>
                <VBox fx:id="vBox" styleClass="transparent" alignment="TOP_LEFT" focusTraversable="true">
                    <children>
                        <Label text="Label" />
                        <Button fx:id="bTest" text="Test" onAction="#test"/>
                        <TreeView fx:id="orgTree" focusTraversable="true" />
                    </children>
                </VBox>
            </content>
        </ScrollPane>
    </children>
</AnchorPane>

As long as I keep using simple controls, no problem, items are correctly placed one after another in th VBox.
But when using TreeViews or TableViews, I can only get my controls to have fixed height, meaning extra space on the bottom, or new scroll bars, in addition to the main one. What I would like to achieve is to adapt my controls to their current content height.
Qt's QML, for exemple, has a childrenHeight property, and it's kind of what I'm looking for. I figure this content height must be calculated somehow, since components scrollbars do adapt to the content.
I had to use a workaround for tableviews :
table.setPrefHeight(list.size() * rowHeight + headerHeight);

but I couldn't find a way to track displayed items on a treeview.
Has anyone an idea of what I could be doing to handle this issue ? Or I am really not using the framework as I should ?
Thanks in advance.
EDIT : Visual description of the problem :
Case 1
Here my treeview's height is set to a default value. There are not enough items to fill the treeview : if I want to put another component below, there'll be a gap; if my scene is not big enough, the ScrollPane's scrollbar appears, even though all the displayable content is visible.
Case 2
If if expand my treeview's items, there are now too many of them. They are not all visible at once, and the treeview's scrollbar appears, even though I already have a scrollable view with the scrollpane.
What I would like is my TreeView to adapt to its content height (reduced height if items are collapsed, bigger height if they are expanded), in order to be able to put several components one after another and to scroll through them all using the ScrollPane's scrollbar.
Since the TreeView component has itself a scrollbar, its visible content's height must be calculated at some point (since scrollbars basically use ratios based on contentHeight/componentHeight). This information doesn't seem to be available in the public API, but I wonder if, developping a custom class that expands TreeView, there could be a way to bind my component to its "visible height".

A: There maybe a proper way to achieve your goal, but I can suggest the approach similar to tableview's.
orgTree.prefHeightProperty().bind(orgTree.impl_treeItemCountProperty()
        .multiply(treeRowHeight)); // treeRowHeight maybe 24.

Note that this is only a workaround where the deprecated and internal use-only method is used, which maybe removed in future releases.

A: I was looking for way to make TreeView auto-resize to fit its content, e.g. when a node is expanded or collapsed. Here's what I eventually do. Note the Platform.runLater() is required, thus simple property binding would not work here. Also note the cellHeight is the height of a tree node. It's beyond the scope of the question here how to get that.
treeView.expandedItemCountProperty().addListener((obs, oldV, newV) -> {
    Platform.runLater(() -> {
        treeView.setPrefHeight(newV.intValue() * cellHeight);
    });
});

A: You can use the binding property of the view to the childs height property. By this, whenever the height of the Parent changes, childs height will automatically change ! This is not automatic height adaption, like you want, but a forced adaption, which will help you !
Width property is also available
Basically this is a snippet that will help you :
pane.heightProperty().addListener(new ChangeListener<Number>() {
    @Override
    public void changed(ObservableValue<? extends Number> arg0,
                                 Number oldValue, Number newValue) {
        table.setPrefHeight(newValue - 200);/*The difference of height between
                                             parent and child to be maintained*/
    }
});


text:
Q: How to get affected rows in previous MySQL operation? mysql_affected_rows is to get number of affected rows in previous MySQL operation, but I want to get affected rows in previous MySQL operation.
For example:
update mytable set status=2 where column3="a_variable";

Before this operation, status of some rows is already 2, and I want to get affected rows in previous MySQL operation, you can not get it by issuing a query of
select * from mytable where status=2

So how to do this work?

A: It can be efficiently and simply achieved with the following:
 select * from mytable where column3="a_variable" and status != 2;
 update mytable set status=2 where column3="a_variable";

The result of the first query are the rows that are going to change, and the second query actually changes them.
If this is a high performance system, you may need to take special care with transactions to prevent a new row slipping in between those 2 queries.

A: The implementation and function you are asking about is from PHP, please tag your question with PHP.
In response to your question tho, in order to do what you are suggesting you would need to keep a copy of the SQL table prior to the change and compare it with the table after the change, the resulting difference would be your answer. You can do this in PHP by simply loading the table contents into an array and comparing the arrays before and after, any new/changed data is your answer (Please note: it is highly not recommended you do this as it can cause an increased load on your server depending on the amount of data stored in the tables.)


text:
Q: Get element at index of a Array[(Array[String, Long)] So I have some data:
val data = Array[(Array[String], Long)]

Which is an array of pairs, where each pair consists of another array and a number. I have created a ListBuffer as follows:
var x = ListBuffer[(Array[String], Long)]

I would like to append an element at some index i to x. I do the following:
 x += data(i)

However, I get the error:

Type mismatch, expected: String, actual: (Array[String], Long)

What am I doing wrong? I am working in IntelliJ and Scala 2.10.7.
Also this example (which is a concrete example (I cannot provide the original example)) also gives the same error:
val xData = ListBuffer[(Array[String], Long)]
    var x = ListBuffer[(Array[String], Long)]
    x += xData(0)

A: I have tried the same thing in scala REPL just now, and it is working fine.
What I did is -
    scala> val arr = Array("Hello", "Bye")
    arr: Array[String] = Array(Hello, Bye)

    scala> var data = Array((arr,1), (arr,2))
    data: Array[(Array[String], Int)] = Array((Array(Hello, Bye),1),
    (Array(Hello, Bye),2))

    scala> import scala.collection.mutable.ListBuffer
    import scala.collection.mutable.ListBuffer

    scala> val list = ListBuffer((arr, 1))
    list: scala.collection.mutable.ListBuffer[(Array[String], Int)] =
    ListBuffer((Array(Hello, Bye),1))

    scala> list += data(0)
    res1: list.type = ListBuffer((Array(Hello, Bye),1), (Array(Hello,
    Bye),1))

It did not give any error

A: So the issue was that I forgot brackets at the end of ListBuffer initiation.
This works:
var x = ListBuffer[(Array[String], Long)]()


text:
Q: Azure's Security Center highlights recommendations to be carried out. For instance "Enable auditing and logging" I have been searching for a way to do this programmatically, rather than manually going through thousands of items via the portal. I'd like to be able to run some PowerShell to enable all logging and push this to a centralised analytical workspace.
I can't seem to find any way to do this via Powershell or any other programmatical approach.

A: You may be able to accomplish what you are looking for using the Security Center REST APIs. For exmaple, see the assessment return here: https://learn.microsoft.com/en-us/rest/api/securitycenter/assessments/get
You can call this API easily via PowerShell and the Az module with the Invoke-AzRestMethod command, which will take care of authentication and return a PowerShell object/array of objects you can work with.
Another option is to export Security Center recommendations and alerts to Log Analytics--https://learn.microsoft.com/en-us/azure/security-center/continuous-export?tabs=azure-portal#information-about-exporting-to-a-log-analytics-workspace


text:
Q: Can one encapsulate Xml Rpc call within an winhttp object? Is it possible to encapsulate an Xml Rpc call within an Winhttp 5.1 object ?
The reason I am asking this is because as far as I know Winhttp automatically resolves any proxy settings which I do not know beforehand for each user. I also don't want to set the proxy for each xml rpc call I make by hand since my users are all over the country.
Thx for any suggestions.

A: This helped me :
var url = new Uri("http://www.example.com/");
string ProxyUrl = WebRequest.DefaultWebProxy.GetProxy(url).ToString();


text:
Q: PhpExcel Workbook I currently have a .xlsx file with a workbook with multiple sheets with text and images.
I need to import this data into my MySQL database.
Does anyone know of any tutorials or just some code that can help me get all the sheet within the workbook and retrieve text and images, and insert them into the database.

A: Check out PHPExcel. Here's how you would loop through the sheets. I'm not sure how you can get images though.
$reader = new PHPExcel_Reader_Excel2007();
$excel = $reader->load($filename);

foreach ($excel->getWorksheetIterator() as $worksheet){
    // Get the data from current worksheet
    // and store in DB as you like
}

A: $reader = new PHPExcel_Reader_Excel2007();
 $PHPExcel = $reader->load('test.xlsx');
 $worksheet = $PHPExcel->getActiveSheet();

 // extract images from worksheet and save files:  0.jpeg, 1.jpeg, 2.png, ...
 foreach ($worksheet->getDrawingCollection() as $i => $drawing) {
     $filename = $drawing->getPath();
     $imagesize = getimagesize($filename);

     switch ($imagesize[2]) {

     case 1:
         $image = imagecreatefromgif($filename);
         imagegif($image, "$i.gif");
         break;

     case 2:
         $image = imagecreatefromjpeg($filename);
         imagejpeg($image, "$i.jpeg");
         break;

     case 3:
         $image = imagecreatefrompng($filename);
         imagepng($image, "$i.png");
         break;

     default:
         continue 2;

     }
 }


text:
Q: Knowing the number of users with a group policy aplied The question is pretty simple. Is there any way to get the number of users on an Active Directory with a specific Group policy applied?
For example, i need to know how many users has the strong password policy applied and i can't access computer by computer to check it.

A: I'll address this in two sections, since password policies are handled differently than most other GPO settings.

For example, i need to know how many users has the strong password policy applied and i can't access computer by computer to check it.

If you're not using Fine Grained Password Policies, then all of your users will have the same password policy.
If you are using Fine Grained Password Policies, then you have to define a specific user or group to apply that policy to, so just count who is in that group.
You can use a combination of Get-ADGroupMember and Measure-Object in PowerShell if there are too many to count by hand or you want to automate it, for some reason.

Is there any way to get the number of users on an Active Directory with a specific Group policy applied?

Group policies apply to users or computers and are linked to domains, sites, and OUs. Simple check where the the policy that you're curious about is linked to, and then count everything that it applies to within that domain, site, or OU. The Measure-Object PowerShell cmdlet is your friend here.


text:
Q: fullcalendar - date format for end/start events This (I hope) is a basic question.  I'm not seeing calendar events in fullcalendar, and I believe the issue is the date format I am attempting to use for start/end events.  I am attempting to setup a basic calendar by loading JSON events.  Here is my JSON output (trimmed to one event so as not to take up much room):
[{"id":"89","title":"A Title","start":"June 2nd 2015","end":"August 14th 2015"}]

My javascript looks like this:
$(document).ready(function() {
    $('#calendar').fullCalendar({
        editable: false,
        events: "data.php"
    });
});

Again, very basic.  I know for certain that the issue for the events not appearing is due to the date format I am using, but I am not certain how to tell fullCalendar to use the MMMM Do YYYY format for start/end events with moment.js.  Does anyone have advice on how this is accomplished?
EDIT:
Attempted to add something along these lines...but still no luck:
var start = moment(event.start).format("MMMM Do YYYY");
var end = moment(event.end).format("MMMM Do YYYY");

A: I'm not sure if this would be considered an answer or more of a workaround, but I'll post it as an answer anyway.
I ended up just converting the date format in the json output as Bruno had suggested in the above comment.  Sort of wished I could have figured it out with the javascripting, but after hours of trying I could never get the events to display in the calendar.
I'll go ahead and post my php source for those curious (just showing the start date):
    $start = $row['startdate'];
    $start_obj = new \DateTime($start);
    $events['start'] = $start_obj->format('Y-m-d');

A: I accomplished something similar by defining a function for the events, iterating through the data creating moment.js objects for the start field using my desired format. The docs have the basics for how to accomplish this.
EDIT: I copied the example from the docs and modified the start time using moment.js.
$('#calendar').fullCalendar({
events: function(start, end, timezone, callback) {
    $.ajax({
        url: 'myxmlfeed.php',
        dataType: 'xml',
        data: {
            // our hypothetical feed requires UNIX timestamps
            start: start.unix(),
            end: end.unix()
        },
        success: function(doc) {
            var events = [];
            $(doc).find('event').each(function() {
                events.push({
                    title: $(this).attr('title'),
                    start: moment($(this).attr('start'), 'MMMM Do YYYY') // will be parsed
                    });
                });
                callback(events);
            }
        });
    }
});


text:
Q: Can I configure Visual Studio 2010 to show warnings only in my source code? I like having a high level of warnings (usually W4). However, with a warning level of 4 or higher, I get a lot of warnings from Windows headers and from third party headers, which makes it very difficult to find the ones I can actually do something about.
Hence my question: Can I tell Visual Studio to show warnings only for those files which belong to my current project?

A: This would be especially useful when running code analysis. Why show all those warnings for code that I don't own?
I found one thing that might help:
Right click anywhere on one of the rows in the Error List and click Grouping->Path. The path to the file will show up on the left. Now you can collapse all the paths to code that you want to ignore.
It's not ideal, but it's better than nothing.


text:
Q: How to add click event to an img element in jquery grid I have a jquery grid and i have added img element to a grid column value with the formatter. How di i add click event to that element and hide /show the image based on a condition.
{
  name : 'adjust',
  formatter : function (){
    return "";
  }
}

A: Easiest and to me the best way is to give the image a class, return "";
Then using jquery you use the code below:
$ (document).on ('click', '.my_img', function (e) {
    var obj = $ (this);

    if (obj.hasClass ('hide'))
        obj.removeClass ('hide'); // or add a placeholder, etc
    else
        obj.addClass ('hide');
});

`$ (document).on ('click', '.my_img', function (e).... is used beacuse if any image is added after the page has load, the click event will still work on those new ones
var obj = $ (this); is used because depending on what you do in the function, this could be different.
By using the above coe, when your image hides you will not be able to click on it again :) this is just an example of how to add the click event


text:
Q: How to improve UITableView scrolling when data is calculated on the go in Swift? Before changes to the way we return cells in the cellForRow: method, I remember I would be able to check if cell == nil, and basically have two separate areas for cell-related-customization (properties that apply to all cells vs. only to some). However with dequeueReusableCell: I am unsure how to handle this and put it off until I was able to get all my cells populated properly -- but seemingly at the expense of a great amount of CPU and Memory usage. Here is my code in cellForRow: currently:
    if case (1...(days.count + 1), 2...(hours.count + 2)) = (indexPath.column, indexPath.row) {

            let cell = spreadsheetView.dequeueReusableCell(withReuseIdentifier: String(describing: ScheduleCell.self), for: indexPath) as! ScheduleCell

            let legs : NSArray = importedDict.object(forKey: "legs") as! NSArray

            print(hours![indexPath.row - 2])

            var profits : Array<Double> = []

            if let singleLegDict2 = legs as? [[String:AnyObject]] {

                print (singleLegDict2)
                for singleLegDict in singleLegDict2 {
                    let dict = singleLegDict as NSDictionary

                    let dateFormatter = DateFormatter()
                    dateFormatter.dateFormat = "yyyy-MM-dd"
                    let datee = dateFormatter.date(from: days![indexPath.column - 1] as! String)!
                    let datee2 = dateFormatter.date(from: dict.object(forKey: "expiry") as! String)!

                    let calendar = Calendar.current

                    // Replace the hour (time) of both dates with 00:00
                    let date1 = calendar.startOfDay(for: datee)
                    let date2 = calendar.startOfDay(for: datee2)

                    let components = calendar.dateComponents([.day], from: date1, to: date2)
                    let doub = Double(components.day!)

                    let years = doub * 0.00273972602

//                    let under : NSNumber = dict.object(forKey: "underlying") as! NSNumber
                    let strike : NSNumber = dict.object(forKey: "strikePrice") as! NSNumber
                    let interest1 : NSNumber = dict.object(forKey: "interest") as! NSNumber
                    var interest2 = interest1 as! Double
                    interest2 = interest2/100
                    let userIV : NSNumber = NSNumber(value: Double(dict.object(forKey: "userIV") as! String)!)
                    var userIV2 = userIV as! Double
                    userIV2 = userIV2/100

                    var type = 0
                    if dict.object(forKey: "putCall") as! String == "CALL" {
                        type = 0
                    } else {
                        type = 1
                    }

                    let theo = getTheoreticalOptionPrice(forUnderlyingPrice: hours![indexPath.row - 2] as! NSNumber, withStrike: strike, withInterestRate: NSNumber(value: interest2), withVolatility: NSNumber(value: userIV2), withTimeToExpirationInYears: NSNumber(value: years), withType: NSNumber(value: type))
                    let userC : NSNumber = NSNumber(value: Double(dict.object(forKey: "userCost") as! String)!)
                    let quan : NSNumber = dict.object(forKey: "quantity") as! NSNumber
                    let diff = (theo - (userC as! Double)) * (quan as! Double)
                    print(theo, (userC as! Double))
                    profits.append(diff)
                }

            }

            print(profits)

            var sumedArr : Double = profits.reduce(0, {$0 + $1}) as Double
            sumedArr = sumedArr * 100

            if sumedArr < 0 {
                cell.backgroundColor = UIColor(red: 0.8667, green: 0.1804, blue: 0.1804, alpha: 1.0)

            } else {
                cell.backgroundColor = UIColor(red: 0.3843, green: 0.7686, blue: 0.1608, alpha: 1.0)
            }

            cell.label.text = String(format: "%.0f", sumedArr)

            return cell
        }

Any ideas on how to speed that up? Is the only way going to be preloading the data and then only referencing it in cellForRow:? How would I go about addressing this situation given the calculations I am doing per cell?
I don't need the cells to reload their data every time they are scrolled to. If all the cells load their data once when the view loads, and that data was just displayed — that would be perfect.
With that in mind, I tried adding a check to see if the cell's label was populated or not, and only if not, do all those calculations (assuming this would be the first loading of the table view). While that improved scrolling performance, the cells weren't properly displaying and were completely out of order. Help?
Update: I have moved the heavy calculations to a background thread and now experience smooth scrolling. However, the cells still flicker because they are still regenerating their data each time they are shown. What is the easiest way to cache the cells so that they load once when the tableView is shown, and then scroll smoothly because they reference already loaded data?

A: I do not understand why it is so important for the performance of your app to know whether a tableView cell has been initialized newly or is re-used. But if so, you can handle it as earlier. The docs say:

If you registered a class for the specified identifier and a new cell
  must be created, this method initializes the cell by calling its
  init(style:reuseIdentifier:) method. For nib-based cells, this method
  loads the cell object from the provided nib file. If an existing cell
  was available for reuse, this method calls the cell's
  prepareForReuse() method instead.

So you should be able to distinguish both cases and respond accordingly.

A: Using JavaScriptCore to calculate data for each cell in cellForRow was slowing down my tableView beyond fixing. The only alternative was to cache the data in an Array beforehand and then display it. However, for my use-case, this was not an option.
I rewrote the JavaScript in Swift and the scrolling improved.


text:
Q: Spark Logs in Yarn Resource Manager
    In YARN Resource Manager fails to open the execution history of the Spark job.

    In the Tracking UI column provided Unassigned, when you try to open the history by clicking on job ID falls error:

Failed to read the attempts of the application.

    Through the Spark History Server logs perfectly visible.

Failed to read the attempts of the application application_1472109196019_0094.
java.lang.reflect.UndeclaredThrowableException
    at org.apache.hadoop.security.UserGroupInformation.doAs(UserGroupInformation.java:1727)
    at org.apache.hadoop.yarn.server.webapp.AppBlock.render(AppBlock.java:221)
    at org.apache.hadoop.yarn.server.resourcemanager.webapp.RMAppBlock.render(RMAppBlock.java:65)
    at org.apache.hadoop.yarn.webapp.view.HtmlBlock.render(HtmlBlock.java:69)
    at org.apache.hadoop.yarn.webapp.view.HtmlBlock.renderPartial(HtmlBlock.java:79)
    at org.apache.hadoop.yarn.webapp.View.render(View.java:235)
    at org.apache.hadoop.yarn.webapp.view.HtmlPage$Page.subView(HtmlPage.java:49)
    at org.apache.hadoop.yarn.webapp.hamlet.HamletImpl$EImp._v(HamletImpl.java:117)
    at org.apache.hadoop.yarn.webapp.hamlet.Hamlet$TD._(Hamlet.java:845)
    at org.apache.hadoop.yarn.webapp.view.TwoColumnLayout.render(TwoColumnLayout.java:56)
    at org.apache.hadoop.yarn.webapp.view.HtmlPage.render(HtmlPage.java:82)
    at org.apache.hadoop.yarn.webapp.Controller.render(Controller.java:212)
    at org.apache.hadoop.yarn.server.resourcemanager.webapp.RmController.app(RmController.java:54)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:498)
    at org.apache.hadoop.yarn.webapp.Dispatcher.service(Dispatcher.java:153)
    at javax.servlet.http.HttpServlet.service(HttpServlet.java:820)
    at com.google.inject.servlet.ServletDefinition.doService(ServletDefinition.java:263)
    at com.google.inject.servlet.ServletDefinition.service(ServletDefinition.java:178)
    at com.google.inject.servlet.ManagedServletPipeline.service(ManagedServletPipeline.java:91)
    at com.google.inject.servlet.FilterChainInvocation.doFilter(FilterChainInvocation.java:62)
    at com.sun.jersey.spi.container.servlet.ServletContainer.doFilter(ServletContainer.java:900)
    at com.

    I would be grateful for any ideas!


text:
Q: Django DB Migration InconsistentMigrationHistory when running migrate I am unable to migrate my django after running python ./manage.py migrate.
This is what showmigrations is displaying
customerweb
 [X] 0001_initial
 [X] 0002_user_industry
 [X] 0003_auto_20220209_1737
 [X] 0004_userconfiguration_night_surcharge_exempt
 [ ] 0005_auto_20220614_1100
 [X] 0006_orderdelivery_is_order_unique
 [ ] 0007_orderdelivery_client_reference_no

I have tried --fake as well as trying to move back by one migrate using
python ./manage.py migrate <app_name> <000x_migrate_file>

all these is not working as the exeception keeps prompting InconsistentMigrationHistory. I have tried deleting the migration folders as well (keeping init only) but does not work as well.

A: So Django admin expects a default auth model which is AUTH_USER_MODEL.  Admin app apply migration as django's auth model Now since you changes the dependency hence the error. Please follow the below steps

*

*Take a backup of your database

*Comment out your created app in INSTALLED_APPS and AUTH_USER_MODEL = 'account.User' in your settings.py in project folder

*Run python manage.py admin zero

*Uncomment lines commented in step 2

*Run python manage.py migrate


text:
Q: ID4037: The key needed to verify the signature could not be resolved from the following security key identifier I have two web applications that are getting a SAML2 SSO between them. One direction is working fine. But the other results in this error:

ID4037: The key needed to verify the signature could not be resolved from the following security key identifier

With this stack trace:

at System.IdentityModel.EnvelopedSignatureReader.ResolveSigningCredentials()
at System.IdentityModel.EnvelopedSignatureReader.OnEndOfRootElement()
at System.IdentityModel.EnvelopedSignatureReader.Read()
at System.Xml.XmlReader.ReadEndElement()
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadAssertion(XmlReader reader)
at System.IdentityModel.Tokens.Saml2SecurityTokenHandler.ReadToken(XmlReader reader)
at ITfoxtec.Identity.Saml2.Saml2AuthnResponse.ReadSecurityToken(XmlNode assertionElement)
at ITfoxtec.Identity.Saml2.Saml2AuthnResponse.Read(String xml, Boolean validateXmlSignature)
at ITfoxtec.Identity.Saml2.Saml2PostBinding.Read(HttpRequest request, Saml2Request saml2RequestResponse, String messageName, Boolean validateXmlSignature)
at ITfoxtec.Identity.Saml2.Saml2Binding`1.ReadSamlResponse(HttpRequest request, Saml2Response saml2Response)

I control both sides of the code.
When running the SAML messages through my unit tests on my development machine it works. But on the test server the SAML messages fail. I have verified that the correct certificates are being used, and included in the SAML. I have even changed to other certificates to ensure there isn't an issue with that but it still failed at the same place.
The test server is part of a larger application. So I assume the issue is with how that application is setup or configured but I cannot figure out what to change or update. It's also possible that the problem is with the server itself, but I'm also not sure what to change or update on there.
The application is .NET 4.7.2. So I've looked at the SAML2 code here (https://github.com/ITfoxtec/ITfoxtec.Identity.Saml2/blob/bdc785d01fd38c2213659be2116ebb8ae19ed4d9/src/ITfoxtec.Identity.Saml2/Request/Saml2AuthnResponse.cs):
    private Saml2SecurityToken ReadSecurityToken(XmlNode assertionElement)
    {
        using (var reader = new XmlNodeReader(assertionElement))
        {
            return Saml2SecurityTokenHandler.ReadToken(reader) as Saml2SecurityToken;
        }
    }

To .NET's EnvelopedSignatureReader.ResolveSigningCredentials here (https://github.com/microsoft/referencesource/blob/dae14279dd0672adead5de00ac8f117dcf74c184/System.IdentityModel/System/IdentityModel/EnvelopedSignatureReader.cs#L183)
Which lead me to create my own TokenResolver and assign that to the config, but I'm not too sure it's being called as the same error comes up.
Any help is greatly appreciated!

A: My custom TokenResolver was not being used. Because I specified it AFTER creating the response. Gotta be before.
config.CustomIssuerTokenResolver = new TokenResolver

I do need to specify my own Token Resolver because the default has been overriden via the web.config. But it is working now.


text:
Q: PLS-00306: wrong number or types of arguments in call to 'CREATE_PROGRAM' I have googled around for this error but seems my problem is unique. I am trying to schedule a procedure inside a package in Oracle 11g. I have create a package and a procedure successfully. Now I need to schedule this package to execute every day at 2200hrs, begining today at 1710hrs. I have written a scheduler like this:
BEGIN
  SYS.DBMS_SCHEDULER.CREATE_PROGRAM
    (
      program_name         => 'SIMBABI.EXTRACTOR'
     ,program_type         => 'STORED_PROCEDURE'
     ,program_action       => 'SIMBABI.BIEXTRACTOR.SIMBABIEXTRACTOR'
     ,start_date=> trunc(sysdate)+17.10/24
     ,repeat_interval=> 'FREQ=DAILY; BYDAY=MON,TUE,WED,THU,FRI,SAT,SUN; BYHOUR=22;'
     ,enabled              => TRUE
     ,number_of_arguments     =>  0
     ,auto_drop=>false
     ,comments             => 'EXTRACTION FOR BI DATA'
    );

  SYS.DBMS_SCHEDULER.ENABLE
    (name                  => 'SIMBABI.EXTRACTOR');
END;
/

I do not have any arguments either in my procedure or Package:
CREATE OR REPLACE package body SIMBABI.biextractor as
procedure SIMBABIEXTRACTOR is
begin
insert into general_accounts_master
select foracid,
          acid,
          acct_n......

When I try to compile my scheduler I am getting the error:
PLS-00306: wrong number or types of arguments in call to 'CREATE_PROGRAM'

What am I doing Not Right??

A: You are supplying some arguments that CREATE_PROGRAM doesn't have.
Those extra arguments are valid for CREATE_SCHEDULE or CREATE_JOB, but not for CREATE_PROGRAM.
CREATE_PROGRAM accepts the following arguments:
DBMS_SCHEDULER.CREATE_PROGRAM (
   program_name             IN VARCHAR2,
   program_type             IN VARCHAR2,
   program_action           IN VARCHAR2,
   number_of_arguments      IN PLS_INTEGER DEFAULT 0,
   enabled                  IN BOOLEAN DEFAULT FALSE,
   comments                 IN VARCHAR2 DEFAULT NULL);

After creating the program, you can use CREATE_SCHEDULE or CREATE_JOB to schedule the execution of the program.


text:
Q: Android unable to download APK from end-point signed by NetworkSolutions DV CA I have an nginx serving an .apk file. For my domain name, the nginx is configured to serve a SSL certificate signed by Network Solutions DV Server 2 CA which is in turned signed by AddTrust External CA Root. I'm able to

*

*download the apk file from desktop (Chrome/macOS or curl/macOS) via https in 4 minutes

*download it over http in Android 4.x and 5.1

*verify that the http response has Content-Type: application/vnd.android.package-archive

*access the index page of my domain over https without seeing certificate warnings on Android 5.1 (on Android 4, it would warn untrusted CA despite both versions having AddTrust CA as a root CA.)

*download fully a similar sized JPG photo in the android browser over https from my server

*if I host the apk in S3, Android is able to download it using https
However, I'm not able to

*

*download the apk from my server with https in Android 4 or 5, the download is queued in download center and eventually failed (I saw that it would transiently switch to In Progress state and then back to Queued state quickly.)

*or download from my server over https when it is served directly by nginx (without proxying to tomcat)

Repeating the download many times still won't work.
While the SSL issue may cause it to fail on Android 4, I would expect it to go through in Android 5 at least. What would cause Android download center to fail?

A: It turns out that Android Download Center has a different SSL verification than the browser. The intermediate CA certificate is built in in the Android 5 browser but not in the Download Center or Android 4 browser. After configuring nginx to present full certificate chain, the APK download works and also the Android 4 browser also will not show untrusted CA warning.


text:
Q: New inherited class gets its property name renamed on migration with EF Code First I'm using Entity Framework Code First with inheritance to define my classes each implementing an abstract class containing common properties all of them should have.
I ran into a problem when I wanted to add new one to batch. All inherited classes have property having a common name with different type, but in this last class, property had same type as well.
public abstract class ProductProperty
{
    public string CommonProp { get; set; }
}

public class IntegerProperty : ProductProperty
{
    [Required]
    public int Value { get; set; }
}

public class StringProperty : ProductProperty
{
    [Required]
    public string Value { get; set; }
}

public class DoubleProperty : ProductProperty
{
    [Required]
    public double Value { get; set; }
}

Up to this point things where good. When I've added another one with integer Value property, Code First Migration is created by moving existing Value column on SQL table, instead of creating new one, which of course causes problem, because I already have data in Properties table.
public class IntWithUnitProperty : ProductProperty
{
    [Required]
    public int Value { get; set; }

    public string Unit { get; set; }
}

RenameColumn(table: "dbo.ProductProperties", name: "Value1", newName: "Value2");
RenameColumn(table: "dbo.ProductProperties", name: "Value2", newName: "Value3");
AlterColumn("dbo.ProductProperties", "Value1", c => c.Int());
AlterColumn("dbo.ProductProperties", "Value2", c => c.String());

It is obvious this is wrong in multiple ways yet I've tried to update database:

Error: The new name 'Value2' is already in use as a COLUMN name and
  would cause a duplicate that is not permitted.

From this behaviour, what I understand is EF starts giving names and suffixes by class name order:

*

*Value for Double

*Value1 for Int

*Value2 for String

And when I've tried to add another class with name starting Int... into batch, it tries to put it after Value1.
Question is, where are column names with number suffixes pointing properties with same name of inherited classes mapped in EF?
Maybe I can tell EF to add a new column in SQL and point to right class instead of trying to manipulate existing ones.

A: I think you'd be better off explicitly naming your Value columns by using data annotations, rather than risking them being re-assigned during migration. For example:
public class IntegerProperty : ProductProperty
{
    [Required]
    [Column("Value1")]
    public int Value { get; set; }
}

public class StringProperty : ProductProperty
{
    [Required]
    [Column("Value2")]
    public string Value { get; set; }
}

And so on.
Alternatively you could use table-per-type (TPT) rather than the default table-per-hierarchy (TPH), so that each subclass has it's own table, and therefore Value will always be called Value. Example: http://weblogs.asp.net/manavi/inheritance-mapping-strategies-with-entity-framework-code-first-ctp5-part-2-table-per-type-tpt


text: Q: Integral over hemisphere not aligned with principle axis. I'd like to integrate a function over a hemisphere (obtained from a sphere of radius $\delta$) whose flat side is normal to an arbitrary vector $\mathbf{n}$. I thought a change to spherical coordinates would be an appropriate way to solve this; however, the limits of integration are giving me a bit of trouble. I considered a modification of spherical coordinates so that the north pole is aligned with $\mathbf{n}$; however, this ended up being rather messy. If someone has a reference or a more elegant solution I would really appreciate it.


text:
Q: Why is a good practice to inherit any class we make from the class 'object'? In python, why is recommended to inherit any class we make from the class object , why not directly make it as the base class??
An important thing I noticed is that the declaration __slots__ does not work if I make my class as a base class (instead as a subclass of the class object).
What other advantages/disadvantages do I have by inheriting my class from the class object?

A: In Python2, you must inherit from object in order to create a "new-style" class. Things like descriptors, super and __slots__ do not work correctly with "old-style" classes, but old-style classes remained for backwards compatibility.
In Python3, all classes are new-style classes, so inheriting from object is no longer necessary.

A: when you inheriting from the object you create new style class, without it you have old style class see: http://www.python.org/doc/newstyle/ for more


text:
Q: Two cospectral (normal) digraphs which are not orthogonal similar Preliminaries
A complex matrix $A$ is normal when $A$ and $A^*$ commute. A real matrix $A$ is normal when $A$ and $A^t$ commute.
Two complex matrices $A$ and $B$ are said to be unitary similar if there exists a unitary matrix $U$ such that $A\cdot U=U\cdot B$. Two real matrices $A$ and $B$ are orthogonal similar if there exists a (real) orthogonal matrix $O$ such that $A\cdot O=O\cdot B$.
When $A$ and $B$ are complex normal matrices then $A$ and $B$ are unitary similar if and only if $A$ and $B$ have the same characteristic polynomial (see e.g., this post).
Let $A$ and $B$ be real normal matrices. If $A$ and $B$ are orthogonal similar then $A$ and $B$ have the same characteristic polynomial. The converse does not hold, however, since $A$ and $B$ may have complex eigenvalues and unitary rather than orthogonal matrices are needed.
Question
I would like to have an graph-based example showing that having the same characteristic polynomial does not suffice for orthogonal similarity.
More precisely, call a directed graph $G=(V,E)$ normal if its adjacency matrix $A_G$ is normal.
Normal directed graphs are necessarily balanced, i.e., the in-degree of each vertex is equal to its out-degree (see e.g., this  post).
So, what are examples of two normal (and thus balanced) graphs $G$ and $H$ (consisting of the same number of vertices) whose adjacency matrices have the same characteristic polynomial yet are not related by means of an orthogonal similarity?

A: Two normal digraphs with the same characteristic polynomial are orthogonally similar. So no counter example can exist.
Let $A$ and $B$ two real normal matrices. From the comment above, it suffices to check that $tr(w(A,A^t))=tr(w(B,B^t))$ holds for all words $w(x,y)$. Since $A$ and $A^t$ commute (because of $A$ being norma) we may assume $w(A,A^*)$ to be of the form $(A^t)^k\cdot A^\ell$ for some $k$ and $\ell$. We can further diagonalize $A$ (again using normality) by means of a unitary matrix $U$, i.e., $A=U\cdot \Delta_A\cdot U^*$ where $\Delta_A$ is a diagonal matrix with $A$'s (possibly complex) eigenvalues $\lambda_1,\ldots,\lambda_n$ on its diagonal. Note also that $A^t=U\cdot\Delta_A\cdot U^*$ (for normal matrices, an eigenvector of $A$ is an eigenvector of $A^t$ for the same eigenvalue and $U$ may be assumed to consist of eigenvectors). Using properties of trace and $U\cdot U^*=I=U^*\cdot U$:
\begin{align*}
tr((A^t)^k\cdot A^\ell)&=tr(I\cdot (A^t)^k\cdot I\cdot A^\ell)\\
&=tr(U\cdot U^*\cdot (A^t)^k\cdot U\cdot U^*\cdot A^k)\\
&=tr(U^*\cdot (A^t)^k\cdot U\cdot U^*\cdot A^k\cdot U)\\
&=tr((\Delta_A)^k\cdot\Delta_A^\ell)\\
&=\sum_{i=1}^n \lambda_i^{k+\ell}.
\end{align*}
Since $A$ and $B$ are assumed to have the same characteristic polynomial,
$tr((B^t)^k\cdot B^\ell)=\sum_{i=1}^n \lambda_i^{k+\ell}$ as well. Hence, repeating this for every word $w(x,y)$, $tr(w(A,A^t))=tr(w(B,B^t))$ holds for all words $w(x,y)$.