How can I make the left margin bigger?

Question: I would like to move the h1 text more to the middle of the screen, but the left margin isn't working properly. I've tried increasing and decreasing the size of the margin (both with pixels and percentages) but it has no effect on the page. I've also tried changing the background colour to see if I just forgot to end the previous line or I had the wrong dimensions, and the colour changed (so no errors there). I've also ran both the HTML and the CSS code through their respective validators and there's no errors related to the margin/header.
Here's the HTML code:

Welcome!
What do you want to make?

and the CSS code:

    img, img.menui {
        width: 165px;
        height: auto;
        margin-left: 0px;
        margin-right: 0px;
    }
    div, div.cake, div.menu {
        width: 80%;
        height: 60%;
        margin-left: 10%;
        margin-right: 10%;
        margin-top: 7%;
    }
    h1 {
        font-size: 16px;
        /*margin-left: 428769875937548px;*/
    }

Welcome!
What do you want to make?

For more context you can find the website here
Comment: why do you have a margin left that is that big/useless on your h1?
Comment: Wrap texts in one inline-block element and then `h1 {text-align: center}`
Comment: I don't want a margin that big, but usually if I make small adjustments I can barely see them. I made the margin dramatically big so I could clearly see when the code does work
Comment: If you uncomment your margin-left it works...
Answer:

    div, div.menu {
        width: 80%;
        height: 60%;
        margin-left: 10%;
        margin-right: 10%;
        margin-top: 7%;
    }
    h1 {
        font-size: 16px;
       display: inline-block;
       text-align:center;
    }
    h1 > span {
       font-size: 50px;
       text-decoration: none;
       text-shadow: 4px 4px 1px #ffffff;
       color:#f5cec9;
    }

Welcome!
What do you want to make?

Move your inline CSS into a CSS class/identifier (span)
Set your H1 wrapper tag to "inline-block" to retain margin values
Set your text to centered to centered the contents text.
Answer: Just add "display: inline-block;" to h1:

    img, img.menui {
        width: 165px;
        height: auto;
        margin-left: 0px;
        margin-right: 0px;
    }
    div, div.cake, div.menu {
        width: 80%;
        height: 60%;
        margin-left: 10%;
        margin-right: 10%;
        margin-top: 7%;
    }
    h1 {
        font-size: 16px;
        display: inline-block;
        margin-left: 150px;
    }

Welcome!
What do you want to make?

Answer: margin-left works, you just have to use a realistic value, not billions of pixels like in your (commented)  setting:

img,
img.menui {
  width: 165px;
  height: auto;
  margin-left: 0px;
  margin-right: 0px;
}

div,
div.cake,
div.menu {
  width: 80%;
  height: 60%;
  margin-left: 10%;
  margin-right: 10%;
  margin-top: 7%;
}

h1 {
  font-size: 16px;
  margin-left: 80px;
}

Welcome!
What do you want to make?

But if you want to center the text, just use text-align: center on it:

img,
img.menui {
  width: 165px;
  height: auto;
  margin-left: 0px;
  margin-right: 0px;
}

div,
div.cake,
div.menu {
  width: 80%;
  height: 60%;
  margin-left: 10%;
  margin-right: 10%;
  margin-top: 7%;
}

h1 {
  font-size: 16px;
  text-align: center;
}

Welcome!
What do you want to make?

How can I make the left margin bigger?


Babel compile error: Cannot find module core-js/library/fn/get-iterator

Question: This is my directory structure:
├───demo
│   ├───entry
│   │   ├───index.js
│   │   ├───tap.js
│   │   └───util.js
│   ├───node_modules
│   ├───index.html
│   ├───package.json
│   └───webpack.config.js
├───src
│   ├───tap.js
│   └───util.js
├───index.js
└───package.json

In demo/entry/index.js I have
import tap from '../../src/tap';

When compiling this, babel throws error
ERROR in ../src/tap.js
Module build failed: Error: Cannot find module 'core-js/library/fn/get-iterator'

But it works if I import like this
import tap from './tap';

The file ./tap.js and ../../src/tap are the same.
Is the problem node_modules? Because in demo directory, the babel and anything else is in node_modules, so I can import any file I like. But src/tap.js has no such parent or sibling directory like node_modules, so it will trigger this error.
Comment: The only time this happened to me, some folders disappeared from node_modules/core-js/library. I had to delete and re-install core-js.
Comment: you sure that `tab.js` does not have a `import ...get-iterator` somewhere it looks to me that you are doing it right, tab.js is now imported, but then you have to deal with it's imports.
Comment: any progress on this error? I got the same error while running react tutorial. https://www.tutorialspoint.com/reactjs/index.htm
Answer: Try to install babel-loader and babel-core as dev-dependency:
npm install babel-core babel-loader --save-dev

Also you need to update your .babelrc
{
    "presets" : ["es2015", "react"]
}

It works good for me. Good luck ;)
Answer: Maybe you did not install core-js.
I used to meet this problem.

First, delete your node_modules directory contents
Second, execute yarn install if you had installed yarn
Third, check your webpack version and babel-loader version, webpack 1.x can must be related to babel-loader 6.x
Comment: this `delete and reinstall all` works for me. But why?
Answer: I just installed core-js and it worked.
Comment: reinstall core-js was enough for me too, I don't understand downvotes
Answer: Updating to node version 11.10.0 (Current Version) worked for me.


How to bind two different samples one on my pad and the other onto keyboard keys

Question:
Have Oxygen v4 49
Using Ableton Lite x64
I have sample packs
Using Win 8.1 x64
Using Pod X3 Live as a soundcard.

I drag'n drop sample into my pad section, works fine.
I would like to drag'n drop another sample which works for keyboard keys.
My purpose is using different samples on my pad and keyboard keys same time, real-timed.
Then I want to start recording by using both pad section and keyboard keys which has binded different samples.
Answer: I guess you want to use your keyboard keys to play one sample at different pitches, right?
For that purpose, you might want to use Live's "Simpler" instrument, instead of the "Drum Rack" you're probably using with your pad section. All you need to do is create a new MIDI track with a Simpler, and drag'n drop your sample onto it.
Then if you arm both tracks (Drum Rack and Simpler), you should be able to control both at the same time with your keys and your pad (I guess it's possible to route your MIDI controls so that your keys don't trigger your Drum Rack's samples and vice-versa)
I hope this will help.
Comment: yes it works that way i did that, one sample for each pad button. But it conflicts with keyboard buttons. So when i both add drums and my synth sample, and press on C0 Key on midi keyboard, i hear both drum kick and synth sample C0 note. I'll update the post with images so i will be able to explain better. Thank you for your participation.
Comment: I added a simpler instrument, but cannot drag'n drop nor my voice sample, neither drum rack. Am i doing something wrong ?
Comment: @blankBird_ In the Simpler instrument there's a blank square zone with a "Drop Sample Here" inscription. This is where you should be droping your voice sample (mp3/wav/... file). Here's some video tutorial: https://www.youtube.com/watch?v=7pPGtxYJGOA
Comment: it works for now. But i want to improve. My 8 button pads starts from C0. How can i bind my 8 button pads starts from C -2 ?
Comment: @blankBird_ I'm not exactly sure of what you're trying to do here, but your pad is bound to your Drum Rack right? The "notes" you trigger with your Pad for your Drum Rack are just a way for Live to indentify which slot to trigger (i.e. which sample to play). And you can place each sample of your Drum Rack on any slot you want by drag'n droping your sample on a slot. This is the way you can custom how your samples and pad buttons are bound to each other.
Comment: @blankBird_ I found this link : http://www.akaipro.com/kb/article/1509
I know it's not the MIDI controler you're using but the solution might be analogue
Answer: With @eyam 's help, i found out a solution for this, and i think this is available just for m-audio oxygen v4 series.

Create a midi channel and add just 1 instrument on it,
Create another midi channel and add drums on it,
For your first channel's instrument, in MIDI From seciton, change All channels to Ch. 1
For your second channel's drums, in MIDI From seciton, change All channels to Ch. 10

Works perfectly !


How can I avoid "Open cursor limit exceeded" error for this code?

Question: <code>foreach (string num in ld2.Keys)
{
  double state;
  int i;

  for (i = 0; i < states.Count; i++)
  {
    cmd = mdb.getCommand("select value V " +
                         "  from TAB_CHART_DATA " +
                         " where TIMESTAMP = (select max(TIMESTAMP) " +
                         "                      from TAB_CHART_DATA " +
                         "                     where chart_type= " + chart_type +
                         "                       and upper(upper(state)) = '" + states[i] + "' " +
                         "                       and CSIS_ID = " + CSISPID +
                         "                       and baselinecode like '" + num + "'" +
                         "                   ) " +
                         "   and chart_type = " + chart_type +
                         "   and upper(state) = '" + states[i] + "' " +
                         "   and CSIS_ID = " + CSISPID +
                         "   and baselinecode like '" + num + "'"
                        );

    state = mdb.ExecSQLAndGetFirstInt(cmd);
  }

}
</code>
This loop runs for more than 3000 times.
Comment: Your code is open to [SQL Injection](http://en.wikipedia.org/wiki/SQL_injection)
Comment: Whatever `ExecSQLAndGetFirstInt` is doing, it should close the reader it uses to retrieve the data.
Comment: Please show us the real code. Are you maybe creating a new statement each time in the loop and not closing it?
Comment: @a_horse_with_no_name- Yes it closes the reader.
Comment: does closing the reader mean that the cursor is closed?
Answer: Fetch all rows in one query and loop over the result set in your code instead of opening cursors and killing the database.
Comment: I want to use the result of the query for further fetches.
Comment: @laksh - Please post the complete code and explain _exactly_ what you are trying to do (edit your question and add the details to it).


How to prevent React admin's auth provider from requesting authorization on 400 Bad request?

Question: I have ordinary custom data provider with only urls changed, and I see no sense to bring it's code here. The problem is that on 400 HTTP status response, my data provide redirects to /login.
As for me it's quite inadequate behaviour, since 400 bad request is not a 401 unauthorized. The problem of 400 originates from API backend, and I see no reason to re-login the user. Is it possible to prevent that redirection?
Comment: This behavior is set in your Auth Provider: https://marmelab.com/react-admin/AuthProviderWriting.html
Answer: The authProvider inspects API errors in its checkError method, so your normally have the ability to decide when an error requires a logout (in that case, return a rejected Promise), and when the error should just trigger a notification (and in that case, return a resolved Promise).
For instance:
// in src/authProvider.js
export default {
    login: ({ username, password }) => { /* ... */ },
    checkError: (error) => {
        const status = error.status;
        if (status === 401 || status === 403) {
            localStorage.removeItem('auth');
            return Promise.reject();
        }
        // other error code (404, 500, etc): no need to log out
        return Promise.resolve();
    },
    // ...
};

More info at https://marmelab.com/react-admin/AuthProviderWriting.html#checkerror
Comment: On 400 my checkError receives error=undefined and status is empty string, so I don't see the possibilty to tune here.
Comment: the the problem is in your dataProvider, which doesn't return an error with a status


Accessing database from local network

Question: I would like to access database running on virtual machine which resides in server connected to local network.
Here's the whole situation:
  There is Windows Server 2008 R2 Datacenter running as virtual machine and it has Oracle database on it. I'm using RDP to control OS remotely, but now I would like to use my computer to access database. I've tried creating database connection in JDeveloper with hostname just like my RDP connection IP, but unfortunately this way doesn't work.
Could anybody suggest the best way to accomplish such task?
Answer: There is a great answer for a very similar issue over on superuser.com at https://superuser.com/questions/130552/tunneling-a-tcp-ip-connection-through-remote-desktop-connection
Comment: The method suggested above will work if you can't expose the oracle server to the network via a public IP. However, depending on your circumstances simpler solutions might exist. Can you tell us more about your network setup, where the vm lives, etc.?

Accessing database from local network


A coin is tossed $n$ times. What is the probability of getting odd number of heads?

Question:
A coin is tossed $n$ times. What is the probability of getting odd number of heads?

I started this chapter sometimes ago and faced in front of a tough problem. At first I started considering cases. Case-I : The probability of getting 1 head.Case-II : The probability of getting 3 head and so on. But there are many cases. So how can I solved this . Please help me. Thank you!
Answer: Hint. Let $p_n$ be the probability of getting an odd number of heads tossing a coin $n$ times, then
$$p_{n+1}=(1-p_1)\cdot p_{n}+ p_1(1-p_{n})$$
where $p_1$ is the probability to obtain a head with one toss. So given $p_1$ (if the coin is fair then $p_1=1/2$), the above linear recursion allows us to evaluate $p_n$ for any positive integer $n$.
P.S. The recursion is explained as follows: at the $(n+1)$th toss we have an odd number of heads if and only if one of these disjoint cases occurs:
i) we have a tail and in the previous $n$ tosses there are an odd number of heads;
ii) we have a head and in the previous $n$ tosses there are an even number of heads.
Comment: @RoberZ So what is the answer
Comment: @DeltaScuti_Fomalhautb What is $p_1$? Then you will be able to find $p_n$...
Comment: @DeltaScuti_Fomalhautb it isn't always necessary to answer the question - it is a hint.
Comment: @RobertZ Ok sorry got it
Comment: @RobertZ please explain why you had written $p_n=(1-p_1)p_n+p_1(1-p_n)$?
Comment: @Sufaid Saleel See my P.S.
Answer: First toss $n-1$ times. When you toss the $n^{th}$ time, one outcome will give an even number of heads and one outcome an odd number of heads.
If the coin is a fair coin, this gives the result immediately. If it is not, then you need to combine the probabilities of odd/even after $n-1$ tosses with the probabilities on the last toss as Robert Z has done, or sum the binomial.
Comment: For a fair coin this analysis is complete due to indistinguishability, but for a biased coin it is not, then it matters if $n$ is odd or even.
Comment: @orip True, I had assumed an unbiased coin, and will make that clear. Robert Z's answer does the recurrence version o which this would lead and others are summing the binomial.
Answer: The probability of getting $k$ heads is $\binom{n}{k}2^{-n}$. So the required probability is $$\sum_{k=0}^{\lfloor\frac{n-1}{2}\rfloor}\binom{n}{2k+1}2^{-n}=2^{-n}\times2^{n-1}=\frac{1}{2}$$
Answer: At first we need to determine the sample space.
The sample space is analogous to a 'n' digit number whose each place can have only two digits, i.e., either a head(H) or a tail(T). For example, a three digit number can be written as HTT, or, HTH, or, HHH, etc.
Considering this analogy, we get the total number of 'n' digit numbers as $2^5$. Please refer to the figure: Sample space. So, our sample space consists of $2^5$ elements.
Now, we need the number of favorable events, which is in this case, odd number of heads. Therefore the number of favorable events is the summation of the series -
number of times we get only 1 head + number of times we get 3 heads + number of times we get 5 heads + number of times we get 7 heads + $\cdots$
Let the desired number of head be 3 and the coin is tossed eight times. So, one of our possible number is HHHTTTTT. The number of distinct permutations of this number is $\frac{8!}{3! \times 5!}$, which is equal to $8C_3$.
Generalizing this case, when the coin is tossed n number of times and for 'k' number of desired heads, the number of outcomes is $nC_k$.
So, finally we get the number of favorable events as $nC_1+nC_3+nC_5+nC_7+\cdots$
Now, we can determine the probability of getting odd number of heads as
\begin{align}
\text{P(odd numbers of heads)} &= \frac{nC_1+nC_3+nC_5+nC_7+\cdots}{2^n} \\
&= \frac{2^{n-1}}{2^n} \\ &= \frac{1}{2}
\end{align}
Answer: If $X$ is the number of heads you have to calculate
$$P(X \text{ is odd})=\sum_{k=0}^{\left\lfloor \tfrac{n-1}2 \right\rfloor}P(X=2k+1).$$
As $X\sim Binomial(n,1/2)$, you can calculate that probability for each $k$. That is:
$$P(X \text{ is odd})=\sum_{k=0}^{\left\lfloor \tfrac{n-1}2 \right\rfloor}{n \choose 2k+1}\left(\frac12\right)^{2k+1} \left(\frac12\right)^{n-(2k+1)} =\left(\frac12\right)^n \sum_{k=0}^{\left\lfloor \tfrac{n-1}2 \right\rfloor}{n \choose 2k+1}.$$
Now, if $n$ is odd the last sum is
$${n \choose 1}+{n \choose 3}+\cdots+{n \choose n-2}+{n \choose n},$$
which by the symmetry of the binomial coefficients is equal to
$${n \choose n-1}+{n \choose n-3}+\cdots+{n \choose 2}+{n \choose 0}.$$
Since it is known that
$${n \choose 0}+{n \choose 1}+{n \choose 2}+\cdots+{n \choose n-1}+{n \choose n}=2^n,$$
then both previous sums add up to $\tfrac{2^n}2=2^{n-1}$.
On the other hand, if $n$ is even the sum is
$${n \choose 1}+{n \choose 3}+\cdots+{n \choose n-1}=$$
$$=\left[{n-1 \choose 0} + {n-1 \choose 1}\right] + \left[{n-1 \choose 2} + {n-1 \choose 3}\right]+\cdots+\left[{n-1 \choose n-2}+{n-1 \choose n-1}\right]=$$
$$=2^{n-1},$$
as in the '$n$ is odd' case.
So for every $n \in \mathbb{N}$
$$P(X \text{ is odd})=\left(\frac12\right)^n \cdot 2^{n-1}= \frac12.$$


