How to solve the recursive complexity?

Question: I have such recursive complexity  $T(n) = T(n-2) + log(n)$. The problem is that I cant use a recursion tree or the master theorem. The only way, which I know, is to guess and then proof the answer.
Any ideas?
Answer: Opening the recursion
$$
T(n)=T(n-2)+\log(n)=T(n-4)+\log(n-2)+\log(n)=...=T(0)+\log(2)+...+\log(n-2)+\log(n)
$$
Thus
$$
T(n)=c+\sum_{i=1}^{n}\log(2i)=c+\log(\Pi_{i=1}^{n}2i)
$$
Now note that
$$
\log(\Pi_{i=1}^{n}2i)=\log(2^{n}\Pi_{i=1}^{n}i)=\log(2^{n}n!)=\log(2^{n})+\log(n!)\underbrace{=}_{\text{Using Stirling' approximation}}2\log(n)+\theta(n\log n)=\theta(n\log n)
$$
For more details see Stirling's approximation
Comment: That`s just great, to find the sum was the most difficult part))

How to solve the recursive complexity?


Let's get critical: Sep 2014 Site Self-Evaluation

Question: We all love Magento Stack Exchange, but there is a whole world of people out there who need answers to their questions and don't even know that this site exists. When they arrive from Google, what will their first impression be? Let's try to look at this site through the eyes of someone who's never seen it before, and see how we stack up against the rest of the 'Net.
The Site Self-Evaluation review queue is open and populated with 10 questions that were asked and answered in the last quarter.
Run a few Google searches to see how easy they are to find and compare the answers we have with the information available on other sites.
Rating the questions is only a part of the puzzle, though. Do you see a pattern of questions that should have been closed but are not? Questions or answers that could use an edit? Anything that's going really well? Post an answer below to share your thoughts and discuss these questions and the site's health with your fellow users!
Answer: My thoughts:

This site Does not allow discussion about 3rd party modules. Such discussions -probably- finally go to SO.
Even though Magento is popular, it has not a so-wide scope to be recognized by people to have an own site.
Drupal SE site allows discussion about 3rd party modules like Webforms. Don't see any reason why such Magento site shouldn't allow that, since there are really popular / well-known modules out there. Will not negotiate or accept any of such possible reasons since Magento is a CMS/eCommerce mainly built from modules (it's like Drupal, but with ecommerce as built-in). That makes Magento SE a highly-undesirably-strict site which is not always so pleasant to visit. That brings to play a chicken-and-egg problem: posts have not as good as expected answers in quality and/or quantity.
Comment: It's not that we don't allow 3rd party product support - it is that the ecosystem is too vast for us to have an effective answer rate on these types of questions. As the community grows I'm sure we're willing to revisit this or make exceptions for the more popular products like M2E, Magmi, etc. As for your other feedback, I'm glad to hear your thoughts and opinions - and I want to help you get the answers you're looking for - but to be quite honest you have been a member for 6 months, have asked 0 questions and have answered only 2, both of which are critical to our work here.
Comment: This site is supported by a community of enthusiasts for  users of all skill levels. We make an effort to keep this open and friendly. We have been inundated with traffic since the freeze of the Magento Forums and we are struggling to cope. At one point we were the second-highest traffic site in the SE network with a mere fraction of the user base. 75% of users on this site have < 10 karma. We fight to make this an open and honest place for people to ask questions of all types - not just dev. It'd be better for you to join us in helping answer rather than shout from the sidelines.
Comment: Wait, no :p, I double checked. I have questions done in Magento which are not deleted :p. I have 0 questions in META Magento, but 10 questions in Magento
Comment: Don't worry Luis, a new community is coming that will be entirely focused on extensions.  A place to get advice from peers, experts and even connect with developers, all in your own personal Magento sandbox of nearly any version that you can make and share within minutes.  I have to agree with Phil, Magento Stack Exchange just isn't the place for this.  Way too many questions would get totally lost.  Not to mention, it would often be very hard to get a specific question answered if everyone couldn't see the extension(s) in action.
Comment: @philwinkle in fact I deleted the few questions I did, since I misunderstood the conditions about the problems, and so the questions were not so useful to be in the KB. Magento is not the technology I use to work on, but a technology I'm forced to work on eventually. I don't have enough knowledge to be quite useful to answer here, unfortunately. I'm sorry if i sounded harsh with my answer, but I got upset when I saw questions I use to consider legitimate in SO, being closed bc they related 3rdp modules.
Comment: You're right about that I stand corrected, the point remains that what we really need is people who are going to commit to help us
Answer: Final Results

How do I create a "Spend and Save" style promotion? 10% off $99, 15% off $149, 20% off $199 with no coupon

Net Score: 13 (Excellent: 15, Satisfactory: 8, Needs Improvement: 2)

Estimating the amount of space products take up in the database

Net Score: 10 (Excellent: 12, Satisfactory: 12, Needs Improvement: 2)

Reset "Use Default Value" for specific store view on all products

Net Score: 9 (Excellent: 11, Satisfactory: 10, Needs Improvement: 2)

Debugging: Sorry, no quotes are available for this order at this time

Net Score: 9 (Excellent: 10, Satisfactory: 9, Needs Improvement: 1)

How to create a shopping cart rule - Get an certain item free if you spend over $50

Net Score: 3 (Excellent: 6, Satisfactory: 15, Needs Improvement: 3)

Benchmarking Magento performance between 2 servers

Net Score: 3 (Excellent: 5, Satisfactory: 13, Needs Improvement: 2)

SOAP V2 - Getting gift message 'To' & 'From' information from the sales order

Net Score: -1 (Excellent: 5, Satisfactory: 12, Needs Improvement: 6)

Force all products in store to have default value of "taxeable goods"

Net Score: -3 (Excellent: 4, Satisfactory: 10, Needs Improvement: 7)

One click subscription purchase with no shopping cart?

Net Score: -13 (Excellent: 1, Satisfactory: 4, Needs Improvement: 14)

How to set an image which is already on the server as product image

Net Score: -15 (Excellent: 0, Satisfactory: 7, Needs Improvement: 15)


NetSuite SuiteScript SSS_CONNECTION_CLOSED

Question: Have been getting the SSS_CONNECTION_CLOSED error on https requests within User Event Scripts and suitescript 2.0.  But only on the released versions of the deployments and not if they are in testing. Thought it may be related to tls depreciaation, our server has tls 1.0, 1.1, and 1.2 enabled.
Comment: Are you connecting to a different URL in your released script, as opposed to your testing script?
Comment: Seems to be happening on the testing versions now as well, same url. Working with netsuite support, but enpoint consistantly works in postman so not sure what the issue is.
Comment: Do you mind sharing your code?
Comment: Netsuite recommended implementing a retry mechanism, the request will still fail sometimes but then succeed after retrying once.
Comment: So I assume it doesn't fail every time then?
Answer: In my case, there were two SuiteScripts deployed for the Sales Order. However, after deleting one of them, the problem was resolved.


mysql join two table with MAX(value)

Question: I have this mysql code witch is working very well
SELECT uid , MAX(value) AS bidvalue FROM auction
WHERE pid = '$pid' and max_bid=0
GROUP BY uid
ORDER BY bidvalue DESC
LIMIT 1

How can I join this selection with users table ON users.id=auction.uid?
Thank you
Answer: I don't see any magic here:
SELECT uid, users.name, MAX(value) AS bidvalue
FROM auction
INNER JOIN users ON users.id = auction.uid
WHERE pid = '$pid' and max_bid=0
GROUP BY uid
ORDER BY bidvalue DESC
LIMIT 1

Answer: You may use join for that your query might look like
SELECT uid, users.name, MAX(value) AS bidvalue
FROM auction
INNER JOIN users ON users.id = auction.uid
WHERE pid = '$pid' and max_bid=0
GROUP BY uid
ORDER BY bidvalue DESC
LIMIT 1

or
SELECT uid, users.name, MAX(value) AS bidvalue
FROM auction
OUTER JOIN users ON users.id = auction.uid
WHERE pid = '$pid' and max_bid=0
GROUP BY uid
ORDER BY bidvalue DESC
LIMIT 1

with the joins details as per your need

mysql join two table with MAX(value)


Property [] does not exist on the Eloquent builder instance using one to many relationships with laravel

Question: I am using Laravel 7.
I have two tables: request_properties and requests. request_properties may have many requests (The FK in requests is request_properties_id).
I would like to return all the id of the table requests starting from an id of the table Request_properties using one to many relationship in the model but I receive the following error:
Property [reqs] does not exist on the Eloquent builder instance.

This is the code in my controller:
return Request_property::where('id', 71979)->reqs->id;

These are the methods in my models:
Req.php
public function request_property()
    {
        return $this->belongsTo('App\Request_property', 'id', 'request_properties_id');
    }

Request_property.php
public function reqs()
    {
        return $this->hasMany('App\Req', 'request_properties_id', 'id');
    }

Answer: use first()
Request_property::where('id', 71979)->first()->reqs()->pluck('id');

then use pluck() get all the id of reqs()


Home vidiorecording classical piano music with M-1 orchesta accompaniment at home

Question: I would like to record Rachmaninoff's 2nd piano concerto, accompanied by the Stuttgart Symphony orchestra (Music Minus One CD). The setting is our parlor in an antebellum Virginia plantation home.  The dimensions of the room are 18'wide, 24' long and 12' high.  There is a large bay window and two other windows (9'high, 4' wide), three doors, a marble fireplace and a wide-plank heart-pine floor. The living room is furnished with several sofas, easy chairs, chests, small occasional tables and an Indian carpet.  The acoustics are excellent.
The piano is located against the inner wall and will be "the star" of the show, a vintage 9' Bechstein concert grand (1896) that has undergone a meticulous 21st century restoration.  Its dramatic base register, the finest I have ever heard, will tear your heart out. This is the same model as Rachmaninoff's personal piano currently displayed in The Museum of Vano Sarajishvili, Tbilisi State Conservatoire, Georgia.
Because Bechstein pianos had to inform Rachmaninoff's Russian compositions, including Rach II, I would like to achieve the best sound reproduction possible and set our Bechstein afloat on Youtube for everyone to hear and enjoy the same reverberations that captured Rachmaninoff's imagination.
However, I am a total novice in sound recording.  To produce audio recordings for family, I have been using two pencil microphones directed respectively to the base and treble sections of the piano near its rim (lid fully opened) and a Z2 hand-held recorder.  Obviously, we are now taking a more serious turn that will demand the best possible sound engineering possible on a reasonable budget.
Here are the problems:

How do we get the best out of the Bechstein? How many speakers are needed, what kind and where to place them? I would like to keep it as simple as possible, so it will not require a mixer to manage them.
How do we best pick up the orchestra which will be playing from two stereo speakers on either side of the room?
For dialogue, will I need a separate lapel mike, or can the voice be picked up from one of the existing microphones?
What would be the best semi-pro camcorder to buy (it would need to accommodate two XRL couplings)?

Where is the best place to get recording advice?
Should I give up the idea of recording myself (which provides flexibility and ongoing use) and simply have it done professionally?
Comment: Imagine if you were an expert at sound recording and a novice at playing the piano. What would you do? Perhaps you would spend 10+ years practicing piano and then play it and record it yourself, or maybe you would find a great pianist so you could be confident of capturing a great performance. I posed that hypothetical because learning to record is just as demanding as learning to play an instrument. It's not as simple as getting some pointers online and then making a great recording. If you want it to sound its best, you'll have to find an experienced recordist to handle that part.
Comment: Gary - please read our [about] and [ask] pages to understand why this post has been put on hold. 1) opinion based questions are not a good fit here 2) hardware recommendations are off topic, generally, and 3) please just ask 1 question, not multiple ones.
Answer: If you are serious about the audio quality, IMO you most definitely need a mixer.
The Music Minus 1 CD presumably has been produced with the ambience and reverberation of the hall where it was made. Playing that back and re-recording it in a different room (especially one that may have its own acoustical problems) will most likely end up sounding like a poor quality copy of the original.
Since two plays of a CD using the same player are "guaranteed" to be perfectly synchronized, personally I would make two takes of this: one to record the video, not bothering too much about the audio quality, and a second one to record the piano only, with the performer listening to the CD through headphones. You don't need to "re-record" the CD - just rip the audio from it!
Unless the performer is indulging in a lot of rubato, there should be no serious problems syncing the audio and video streams - and you can probably "hide" any problems by using a video shot from an angle that doesn't actually show the performer's hands. That might mean you need two video cameras, of course, or you could shoot multiple takes of any problem sections.
I would attempt to get the room as acoustically "dead" as possible for the audio recording the piano, and then add reverb and equalization to match the orchestra environment as closely as possible. Cover all the walls and floor with the thickest blankets (or better, duvets and pillows) available. If the location is quiet enough, opening all the windows would be more effective than covering them the same way as the walls - glass is an excellent sound reflector!
Note: professional music recordings on location are often made in the middle of the night, to avoid "random noises" from the environment.
From the dimensions you give, the room is really too small to record a concert grand piano well, and the dimensions (exactly in the proportion of 2:3:4) are to say the least "unfortunate". Hence the strategy eliminate as much of the room ambience as possible in the recording itself, and replacing it with something that sounds better at the mixing stage.
This approach would also avoid any problems in balancing the sound level of the orchestra and piano, which is unlikely to "just work out OK" if you positions the mike(s) to record the piano sound and hope they will pick up the orchestra.
All this effort (and using equipment you don't own and don't have any experience of using) might suggest you get some professional help. Considering the cost of "doing it right", it would certainly be worth getting a quote, and advice, from a recording engineer who is used to working on location.
An alternative plan would be to move the piano to a proper recording studio rather than attempt to fix the acoustics of your room. Of course you can record the video anywhere you like, since its audio track won't be used except as a guide for syncing the other audio.
Finally, recording the "dialogue" is a completely separate issue - there is no point making things even harder by trying to capture everything "all in one take." Whether you use a lapel mike, or an "old school" huge ribbon mike (see http://www.coutant.org/bbc/ for lots of images, and technical details) on a stand with an enormous wind shield, is entirely up to you!


Dates disappear on 'Edit'

Question: We are still on Drupal 6 which has worked fine for years, and I have not done any updates.
We have Date/Time boxes on our "Events" items with pop-up boxes (see image).
But since recently the when you 'Edit' an event the dates/times go blank, but they didn't use to.
We've done nothing to alter the setup at all!
It is not only annoying, but as the 'Front Page' is set to Chronological order, if the date is blank the event disappears (past it's date presumably), so the author can't even see it to notice & correct it!
There is another question similar "when using Scheduler......"
The only answer was "it must be a bug - report it"  BUT it used to work fine, and we have not changed or updated anything (I don't know how to!)
Apart from this the site works fine!
I am not a Drupal programmer so don't ask me to update any code!
I presume it must be a 'setting' somewhere, or could it be to do with lack of memory????
one image is date/time boxes as they appear on editing, the other image is how they look when the event is first posted (or when dates re-entered)
Mike
Comment: I Posted this under Scheduler, but could it be the WYSIWYG editor playing up???
Answer: Try looking at yoursite.ca/admin/build/themes/settings.
When there, check that under "Display post information on" that your content type is checked.
After looking at this, it seems like a bug in the date module. Try updating the date module, but make sure that you have a backup of the site before doing so.
You should also soon upgrade to Drupal 7 or 8, as Drupal 6 sites risked being hacked.
Comment: That seems to be just the "submitted by Username on date text" not the Event Date.
Comment: Oh, okay. Could you post screenshot of the edit display of the date field?
Comment: Here is a screen-shot as soon as you open it to edit, the picture above is view just before edit.   ..... I can't find how to add an image here!
Comment: @MikeDavies You can't add image in comments. Please update post with the screenshot. Thank you.
Comment: Yep, found that - added to original question.
Answer: I think this issue is the likely culprit:
https://www.drupal.org/node/1808416
PHP version 5.4 and above caused some issues with the Date module in Drupal 6 that appear to match your symptoms.
The changes in the patch in comment #19 are probably what is needed.
This change should be included in the 2.10 release.
I would also recommend upgrading to Drupal 7 or 8 as soon as you can for security and longevity.
Hope this helps!
Finn

Dates disappear on 'Edit'


How to dynamic plot with data from database instead of .txt?

Question: I have a code that mimics a sensor, putting random values and timestamps on a txt file. From this file, being constantly updated, I can dynamic plot those values. Now my idea is to do the same thing, but getting data from a database. I'm already able to save whatever data comes for my server into the database. The thing now is the dynamic plot area.
My code for saving data into the table:
while True:
    data = conn.recv(2048).decode('utf-8')
    if not data:
        break
    #print('Servidor recebeu :', repr(data))
    t = dt.datetime.now().strftime('%H:%M:%S')
    c.execute('INSERT INTO edgedata VALUES (?,?)', (data, t))
    con.commit()

My code for dynamic plotting from .txt file:
#!/usr/bin/env python
import matplotlib.pyplot as plt
import matplotlib.animation as animation
import numpy as np

fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    print("inside animate")
    pullData = open("datatest.txt","r").read()
    dataArray = pullData.split('\n')
    xar = []
    yar = []

    for eachLine in dataArray:
        if len(eachLine)>1:
            x,y = eachLine.split(',')
            xar.append(str(x))
            yar.append(float(y))

    ax1.clear()
    ax1.plot(xar,yar)

    plt.xlabel('Hora')
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.ylabel('Valor Dado')
    plt.title('Pseudo-Sensor x Hora')

ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()

Any help will be appreciated. Thanks in advance!
Answer: This code did the job for me. Thanks
fig = plt.figure()
ax1 = fig.add_subplot(1,1,1)

def animate(i):
    print("inside animate")

    con = sqlite3.connect('edgedb')
    c = con.cursor()

    c.execute('SELECT data, timestamp FROM edgedata')
    data = c.fetchall()

    datas = []
    dates = []

    for row in data:
        datas.append(row[1])
        dates.append(float(row[0]))

    ax1.clear()
    ax1.plot_date(datas,dates,'-')

    plt.xlabel('Hora')
    plt.xticks(rotation=45, ha='right')
    plt.subplots_adjust(bottom=0.30)
    plt.ylabel('Valor Dado')
    plt.title('Pseudo-Sensor x Hora')

ani = animation.FuncAnimation(fig, animate, interval=1000)
plt.show()


Direct sum of Abelian groups and Isomorphism

Question: I'm currently reviewing my algebra for my last prelim and came across the following problem that has me stumped:  If $A,B,C $ are finite Abelian groups such that $A\oplus B \cong A\oplus C$ then show that $B\cong C$.  I'm not really sure where to start; the only thing that comes to mind is the fundamental theorem of finitely generated Abelian groups, I'm not sure if that's useful though.
I really only want a good hint.
Comment: The fundamental theorem is probably the way to go.  It provides a one-line solution.
Comment: @Slade: That's a pretty long line....
Comment: Suppose that $B$ and $C$ are not isomorphic, so they don't have the same list of cyclic factors when decomposed (into powers of primes). Then, can $A \oplus B$ and $A \oplus C$ have the same list of cyclic factors when decomposed as powers of primes?
Answer: We know that each of $A$, $B$, and $C$ are direct sums of cyclic groups of prime power order,
$$\begin{align*}
A &\cong C_{p_1^{a_1}}\times \cdots \times C_{p_k^{a_k}}\\
B &\cong C_{q_1^{b_1}}\times \cdots \times C_{q_{\ell}^{b_{\ell}}}\\
C &\cong C_{r_1^{c_1}}\times\cdots\times C_{r_m^{c_m}}.
\end{align*}$$
By the Structure Theorem for Finite(ly generated) Abelian groups, these decompositions are unique up to the order of the cyclic factors.
The decomposition of $A\times B$ is obtained by simply concatenating the two decompositions, as is the decomposition for $A\times C$. The fact that the two products are isomorphic means that the multisets
$$\{p_1^{a_1},p_2^{a_2},\ldots,p_k^{a_k},q_1^{b_1},\ldots,q_{\ell}^{b_{\ell}}\}$$
and
$$\{ p_1^{a_1},p_2^{a_2},\ldots,p_k^{a_k},r_1^{c_1},\ldots,r_{m}^{c_m}\}$$
are equal. Subtracting the multiset $\{p_1^{a_1},\ldots,p_k^{a_k}\}$ from both, you get that the multiset of factors for $B$, namely
$$\{ q_1^{b_1},\ldots,q_{\ell}^{b_{\ell}}\}$$
and that for $C$, namely
$$\{ r_1^{c_1},\ldots,r_m^{c_m}\}$$
are in fact identical, which again by the Structure Theorem implies that $B\cong C$.
The result holds more generally for finitely generated abelian groups, but fails once you drop that assumption. (For example, you could take $A$ a product of infinitely many copies of $\mathbb{Z}$, $B$ equal to $\mathbb{Z}$, and $C$ trivial).


Jquery find a checkbox inside a table row

Question: My html

1	895171	<INPUT type="checkbox" />

how do I use Jquery to find out whether the checkbox in this particular row is checked or not. Assume that i know the unique rowId.
Currently, I am doing this
var checkbox = $('#' + rowId + " td input:checkbox");

        if (checkbox.checked) {
           alert("checked");
        } else {
           alert("unchecked");
        }

But this doesn't seem to detect when the checkbox is checked.
EDITED
Curiously, the following didn't work either:
        var curRow = $('#' + curRowId);
        var checkbox = $(curRow).find('input:checkbox').eq(0);

        if (checkbox.checked) {
           alert("checked");

        } else {
           alert("unchecked");

        }

Answer: You can do this:
var isChecked = $("#rowId input:checkbox")[0].checked;

That uses a descendant selector for the checkbox, then gets the raw DOM element, and looks at its checked property.
References for selectors:

Selectors supported by most browsers: CSS 2.1
Newer selectors supported by some browsers and by various JavaScript libraries (for interacting with the DOM): CSS3 Selectors
Comment: @MiguelStevens: Actually, a more jQuery-ish way would use `prop`: `$("#rowId input:checkbox").prop("checked", true);`. That also has the characteristic (advantange or disadvantage, depending on your point of view) that it won't cause an error if the selector didn't find anything.
Comment: Er, and the missing reference above: [Additional selectors supported by jQuery](http://api.jquery.com/category/selectors/)
Comment: This is working! Could you provide a solution on how to set it selected if it's not? I can't seem to find it #confused
Comment: @MiguelStevens: Just assign `true` or `false` to the `checked` property.
Comment: @MiguelStevens: "Assignment" is one of the most basic programming operations. `a = b` assigns the value of `b` to `a`. So `$("#rowId input:checkbox")[0].checked = true;` assigns `true` to the `checked` property of the DOM object found via the jQuery expression.
Comment: Thanks! It's just that there's so many ways of assigning things in jQuery :) this one's working!
Answer: Updated:
var rowId = "";
var checked = $("#" + rowId + " input:checkbox")[0].checked;

Your original code does not work because you're calling checked on a jQuery result set.  You need to get out the actual DOM element, which you can do by calling get() (Or by indexing the object directly like in T.J.'s answer).  Since there's only one result, you want the element at index 0 in the result set.
Edit after seeing updated code in OP:
Using eq() reduces the matched elements to the one at the specified index.  Effectively this will return a jQuery result set with one matched object--the one you requested at the specified index.  It still doesn't return a DOM element, which you need to use the checked property.
Comment: @gnomixa: The problem is that executing a jQuery selector returns *a set of matched elements*.  Your code will not work because `checked` is not a property or function of the jQuery result set.  You need to pull out the actual DOM element returned by the selector, which you can do by directly indexing the object as shown above. `eq(0)` won't work because it retrieve's a single result in the jQuery result set--but still wrapped in a jQuery object.
Comment: @Andrew: `get(0)` is a long way 'round too. ;-)
Answer: If you only have one checkbox per row this is the quickest way
!!$('#rowId input:checked').length

You can also omit the !! and check against '>0' but I think the !! is actually faster
Answer: This would do it
var checked = $("#rowId" + rowId + " td.classID input:checkbox").is(":checked");


C# reference variable, does making one null make the other null?

Question: I have a question about how C# works.
m_MyClass = new MyClass();
Dispatcher.m_MyClass = m_MyClass;

If I set m_MyClass = null, will that automatically make Dispatcher.m_MyClass null?
Comment: Variables are storage locations. You put things inside of them. When you assign the contents of one storage location to another, you make a *copy* of the contents of the source storage location and put it in the target location. Later, you assign another value to the source storage location. It has *zero* impact on the target storage location, or *any* other storage location for that matter.
Answer: No.  The variable assignment is assigning a copy of the reference by value.  Changing the variable after the assignment will not affect the Dispatcher.m_MyClass field/property.
Answer: No. Assigning a different value to a variable of a reference has no effect on other
references.
Only modifying fields of an instance or using properties or methods which modify those fields will have an effect:
m_MyClass = new MyClass();
Dispatcher.m_MyClass = m_MyClass;

m_MyClass.MyProp = null;
// Dispatcher.m_MyClass.MyProp == null

Comment: I see. I've been studying C# lately, but didn't understand this section.


Add subquery with count, having, and orderby

Question: I just started working with Drupal 7 and I'm stuck at something I believe should be really easy (I could easily write it using plain SQL).
I have a query, rather complex (but that's not relevant) which I wanted to extend with hook_views_query_alter. What I need to achieve:
Based on base table users I need to:

Join a table node based on users.uid (many-to-one)
Then join a table node_param on node.id (one-to-one)
select count(node_param.id) WHERE node_param.value is greater than X
Order everything based on that count field

I've done research on Drupal website and stackoverflow, but couldn't find anything that would actually work, everything I've tried ended up with no results at all and I did build the query with SQL that returns results - therefore I believe my altered query gone wrong.
I will really appreciate your help here! :)
P.S. I can only modify this query using this hook!
Answer: So, from reading your question, it seems you're missing a fundamental step to data modeling with Drupal. The first thing you're going to want to do is to build out content types and fields for your data. This is done through the content types user interface. Once you have all of your data in node content types and fields, it becomes much easier to access this data in views.
When it comes to creating joins in views, you'll want to use "relationships" under "advanced" on the right hand side of the views UI. Since you're new to Drupal, but not to SQL, you might find it helpful to turn on "Show the SQL Query" here: /admin/structure/views/settings
So, the big realization here is that you don't create custom tables in Drupal databases manually. There are use cases where using a node doesn't make sense. In that case, you'll want to create a custom content entity. This is not done manually in Drupal. While creating entities can be done through code, you're better off using this module to generate your tables:
https://www.drupal.org/project/eck
Finally, most Drupal developers prefer nodes for data storage because Nodes are special entities that have many wonderful features that almost all data in Drupal needs.


Hermitian/positive definite matrices and their analogues in complex numbers

Question: I've heard a couple of times some people say that in a way, Hermitian matrices are to matrices as real numbers are to complex numbers. I know two examples where this is sort of true:
Complex conjugate vs conjugate transpose We can realize complex numbers as a set of matrices, where complex number $z = a + bi$ corresponds to a matrix $$A = \begin{bmatrix}a & -b \\ b & a\end{bmatrix}$$
Then the conjugate $\bar{z} = a - bi$ corresponds to the conjugate transpose $A^*$. A complex number is real if and only if $z = \bar{z}$. On the other hand, matrix $A$ is called Hermitian if and only if $A = A^*$.
Polar form vs polar decomposition: We can represent every complex number $z$ as $z = re^{i\varphi}$, where $r \geq 0$ and $\varphi \in [0, 2\pi[$. This representation is unique when $z \neq 0$. On the other hand, any $n \times n$ matrix $A$ with complex entries can be represented as $A = RU$ where $R$ is positive semidefinite (thus Hermitian) and $U$ is unitary. This representation is unique when $A$ is invertible. Also, if $\det A = re^{i\varphi}$, then $\det R = r$ and $\det U = e^{i\varphi}$.
Taking the second example really far, you could say positive semidefinite matrices are like nonnegative real numbers and unitary matrices are like points on the unit circle.
Are there more examples? I think this is interesting, but is thinking like this useful at all? It seems like oversimplifying things and I doubt if this leads to anything other than some fun facts.
Answer: Well, one trivial connection is that if you look at $1\times 1$ matrices (which have only a single complex entry), then you'll find that it is real iff it is Hermitian, its complex conjugate is its conjugate transpose, and its polar decomposition is the polar form.
Also, just like a complex number can be uniquely decomposed into a real and an imaginary part ($z = a+\mathrm ib$ with real $a,b$), a complex matrix can be uniquely decomposed into a Hermitian and an "anti-Hermitian" part, i.e,. $M =A + \mathrm iB$ with $A$ and $B$ Hermitian. And just like $\Re(z)=\frac12(z+\bar z)$ and $\Im(z)=\frac1{2\mathrm i}(z-\bar z)$, the Hermitian part of a matrix is $\frac12(M+M^*)$ and the "anti-Hermitian" part is $\frac1{2\mathrm i}(M-M^*)$.
Moreover, just like $\bar zz$ is a non-negative real number, $M^*M$ is a positive semidefinite matrix.
Another point: Hermitian matrices have real eigenvalues, and unitary matrices have eigenvalues of the form $\mathrm e^{\mathrm i\phi}$.
About the usefulness of the analogy:
In classical physics, observables should be real. In quantum physics, observables are represented by Hermitian matrices. Also, the quantum analogue to probability densities, which are non-negative functions with integral $1$, are density operators, which are positive semidefinite matrices with trace $1$. So there's indeed some connection.


Singular simplicial sets that are (nerves of) categories

Question: The simplicial sets that are both Kan complexes and nerves of a category are exactly the groupoids.
Simplicial sets of the form $\mathrm{Sing}_\bullet(X)$ are a proper subclass of Kan complexes.
Question: Can one characterize which simplicial sets of the form $\mathrm{Sing}_\bullet(X)$ are nerves of categories? (Either in terms of a condition on $X$ or a condition on the category $\mathcal C$, in the sense of "a simplicial set of the form $\mathrm{Sing}_\bullet(X)$ is the nerve of a category if and only if it is the nerve of a category $\mathcal C$ that satisfies $\mathrm{condition}(\mathcal C)$".)
Answer: Nerves of categories are 2-coskeletal, i.e. right orthogonal to the boundary inclusion $\partial \Delta^n \hookrightarrow \Delta^n$ for all $n > 2$.
On the other hand, the singular set of a topological set $X$ is right orthogonal to $\partial \Delta^n \hookrightarrow \Delta^n$ if and only if $X$ itself is right orthogonal to the geometric realisation of $\partial \Delta^n \hookrightarrow \Delta^n$.
This almost never happens.
The existence of many continuous endomaps of $\left| \Delta^n \right|$ that restrict to the identity on $\left| \partial \Delta^n \right|$ means you can easily manufacture more continuous maps $\left| \Delta^n \right| \to X$ with the same restriction to $\left| \partial \Delta^n \right|$ – unless the map is constant on $\left| \Delta^n \right| \setminus \left| \partial \Delta^n \right|$.
Similarly, the existence of many continuous endomaps of $\left| \Delta^2 \right|$ that restrict to the identity on $\left| \Lambda^2_1 \right|$ makes it difficult for $X$ to be right orthogonal to the geometric realisation of $\Lambda^2_1 \hookrightarrow \Delta^2$, unless every continuous map $\left| \Delta^1 \right| \to X$ is constant.
This implies every continuous map $\left| \Delta^n \right| \to X$ is constant, for all $n \ge 0$.
Therefore:
Proposition. The singular set of $X$ is (isomorphic to) the nerve of a category if and only if, for every $n \ge 0$, every continuous map $\left| \Delta^n \right| \to X$ is constant.
For example, this happens if $X$ is discrete, or more generally, totally disconnected.
Comment: Thanks! Can you also characterize this in terms of categories $\mathcal C$: for which $\mathcal C$ is $\mathrm{nerve}(\mathcal C)$ isomorphic to the singular simplicial set of some topological space?
Comment: Also, are there nondiscrete spaces for which this happens or are the discrete spaces basically all spaces for which this happens?
Comment: The only nerves that arise this way are the discrete ones. There are non-discrete topological spaces that have the property but they are indistinguishable from discrete topological spaces from the point of view of $\Delta^n$.


What is the difference between "the above theorem" and "the theorem above"?

Question: How do you use these two? What is their difference?
"the above theorem" and  "the theorem above".
In my case, I want to say something like:
Proof of the theorem above follows from lemma X and theorem Y.
Comment: Huh, the context-free-grammar tag seems weirdly appropriate here....
Comment: Um, you are asking about proper English usage?  Perhaps you should ask at an writing or language forum?  As a mathematician all I can say is they both refer to a theorem that is above on a page.  Can't see this as a mathematical question at all.
Comment: @fleablood I think this is a question of mathematical writing in particular, not general English usage. Still, it might be more suitable to migrate this question to http://english.stackexchange.com/ after all.
Comment: I see that writing a math paper might have particular grammar issues that doesn't necessarily pertain to any mathematics.  However this usage doesn't seem to pertain to solely mathematics.  I imagine an english paper ("the above argument") and any discipline ("the above result") will have the same issue.
Comment: @T.Bongers Damn, I was going to say that. You win this one.
Comment: @user360392 If your professor has issues at this level, there is something he/she is not getting at home...
Answer: In your sentence, "above" is an adjective describing the noun "theorem," therefore technically you should say: "the above theorem."
The phrase "the theorem above," is actually short for saying "the theorem that is above."
Comment: So the two expressions can be seen as grammatically correct, if I understand well.
Comment: @paf I agree with that.
Answer: My first thought is that "the theorem above" sounds much better. Wondering to myself why, I think it's because "the above theorem" is using "above" as an adjective, which it's not - it's an adverb or a preposition.
People do say "the above theorem", however - I wish they wouldn't, but they do, and since people do it's probably not worth worrying about.
Now, if you asked about the difference between "What is there difference?" and "What is their difference?" I could be more definitive - the first is simply wrong.


Is there a guitar amp simulator for windows that doesn't block other apps sounds?

Question: I have Guitar Rig 5 that am using it with the Rocksmith cable, had to install something called "ASIO" to make it work because the other one (WASAPI) doesn't work with Rocksmith usb cable.
Guitar Rig, Asio and rocksmith cable work just fine until i decide to watch a youtube tutorial or open a tab in guitar pro, and i realized that the whole computer sound is turned off.
Been searching to solve this problem for the past ~5 days, installed ASIO4ALL, AsioLink and AsioServer but i really could not make it work as there is no clear instructions to do it.
Is there a solution for this please ? a guitar rig alternative maybe that works fine with rocksmith cable ?
Thank you
Comment: Maybe this question can help: http://music.stackexchange.com/questions/20484/how-to-make-asio-work-with-multiple-programs-simultaneously-how-can-i-listen-t/
Answer: The Rocksmith audio cable forces Audio Exclusivity on the PC, this can be turned off in the PC's Audio Settings.
You'd be better off buying a dedicated USB audio interface, they can be found relatively cheaply, and will not force any kind of exclusivity as it will act as the sound card for the PC. Be aware though that some PCs introduce latency into signals with heavy processing, and might make practicing to Youtube difficult. I've had this issue in the past.
Comment: *ASIO* forces exclusivity (this is not a Rocksmith problem), and non-ASIO drivers are a primary reason for latency. However, the exclusivity is for one software package, not the whole audio subsystem so if the OP were to get a secondary device as described, then one could be used for computer audio, the other used for Guitar Simulation (using ASIO). This requires two sets of speakers or a mixer however.
Comment: I use the Rocksmith game, and it indeed does force Audio Exclusivity. I had to disable it to enable streaming of the game. If the OP got an interface, plugged the guitar into it, discarded the use of the Rocksmith cable and fired up Guitar Rig alongside a YouTube video, they'd be able to play along. Latency issues notwithstanding.
Comment: The Rocksmith game software has an exclusive mode setting. the Rocksmith cable does not. Note that the rocksmith cable is simply a USB microphone device where the mic head is replaced with a guitar pickup.


AWS ElasticCache - Cross Site - Disaster Recovery

Question: I'm using AWS ElasticCache (MemCached) and can see how instances can be created at different data centers/sites. (eg: singapore A or B)
There is no AWS Automatic Replication of ElasticCache from DataCenter to DataCenter...
Therefore is there a way to replicate cache from one site/dc to another? Thus allowing a successful Fail over of Cache...
Comment: [You don't want this.](http://code.google.com/p/memcached/wiki/NewConfiguringClient#Failure,_or_Failover)
Comment: I want to know how to do this... is it possible to replicate cache like this? ... just learning... (how to cross site replicate cache?)
Comment: Anyone... is this possible???
Answer: No, there is no way to automatically do this.
You could write a simple script in your language of choice to manually replicate keys to a different region.  I'm not really sure why you'd want to do this though?  The network latency introduced from traveling half-way around the world would negate any benefits of memcache.  You're better off replicating your persistent datastore and then having a separate memcache cluster in from of that data in each region.


Trace what Application is Going through HAproxy

Question: I have this setup where several applications are going through the load balancer (HAproxy) and accessing the MySQL database.
Several applications -> HAproxy -> MySQL database

I would like to know which specific application is accessing the database. When I did a show processlist on the database, it shows the IP of the HAproxy (of course). Then I tried to do lsof on haproxy and mysql database but it didn't help me (or I just don't know to interpret the results properly). And finally I checked the haproxy logs but it didn't show anything.
Thanks.
Comment: This would be easier if you can reconfigure applications to use separate accounts to log into MySQL.
Answer: I was also looking for a way to trace haproxy connections back to specific processes on various machines.  This dinky little hackery looks on the haproxy machine for a host that you give it.  It then goes over to the source machine and looks for the connections through to the backend databases.
The most basic part is running the echo 'show sess' | socat stdio unix-connect:/tmp/haproxy on the haproxy server itself
#!/bin/bash
# comments here:

haproxy='<your haproxy target>'

if [ $# -ne 1 ]
then
echo ""
echo "usage: db_trace_haproxy_sessions.sh <hostname>"
echo "looks at connections from <hostname> to load balanced database and traces them back to processes"
echo ""
exit
fi

ip=`host $1 | awk '{print $4}' 2>/dev/null`
if [ "$ip" == "found:" ]
then
echo ""
echo "couldn't resolve $1"
echo ""
exit
fi

IFS="
"

for i in `ssh $haproxy "echo 'show sess' | socat stdio unix-connect:/tmp/haproxy | grep     $ip"`
do
# output example:
#0x2cd2780: proto=tcpv4 src=10.210.50.104:50791 fe=mysql be=mysql srv=db302 ts=04 age=1d11m calls=5 rq[f=909202h,l=0,an=00h,rx=7h59m,wx=,ax=] rp[f=109202h,l=0,an=00h,rx=7h59m,wx=,ax=] s0=[7,18h,fd=32,ex=] s1=[7,18h,fd=52,ex=] exp=7h47m

echo ""
db=`echo $i | awk '{print \$6}' | cut -d "=" -f2`
src=`echo $i | awk '{print \$3}' | cut -d "=" -f2`

echo "Source Connection: $src ... connected to $db"

ssh $1 "ps=\`netstat -naltp | grep $src | awk '{print \$7}' | cut -d "/" -f1\`; ps aux |     grep \" \$ps \" | grep -v grep"
done;
echo ""

Output looks like this:
db_trace_haproxy_sessions.sh appserver

Source Connection: 10.210.50.103:37114 ... connected to database319

root     19300  1.0  0.0  53944 16180 pts/0    S+   Feb19  16:02 /usr/bin/perl somePerlScript.pl

Source Connection: 10.210.50.103:37115 ... connected to database142

root     19301  5.4  0.0  53940 16160 pts/1    D+   Feb19  81:41 someapachethread


Verificar se email está cadastrado no BD

Question: Estou fazendo uma busca em meu BD para verificar a existência de e-mail, evitando o cadastro do mesmo novamente, mas estou com problema no retorno, o script abaixo envia e trata o retorno.
 if (sender.getFieldName() == 'Email') {
 if (sender.getValue()) {

     var emailExist = false;

     $.ajax({
         type: 'GET',
         url: 'AjaxBasedValidation.php',
         data: {
             checkEmail: sender.getValue()
         },
         async: false,
         dataType: 'json',
         success: function(dataResult) {
             emailExist = dataResult;
         }
     });

     editors['Email']
         .setState(emailExist ? 'warning' : 'success')
         .setHint(emailExist ? 'E-mail ' + sender.getValue() + ' já está cadastrado' : null);
 } else {
     editors['Email']
         .setState('normal')
         .setHint(null);
 }

}
O código que verifica no BD:

    #Recebe o Email Postado
    $emailPostado = $_GET['checkEmail'];

    #Conecta banco de dados
    $con = mysqli_connect(".", "", "", "");
    $sql = mysqli_query($con, "SELECT * FROM `usuarios` WHERE `Email` = '{$emailPostado}'") or print mysql_error();

    if($rcQuery == true){
        die('{"dataResult" : 0"}');
    } else {
        die('{"dataResult" : 1"}');
    }

Todos os e-mails que informo o script está acusando que já estão cadastrados.
Answer: Conte o número de linhas retornadas pela consulta com mysqli_num_rows(). Veja que no if a comparação é feita com uma variável que não existe no código da pergunta $rcQuery
$result = mysqli_query($con, "SELECT * FROM `usuarios` WHERE `Email` = '{$emailPostado}'");
$retorno['dataResult'] = ($result) ? mysqli_num_rows($result) : 0;
echo json_encode($retorno);

Comment: Olá @rray, eu editei a pergunta depois da sua resposta, obrigado pela dica,  vou testar.
Comment: @adventistapr lembre de converter o retorno do ajax em json, `var retorno = JSON.parse(dataResult)`, depois pode usar.  `console.log(retorno.dataRresult);`
Comment: Olá @rray, poderia me dar um exemplo de como  converter o retorno do ajax em json? Fiz do modo que me passou, mas não sei se fiz certo. Agradeço.
Comment: @adventistapr o que aconteceu:? deu erro?
Comment: Olá @rray, ainda continua acusando que todos e-mail já estão cadastrados
Comment: @adventistapr no javascript se vc fizer `console.log(dataResult);` mostra o que?
Comment: Olá @rray, valeu pela ajuda, refiz a busca e debuguei o script, agora está tudo correto.
Estava errando no retorno do php, valeu pelas dicas.
Comment: @adventistapr tranquilo ;) q bom q acertou o código
Answer: Sei que essa pergunta já foi respondida, mas gostaria de deixar uma solução mais segura no caso de instruções sql voltadas para consultas de strings:
No caso do seu select ficaria mais seguro executar as consultas de emails da seguinte maneira:
$result = mysqli_query($con, "SELECT * FROM `usuarios` WHERE `Email` LIKE \"%".$emailPostado."%\"");

Outra coisa, procure estudar sobre a classe PDO, pois estas funções do php mysql_* e mysqli_* estão obsoletas e já não existem mais a partir da versão 7 do php.
Comment: Grande dica @Rafael Andrade, muito obrigado.
Comment: Obrigado @adventistapr, prazer em ajudá-lo!


Relating the pairwise determinants of $n$ elements of $\mathbb{Z}^2$

Question: A similar question may have already been answered somewhere, but I have not been able to find it.
Let $v_1,\dots,v_n$ be elements of $\mathbb{Z}^2$, with $v_i=\begin{pmatrix} a_i \\ b_i \end{pmatrix}$ for all $i$. For all $i<j$, define $n_{ij}:=\operatorname{det}(v_i,v_j)=a_ib_j-a_jb_i$. Which $\binom{n}{2}$-tuples of integers can be equal to $\{n_{ij}\}_{i<j}$ for some collection of vectors $v_1,\dots,v_n$?
Edit: the question is not clear. What I mean is: given $v_1,\dots,v_n \in \mathbb{Z}^2$, set $N(v_1,\dots,v_n):=\{n_{ij}\}_{i<j}$, in the same notations as before. For which $\binom{n}{2}$-tuples of integers $S$ there exist $w_1,\dots,w_n \in \mathbb{Z}^2$ such that $N(w_1,\dots,w_n)=S$?
As Jean Marie points out, this is equivalent to the following question. Which $n \times n$ skew symmetric, integer matrices $N$ of rank two can be written as $N=AB^T-BA^T$, for column vectors $A,B \in \mathbb{Z}^n$?
Comment: It might be simpler to regard $n_{ij}$ as an antisymmetric matrix and remove the requirement that $i<j$.
Answer: As the text of your question has been modified, my previous answer (A1) has become obsolete. But I just added an Edit (A2), which is only a very partial solution.

Here was my previous answer (A1) :

Your issue can be re-written in the following way: if a $n \times n$ matrix $N$ can be written in the form $AB^T-BA^T$ (therefore is a rank-2 skew symmetric matrix), where $A,B$ are $n \times 1$ column vectors, can other solutions $N=A'B'^T-B'A'^T$ exist ?
The answer is yes in the case of real coefficients : just take
$$A'=uA, \ \ B'=vB \ \ \text{with} \ \ uv=1$$
(which amounts to a shrinkage on the $a_i$ and an extension of the $b_j$ (or the contrary).
In the integer case, in order to have a non trivial solution (set apart solution $u=v=-1$), it is necessary that the $a_i$ or the $b_i$ have a GCD (Greatest Common Divisor) $>1$.
Edit : (A2) : a "pseudo-answer" :
As the rank of your matrix $N$ is two and that the non-zero eigenvalues of an antisymmetric matrix are known to come in conjugate pairs, $\pm ia$, the singular values of $N$ are :
$$-a^2,-a^2,0,0...$$
Therefore, the SVD (Singular Value Decomposition) of $N$ can be written :
$$N=-a^2 UV^T -a^2U'V'^T\tag{1}$$
Where $U,U'$ are the left (resp. $V,V'$ the right) singular vectors of $N$.
(1) can be written, by incorporating the $a^2$ factors into vectors :
$$N=UV^T-U'V'^T$$
But I am unable at present to establish that necessarily, $U'=V$ and $V'=U$, not to speak of the possibility that their entries can be integers.
Comment: Thank you for your answer. I should have phrased my question better. What I meant, in your notation, is the following: how can you characterize all skew symmetric, integer matrices $N$ of rank two admitting a decomposition of the form $N=AB^T-BA^T$?
I will edit the question to explain better what I meant.
Comment: This is a nice post, but 1) as the OP already mentioned, the question was a bit different, and 2) "I don't think a solution exists" is hardly an answer, and should probably be a comment.
Comment: @lisyarus 1) The question has been slightly modified since I wrote this answer 2)  You are right : I erase this last sentence.
Answer: Solution with a sketch of a proof:
The problem ( and its generalization) consists of two parts:

What can be said about the $k\times k$ minors of $k \times n$ minors of a matrix with coefficient in some field?

The answer is given by the Plucker relations

Let $R$ be a domain, $k$ its field of fractions. Assume that we have a $k\times n$ matrix with elements in $k$ such that all its $k\times k$ minors are in $R$.  Does there exist another $k\times n$ matrix with elements in $R$ with the same $k\times k$ minors?

The answer is Yes if $R$ is a PID. For this, use the Smith normal form.

This part seems tricky so I am adding more details. The statement is this: given a matrix $M$ of size $k \times n$ with rational entries and all of the $k\times k$ minors integers, there exists a matrix $M'$ of size $k\times n$, with integer entries, and same corresponding $k\times k$ minors.
Indeed, consider the Smith normal form of $M$
$$M = S \cdot D \cdot T$$
where $S \in SL(k, \mathbb{Z})$, $D = \operatorname{diag}(d_1, \ldots, d_k)$, and $T \in SL(n, \mathbb{Z})$, with $\det D = d_1 \cdots d_k$ equals the $\operatorname{gcd}$ of all the $k\times k$ minors of $M$, so integer. ( the Smith normal form works for matrices $M$ with rational entries, just bring all to a common denominator).  Now consider the matrix $M' = S\cdot D'\cdot T$, where $D' = \operatorname{diag}(1, 1, \ldots, 1, d_1\cdots d_k)$.  Note that the only change is from $D$ to $D'$ ( the matrices $D$, $D'$  are not exactly diagonal, since they are size $k\times n$). The $k\times k$ minors of $D$ equalt the corresponding $k\times k$ minors of $D'$. Moreover, $D'$ has integer entries ( obviously, since $d_1\cdot d_k$ is integer). We conclude that $M'$ has integer entries and the same $k\times $ minors ( from Cauchy-Binet)  as $M$.

Examples:

Q: what can be said about the $2\times 2$ minors of a $2\times 3$ matrix with integer coefficients? A: They are integers.

Q: what can be said about the $2\times 2$ minors $m_{ij}$, $1\le i< j \le 4$, of a $2\times 4$ matrix with integer coefficients? A: $m_{ij} \in \mathbb{Z}$ and $m_{12}m_{34} -m_{13}m_{24}+m_{14}m_{23} = 0$.

Q: what can be said about the $(n-1)\times (n-1)$ minors of a $(n-1)\times n$ matrix with integer coefficients? A: They are integers.

Why do we have the Plucker relations ( the necessity)?  If we have $k+1$ column vectors of size $k$ then among them there is a generic linear dependence given by the Cramer rule. For instance, for $4$ column vectors of size $3$ we have
$$(v_1 v_2 v_3) v_4 = ( v_4, v_2, v_3)v_1 + (v_1, v_4, v_3) v_2 + (v_1 v_2 v_4) v_3$$
Now if these vectors $v_i$ are columns of some $3\times n$ matrix, consider completing the linear relation above to something involving product of determinants, as follows
$$(v_1, v_2, v_3)(v_4 v_k v_l) - (v_4 v_2v_3) (v_1, v_k, v_l) - (v_2, v_4 v_3)(v_2 v_k v_l) - ( v_1 v_2 v_4) (v_3 v_k v_l)$$
so we got one of the (many) Plucker relations. ( Not all of them are independent)
The converse ( that given the equality we can find $n$ columns of size $k$ satisfying $a_{ijk} = (v_i v_jv_k)$ is a bit more involved.


Predicting Y from a regression model for dY

Question: I have some time series data where I'm modelling temperature as a function of various predictors. On physical grounds, I can expect that
$$\frac{dT}{dt} \propto T_a - T$$
where $T_a$ is the ambient temperature (which can vary over time, but whose values are known). I thus fit models of the form
$$\Delta T(t) \sim \alpha + \beta \left[ T_a(t) -T(t) \right] + \gamma X(t)$$
with $X$ being the other covariates, and $\alpha$, $\beta$ and $\gamma$ are the regression parameters. I can fit these easily enough in R:
<code>lm(diff(T) ~ I(Ta - T) + x, data=df)
</code>
and I can get predictions for the change in $T$. However, what I really want are predictions for $T$ itself. At the moment I'm calculating these via a loop, where I plug $\hat{T}(t)$ into the regression equation to obtain $\hat{\Delta T}(t+1)$.
Is there any R package, probably time series-related, that will do these calculations automatically?
Also, if there are any issues with this approach, I'd be happy to know about them.
Comment: What do you mean in the sentence "what I really want are predictions for T itself"? You want to predict T from what inputs?
Comment: Did you mean you want to predict T at time t' where t'>t? In this case iterating probably is the best way to estimate this (due to the nature of differential equations). Or are you trying to find a steady state for T?
Comment: @user3244965 I want to predict $T(t)$ taking into account the fact that it's a differential equation. I'm doing this using my own code, but maybe someone else has already written a package for it. I'm not interested in finding steady states or equilibria.
Comment: Can you confirm that $T(t)$ observed?  On physical ground, would not it be expected that $\textrm{d} [ T - T_{\textrm{a}} ]/
\textrm{d}t \propto -[T - T_{\textrm{a}}]$ (with a negative proportionality constant)?
Comment: `Ta` and `T` are observed, yes.
Answer: Your approach can be related to using a time-series model either in
discrete time (DT) or continuous time (CT). It seems better to work
with the difference $Z(t) := T(t) - T_{\textrm{a}}(t)$ because
$T_{\textrm{a}}(t)$ will be required as an offset term for forecasting
as well as for fitting. A possible model writes in CT as
$$
\frac{\textrm{d}}{\textrm{d}t}Z(t) + \theta Z(t) = \alpha +
\boldsymbol{\gamma}^\top \mathbf{X}(t) + \varepsilon(t)
$$
where $\varepsilon(t)$ stands for a white noise. The constraint
$\theta > 0$ should hold to ensure stability.  A very important point
is that the covariates in $\mathbf{X}(t)$ should be exogenous, which
excludes e.g. a temperature-driven heating power.  Note that with
$\alpha = 0$ and no covariates, the temperature difference $Z(t)$
would return to zero, which should make sense on physical grounds.
Now the corresponding approximate DT model for $Z_t$ at times $t=1$,
$2$, $\dots$ is
$$
  Z_t = \alpha + \beta Z_{t-1} + \boldsymbol{\gamma}^\top \mathbf{X}_t
  + \varepsilon_t,
$$
with $\beta := 1 - \theta$, so $\beta < 1$ should hold.
This model slightly differs from your one because of the use of $Z_t$ in
place of $T_t$ at left hand side and, more importantly, because at the
right hand side we have the lagged $Z_{t-1}$ where you used
$Z_t$. This is an ARMAX model, with parameters $\alpha$, $\beta$, $\gamma_i$ and
$\sigma_{\varepsilon}^2$ which can be estimated by Maximum Likelihood
or Least Squares. In the second case, the parameters can be obtained
by a regression similar to the one you used.
To forecast $T_{t+1}$ using observations up to time $t$, you need
forecast $Z_{t+1}$ using a forecast of $\mathbf{X}_{t+1}$
$$
  \widehat{Z}_{t+1|t} = \alpha + \beta Z_t + \boldsymbol{\gamma}^\top \widehat{\mathbf{X}}_{t+1|t}
$$
where the parameters are replaced by their estimated value, and then
simply add the forecast of $Z_{t+1}$ to that of $T_{\textrm{a},t+1}$
according to $\widehat{T}_{t+1|t} = \widehat{T}_{\textrm{a},t+1|t} +
\widehat{Z}_{t+1|t}$. Multistep forecasts $\widehat{T}_{t+h|t}$ can be
derived as well for $h >1$.
Although general ARMAX functions exist in several R packages, they do
not all allow this simple parametric form. So it may be easier to keep
on writing your own estimation and forecasting functions using the
specific form of your model, unless you want to experiment with some
model changes. You can also try the R package named dynlm (on CRAN)
working on time series (ts) objects rather than on numeric vectors.


MatPlotLib is very slow in python

Question: <code>import matplotlib
matplotlib.use('TkAgg')
def generate_graph(self,subject,target,filename):
    x_data = range(0, len(self.smooth_hydro))
    mslen = len([i[1] for i in self.master_seq.items()][0])
    diff=(mslen-len(self.smooth_hydro))/2
    x1_data = range(0,len(self.smooth_groups.items()[0][-1]))
    x2_data = range(0,mslen)
    plt.figure()
    plt.axhline(y=0, color='black')
    plt.ylim(-3, 3)
    plt.xlim(right=mslen)
    plt.plot(x_data, self.smooth_hydro, linewidth=1.0, label="hydrophobicity", color='r')
    plt.plot(x_data, self.smooth_amphi, linewidth=1.0, label="amphipathicity", color='g')
    for pos in self.hmmtop:
        plt.axvline(x=pos-1-diff, ymin=-2, ymax = 0.1, linewidth=1, color='black',alpha=0.2)

    plt.axvspan(subject[0]-diff,subject[1]-diff, facecolor="orange", alpha=0.2)
    plt.axvspan(target[0]-diff,target[1]-diff, facecolor="orange", alpha=0.2)

    plt.legend(loc='upper center', bbox_to_anchor=(0.5, 1.05),
              ncol=3, fancybox=True, shadow=True)
    plt.xlabel("Residue Number")
    plt.ylabel("Value")
    width = (0.0265)*len(self.master_seq[0]) if mslen > 600 else 15
    plt.grid('on')
    plt.savefig(self.out+'/graphs/'+filename+'.png')
    plt.clf()
    plt.cla()
    plt.close()
</code>
I am calling this function repeatedly, but the images generated are extremely slow. Can someone please help me optimize this code so that it can run faster?
Thank you!
Comment: Possible duplicate of [why is plotting with Matplotlib so slow?](http://stackoverflow.com/questions/8955869/why-is-plotting-with-matplotlib-so-slow)
Answer: I found this answer in another post. All credit to Luke.

Matplotlib makes great publication-quality graphics, but is not very
  well optimized for speed. There are a variety of python plotting
  packages that are designed with speed in mind:

http://pyqwt.sourceforge.net/ [ edit: pyqwt is no longer
  maintained;the previous maintainer is recommending pyqtgraph ]
http://code.google.com/p/guiqwt/
http://code.enthought.com/projects/chaco/
http://www.pyqtgraph.org/

MatPlotLib is very slow in python


What do I need to look for in a Y splitter for guitar?

Question: I have started recording band practices. I'd like to record my guitar signal twice, one DI with no effects and the other mic'ing my amp. So I want to split my signal prior to effects chain (maybe post wah, which is the 1st effect in my chain). What do I need to do this?
If I just use a simple cable splitter, I assume I'll cut my signal in half and lose tone. Is that right? I'm guessing that I need some sort of A/B/Y pedal to use in the Y mode. What should I be looking for in that pedal? What distinguishes a bad from a good splitter pedal? Am I just looking for a good buffer? Are there options other than an ABY pedal, like maybe a tuner with two outputs?
Answer: Yes, a simple cable splitter is a bad idea, and an ABY pedal will solve that problem---but you  don't even need that.  If you have an active DI with an unbalanced, buffered 1/4" out, you can simply send that to the effects and amp while sending the balanced XLR out (which will still be dry) directly to the board.  Here's an example of what I'm talking about; I'm not familiar with this specific make & model, though, so this isn't a product recommendation.
Comment: @yossarian Better? I can't imagine it is, but unless you already have an active ABY box (and if you did, why would you have posted?), it seems to me you're going to be buying a gadget anyway, in which case the active DI solution seems simpler---to me, anyway.
Comment: I don't have one lying around. Is that better than using an aby box?
Answer: Actually, although an active DI is probably a good idea, a passive DI will solve the same problem.
A DI box is little more than an electrical transformer; the "hot" side of the unbalanced signal is wound around one side of a ferrous metal ring. On the other side of the ring is another loop of wire that feeds the "balanced" output. Alternating current produced by the instrument passes through the loop one one side, and induces a magnetic field in the ring. The magnetic field then induces a current in the loop of wire on the opposite side.
While this process is "work", and will thus reduce the remaining power of the signal, an XLR signal is expected to be 20dBm less powerful than most unbalanced signals. A 10dB change is an increase or reduction of 10x the original signal, so a signal that is 20dBm lower than another is 1/100 or 1% of the wattage of that signal. So, your original signal loses 1% (plus a little overhead) of its original wattage to create the balanced XLR signal. I guarantee you that you will not notice a loss of 1% of your signal wattage; that's less than 1dB, and 3dB is the minimum change in volume level that a human can notice.
You still shouldn't use a Y-splitter; this will form a parallel circuit, with very low impedance (an "easy" path) on the side of the DI. That will cause most of the signal (not just half; almost all, really) to go through the DI side of the split and back into the instrument, instead of the very high-impedance path through the pedals and into the amp. Instead, use the DI's "thru" input, which engages either passive circuitry that puts the transformer in series with the rest of the chain, or active circuitry that includes a gain stage to boost the "thru" signal back up to its original level. Either way, you should be able to plug the DI into your effects chain with a couple of simple patch cables, like any other "effect", and see little difference in tone. The better the DI, the less it will color your tone; Radial is a good brand but you'll pay for it.
Comment: Signal wattage is not that relevant here, the problem with passive DIs is that they interact with the guitar pickups' high inductive impedance and can thereby alter the sound quite substantially. As for the "thru" jack – to be honest I haven't looked in many DIs, but I'm quite sure that it's also simply wired parallel on most models, so that would yield exactly the same result as a Y-cable.
Comment: 3dB?  I usually hear the just noticeable difference pegged at the much more believable 1dB.
Answer: Standard Y-cable splitter will be fine and no issues with signal at all if the one end is connected to the amp and the other to a high-impedance audio interface input.The problem is if you connect it to low impedance inputs (non instrument inputs or other low impedance preamp or amp).
Answer: I needed to send my guitar's signal to two amps. Using a Y cable caused signal loss resulting in the amps producing too little volume along with hum.
I have used two floor switches (pedals) to Y split a guitar's output with success.  One was a non powered, one of a kind, floor switch with built for me by a band member. It had circuitry components as found in amps but no power source.  The single switch gave a selection between amp A and amp A/B.
Another is a dual switch pedal that is powered by a 9v battery or 9v adapter.  It has LEDs, two switches, and three jacks with options A or B  A and B.  It can be used as one source in two out, or two in one out.  I found it at a big online music store.
The guitar used with these switches was a passive pickup electric.


What is happening in binary IO in C?

Question: I imagine this applies to a lot of other languages as well.
I have this code here, and I am wondering what is actually happening and how I can interpret what is written to the file...
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main ()
{
    //Initialize a variable and load it with input using scanf
    char write[100] = "Write this.";

    FILE *fp = fopen("./binFile.txt", "w+");
    fwrite(write, sizeof(write[0]), sizeof(write)/sizeof(write[0]), fp);
    fclose(fp);
}

and then when I open the text file I see this...
5772 6974 6520 7468 6973 2e00 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000

But I am having some trouble seeing exactly what is going on here. How does this text break down to binary?
Comment: Seriously? you've never heard of ASCII?
Comment: The editor you are using thought that you'd like to see things clustered that way. You might be able to change this via the editor's configuration options
Comment: You're opening the text file using a program which displays the hex codes of the characters in the file. `57` means `W`, `72` means `r`, etc.  If you open the file in a text editor you should see `Write this.` followed by however that editor displays null bytes
Comment: Do you expect any kind of output?
Comment: @M.M I see so hex code 57 = 87 ASCII = W. Got it. Thanks. Why is it clustering like that (5772 6974..instead of 57 72 69 74)
Comment: hmmm. ok thanks for the info, just curious what is happening behind the scenes
Answer: You are writing the entire char array to the file, and the char array was initialized to 12 chars, followed by all zero values. That's why you see all the zeros after the string, perhaps that makes your system thinks it's a binary file. So use the following instead if you want to write a string:
fwrite(write, sizeof(write[0]), strlen(write), fp);

What is happening in binary IO in C?


Hierarchical plot with bubbles in r

Question: On this page, I found an interesting plot:

Is it possible to do something similar or exactly? (Combination between treemap and ggraph library).
Answer: You can get a similar appearance with the voronoiTreemap package:
library(voronoiTreemap)

vor <- data.frame(h1 = 'World',
                  h2 = c('Europe', 'Europe', "Europe",
                         'America', 'America', 'America', 'America',
                         'Asia', 'Asia', 'Asia', 'Asia', 'Asia', 'Asia',
                         'Africa', 'Africa', 'Africa'),
                  h3 = c("UK", "France", "Germany",
                         "USA", "Mexico", "Canada", "Brazil",
                         "China", "India", "S Korea", "Japan", "Thailand",
                         "Malaysia", "Egypt", "South Africa", "Nigeria"),
                  color = rep(c("pink", "steelblue", "#96f8A0", "yellow"),
                              times = c(3, 4, 6, 3)),
                  weight = c(12, 10, 15, 40, 5, 7, 9, 45, 30, 20, 20, 6, 9,
                             8, 10, 5),
                  codes = c("UK", "France", "Germany",
                            "USA", "Mexico", "Canada", "Brazil",
                            "China", "India", "S Korea", "Japan", "Thailand",
                            "Malaysia", "Egypt", "South Africa", "Nigeria"))

vt <- vt_input_from_df(vor)

vt_d3(vt_export_json(vt))

Hierarchical plot with bubbles in r


Finding the angles of $\triangle ABC$

Question: In a $\triangle ABC$, from vertex $C$, the median to $AB$, the angle bisector of $\angle BCA$  and the perpendicular to $AB$ divides angle $\angle BCA$ into four equal parts.
The task is to compute angles in $\triangle ABC$.
Thanks for any help.
Comment: Let $\angle A = x$. Then $\angle B$ = ... = 3x - 180. The median CD divides ABC into two smaller triangles. In them, BD of $\triangle BCD$ = DA of $\triangle ACD$. Also, CD is the common side to both triangles. Applying sine law to both triangles, we might be able to get a trig equation in x. A value of x may be obtained if that equation is not going round and round. Just a suggestion and I have no time to try.
Comment: It's a right triangle with an angle of $\dfrac\pi8.~$ I know this by heart, because I've asked myself a somewhat similar question several months ago, namely, in what triangle do the angle bisector and the height or altitude trisect one of the two segments formed by the median on the opposite side. $($Initially, I wanted to find a triangle such that the three lines quadrisect the basis, but that is impossible, since the angle bisector is always trapped between the median and the height or altitude$).$
Answer:
Applying sine law to triangle ACD, we have $\dfrac {s}{t} = \dfrac {\sin (90 – 3x)}{\sin x} = \dfrac {\cos 3x}{\sin x}$
Applying sine law to triangle BCD, we have $\dfrac {s}{t} = \dfrac {\sin (90 – x)}{\sin 3x} = \dfrac {\cos x}{\sin 3x}$
Then $\sin 3x \cos3x – \sin x \cos x = 0$
By Wolframalpha, we have x = $\dfrac {\pi}{2} - \dfrac {3 \pi}{8} radian = 22.5^0$ (an answer that matches @Lucian 's)
[Note: the trig equation can also be solved as $2 \sin 3x \cos3x = 2\sin x \cos x$. Then, $\sin 6x = \sin 2x$. This means $x = 0$ or $6x = \pi - 2x$; and this further yields $x = \dfrac {\pi}{8}$.]
Result follows.

Finding the angles of $\triangle ABC$


SCSS syntax error in safari only hack

Question: While converting a .css file to .scss I am getting a Sass syntax error in safari only hack section.
At the following part of the code its throwing Invalid CSS after "...tio:0) { @media": expected media query (e.g. print, screen, print and screen), was "{" error.
@media screen and (min-color-index:0) and(-webkit-min-device-pixel-ratio:0) { @media
{
// some code here
}}

Comment: why have you got a media query inside your media query?
Answer: Your media query is invalid, you have a media query inside your media query which has no conditions.
Try this:
@media screen and (min-color-index:0) and(-webkit-min-device-pixel-ratio:0) {
    // some code here
}

Comment: followed the safari hacks from https://jeffclayton.wordpress.com/2015/04/28/css-hacks-for-safari-6-1-7-and-8-not-chrome
Comment: I've never seen a media query like that before, pretty weird hack. Do you need it? or does my code work?
Answer: @media screen and (min-color-index:0) and(-webkit-min-device-pixel-ratio:0) { @media { // some code here }}

should be
@media screen and (min-color-index:0) and(-webkit-min-device-pixel-ratio:0) { // some code here }}

You have a media query inside a media query, which is invalid.
https://www.w3schools.com/css/css_rwd_mediaqueries.asp
You can use javascript to properly detect safari, something like this:
function isiPad() { return (
(navigator.userAgent.toLowerCase().indexOf(/iPad/i) > -1));}

SCSS syntax error in safari only hack


Change button markup of searching form

Question: I am trying to find a way out about five hours now, i have studied and tried a lot of different things but i couldn't find the right drupal way to do what i want... Please help with the following.
I have the search-block-form which displays a search input text field and a button. The markup for the button now is the following (produced by drupal core):
<button class="form-submit" id="edit-submit--2" name="op" value="Search" type="submit">Search</button>

I want to add extra markup inside the <button></button>, like the following:
<button class="form-submit" id="edit-submit--2" name="op" value="" type="submit"></button>

I know of course how to set the value=' ' and i have to say that i've already tried #prefix and #suffix parameters. I don't want to add markup prior to the button element or after that. I should put markup inside, between the element's tags.
I tried also change the hook theme_button($variables) but my problem is that i want to change only the button for search-block-form and not all the button elements.
As some of you have already understand, i use foundation 5 framework and i want to make the search button like this:
Answer: * Updated *
You can do this by overriding theme_button() in your theme. Note that the code here is copied from theme_button(), with the return value adjusted accordingly:
function THEMENAME_button($variables)
{
  $element = $variables['element'];
  $element['#attributes']['type'] = 'submit';
  element_set_attributes($element, array('id', 'name', 'value'));

  $element['#attributes']['class'][] = 'form-' . $element['#button_type'];
  if (!empty($element['#attributes']['disabled']))
  {
    $element['#attributes']['class'][] = 'form-button-disabled';
  }

  if(isset($element['#search_button']) && $element['#search_button'])
  {
    return '<button' . drupal_attributes($element['#attributes']) . '></button>';
  }
  else
  {
    return '<input' . drupal_attributes($element['#attributes']) . ' />';
  }
}

Then you need to add #search_button = TRUE to the button in hook_form_alter()
function hook_form_alter(&$form, &$form_state, $form_id)
{
  if($form_id == 'MYFORMID')
  {
    $form['actions']['submit']['#search_button'] = TRUE;
  }
}

Note: This will render the button as requested. No guarantees that it will actually work with the Form API. That needs separate testing.
Comment: OP = Original Poster (you)
Comment: Thanks for the reply but no. It's all about security. The #value is just plain text.
Comment: I just did some testing - this can't be done. Browsers render the value attribute as plain text, so there isn't anything you can do in Drupal that would get around that. It's a browser limitation not a Drupal limitation.
Comment: @Jaypan I think you might have misunderstood...the OP is trying to get some extra markup into a FAPI submit button (not input); browsers are happy to render the markup inside a ``, even of type submit, but it's not necessarily obvious how to get Drupal to play along, especially if you only want to target the one element. You're right that `value` _attributes_ are rendered as plain text, but FAPI `#value`s are a different thing. This is something that just needs to be attacked at the theme level
Comment: You're right, I did misunderstand. I updated my post with a solution.
Comment: Good approach, in case OP is using a sub-theme of [Foundation](https://www.drupal.org/project/zurb_foundation) the code should be copied from `zurb_foundation_button` instead to make sure everything stays consistent
Comment: Yes, @Jaypan, this seems to work. I am still testing the rest Form API but it seems no problem.
Comment: @Clive, you said _OP_. What does this mean ?

Change button markup of searching form


R: changing the color of lines in R

Question: I am using R. I am trying to change the color of different lines on a graph. I figured out how to make each line a different color in the code below:
library(xts)
library(ggplot2)
library(dplyr)
library(plotly)
library(lubridate)

#time series 1
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")

property_damages_in_dollars <- rnorm(731,100,10)

final_data <- data.frame(date_decision_made, property_damages_in_dollars)

final_data %>%
  mutate(date_decision_made = as.Date(date_decision_made)) %>%
  add_count(week = format(date_decision_made, "%W-%y"))

final_data$class = "time_series_1"

#time series 2
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")

date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")

property_damages_in_dollars <- rnorm(731,10,10)

final_data_2 <- data.frame(date_decision_made, property_damages_in_dollars)

final_data_2 %>%
  mutate(date_decision_made = as.Date(date_decision_made)) %>%
  add_count(week = format(date_decision_made, "%W-%y"))

final_data_2$class = "time_series_2"

#time series 3
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")

date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")

property_damages_in_dollars <- rnorm(731,50,50)

final_data_3<- data.frame(date_decision_made, property_damages_in_dollars)

final_data_3 %>%
  mutate(date_decision_made = as.Date(date_decision_made)) %>%
  add_count(week = format(date_decision_made, "%W-%y"))

final_data_3$class = "time_series_3"

#time series 4
date_decision_made = seq(as.Date("2014/1/1"), as.Date("2016/1/1"),by="day")

date_decision_made <- format(as.Date(date_decision_made), "%Y/%m/%d")

property_damages_in_dollars <- rnorm(731,50,50)

final_data_4<- data.frame(date_decision_made, property_damages_in_dollars)

final_data_4 %>%
  mutate(date_decision_made = as.Date(date_decision_made)) %>%
  add_count(week = format(date_decision_made, "%W-%y"))

final_data_4$class = "time_series_4"

data = rbind(final_data, final_data_2, final_data_3, final_data_4)

a = data  %>%

    group_by(class) %>%
    plot_ly(x = ~ (date_decision_made)) %>%
    add_lines(y = ~ property_damages_in_dollars,
              color = ~ factor(class)
    )

Is there a way to make (time series 1 , time series 2) the same color and (time series 3, time series 4) the same color?
I tried the following code, but now there are only 2 time series instead of 4:
final_data_4$class = "red"
final_data_3$class = "red"
final_data_2$class = "blue"
final_data$class = "blue"

data = rbind(final_data, final_data_2, final_data_3, final_data_4)

a = data  %>%

    group_by(class) %>%
    plot_ly(x = ~ (date_decision_made)) %>%
    add_lines(y = ~ property_damages_in_dollars,
              color = ~ factor(class)
    )

Can someone please show me what I am doing wrong? I want there to be 4 time series, the first two to be one color and the other two be the same color.
Thanks
Answer: library(xts)

dat <- matrix(rnorm(400), ncol = 4)
tindex <- seq.Date(from = Sys.Date()-99,
                   to = Sys.Date(),
                   by = 'days')

dat_xts <- xts(dat, order.by = tindex)
names(dat_xts) <- paste0('ts', 1:4)

plot.xts(dat_xts, col = c('red', 'red', 'blue', 'blue'),
         legend.loc = 'bottomright')

Using ggplot:
library(ggplot2)

autoplot(dat_xts, facets = FALSE) + scale_color_manual(values= c('red', 'red', 'blue', 'blue'))

Comment: Thank you for your reply! Can this be converted into a plotly object? With the ggplotly() function? Thanks you for all your help!
Comment: Thank you! I will see if autoplot is compatible with ggplotly.
Comment: Can you please take a look at these questions if you have time? https://stackoverflow.com/questions/65655864/r-plotting-multiple-confidence-intervals-on-the-same-graph , https://stackoverflow.com/questions/65657858/r-removing-half-of-the-confidence-bands
Comment: https://stackoverflow.com/questions/65650991/r-overlaying-points-on-a-graph

R: changing the color of lines in R


How to simplify boolean algebra (~a~b)+(abc)+(a~c)

Question: I've been trying for ages and keep getting (~a~b)+(ab)+(a~c), but all simplification websites keep saying (~a~b)+(ab)+(~b~c).
My reasoning:

(~a~b)+(abc)+(a~c)
(~a~b)+(a(bc+~c))
(~a~b)+(a((b+~c)(c+~c)))
(~a~b)+(a((b+~c)(1)))
(~a~b)+(a(b+~c))
(~a~b)+(ab)+(a~c)

Any help would be greatly appreciated, thanks.
~ = NOT
ab = a AND b
a+b = a OR b
Answer: Both answers are correct, as they are equivalent:
$$a'b'+ab+ac'$$
$$\overset{Adjacency}{=}$$
$$(a'b'c+a'b'c')+(abc+abc')+(abc'+ab'c')$$
$$\overset{Association}{=}$$
$$a'b'c+a'b'c'+abc+abc'+abc'+ab'c'$$
$$\overset{Idempotence}{=}$$
$$a'b'c+a'b'c'+abc+abc'+ab'c'$$
$$\overset{Idempotence}{=}$$
$$a'b'c+a'b'c'+a'b'c'+abc+abc'+ab'c'$$
$$\overset{Commutation}{=}$$
$$a'b'c+a'b'c'+abc+abc'+ab'c'+a'b'c'$$
$$\overset{Association}{=}$$
$$(a'b'c+a'b'c')+(abc+abc')+(ab'c'+a'b'c')$$
$$\overset{Adjacency}{=}$$
$$a'b'+ab+b'c'$$


Need a categorized post list for WordPress site, but having trouble with loops

Question: I'm working on a wordpress blog (_'s theme) and want to display all posts for every category in a menu that will be available on all pages
I am using the below code
<?php
        $cat_args = array(
          'orderby' => 'name',
          'order' => 'ASC',
          'child_of' => 0
        );

        $categories =   get_categories($cat_args);

        foreach($categories as $category) {
            echo '
name.'" >' . $category->name.'
';

             $post_args = array(
              'numberposts' => 5,
              'category' => $category->term_id
            );

            $posts = get_posts($post_args);

            foreach($posts as $post) {
            ?>

<a href="<?php the_permalink() ?>" rel="bookmark" title="Permanent Link to <?php the_title_attribute(); ?>"><?php the_title(); ?>

            <?php
            }
            }
            ?>

This code will display and format the list exactly as I want it to.
The problems...
1.) On the index page this code will make my sticky posts disappear if it comes before the loop.
2.) On the single post page, nothing will display after the loop if the code comes after the loop.
Which would be fine as I can just use conditionals to display the code either or depending on the page, however...
3.) This code also makes it so that the single post loop will only display the content of the most recent post, but only when it comes before the loop, otherwise I'm back to problem 2.
I have tried following the code with wp_reset_postdata(); and wp_reset_query(); to no avail, and I cant figure out how to display everything correctly with the multiple loop tutorial in the codex.
also this is my single.php loop
<?php while ( have_posts() ) : the_post(); ?>

            <?php get_template_part( 'content', 'single' ); ?>

            <?php
                // If comments are open or we have at least one comment, load up the comment template
                if ( comments_open() || '0' != get_comments_number() ) :
                    comments_template();
                endif;
            ?>

            <?php endwhile; // end of the loop. ?>

and this is my index.php loop
<?php if ( have_posts() ) : ?>

            <?php /* Start the Loop */ ?>
            <?php while ( have_posts() ) : the_post(); ?>

                <?php
                    /* Include the Post-Format-specific template for the content.
                     * If you want to override this in a child theme, then include a file
                     * called content-___.php (where ___ is the Post Format name) and that will be used instead.
                     */
                    get_template_part( 'content', get_post_format() );
                ?>

            <?php endwhile; ?>

            <?php wdh_paging_nav(); ?>

        <?php else : ?>

            <?php get_template_part( 'content', 'none' ); ?>

        <?php endif; ?>

Please help me
Answer: <?php
   $args = array(
    'posts_per_page'   => -1,
    'offset'           => 0,
    'category'         => 8, // specify category id here
    'orderby'          => 'post_date',
    'order'            => 'DESC',
    'post_type'        => 'post',
    'post_status'      => 'publish',
    'suppress_filters' => true );

    $myposts = get_posts( $args );

    foreach( $myposts as $post )
    {
      setup_postdata( $post );
      ?>
      <a href="<?php the_permalink(); ?>"><?php the_title(); ?>
      <?php
    }
    wp_reset_postdata();
?>

Comment: Thanks! The updated code is at the bottom of my post.


Vantagem em dar null em uma variável no Android

Question: Atribuir o valor de null em uma variável no Android pode melhorar o desempenho do aplicativo?
Até onde sei, em Java temos o Garbage Collector, e no Android, o ciclo de atividade das Activities e Fragments.
Problema:

Em uma classe uma variável local será limpa quando? Se der null nela, pode ajudar na questão do desempenho do aplicativo?
Em uma variável global, se der null nela, sabendo que ela não será mais útil, irá ajudar no desempenho do aplicativo?
Em variáveis de classe, dar null sempre que não for mais usar, pode melhorar no desempenho do aplicativo?

Pesquisando, encontrei isto sobre variáveis e métodos estáticos:

Use métodos estáticos
Você criou um método e ele é totalmente independente da classe onde ele está, o que você está esperando para tornar seu método estático?
Tornando um método estático você está dizendo para o compilador, ou interpretador, que o conteúdo do método só precisa estar na memória durante sua execução, não enquanto a classe estiver instanciada, ou seja, você libera a memória das variáveis locais após a execução do método. Além dessa maravilha, você não necessita de uma instância para executar um método estático, você invoca o método direto de sua classe, livrando sua memória de ter que armazenar atributos da classe que você não irá utilizar.
Use com moderação, não troque todos seus métodos para estático só para ganhar performance, senão o feitiço pode virar contra o feiticeiro. Métodos não estáticos tem o privilégio de compartilhar atributos, evitando de armazenar mais de uma vez a mesma informação."

No Android, seguir a mesma prática também é sinônimo de performance? Fazendo isso, eu não estaria "guardando" memória sem usar?
Fonte: http://www.brunonardini.com.br/desenv-back-end/5-boas-praticas-para-deixar-o-codigo-otimizado
Answer: Então

Em uma classe, uma variável local será limpa quando?

Quer dizer em um método? Não precisa a não ser que ele tenha seríssimos problemas.

Em uma variável global, se der null nela, sabendo que ela não será mais útil, irá ajudar no desempenho do aplicativo?

Sim, ajuda, mas, se possível, mude esse padrão para não precisar fazer isso.

Em variáveis de classe, dar null sempre que não for mais usar, pode melhorar no desempenho do aplicativo?

Talvez, mas também deveria mudar o padrão.

No Android, seguir a mesma prática também é sinônimo de performance? Fazendo isso, eu não estaria "guardando" memória sem usar?

Ser estático nada tem a ver com performance, pelo menos não diretamente. Até pode ter um ganho ínfimo na chamada, mas não é relevante.
Métodos estáticos não guardam memória sem usar. Variáveis estáticas podem ajudar fazer isso eventualmente.
Explicações
De forma geral a vantagem é zero, pelo menos se o código é bem feito.
De fato anular uma variável pode fazer com que uma referência deixe de existir e um objeto que está ano heap pode ser coletado pelo GC a qualquer momento liberando memória.
Isso não é garantido porque o objeto pode ter outras referências que ainda o segure vivo na memória. Mas anulando a variável já está fazendo sua parte.
Anular uma variável local em um método não faz sentido, porque todas elas são automaticamente anuladas no fim do método. Faria sentido se o método fica pendurado em uma thread por alguma razão e por uma péssima razão fica segurando referências que não deveria. Isso na verdade é erro de programação, conserte o erro em vez de fazer gambiarra tentando librar a referência. Não importa se o método é estático ou não, eles em si não são problemáticos.
Em uma classe um membro pode segurar uma referência quando na verdade não deveria. Na verdade em instâncias é menos comum porque em determinado momento a instância irá morrer e todas suas variáveis são automaticamente anuladas nesse momento. O que pode ocorrer é um objeto sobreviver mais do que o esperado e isso provavelmente é um erro de programação também e deveria ser solucionado.
Mas se o objeto dura muito mesmo então deveria repensar a estrutura do objeto. Talvez ele tenha uma variável segurando uma referência para outro objeto que não deveria estar ali.
Isto pode ocorrer com membros estáticos de uma classe que tem durabilidade de toda a aplicação. Se uma variável estática deve ter seu valor anulado, deveria repensar se a variável deveria ser estática ou até existir.
Membros estáticos podem ser problema por causa do estado global, mas eles podem ser úteis se souber o que está fazendo. Quase sempre que está precisando anulá-lo não sabe o que está fazendo. O fato da variável estática ficar lá o tempo todo não é um problema porque ela tem um pequeno valor sempre, ou é um tipo por valor ou é uma referência. O problema dela pode ser a concorrência ou o fato de segurar uma referência por mais tempo do que deveria. Mas há casos para seu uso. Quem entende o funcionamento das coisas e não segue "boas práticas" cegamente sabe disso. Sempre estude antes de usar algo.
Note que anular uma variável é diferente de trocar o seu valor. Quando colocamos outra referência para uma variável o objeto que antes era pontado por esta variável perde esse apontamento e possivelmente poderá ser coletado.
Até existem alguns raros casos onde anular a variável pode ser útil, mas é raro, quase sempre tem forma melhor de fazer isso e deveria corrigir o problema certo.
Mesmo que anule uma variável e o objeto referenciado não tenha outras referências nada garante que o GC colete o objeto em algum momento. Não que o GC seja imprevisível, só não se sabe quando ele rodará. Só o tempo não é determinístico e a aplicação pode encerrar antes de uma coleta ocorrer. Mas se uma coleta for disparada e o objeto não tiver referências ele será coletado com certeza, não é uma coisa louca que ninguém sabe se ocorrerá ou não.
Falou em boa prática eu torço o nariz. Em geral a pessoa está reproduzindo o que leu sem entender aquilo ou está vendendo uma ideia sem querer instruir o leitor.
O texto citado tem vários erros, alguns graves e é o oposto da realidade, a citação em negrito na pergunta por exemplo, não confiaria nele. Ocorre na maioria do conteúdo da internet.
Coloquei no GitHub para referência futura.
Comment: São sim, desde que saiba o que está fazendo. Achei que ficou claro quando eu disse que sempre prefiro eles. Só que em muitos casos eles não fazem sentido, métodos que precisam operar na instância não podem ser estáticos. Todos os métodos limpam as variáveis quando terminam, isto tudo está na resposta. Limpar a variável não é limpar o objeto automaticamente, isto é trabalho do GC. Certamente é mais eficiente não instanciar uma classe, mas nem sempre podemos fazer isso.
Comment: O mesmo vale para os métodos estáticos? (fugindo um pouco)
Comment: Eu estava justamente editando isso.
Comment: Eu achei muito bom e claro aquilo que você escreveu. Só não ficou claro pra mim a parte dos métodos estáticos. Então métodos estáticos não são tão bons pra serem escritos, correto? Porém, isso não tem a ver com memória. As variáveis são limpas também, assim que se é usado um método estático? Pois de certa forma, fica mais "eficiente" não instanciar uma classe e chamar o método estático, do que instanciar ela e chamar o método, não?
Answer: Em poucas palavras: não, não vai resolver.
Em todo tempo de experiência que eu tenho, a JVM (Dalvik/Art), e o Garbage collector do android são totalmente independentes e você não controla sua execução. Trocando em miúdos, são "cachorro louco" (independentes e imprevisíveis)
Passar null para uma variável, independe se ela é da classe, global ou local, vai indicar que ela deve ser limpa pelo Garbage Collectork, mas não indica que vai ocorrer naquele exato momento.
Além do que o próprio sistema vai limpar os recursos do aplicativo quando ele precisar de memória (estando em background).
Um ponto sobre métodos estáticos é que eles não são os melhores, variaveis então nem se fala. Pelo meu conhecimento, as variáveis estáticas são alocadas na memória e ficam lá disponíveis até serem explicitamente removidas, seja pelo sistema operacional ou pela execução do programa.
A melhor forma de se otimizar um aplicativo no android, é entender o ciclo de vida, e como o mesmo armazena as informações entre transferências de intent, e salvamento de estado. Além de diminuir operações custosas para threads principais e uso de tarefas/services em background para operações mais demoradas.


Why are weather prediction models--such as hurricane forecasts--so accurate?

Question: I have been watching the hurricane forecasting for Hurricane Henri, and it made me think about the accuracy of the forecasting for hurricane tracks. While I don't know much about meteorology, it seems that hurricane models are likely based on large systems of hyperbolic PDEs. My question is, what methods are used to solve these PDEs or whatever models, such that it allows weather forecasters to predict the flow of the system over hundreds of miles?
There are many different methods for solving hyperbolic pdes, finite elements, finite volume methods, etc., symplectic integrators for the timestepping. But I did not think that these types of methods would guarantee accuracy over such a long long time domain and spatial domain.
I was hoping someone might know what techniques are used to solve these hurricane models, that enable such a high level of accuracy over hundreds of miles.
Answer: It's not just the choice of pde models and of numerical solvers that makes modern numerical weather prediction (NWP) so successful. The availability of data (weather stations, radio sondes, satellites etc.), international cooperation, new techniques such as ensemble forecasting and data assimilation, and improved physical models for atmospheric phenomena and for ocean-atmosphere interaction all have contributed.
For a thorough discussion of the progress of NWP during the last 100 years, take a look at the linked article.
Comment: thanks so much for the info, and for the link to the paper. Yes certainly to better data from multiple sources, that makes sense. I have heard people talk about the importance of data assimilation in weather forecasting applications, but did not realize how important it was in such high dimensional cases. Haha, also as you say the underlying models became better, and not just the numerical methods used to solve them--though the numerical methods became better too.