StreamBuilder is not rebuilding on new event in stream

Question: My StreamBuilder in view:
Widget build(BuildContext context) {
    print("rebuilding..."); // as of now this gets called only on view initialization and never again - i.e. not on new events going through alarmController.stream

    return StreamBuilder(
        stream: widget.bloc.alarmController.stream,
        initialData: Alarm(''),
        builder: (BuildContext context, AsyncSnapshot<Alarm> snapshot) {
          if (!snapshot.hasData) {
            return Center(
              child: Text(StringLiterals.NO_ALARM_DATA_MSG))
            );
          }

          return Switch(
                  activeColor: Colors.red,
                  value: snapshot.data.status == 'Started',
                  onChanged: (bool _value) {
                    _newAlarmValue = _value;
                    _askAlarmConfirmation();
                  }));
        });
  }

meat of my bloc:
AlarmBloc(this.Api) {
    getAlarm();
}
  getAlarm() async {
    Alarm response = await Api.getAlarmStatus();
    alarmController.sink.add(response); // here im adding new event, therefore streambuilder should rebuild, right?
}

And lastly the code I call to initiate new event(in this case it's firebase message):
if(_message.notification.body.contains("Alarm") && IS_LOGGED_IN == true) {
   alarmBloc.getAlarm();
 }

So the problem is StreamBuilder not rebuilding whenever new event passes through alarmController.stream. What could be the reason?
Comment: Try testing by adding your print statement inside `StreamBuilder`. AFAIK it doesn't force the entire widget to rebuild.
Comment: I am ssuming that you're using rxDart so tell me something what kind of stream controller are you using? PublishSubject or BehaviorSubject?
Comment: It's BehaviourSubject @MarcosBoaventura
Answer: Your bloc needs to be a type of Stream. The same stream type as your StreamBuilder. For example your bloc needs to be a Stream<Alarm>. Otherwise stream: widget.bloc.alarmController.stream, will only be called once and won't act as an asynchronous stream of data.
Your Streambuilder needs to check for connection states
Widget build(BuildContext context) {
    print("rebuilding..."); // as of now this gets called only on view initialization and never again - i.e. not on new events going through alarmController.stream

    return StreamBuilder<Alarm>(
        stream: widget.bloc.alarmController.stream,
        initialData: Alarm(''),
        builder: (BuildContext context, AsyncSnapshot<Alarm> snapshot) {
          if (snapshot.hasError) return new Text('Error: ${snapshot.error}');
      switch (snapshot.connectionState) {
        case ConnectionState.waiting:
          return Text('Loading...');
        default:
          if (!snapshot.hasData) {
             return Center(
                child: Text(StringLiterals.NO_ALARM_DATA_MSG))
             );
          }

         return Switch(
              activeColor: Colors.red,
              value: snapshot.data.status == 'Started',
              onChanged: (bool _value) {
                _newAlarmValue = _value;
                _askAlarmConfirmation();
              }));
      }

Here are the other types of connection states you can check for:
async.dart
    enum ConnectionState {
  /// Not currently connected to any asynchronous computation.
  ///
  /// For example, a [FutureBuilder] whose [FutureBuilder.future] is null.
  none,

  /// Connected to an asynchronous computation and awaiting interaction.
  waiting,

  /// Connected to an active asynchronous computation.
  ///
  /// For example, a [Stream] that has returned at least one value, but is not
  /// yet done.
  active,

  /// Connected to a terminated asynchronous computation.
  done,
}

Comment: Unfortunately, this isn't the case. The connection is not being terminated and even with StreamBuilder type given it's still not rebuilding the widget on new event being added to sink...
Comment: Streams can be tricky. There are more options we can check out for you. We would need to reconfigure the calling stream in place of sending the 'response' back through the controller. It looks like the getAlarm is only getting call on the build and isn't streaming data back asynchronously. First can you tell me what type of response Type you are expecting from getAlarm?
Answer: The issue was I was instantiaing my BLOC incorrectly(second one) and working on a second parallel stream and therefore not the one passed to StreamBuilder.


$A\in M_{3}(\mathbb{R})$ is a matrix such that $\mbox{ Tr }(A-A^t)^{2n}=0$

Question: If $A\in M_{3}(\mathbb{R})$ is a matrix such that $\mbox{ Tr }(A-A^t)^{2n}=0$ for some integer $n>0$. Show that $A=A^t$
I have tried like this: Let $X=A-A^t$. Then $X$ is a skew symmetric matrix with all its eigenvalues are zero. This follows from the trace condition. From this how I can proceed?
Comment: Technically, $X$ doesn't have sum of all its eigenvalues zero. There is an $n>0$ such that $X^{2n}$ has sum of all its eigenvalues zero.
Comment: Tr $X$=0, this is because Tr $X$=Tr$ A$- Tr$ A^t$=0
Comment: Sorry, that was poorly worded. What I meant was that that isn't what the trace condition tells you. In _any_ skew-symmetric matrix, all diagonal entries are $0$, so the trace is $0$. It's not the given trace condition which tells you this.
Comment: Using the given trace condition we can conclude that all the eigenvalues of X=A-$A^t$ will be zero. This follows from the fact that all eigenvalues of a skew symmetric matrix are either 0 or purely imaginary. Now from the given trace condition we obtain that all eigenvalues of X is zero. from this it is enough to show that X=0. But how to show this.
Comment: I can get that $X^2 = 0$ (all complex eigenvalues being $0$ means it's nilpotent and $X^2$ being symmetric means it's diagonalizable, and there is only one nilpotent diagonalizable matrix). But I don't see yet how to get $X = 0$ from that.
Answer: Hint for the number-crunching route: Show that for $n>1$ and an arbitrary skew-symmetric matrix, we have
$$
\begin{bmatrix}
0&a&b\\-a&0&c\\-b&-c&0
\end{bmatrix}^{2n} = (-1)^n(a^2+b^2+c^2)^{n-1}\begin{bmatrix}a^2 + b^2 & bc&-ac\\bc & a^2 + c^2 & ab\\-ac&ab&b^2+c^2\end{bmatrix}
$$
Answer: $X=A-A^t$, being a $3\times 3$ skew-symmetric real matrix, have eigenvalues $0,\pm ic$ for some $c\geq 0$.  So $\operatorname{Tr} X^{2n}=2(-1)^nc^{2n}$
Answer: Let $X=A-A^t$. Note that $X$ is a skew symmetric matrix. Now $X$ being a $3\times3$ skew symmetric real matrix, its eigenvalues are $0,\pm i c$ for some $c\geq0$. Then $$\mbox{ Tr }X^{2n}=0\implies2(-1)^{n}c^{2n}=0\implies c=0$$ Hence all the eigenvalues of $X$ are zero. Now consider $$\mbox{ Tr }(XX^t)=\mbox{ Tr }(X(-X))=-\mbox{ Tr }X^2=0.$$ Consequently we have $X=0\implies A=A^t.$


Proving definition for marginal distribution function

Question: I am looking at elementary properties of joint distribution functions and I want to show that
$$F_{X, Y}(\infty, y)=\lim _{x \rightarrow \infty} F_{X,Y}(x,y)= F_{Y}(y)$$
This is the definition for the marginal distribution function. Any clues on how to prove this without recourse to the density function ?
If not, my approach would be to show, by the definition of $F_{X,Y}$ ;
$$F_{x, y}(x, y)=\int_{-\infty}^{x} \int_{-\infty}^{y} f_{X,Y}(s,t)  \,ds\, dt$$
that:
$$\lim_{x \rightarrow \infty} F_{x, y}(x, y)= \lim_{x \rightarrow \infty} \int_{-\infty}^{x} \int_{-\infty}^{y} f_{X,Y}(x,y)  \,dx \,dy$$
... $$= \int_{-\infty}^{y} \lim_{x \rightarrow \infty} \int_{-\infty}^{x}  f_{X,Y}(x,y)  \,dx \,dy = \int_{-\infty}^{y} f_{Y}(y)\,dy = F_{Y}(y)$$
Unsure though, how to swap here the $x,y$ for the placeholder variables $s,t$ without altering the definitions.
Answer: No integrals required. Instead, go back to the definition $F_{X,Y}(x,y):=P(X\le x,Y\le y)$. It's enough to prove for each fixed $y$ that
$$\lim_{n\to\infty}P(X\le x_n, Y\le y)=P(Y\le y)
$$
whenever $x_n\uparrow\infty$. To prove this,
write the LHS as $\lim P(A_n)$ where $A_n:=\left\{X\le x_n\right\}\cap \left\{Y\le y\right\}$. As $n\to\infty$, the events $A_n$ increase to the event $A:=\left\{Y\le y\right\}$, so by continuity from below
$$\lim P(A_n)=P(A).$$


Application\CAPI2 Event 513 - Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object

Question: A team member informed me that one of our Windows Server 2008 (not 2008 R2) based MSSQL Servers had begun to generate CAPI2 Event ID 513 Errors in the Application Event Log:
Application\CAPI2

Cryptographic Services failed while processing the OnIdentity() call in the System Writer Object.

Details:
AddCoreCsiFiles: BeginFileEnumeration() failed.

System Error: Access is denied.

A little PowerShell reveals that the issue started back on 08/06/14 and primarily seems to occur after 22:00 on a daily basis:
PS C:\Users\Administrator> Get-EventLog -LogName Application | ? { $_.EventID -like "513" -and $_.Source -like "Microsoft-Windows-CAPI2" } | Select -Property TimeGenerated

TimeGenerated
-------------
8/18/2014 10:41:32 AM
8/18/2014 10:25:17 AM
8/18/2014 10:15:20 AM
8/17/2014 10:55:41 PM
8/17/2014 10:55:27 PM
8/17/2014 10:55:26 PM
8/16/2014 10:49:44 PM
8/16/2014 10:49:28 PM
8/16/2014 10:49:28 PM
8/15/2014 10:52:11 PM
8/15/2014 10:51:58 PM
8/15/2014 10:51:57 PM
8/15/2014 1:03:06 AM
8/15/2014 1:02:45 AM
8/15/2014 1:02:45 AM
8/13/2014 10:58:49 PM
8/13/2014 10:58:32 PM
8/13/2014 10:58:31 PM
8/12/2014 10:57:09 PM
8/12/2014 10:56:56 PM
8/12/2014 10:56:56 PM
8/11/2014 10:56:13 PM
8/11/2014 10:55:56 PM
8/11/2014 10:55:55 PM
8/10/2014 10:50:15 PM
8/10/2014 10:50:04 PM
8/10/2014 10:50:03 PM
8/10/2014 7:12:09 AM
8/10/2014 7:11:52 AM
8/10/2014 7:11:51 AM
8/8/2014 10:57:00 PM
8/8/2014 10:56:44 PM
8/8/2014 10:56:43 PM
8/6/2014 9:47:26 PM
8/6/2014 9:47:03 PM
8/6/2014 9:47:02 PM
8/6/2014 10:48:33 AM

Curious no? I wonder what the System Writer Object is used for? Shadow Copy! Oh duh! I started doing VSS-based Application Aware backups of this virtual machine using Veeam this month. Naturally the backup process starts at 22:00 which explains the repeated frequency instead of the the error just occurring at "random" times.
Interestingly enough Veeam did not register this as a failed backup attempt which makes me wonder if the Restore Points are actually transaction consistent. Regardless, I did a quick search through the Veeam Backup Logs and did not find anything obviously wrong but it is probably worth reviewing them closer and confirming that a recovery from those Restore Points is transaction consistent.
The Event ID 513 TechNet reference recommended Resolution indicates a NTFS permission issue could be at fault, however the C:\Windows\Registration COM+ registration folder has the appropriate permissions.
Ideas?
Comment: Seems like WinSxS might be at fault here: http://support.microsoft.com/kb/2009272
Answer: Mathias R. Jessen got me pointed in the right direction, the ever famous WinSxS folder. However I did not see any of the VSS errors in the Event Log which made me a little hesitant to just nuke all the NTFS permissions lest I break something else.
Lesson 1: Read
I went back and read Event ID 513 TechNet reference  again and noted that under the Verify section it was recommended that I check to see the System Writer was available as VSS writer using vssadmin list writers and sure enough it was NOT. Lesson Learned #1: Read the whole KB/TechNet/Blog
Lesson 2: Reproduce
Doing a bit more researching I came across Missing System Writer Case Explained which seemed to indicate the issue was originating with Cryptographic Services. I found that I could reproduce by CAPI2 error at will by stopping and starting the CryptSVC service. Lesson Learned #2: Try to figure out a way to reproduce your error at will.
Using ProcMon
At this point, I pretty much followed the post's instructions. I located the PID of which instance of svchost was wrapping CryptSVC using Task Manager. You could alternatively force CryptSVC to run as its own process using sc config if you can reboot the server in question. Depending on how deep you get into ProcMon it is worth isolating services under a single PID just to cut down the amount of events you have to sort through.
From here it is back to good old ProcMon. Setup a filter to exclude all PIDs that are not the one used by the svchost process that is wrapping CryptSVC:

Lesson 3: Love ProcMon
I applied my trusty first pass filter which is to exclude all events that have the results of SUCCESS. This reduced the events from 31,118 to a much more manageable 139 and at the bottom I found the ACCESS DENIED event I was looking for, not surprisingly in the WinSxS folder (C:\Windows\winsxs\FileMaps\$$.cdf-ms). Lesson Learned #3: Learn to use and love ProcMon

Lesson 4: Verify
Now what? KB2009272 that Mathias linked has the solution but now I know why. Lesson Learned #4: Don't guess, know!
Lesson 5: Start small
The resolution is exactly as explained in KB2009272. Take ownership and reset the permissions of the FileMaps folder and then restart CryptSVC:
Takeown /f %windir%\winsxs\filemaps\* /a
icacls %windir%\winsxs\filemaps\*.* /grant "NT AUTHORITY\SYSTEM:(RX)"
icacls %windir%\winsxs\filemaps\*.* /grant "NT Service\trustedinstaller:(F)"
icacls %windir%\winsxs\filemaps\*.* /grant BUILTIN\Users:(RX)

net stop cryptsvc
net start cryptsvc

and... we have lift off! The System Writer is now available as a VSS writer.  No need to change the permissions for the PendingRename folder. Lesson Learned #5: Start with the smallest changes and work your way out to changes that effect more things.
C:\Users\administrator>vssadmin list writers
vssadmin 1.1 - Volume Shadow Copy Service administrative command-line tool
(C) Copyright 2001-2005 Microsoft Corp.

Writer name: 'System Writer'
   Writer Id: {e8132975-6f93-4464-a53e-1050253ae220}
   Writer Instance Id: {98c52075-429a-4487-8b77-e42b18767458}
   State: [1] Stable
   Last error: No error

Restarting CryptSVC at will no longer produced the CAPI2 error and after a day or two of monitoring it looks resolved.


Introduction to combinatorics

Question: Are there lecture notes on the internet (or even books) with an introduction to combinatorics using the modern language as in the book Analytic Combinatorics by  Philippe Flajolet and Robert Sedgewick or the introduction to combinatorics in the handbook of enumeration by ardila?
Comment: Does this answer your question? [Undergrad-level combinatorics texts easier than Stanley's Enumerative Combinatorics?](https://math.stackexchange.com/questions/1454339/undergrad-level-combinatorics-texts-easier-than-stanleys-enumerative-combinator)
Answer: Two online courses from Coursera, both taught by Robert Sedgewick:
Analysis of Algorithms based on the textbook An Introduction to the Analysis of Algorithms by Sedgwick and Flajolet
Analytic Combinatorics based on the book by the same title
"Analysis of Algorithms" should be viewed as a prerequisite to "Analytic Combinatorics".  I've taken both courses, and my sole criticism is that there is so much to read in "Analytic Combinatorics" that's it's almost impossible to do the readings and assigned exercises and keep on schedule.  But so what, no one is looking over your shoulder.  Highly recommended.

Introduction to combinatorics


insert a row based on column value in sql

Question: I have three tables. In table one I have id, name, and two columns. In the other table I have id, name, etc.. Similarly the third one. The values of the tables are listed below

In the above image the column nameEEE consist of same values.
Another table has a column like nameECE consist of same values.
My issue is:
I have textbox controls. When I input eee in the textbox the values should be inserted to the respective table where the column consist of eee values. This can be done using if else condition but in the case of 20 tables how to write the query
insert query is something like this:
SqlConnection con = new SqlConnection("Data Source=DESKTOP-CEUQVES;Initial Catalog=register;Integrated Security=True;Pooling=False");
con.Open();

string projid = projectidText.Text;
string videourl = videoText.Text;

string filename = Path.GetFileName(abstractFile.PostedFile.FileName);
abstractFile.SaveAs(Server.MapPath("documents/mini/" + filename));

SqlCommand cmd = new SqlCommand("insert into ece(projectid, video, abstract) values(@id, @video, @abstract)", con);
cmd.Parameters.Add("@id", SqlDbType.NVarChar).Value = projid;
cmd.Parameters.Add("@video", SqlDbType.NVarChar).Value = videourl;
cmd.Parameters.Add("@abstract", SqlDbType.NVarChar).Value = filename;

cmd.ExecuteNonQuery();
con.Close();

By using if else it can be done but the code will be huge.
Comment: Tag your question with the database you are actually using.  I removed the extraneous database tags and added sql.
Comment: Okay, but which are you using?  mysql or sql-server?  And how is .NET taking to the database?  Are you using Entity Framework?
Comment: You could generate the SQL queries dynamically on the server side based on the user entry, but you'd have serious security issues.  Dare I ask WHY you need to do this?
Comment: Mainly it is to develop a website and add table values by the admin based on the column field. @Dave
Comment: @Crazyy.Net if you want to add RDBMS specific tags, then add the proper one, not random ones or explain in the question why you have more than one product tag listed. Reverted back to Gordon's version.
Comment: I am using Microsoft SQL sever 2014
Comment: show us some of your code. Are you using c# or vb? What does your insert statement look like
Comment: Updated my question. Its c#
Answer: You can construct your SQL query like this:
string commandText = string.Format("INSERT INTO {0} (projectID{0}, video{0}, abstract{0}, values(@id, @video, @abstract)", UserEnteredTableName);
SqlCommand cmd = new SqlCommand(commandText, con);

But you shouldn't.  It leaves you critically open to SQL injection, if a user puts valid SQL into the textbox where they enter the table name.
I've done similar projects where the users create the field names and values, and I've had success mapping it like:
table CustomTables
tableID tableName
------- ---------
1       eee
2       ece

table CustomFields
FieldID tableID rowNumber fieldName fieldValue
------- ------- --------- --------- ----------
1       1       1         projectid 1
2       1       1         name      eee
3       1       1         video     ssssas
3       1       1         abs       xadads
4       1       2         projectid 2
5       1       2         name      eee
6       1       2         video     jsdksj
7       1       2         abs       jdxksk
8       1       3         projectid 4
9       1       3         name      eee
10      1       3         video     rvrge
11      1       3         abs       dtydd
12      2       1         projectid 1
13      2       1         name      ece
14      2       1         video     werwerwerw
15      2       1         abs       etertertf

(You might not need the "name" field, if all it does is store the name of the custom table, because you're storing that name in the CustomTables table)
Answer: I recommend you combine all your tables into one. So instead of this:
table EEE:
projectidEEE nameEEE videoEEE absEEE
------------ ------- -------- ------
 1            eee     blah     gorp

table ECE:
projectidECE nameECE videoECE absECE
------------ ------- -------- ------
 1            ece     blick    blork

You would add a column and combine the tables like so:
table ProjectSomething:
projectidECE SomethingId nameECE videoECE absECE
------------ ----------- ------- -------- ------
 1             1          eee     blah     gorp
 1             2          ece     blick    blork

Where SomethingId 1 is EEE and 2 is ECE, as foreign keys from a table listing each of the 20 types.
I suspect that you could drop the nameECE column if it really has the values EEE and ECE that are the same for every row in each table (it's not clear from your fake data). If the rows are different, then of course the column can stay, or be normalized if there are some duplicates but not all.


DHCP Troubleshooting

Question: I am working at a branch office and have been tasked with changing out the DHCP scope to match the overall corporate IP address scheme.  The main office assigned me an IP address range of 192.168.0.200 through 192.168.0.225.  I changed the scope on Friday afternoon and came in on Monday morning to discover that only some of the workstations had picked up new leases from the new DHCP scope.  Any ideas as to what may be happening, what I might check or adjust?
Comment: This guy hat the *exact* same question: http://www.techrepublic.com/forum/questions/101-392956/analyze-dhcp-configuration-options
Answer: Basically Time-To-Live. If you had the original scope set with a 7 day lease time, the clients will not try for a new IP until the half life of their current lease is reached (3.5days). If you had clients renew their IPs on friday before you changed the scope they may not renew again until tomorrow some time.
Edit: horrible flow & grammer

DHCP Troubleshooting


How can I block an email address in google apps?

Question: I'm using google apps for email, and my primary accound is also the catch-all email address.
Now, there are a number of email addresses that seem to attract a lot of spam - is there any way to exclude them, so that the sender gets an error?
The google spam filter picks up almost all of these, but I'm wondering if this is possible.
Answer: Catchalls in mail domains today are somewhat brave.  In addition to all the mail coming in to fake addresses, you then have the spam harvesters who can't tell a message-id from an email address, etc, and all those mails can come in too.
Honestly, it's better to use:

Aliases, set up in the accounts page, you can create lots of aliases
Variant address forms.  Gmail supports firstname.lastname@example.com addresses, and also canonicalises away dots, so that firstname.lastname@example.com == email@example.com == email@example.com
Addresses with a reasonable length left-hand-side.  Much as it pains me, as a three-letter initial sort of person, there's a reason Google don't allow such short addresses in @gmail.com; they really do receive a lot more spam from just random dictionary probes.

If you try excluding some addresses by filtering them aside then you just end up with more and more complex filters, which are a pain to keep up-to-date and if you're not careful might catch too much.
Comment: This is not an answer to the question but an completely different way of handling the situation!
Answer: It is not possible to block them like you want to, however it is possible to use the filter feature and send some e-mails directly into the trash where they'll get deleted from automatically after a few days.
Another option may be moving the catchall e-mail address to some other mailbox or removing it altogether.
Comment: Filters don't work on messages marked as spam.
Comment: Well, if they're in the spam box then you shouldn't worry about them, as they'll be deleted as time goes by.
Answer: You would have to get your users to create a filter (in settings -> filters) to delete messages as they come in from certain addresses, i would also recommend that you mark them as read so it doesnt show you as having un-read messages in your trash box
Answer: Create another user in your domain, I named mine "Spam Aliases". Give it all the aliases you consider "tainted" mailboxes. Never log in.
The only thing I am still figuring out is how to actually make the emails bounce... I was thinking about giving "Mr. Spam Aliases" a quota or disabling his Gmail app altogether but I can't find the settings  am looking for in the admin console...
Answer: I realize this is a very old question, but here's some advice for anyone else Googling this.  What I was able to do years ago within Google Apps was create a group with the name that you want to have the email bounce.  For example, if you want to have emails bounce that are addressed to firstname.lastname@example.com, create a group called "user".  Under roles and permissions of that user, set the access level to Restricted - only members can post messages".  If someone sends an email to that email address, they will receive a delivery status notification (failure) stating that the group you tried to contact (user) may not exist or you may not have permission to post messages to the group.


Add CSS class to view fields

Question: I would like to add a CSS class to fields in a view. The view in the screenshot takes the title, the summary, the date and the tags of articles that are published to the frontpage. I know how to add a class to the whole article in the GUI, but I want to add a class to fields on the article in the view.

I have made changes to existing CSS classes, but they appear on other parts of the site.
Answer: I found the answer on a video

Go to 'Edit View'
Click on the field you want to add a CSS class to
Go to the 'Style Settings'
Check 'Customize field HTML'
Check 'Create a CSS class'
Answer: What @David said.
Or, if you want to keep the customization out of the DB and put it in your theme, copy the views field template into your theme and rename it...
Find the original template in the Views module folder. Just make a copy and put it in your theme templates folder.
Then rename it...
views-view-field--my-field.tpl.php
Add your classes, then clear the theme cache.
If you ever work on larger projects, sometimes the back end folks don't want you to do anything to the DB. This approach maintains a complete separation, and nobody steps on anyone's toes.
This template suggestion would apply anywhere 'my-field' is displayed. If you need more specificity, go into the view under Advanced / Theming and look at the available template suggestions for ideas.

Add CSS class to view fields


Removing an Antecedent

Question: Suppose $ A \vdash B$
where $A$ is of the form $\forall x\  P(x) \rightarrow \ ... $
and where $B$ does not include the predicate $P$.
My intuition is that this implies that $B$ is a tautology, as in :
$ \vdash B$
But unfortunately I lack the proof-theoretic background to determine exactly why. I can think of an argument involving resolution-proofs, but that requires that the logic we're dealing with is Classical First-Order-Logic, and I was hoping that the result could be shown for a more general case.
Appreciate if anyone has any thoughts... Thanks!
Comment: Is P a constant symbol?  I imagine that is what you mean, but it is not required in all formulations of FOL.  If it is a constant, is it a defined constant, or are there potentially axioms that mention P?  If so the outcome depends on those axioms or the definition of P.
Comment: Also, is A of the form ∀ [()→ . . .] , or the form (∀())→ . . . ?
Comment: It is of the first form @CrisP
Answer: For classical logic, one can give a very short semantic proof. If $B$ is not a tautology, then it fails in some model $\mathcal{M}$. Extend that model to $\mathcal{M}_+$ by interpreting $P$ as the empty unary relation, and observe that $\mathcal{M}_+ \models \forall x. P(x) \rightarrow Q$.
The syntactic argument is somewhat more difficult. I will prove the intuitionistic case, but one can show the classical case by a similar argument.
The cut-free sequent calculus proof system LJ has the following convenient property: if $\Gamma, X \vdash \Delta$ has an LJ-proof in which every subformula of $X$ eventually disappears by weakening, then $\Gamma \vdash \Delta$ has a proof. This can be established by a simple induction on the length of the proof.
Now assume that $\forall x. P(x) \rightarrow Q \vdash B$ has an LJ-proof. We claim that in this proof no formula $P(t)$ ever occurs on the left of the turnstile. If one applies the left implication rule to something of the form $P(t) \rightarrow Q$, then $P(t)$ ends up on the right of the turnstile, and since $P(t)$ is atomic, it will not migrate back to the left. The only other way it could appear on the left is if it was a subformula of $B$, but by assumption $B$ does not mention the predicate $P$ at all. Hence, $P(t)$ never occurs on the left of the turnstile in this LJ-proof. It follows that $P(t) \rightarrow Q$ and $\forall x.P(x) \rightarrow Q$ never occur on the right (otherwise, we could use the right universal and right implication rules to make $P(t)$ appear on the left).
Since $P(t)$ cannot occur on the left, it won't appear as the active formula of any axiom $\overline{P(t) \vdash P(t)}$. Therefore, no finished branch of the proof can contain $P(t)$, so every instance of $P(t)$ must eventually (dis)appear as the active formula of weakening. The same holds for $P(t) \rightarrow Q$ and $\forall x. P(x) \rightarrow Q$, which cannot occur on the right. So in the assumed proof of $\forall x. P(x) \rightarrow Q \vdash B$, every subformula of $\forall x. P(x) \rightarrow Q$ eventually disappears by weakening. By the convenient property above, we conclude that $\vdash B$ has a proof. Therefore, $B$ is a tautology.
Comment: Thank you for this response @z-a-k . Your proof for the classical case is quite elegant! The second part of your response is a bit beyond my expertise, but makes me excited to learn more about proof theory. Have a great day! :)
Answer: We have a related result, the Craig interpolation theorem.

Assume that $\alpha$ and $\beta$ contain no common predicate symbols and that $\vdash \alpha \to \beta$.
Then:

either $\vdash \lnot \alpha$ or $\vdash \beta$.

Thus, under what condition we have that $\alpha$ is unsatisfiable,  when it has the form $\forall x Px \to C$ ?
But we can always find some interpretation where $Px$ does not hold of every objects. Thus, we can always find some interpretation where $\forall x Px \to C$ is a conditional with False antecedent, i.e. such that the formula is True.
Comment: It's so awesome that there's a straightforward proof for the intuitive notion that a universal-conditional can never be un-satisfiable. The corollary of Craig Interpolation that you bring up makes it very clear why a theory whose language is disjoint from another will conservatively-extend it as long as it is consistent. Thanks once again for your help @mauro-allegranza !!
Comment: @user1050268 - You are welcome :-)
Comment: @Mauro Your account does not seem to match up with the description in Wikipedia.  It refers to → in case   and  have "at least one atomic variable symbol in common"? And the conclusion is that an interpolant exists. Can you clarify with e.g. a reference?

Removing an Antecedent


Get dynamically created image URL in a block with paragraph and media bundle

Question: I have seen a lot of related answers to this question but nothing specific to my issue - apologies in advance if it has already been answered.
In Drupal 8, I have a custom block type that references a Paragraph type.  The Paragraph has a field that references an image media bundle.  So it looks something like this:
Block-> ReferenceFieldForParagraph-> Paragraph-> ReferenceFieldForMediaBundle-> MediaBundle-> ImageUploadField
I need to apply various image styles to that image and then get the URL for each image.

In the Paragraph's Display, I have set the field that references the media bundle to display Thumbnail: Original Image
I have created a twig template for the paragraph bundle and I am able
to generate my various images by doing the following:

The media bundle reference field is named field_slide_image:
{% block paragraph %}
  {% block content %}

    {# set the styles #}
    {% set image1 = content.field_slide_image.0|merge({'#image_style': 'style1'}) %}
    {% set image2 = content.field_slide_image.0|merge({'#image_style': 'style2'}) %}
    {% set image3 = content.field_slide_image.0|merge({'#image_style': 'style3'}) %}

    {# render images #}
    {{ image1 }}
    {{ image2 }}
    {{ image3 }}

  {% endblock %}
{% endblock paragraph %}

I cannot figure out how to get the URL.  I have tried to use file_url() but I don't see any reference to the uri when I use kint.  In other words, something like this doesn't work:
{% set image1 = content.field_slide_image.0|merge({'#image_style': 'style1'}) %}
{% set uri1 = file_url(image1.uri.value)  %}
{{ uri1 }}

I need the url's so that I can create a custom responsive image using the picture tag.  I need to generate this dynamically because I have another field (select box) that specifies the dimensions of the images (ie the image styles).  For example, option 1 is a 1x1 ratio, option 2 is a 3x4 ratio, etc.  I could easily print all images and set up media queries to hide/display them but I don't want to resort to that if I don't have to.
Here is what I see when I kint image1

Thanks in advance
Answer: I wouldn't try to hack the render array content. You might be more successful with the paragraph entity:
{% set uri = paragraph.field_slide_image.0.entity.field_image_upload.entity.uri.value %}

{% set url1 = uri|image_style('style1') %}
{% set url2 = uri|image_style('style2') %}
{% set url3 = uri|image_style('style3') %}

For the filter image_style install the module Twig Tweak.


How to COMPLETELY limit access to Views pages?

Question: I've got a content type that has attached to each of its nodes a calendar (e.g., node/123/calendar); this is generated by fullcalendar via Views.  I'm setting up node access rules on that page so that some users can see the calendar and some can't.  The node access is handled through the "Access:" field in Page Settings for the view, in what I think is the usual way (I'll admit to being something of a Views newbie).
This works, but (to my eyes) only sort of.  If a restricted user tries to get to the page, they get the same page structure, generated by a page--node--calendar.tpl file, that they'd get if they were allowed to see the page, except that the content is the "You are not authorized to access this page" message.  Thus the user is able to get some information about this restricted item, like the fact that there is a node that has a calendar attached to it.  I'd prefer to have a more empty 403 or 404 error page come back, without the node-related wrappings.
Is there any way to do this?  I suppose my page template could check the content it's about to display and see if it matches the access denied message, but that's a little more hackish than I'd like to get...
Answer: That is because Drupal, when users access a page to which they don't have access, it draws the page using its template file, and replaces its content with the error message.
What you can do is setting a page to use for the access denied page, and use a different template file for that page. In Drupal 7, that is done in admin/config/system/site-information, under Error pages.

Keep in mind that, when an access denied error is returned, the URL of the page is not changed; this means the users would still know the node has a calendar attached, if they try to access the page using the URL directly. The Calendar tab is not shown to users who don't have the permission to access it, though; they can only try using the tab URL, and see if they get an access denied error.
Comment: Good suggestion; thanks.  As a bit of clarification for future visitors to this page, a custom "access denied" page, created as above, will handle both kinds of access violations -- "you can't see this node" and "you can't see this view attached to this node that you ARE allowed to see".  I think I've said that right, anyway...


Does Phish base their improvisational style on any predetermined techniques?

Question: I have heard of the phrase "The Circle Game" used in reference to Phish and their style of improvisation and extended jams.
How does this work, and is it evident in their live performance?
Comment: The answer you provided for this question is a good one, but I agree the _question_ could use some fleshing out. The phrase "principles of improvisation" I find questionable since it seems to be avoiding critical thought about what the question actually is. I'm going to edit the question as an example of what I mean and what I'd much like to see instead.
Comment: Breaking up the question is good, but please make sure that each question is good (clearly described, with research effort) or you're unlikely to get many good answers to them. I upvoted this question because I personally would like to know the answer too, but honestly it could use some significant fleshing out. As written it sounds brusque and unhelpful.
Answer: In The Phish Book, band members explain that their improvisation was based on what they called "The Circle Game."  Band members would face each other and one band member would start a riff.  Each band member would then experiment and add to the riff until they all thought that they were locked on the riff and that the riff had been taken as far as it could.  Then the next band member would start a new riff and the process would repeat, moving around the circle.
Once you know the Circle Game, you hear it in practically every extended solo that Phish takes.  All the group solos in A Live One are based on this principle.  It's a very compact but powerful rule which enables the band to easily jam for extended periods of time but still remain fresh.
Comment: Interesting! Would be even better if you expanded the last sentence into an extended example based on one of their iconic long songs like Esther or My Friend, My Friend or Reba.


For a real number $x$, prove that for $f(x)= \frac{\tan \pi [x-\pi])}{1+[x]^2}$, $f'(x)$ exists for all $x$. [.] is GIF

Question: I don't know how to is start this. Calculation left hand and right hand derivative is cumbersome because no particular value of $x$ is given. The function doesn't appear to be continuous at integral values but according to graph it is. Can I get a hint on how to solve this?
Edit
Let the function be $f(x) = h(x).g(x)$
$h(x)$ is discontinues at $x=\pi$ and$g(x)$ is discontinuous at $1,\sqrt 2, \sqrt 3..$ etc.
Answer: $[x-\pi]$ is an integer and $\tan (n\pi)=0$ for any integer $n$. Hence $f(x)=0$ for all $x$.
Answer: The numerator is of the form $\tan(nπ)=0$ where n is an integer. Hence $f(x)=0 \forall x$ and $f'(x)=0 \forall x$ as well.

For a real number $x$, prove that for $f(x)= \frac{\tan \pi [x-\pi])}{1+[x]^2}$, $f’(x)$ exists for all $x$. [.] is GIF


Migration doesn't work when executed with cron

Question: I've set up a migration between 2 Drupal sites hosted on the same server (Drupal 8 -> Drupal 9). I'm using migration support recently added to drush to run these commands. I've created a helper bash script, which contains:
#!/bin/bash
sites=(<mysite>)
for site in "${sites[@]}"; do
  drush -r /var/www/drupal -l $site mim <migration_id> --update --execute-dependencies >> /home/<myuser>/migration.log
done

This works fine, when I execute this script manually. However, it doesn't work (content isn't migrated), when it's executed by cron, defined like this:
0,5,10,15,20,25,30,35,40,45,50,55 * * * * /home/<myuser>/<myscript>.sh >> /home/<myuser>/migration.log

There's no output in the log and no errors in /var/log/syslog, where can I only see output like this every 5 minutes:
Feb 16 15:35:01 <hostname> CRON[22314]: (<myuser>) CMD (/home/<myuser>/<myscript>.sh >> /home/<myuser>/migration.log)

What can I do to debug this issue and resolve it?
Comment: Cron doesn't source .bash_profile, which is often where the path to drush is included. As a dirty hack to test, add `PATH="/usr/local/bin:$PATH"` to the top of your user's `~/.profile` file, where `/usr/local/bin` is the path to the drush executable, and run cron (`~/.profile` is always sourced for cron in my experience)
Comment: As an aside, if you change the command to `/home//.sh >> /home//migration.log 2>&1`, you should start seeing the log output
Comment: This is not really a Drupal question. Asking how to set up, rund and debug cronjobs is better suited for StackOverflow
Comment: Drush does neither know nor care if it is run by a cronjob or manually. It is more likely your cronjob doesn't have the same environment as your manual shell (different user? different PHP version?...)
Comment: But the thing is that the cronjob itself apparently works, that's why I'm explicitly mentioning it at the end of my qustion. I believe it may be somehow related to the way drush works.
Comment: Thanks, I checked that I'm indeed running another script calling drush using the same user and the same shell (bash).
Comment: Thanks, you're right. I ended up using full path to drush. Also, this fix allowed my to see the log.
Answer: It seems that the path to drush was wrong when the script was running by cron. Lesson learned - I should be using full paths when working with cron.


Is in Drupal the way to cache whole region?

Question: I have a region which contain several blocks, each of them is changed rarely. I want to cache whole region (for each user), but i can not find the solution. Watching into the sourses gives no result too. Is anybody who knows is it possible, and how to do that? Thank you for every answer!
Comment: No you can't. Cache the blocks in the region in the Block UI
Comment: I'm guessing you actually mean in the performance admin screen (/admin/config/development/performance) rather than in the block UI screen
Comment: @LeighMason Yes. Was thinking of the way blocks can be cached in code (per user/page etc). This module [Block Cache Alter](https://www.drupal.org/project/blockcache_alter) allows configuration for that apparently.
Answer: Rather cache the individual blocks. There is a module for that: Block Cache Alter

Alter cache settings per block. Cache settings per block are now set
  in code, but if you don't like the default - usually none - you can
  now easily change this. Install this to speed up block rendering for
  authenticated users.

It will give you the optioon in the Block UI to alter the cache settings for that block:


Does ComponentDidMount not work with react hooks?

Question: I have been trying to use componentDidMount on a project but it only appears to work when the file uses classes.
Comment: You have answered your own question! Look into the [`useEffect`](https://reactjs.org/docs/hooks-effect.html) hook to achieve the same behaviour in a functional component.
Comment: There are no lifecycle hooks with functional components + hooks. Hooks are a way to synchronize side effects with state and state changes. For similar behavior, check out useEffect(), which is a general way to sync side effects with state changes, and run effects + cleanup functions https://reactjs.org/docs/hooks-effect.html
Answer: According to the React docs:

You can't use Hooks inside a class component, but you can definitely
mix classes and function components with Hooks in a single tree.

Instead of componentDidMount you can use useEffect instead, with an empty array as its dependency which will serve the same purpose of running code when the component mounts:
useEffect(() = > {
// ... code
}, [])

Answer: With hooks you can use useEffect to get same result.
This one would work like componentDidMount
useEffect(() = > {
}, [])

If you put a callback in empty array then it would work when you use that callback
Answer: The above answer:
With hooks you can use useEffect to get same result.
This one would work like componentDidMount
useEffect(() = > {
}, [])
is right except:
If you put a callback in empty array then it would work when you use that callback
that empty array is where you would list dependencies that upon change would re-run the function. The empty array turns it into run only once.


Conference call using twilio php

Question: I using @twilio/voice-react-native-sdk in Mobile App side and php for server side. My aim is first clinetA  start the call to clinetB then during the call  clinetA or clinetB wants to add people in call using phone number.  I am able to make the call between clinetA and clinetB.And also able to call phone number during call. My issue is   my code is creating two calls. First clinetA to clinetB and second clinetA to phone number.I want all these or more in one conference call. I am new in twilio and PhP.I have some idea that I am creating normal call first time and then creating  conference during the call using phone number. First time app will send the participant as string then will add participant as phone number.I am not sure how i should do here to make conference call between clinetA  to ClinetB then adding same call a phone number.
<code>if (!is_numeric($participantPhoneNumber)) participant is string clinetA to clinetB
</code>
<code>  <?php
error_reporting(E_ALL);
ini_set('display_errors', 1);
require __DIR__ . '/twilio-php-main/src/Twilio/autoload.php';

use Twilio\TwiML\VoiceResponse;
use Twilio\Rest\Client;

$accountSid = 'xxxxxxxxx';
$authToken = 'xxxxxxxxx';

$response = new VoiceResponse();
$callerNumber = '+447401120267';
$callerId = isset($_POST["callerId"]) ? $_POST["callerId"] : "";
$typeOfCall = isset($_POST["typeOfCall"]) ? $_POST["typeOfCall"] : "audio";
$minimumMinutes = isset($_POST["minimumMinutes"]) ? $_POST["minimumMinutes"] : "60";
$language = isset($_POST["language"]) ? $_POST["language"] : "Arabic";
$speciality = isset($_POST["speciality"]) ? $_POST["speciality"] : "Social Services";
$from = isset($_POST["from"]) ? $_POST["from"] : "";
$to = isset($_POST["to"]) ? $_POST["to"] : "";
$participantPhoneNumber = isset($_POST["participant"]) ? $_POST["participant"] : "";

if (!isset($to) || empty($to)) {
    $response->say('Hello');
} else {
    if (!is_numeric($participantPhoneNumber)) {
        // Initial call between clients

        $dial = $response->dial();
        $client = $dial->client($to);
        $client->identity($to);
        $client->parameter(['name' => 'typeOfCall', 'value' => $typeOfCall]);
        $client->parameter(['name' => 'minimumMinutes', 'value' => $minimumMinutes]);
        $client->parameter(['name' => 'language', 'value' => $language]);
        $client->parameter(['name' => 'speciality', 'value' => $speciality]);
    } else {
        $callSid = isset($_POST["callSid"]) ? $_POST["callSid"] : "";
        // Conference call
        $conferenceOptions = [
            'startConferenceOnEnter' => true,
            'endConferenceOnExit' => true,
        ];

        $conferenceName = $to; // Replace with a unique conference name
        $conferenceDial = $response->dial();
        $conferenceDial->conference($conferenceName, $conferenceOptions);
        // Add participant to the conference
        if (isset($participantPhoneNumber) && !empty($participantPhoneNumber)) {
            $client = new Client($accountSid, $authToken);
            try {
                $participant = $client->conferences($conferenceName)->participants->create(
                    $callerNumber,
                    $participantPhoneNumber,
                    ["beep" => false]
                );
            } catch (Twilio\Exceptions\TwilioException $e) {
                echo $e->getMessage();
            }
        }
    }
}

header('Content-Type: text/xml');
print $response;
?>

</code>
I am able to make the call between clinetA and clinetB.And also able to call phone number during call. My issue is   my code is creating two calls. First clinetA to clinetB and second clinetA to phone number.I want all these or more in one conference call.
Answer: As a starting point, I'd suggest not making a Voicecall between the first and second caller. Instead, start off with creating a Conference.
The first caller will initiate the Conference using Conference Twiml. Twilio provides this PHP code for a Simple Conference.
The second caller can either be added to the Conference using Twiml (esentially reuse the same Twiml as the first call) or using the REST Api to create a Conference Participant.

Conference call using twilio php


Problem with remote sync because of wrong UUID

Question: I have a problem with syncing my config to the remote server with Drupal 8. When I pull everything with GIT, and use drush to update the config via drush cim I get the following error:
Attempt to save a configuration entity 'field_bestand_en_' with UUID '' when this entity already exists with UUID
'b8bbd770-1533-4680-88cd-3409b0921d02&#039

So the problem is that the UUID doesn't match, the new file for some reason lost its UUID and is null now. I tried adding the given UUID by hand to the right yml file but on every new config update it gets overwritten.
So when I do drush cex locally, the UUID is null again. How can I fix this, I guess deleting the field and creating it will fix it but this is not really an option.
Thanks in advance
Answer: I was synchronizing the configuration between local environment and remote repo, and after doing the Pull and drush cr, when using drush cim, I got a similar error.
In my case, the UUID (unique identifier of Drupal element), of the configuration entity was in NULL value. Since I didn't know the origin of this, I went to the remote repository and I saw that it was pushed like this. In origin, it seems an export failure (drush cex).
I solved it by getting the number and writting the UUID (it's the same one that announces the error of drush cim by console). I edit the field configuration file and change NULL for this value of the UUID and again drush cim works again. Next, it is important to commit this change to remote (git push) so that it can be modified there, otherwise it can be lost locally after a global "pull".
Comment: Yes, the error message suggests somehow the configuration item is getting stored with an empty UUID, so that's the issue to worry about. I did a quick search to see if it's a known error but nothing turned up.
Answer: Drupal 8 configuration was designed to manage configuration on different instances of the same Drupal site. The best way to start local development is to copy the entire database from the remote site to your local site, e.g. using drush sql-sync.
If you do not wish to copy your entire live database on your local site, then you need to be sure to import your configuration at site-install time. There are two ways to do that:

Using drush site-install with the --config-dir option
Using the config installer

If you start off your local site like this, then your uuids will remain in-sync, and you will be able to export your config from the local site and re-import it on the remote site.
Comment: Hi Greg, Thanks for your reply. And sorry if I wasn't clear i have been working on this site for more then a month now with local and remote in sync. Since yesterday I have this problem out of nowhere, i didn't even change the field. So I do know how to start with a project but since I'm working on this for a while now I was wondering if there is a fix for this? Isnt it strange that The field yml doesnt have a uuid? And is it possible to change this in de database manually?
Comment: Hm, I don't have an answer for that. I've never encountered anything like that before.


Como usar sistema de posts do Jekyll para fazer app

Question: Eu estou a fazer uma app android, usando apache cordova. Eu quero saber como fazer um sistema de "posts" como no Jekyll, ele simplesmente pega em arquivos de texto e transforma-os em post. Por cada ficheiro .txt ele cria um post. Como posso fazer isso?
Por exemplo, no arquivo .txt eu tenho:
### Titulo
## Texto
# link do botão

E ele gera um post tipo este:
Answer: Montei o CSS que está abaixo. Acho que faz o que você quer. Não sei se está exatamente conforme o original porque você não postou a imagem em sua resolução original, mas seja como for, está bem próximo.
O HTML a ser preenchido é o que é representado pela
 de classe caixa. Essa
 é criada pelo jQuery na função fazCaixa usando-se um pedaço de TXT assim:

Torre de Belem###A Torre de Belém localiza-se na freguesia de Belém, concelho e distrito de Lisboa, em Portugal. Na margem direita do rio Tejo, onde existiu outrora a praia de Belém, era primitivamente cercada pelas águas em todo o seu perímetro.###Google Maps

Esse formato corresponde ao título seguido do conteúdo e depois o texto do botão, separados por ###. Não deve ser muito difícil fazer-se adaptações no formato do texto se for necessário caso algum outro formato seja desejável.
Clique no botão azul Executar lá em baixo para ver o resultado.

function fazCaixa(txt) {
    var parts = post.split("###");
    var titulo = parts[0];
    var texto = parts[1];
    var botao = parts[2];
    var esqueleto = $(""
            + "
"
            + "

"
            + "

"
            + "
"
            + "        <button></button>"
            + "
"
            + "
"
    );
    var div = $(esqueleto);
    div.find("h2").html(titulo);
    div.find("p").html(texto);
    div.find("button").html(botao);
    $(".area-externa").append(div);
}

var post = "Torre de Belem###A Torre de Belém localiza-se na freguesia de Belém, concelho e distrito de Lisboa, em Portugal. Na margem direita do rio Tejo, onde existiu outrora a praia de Belém, era primitivamente cercada pelas águas em todo o seu perímetro.###Google Maps";

fazCaixa(post);
.area-externa {
    width: 330px;
}

.caixa {
    background-color: rgb(238, 238, 238);
    padding-bottom: 10px;
    padding-top: 10px;
    padding-left: 15px;
    padding-right: 15px;
    font-family: sans-serif;
    box-shadow: 2px 2px 6px rgb(160, 160, 160), -3px 0 rgb(0, 123, 255);
    border-radius: 3px;
}

.caixa p, .caixa h2 {
    margin: 0;
    padding: 0;
}

.caixa p {
    margin-top: 15px;
    margin-bottom: 15px;
}

.caixa .bt {
    text-align: right;
}

.caixa .bt button {
    background-color: rgb(0, 123, 255);
    color: white;
    padding: 12px;
    border-style: none;
    border-radius: 5px;
}


4th Species Counterpoint in Triple Time

Question: I'm experiencing a lack of clarity on this.
Now, understanding 4th species in duple time is a matter of understanding Fux's text and seeing it in actual use.  In 4/4 for example, it is easy to see the strong beat / weak beat relationships between beats 1 and 2 and also between beats 3 and 4.  You can even see the strong/weak relationship between the first half and the last half of the measure, which is why it is justifiable to hold a suspension dissonance until beat 3 in 4/4.
I have also read that 4th species suspensions are a 3 beat action: a weak beat preparation, strong beat dissonance and finally weak beat resolution.
Yet, things aren't so cut and dry in triple time.  Fux himself applies only a few paragraphs (if that) to the topic.  Fux simply sees triple time as 2nd species with an extra beat.  A dissonance can occur, for example, in the middle beat in 3/4 time with a stepwise bass.  This makes sense and shows the relationship with 2nd species.  With some observation of triple time, it seems to me that in triple time you can have a passing tone on beat 3 moving to consonance on beat 1 of the next measure using Fux's logic of the "2nd species extension."  This also makes triple time interesting due to its variability.
Where it gets dicey is 4th species.
In the following please note that I am speaking strictly of a situation with 3 quarter notes in a bar in 3/4 time.  I do understand that you can divide each of those beats by 2 and now you have created 3 smaller strong/weak relationships.  This is not the type of action I'm referring to.
Now anyone can see that in 3/4 time, beat 1 is obviously the strongest beat.  Therefore, a beat 3 preparation, beat 1 dissonance and beat 2 resolution seems very logical.  But, if we take Fux's logic into consideration where he sees triple time as simply 2nd species with an extra beat, one would almost be inclined to believe that you can do a preparation on 2, dissonate on 3, and resolution on 1.
Yet, the aforementioned action goes against "prepare on weak, dissonate on strong, resolve on weak" literature (the final step in the aforementioned action actually resolves on a clearly strong beat.)
I'm working on a Scarlatti partimento right now in 3/4 time, and it seems to me that his approach to the problem is to prepare on 2, dissonate on 3, continue dissonance on 1, and finally resolve on beat 2 (ultimately a 4 beat action.)
Yet, I'm very interested in the experts take here.  I thank you much in advance for an answer that will help me in my understanding of music.
Answer: Fux is very clear that in a suspension, the dissonance occurs on the strong beat.

In [fourth] species, there are two half notes set against a whole note. These half notes are on one and the same tone and are connected by a tie, the first of which must occur on the upbeat, the second on the downbeat.1

The dissonant ligature [suspension] results when the half note on the upbeat is consonant (which must always be the case); the half note on the downbeat, however, is dissonant.2

This eliminates the possibility of a beat 1 resolution of a suspension.
The rules of second species do not apply to fourth species.
Second species rules are intended to teach the use of unaccented, dissonant passing tones; whereas, fourth species is solely concerned with suspensions, where the dissonance is accented.
Second species moves from consonance to consonance through an unaccented dissonance. As such, triple meter presents no problem: as long as the dissonance is on a weak beat, it doesn't matter whether the following consonance is on a strong or weak beat.
To understand Fux, look to Palestrina.
Fux's goal was to preserve the art of the "great masters", notably Palestrina. In light of this, it's worth a look at how Palestrina handled suspensions in triple meter.
Based on an examination of his four-voice triple meter compositions, it appears that Palestrina employed suspensions on every beat (that is, the dissonance can occur on any beat), but when the dissonance occurs on beat 3, the resolution is on the "&" of three, not on the following beat 1.3
Regarding Alessandro Scarlatti
Scarlatti died the same year that Fux published his Gradus ad Parnassum: 1725. But the practice described in his Partimenti is consistent with Palestrina and Fux. This would seem to reinforce the idea that Fux does not allow beat 1 resolution of a suspension.

1 Johann Fux, The Study of Counterpoint, from Johann Joseph Fux's Gradus ad Parnassum, rev. ed., translated and edited by Alfred Mann (W. W. Norton & Co., 1971), page 54 (emphasis added)
2 Ibid.
3 "Palestrina's Use of Triple Meter in Four-Voice Counterpoint", PhD dissertation, Louisiana State University, 1979. My conclusion is based on a perusal of the included scores as well as the following passage from page 132.

In the 982-1/3 measures analyzed for this portion of the study, 230 suspensions occur. Of these, twelve (5%) are on beat one, one hundred sixty-six (73%) on beat two, and fifty-two (23%) on beat three.
Comment: Thank you for your intelligent and thoughtful answer Aaron!

4th Species Counterpoint in Triple Time


Player out of bounds during fumble?

Question: I was watching football this past week and a play got to me.  Sorry I can't remember the exact game (I watched all 32 games the past two weeks) but maybe someone will be able to find it.  This question has me a little perplexed because I know the answer for high school football but not NFL.
So NFL.  Player fumbles.  Offensive player has part of his body out of bounds.
Two part question:

If defensive player is gathering the fumble but hasn't retained 100% possession is the ball considered out of bounds if the offensive player makes contact with the ball when he is touching out of bounds.
Same question but instead of touching the ball the defensive player is resting on the offensive player who is out of bounds.
Comment: I believe you are referring to the Oakland/Houston game.  There was actually a double fumble.
Comment: What part of the offensive player's body is out of bounds?  Is this body part touching the ground out of bounds, or are we talking about him standing with his feet in bounds and holding his arm over the line?
Comment: @NateEldredge - His physical body was touching the white chalk.  I was a bit taken that none of the announcers talked about but you know how that is.  I have to say this is the first football rule I have looked up in years and I couldn't find this exact scenario.
Comment: @steelerfan That was last year, not this year (it was James Jones, who's now a Packer), and didn't involve a ball going out of bounds.  (Raiders have played BAL and NYJ this year.)
Comment: The only out-of-bounds controversy I could find was [TB vs NO](http://sports.yahoo.com/video/instant-replay-fumble-recovery-bounds-202742319.html), which doesn't precisely match the above scenarios (no offensive player was near).  I do disagree with it being considered a recovered fumble, though...
Comment: @Joe my bad, I wasn't paying attention to the details of the question, I just remember that game last year and the controversy surrounding that play.  I didn't see the Tampa Bay/ New Orleans game this past weekend.
Comment: I think it was the houston/oak game.  I have NFL rewind so I can find it just might take some time.
Answer: Some rule notes that may help clear this up, from the NFL Rulebook 2015 edition.  However, it's likely that this is a highly technical issue that is hard to give a good answer to without game film.
Rule 3, section 2:

A recovery is made when a player inbounds secures possession of a loose ball after it has touched the ground.

Rule 3, section 2, article 7:

Item 2. Possession of Loose Ball. To gain possession of a loose ball that has been caught, intercepted, or recovered, a
  player must have complete control of the ball and have both feet or any other part of his body, other than his hands,
  completely on the ground inbounds, and then maintain control of the ball until he has clearly become a runner. A player
  becomes a runner when he is capable of avoiding or warding off impending contact of an opponent. If the player loses the ball
  while simultaneously touching both feet or any other part of his body to the ground, there is no possession. This rule applies in
  the field of play and in the end zone.

So we know what a player has to do to secure possession: have the ball, and both feet or hands OR one elbow/knee/etc. in bounds.  Just like a catch, and in fact there is later information that says the same - it has to continue through a trip to the ground, aka the Calvin Johnson rule, just like a pass.  This should cover your second point, in part: regardless of anything else, the ball must be possessed in bounds, so a player out of bounds would have to reestablish in bounds.  A player on top of an out of bounds player could only recover the ball if parts of him are in bounds.
Now, what about the ball being out of bounds/in bounds (ie, the first scenario)?
Rule 8, section 7 (Fumbles):

If a fumble goes backward and out of bounds, the ball is next put in play at the inbounds spot by the team that was last in possession

Note that the ball is what this is discussing, in terms of being 'out of bounds' (this is important, because there are some slight differences in what counts for ball vs. person).  (The rule about 'forward' is similar.)  So we go back to Rule 3, Section 21 to look at whether a ball is in bounds or out of bounds:

Item 2. Loose Ball. A loose ball is out of bounds when it touches a boundary line or anything that is on or outside such line,
  including a player, an official, or a pylon.

A loose ball is out of bounds when it touches a player who is out of bounds.  That means that in the first scenario, that ball instantly is out of bounds - it has touched a player out of bounds. It doesn't matter that it's the offensive player.
However, if the ball was determined to be in possession of the defensive player, the rule is different:

Item 1. Ball in Player Possession. A ball that is in player possession is out of bounds when the runner is out of bounds, or
  when the ball touches a boundary line or anything that is on or outside such line, except another player or an official.

So if the ball is not yet recovered (per 3-2-7), the touching of the offensive player is sufficient to make it out of bounds.  If the ball is recovered per 3-2-7, then touching the offensive player is irrelevant.

To specifically answer the question, if the conditions are as stated, in scenario 1 the ball is out of bounds and reverts to the team who last possessed it (regardless of side).  In scenario 2, the ball is also likely out of bounds, but not definitely (as the player is not "out of bounds" until some part of him actually touches the ground), and the defensive player could theoretically touch down in bounds.  NFL does not consider a player touching another player to be out of bounds:

ARTICLE 1. PLAYER OR OFFICIAL OUT OF BOUNDS. A player or an Official is Out of Bounds when he touches a
  boundary line, or when he touches anything that is on or outside a boundary line, except a player, an official, or a pylon.
Comment: Wow!  Detailed answer.  I am glad the question didn't involve a fumble after the two minute warning...that would have been another headache.  Horrible rule.
Comment: Very good answer.  We need to find the tape of the play to show the example.    I am pretty sure it is the game that @steelerfan suggested.  I wasn't 100% sure that the player out of bounds make contact with the ball but I was like whhhhhatttt...  Because nobody talked about the call made.  The referees ruled possession by defensive player.  Also is this rule implying that if you catch the ball with a foot on top of a foot that is out of bounds and tap your other foot down twice you are in bounds?
Comment: I think you'd have to have two different feet in bounds.  I just saw video of the game Steelerfan suggested, and that game (from 2014) didn't have the player anywhere close to out of bounds, so I doubt that is the case.
Comment: @Joe - Just two points below the knee or one above.  I don't know if this rule explains the situation of on an out of bounds player well.  I think we need to find the scenario sheet for that.

Player out of bounds during fumble?


Insertion Sort Average case giving n instead of n^2 unless in really large array sizes

Question: im having issue with the average case of insertion sort and testing/implementing it.
As far as I know its meant to be n^2, and when I did around 1 to 200000 arrays filled with random numbers I got exactly that. But now that im doing 20 points and calculating the average to ensure this I get a straight line so O(n)
However when I tried arrays of sizes 100,000, from 100,000 to 1,000,000 I get somewhat of a curved, quadratic line
public static void averageCase() {
    for (int x = 10000; x <= 30000; x += 1000) {
        int[] averageArray = randomArray(x);
        float average = 0;
        for (int i = 1; i <= 100000; i++) {
            float startTime = System.nanoTime();
            insertionSort(averageArray, averageArray.length);
            float estimateTime = System.nanoTime() - startTime;
            average += estimateTime;
        }
        System.out.println(average/100000);
    }
}

public static int[] randomArray(int n) {
    Random random = new Random();
    int[] randomArray = new int[n];
    for (int i = 0; i < randomArray.length; i++) {
        randomArray[i] = random.nextInt(1000);
    }
    return randomArray;
}

results are:
16504.586
18559.795
20468.203
22083.01
23530.045
25186.795
27179.09
28793.896
30534.533
32149.34
33869.004
35819.355
37539.02
39216.742
40978.35
42551.215
44186.992
46158.316
47584.38
49660.56
51191.48
Comment: Yes, and?  O(n^2) refers to long term behavior, it can look different for small n.
Comment: To agree with Louis, O, theta, and omega time only refer to the asymptotic bounds. Try with inputs much closer to infinity. And then rule out all possible runtime testing issues like hidden behaviors such as caching as well as anything else that makes physical computers different from theoretical ones. And then you might see results matching your expectations.
Comment: I was just making sure/confirming to be honest, I spent so much time thinking theres something wrong with my method of implementation because I already tried out and confirmed best and worst case, and wasn't sure why I couldnt get appropriate measurements.
Comment: I think the problem isn't that n isn't large enough, it's that your code isn't measuring what you think it's measuring. See my answer.
Answer: Remember O(n^2) signals your upper bound. Insertion sort has a linear lower bound. Try with larger numbers and a bunch of times.
Answer: In your inner loop, you're repeatedly sorting the same array, rather than randomizing it each time.
for (int i = 1; i <= 100000; i++) {
    float startTime = System.nanoTime();
    insertionSort(averageArray, averageArray.length);
    float estimateTime = System.nanoTime() - startTime;
    average += estimateTime;
}

Since insertion sort runs in linear time on already sorted input, you're measuring 1/100000 of a quadratic time algorithm, and 99999/100000 of a linear time algorithm.
And that's why your timings are much flatter than you expect.


Simple standard deviation question using stocks as example

Question: The following table is from page 171 of Fundamentals of Investing (11th edition) by Gitman, Joehnk, Smart. Please consider only the X, Y and XY columns (second, third, fifth).
Portfolio XY comprises assets X and Y in the proportion $2:1$. As you can see, while the average expected (here, "expected" is not used in the statistical sense, but to mean the forecast value) returns of assets X and Y have a standard deviation of $3.16$ and $6.32$ respectively, portfolio XY's expected return has a standard deviation of $0$!

Some further context: The authors are trying to illustrate the power of diversification: by replacing $\frac13$ of the original quantity of X with Y, the expected return of the portfolio is increased, while its risk (the standard deviation of the expected return) is decreased.
But how can the portfolio's risk possibly become nil !? Can someone pinpoint what is amiss?
Comment: There is no paradox. The textbook's conclusion is correct within its own framework. Zero standard derivation simply doesn't mean risk-free. In real market,  $5-\sigma$ events occur much frequently than expected. The risks associated with these events are usually unhedgeable and cannot be measured properly using "standard derivation". People sometimes use another concept "value at risk" to compensate "standard derivation". The "value at risk" is simply an estimate of the maximum potential lose within 95% level of confidence.
Comment: @achillehui Thank you! Could you post this as an Answer? Also, I was wondering if my comment below at 22:56:44 makes sense to you?
Comment: Can't see the time stamp. No idea which comment you referred to. What you said below does make sense (to a certain extent).
Answer: It's because $X$ and $Y$ are perfectly negatively correlated: $Y = 40 - 2X$. So a mix of $\frac{2X + Y}{3}$  is a constant, which is why its standard deviation is zero.
Edit:
As you mentioned, it seems paradoxical that the risk of a combination of two risky assets can be zero. This is because of the intuitive notion that $\mathrm{risk}(X+Y) = \mathrm{risk}(X)+\mathrm{risk}(Y)$. However, this is only true if $X$ and $Y$ are uncorrelated. The correct way to calculate the variance (more or less the same thing as risk) of the sum of two variables is shown here.
Comment: Yes according to the textbook, X and Y have a correlation coefficient of -1. The problem though, is, while the computation seems straightforward, it doesn't seem correct that a portfolio comprising two risky assets is risk-free. Don't you smell a paradox?
Comment: Thanks. I wasn't expecting the combined risk to be higher; I was thrown off because zero is, well, zero, not $0.00001$. But I've since figured out that (a) all the data values are approximatations, and so is the $0$ std dev, (b) the forecast is merely an extrapolation of historical data, so even if we predict a $0.000001$ std dev and a return of 13.3%, this does not preclude the possibility that I can still suffer a 90% loss. Meaning, I was forgetting that we are dealing with data here, as opposed to inevitable combinatorial-type probability logic (am I making sense?).
Comment: (a) It's true that you'll never find perfectly negatively correlated stocks in real life; and (b) with a stddev that low, a 90% loss is next to impossible, but still has probability greater than 0, which I guess is your point
Comment: BTW is there some term to distinguish data-based statistical inference and data-based probability distributions from theoretical probability distributions?
Comment: I guess the correct term for my point (b) is confidence interval. I was completely neglecting that even if the std dev is predicted to be $0$, it is still only so within a certain confidence interval.
Answer: There is no paradox. The textbook's conclusion is correct within its own framework.
Zero standard derivation simply doesn't mean risk-free. In real market, 5-$\sigma$ events occur much more frequently than expected. The risks associated with these events are usually unhedgeable and cannot be measured properly using "standard derivation". People sometimes use other tools like "value at risk" to compensate "standard derivation". The "value at risk" is simply an estimate of the maximum potential lose within 95% level of confidence.
Answer: Hint:
Let's play a game, where I flip a coin and you can bet any amount on Heads or on Tails.
 For every \$1 you bet on Heads, you get \$0.90 if it lands Heads, and lose the \$1 otherwise.
 For every \$1 you bet on Tails, you get \$0.90 if it lands Tails, and lose the \$1 otherwise.
Assume you bet \$1 on Heads and \$1 on Tails:

What is the probability of landing on Heads? What is the payoff when it lands on Heads?
What is the probability of landing on Tails? What is the payoff when it lands on Tails?
What is the payoff structure look like?
What is the variance?
What is the standard deviation?

No matter the outcome of the coin flip, you will get exactly \$0.90 each time. This is completely risk-free! You should play this game with me many many times.
Comment: @Ryan the parentheses have been removed and elaborated. Work through the example.
Comment: So the variance and standard deviation are both $0$, since the loss is constantly $20$cents. What is your point though? How can a portfolio comprised of two risky stocks have zero risk ??
Comment: @Ryan The loss is constantly \$1.10 actually. Consider the risky stocks as betting \$1 on Heads, and betting \$1 on Tails. The combined portfolio has 0 risk.
Comment: Oh yes sorry, it should be $\$1.1$. I know that the two stocks have a perfect un-correlation, hence their risk negating each other (and in this case, apparently cancelling out entirely). But is this reasonable though? I mean, you have two risky stocks. Even if the risk becomes 0.0000000000001%, there's still some risk. But to have zero risk? Oh ok, since the forecast are estimates, then the 0 std dev is consequently also an estimate; I shall accept my own such explanation for the time being.
Comment: @Ryan Think of this simple example. You place \$1000 with fund manager A, and \$1000 with fund manager B. Both of them charge you a fee of \$100 per year. A buys (and sells) some stocks. B does the exact same opposite of A at the exact same time (think of B as the counterparty to all of A's trades). What is your outcome given any set of stock prices in a year? Do you have any risk? Does it matter how risky the stocks are?
Comment: Oh hehe-which illustrates the perfectly opposite/inverse relation between X and Y. But while A and B have an actual $-1$ correlation coefficient, X and Y's $-1$ correlation coefficient can only be an estimate. So the standard deviation of $0$ is not a true nil value.
Comment: In fact, we don't even know that X and Y actually have an opposite relation. Could just be a historical fluke. One reason for my confusion was forgetting that our table is merely an extrapolation of historical data (i.e. a statistical prediction, as opposed to a theoretical-combinatorial-probabilistic prediction.) I'm probably not making *perfect* sense here, and I do apologise. p.s. Your example would be clearer without the $100 fee charged by A and B, which I think is superfluous.


How to add a checkbox for contact page in drupal?

Question: I added a checkbox in my register form in drupal name
"do you want a contact form?"
If the user checked it then in profile page a menu for contact is shown but if it says no then in the same page "Contact:Not Reachable " is shown.
Comment: I don't understand what you want to ask? You said you added a checkbox then what are you asking?
Comment: I added a checkbox in registration page and now I want to show the contact page based on the value of this checkbox, If it say yes, then contact page is shown else "Contact:Not Reachable"
Answer: You can do this with Drupal core Contact module and with small custom code. As Drupal 7 contact module provide personal contact form and site wide contact form. See here Working with the Contact Form. You can enable Personal contact form by default for each user and hide the Contact Settings under /user/[uid]/edit which will be enabled for all users. Then with custom code you can show and hide Contact form Based on the Checkbox you added.
The setting shown in below screenshot will be enabled for all users by default then you will hide this setting with custom code. Because there is no configuration to show this setting on user registration form.

Steps:

Enable Drupal core Contact module.
Then Goto admin/config/people/accounts and enable Enable the personal contact form by default for new users. setting.

Give the following permission to Authenticated Users

View user profiles
Use users' personal contact forms

Add the checkbox field in User profile and enable that on registration form. Assuming the field name is field_do_you_want_contact_form.
Then in custom module with hook_form_alter hide the personal contact form setting and show/hide the contact form based on the value of checkbox.
//custom.module
function custom_form_alter(&$form, &$form_state, $form_id){

  // Hide the personal contact form setting under /user/[uid]/edit

  if ($form_id == 'user_profile_form') {
   $form['contact']['#access'] = FALSE;
  }

 // Show the Contact form Or custom message under contact tab based on checkbox value.
  if ($form_id == 'contact_personal_form') {
    $user = $form['recipient']['#value'];
    $wrapper = entity_metadata_wrapper('user', $user);
    $do_you_want_contact_form = $wrapper->field_do_you_want_contact_form->value();

    if (!$do_you_want_contact_form) {
    // hide all the contact form element.
        $form['name']['#access'] = FALSE;
        $form['mail']['#access'] = FALSE;
        $form['to']['#access'] = FALSE;
        $form['subject']['#access'] = FALSE;
        $form['message']['#access'] = FALSE;
        $form['copy']['#access'] = FALSE;
        $form['actions']['#access'] = FALSE;

    // Add custom message
        $form['not_rechable']['#markup'] = t('Contact: not rechable');
    }
  }
}

Comment: Hello sir, Thank you for reply, as I am a novice in drupal I made a custom module and name="custom"
description="hide contact form"
core="7.x"
version="7.x-1.0"
dependencies[]="Contact"
in custom.info and this code
your code with a little change in field, but it is showing  Fatal error: __clone method called on non-object this error. Please reply
Comment: Thank you its work, There was some problem in my modules.
Comment: I am just a starter on this site, so I dont have any reputation.


Brute Force in java

Question: Okay I know how brute force works can anyone explain me how to implement it/create it in java. If possible I don't need the original source code, I just want to understand the algorithm. Can anyone please?
Comment: Brute-force isn't an algorithm. It's an approach to solving problems by guessing every possibility.
Comment: This is the equivalent of "how do I write a book?"
Answer: Brute force isn't an algorithm, it's a general problem solving technique. If i'm going to solve a problem with brute force, all it means is "I'm going to try every combination possible until I find the solution".
Here's an example. The question is "What is the sum of all numbers between 1 and n?"
Brute force solution:
int sum = 0
for i in range(n):
    sum += i
return sum

And here's a more elegant solution:
return n*(n+1)/2

"Brute force" is just a description, not an algorithm.
Comment: Okay thanks now I understand brute Force is a logic applied in terms  we don't know the  certain specifications and we try whatever possible. Thanks very helpful. But can you tell me anything about the for loop you used. I basically use this {(int i=*;i<*;i++)} or sometimes the enhanced for loop. But what is this one?
Comment: This is python, it's just quicker to write. it's the same as "for(int i = 0; i < n; i++)"

Brute Force in java


Software for managing outside inventory, users and passwords

Question: We are a small sized consulting and system integration company, and we install and partially manage (not always with remote access) different servers and workstations.
We need a centralized, and preferently multiuser, way of inventory all our servers (ok, not ours, but our clients) and the credentials.
I've been checking software around and it's:
1) overkill: things like OCS Inventory are too big, and too detailed
2) too small: rackmonkey doesnt store credentials and keepass is mono-user
3) too expensive: secret server begins at 1500$ ¡¡!!
We need just:
IP addresses, general config info on that machine (OS versions and storage capacity and so on), and credential management...
Is there something simplistic, that runs on unix/linux and is, preferently OSS?
EDIT: Seems that a lot of the 'usual' inventory softwares are based on agents (which I cannot use), and are oversized for me, I just need to manually gather basic info on each server (IP, storage, OS Version, user, password) and put it on a table, so it seems that would be better for me just composing some easy django software in some free hours...
Answer: How many machines are in use?  If you consider OCSInventory too big, this sounds like a very small environment.  Have you considered simply creating a text template for the information you want to keep so the bits are in a standard format, then simply placing the information into individual text files, one per machine, using the directory structure for classification, then putting the entire thing into a version control system (i.e. git or mercurial)?
It may sound crude, but it's very low-maintenance, retains history, and is searchable enough with grep if the total count is small.
Comment: I've been checking and OCS seems to be only agent-driven, so I cannot add manually the computers I have... This are remote servers that cannot be connected, and cannot have agents installed...
Comment: The solution to adding data easily to OCS is to use GLPI as your main inventory, and use OCS as a scanning backend, but GLPI is substantially larger both in scope and complexity than OCS.
Comment: Finally we did almost that...  I've made my own inventory solution in two afternoons with some simple database tables and django... I'll see if something better sorfaces or I'll finish adding features to my own software...
Answer: I use and swear by LastPass.  It's browser-based, so you may have an aversion to that, but it's worked wonderfully for me.
Edited to add:  Another service that you might consider is Passpack.  I used them briefly, but honestly, once I found LastPass, I quit using Passpack...
Edited to add (2):  Since you have an aversion to "hosted" solutions, you could do something like Keepass via dropbox and just backup the Keepass db occasionally.  Granted, Keepass is single user, it does warn you if you try to open it and someone else already has it open.
Comment: @Andor - You can store non browser passwords.  You can also store secured notes.  The advantage that LastPass has over xmarks is that LastPass does the encryption/decryption on your workstation.  The passwords can also be "shared" to other LastPass users without revealing what the password is.
Comment: In the case of browser passwords I use XMarks, and also, that way, I can sync passwords between my machines. I was looking soemthing for storing non-browser passwords. Thx.
Comment: LastPass also has an iPhone and Android client for when you're onsite visiting each location.
Comment: Both are out of our control, and I don't really like that much :(
Comment: I mean, are hosted solution, not owned... :P


Monitoring Apache and Postgres

Question: What tool would I need to use if I need to monitor an Apache installation and a Postgres installation?
In Apache: I'm mainly interested in the logs and the requests per second and few other simple metrics.
In Postgres: I'm looking to monitor DB load, table space sizes and few other things.
Is this where something like Nagios comes in? If I'm correct these would be pretty common things to monitor and I guess there must be tools around to do that without the need of a hodgepodge of scripts and digging through logs manually.
Thank you everyone.
Answer: For performance monitoring there are a bunch of tools, some popular Linux ones are,

nagios
munin
cacti
zabbix

Here's a nice list at Wikipedia.
None of them are trivial to setup, but they do vary in their complexity.  In the above list, I would rate them (in order of setup complexity, highest first), nagios, zabbix, cacti, munin.
Munin will certainly show you performance data for Apache and Postgres with very little effort out of the box.
For log monitoring, it depends specifically want you want out of the Apache logs, if you want web page stats, then something like webalizer is probably sufficient, but if you want to look for attempted attacks and exploits you might want LogWatch.
Answer: There is no one answer to this question.  The best answer you're likely to get is "Pick a monitoring system that is extensible, and extend it to monitor what you care about".  @EightBitTony gave you a nice list above.
As an example, I use InterMapper and monitor both Apache and Postgres using it.

We monitor Apache using their built-in HTTP & HTTPS probes, since all I really care about is that the pages are up and working.  The probes we use exercise a small portion of the web application (it attempts a login: Tests apache, PHP and connectivity to the database we auth against).

We monitor Postgres by way of a "command-line probe" (perl script) that checks number of active connections, idle connections, etc.
That could easily be extended to check on tablespace sizes and such.

Similar setups can be done for Nagios (though I'm biased against Nagios as every setup I've ever seen had decayed to total unusability), and likely for the other tools as well.  You may also find that one of the other tools does what you want "out of the box".

Note that none of this addresses "log monitoring" which you also seem to want (for apache).
Be VERY wary of log monitoring, for that way lies obsession and sleepless nights (you configure the system to report anything unusual, then one day your pager blows up because a normal event never happened when you were collecting your data).
Answer: I think that Nagios not very good solution. I propose you to use Munin for DB load and disk sizes and etc, and phplogcon for logs.
Answer: Hyperic is a pretty neat open source tool. The agent comes with autodiscovery and plugins for a lot of product, including apache and postgresql.
I use it with Oracle, I just had to give it an ojdbc driver and an account on the database and it discovered all my tablespaces and a bunch of system information on its own.

Monitoring Apache and Postgres


Acessar uma variável de um decorator

Question: fiz bastantes buscas, mas não consegui chegar onde penso que posso chegar.
Abaixo encontrei essas duas possibilidade de decorators, fiz uma pequena modificação para testes, vejam que dentro do say_whee eu quero acessar quando que está dentro do count_calls, isso é possível?
import functools

class CountCalls:
    def __init__(self, func):
        functools.update_wrapper(self, func)
        self.func = func
        self.quando = None

    def __call__(self, *args, **kwargs):
        if args[0] == "segunda":
            self.quando = "amanha"

        return self.func(*args, **kwargs)

@CountCalls
def say_whee(dia):
    print(CountCalls.quando)

say_whee("segunda")

import functools

def count_calls(func):
    @functools.wraps(func)
    def wrapper_count_calls(*args, **kwargs):
        wrapper_count_calls.quando = None

        if args[0] == "segunda":
            wrapper_count_calls.quando = "amanha"

        return func(*args, **kwargs)
    return wrapper_count_calls

@count_calls
def say_whee(dia):
    print(count_calls.quando)

say_whee("segunda")

Comment: É possível, com ressalvas importantes, mas a questão é: por que deseja usar decorador para isso?
Comment: Realmente não parece ser a melhor solução, principalmente porque o estado interno do decorador será compartilhado entre as chamadas e isso pode trazer consequências negativas, principalmente se tratando de uma validação de permissões. Se precisará usar esses valores na função, por que então não passá-las como parâmetros?
Comment: Porque esse decorator será uma verificação de permissão de acesso. E nessa verificação terão algumas vars extras para uso dentro da função que utilizou o @decorator, não sei se ficou claro.
Comment: No `say_whee` você diz?
Comment: certo, entendi, neste caso eu devo deletar a minha pergunta?
Answer: Consegui encontrar a resposta para a minha questão, mas antes de chegarmos lá fique atento. Minha necessidade era usar o decorator para validar um acesso e consumir algumas variáveis através deste decorator, conforme me orientaram, não é recomendado para tal uso.
Então, antes de usar pense muito bem para qual finalidade será usado, para que não tenha problemas
def funcDec(func):
    def wrapped(x, y):
        print(x)
        print(y)

        localVariable = "DOIS"
        # print(localVariable)
        funcDec.attrib = localVariable

        func(x, y)
        print("done with calling f1")

    return wrapped

@funcDec
def f1(x, y):
    print(x + y)
    print(funcDec.attrib)

f1(2, 3)

Acessar uma variável de um decorator


Can two teams from the same league be drawn in the same champions league group?

Question: I was sure the answer to my question is "No", but I can't seem to find any concrete resources to confirm it either way.
Is it possible for two teams from the same domestic league to be drawn to play against each other in the same group of the Champions League?
Answer: In the 2015/16 UEFA Champions League competition, two teams from the same domestic league may not be drawn to play in the same group. Furthermore, two teams from the same national association (even if they are in different domestic leagues, eg. the Premier League and the Football League Championship) also may not play in the same group.
From the Regulations of the UEFA Champions League 2015/16 (pdf), p. 22:

Article 16  Match system – group stage
16.01 Once the play-offs have been completed, the 32 remaining clubs are drawn into eight groups of four in accordance with Paragraph 13.05. Clubs from the same association cannot be drawn into the same group.
Comment: There is no mention of this being prevented in the regulations, but it is impossible, given how the places in the qualifying and play-off rounds are allocated. There are two routes through the qualifying and play-off rounds, and at present, an association may only have one team enter each route as you can see here http://www.uefa.com/uefachampionsleague/season=2016/accesslist/index.html
Comment: This is also true for UEFA Europa League Competition. See UEFA Europa League Regualtions, _Article 15, Match system - Group Stage_ [http://www.uefa.org/MultimediaFiles/Download/Regulations/uefaorg/Regulations/02/23/69/59/2236959_DOWNLOAD.pdf]
Comment: Great find thanks, as you mention play-offs, do you know if it would be possible for two teams in the same national association could play each other in the play-offs?
Answer: I'm not sure it's still possible but in the 2005/2006 Champions League group stage both Chelsea and Liverpool were in group G along with Betis Sevilla and Anderlecht.
This was possible because Liverpool lost their protection because they did not finish in a CL qualifying position in the league, but did win the CL the year before.
Comment: That's a good point, if the previous season's winner is treated as a 'non-association' special case I suppose they wouldn't be considered to be conflicting with any other team in their league/association. It would be great to find a reference that proves this to be right or wrong for current standards though
Answer: When clubs of the same league or Association arbe drawn in the same group,,they are not to play before confirmation from the Champions board of Regulations,,,
Comment: This answer need clarification and a link giving a reference to back it up, otherwise it's liable to be deleted.


Como pegar o valor do select

Question: Como faço para pegar o valor do select, dei um onChange, mas o valor não está sendo retornado como esperado.
<select
  className="form-control"
  value={area}
  onChange={e => setAddArea(e.target.value)}
>
  <option disabled selected>
    Selecione
  </option>
  {getArea.map((ar, i) => (
    <option key={i} value={ar.area}>
      {ar.area}
    </option>
  ))}
</select>;

async function handleCreate(e, area) {
  e.preventDefault();

  const response = await api.post("/pergunta", {
    area,
    pergunta
  });
  console.log(response.data);
}

const [area, setAddArea] = useState("");

Comment: Como você sabe que não está retornando o valor esperado? Esse código parece meio incompleto...
Comment: estou usando react hooks, usei o useState
Comment: Aonde está a sua chamada para o handleCreate?
Comment: Coloquei no button para quando der o click ele enviar os dados que serão recebidos pela api Adicionar
Comment: O problema está, exatamente, na forma que você está usando o `handleCreate`, já que ele está recebendo como parâmetro área, ele está escrevendo como `undefined` essa área, não?
Comment: Se o `e.target.value` não é undefined, então o problema é no seu método `setAddArea`.
Comment: @FelipeAvelar o que eu não entendo é que com o input   setAddPergunta(e.target.value)}
                placeholder="Digite a Pergunta"
                /> pode ser feito da mesma forma ele enviar o valor correto, só o select que não funciona
Comment: @PedroHenrique edita tua pergunta, colocando como tá esse teu componente. Imagino que o problema seja no `handleCreate` e não pegando o valor do select...
Comment: @FelipeAvelar Mas o handleCreate só é uma função que vou chamar ela quando o usuário de o click no botão.
Comment: @PedroHenrique você viu o exemplo online que eu coloquei [Exemplo Online](https://codesandbox.io/s/infallible-sanderson-z6y0h?fontsize=14) ? e inclusive tem na resposta ?
Comment: @PedroHenrique o exemplo local também está rodando! dê uma olhada
Answer: Pelo visto estava quase conseguindo resolver, quando você cria um variável area e o seu método de alteração setAddArea (React Hooks) você já fez aonde vai ficar o valor da seleção, e conforme muda o select no evento onChange faz a alteração (e.target.value) e após essa modificação na variável area tem o valor do select como precisa. Se no código precisar utilizar o valor da seleção é só atribuir o valor da variável area.
Um exemplo rodando em Codesandbox

function App () {
  const [selectValue, setSelectValue] = React.useState(1);
  const list = [
    {id: 1, name: 'select 1'},
    {id: 2, name: 'select 2'},
    {id: 3, name: 'select 3'},
    {id: 4, name: 'select 4'},
  ];
  return (

{selectValue}

      <select value={selectValue} onChange={e => setSelectValue(e.target.value)}>
        {list.map((item, index) => (
          <option value={item.id}>{item.name}</option>
        ))}
      </select>

  )
}

const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);

Tem um método no seu código async function handleCreate(e, area) que você tem o area como parâmetro, mas, é desnecessário é só utilizar, exemplo:
async function handleCreate(e) {
  e.preventDefault()
  const response = await api.post('/pergunta', {
      area,//<-- isso já é o suficiente
      pergunta
  })
}

Comment: @VirgilioNovic muito Obrigado
Comment: Porque recebi voto negativo? pode explicar
Comment: Até onde eu entendi, é exatamente isso que ele está fazendo e não resolve o problema dele...
Comment: @FelipeAvelar como você sabe que não é isso?
Comment: Porque o seu exemplo está praticamente igual ao da pergunta, só que ele está usando um handle, o que não é contemplado no seu exemplo...
Comment: Osh, não dei o voto negativo, vou tentar executar, mas pelo visto, é a mesma forma que fiz, só retorna undefined, mas obrigado.
Comment: @FelipeAvelar mais olha a pergunta dele e o que ele está perguntando, eu não mereço levar voto negativo!
Comment: @VirgilioNovic, eu entendo que você recebeu como pega o valor no `onChange`, mas a dúvida é relativo ao fato de ele não ter o valor esperado no `handleCreate`, não de não estar pegando o valor no `select`, até porque ele pega da mesma forma que você colocou no exemplo...
Comment: @FelipeAvelar mas, eu mereço voto negativo mediante a pergunta: **Como pegar o valor do select React** e olha como eu expliquei!
Comment: @VirgilioNovic, eu vou remover o negativo, mas você concorda que isso não resolve o problema dele?
Comment: @FelipeAvelar resolve sim, o problema dele é o que está na pergunta não o que imaginamos, você precisa entender que respondemos de acordo com a pergunta não imaginação, eu expliquei como resgata o valor do Select!
Comment: @VirgilioNovic, agora sim, com essa edição resolve o problema. (:
Answer: O problema não está em coletar o valor do select, mas no fato de você estar criando um novo escopo para a variável area, como aponto o @VirgilioNovic. Segue um exemplo de componente aplicável que resolve o seu problema:
import React, { useState } from 'react';

function Example() {
  const [selectValue, setSelectValue] = useState(1);
  const list = [
    {id: 1, name: 'select 1'},
    {id: 2, name: 'select 2'},
    {id: 3, name: 'select 3'},
    {id: 4, name: 'select 4'},
  ];

  function handleCreate(e) {
    e.preventDefault()
    alert(selectValue)
  }

  return (

{selectValue}

      <select value={selectValue} onChange={e => setSelectValue(e.target.value)}>
        {list.map((item, index) => (
          <option value={item.id}>{item.name}</option>
        ))}
      </select>
      <button onClick={handleCreate}>
        Click me
      </button>

  )
}

export default Example;

Perceba que no handleCreate foi removido a variável area dos parâmetros que ele recebe, justamente pra não criar uma variável local para a função e aproveitar a area que está associada ao state do componente.
Comment: Muito Obrigado, deu certo.

Como pegar o valor do select