Nested copy/paste loops in excel VBA

Question: Very new to VBA and trying to write a macro that has a loop within a loop. I'd like the whole code to run 30 times
For i = 1 To 30

Worksheets("Salary Extract (SPs Only)").Range("B" & (1 + i)).Copy
Worksheets("Pitcher Matchup Analysis").Paste
Destination = Worksheets("Pitcher Matchup Analysis").Range("B9")

For i = 1 To 9

Worksheets("Pitcher Matchup Analysis").Range("B" & (38 + i)).Copy
Worksheets("Batter Matchup Analysis").Paste
Destination = Worksheets("Batter Matchup Analysis").Range("B1")
Worksheets("Batter Matchup Analysis").Range("B88:AC88").Copy
Worksheets("Pitcher Matchup Analysis").Range("C" & (38 + i) & "AD" & (38 + i)).PasteSpecial xlPasteValues

Next i

Worksheets("Pitcher Matchup Analysis").Range("A71:R71").Copy
Worksheets("Pitcher Comparison").Range("A" & (1 + i) & "R" & (1 +  i)).PasteSpecial xlPasteValues

Next i

End Sub

Within each loop I'd like this block to loop 9 times
For i = 1 To 9

Worksheets("Pitcher Matchup Analysis").Range("B" & (38 + i)).Copy
Worksheets("Batter Matchup Analysis").Paste
Destination = Worksheets("Batter Matchup Analysis").Range("B1")
Worksheets("Batter Matchup Analysis").Range("B88:AC88").Copy
Worksheets("Pitcher Matchup Analysis").Range("C" & (38 + i) & "AD" & (38 + i)).PasteSpecial xlPasteValues

Next i

My guess is this is a fairly simple fix but I'm not sure and couldn't figure it out looking at other questions.
Comment: Just place the second loop inside the first loop and rename i of the the second loop to something else.
Answer: At first glance the issue is that you can't use the counter "i" for both loops.  Change one of the counters to "j" and all references in the inner loop to "j" as well.  I'm not sure if there are other problems but that one jumps out at me.

Nested copy/paste loops in excel VBA


After WAMP update & migrate, mysql tables have no structure / primary keys

Question: We've moved WAMP to another drive on our server - the old version was WAMP 2.4, and the new one is WAMP 2.5. We installed 2.5 fresh on the new drive, and copied the www and mysql data folders from the old install.
It's 'working' - sites appear to run fine - but I've discovered that the database structure appears to be gone. All database tables have no primary keys, and no visible structure in phpMyAdmin.
This is the case for databases brought into the new WAMP install in the mysql data folder as well as new databases: I can export a database with structure from a remote server, but after importing to the local WAMP server the structure is stripped.
Two questions:
(How) can the database structure be restored?
How can I create or import new databases with structure?
Answer: Curiously this sorted itself out after attempting to troubleshoot the issue then undoing changes. What we tried:

Restarted all WAMP services, exited and reopened WAMP - unsuccessful.
Copied entire old mysql folder to new WAMP install, attempted to run mysql service with old mysql version - unsuccessful.
Reverted to newer version of mysql that came with WAMP 2.5 (back to initial state before troubleshooting), restarted services - unsuccessful.
Waited 10 minutes - table structure returned, working correctly.

This leads me to believe there was an interaction with another process or condition on the server, rather than a misconfiguration of WAMP.


How do I silence load alerts?

Question: Within the large set of files that comprise our Nagios server, is service check for load:
define service{
        use                             generic-service
        name                            check-load
        hostgroup_name                  nrpe-hosts,!webnodes,!build-cluster
        notification_options            c,r
        service_description             NRPE - Load
        check_command                   check_nrpe!check_load
        contacts                        irc
}

And two contacts:
define contact{
        contact_name                    irc
        alias                           ircbot
        host_notification_period        24x7
        service_notification_period     24x7
        host_notification_options       d,u,r,f
        service_notification_options    w,u,c,r,f
        service_notification_commands   notify-by-epager
        host_notification_commands      host-notify-by-epager
        pager                           email@example.com
        }

define contact {
       contact_name                             pagerduty
       alias                                    PagerDuty Pseudo-Contact
       service_notification_period              24x7
       host_notification_period                 24x7
       service_notification_options             u,c,r
       host_notification_options                d,r
       service_notification_commands            notify-service-by-pagerduty
       host_notification_commands               notify-host-by-pagerduty
       pager                                    lol-no
}

EDIT: also, a service inheritance thing:
define service{
        name                            generic-service
        check_period                    24x7
        max_check_attempts              3
        normal_check_interval           3
        retry_check_interval            1
        notification_interval           0
        notification_period             24x7
        notification_options            w,c,r
        register                        0       ; DONT REGISTER THIS DEFINITION - ITS NOT A REAL SERVICE, JUST A TEMPLATE!
}

Edit2: And an notify command definition, just for the doubters ;) :
# 'notify-by-epager' command definition
define command{
        command_name    notify-by-epager
        command_line    /usr/bin/printf "%b" "Service: $SERVICEDESC$\nHost: $HOSTNAME$\nAddress: $HOSTADDRESS$\nState: $SERVICESTATE$\nInfo: $SERVICEOUTPUT$\nDate: $LONGDATETIME$" | /bin/mail -s "$NOTIFICATIONTYPE$: $HOSTALIAS$/$SERVICEDESC$ is $SERVICESTATE$" $CONTACTPAGER$
}

Edit3: And a host definition:
define host{
        host_name                       vmprod1
        alias                           vmprod1.example.com
        address                         220.127.116.11
        use                             generic-host
        hostgroups                      nrpe-hosts,vm-hosts,vm-prod,dellraid-hosts
        contact_groups                  example,example-pager
}

This is the only check with the service description "NRPE - Load". By my reading, this should only alert the irc contact, and not the pagerduty contact. Yet I got over 100 "NRPE - Load" alerts last month in PagerDuty.
What am I missing?
Comment: This is most likely an inheritance issue - your 'use generic-service' might well be defining other contacts / contact groups.
Comment: what does the "view config" section of the web interface show for one of those services? and add your notification command "notify-by-epager" to the question
Comment: Unfortunately, this does not appear to be the case; I've added in the generic-service template as evidence. =/
Comment: I don't seem to have a 'view config' section? But I did add the notify command.
Comment: Ah, it's a global view config.
Comment: Apparently, services inherit contact groups from host definitions. Researching this now to see if I can undo that or define an empty contact group.
Answer: To repay my debt of graditude, I'll answer my own question. It turns out that services implicitly inherit from hosts, and thus the service check above had a contact setting and an inherited contact_group.
A simple fix to the service check will do:
define service{
        use                             generic-service
        name                            check-load
        hostgroup_name                  nrpe-hosts,!webnodes,!build-cluster
        notification_options            c,r
        service_description             NRPE - Load
        check_command                   check_nrpe!check_load
        contacts                        irc
        contact_groups
}

Comment: I think it's more correct to use "contact_groups null", but if that works... go with it ;-)

How do I silence load alerts?


How to shift an object to rest on the xy-plane?

Question: For example, I have a cube, which exists somewhere in 3-space, that is composed of edge vectors and vertex points. How can I shift these values so that a face of the cube rests on the xy-plane?
I don't want all the vectors to simply be projected onto the xy-plane, since they should retain their magnitude. The cube should appear exactly the same, other than a change in orientation and position.
How can I define a transformation matrix or value to signify how to rotate the top-left cube so that the blue-outlined face is coplanar with the xy-plane (like the bottom-right cube)?
Answer: Yes. You can do this with a translation and a rotation.
Let's start by saying that one of the corners of the blue square that you want to move to the plane is called $A$: then you take all the corners of your cube and subtract $A$ from them, so that $A$ becomes $(0,0,0)$, and the other corners become...some other points. This is "translation" and doesn't change the shape of the cube at all.
Now let's suppose that the two corners of your blue square adjacent to $A$ are called $B$ and $C$, and the third corner adjacent to $A$ (the not-blue one) is called $D$. Compute
$$
u = B - A\\
v = C - A \\
w = D - A
$$
each of these is to be computed term-by-term, so if $B = (4, 6, 3)$ and $A = (2, 0, 1)$, then $u = (2, 6, 2)$, ok? If you use post-translation vertex coordinates, then $A = (0,0,0)$, so $u = B - A$ will contain just the (post-translation) coordinates of $B$. It doesn't matter which you use -- you'll get the same value for $u$.
Now, you're going to alter $u, v, w$ slightly:

compute $L = \sqrt{u_x^2 + u_y^2 + u_z^2}$
replace $u = (u_x, u_y, u_z)$ with $u = (\frac{u_x}{L}, \frac{u_y}{L}, \frac{u_z}{L})$, i.e., divide each coordinate by $L$.

Do a similar operation to $v$ and $w$.
Now you're going to do the following transformation to each $(x,y,z)$ point of the post-translation cube (i.e., each vertex, or each point on any face, whatever).
\begin{align}
(x, y, z) &\mapsto (x', y', z'), \text{where}\\
x' &= u_x x + u_y y + u_z z\\
y' &= v_x x + v_y y + v_z z\\
z' &= w_x x + w_y y + w_z z.
\end{align}
That will send the edge $AB$ to the positive x-axis, the edge $AC$ to the positive $y$ axis, and the edge $AD$ to the positive z-axis.
If you actually know about matrices and linear algebra, this is all a good deal easier: the transformation (using homogeneous coordinates like $(a_x, a_y, a_z, 1)$ for the point $A$), looks  like
$$
X \mapsto \mathbf M X
$$
where
$\mathbf M$ is a matrix whose upper right $3 \times 1$ submatrix contains $-a_x, -a_y, -a_z$. The lower right entry is 1; the bottom left $1 \times 1$ submatrix is all zeroes, i.e., it looks like
$$
\mathbf M = \begin{bmatrix}
 &   & & -a_x \\
 & * & & -a_y \\
 &   & & -a_z \\
 0&  0  & 0 & 1 \\
\end{bmatrix}.
$$
The upper left $3 \times 3$ block has rows $u', v', w'$, where
\begin{align}
u' = \frac{B - A}{\| B - A \|} \\
v' = \frac{C - A}{\| C - A \|} \\
w' = \frac{D - A}{\| D - A \|}.
\end{align}
And that's it. In this form, the letters $A$, $B$, $C$, and $D$ denot the coordinates of the specified vertices before any operations have taken place.
Addition in response to comments
This works because the vectors $u,v,w$ are pairwise perpendicular, so that inverting a particular matrix amounts to just transposing it.
In general, if you have a basepoint ($A$) and a point $B$ that you want on the $x$-axis, and a point $C$ that you want in the +y halfplane, you can compute
$$
u = B - A\\
v = C - A
$$
Then you let
$$
\hat{v} = v - \frac{ (u \cdot v) u}{u \cdot u}
$$
to make $v$ and $u$ perpendicular, and then let
$$
u' = u / \| u \|\\
v' = \hat{v} / \| \hat{v} \|
w' = u' \times v'
$$
Now once again, these are pairwise orthogonal unit vectors, and the matrix described above will do what you need.
Comment: I suppose I could've helped you out a bit, by specifying I understand vector math, such as dot product, addition, and normalizing even though the rest of my linear algebra is a little fuzzy. Will this method work for any objects, whether geometric or free-form, as long as you have a point on that face, and its adjacent points?
Comment: Yeah, that would've saved some typing. :) The nice thing about the cube here is that the three vectors from $A$ to its adjacent points are pairwise perpendicular; that's what lets me compute the transformation that sends them to the $e_1, e_2, e_3$ -- plane by just transposing the matrix whose columns are $u, v, w$. In general, if you have a basepoint ($A$) and a point $B$ that you want on the $x$-axis, and a point $C$ that you want in the +y halfplane,...well, see my additional comments in the answer above.
Comment: When I attempt to make u and v perpendicular, it doesn't always work, i.e. $(u \cdot v)$ doesn't equal 0. Perhaps the vectors are too far apart? If you do the same process again, it works though. Does this change the process, or will the same concept apply?
Comment: Fixed. In trying not to say "Gram-Schmidt", I left out the "normalize $u$ first" step, which made my formula for $v'$ wrong. I've now fixed it (dividing by $u \cdot u$).
Comment: I had actually already tried that, and the vectors still weren't orthogonal after doing that, which is why I repeated the process.
Comment: When I compute $\hat{v} \cdot u$, I get $v \cdot u - \frac{(u \cdot v)(u \cdot u)}{u \cdot u} =  v \cdot u - (u \cdot v) = 0$. Perhaps there's something wrong in your implementation? Regardless, the *idea* is to apply Gram-Schmidt to the vectors $u, v, u \times v$, in that order.
Comment: I thought this worked originally, but now I'm noticing that this seems to only make the face parallel to the xy-plane, not necessarily coplanar with it.
Comment: Did you perhaps forget the first step, which is "... you take all the corners of your cube and subtract $A$ from them, so that $A$ becomes $(0,0,0)$, and the other corners become...some other points. This is "translation" and doesn't change the shape of the cube at all."
Comment: No, I included this. I setup the matrix as specified, including the $-a$ values.
Comment: Well...if you transform $A$ to the origin, and then apply a linear transform, $A$ will still be at the origin. Since the plane you care about includes this transformed $A$, that means you have a plane through the origin that's parallel to the $xy$-plane, which must therefore be the $xy$ plane. Check where $A$ ends up under your sequence of operations.
Comment: You're right. My problem was I was trying to combine the translation and rotation matrix because I needed it in one step... Which I've fixed now. So I really will quit bothering you on this unpopular question...
Comment: Not a problem. Happy to be a help here. I can also (with some diffidence) recommend "Computer Graphics: Principles and Practice", especially the chapters on 2D and 3D transformations. I was the lead author on it. :) I'd like to think that if you'd read those two chapters and done the exercises, not only would this question have been easy for you, but so would the debugging.
Answer: What is needed to map the blue square to the xy-plane is an affine transformation (translation + linear transformation). We will basically rotate one Cartesian coordinate system onto the standard Cartesian coordinate system, and then translate the rotated blue square to the origin. We first define a coordinate system with two coordinate vectors in the plane of the blue square. Let $A$ be a corner of the blue square, $B$ and $C$ adjacent corners to $A$ on the blue square, and $D$ a corner of the cube adjacent to A but not on the blue square. An intuitive Cartesian coordinate system for the cube would then be
\begin{align}
\hat{u} &= \frac{B-A}{||B-A||} \\
\hat{v} &= \frac{C-A}{||C-A||} \\
\hat{w} &= \frac{D-A}{||D-A||}
\end{align}
An affine transformation takes the form
\begin{equation}
\begin{bmatrix} \vec{y} \\ 1 \end{bmatrix} = M \begin{bmatrix} \vec{x} \\ 1 \end{bmatrix}
\end{equation}
where $M$ is the affine transformation matrix and the points have been put it homogeneous coordinates (in homogeneous coordinates, points get 1's appended to them and vectors get 0's appended). The $M$ that maps one coordinate system $(\hat{u},\hat{v},\hat{w})$ with origin $\vec{o}_u$ to another $(\hat{x},\hat{y},\hat{z})$ with origin $\vec{o}_x$ takes the form
\begin{equation}
\begin{bmatrix} \hat{x}& \hat{y} & \hat{z} & \vec{o}_x \\ 0&0&0&1 \end{bmatrix} = M\begin{bmatrix} \hat{u}& \hat{v} & \hat{w} & \vec{o}_u \\ 0&0&0&1 \end{bmatrix}
\end{equation}
\begin{equation}
\implies M = \begin{bmatrix} \hat{x}& \hat{y} & \hat{z} & \vec{o}_x \\ 0&0&0&1 \end{bmatrix} \begin{bmatrix} \hat{u}& \hat{v} & \hat{w} & \vec{o}_u \\ 0&0&0&1 \end{bmatrix}^{-1}
\end{equation}
As an example, let the points of the blue square be $(0.5, -0.5, 0.5)$, $(0.5, -0.5, -0.5)$, $(-0.5, -0.5, -0.5)$, and $(-0.5, -0.5, 0.5)$, then
\begin{align}
a &= (0.5, -0.5, 0.5) \\
b &= (0.5, -0.5, -0.5) \\
c &= (-0.5,-0.5,0.5) \\
d &= (0.5, 0.5, 0.5)
\end{align}
\begin{align}
\hat{u} &= (0, 0, -1) \\
\hat{v} &= (-1, 0, 0) \\
\hat{w} &= (0,1,0) \\
\vec{o}_u &= \vec{a} = (0.5, -0.5, 0.5)
\end{align}
\begin{equation}
M = \begin{pmatrix} 0 & 0 & -1 & 0.5 \\ -1 & 0 & 0 & 0.5 \\ 0 & 1 & 0 & 0.5 \\ 0 & 0 & 0 & 1  \end{pmatrix}
\end{equation}
Another approach that doesn't depend on an affine transformation or homogeneous coordinates relies on dyadics or vector outer products. Once the blue square is translated such that it passes through the origin (subtract $a$ from all corners), the rotation matrix that rotates the translated blue square onto the xy-plane is given by the vector outer product
\begin{equation}
R = \hat{u} \, \hat{x}^\top + \hat{v}\, \hat{y}^\top + \hat{w}\, \hat{z}^\top,
\end{equation}
which for the example above is
\begin{equation}
R = \begin{pmatrix} 0 & 0 & -1 \\ -1 & 0 & 0 \\ 0 & 1 & 0 \end{pmatrix}.
\end{equation}
Because we are mapping to the standard Cartesian basis, the rows of $R$ are simply $\hat{u}$, $\hat{v}$, and $\hat{w}$.
You will notice that $R$ is just the top left $3\times3$ submatrix of $M$, and the last column of $M$ is not $-\vec{a}$ in homogeneous coordinates. The reason the last column of $M$ is not $-\vec{a}$ is because matrix multiplication is not commutative. When we calculate $\begin{bmatrix} \vec{y} \\ 1 \end{bmatrix} = M \begin{bmatrix} \vec{x} \\ 1 \end{bmatrix}$ the matrix $M$ first rotates $\begin{bmatrix} \vec{x} \\ 1 \end{bmatrix}$ and then translates it, so the last column of $M$ is simply $-R \vec{a}$ in homogeneous coordinates.


IIS FTP: Should i create sites or folders?

Question: I need to create a service to host several ip cameras, in the beginning 500+.
The ip cameras send the files over ftp, so, to identify each camera, the files must go to separated folders.
Now the question, does IIS have any issue creating several FTP Sites or should i create just one and put all the users inside and separate files by folders?
I think that isolated FTP Sites are better, my worry is about performance, the server isnt so fast.
Thanks!
Answer: Physically, you have 1 site.
You have 500 IP cameras, so let's say you have 500 accounts.
If you need to reconfigure the site for every camera, you can easily do so.
If you need to change the DNS for your FTP site, you can easily do so.
With 500 sites, you will need either 500 unique binding IP addresses, or 500 unique domain names... otherwise your server will not know where to direct the traffic.
If you need to change the FTP settings for every camera, you will need to change it... 500 times.
If your IP address changes and you need to change your DNS, you will need to do it... 500 times.
For your own sanity, don't make 500 FTP sites.
If anything, you could make 1-10 FTP sites.
Let's say...
ftp.indoor.ipcamera.com  - 100 camera accounts
ftp.outdoor.ipcamera.com  - 200 camera accounts
ftp.corridoor.ipcamera.com  - 50 camera accounts
ftp.vantage.ipcamera.com  - 15 camera accounts
ftp.bottleneck.ipcamera.com - 25 camera accounts
and you could group your cameras in different categories to make management easier.
It's all about making it easier for YOU.
Comment: I have zero experience with FTP. But, thanks, understood what you said. One site can solve it using folders to each user.


Three proportions testing null hypothesis

Question: I have the following question.
In a random sample of 250 people with low incomes, 155 are in favour of a new piece of legislation, while in random samples of 200 people with average incomes and 150 people with high incomes there are, respectively, 118 and 87 who favour the legislation. use a significance level of $\alpha=0.05$ to test the null hypothesis that the proportion of people favouring the legislation is the same for all three groups.
I know that $H_0:p_1=p_2=p_3$ for low, average and high incomes. And $H_1$ is just that they are not equal. I was thinking I would need to do a chi-squared test but I'm not sure how to do that, given that I only have the sample proportions.
Would I just take the actual number of people in favour from each income group and then use the sample proportions? I'm a bit confused. Any help would be really good. Thanks.
Answer: You're essentially doing a test of homogeneity of proportions.
You need to arrange it as a 2x3 table (3 income groups vs favour/oppose) of counts, on which you can do a chi-square.
[Note however, that income groups are ordered (on income); you may want to consider an alternative that would be sensitive to a difference of opinion related to that ordering. On the other hand if you have no a priori expectation that the response will be ordered monotonically in income, the chi-square should be fine as is.]


Yamaha P45 MIDI Capabilities / What are the requirements for controlling this keyboard with my computer?

Question: Prefacing this post with a link to a post covering the same topic, but I'm having a hard time understanding if any of these solutions allow me to use my computer to change the instruments and manipulate sounds.
Yamaha P45 Digital Piano - Can it be made MIDI compatible?
If I'm understanding correctly, if I hook my computer up via usb to midi, the most I will be able to do is play and record something on the keyboard, and listen to it on my computer.
Other comments refer to using the keyboard as a controller. Does this mean only the keyboard can talk to and tell the computer what to do? Versus my computer telling the keyboard what sounds to play and what velocity/pitch to play it at? Will I see recordings as an audio clip or MIDI clip where I can see and change what notes are being played?
What are the minimum requirements a keyboard needs to meet in order to control the sounds, instruments, and effects from my computer? I am currently using an Alesis MIDI keyboard and looking to upgrade. Since my Alesis has this capability I am surprised to see that the Yamaha doesn't.
My current setup is keyboard connected to computer, and computer connected to speaker via AUX. While the Yamaha has internal speakers, I would rather hear it from mine in addition to the other sounds I am playing along with. in Ableton
Thank you for your help, I think I just need a dumbed down explanation of the post I linked to understand. Best, and thanks again
Answer: MIDI is a way for musical instruments to communicate with a device and tell it what notes they're playing. If you're using MIDI, then you need to get your own instrument sound on the computer via something called a VST. You can change the VST currently active to change the instrument.
If you just want to play the sound on your own speakers, you can just connect a cable from the headphone jack to your speakers. Not sure how to get both the sounds from your computer and the keyboard to play.

Does this mean only the keyboard can talk to and tell the computer what to do? Versus my computer telling the keyboard what sounds to play and what velocity/pitch to play it at?

As in using the keyboard to play back a MIDI file or some MIDI input? I'm honestly not sure. But the other way round (keyboard tells the computer what notes it's playing) is supported.

Will I see recordings as an audio clip or MIDI clip where I can see and change what notes are being played?

As a MIDI clip.
Answer: According to the manual, the keyboard has MIDI receive capabilities as well.
If it's implemented as it ought to be, this should mean you can specify it as a MIDI output in your DAW.
Here's an example of a track in Reaper that is routed to UM-ONE (my USB-to-MIDI cable), which connects it to my keyboard. The keyboard then plays the data in whatever voice I have it currently set to. As a bonus, I then record the keyboard audio output so that I don't have to have my keyboard on in future just to hear the track — obviously can only be done once the MIDI is finalized.


Negative Squared Root on Quadratic Equation formula?

Question: I have this basic problem:

In a farm, $X$ animals are added to the farm. These animals gain weight according to the equation: $500 - 2X$ gr. Which interval of animals can the farm take, if the total weight gain is greater than $30,600$ Kg?

Original (Spanish - Español):

En un criadero de cuyes se integran $x$ cuyes, si se tiene presente que los cuyes ganan peso en promedio de $(500 - 2x)$ gramos. ¿Qué intervalo de cuyes puede aceptar esta granja si la ganancia total de peso de los cuyes es mayor a $30 600$ Kg?

Step 1:
Total animals: $x$.
Weigthgain = $(500 - 2x)$ gr.
TotalWeightgain > $30 600(1000)$ converting kg to gr.
Step 2:
$$x(500 - 2x) > 30600000$$
Step 3:
$$0 > 2x^2 - 500x + 30 600 000$$
Step 4:
$$ x = \frac{-(-500) +- \sqrt[2]{(-500)^2 - 4(2)(30 600 000)}}{2(2)}$$
But as you can see, the sqrt is negative. So It does not exist.
What should be the next step?
Comment: *In a farm, X animals are integrated* - Well, $\displaystyle\int x~dx~=~\dfrac{x^2}2$
Comment: @Lucian, don't get what you say. Please, expand your comment.
Comment: @Lucian is being sarcastic. While amusing, it is not relevant.
Comment: I am curious, though, what do you mean by "integrated"? What doe you mean by "can take the farm"? It's a bit hard to tell what you're asking.
Comment: @Cameron Buie. I think a better translation for those are: 1) are joined? 2) can be put into the farm?. Sorry spanish mother tongue here. I've added the original problem in spanish, in case you know un poco de español.
Comment: Mi vocabulario español es insuficiente. ;-) I have added the `translation-request` tag. Hopefully, one of our users who is fluent in both languages will be able to provide a clear translation.
Comment: @CameronBuie, thanks. Hopefully someone can help.
Comment: I'm a native spanish speaker and I don't get what that means either. @user3352567 Por "integran" te referis a "En un criadero se encuentran"? De todas formas, este termino no parece importar en el ejercicio, haha.
Comment: @YoTengoUnLCD, I think it refers to the fact that $x$ animals(cuys) are added to the farm. But there is not information on how many were there already, if any.
Comment: Ahh, recien lo entiendo, una traduccion mas adecuada seria "are added to the farm".

Maybe the wrong part is the "Total animals: $x$", as that is only the amount of animals you've added. If you think (I think the question is a bit unclear) the farm was not empty before adding the cuyes, you'd have $x+c_0$ total animals, where $c_0$ denotes the initial amount of cuyes.
Answer: Assuming that you've transcribed and translated the question correctly, then your math is correct, and indeed no solution exists. So the next step would be to state that it is impossible for the farm to satisfy these conditions (there is no interval, or an empty interval, of solutions).
However, I suspect that there's an error in the units; likely they were intended to be the same (not grams in one place, kg in another). If we graph $y = x(500 - 2x)$, then we see that the maximum point occurs at (125, 31,250). While that's below 30,600,000 by some 3 orders of magnitude, it is slightly above 30,600, and so you will have a nonempty solution interval if the requirements were in matching units. So that's likely what was intended.
(Another slight correction to what you wrote is that $x$ isn't the total animals on the farm, it's just the added animals. I'm assuming that only these added animals gain weight, not the ones originally present, which are an unknown quantity.)


Not able to access "Updates" page logged in as admin user

Question: I am running a site on Acquia's dev cloud, using Acquia's Dev Desktop and sometime in the last few months something has changed to prevent access to the Update tab inside admin/modules/update. I'm logged in as the drupal admin, but when i try to access that page i get:

You are not authorized to access this page.

Also on that page, cron had stopped running regularly. When I tried running manually, it would give me the same error
Answer: This is the code for access to 'admin/modules/update', in 'update_manager_access':
  return variable_get('allow_authorize_operations', TRUE) && user_access('administer software updates');

So there are 2 reasons you wouldn't be able to access this page:

You don't have the administer software updates permission
The allow_authorize_operations variable is set to FALSE

The second is probably your problem.  This is a "global killswitch in settings.php" - the admin/modules/update path allows people to pull and upgrade modules without having actual server access, and Acquia may have disabled that for security.
For those experiencing this and not hosted on Acquia, some of my sites were returning NULL for allow_authorize_operations even though it's FALSE in settings.php.  Rebuilding permissions did not resolve this so I used variable_set in a PHP global field in a view.
References:

https://api.drupal.org/api/drupal/authorize.php/7.x
https://api.drupal.org/api/drupal/modules%21update%21update.module/7.x (look at $items[$path . '/update'] in update_menu)
Comment: The question is about Drupal 8, your answer applies only to Drupal 7.
Answer: What worked for me was rebuilding permissions under "/admin/reports/status/rebuild" (Make sure to take a db backup).
Right after rebuilding, I saw all the available updates.
Thought this might be of help to someone.
Answer: In my case (for Drupal 8 / 9 in contrast to the other anwser) the reason was
$settings['allow_authorize_operations'] = FALSE;

was set in settings.php. The current Drupal default is TRUE.
Down the path this leads to access denied for all paths from update.routing.yml with these requirements:
  requirements:
    _permission: 'administer software updates'
    _access_update_manager: 'TRUE'

Drupal simply returns Access Denied even for admins, but doesn't explain the reason.
See https://www.drupal.org/project/drupal/issues/2055185#comment-14240814 for details and help to improve the situation.
So you should check if
$settings['allow_authorize_operations'] = TRUE;
could be appropriate for you or if it's disabled for security reasons.
Answer: Problem
In Drupal 9.3.5 this message was found in the dblog:
Path: /admin/reports/updates/check.
Drupal\Core\Http\Exception\CacheableAccessDeniedHttpException:
'csrf_token' URL query argument is missing.
in Drupal\Core\Routing\AccessAwareRouter->checkAccess()
(line 118 of
/var/www/site.com/web/core/lib/Drupal/Core/Routing/AccessAwareRouter.php
).

Fix
Fixed with clearing/rebuilding caches with drush:
drush cr

This was on a local Ubuntu development machine.
Trigger - maybe
I remember visiting some page that did not work with a token in the URL parameter. I removed the token and tried again. After that, the access was denied to the Updates page, as an administrator.
I also ran some cli commands to tighten up file permissions prior to this happening.


inserting 1 million random data into PostgreSQL

Question: the table structure is like this:
milliontable(
   name varchar(10),
   age integer,
   joindate date
)

and I want to insert random 1 million data into that table. Is there any way to do that?
Answer: Use the random() function to generate random values:
INSERT INTO milliontable (name, age, joindate)
SELECT substr(md5(random()::text), 1, 10),
       (random() * 70 + 10)::integer,
       DATE '2018-01-01' + (random() * 700)::integer
FROM generate_series(1, 1000000);

It is usually a silly idea to store the age of a person in a table, as this number becomes wrong automatically as time goes by. Use the birthday.
Answer: You can use recursive queries. First is to generate rows from 1 to 1M. then use random() function to generate random age between 1 to 99 years old.
with recursive cte as (
   select 0 as ctr
   union all
   select ctr + 1 from cte where ctr < 1000000
)
insert into milliontable (name, age, joindate)
select 'name'||cast(ctr as varchar(30)) as name, floor(random()*(99)) as age, current_timestamp as joindate
from cte;

try dbfiddle.


Organização de projetos em pacotes

Question: Estou realizando um estudo sobre Java e gostaria de aprender sem utilizar aquelas IDEs cheias de recursos que fazem tudo.
Após várias tentativas de aprender a usar pacotes, criando-os manualmente, uma classe não está conseguindo enxergar outras fora do pacote. Segue um exemplo totalmente genérico:
A estrutura de pastas é a seguinte:
-pacotes
 Teste.java(classe com main)
 --objeto
   Texto.java

E os códigos dos arquivos são os seguintes:
-> Teste.java
package pacotes;
import pacotes.objeto.*;

public class Teste{

    public static void main(String[] args) {

        Texto t = new Texto();
    }
}

-> Texto.java
package pacotes.objeto;

public class Texto{

    public Texto(){
        System.out.println("Construiu um objeto");
    }
}

Ao compilar o arquivo Texto.java tudo ocorre normalmente, mas ao compilar o Teste.java fala o pacote 'pacotes.objeto' não existe, o que há de errado?
Comment: Você está usando alguma IDE (Netbeans, Eclipse, etc) ou está usando apenas editor de texto (ex: bloco de notas)?
Comment: Minha intenção é evitar o netbeans ou eclipse, pois quero aprender manualmente
Comment: Foi o que pensei... pelo jeito você está tentando compilar apenas a classe Teste. Veja minha resposta abaixo mostro como compilar o projeto.
Comment: Apaguei o comentário anterior pois vi algo que não tinha na resposta aceita. Além do mais você disse que seu exemplo é completamente genérico, então o fato da classe Texto não ter um construtor público provavelmente não é um problema no seu exemplo real, entretanto vou consertar pois do jeito que está não funciona.
Answer: Pelo jeito você está fazendo tudo em editor de texto, ou seja, não está usando uma IDE.
Você precisa indicar o pacote para compilar:
C:\Users\Leandro\Documents\Java\Exercícios\testes>javac pacotes/Teste.java

Comment: Você pode compilar seu pacote base: Ex: c:\javac pacotes/*.java
Comment: Obs: Veja que você precisa estar fora do diretório "pacotes" para compilar.
Comment: Muito legal, você me salvou, tipo, agora eu não posso fazer um   ...teste/pacotes/java Teste
Comment: agora, quando eu for rodar um projeto feito e pacotes, tenho que compilar todas as minhas classes sem main pelo metodo normal, e depois compilar a principal deste jeito
Comment: informações realmente úteis
Comment: Ainda assim é sempre melhor usar uma IDE para não ter que se preocupar com isso.
Answer: Não use wildcards isto é *
com isso poderá fazer:
package pacotes;

import pacotes.objeto.Texto;

public class Teste{

    public static void main(String[] args) {

        Texto t = new Texto();
    }
}

Detalhe o construtor de Texto deve ser declarado como público (se não fica como protected e restrito ao pacote pacotes.objeto).
package pacotes.objeto;

public class Texto{

    public Texto(){
        System.out.println("Construiu um objeto");
    }
}

Comment: Droga, agora lendo sua resposta acho que não deveria ter editado a pergunta, mas assim, o problema de não achar a classe era um problema com o classpath, não com a visibilidade do construtor. Para acrescentar, o fato de usar wildcard ou não, não vai interferir no resultado. A resposta é usar corretamente o classpath. Sobre a minha edição na pergunta, se quiser eu posso reverter (ou você mesmo pode).
Comment: @Math acho que não tenho reputação necessária para reverter sua edição. Quanto a wildcards, não era o erro que ele estava encontrando mais ainda assim [não são recomendados](http://javadude.com/articles/importondemandisevil.html)

Organização de projetos em pacotes


How to render the form tag

Question: I am using this code to make the user_profile_form available on my user-profile.tpl.php so the user profile filed can be edited directly from the sure page.
function parce_preprocess_user_profile(&$variables) {
  $variables['user_edit']  = drupal_get_form('user_profile_form', menu_get_object('user'));
}

Then, I can correctly print them individually using this code:
<?php print drupal_render($user_edit['account']['mail']); ?>

It works fine, but the problem is that the <form> tag doesn't appear on the page, and the form doesn't submit. When I add it manually in the template page, it works, but I was wondering how to get Drupal to insert these tags automatically.
I tried something like this (out of pure guess):
function parce_theme($existing, $type, $theme, $path){
  return array(
    'user_profile_form' => array(
      'render element' => 'profile_edit',
      'template' => 'user-profile',
    ),
  );
}

It doesn't work. Am I doing anything wrong?
Comment: I am not clear why you would show the edit form at every user profile page.
Answer: You have to render the full form, so drupal_render($user_edit) is needed.
Comment: Thanks for your answer Daniel, but when i do that the form tag is being printed of the page but now my form elements are not within the Form Tag. Basically i end up with   Then my form inputs
Comment: Still not working, when i do this the form element that i am printing end up outside the `` tags
Answer: I didn't find a way around that; I ended up printing the form tag manually.

How to render the form tag


Fan Speeds on SuperMicro System via IPMI

Question: I have a SuperMicro 4027GR-TRT server that I am running multiple GPUs in. I would like to set the cases fan speed higher that what they are right now using IPMI, although I am not sure how to do it.
I am currently able to interact with the system using ipmitool using raw commands. I have been able to get and set the systems fan settings using the following commands (via http://www.supermicro.com/support/faqs/faq.cfm?faq=18009):
ipmitool -I raw 0x30 0x45 0x01 0x00
This will set the fans to "Normal, Full or Optimal". My fans are currently running on the optimal setting at right around 4,700 RPM.
How can I increase my case fan speed to ~8,000 RPM or so? I have tried changing the fan thresholds but I don't understand what those settings are doing.
Is there a way to set the fan speed to a single value? If not, how would I set the lowest threshold so that its lower limit is 8,000 RPM?
My current threshold settings are as follows:
FAN1 4800.000 | RPM | OK | 300.000 | 500.000| 700.000| 25500.000 | 25500.000 | 25500.000

I have tried setting the lower threshold to 8,000 but that made all of the fans run at 14,000 RPM. I am not sure how the lower thresholds work.
Answer: In order to force the fans at a particular speed all the time, you need to do the following on a Supermicro X9 board:

Set IPMI fan mode to "Full"
Set fan speed for the particular zone to the percentage fan speed you desire, expressed as a hexadecimal number. On the X9 boards, the possible speed range is 0-255, which is 0-100% expressed as hex, but on a scale where 0% = 0x00 and 100% = 0xff.

In your case, with 14k fans, you want their speed at 8k, so the ratio is 57% (8000 / 14000 = .57142...)
Take 255 * .57 = 145.35 = 0x91 would be your speed value. Now plug that in.
Step 1: Set "fan mode" to "Full"
{ipmitool command syntax} raw 0x30 0x45 0x01 0x01

Step 2: Set "fan speed" to 57%
For Zone 0 (normally CPU fans or FAN_ where _ = a number, e.g. FAN1):
{ipmitool command syntax} raw 0x30 0x91 0x5A 0x03 0x00 0x91

For Zone 1 (normally peripheral fans or FAN_ where _ = a letter, e.g. FANA):
{ipmitool command syntax} raw 0x30 0x91 0x5A 0x03 0x01 0x91

NOTE1: Verified on a Supermicro X9DRi-F with Nuvoton WPCM450 BMC.
NOTE2: X10 boards operate differently. Some raw commands are different, and their %age fan speed is 0-100, not 0-255.
Comment: where do  you get these values from?
Comment: @ЯрославРахматуллин a combination of various sources: BMC technical documentation, experimentation on motherboards I have access to, information exchange with others who have performed similar experiments, motherboard manuals. Most motherboards follow particular patterns based on their manufacturer, board generation, and BMC chipset. There are exceptions, though rare. Generally speaking, only server boards allow granular or group fan header control.
Answer: Supermicro has bad data in the IPMI full sensor record. The fans don't have a max of 25K RPM. Fans at 8K are loud and OSHA and the telecom unions get involved. Try this
ipmitool -I raw 0x30 0x45 0xFF 0xFF

Comment: Hey @user3699374, can you tell me what the raw command does? What do the last ```0xFF 0xFF``` do? Do you know how to determine what raw commands are available for a given system via IPMI?
Comment: This did not work at all
Answer: I think the X9 motherboards have the same raw command as the X10 series. A la https://www.supermicro.com/support/faqs/faq.cfm?faq=20882
ipmitool -U <user name> -P <password> -H <hostname or IP> raw 0x30 0x70 0x66 0x01 0x00 0x<01 - 64>

If your fans spin at a max of 14000 RPM and you wanted them to spin at 8000 RPM then you'd set the duty to 0x37
ipmitool -U <user name> -P <password> -H <hostname or IP> raw 0x30 0x70 0x66 0x01 0x00 0x37

Comment: it looks like these commands don't work on X9's; at least not on my super loud desktop X9DRU system.
Comment: +1 as this worked for me on a Supermicro 4028GR-TR (X9-Board)! To get the current values use `ipmitool raw 0x30 0x70 0x66 0x00 0x0[0|1]` with the last value specifying the region (`0`==CPU-zone, `1`=peripheral-zone)
Comment: @user378380 supermicro systems run fans at 100% if there is only one power supply detected of a possible 2
Comment: They do not. The X10/X11 boards use the same or similar IPMI commands. The X9 boards are different. Furthermore, it can also depend on which BMC chip your board has. The X9 gen boards have either no BMC, or one of 4 BMC chips from 3 different manufacturers.
Answer: The 0xFF is used by some vendors to set fan speed to the max. There is no way to find what raw commands work with a specific vendor without consulting the vendor's documentation.
The 25K values you see are very, very out of range. Fans don't run at 25K RPM. So there is a bug in the SuperMico IPMI full sensor record for the fans or ipmitool has a bug.


Como reconhecer o tipo de dado inserido - C

Question: Estou fazendo um programa onde o usuário pode cadastrar, buscar e remover clientes. Para inserir ele digita "inserir [nome do cliente]"  e um código é gerado automaticamente. Estou com um problema na função de busca. Atualmente o usuário tem que digitar: "buscar x y" onde x é um int q identifica se a busca será feita pelo código ou nome do cliente e y é o valor correspondente. Eu queria fazer isso sem pedir ao usuário para especificar o tipo de busca. Tem alguma forma de receber o dado e depois verificar se eu recebi um inteiro ou uma string?
Comment: https://pt.stackoverflow.com/help/how-to-ask
Answer: Você pode usar a função isdigit, terá de percorrer toda a entrada com ela, se colocar o código fica mais fácil, mas segue um exemplo tirado da ajuda do watcom c.
<code>#include <stdio.h>
#include <ctype.h>

    //Aqui você não necessita por um vetor, imagine que seja o texto que
     você está armazenando

char chars[] = {
    'A',
    '5',
    '$'
};
#define SIZE sizeof( chars ) / sizeof( char )
int main()
{
    int   i;

    //Faça um for percorrendo a entrada caracter por caracter

    for( i = 0; i < SIZE; i++ ) {
        printf( "Char %c is %sa digit character\n",
                chars[i],
                ( isdigit( chars[i] ) ) ? "" : "not " );
                 //Verifique na função isdigit se é um numero ou não, da
proxima vez por favor deixar o codigo
    }

    return 0;
}
</code>
Comment: Obrigado, não coloquei o código porque como é um caso mais geral achei que não faria diferença, na próxima eu coloco.
Comment: Tudo bem, mas veja se consegue, caso o contrario só dar uma avisada aqui @Raul Boa sorte


Erro ao conectar PHP ao SQL Server via ODBC Linux

Question: Estou fazendo uma conexao no no windowns via php ao SQL SERVER e esta indo normal, em uma maquina onde o servidor php é linux esta dando o seguinte erro:
Fatal error: Uncaught exception 'PDOException' with message 'SQLSTATE[01000] SQLDriverConnect: 0 [unixODBC][Driver Manager]Can't open lib 'SQL Server' : file not found' in /var/www/html/sql/index.php:8 Stack trace: #0 /var/www/html/sql/index.php(8): PDO->__construct('odbc:Driver={SQ...') #1 {main} thrown in /var/www/html/sql/index.php on line 8

Como habilito o driver odbc no linux ?
LINUX:
PRETTY_NAME="Debian GNU/Linux 8 (jessie)"
NAME="Debian GNU/Linux"
VERSION_ID="8"
VERSION="8 (jessie)"
ID=debian
HOME_URL="http://www.debian.org/"
SUPPORT_URL="http://www.debian.org/support"
BUG_REPORT_URL="https://bugs.debian.org/"

APACHE:
Server version: Apache/2.4.10 (Debian)
Server built:   Nov 28 2015 14:05:48

SQL:
Microsoft SQL Server Standard Edition (64-bit)
Microsoft Windows NT 6.1 (7601)
NT x64
10.0.2531.0

PHP:
PHP Version 5.6.22-0+deb8u1

Comment: Quais as versões dos seus ambiente? Vá em [edit] e inclua essas informações na pergunta
Comment: @gmsantos editei,veja se é as informações que você precisa
Comment: versão do PHP ?
Comment: @gmsantos Inserido na pergunta.
Answer: 1) Primeiro, dê uma olhada nas permissões nolibsqlncli-11.0.so.1790.0, para ver se o apache pode escrever e ler.
2) É necessário ver as dependências da lib e ver se não existe alguma faltando.
ldd /opt/microsoft/sqlncli/lib64/libsqlncli-11.0.so.1790.0
3) Se você está usando CENTos tente desabilitar o SELinux.


C# - Lock method on value of variable (Threading)

Question: I have not much experience with threading, but in this project I need some Threads to request data from a SPS over the Com-Ports.
I have different Threads running and it could happen that 2 or even more Threads would like to access the same Com-Port, which of course doesn't work.
Now my question is if I can lock the called method on the value of a variable which would be the number of the Com-Port, while Threads with a different value can enter the Method.
Btw: I can't use different variables as "keys" for the lock, because I get the values dinamically from a database.
My code could look something like the following:
Main()
{
   Start different Threads calling myMethod
}

myMethod()
{
   lock on value of a Variable
   {
      some code...
   }
}

Comment: You need to use a reference type as lock-object so the _number of the Com-Port_ doesn't work. It depends on _some code..._ what you have to lock
Comment: What is question here?
Answer: I think your best solution is to create a class that contains myMethod and instantiate it for each port.
If you don't want to do that you can (for example) define a thread safe dictionary of locks
public static ConcurrentDictionary<int, object> locks = new ConcurrentDictionary<int, object>();

initialize it before you start your threads:
for (int i=0; i < 10; i++)
{
    locks[i] = new object();
}

and lock by port number:
lock(locks[portnum])
{
    some code...
}

Assuming of course that you know the port number in the context of myMethod (otherwise how would you access the specific port?).
Comment: If `some code...` uses shared resources which aren't initialized for every port this isn't thread-safe either. Also, if this dictionary could be modified later you should use a `ConcurrentDictionary`
Comment: You are right! ConcurrentDictionary is the correct object to use - I edited my answer. Regarding your other point, you are correct of course, however the OP didn't specify which objects he uses so it's impossible to give a concrete example that covers all shared resources.


Proving that $f(x) = \frac{1}{x}$ is not uniformly continuous over $(0,1)$ - Approach to choosing the correct $x$ and $y$

Question: I've looked at the various other posts on this question and I've also worked on uniform continuity in the past. But right now as I work through Spivak's Calculus, I'm seeing that I haven't actually learned how to find choices for my $x$ and $y$ elements in a structured well thought out way. In the past what I thought was doing this was actually me just regurgitating what a professor did in their proof without any understanding of how $x$ and $y$ were chosen.
To illustrate where I'm stuck:
Let $\epsilon = 1$. Taking arbitrary $\delta > 0$. I encounter the following:
$$\bigg|\frac{1}{x} - \frac{1}{y} \bigg| > \epsilon = 1$$
I've seen prior choices such as letting $x = \delta$ and $y = \frac{\delta}{2}$ or letting $x < \delta$ and $y = \frac{x}{2}$. But I want to understand how these choices were made initially.
I know that $x(\delta)$ and $y(\delta)$ as well if I fiddle with the the expression above I have
$$\bigg|\frac{x-y}{xy}\bigg|$$
I also know that since $x,y \in (0,1)$ that $xy < 1$ (but this now won't help me when I want to extend the interval to $(0, \infty)$.
It appears I'm throwing a lot of stuff at the wall hoping for something to stick and this isn't very conducive. How should I be reasoning these steps out?
Comment: I am writing a slightly long answer, request you to wait.
Answer: Some rough steps :

Visualize the graph of this function : since you are asked to prove that the function is not uniformly continuous, you must look for a place where the function is increasing really fast (or has steep slope) . (Note : a heuristic is that this can happen near a point where the function takes the value infinity : that point won't be there in the domain, but points close to it will be there)

Why? Because, at these points, the $x$ coordinates are really close, but the $y$ coordinates are far apart. Remember uniform continuity says that the $y$ - coordinate difference between two points on the function's graph can be uniformly controlled by controlling their $x$-coordinate difference : so the points lying on these high-slope regions are most likely to provide a contradiction.

After doing this, look for points $x,y$ for which the expression for $f(x)$ is very simple. For example, if $f(x) = \sin x$, then for $x$ being multiple of $\frac {\pi}4$, for example, the expression is simple.

Sometimes, you will be able to do both : find a sequence of points in the slopy region, for which the function values are really easy to evaluate. Then you can compare these values and come to a contradiction.

Let us apply these principles for $f(x) = \frac 1x$. Drawing $\frac 1x$ in your head, you see that if $x = 0$ the expression is infinite. So points near $0$ is where you can try to look.
Note that if $x$ is the reciprocal of an integer, then $f(x) $ is that integer! So taking $x = \frac 1n$ for $n \in \mathbb N$ gives simple values of $f(x)$. Thus, we don't need to complicate matters by looking at the general expression $|f(x)-f(y)|$.
Finally, we notice that if $x_n = \frac{1}{n}$ and $y_n = \frac 1{n+1}$, then $|x_n-y_n|$ can be made small enough, but we always have $|f(x_n)-f(y_n)| = 1$. So, for a given $\delta$, we can easily take such large $N$ that $\frac 1N < \delta$ (and $|x_N - y_N| =x_N-y_N < x_N < \delta$) but $|f(x_n)-f(y_n)| = 1$.
Thus uniform continuity is contradicted with $\epsilon = 1$, because we can find for any $\delta$ a pair of points differing by less than $\delta$ but whose function values have difference $1$.
You can keep these points in mind while approaching "non-uniform continuity" questions.
Comment: They seemed to have down voted the other good solution and up voted the one that really didn't provide any help....
Comment: Typo? In your 3rd $\bullet$ what is $\frac {p}{i}4$?
Comment: ouch@DanielWainfleet, thanksies!
Comment: I'm not really sure who is down voting your solution, but I like it.
Comment: I am happy you like my answer @dc3rd
Comment: @dc3rd I have no problem at all, this often happens in scattered fashion : if there is serial downvoting I will report it anyway. If you wanted to accept my answer, then I apologize , because the scattered downvotes won't let you accept the answer , unfortunately.
Answer: Informally, uniform continuity means the (absolute value of the) slope of the function is bounded above.  You should recognize that the derivative of $\frac 1x$, which is $\frac {-1}{x^2}$, can get as large as you want, so the function is not uniformly continuous.  The problem occurs close to $0$, so that is where you should choose your points.  You just have to find, based on the parameters you are given, how close you have to get.
You should not use $x$ for the variable in your function and again for one of the points, so I will use $y$ and $z$ as the two points.
The formal definition of uniform continuity says that for any $\epsilon \gt 0$ there is a $\delta \gt 0$ such that $|y-z| \lt \delta \implies |f(y)-f(z)| \lt \epsilon$.  I like to think of quantified statements as a game.  If somebody says the statement is true and I dispute that, I get to choose all the variables with a $\forall$ in my effort to make the statement false, while they get to choose all the variables with a $\exists$ in an effort to make the statement true.  We play in order of the quantifiers, so I choose $\epsilon$ first and choose $1$.  Now they have to choose $\delta$.  Here is the difference with normal continuity.  In the normal continuity definition, I have to choose $y$ before $\delta$ is chosen.  For uniform continuity, $\delta$ is chosen before $y$.  We assume $\delta$ is given to us.  We need to find $y,z$ that are within $\delta$ of each other but $|\frac 1y - \frac 1z| \gt 1$.  Here we can just take $z=y+\frac 12\delta$.  That keeps them within $\delta$ and we know $\frac 1y \gt \frac 1z$ so we can get rid of the absolute value signs.  Now we need
$$\frac 1y - \frac 1{y+\frac 12\delta} \gt 1\\
y+\frac 12\delta -y \gt y(y+\frac 12 \delta)\\
\delta \gt 2y^2 + y\delta\gt 2y^2\\
y \lt \sqrt{\frac \delta 2}$$
So I can choose $y=\frac 12 \sqrt \delta, z=y+\frac 12\delta$ and the claim will fail.
Comment: Because of the symmetry we can take it to be so.  Whatever two points we are going to use, we label the smaller one $y$.
Comment: No, just that the equation involves $|y-z|$ and $|\frac 1y-\frac 1z|$.  These are equal under interchange of $y$ and $z$ so we can assign them arbitrarily.  Either way will work just the same.  You would just replace $y$ with $z$ in all my display equations.
Comment: This helps me think about things a bit more structured. But why do we know $\frac 1y \gt \frac 1z$ ?
Comment: Forgive me, but which symmetry are you alluding to? Are you basing it off the idea of "well ordering" of the Reals? So like you said I can choose for $y < z$ or $z < y$. And since it doesn't matter which order we choose them both forms are satisfactory?
Comment: Ok. That makes sense too. Thanks for the clarification
Answer: Simply let $ x = 2y \implies \left|\dfrac{x-y}{xy} \right| = \dfrac{1}{x} \ge \epsilon = 1$ when $0 < x < \delta < 1$.
Comment: This is just giving the answer.  The OP wants to understand how you would think of such a proof.


Probability mass function and Random measure

Question: I have seen this in a few tutorial and papers on Dirichlet Process, where people refer to the probability mass function of stick-breaking-process as a random measure. From the wikipedia definition there doesn't seem to be any link between these two. I wonder what is the relationship.
Note: [I am a computer science student, so there are definitely some missing stuff in my knowledge which may seem obvious to a statistics student].
Comment: You were one Wikipedia click away from the connection! From the page on "random element" (linked on the page for "random measure"): "In probability theory, random element is a generalization of the concept of random variable to more complicated spaces than the simple real line".
Answer: The Dirichlet process can be thought of as a random variable where any particular realisation is a measure. In the case of the Dirichlet process this random measure is almost surely a discrete probability measure, and may be written as
$$
\sum_i w_i \delta_{X_i},
$$
where $\{w_i\}$ are distributed according to a stick breaking process and the atom locations $X_i$ are i.i.d from some distribution.


Explosive AR(MA) processes are stationary?

Question: According to Theorem 8.8 in Time Series A.W. van der Vaart an ARMA process $$\phi (L)X_t=\theta(L)\epsilon_t$$
has a  unique stationary solution $X_t=\psi(L)\epsilon_t$ with $\psi=\theta/\phi$ if $\phi$ has no roots on the complex unit circle. This would imply that the explosive process, with $\rho>1$, is a stationary process $$X_t=\rho X_{t-1}+\epsilon_t$$ with stationary solution $X_t=\sum_{i=1}^\infty \rho^{-i}\epsilon_{t+i}$.
Now indeed $\sum_{i=1}^{\infty} \rho^{-i} < \infty$ so that weak stationarity can be proved by using this representation.
However, here on stackexchange I see a lot of question/answers that suggest that the process above is not stationary (see for example Are explosive ARMA(1, 1) processes stationary?, Non-Stationary: Larger-than-unit root). In particular, the accepted answer of the latter question claims that the process is non-stationary by simulating a series and showing it displays explosive trending behaviour.
I think the only way to reconcile the theorem I mention above and the plots in the accepted answer of (Non-Stationary: Larger-than-unit root) is the following: the explosive process is indeed stationary but non-ergodic, that is, we cannot find the statistical properties of $X_t$ such as $\mathbb{E}(X_t)=\mu$ by observing a single infinitely long sample path of the explosive process, mathematically:
$$\lim_{t \to \infty}\frac{1}{t}\sum_{t=1}X_t \neq\mathbb{E}X_t$$
Is this reading correct?
Comment: @corey979 I am baffled by the notion that an explosive process could be considered stationary, and would undoubtedly experience wonder and delight if I were shown that it is so. That said: the variances of explosive processes are functions of time, and the means of explosive processes are functions of time, and perturbations to explosive processes give stronger effects as more time passes since they occurred, so I am not understanding how an explosive process could be stationary in any sense.
Comment: Excellent question on a subtle topic!
Comment: @Alexis, you have to turn time back
Comment: @Alexis, "variances of explosive processes are functions of time" - sure about this?
Comment: @Aksakal I spent some time starring at the solution, and it went click: you not only need a time machine for *some* point in the future, but for *all* futures. So you are quite correct when you say "I won't like it!" :)
Comment: ARMA is stationary when the _roots of the autoregression polynomial lie outside the unit circle_.
Comment: Also: Welcome to CV, Joogs!
Comment: Might this be a duplicate of [this](https://stats.stackexchange.com/questions/400296/are-explosive-arma1-1-processes-stationary)? Or the other way around?
Comment: @Aksakal Am learning here, so I am placing my money and being willing to be wrong. :) Let me say that I would be surprised to learn that the variance of an explosive process is independent of time *without* invoking slight of hand like "if you assume a separate linear model at for each length of the time series". So, sure? :) The variance of $y_{t} = \rho y_{t-1} + \varepsilon_{t}$ grows with $t$ for $|\rho| \ge 1$
Comment: It seems me that this story not hold. The AR(1) model is stationary if, using the notation above, $-1<\rho<1$. Moreover, put aside stationarity, I'm dubious about the possibility to use $\rho>1$ at all. Read (also) my answer on this this "mirror" discussion: https://stats.stackexchange.com/questions/494135/the-explosive-ar1-process-with-varphi1-where-was-this-first-represented-a/494187#494187
Comment: @ Joogs ; take care with parameters. You said that "… an ARMA process has a unique stationary solution if $\phi$ has no roots on the complex unit circle. This would imply that the explosive process  … is stationary". Contradictory conclusion. I do not have your book at hand but I know that some presentations and software make different inversion/manipulation on the characteristic polynomials.
Comment: @markowitz, when $|\rho|<1$ the process is not only stationary but also *causal*, when $\rho>1$ it is not *causal* but is still stationary.
Comment: @Aksakal; in some books AR processes with $|\rho| \geq 1$ are considered as non stationary and/or not considered at all. Moreover in some books the concept of "causal process" you refers on are not mentioned at all. I'm dubious, give me more time for think better about all concept used here and in related post. However I expressed one point of view in this strongly related discussion. Take a look:
https://stats.stackexchange.com/questions/494135/the-explosive-ar1-process-with-varphi1-where-was-this-first-represented-a/494187#494187
Answer: Yes, there is a stationary solution for $\rho>1$ in AR(1) process:
$$X_t=\rho X_{t-1}+\varepsilon_t$$
I'm not sure you'll like it though:
$$X_t=-\sum_{k=1}^\infty\frac 1 {\rho^k}\varepsilon_{t+k}$$
Notice the index: $t+k$, you'd need DeLorean to use this in practice.
When $\rho>1$ the process is not invertible.
Comment: @Alexis, look at 4.5.3 example to simulate here http://www.maths.qmul.ac.uk/~bb/TimeSeries/TS_Chapter4_5.pdf basically, it's stationary but not causal, i.e. your today depends on tomorrow.
Comment: Stangely appropriate to what I am currently busy with: time-varying confounding and g-estimation of causal effects in Hernán & Robins. :)
Comment: Argh! I am so busy right now. I wanna go play with this in simulation to appreciate why that is stationary, but that is going to have to wait until at least tonight. Thank you, as always, for pushing my understanding on time series.
Comment: Am I right about the non-ergodicity of the process?
Comment: @Joogs, I don't think so.
Comment: But from the stationary solution we obtain $\mathbb{E}(X_t)=0$, but all the simulated series display trending behaviour which basically becomes unrevertible for values of the process high enough, why would the time average converge to something finite (and in particular 0)?
Comment: @Joogs, I need to think about ergodicity. My gut feeling is that if we drop causality, then how is $\rho>1$ process is different from $\rho<1$? One is the mirror of another on time axis, i.e. you turn time back and ergodicity seems to be the same for both. I'll think more tonight, and may change answer later. However, my main answer stands correct in either case: AR(1) is stationary for $\rho>1$
Comment: @Joogs, I thought about ergodicity, and couldnt find argument why solution for $\rho$>1 wouldn't be considered ergodic. So, no, I disagree with your statement on ergodicty. Again, the only problem with that solution is that it's non causal, which makes it useles in most poractical situations, but it's a valid stationary solution nevertheless
Comment: 1/2 @Aksakal "I couldn't find argument why solution for $\rho>1$ wouldn't be considered ergodic": I do not have the mathmatical statistics to put this formally, but when you look at simulated processes (graphically) with $|\rho|>1$ they diverge, and pretty quickly. Like, pick any time series of length $T$ to simulate, then simulate, say, $2T$, and you are **very** likely to see the period from $t=1 \to T$ represented as a flattish line, with 'the action' happening from $T+1 \to 2T$. ('Quickly' unless $|\rho| \approx 1$ but still $>1$)
Comment: 2/2 @Aksakal  So: would a possible argument against ergodicity be that the rate of divergence away from $X_t=0$ is happening much faster than the rate of decrease in probability of return to values near equilibrium? Just musing.
Comment: @Aksakal: In your last sentence of the answer, as far as I know, the word you're looking for is "causal" not "invertible". Invertible is reserved for whether MA or ARMA processes can be written in terms of $X$. You can also expand the answer to include $\rho<-1$.
Answer: First we can write the model in reverse AR(1) form as:
$$X_{t} = \frac{1}{\rho} X_{t+1} - \frac{\epsilon_{t+1}}{\rho}.$$
Suppose you now define the observable values using the filter:
$$X_t = - \sum_{k=1}^\infty \frac{\epsilon_{t+k}}{\rho^k}.$$
You can confirm by substitution that both the original AR(1) form and the reversed form hold in this case.  As pointed out in an excellent answer to a related question by Michael, this means that the model is not identified unless we exclude this solution by definition.


Apache MPM workers stuck in G (gracefully finishing) growing - "scoreboard is full"

Question: Running MPM worker, Apache 2.4.46, Debian 9
Gracefully finishing workers just grows over time, they dont seem to ever finish. Eventually I run out of capacity and get "scoreboard is full" error. If I restart apache they get released.
I dont believe its anything to do with my website code (php) as many of the hanging requests are just pure image GETs, no php involved.

<IfModule mpm_worker_module>
ServerLimit 500
StartServers       10
MinSpareThreads    50
MaxSpareThreads    100
    ThreadLimit          64
    ThreadsPerChild      64
    MaxRequestWorkers     500
    MaxConnectionsPerChild   0
</IfModule>

scoreboard

example g workers

apache over week, free slots dwindling

tried with keep alive on and off
Comment: Where im at with in now is that ive realised the G stuck PID shown in apache status are not even running ?? > kill 21734 sh: 1: kill: No such process
Answer: When you use MPM worker, requests are handled by threads that exist in processes.
From https://httpd.apache.org/docs/2.4/mod/worker.html

A single control process (the parent) is responsible for launching child processes. Each child process creates a fixed number of server threads as specified in the ThreadsPerChild directive, as well as a listener thread which listens for connections and passes them to a server thread for processing when they arrive.

On Linux, a process 'contains' threads, that is one PID can have multiple threads which share memory (amongst other resources) with other threads in that PID.
As a matter of fact, Linux really only cares about 'tasks', a non-multi-threaded process is a PID with a container of one task.
When you gracefully reload Apache, you're terminating the containing process.
What is happening here is Apache is making each thread wait until all the threads in the containing process have completed prior to restarting the container PID.
So, in you're case, you've got a single thread contained in all the processes in that list that is still busy or stuck somehow.
You've got a few options.

Just give up waiting anyway and restart.
Find the problem thread (might be a bug in the application) and fix it.

1, is easy. Add the configuration option GracefulShutdownTimeout with a value that is high but not stupid. Say 900 seconds. By default this is infinite which means your threads wait forever for your problem thread to finish.
The main downside to this is you run into a chance of hitting a process in the middle of doing something critical -- which terminating might in turn corrupt a file or break the application subtley.
You also run a (vanishingly small) chance of terminating a client half-way through processing.
2, will involve you spotting the thread that is stuck in the list of workers and then diagnosing what the connection is doing, but you're bound to find what could be a design flaw and you can account for the behaviour more confidently before just blowing away a problem thread.
Comment: First thanks for your answer, some (multi tasks per pid) of what you say relates and makes sense and has given me some clues but what you say about apache gracefully restarting i dont believe is related as GracefulShutdownTimeout afaik is only related to behaviour of apache when you issue a restart. Im not issuing a restart, my problem is just happening over time, no restarts. What I investigate though is all tasks with same PID, maybe there is a PHP process within that list that is hanging.
Comment: Still happening, I looked over my PID and there is no PHP tasks in the G stuck threads... so not sure whats going on, only static image/asset requests that never get out of gracefully finishing
Comment: So I got the idea that apache server-status only shows static files, not php-fpm activity, which turned out to be the case, so i set up php-fpm status so i can see what its up to, as it seems most likely that its what is hanging, and i also set up slow log to catch it. https://gist.github.com/Jiab77/a9428050ab9bb3f17c5e33343da94fd8
Comment: So still no luck, I set up php process monitoring and the pid is not in there that is stuck in G, and i realise i didnt even need to do that as i could have just looked at the list of running processes for the stuck PID ! So it seems the pid is either not running but apache thinks it is, or its in some state which make it not show up in normal process display ???


Qual a diferença entre $(this) e $this e this?

Question: Sempre usei o $(this) independente da situação e sempre funcionou. Raras vezes que tive que usar um dos outros e nessas vezes fiz por orientação de alguém e não por saber exatamente o que eu tinha que fazer.

Então qual a diferença entre os 3 tipo de this?
Quando devo usar um e quando devo usar outro?
Muda de alguma forma a performance do código?
Comment: @Earendul eu tinha visto, mas meu inglês não é dos melhores
Comment: Aqui tem as respostas em Inglês: http://stackoverflow.com/questions/3889570/what-is-the-difference-between-this-this-and-this
Answer: Versão simples:
this - objeto simples. Elemento DOM, window ou global do Nodejs
$this - uma simples variável, pode ter qualquer valor
$(this) - objeto jQuery com métodos que o jQuery disponibiliza
Versão mais alongada:

this quando apontando um elemento

Quando usamos this dentro de por exemplo um event handler estamos a referir-nos ao elemento raw, simples, original.
Exemplo:
$('#minhadiv').click(function(){ alert(this.id)}); // dá: "minhadiv" quando clicado

this quando no escopo global

Quando usamos o this no espaço global estamos a referir-nos a window ou global se fôr em NodeJS
(function(glob){
    glob.variavelXPTO = '2014!';
})(this);
alert(variavelXPTO); // dá: 2014 - note que está no escopo global

$this é uma simples variàvel

O $this é usado como uma simples variável. Muito comum usar $this = $(this); que é uma maneira de guardar a referência ao objeto jQuery em escopos onde o this é outro, como dentro de uma chamada Ajax ou dentro de uma Classe.
var $this = 'that';
alert($this); // dá: "that" - aqui o $this guarda simplesmente uma string
var $this = $('#minhadiv');
alert($this.attr('id')); // dá: "minhadiv", ou seja retorna a id via método .attr() do jQuery

$(this) é this mas com poderes jQuery!

Para poder usar métodos jQuery em objetos tem de se passar o objeto como parâmetro da função jQuery $(). Aí a função retorna um novo objeto com os métodos que o jQuery disponibiliza. Pode usar-se em arrays, por exemplo $(['foo', 'bar']).each(minhaFn);
Exemplo usando algo do primeiro exemplo:
$('#minhadiv').click(function(){ alert(this.id)}); // dá: minhadiv
$('#minhadiv').click(function(){ alert($(this).id)}); // dá erro
$('#minhadiv').click(function(){ alert($(this).attr('id'))}); // dá: minhadiv

$('#minhadiv').click(function(){
    $(this).closest('.main'); // aqui vai procurar o elemento pai com a classe "main"
});

Para fazer o mesmo que o  $(this).closest('.main'); faz mas em JavaScript puro, ou seja usando o this tinha de ser algo como:
 var closestByClass = function(el, clz) {
    while(el && el != document) {
      var p = el.parentNode;
      var classes = ((p && p.className) || '').split(/\s+/);
      if (arrayIncludes(classes,clz)) {
        return p;
      }
      else {
        el = p;
      }
    }
    return null;
  };

Que dá mais trabalho a escrever :P
Para se retirar o elemento original de dentro de um objeto jQuery podemos usar index, ou seja var divs = $('div'); dá um objeto parecido a uma array onde divs[0] é a primeira div, raw. seria o mesmo que com o this. Pode também usar-se .get() para ir buscar o objeto raw, simples, do objeto jQuery
Comment: @Sergio muito bom :D ahh, e o ultimo exemplo expressa bem o por que eu não uso javascript pura :3
Comment: Não entendi foi nada. Acabou me trazendo mais dúvidas, pois não sei o que significa alguns termos, como `event handler`. Se incomoda em explicar a função do `this` em poucas palavras? Se o `this` simplesmente retorna o elemento puro, não é a mesma coisa de chamar tal elemento pelo nome?
Comment: @yoyo o `this` pode ser coisas diferentes em casos diferentes. Depende de muita coisa. Se tens duvidas cria uma pergunta nova que tenho gosto em responder. Procura também outras perguntas com respostas para aprenderes mais.
Comment: @yoyo se não compreendes a resposta não a desvalorizes... podes explicar melhor que parte não faz sentido?
Comment: Acredito que no fim das contas preciso de mais conhecimento geral em JS pra poder entender isso. Me falta base
Answer: $() é a função construtora do jQuery.
this é uma referência ao elemento DOM invocado.
Então, basicamente, em $(this), você está simplesmente passando this para a função $() como parâmetro, assim poderá chamar métodos e funções jQuery.
Interessante:

$(this)[0] === this
$("#myDiv")[0] === document.getElementById("myDiv")
Answer: Resposta curta
Dentro de um event handler (ex.: a função fn em $(...).click(fn)) o this se refere a um elemento do DOM. Isso significa que a maneira mais direta - e mais performática - de se atuar sobre esse elemento é chamando métodos nele próprio:
var id = this.id;
if ( (" " + this.className + " ").replace(/[\n\t]/g, " ").indexOf("minhaClasse") > -1 ) {
    var p = document.createElement("p");
    p.innerHTML = "Olá, Mundo!";
    this.appendChild(p);
}

O uso de $(this) encasula (wraps) esse elemento em um objeto jQuery, permitindo que você use as diversas funções disponibilizadas por essa biblioteca e seus plugins. É um pouco menos eficiente, porém muitas vezes bem mais conveniente:
var id = $(this).prop("id");
if ( $(this).hasClass("minhaClasse") )
    $(this).append("
Olá, Mundo!
");

Já o $this é uma variável comum, sem nada de especial. Muitas vezes convenciona-se esse nome para o objeto jQuery contendo o this, e seu principal uso é para se evitar repetir o $(this) diversas vezes (o que traz um certo overhead desnecessário):
var id = this.id;
var $this = $(this); // Poderia ser "var elefante = $(this);" tanto faz...
if ( $this.hasClass("minhaClasse") )
    $this.append("
Olá, Mundo!
");

Resposta completa
Um "objeto jQuery" é um wrapper ("envelope"?) sobre uma lista de objetos. Foi criado com a intenção de ser usado com elementos do DOM, mas a princípio pode-se encapsular qualquer coisa nele:
$([1,2,3]).each(function() { /* aqui o "this" é um elemento da lista */ });
$(); // Vazio
$(el); // Um elemento
$([el1, el2, el3]); // Vários elementos
$(strSeletor); // zero, um ou vários elementos (depende do que o seletor "pegar")

Dado um objeto jQuery, pode-se descobrir quantos elementos ele possui usando length, e acessar qualquer elemento individual usando [indice]. Ou seja, ele se comporta como se fosse um array (i.e. é um "array-like").
var $els = $([el1, el2, el3]);
$els.length; // 3
$els[1]; // el2

Quando você usa $(...).each(fn), ele chama a função fn usando cada elemento individual a ser percorrido como o contexto da função (i.e. o this). Por isso, se seu objeto jQuery possui uma lista de elementos, a cada iteração do loop o this será um elemento "cru".
E por que isso é relevante? Simples: toda função que atua num objeto jQuery - funções essas que você pode encontrar em $.fn - recebe como contexto o próprio objeto jQuery, e então decide o que fazer com ele:
$.fn.meuPlugin = function() {
    var $this = this; // Aqui this já é um objeto jQuery
};

Em geral, as funções mais comuns que conhecemos fazem das duas uma: ou obtém um valor do primeiro elemento, ou atribuem um valor a todos os elementos:
$.fn.meuPlugin = function(argumentoOpcional) {
    if ( argumentoOpcional === undefined ) { // get
        return this[0].umValor;
    }
    else { // set
        return this.each(function() { // O this aqui fora é um objeto jQuery
            this.umValor = argumentoOpcional; // O this aqui dentro é um elemento individual
        });
    }
};

$(meuSeletor).meuPlugin(); // Obtém o valor do primeiro elemento encontrado
$(meuSeletor).meuPlugin(42); // Atribui o valor 42 a todos os elementos encontrados

Por conta disso - pelo fato dos plugins fazerem uso comum de each ou map - é que as funções que passamos como argumento para esses plugins normalmente recebem o elemento cru como contexto. Essa organização permite que uma mesma função trabalhe sem distinção entre zero, um, ou vários elementos - simplificando o código para o usuário final.
Comment: @brasofilo hehe eu tive uma professora de matemática que gostava de criar parâmetros de função "elefante" pros alunos não ficarem viciados no "x" (e ela desenhava um elefantezinho no meio das fórmulas, não era simplesmente a palavra "elefante"... :P)
Comment: Também tenho [saudade da minha professora](https://www.youtube.com/watch?v=NNrJjXWblQQ) lá em Miraí, quanta travessura com JavaScript na hora do recreio :)
Comment: É, o `$this` certamente pode ser confuso para o não iniciado. A comparação do elefante merecia um ``.


Trouble accessing Apache NiFi UI behind AWS ALB

Question: I am having an issue setting up Apache NiFi behind AWS ALB. I can currently access the UI when hitting the server's public IP address directly but have been unsuccessful getting it working behind the ALB. It does work behind the ALB when HTTPS is not setup in NiFi. It fails to work when NiFi https is enabled with certificate authentication. Any help is appreciated. Thank you.
Answer: The ALB is not going to pass the client certificate to the server. If you want to use use client certificate authentication, you will have to switch to an NLB with TCP passthrough, at which point the NiFi server will be serving an SSL certificate directly to the client, and the client's certificate will be passed through the load balancer to the Nifi server.