Integrating indicator function to derive pseudovalue

Question: I'm reading a paper on the use of pseudovalues in survival analysis and am trying to derive the pseudovalue for the restricted mean lifetime function. We have,
$$ \hat{\mu}_{\tau_i} = \int_{0}^{\tau} \hat{S}_{i}(t) ~ dt $$
where $\hat{S}_i(t)$ is the ith pseudovalue of the survival function.
With no censoring,
$$ \hat{S}_{i}(t) = \mathbb{I}(X_i > t)$$
where $X_i$ is the $i^{th}$ event time. So,
$$ \hat{\mu}_{\tau_i} = \int_{0}^{\tau} I(X_i > t) ~dt $$
By evaluating this, apparently $\hat{\mu}_{\tau_i}$ should be equal to $X_i$ when $X_i \leq \tau$ and $ \tau$ when $X_i > \tau$. I think I am missing something with regards to integrating the indicator function because I am getting $\hat{\mu}_{\tau_i} = \tau - t$.
For indicator functions, I thought
$$ \int_{-\infty}^{\infty} I(X > a) dx  = \int_{a}^{\infty} dx$$
So I changed my integral such that,
$$ \hat{\mu}_{\tau_i} = \int_{t}^{\tau} 1 ~dt = \tau - t$$
I'm thinking this is wrong because the differential is in the integral limits but I'm not sure how to do this correctly. Is anyone able to help point out the correct way of handling this?
Answer: The notation $\hat{\mu}_{\tau_i}$ is bad notation, since there is no variable $\tau_i$.  Using the alternative notation $\hat{\mu}_i(\tau)$ for the same thing (which is better notation), you should have:
$$\begin{aligned}
\hat{\mu}_i(\tau)
&= \int \limits_0^\tau \mathbb{I}(X_i > t) \ dt \\[6pt]
&= \int \limits_0^\tau \mathbb{I}(t < X_i) \ dt \\[6pt]
&= \int \limits_0^{\min(X_i,\tau)} \mathbb{I}(t < X_i) \ dt + \int \limits_{\min(X_i,\tau)}^\tau \mathbb{I}(t < X_i) \ dt \\[6pt]
&= \int \limits_0^{\min(X_i,\tau)} 1 \ dt + \int \limits_{\min(X_i,\tau)}^\tau 0 \ dt \\[6pt]
&= \int \limits_0^{\min(X_i,\tau)} 1 \ dt \\[6pt]
&= {\min(X_i,\tau)}. \\[6pt]
\end{aligned}$$
Note that when you perform a definite integral over the variable-of-integration $t$ (and so long as the limits of the integral do not involve $t$) you must get an answer that does not have a $t$ in it.  That is, you "integrate out" the $t$.  The fact that you are getting an answer involving $t$ means that you have not integrated this out correctly.
Comment: Fantastic, thank you!
Answer: Okay I've figured it out.
My indicator function is
$$ I(X_i > t) = \begin{cases} 1 ~,~ t < X_i < \infty \\ 0 ~,~ otherwise\end{cases} $$
I can rewrite this as a function of t instead of $X_i$,
$$ I(t \leq X_i) = \begin{cases} 1 ~,~ 0 \leq t \leq X_i \\ 0 ~,~ otherwise\end{cases} $$
So I have,
$$ \hat{\mu}_{\tau_i} = \int_{0}^{\tau} I(t \leq X_i) ~dt = \int_{0}^{X_i} 1 ~dt $$
When $X_i \leq \tau$,
$$ \int_{0}^{\tau} I(t \leq X_i) ~dt = \int_{0}^{X_i} 1 ~dt + \int_{X_i}^{\tau} 0 ~ dt = X_i $$
When $X_i > \tau$, we are only integrating to $\tau$ so we have
$$ \int_{0}^{\tau} I(t \leq X_i) ~dt = \int_{0}^{\tau} 1 ~dt = \tau$$
Comment: Unfortunately your re-writing of the indicator in your working is not presently correct --- your working asserts that $\mathbb{I}(X_i > t) = \mathbb{I}(t \leq X_i) = \mathbb{I}(0 \leq t \leq X_i)$, but this involves changing the condition in the indicator.  (Note that strict inequality is not the same as non-strict inequality.)
Comment: @Ben-ReinstateMonica Ah I see my error, thank you!


Show that any root $z$ of $z^4+z+3=0$ satisfies $|z|>1$

Question: Show that any root $z$ of $z^4+z+3=0$ satisfies $|z| > 1$
My working is as such:
Let $|z| \leq 1$.
Then consider $|z^4+z| \leq |z^4| + |z| \leq 1 + 1 = 2$.
So, $|z^4 + z| \leq 2$.
Thus $-2 \leq z^4 + z \leq 2$. So $1 \leq z^4+z+3 \leq 5$.
And so $z^4+z+3 \neq 0$.
Hence if $|z| \leq 1$ there is no root $z$, and so any root $z$ must satisfy $|z| < 1$.
Is this correct?
Answer: This is very close to right. The one bit that is not correct is your claim that  $-2 \le z^4+z \le 2$. It is not correct since $z^4+z$ is complex, and you can't use $\le$ on complex numbers†.
But you don't actually need that:
A solution to $z^4 + z +3 = 0$ has $|z^4 + z| = 3$ (add -3 to both sides and take absolute value).
You've shown that $|z| \le 1 \to |z^4 + z| \le 2$. These contradict, so no solution with $|z| \le 1$ exists.

† You could argue that since $z$ satisfies $z^4+z=3$, $z^4 + z$ must be real, where $\le$ is valid, but while technically OK, the argument feels a little circular to me.
Comment: thank you so much! what about for a question where its the opposite i.e. it must satisfy |$z$| $\leq$ 1? if i try to do this the same way it doesn't really work since i'd be letting |$z$| > 1 but then i wouldnt be able to use triangle inequality?
Comment: @sam In the cases where the triangle inequality doesn't work for you, you may need heavier machinery like Rouche's theorem that Nosrati refers to in his answer. But it's hard to know without a concrete example.
Comment: Yes i think I can use the circle inequality in this case
Answer: It's better to use Rouché's theorem, with $f(z)=z^4+z$ and $g(z)=3$ then on $z=1$ we have
$$|f(z)|=|z^4+z^3|\leq2<3$$
then the number of zeros $z^4+z+3$ and $3$ are the same.


How can you define something without giving it any type like integer?

Question: I could not figure out the part about " void change(Square& obj){obj.side+=y;} " how can you define a "obj" without giving it a type like integer or else. Also what does Square& obj does for this code? Thank you.
#include<iostream>

using namespace std;

class Increment;
class Square
{
    private:
    int side;

    public:
        Square()
        {
        side=2;
        }

        void print()
        {
            cout << "side of square is: " << side<<endl;
        }
        friend class Increment;
};

class Increment
{
    private:
    int y;
    public:
        Increment()
        {
            cout<<"enter increment value: ";
            cin>>y;
        }
    void change(Square& obj){obj.side+=y;}
};

int main()
{
    Square s;
    s.print();
    Increment t;
    t.change(s);
    s.print();
}

Comment: `Square` is too a type. In light of this fact, I'm not sure I understand your question.
Comment: Note that `obj` is just a parameter-name, specified in the method's arguments-list.  The fact that the code's author chose to name the parameter `obj` doesn't mean anything in particular; he could have chosen any name for it that follows the allowed syntax.
Answer: In void change(Square& obj){obj.side+=y;} you are not defining obj, but saying that the method change receives a type Square& named obj. Square& is a reference to a Square, it means that when you call change(s), s is not copied inside the function to be used, but a reference is passed and any modifications you make inside the function to the object s will be reflected outside of the function.
Then, if you were to change Square& for Square in change, you wouldn't see any changes to s after doing t.change(s), since the function did anything it had to do with a copy of s.


What are the prerequisites on the host for running an NFS server in a container?

Question: I want to run an NFS server in a privileged Docker container.
A simple "modprobe nfs" on the host is not sufficient according to my tests – starting an NFS server in the container says "Not starting NFS kernel daemon: no support in current kernel".  The modprobe itself worked, however, as I can see "nfs" afterwards in /proc/modules on the host.
Then, I installed the (Ubuntu) package nfs-kernel-server on the host, and now, the NFS server in the container starts successfully.  However, I wonder whether a full-fledged NFS server on the host truly is necessary.
So, what are the minimum prerequisites on the host for that?
Answer: I am pretty sure that you can't start kernel nfsd process inside a container. If you want to use container to export file system, than you need to run a user space nfs server like nfs-ganesha, nfs4j or similar.
Comment: Well, I did it.  ;-)  It really works.

Recently, I found out that there is also a kernel module "nfsd".  Maybe modprobing this is enough …  I can't test myself because I would have to reinstall my whole server for this.
Comment: Can you elaborate more, and if you was able to run kernel nfsd in container, then post an answer yourself.


Import a class via template.php or other ways

Question: I'm using Drupal 7 and have this structure:

Lorem Ipsum

...

I want add a class top of this structure. E.G.
**
**

Lorem Ipsum

    ...

**
**

I don't use page.tpl.php files because using Views module. I put this code in template.php but don't working:
function mysite_preprocess_image(&$variables) {
if ($variables['style_name'] == 'node-ortaklar-cv') {
$variables['attributes']['class'][] = 'header';
}

}
Is is possible put a div in structure via template.php or some way? And how? Thanks.
Answer: The code needs to go in node.tpl.php, not page.tpl.php or template.php. Just follow these steps:

If you haven't already, copy the code from node.tpl.php into a file with the same name inside your theme's folder.
Edit the node.tpl.php file and add your markup around the main node div
Flush Drupal's caches (or at least the theme reigstry)

Then your nodes will all be wrapped in the markup you need.
If you just need to do this for a specific content type (I'm going to guess at one called image here), your template file will need to be called node--image.tpl.php. You'll still need the original node.tpl.php file in your theme though, as node template overrides won't work without it.
Comment: thanks. Now, i must copy node.tpl.php files in my theme directory, after create node--mycontenttype-tpl.php files?
Comment: Yep that's the one. Make sure you call the file `node--mycontenttype.tpl.php` (notice the `.` instead of `-`) otherwise it won't work
Comment: Thank you, it's work. Well, how to embed field id in this class? E.g. field_myfield ?


Terminology for determining form and harmonic structure when there are no apparent chords?

Question: There are some songs out there, that seem to not have any chord progressions, the melody and bass line all are in sync and sound great, but there aren't any actual chords. In the song, yet you can tell that's its following some form of structure to make it sound good. Is there a method or name for this?
Example: Michael Jackson's Billie Jean intro, the bass line and a few synth chords, but what if those synth chords were only root notes, and if hypothetically, lets say the whole song was like that entirely- how would the song be classified in key, and tonal center, and how would you even be able to create something like it.
So how can a song be, verse chorus etc. without a chord being played in the background, how are all the instruments that aren't playing chords sound good. In this video I THINK OF YOU BY THE CHANTELLES, you can tell there aren't any chords being played first while in the verse or chorus they somehow follow the other sounds that come before it, but separate instruments playing something that somehow fits that aren't chords.
Comment: "... separate instruments playing something that somehow fits that aren't chords" By that definition of "what isn't a chord", no piece of music for (classical) orchestra contains any chord, because there are no "rhythm section" instruments that play "chords" and nothing else. That idea doesn't make any sense at all. In your Chantelles link, the singers are singing three-part chords, quite apart from what anybody else is playing.
Comment: Could you edit your headline to something describing the contents of your question?
Answer: Here is a rather old example ("Agnus Dei" from the Bach B minor mass in case the link dies).  This is basically just a singer (after the intro) and a violin, not even "in sync" as their lines are alternating/competing with their material and there is a single continuous bass line supporting it (you need to play this over headphones or a stereo since the bass is played without distortion and becomes near inaudible when played over something anemic like laptop speakers).
Now this is not really without harmony, but for one, the underlying chords/harmony changes at a rather fast pace (almost every bass note) and for another it's not even spelled out by the instruments but at best insinuated.  And not even unambigiously so.
This kind of stuff relies on the listeners' habits filling in the rest, like a sketch relies on the viewing habits and cultural background of the observer, more so than a full-blown orchestrated version would.
And sometimes, like an Escher painting, a "full-blown" version of the sketch would not even work because the ambiguities cannot be "resolved" in a consistent manner.
There is a saying attributed either to Mies van der Rohe or Antoine Saint-Exupéry: "Perfection is not achieved when there is nothing that can be added but when there is nothing that can be taken away".  Particularly in music, there are some pieces where neither adding nor taking away stuff works.
Much of pop music has a robust harmonic background and framework which makes it reasonably easy to add quite a bit stuff or take it away without affecting the substance, and so does much symphonic stuff.  But you'll often find that there are certain elements which are essential for any particular rendition of a piece and where you'd say they are not the same if those elements are either left out or masked by too much other stuff.
And some pieces, like you observed, may be whittled down to a degree where there is no longer a solid fixed harmonic spine everything is obviously hanging from.  If it's done smart and intentionally, that may work.
Comment: I don't understand what you are trying to say about the Bach example. There is a perfectly clear and fully harmonized set of chords through the whole piece, played on the organ. If you can't hear them when the solo parts begin, either you need a better sound system or better ears!
Answer: It's pretty common in funk. E.g. Check out "flashlight" or "p-funk" by the band "parliament" just as a couple examples. I think you will hear there's always a chord/tonality being described. I think there is still usually a verse - chorus type separation. It's just that there may be only one chord type played through each section. It might change for the different section.
How can it stay interesting? I think that by listening you could answer that. Maybe a more interesting bass line. Etc. It can allow the other instruments to have more freedom in exploring that tonality.
Answer: In your Chantelles example, there actually are chords playing at all times; perhaps I misunderstood what you meant there.
But even if there's just a bassline throughout with no explicit chords, the bassline will still imply a given harmonic structure (as it does in "Billie Jean"). Even if there were no chords moving above it, it's still clearly in Fs minor:

Even if there were no bassline and only an occasional pitch given in some instrument, our culturally-attuned ears would still try to fit it into a harmonic context.
To (sort of) take it one step further, check out the opening to Wagner's Das Rheingold. It's all just based on an Ef chord; there's no real progression to speak of; but it's still clearly an Ef piece. (Note that some call this a "drone" piece because of the "drone" Ef throughout.)
Answer: You can easily determine form given a melody line only.
Take "Twinkle Twinkle Little Star" as an example. Note-wise, the C major version goes like this:
C-C-G-G-A-A-G--F-F-E-E-D-D-C
G-G-F-F-E-E-D--G-G-F-F-E-E-D
C-C-G-G-A-A-G--F-F-E-E-D-D-C
As shown above, it's clearly in ternary form.
Sing only the melody of the first movement of Beethoven's 5th, and I will tell you that it's still in sonata-allegro form.
Sing only the melody of Celine Dion's "That's the Way It Is", and I will tell you that it's still in verse-chorus form. I will also tell you that it contains a bridge and that she moves the tune up to the subdominant for the last repeat of the chorus.
It's not so easy to determine harmony given a melody only. Take "O Christmas Tree" as another example. This is the start of its melody when it's in F major:
C-F-F-F-G-A-A-A--A-G-A-Bb-E-G-F
I'd stereotypically harmonize it like this:
C-F-F-F-C-F-F-F--D-Gm-D-Gm-E diminished-C7-F
But Vince Guaraldi's harmonization is significantly different and, with its added chord tones, reveals the jazz style that he uses.


How to get intranet uptime (availability reports) from datadog or newrelic?

Question: We are using DataDog and NewRelic to monitor the performance of few DevOps supported systems and we need to provide some uptime reports like:

99.5% up last month (x minutes downtime)
99.1% up last year (x minutes downtime)

While we do have URL monitoring configured on DataDog we were not able to find a way to compute the uptime (only to get an alert when the service is down).
NewRelic is also used but it seems that they have an URL monitoring service which works only on publicly accessible sites, making it useless for 9/10 cases.
Comment: If you report the service down/up times using the New Relic Insights API you may be able to build the report using it.
Comment: I think that with either service you could pull up/downtime statistics and build the report with it, as already mentioned. As far as I know, there is no built in service with datadog or newrelic that will do this for you. Datadog does have a pingdom integration, but as you said, it will only monitor servers that can be accessed from the outside.
Answer: The Monitor section of Datadog now includes a "Monitor status" page for each of the monitor you define (for example the URL monitoring you already have). On this page, you can see by group/scope the monitor history and it shows you the uptime for that monitor.
More to read about this new feature here
It's not yet available as a "report" but that's a good idea!


Upgrade grub to grub2 with MD RAID

Question: I have a machine running Debian 6. Because of some recent changes, I tried upgrading to Grub2 (yes, grub legacy was installed by default). Everything went well (chainloading, reboot) until I started "upgrade-from-grub-legacy". The machine has 2 harddisks which contain two software raid1 - /dev/md0, a small one containing /boot and /dev/md1 using the remaining capacity.
Parted shows me:
Disk /dev/sda: 1000GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system     Flags
 1      512B    512MB   512MB   primary  ext2            raid
 2      513MB   2560MB  2047MB  primary  linux-swap(v1)
 3      2560MB  954GB   951GB   primary  ext3            raid

and for the second disk:
Disk /dev/sdb: 1000GB
Sector size (logical/physical): 512B/512B
Partition Table: msdos

Number  Start   End     Size    Type     File system     Flags
 1      512B    512MB   512MB   primary  ext2            raid
 2      513MB   2560MB  2047MB  primary  linux-swap(v1)
 3      2560MB  954GB   951GB   primary  ext3            raid

The dialog for "upgrade-from-grub-legacy" shows:
[ ] /dev/sda (1000204 MB; Hitachi_HDS721010CLA332)
[ ] /dev/sdb (1000204 MB; Hitachi_HDS721010CLA332)
[ ] /dev/md0 (511 MB; ???)
[ ] /dev/md1 (951308 MB; ???)

but no matter which I select, it fails saying:
/usr/sbin/grub-setup: warn: This msdos-style partition label has no post-MBR gap; embedding won't be possible!.
/usr/sbin/grub-setup: error: embedding is not possible, but this is required when the root device is on a RAID array or LVM volume.

As far as I could guess from various posts, there should be a boot_grub Flag somewhere.
Can I use Grub2 in my current configuration, if yes, how and is it safe to reboot in the current stage?
Comment: Why did you create partitions that start at `512B`?  That is very unusual.
Comment: @Zoredache I did not create those, they were preformatted by the hoster - and btw I think it is next to impossible for me to resize the array.
Answer: Okay, I figured it out.
The problem was that grub2 needs space to save the stage2 loader to - and in my configuration, there was none.
The solution was to shrink Partition 1 on both disks using resize2fs, parted and mdadm by taking out one disk at a time from the RAID.
I shrank 16MB of the front of Partition 1, retried "upgrade-from-grub-legacy", installed to /dev/sda AND /dev/sdb, because the machine may boot from either one. Everything went well, reboot - and it was done.
So, in summary:
Yes, I can use Grub2, but I had to rearrange the partitions to make space for stage2.
Yes, it was safe to reboot as long as "upgrade-from-grub-legacy" had not finished because the chainloader with grub1 was still in place and working.
Comment: Thanks for sharing but, consider following:
There are too many bugs in grub2 related to bootable mdraid-based partitions. Sometimes it just won't work. Google :)

Upgrade grub to grub2 with MD RAID


Why IN OUT parameter returning value without registering for callable statement?

Question: I am invoking pk_adduser.pr_checkuser() from java using CallableStatement which contains two IN parameters and one IN OUT parameter. I have not registered IN OUT parameter using CallableStatement.registerOutParameter(int parameterIndex, int sqlType).
But still i am able to get the output value using IN OUT parameter if the returning value length is same as input value length else i am getting SQL exception like ORA-06502: PL/SQL: numeric or value error.
I am using Java 1.7 and Oracle 12c.
My package like below:
I have used the p_user_login_id parameter but not included in given code, just given piece of code.
create or replace PACKAGE BODY pk_adduser
AS
PROCEDURE pr_checkuser (
      p_first_name          IN       VARCHAR,
      p_last_name           IN       VARCHAR,
      p_user_login_id       IN OUT   VARCHAR);

/

PROCEDURE pr_checkuser (
      p_first_name          IN       VARCHAR,
      p_last_name           IN       VARCHAR,
      p_user_login_id       IN OUT   VARCHAR)
IS

BEGIN
    SELECT user_login_id
    INTO p_user_login_id
    FROM user_account
    WHERE first_name = p_first_name
    AND last_name    = p_last_name;
END pr_checkuser;
END;

My Java code like below:
String getcall = "{call pk_adduser.pr_checkuser (?,?,?)}";
CallableStatement callsts = connect.prepareCall(getcall);
callsts.setString(1, "Ramesh");
callsts.setString(2, "Nuvvula");
callsts.setString(3, "RamN");
callsts.execute();
String user_id = callsts.getString(3);
System.out.println("user_id: "+user_id);

p_user_login_id='RamN' i am passing to IN OUT parameter, select query returns 'RameshN' which is available in Data base and trying to assign to p_user_login_id.
If i pass p_user_login_id='RamN123' its returning 'RameshN' successfully.
I think Passing parameter value's length is the Issue. But my question how can it behave like this ?
Comment: Why declare `p_user_login_id` as `IN` parameter if you do nothing with the value inside your procedure?
Comment: Thanks for reply. I have used the p_user_login_id   parameter but not included in given code, just given piece of code.
Comment: Then please show the actual relevant code
Comment: What JDK are you using? Is it Oracle's? What JDBC driver are you using? Is it Oracle's? If you are using Oracle JDK and JDBC driver, then you need to match JDK version to JDBC driver version to Oracle database version. The [Oracle JDBC FAQ](https://www.oracle.com/technetwork/database/enterprise-edition/jdbc-faq-090281.html#01_02) has information on what versions are compatible. You can also refer to [JDBC Developer's Guide](https://docs.oracle.com/database/121/JJDBC/title.htm) for Oracle 12c. My guess is either you have uncovered an Oracle bug or you are using an incompatible combination.
Answer: Taking a wild guess here, but try this:
String result = "RamN";
String getcall = "{call pk_adduser.pr_checkuser (?,?,?)}";
CallableStatement callsts = connect.prepareCall(getcall);
callsts.setString(1, "Ramesh");
callsts.setString(2, "Nuvvula");
callsts.setString(3,  result);
callsts.execute();
String user_id = callsts.getString(3);

However, the pl/sql code does not make sense to pass in an in/out parameter whose in value is never used.
Comment: Thanks for reply. I have used the pass in IN/OUT parameter but not included in given code, just given piece of code.  I have tried what have suggested but still not working..


Android AudioRecord Configuration does not match recorded Audio

Question: I am intending to record stereo audio on an Android 4.4.2 device. However the audio being recorded via a simple recording App (using AudioRecord) does not match the configuration supplied. I would hope to see error messages in logcat if the device is using default configuration values, but I can see that the supplied values appear to be accepted by AudioHardware, and AudioPolicyManagerBase.
The current configuration for:
recorder = new AudioRecord(Media.Recorder.MIC,
                           sampleRate,
                           AudioFormat.CHANNEL_IN_STEREO,
                           AudioFormat.ENCODING_PCM_16BIT,
                           audioBufferSizeInBytes);

Changing the Media.Recorder.AudioSource has been raised an option for trying to resolve this issue; But this has not changed how the Android stack behaves- Except to (understandably) fail to load the recorder when the configuration is invalid.
Changing SampleRate has shown also produced no visible change in the output- both 44.1kHz, and 16kHz are valid options, however both produce 16kHz audio when examined. The output audio also appears to be one channel of audio upmixed to stereo.
TinyALSA/Tinycap is available to capture the audio, and this appears to behave as expected.
Could this be an issue within the Android Stack? Or is this more likely to be an issue with the code supplied by the OEM?
Answer: The reason for the downmixed audio in this case was that the Speex Codec was being used in the HAL to downmix and de-noise the stereo input.
This was configured under:
<android source tree>/hardware/<OEM>/audio/audiohardware.h

The alternatives to this problem would be to route the audio out of ALSA, and around the android stack via a unix domain stream socket. This would be accessible in the application layer with androids localSockets.


How to use JavaScript replace an inline html element preceded and followed by text with another html element?

Question: I know, this seems like a really simple, straightforward question but bear with me for a minute.
Lets say we have a HTML document that looks something like this:

  <title>My Awesome Example.</title>

World History is fascinating but can also be overwhelming because of its
sheer magnitude. Every historian brings their own lens
to historical interpretation so one must not only know the historical events but
also use reasoning skills to determine when a
historian's perspective is distorting the actual historical record.

Now lets say we want to replace each occurrence of  and replace it with another element and the original element's innerHTML. So the end result would be something like:
<input type="text" id="lens115">
<input type="text" id="reasoning118">

The issue is the element being inline with the text. I had come up with some code that looks something like this:
// Get the element to be replaced
let blankhtml = document.getElementByClassNames("blank-it");
// Get the text we'll use as the ID of our new element
let blanktext = document.getElementByClassNames("blank-it").innerHTML;
// Create a variable to hold input text box code
let inputtext = '<input type="text" id="' . blanktext . '" class="blank-input">';
// Prepend the input box before the blankhtml element
// Remove the old element.

And this is where I get stuck. Because it seems that whether I use insertBefore or removeChild it wants me to specify the parent element. But how can I know this? In the above example it is a simple
 element but what if the code looked something like this:

<title>Something Goes Here</title>

This is a an important fact.

Ideally one should only have a single span in this instance, but we are talking about user entered content, so I can't guarantee there won't be a situation like this.
I'm sure this is still a fairly simple problem to resolve, just slightly more complicated than telling me to use replaceChild, etc. Any thoughts?
Comment: Maybe I didn't quite understand the problem, but have you considered using `outerHTML` to replace the element? You can set the outerHTML of your span with your input HTML code.
Comment: It's `getElementsByClassName` with an `s` and it returns a collection not a single element
Answer: Here's a rough starter for you that replaces each of those spans with an input that has the span's innerHTML as value.
To start with you need to loop over the collection, create a new element to replace each instance with and then use parentNode.replaceChild(newChild, existingChild)
You can dress up the attributes/classes of the new element with whatever you need yourself

document.querySelectorAll(".blank-it").forEach(el => {
    const input = document.createElement('input');
    input.value = el.innerHTML;
    input.classList.add('blank-input');
    el.parentNode.replaceChild(input, el);
});
.blank-input{color:red}

World History is fascinating but can also be overwhelming because of its
sheer magnitude. Every historian brings their own lens
to historical interpretation so one must not only know the historical events but
also use reasoning skills to determine when a
historian's perspective is distorting the actual historical record.

Answer: Have you tried using outerHTML to replace the element, instead of using insertBefore/removeChild?
If I understood correctly, you want to replace your span with an input, correct?
See if the snippet below can help you out:

// Get elements to be replaced
let blankElements = Array.from(document.getElementsByClassName("blank-it"));

blankElements.forEach(blankElement => {
  // Get the text we'll use as the ID of our new element
  let blanktext = blankElement.innerHTML;
  // Create a variable to hold input text box code
  let inputtext = '<input type="text" id="' + blanktext + '" class="blank-input">';
  blankElement.outerHTML = inputtext;
})

  <title>My Awesome Example.</title>

World History is fascinating but can also be overwhelming because of its
sheer magnitude. Every historian brings their own lens
to historical interpretation so one must not only know the historical events but
also use reasoning skills to determine when a
historian's perspective is distorting the actual historical record.


What is ${\cal P}(A ) \cap A$?

Question: I need some clarification
I am not sure but what is :
${\cal P}(A ) \cap  A$ equal to the empty set? For any $A$ ? If not how can we prove it ?
Dir example $A=\{1,2\}$,
${\cal P}(A) = \{ \{1\},\{2\},\{1,2\}, \emptyset \}$.
Then ${\cal P}(A) \cap A = A$ ?
Comment: the intersection is empty. No element of $A$ is in $P(A)$. (notice that $1\neq\{1\}$, $2\neq\{2\}$ and most importantly $A\notin A)$
Comment: Oliver Diaz is right.
Comment: P(A) $\cap \{A\}=\{A\}$ though.
Comment: Yes P(A) ∩ A = A
Answer: Specific Sets are specific sets and the element elements in the sets are elements in the sets.  They are not the same.   $1\in \{1,2\}$ because $1$ is an element in $\{1,2\}$ but $\{1\} \not \in \{1\}$ because $1$ is the number $1$ and $\{1\}$ is the set containing the number $1$.  The set containing the numbers $1$ is not the same thing as the number one and of the two elements in $\{1,2\}$ neither one of them are are the set containing $1$.
If $A= \{1,2\}$ then $A$ is a set with two elements.  They are the number $1$ and the number $2$.  All of its elements are numbers.  None of its elements are sets.
And $P(A) = \{\emptyset, \{1\},\{2\},\{1,2\}\}$.  That is a set with four elements.  They are: a set with no elements, a set with the element $1$, a set with the elements 2, and the set $A$.  All if it's elements are sets.  None of its elements are numbers.
$P(A)\cap A = \{w| w\in A; w\in P(A)\} = ???$.  $A$ has two elements.  They are $1$ and $2$.  $1$ is not an element of $P(A)$.  (Note: $\{1\}$ and $\{1,2\}$ are elements of $P(A)$ but neither of those are the number $1$).  ANd $2$ is not an element of $P(A)$.  So none of the elements of $A$ are elements of $P(A)$.
ANd likewise all the elements of $P(A)$ are not elements of $A$.  So $P(A)$ and $A$ have no elements in common.  SO $P(A)\cap A = \{w|w\in A;w\in P(A)\} = \{w| w$ is an element that is common to both $A$ and $P(A)\} = \{w|w $ does not exist$\} = \{\} =\emptyset$.
....
But that doesn't mean $P(A)\cap A = \emptyset$ always.
Consider $A = \{1,2, \{1\}\}$ that is a set with three elements: the number $1$, the number $2$, and the set $\{1\}$.  And $P(A)=\{\emptyset, \{1\},\{2\}, \{\{1\}\}, \{1,2\}, \{1,\{1\}\},\{2,\{1\}\}, \{1,2,\{1\}\}$ is a set with nine elements all of them sets.  Of the three elements in $A$ and the nine elements of $P(A)$ note that $\{1\}$ is an element the both contain.  And it is the only element they both contain.
So $\{1\} \in A$ and $\{1\} \in P(A)$ and $P(A)\cap A = \{\{1\}\}$.
That's it.
Another example is if $B= \{\emptyset\}$, the set that has a single element, that element being the empty set.  An if $A = \{\emptyset, B\} = \{\emptyset, \{\emptyset\}\}$ then $P(A) = \{\emptyset, \{\emptyset\}, \{B\},\{\emptyset,B\}\} = \{\emptyset, B,\{B\},A\}$.  And
$P(A) \cap A =  \{\emptyset, B,\{B\},A\} \cap \{\emptyset, B\}=$
$\{\emptyset, B\} = A$.
=======
I think the confusion come that if $A=\{babar, tantor, pink honk-honk\}$ is a set containing three elephants, that a student naively thinks that because the set is made of three elephants, that the set must be three elephants.
This is just not the case.  A set is a collection of things and what the set is the idea of the collection.  It is distinct from the things in the collection.
And then I guess the student often finds this complicated and figures it must have hard to understand rules.  But the rules are simple. SETS are collections of things, but the things inside the collections are not the same thing at all and have a completely separate "existence".  $\{A\}\ne A$ and $\{1,2\} \ne $"then numbers $1$ and $2$" and $\{1,2\}$ is not an element in the set $\{1,2,3\}$.  $1$ is an element.  And $2$ is an element. But the set containing $1$ and $2$ is not.
It's not a complicated rule.  It is a simple rule of looking through a microscope and never looking outside the range of the slide.  Ever.
Comment: Wow, that downvote was fast.  I must have an enemy.
Comment: The first sentence *is* true.  The elements of a set and the sets containing the elements of the set are not at all the same things.
Comment: My first sentence was claim that the elements of a set and the set containing the elements of the set are not the same.  There is not and was not any claim whether the elements were or were not sets themselves.
Comment: @Vercassivelaunos: Poor OP, now you are talking about Zermelo Frankel set theory due to an innocent question that fleablood tried to clarify in plain English. I understand the urge for rigor but let's not get all fancy.
Answer: An example where $P(A)\cap A=A$ and $A\neq\emptyset$:
Let $A=\{\emptyset\}$. Then $P(A)=\{\emptyset,\{\emptyset\}\}$, so $P(A)\cap A=\{\emptyset\}=A$.
An example where $P(A)\cap A=\emptyset$:
Let $A=\{a\}$, $a\neq\emptyset$. Then $P(A)=\{\emptyset,\{a\}\}$, so $P(A)\cap A=\emptyset$.
You can also construct situations where $\emptyset\neq P(A)\cap A\subsetneq A$, for instance by letting $A=\{\emptyset,a\}$, $a\neq\emptyset$. Essentially, make $A$ contain subsets of itself as elements.
Comment: Sure, that is how natural numbers are constructed, but I don't think that the OP is ready for that level of abstraction yet.
Comment: @OliverDiaz I don't think it's that abstract. Sets can contain other sets, including subsets of themselves (except of course, they can't contain themselves). This is a kind of pathological example, of course, since you'd probably construct any mathematically relevant sets such that $P(A)\cap A=\emptyset$, but the premises you need aren't that far out.
Answer: ${\cal P}(A)$ is the set of subsets of $A$. One of its elements is $A$. Thus it is correct to write $A \in {\cal P}(A)$, $\{A\} \subset {\cal P}(A)$ and ${\cal P}(A) \cap \{A\} = \{A\}$. This can be disturbing as, in some context, a singleton $\{m\}$ is sometimes simply denoted by $m$.
In your example, the intersection is empty.
Comment: @fleablood What?
Comment: Argh.....  I have *no* idea why I typed $\subset$ instead of $\cap$.  But the OPs question was about $P(A) \cap A = A$ which is not true.  The OP is having trouble with realizition $A \not \in A$ and $\{A\} \ne A$.   $A= \{1,2\}$ and $P(A) = \{\emptyset, \{1\},\{2\},\{1,2\}\}$ and the OP *thinks* but is *wrong* that $1 \in  \{\emptyset, \{1\},\{2\},\{1,2\}\}$ and $2 \in  \{\emptyset, \{1\},\{2\},\{1,2\}\}$ because the OP thinks $\{1\} = 1$ and $\{2\}$ and that is wrong.
Comment: $P(A) \subset \{A\} = \{A\}$ but $P(A)\subset A \ne A$.  And $\{A\} \ne A$.  I think its important to distinguish that and I think that is where the OP is having trouble.
Comment: @fleablood I fully agree with you.
Answer: $P(A)\cap A$ consists of all the elements of $A$ that are also subsets of $A.$ What that is depends heavily on what $A$ is. It could be $\emptyset,$ it could be $A,$ it could be something in between. If $P(A)\cap A=A,$ we say $A$ is transitive.
In order to answer your question, we need to know what $1$ and $2$ are. If the natural numbers are to be viewed as non-sets (aka urelements), then certainly none of them are subsets and $P(A)\cap A=\emptyset,$ and it would be so for any subset of the naturals.
However, a lot of times, we define the natural numbers as sets $0=\emptyset, 1=\{0\}, 2=\{0,1\},\ldots$ in which case $P(A)\cap A$ for $A=\{1,2\}$ is still $\emptyset,$ but the argument is a bit more complicated (for instance, you can notice that both $1$ and $2$ have the empty set as an element, but $A$ does not, so $1$ and $2$ can't be subsets of $A$). And for instance, if we had $A=\{0,1\}=2,$ then $P(A)\cap A=A.$

What is ${\cal P}(A ) \cap A$?


Equivalent linq query syntax

Question: What is the equivalent query syntax for the following overload of GroupBy:
public static IEnumerable<IGrouping<TKey, TElement>>
   GroupBy<TSource, TKey, TElement>(
      this IEnumerable<TSource> source,
      Func<TSource, TKey> keySelector,
      Func<TSource, TElement> elementSelector
)

This question cropped up when trying to write the equivalent query syntax of the following:
var groups =
    products.SelectMany(p => p.Categories,
                    (p, c) => new { Product = p, Category = c })
            .GroupBy(p => p.Category, p => p.Product);

The "normal" query syntax would give back redundant information: Category already given by the Key property:
var groups = from p in products
             from c in p.Categories
             let pc = new { Product = p, Category = c }
             group pc by pc.Category into g
             select g;

Which is equivalent to:
var groups =
    products.SelectMany(p => p.Categories,
                    (p, c) => new { Product = p, Category = c })
            .GroupBy(p => p.Category);

This issue cropped up while answering this question.
Answer: The expression between group and by is the element selector.  You went out of your way to add the information you specifically don't want into that element.  You just need to...not do that.
var groups = from product in products
             from category in product.Categories
             group product by category into g
             select g;

Comment: oh god, I feel dumb. Thanks

Equivalent linq query syntax


A pigeonhole problem from "Conjecture and Proof"

Question: I don't really know how to start this problem at all. I would like a solution or even hints.
"Prove that for every odd integer $n$ there is an integer $i$ such that $n \mid 2^i- 1.$"
The chapter in the book which provides this problem as an exercise is entitled "The Pigeonhole Principle" so I assume that the Pigeonhole Principle will be used in some way. The book is entitled "Conjecture and Proof" by Miklos Laczkovich.
Comment: In Andres Calcedo's answer, the pigeonholes are the numbers $0$ to $n-1$. The pigeons are the numbers $2^i-1$, say $i=1$ to $n+1$. The pigeonhole that the pigeon named $2^i-1$ belongs to is the hole with number the remainder when you divide $2^i-1$ by $n$. Among the $n+1$ pigeons, there must be $2$ that belong to the same pigeonhole, i.e. have the same remainder.
Answer: Consider the numbers $2^1-1, 2^2-1,\dots$ Since there are infinitely many, at least two must have the same remainder modulo $n$. (This is the application of the pigeonhole principle. Naturally, you do not need to consider infinitely many of these numbers to reach the conclusion.)
Say that $i<j$, and that $2^i-1$ and $2^j-1$ have the same remainder modulo $n$. Then $n$ divides their difference, $2^j-2^i=2^i(2^{j-i}-1)$. Now use that $n$ is odd to conclude from this that, in fact, $n$ divides $2^{j-i}-1$.
Answer: Consider the set $\{2^k:k\in \Bbb N\}$. This set is infinite, so by the pigeonhole principle there are $l,m$ such that $l\lt m$ and $2^l, 2^m$ are in the same equivalence class of $\Bbb Z/n\Bbb Z$. Take $i=m-l$ then $2^i\equiv 1(\text{mod}\;n)$.
Answer: HINT: Suppose that $i<k$ and $2^i\equiv 2^k\pmod n$. Then $n\mid 2^k-2^j=2^j(2^{k-j}-1)$. There are only $n$ congruence classes modulo $n$, and there are more than $n$ numbers of the form $2^k$ for $k\in\Bbb N$, so ...


Domain and Codomain determining if it is a function

Question: I am working on a question about domain and codomain. So far, I know that domain is all the $x$ values of the function, and that the codomain is all the possible values that could be in the domain, and I also know that for it to describe a function it has to be a one to one relation. But what I'm not understand is how to read that from a question such as $f: \mathbb{N} \to \mathbb{N}$ where $f(n) = \sqrt{n}$, I don't see where to get the domain and codomain from it.
Thanks!
Comment: A function can also be many to one (it will just not be invertible).
Comment: ok , I am just very confused on what makes the domain and co domain in this question
Comment: See my answer, basically, you have to keep in mind the two golden conditions (no negative numbers in square roots and no division by 0), while adjusting according to the question.
Comment: This [tutorial](https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference) explains how to typeset mathematics on this site.
Answer: Let's consider some definitions.
Definition.  An ordered pair $(a, b)$ is a set of two elements with the property that $(a, b) = (c, d)$ if and only if $a = c$ and $b = d$.
Definition.  Let $A$ and $B$ be sets.  The cross-product of sets $A$ and $B$, denoted $A \times B$, is the set of ordered pairs $$A \times B = \{(a, b) \mid a \in A, b \in B\}$$
Definition.  A relation $R$ from a set $A$ to a set $B$ is a subset of $A \times B$.
Definition.  A function $f: A \to B$ is a relation from set $A$ to set $B$ in such that for every $a \in A$, there exists exactly one ordered pair $(a, b) \in f$.
Definition.  Let $f: A \to B$ be a function.  If $b \in B$ is the unique element assigned to $a \in A$ by $f$, we write $f(a) = b$ and say that $b$ is the image or value of $a$ under $f$.
Definition.  Let $f: A \to B$ be a function from set $A$ to set $B$.  The set $A$ is called the domain of $f$ and $B$ is called the codomain of $f$.  The range, denoted $f(A)$, is the set of images of the elements of $A$. $$f(A) = \{f(a) \mid a \in A\}$$
Note that the domain is the set of input values, the range is the set of output values, and the codomain is a set that contains the set of output values.
*Definition.** The graph of function $f: A \to B$ is the set of ordered pairs $(a, b)$ such that $f(a) = b$.
Note that a function is specified by its domain, codomain, and graph.

Is $f: \mathbb{N} \to \mathbb{N}$ defined by $f(n) = \sqrt{n}$ a function.

We are given the domain $\mathbb{N}$ and codomain $\mathbb{N}$.  If $f$ is a function, then for each $n \in \mathbb{N}$, there must exist an ordered pair $(n, \sqrt{n})$, where $n \in \mathbb{N}$ and $\sqrt{n} \in \mathbb{N}$.  Since $2 \in \mathbb{N}$ and $\sqrt{2} \notin \mathbb{N}$, this is impossible, so $f$ is not a function.
Answer: You could define $f(x) = \frac{1}{\sqrt{x}}$ for complex numbers different from 0, but depending of your problem you can consider only positive real number, natural numbers, rational number, so on. And about the codomain, who it is written on your question is not true, since the multiplicative inverse of the square root of a natural number is not always a natural number, so the codomain cannot be $\mathbb{N}$. And about a function being a relation one to one is not necessaraly true, since $f(x) = x^{2}$ is a function but not one to one, i.e, not injective.
Comment: so does it being a natural number make it not a function or does that only apply to the co domain ?
Comment: If you keep this definition $f:N\rightarrow N$ defined that way, it is not a function. But if you fix that like $f:N\rightarrow R$ it turns out to be a fucntion
Comment: ok I think I am starting to get it , for clarification , the domain in this case would be the natural numbers and the co domain is the f (n)?, if I am wrong please correct me
Comment: As in my answer, the domain may change depending of your context, but the codomain is going to be any set whose contains $f(N)$
Answer: In your case, you have $f:\mathbb{N} \to \mathbb{N}$, $f(n)=\sqrt{n}$.
Here, all natural numbers are valid arguments for the square root(no square roots of negative numbers or division by $0$), so domain will be $\mathbb{N}$. But there is a catch! All natural numbers do not give square roots lying in $\mathbb{N}$. Let us cine back to this after dealing with the range.
However, the co-domain is $\mathbb{N}$ ad given in the function definition.
Now, for the range, note that the function shall map real numbers onto their square roots which also have to be natural numbers. Clearly, the function shall map onto natural numbers which are square roots if other natural numbers.
We can now see that the d domain consists of all natural numbers having natural square roots, while the range of all natural numbers which are square roots of the natural numbers from the domain. But notice that, the all natural numbers are square roots of some or the other natural numbers ( can you see why?).
Symbolically,
$D(f) =\{ n | \sqrt{n} \in \mathbb{N} \} = \{ n^2 | n \in \mathbb{N} \} = \{ 1,4,9,..\}$ and,
$R(f) = \mathbb{N} =$ Codomain$(f)$.
Now, can you see how if we take the function to be $f : \mathbb{R^{*}} \to \mathbb{R^{*}}$, you will have -
$D(f) = R(f) = C(f) = \mathbb{R^{*}}$


Unable to create another box in a column

Question: Bootstrap Code: http://www.bootply.com/rKAlUVLSTA
I'm trying to create a box below the left sidebar but whatever I do, it is always in the white background zone. I do understand that if i add the "leftbar" class elsewhere, it will work but the width has to remain same as the logo background.
Screenshot:
Comment: Please put any relevant code in the question. Not everyone can access external sites, and the links may break over time.
Comment: What Marcelo means is the code that you use for creating the sidebar, you can add code with your question
Comment: I thought it's better to put it in the third party website as it compiles the code too. Next Time. Thank You.
Answer: Here is the solution: http://www.bootply.com/rw2brhxWy7 Basically what you had to do is split up the two into two separate columns within a parent column. I added a margin-top: 20px to be able to distinguish the two.
Relevant code below:

          <button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".sidebar-navbar-collapse">
            Toggle navigation

          </button>
          Sidebar menu

John Doe

Points

 Dashboard

 Innovation

 Redeem

 Settings

      I want to free myself from this white box and be in a new box instead.

Edit: The problem was that now the column did not match the width of the green navbar div. You must remember that bootstrap's CSS will apply a padding of 20px left & right to every column. In order to fix this you should add a custom class to override that. Add the following class:
.noPadding {
    padding-left: 0;
    padding-right: 0;
}

Add this class to the following div:

Edited Solution Bootply: http://www.bootply.com/tLCcdki4uP
Comment: Please put the relevant code in the answer, this helps prevent link rot and maintain the answer quality in the future.
Comment: Please just comment and I will do so,
Comment: Thank You very much @VladBardalez. However, the width (check the logo width) has decrease as you can see. This was the problem :(
Comment: @VladBardalez it's not working. this was exactly what i had earlier :(
Comment: @ElaineByene Please see edit. Add a custom CSS class to override Bootstrap's CSS


Setar dificuldade para uma questão e ao selecionar a dificuldade buscar somente aquelas questões

Question: Boa tarde!
Estou finalizando um Quiz em C# feito em Unity. A dúvida que tenho é, tenho várias questões que gero via um Asset. Porém eu preciso setar as dificuldades para cada uma das questões. E ao clicar no menu na dificuldade Fácil, quero que ele carregue somente aquelas questões que estão com a dificuldade selecionada. Porém ando tendo dificuldade. Vou colocar aqui o código da minha classe que cria a pergunta.
<code>using System.Collections;
using System.Collections.Generic;
using UnityEngine;
#if UNITY_EDITOR
using UnityEditor;
#endif

[CreateAssetMenuAttribute]

public class QuizQuestion : ScriptableObject {
    // Use this for initialization
    void Start () {

    }

    // Update is called once per frame
    void Update () {

    }

    //Campos que receberão dados do arquivo .xml ou .json
    [SerializeField]
    private string pergunta;
    [SerializeField]
    private string[] respostas;
    [SerializeField]
    private int respostaCorreta;

    //Métodos para buscar as perguntas, opções, resposta correta e dificuldade
    public string Pergunta { get { return pergunta; } }
    public string[] Respostas { get { return respostas; } }
    public int RespostaCorreta { get { return respostaCorreta; } }

    //public int Dificuldade {  get { return dificuldade; } }

    public bool Asked { get; internal set; }

    //Validar a resposta
    private void OnValidate()
    {
        if (respostaCorreta > respostas.Length)
        {
            respostaCorreta = 0;
        }

       RenomearObjetoDeAcordoComPerguntaResposta();
    }

    private void RenomearObjetoDeAcordoComPerguntaResposta()
    {
        string desiredName = string.Format("{0} [{1}]",
            pergunta.Replace("?", ""),
            respostas[respostaCorreta]);

        string assetPath = AssetDatabase.GetAssetPath(this.GetInstanceID());
        string shouldEndWith = "/" + desiredName + ".asset";
        if (assetPath.EndsWith(shouldEndWith) == false)
        {
            Debug.Log("Want to rename to " + desiredName);
            AssetDatabase.RenameAsset(assetPath, desiredName);
            AssetDatabase.SaveAssets();
        }
    }
}
</code>
Agradeço desde já!
Comment: Não vejo nenhum atributo relacionado ao nível de dificuldade da `Pergunta`
Answer: Tudo bem?
Você pode criar referência para as questões, com números, por exemplo. Vamos supor que na lista há 30 questões e estão divididos nas 3 dificuldades: fácil(1), médio(2) e difícil(3).
Então o jogador escolhe a dificuldade, logo (pseudo-código):
<code> \\aqui é a variavel que recebe a escolha da dificuldade
 int escolha_do_jogador = escolha;

  \\aqui analisa a escolha, no caso, a escolha é 1, logo, é a dificuldade facil.
 if(escolha do jogador == 1)
    {
       for(int i = 0; i <= 10;i++)
       {
          \\as questões faceis, neste caso, são as 10 primeiras da lista
          exibirQuestao = questao[i];
       }
    }
     \\dificuldade media
 if(escolha do jogador == 2)
    {
       for(int i = 0; i <= 10;i++)
       {
           \\aqui, a dificuldade media está de 10 a 20
          exibirQuestao = questao[i+10];
       }
    }
 if(escolha do jogador == 3)
    {
       for(int i = 0; i <= 10;i++)
       {
          \\aqui, a dificuldade esta no dificil, de 20 a 30
          exibirQuestao = questao[i+20];
       }
    }
</code>
É um código de exemplo, adapte seu código a esse pensamento.


How can I use responsiveslides.js if I'm hosting my site on Google Drive?

Question: I downloaded and implemented the original files from here, but it doesn't play.
Interestingly, when I host my files on Dropbox using pancakeapps, it does work. Is there something preventing me from using the script while hosting with Google?
Answer: Linking
Check this website: CDNJS
Hosts JS's. For ResponsiveSlides: http://cdnjs.cloudflare.com/ajax/libs/ResponsiveSlides.js/1.53/responsiveslides.min.js
Google drive hosting: tutorial
Source (JSFiddle)
<!DOCTYPE html>

  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title>Slider</title>

  <link rel="stylesheet" type="text/css" href="/css/result-light.css">

Donec id elit non mi porta gravida at eget metus.

Donec ullamcorper nulla non metus auctor fringilla.

Pellentesque ornare sem lacinia quam venenatis vestibulum.

Customization
Now you can easly customize by editing the script and css:
available options (js):
 $(".rslides").responsiveSlides({
      auto: true,             // Boolean: Animate automatically, true or false
      speed: 500,            // Integer: Speed of the transition, in milliseconds
      timeout: 4000,          // Integer: Time between slide transitions, in milliseconds
      pager: false,           // Boolean: Show pager, true or false
      nav: false,             // Boolean: Show navigation, true or false
      random: false,          // Boolean: Randomize the order of the slides, true or false
      pause: false,           // Boolean: Pause on hover, true or false
      pauseControls: true,    // Boolean: Pause when hovering controls, true or false
      prevText: "Previous",   // String: Text for the "previous" button
      nextText: "Next",       // String: Text for the "next" button
      maxwidth: "",           // Integer: Max-width of the slideshow, in pixels
      navContainer: "",       // Selector: Where controls should be appended to, default is after the 'ul'
      manualControls: "",     // Selector: Declare custom pager navigation
      namespace: "rslides",   // String: Change the default namespace used
      before: function(){},   // Function: Before callback
      after: function(){}     // Function: After callback
    });

Comment: Thanks. I've pointed to this link instead of my hosted file, but the slideshow still doesn't play. Does Google Drive somehow block the js from running?
Comment: Can you show me the .js url? And the sequence of .js's, are they correct?
Comment: These are the scripts I am pointing to:

`

` Sorry for the formatting; I'm new to coding and this forum.
Answer: Well without being able to the code your using I'm going to assume you have similar code to the answer here. If so, Google Drive hosting has to have https linking for external calls (i.e. jQuery library call; it has to be http,  // and http don't work)


Find which views are using Views PHP

Question: I have a project that is using Views PHP, and I'd like to figure out which views are using PHP from this module. This will help me determine if I can easily remove the dependency on the module.
Is there a query or something else I can use to figure out what views are using this module?
Answer: Using the PHP filter in the fields should require you to use <?php ?> tags as part of the content.
The views data (unless its been exported with features) will sit inside the cache_views table in your DB, so you should be able to reliably find views using PHP filter by searching like so:
SELECT * FROM cache_views WHERE data LIKE '%<?php%';
There is probably a more sophisticated way of finding this.. but hopefully its a good start!
Comment: This is a cache, so data is not guaranteed to be there. For example, if the cache was just cleared, it will be empty.
Answer: Searching cache_views as this answer suggested is a partial solution that helps, but a full solution will include views that are not cached.
In order to do this, you can export views to code (e.g. using the Features module), and search the views for 'php' or php to find Global: PHP fields and sort criteria.
Answer: Searching the views table directly seems to be best approach:
SELECT
  v.vid,
  v.name,
  d.display_title
FROM
  views_display d
JOIN
  views_view v
USING
  (vid)
WHERE
  d.display_options LIKE '%<?php%'
ORDER BY v.name;

+-----+----------------------------------------------+-------------------------------+
| vid | name                                         | display_title                 |
+-----+----------------------------------------------+-------------------------------+
| ID  | VIEW MACHINE NAME                            | VIEW DISPLAY NAME             |
+-----+----------------------------------------------+-------------------------------+

Find which views are using Views PHP


Java8 stream.reduce() with 3 parameters - getting transparency

Question: I wrote this code to reduce a list of words to a long count of how many words start with an 'A'.  I'm just writing it to learn Java 8, so I'd like to understand it a little better [Disclaimer: I realize this is probably not the best way to write this code; it's just for practice!].
Long countOfAWords = results.stream().reduce(
    0L,
    (a, b) -> b.charAt(0) == 'A' ? a + 1 : a,
    Long::sum);

The middle parameter/lambda (called the accumulator) would seem to be capable of reducing the full list without the final 'Combiner' parameter.  In fact, the Javadoc actually says:

The {@code accumulator} function acts as a fused mapper and
  accumulator,
       * which can sometimes be more efficient than separate mapping and reduction,
       * such as when knowing the previously reduced value allows you to avoid
       * some computation.

[Edit From Author] - The following statement is wrong, so don't let it confuse you; I'm just keeping it here so I don't ruin the original context of the answers.
Anyway, I can infer that the accumulator must just be outputting 1's and 0's which the combiner combines.  I didn't find this particularly obvious from the documentation though.
My Question
Is there a way to see what the output would be before the combiner executes so I can see the list of 1's and 0's that the combiner combines?  This would be helpful in debugging more complex situations which I'm sure I'll come across eventually.
Comment: Why not simply `long countOfAWords=results.stream().filter(x->x.charAt(0)=='A').count();`?
Comment: I definitely could have, but I was just playing around with the new mechanisms for experience; this wasn't real code :)
Answer: The combiner does not reduce a list of 0's and 1's. When the stream is not run in parallel it's not used in this case so that the following loop is equivalent:
U result = identity;
for (T element : this stream)
    result = accumulator.apply(result, element)
return result;

When you run the stream in parallel, the task is spanned into multiple threads. So for example the data in the pipeline is partitioned into chunks that evaluate and produce a result independently. Then the combiner is used to merge this results.
So you won't see a list that is reduced, but rather 2 values either the identity value or with another value computed by a task that are summed. For example if you add a print statement in the combiner
(i1, i2) -> {System.out.println("Merging: "+i1+"-"+i2); return i1+i2;});

you could see something like this:
Merging: 0-0
Merging: 0-0
Merging: 1-0
Merging: 1-0
Merging: 1-1

This would be helpful in debugging more complex situations which I'm
  sure I'll come across eventaully.

More generally if you want to see the data on the pipeline on the go you can use peek (or the debugger could also help). So applied to your example:
long countOfAWords = result.stream().map(s -> s.charAt(0) == 'A' ? 1 : 0).peek(System.out::print).mapToLong(l -> l).sum();

which can output:
100100

[Disclaimer: I realize this is probably not the best way to write this
  code; it's just for practice!].

The idiomatic way to achieve your task would be to filter the stream and then simply use count:
long countOfAWords = result.stream().filter(s -> s.charAt(0) == 'A').count();

Hope it helps! :)
Comment: That's one of the best SO answer's I've ever had to a question :) Thanks.
Comment: @JohnHumphreys-w00te Wow thank you very much :-) Glad that it answered your question!
Answer: One way to see what's going on is to replace the method reference Long::sum by a lambda that includes a println.
List<String> results = Arrays.asList("A", "B", "A", "A", "C", "A", "A");
Long countOfAWords = results.stream().reduce(
        0L,
        (a, b) -> b.charAt(0) == 'A' ? a + 1 : a,
        (a, b) -> {
            System.out.println(a + " " + b);
            return Long.sum(a, b);
        });

In this case, we can see that the combiner is not actually used. This is because the stream is not parallel. All we are really doing is using the accumulator to successively combine each String with the current Long result; no two Long values are ever combined.
If you replace stream by parallelStream you can see that the combiner is used and look at the values it combines.
Comment: Thank you for your answer as well; this was definitely easy to use in my situation.


Múltiplos contextos Migrations Entity Framework

Question: Tenho vários projetos e cada projeto possui um contexto.
Gostaria de saber, como utilizar o Migrations para atualizar e gerar apenas um banco de dados desses vários contextos?
Comment: você já leu este artigo: https://msdn.microsoft.com/en-us/data/jj591621.aspx ? Neste artigo ele menciona uma configuração nova do EF6 que permite isto, `ContextKey`,
Comment: Veja se essa thred o ajuda, http://stackoverflow.com/a/10009491/2187618.
Comment: Sim, mas ele nao especifica sobre os varios projetos e contextos.
Comment: E as entidades dos Projetos se comunicam entre si
Comment: faz um tempo já... conseguiu resolver? entendi que cada projeto tem um contexto, mas a estrutura do banco é a mesma usada por todos eles?
Comment: Até onde sei para gerar um único banco todos os contextos devem apontar para o mesmo caminho para poder unificar todas as entidades
Answer: Múltiplos contextos são úteis para estruturar/isolar áreas do projeto; obviamente isso aumenta a complexidade. Então você pode criar cada contexto apontando para a mesma base e realizar o trabalho normalmente.
Answer: Um diferencial do EF6 é que ele foi lançado com a funcionalidade para suportar multiplos contextos. Encontrei algumas respostas para o seu problema :
Tutorial :
http://www.dotnet-tricks.com/Tutorial/entityframework/2VOa140214-Entity-Framework-6-Code-First-Migrations-with-Multiple-Data-Contexts.html
Resposta :
https://stackoverflow.com/questions/21537558/multiple-db-contexts-in-the-same-db-and-application-in-ef-6-and-code-first-migra
Answer: Você de criar apenas UMA conexão, e utiliza ele para os seus projeto. Assim:
<code>Context contexto = new Context();   <----(cria uma conexao)

ProjetoRepository nomeRepositorio = new ProjetoRepository (contexto);
(ProjetoRepository usando a conexao "contexto ")

OutroProjetoRepository nomeOutroReposito = new OutroProjetoRepository (contexto);
(OutroProjetoRepository usando a mesma conexao "contexto ")
</code>
Answer: Como cada contexto é uma instância completamente diferente acredito que isto não seja possível.
A não ser que você crie um contexto que gerencie todos os contextos e englobe em um só.
Comment: Se você acha que não é possível, demonstre o porque. Se acha que é criando um contexto que gerencie os outros, demonstre o que fazer.


Controller Laravel?

Question: Como consigo estilizar um objeto em um array no controller Laravel?
Mapper::marker($marker['lat'],
          $marker['lng'],['label'=> "
".$marker['label']."
"]);

Controller
public function index(){

  Mapper::map(-22.886449, -43.118474,
      [   'marker'=>false,
          'zoom' => 10,
          'draggable' => true,
          'center' => true,
          'cluster' => false,
          'markers' => [
          'eventBeforeLoad' => 'addMapStyling(map);',
          'icon' =>'img/ida_22.png',
          'title' => '166001',
          'animation' => 'DROP'],
      ]);

      $markers = array(['lat' => -22.886449,'lng' => -43.118474,'label'=> 'Veículo 01'],
                       ['lat' => -22.885632,'lng' => -43.118143,'label'=> 'Veículo 02'],
                       ['lat' => -22.883990,'lng' => -43.119513,'label'=> 'Veículo 03'],
                       ['lat' => -22.885734,'lng' => -43.124988,'label'=> 'Veículo 04']);

      foreach ($markers as $marker) {
            //dd($marker['label']);
            Mapper::marker($marker['lat'], $marker['lng'],
                          ['label'=> $marker['label']]);

           Mapper::informationWindow($marker['lat'], $marker['lng'], $marker['label']);
      }

    return view('rastreamento.mapa.mapa');
}

View

    {!! Mapper::render() !!}

O nome do pacote e cornford googlmapper
Perciso que fique assim:
Comment: Você configura o estilo na própria View e no Controller só envia dados!? entendeu
Comment: Eu estou usando aquele pacote do cornford google mapper, que facilita aintegração com mapa da google, pórem toda a logica roda no controller, na view fica apenas uma variavel renderizada e no controller fica como o exemplo abaixo:
              foreach ($markers as $marker) {
                   Mapper::marker($marker['lat'], $marker['lng'],['label'=> $marker['label']]);          Mapper::informationWindow($marker['lat'], $marker['lng'], $marker['label']);
              }
Comment: Coloque o nome do pacote, coloque todo o código, coloque um exemplo de como fica e como você quer que fique estilo ... !!! é pouca informação.
Answer: Lembre-se de não ferir os princípios do padrão de arquitetura MVC.
Controller só coordena a comunicação entre Model e View. Ele não deve conhecer implementações e nem deve conter regras de negócio.
Exemplo:
Você poderia criar um método em seu model com toda a implementação do mapa, retornar como um array, chamar o método do model no controller, passá-lo para view e iterar esse array com o @foreach do blade.
Seu index no Controller ficaria assim:
public function index()
{
    return view('caminho.nome.da.view', ['mappeds' => Mapper::mappedItems()]);
}

Na view
@forelse($mappeds as $mapped)
{{ $mapped->value }}
@else

Nenhum resultado encontrado

@endforelse

Ou, implemente da maneira que desejar.
Lembre-se:
Model só ele conhece implementações de regra de negócio, validação, verificação e etc..
View só conhece a entrada e saída de dados.
Controller coordena o Model e a View invocando metódos, sem conhecer suas implementações.

Controller Laravel?


Word for part of a beat

Question: I'm writing an article describing the musical tradition of a particular culture, but I'm at a loss for general terms for durations shorter than a beat. Simple prolation (such as 2/4 or 3/4) divides a beat into two X's. Compound prolation (such as 6/8 or 9/8) divides a beat into three X's. What is X called?
Background: Mensural notation nomenclature
In the mid-13th century, Franco of Cologne published a groundbreaking musical treatise that led to introduction of mensural notation based on note shapes. Codeswitcher's answer to "Why are only even values used for note duration?" defines several terms associated with mensural notation:

Breve: A brief duration corresponding to a periodic accent phenomenon with a period of about a second or two.
Time: Division of the breve into two or three semibreves.
Semibreve: One-half or one-third of a measure, depending on imperfect or perfect time.
Prolation: Division of the semibreve into two or three minims.
Minim: One-half or one-third of a semibreve, depending on minor or major prolation.

Modern musical notation is descended from this mensural notation. Apart from rounded note heads and fourfold value inflation, the biggest functional change is the loss of "imperfection", or shortening a perfect-time breve to squeeze in a semibreve or shortening a major-prolation semibreve to fit a following minim. Instead, modern notation assumes fully imperfected values and makes perfection (making a note 50 percent longer) explicit by reinterpreting the separator dot that had blocked imperfection in the mensural notation. The converse "alteration" was also dispensed with. This was made practical by the rise in popularity of simple duple meter.
What have you tried?
I've been trying to come up with modern counterparts to the mensural terms. I was considering repurposing the mensural terms (breve meaning 2 or 3 beats, semibreve meaning beat, and minim meaning a half or third of a beat) for relationship with the beat and the Germanic terms (whole note and binary fractions thereof) for durations as written. I dropped this when I remembered that British English uses the mensural terms with modern notation, with their inflated values; for example, Brits call the  half note a minim. Here's what I have:

Measure: A brief duration corresponding to a periodic phenomenon with a period of about a second or two.
Time: Division of the measure into two or three beats. (Common time is two layers of duple time.)
Beat: One-half or one-third of a measure, depending on duple or triple time.
Prolation: Division of the beat into two or three X.
X: One-half or one-third of a beat, depending on simple or compound prolation.

Is there a clear name for this sort of part of a beat? It'd represent a  quarter note in 2/2 (cut time) or an  eighth note in 2/4, 3/4, 4/4, 6/8, or 9/8.
Comment: Is [subdivision](http://www.smccd.net/accounts/mecklerd/MUS202/METER.htm) the term you are looking for?
Comment: I think they're just a whole note, a quarter note, and an eighth note
Comment: There are some glyphs in your post that don't display properly. Are you aware of this, aren't they important to understand your question?
Comment: @Wolf The Unicode musical symbols in the Q look fine on my copy of Ubuntu, but appropriate fonts may not be included with Windows. They're essential only to readers who do not understand the German-derived American English names of note values (whole, half, quarter, eighth).
Answer: The closest term for what you are referring to is subdivisions as the beat is divided in into smaller parts. The term subdivision is always used when talking about note values less than the beat:
For example on the Wikipedia article for Counting Music states:

Triple meter, such as 3/4, is often counted 1 2 3, while compound
  meter, such as 6/8, is often counted in two and subdivided
  "One-and-ah-Two-and-ah"2 but may be articulated as
  "One-la-lee-Two-la-lee".2 For each subdivision employed a new
  syllable is used. For example, sixteenth notes in 4/4 are counted 1 e
  & a 2 e & a 3 e & a 4 e & a, using numbers for the quarter note, "&"
  for the eighth note, and "e" and "a" for the sixteenth note level.

Along with with the definition of meter and beat:

Most music in the world has a pulse or beat.  Usually, the pulses are organized  into groups, usually from 2 to 5 beats in a group, and are usually regular (the same number of beats repeating over and over, and the beats always the same length).This grouping is the general idea of METER.  Most music derived from
  European sources falls into DUPLE (2 or 4 beats) or TRIPLE meters.
  Beats themselves can be SUBDIVIDED into smaller parts, usually 2, 3,
  4, 6 or 8 even parts (duple or triple subdivisions)

If subdivision alone seems like it's not descriptive enough term you could use first subdivision to refer to the next smaller note value.
Answer: It appears from the previous answer that musicologists call these "subdivisions," but I think drummers call them the "pulse." I.e. '70s R&B has an "8th-note pulse" (represented by 8th notes on the hi-hat).

Word for part of a beat


How can I get this to move to a new directory?

Question: I have tried and it will only put files into the parent folder, not a new folder. i Also cannot get it to also create the folder.
<code>    move_uploaded_file($_FILES['file']['tmp_name'][$i],'upload/'.$i);   }
</code>
Comment: check the permissions
Comment: Give recursive permission to the folder
Answer: An answer from another question. Grant the www-user write access to the folder where you are trying to write to.
<code>sudo chown -R www-data:www-data /var/www/example.com/uploads
sudo chmod -R 770 /var/www/example.com/uploads
</code>
source ~
https://superuser.com/questions/646062/granting-write-permissions-to-www-data-group


How to ignore "-Wunused-result" and "-Wunused-but-set-variable" Errors in Eclipse

Question: recently I got some errors in Eclipse while upgrading to Eclipse 4.2 (Juno) from 3.6 (Helios),
My environment as following:

OS: Ubuntu 12.04 32bit
Eclipse: 4.2 Juno
GCC: 4.6.3

my code as following:
<code>static void doMatch(check_context_ptr ctxt)
{
    char    *cmd, *result;
    int k;//test 20120417
    char sourceName[10];
    asprintf(&cmd, "match %s %d %d\n",ctxt->filename, ctxt->probe_count, ctxt->threshold);
    free(cmd);
    for(k=0;k<10;k++)
        sourceName[k]=ctxt->filename[39+k];
}
</code>
the errors such as the followings:
Description Resource    Path    Location    Type

warning: ignoring return value of 'asprintf', declared with attribute warn_unused_result [-Wunused-result]
warning: variable 「sourceName」 set but not used [-Wunused-but-set-variable]

I know there are all warnings, but in my eclipse they are showed in errors items

I know there are a solution to solve the error by line 60, 64 and 71, such as the following:

I know it is a bad programming style, but I always use this way to test my code, and I am sure the command parameters have a -wall option, and set unused return value flag as warning in code analysis setting.
so anybody know how to ignore the warning errors? How to set the parameter in Eclipse?
Comment: I solved it.
I changed the eclipse all language related environment variable to en_US_UTF-8
Window -> Preference -> C/C++ -> Build -> Environment -> LANGUAGE, LANG, LC_ALL, LC_MESSAGE, etc..
Answer: In reference to Strange diagnostic pragma behavior in GCC 4.6, it's a localized question. so I just do change the language related environment variable to en_US_UTF-8. (Window -> Preference -> C/C++ -> Build -> Environment)
the related environment variable:  LANGUAGE, LANG, LC_ALL, LC_MESSAGE, etc..


CVE-2021-26855 Explanation

Question: I patched on 3/3
This just looks like we were probed and not compromised, can some one please confirm? I'm not sure how to interpret this.
Ran Test-Hafnium.ps1
Contents of CVE-2021-26855.log
#TYPE Selected.System.Management.Automation.PSCustomObject
"DateTime","AnchorMailbox"
"2021-03-02T09:50:56.279Z","ServerInfo~a]@Exchange001.contoso.com:444/autodiscover/autodiscover.xml?#"

edit:
The scan found the following entry

2021-03-02T09:50:56.279Z,5f083d36-1b8a-489b-9bdc-e3859dea08f4,15,1,2106,2,,Ecp,220.127.116.11,/ecp/y.js,,FBA,false,,,ServerInfo~a]@Exchange001.contoso.com:444/autodiscover/autodiscover.xml?#,ExchangeServicesClient/0.0.0.0,184.108.40.206,EXCHANGE001,200,200,,POST,Proxy,exchange001.contoso.com,15.00.0001.000,IntraForest,X-BEResource-Cookie,,,,347,362,,,0,0,,0,,0,,0,0,,0,295,0,0,17,0,274,0,0,0,1,0,294,1,274,4,21,21,295,,,,BeginRequest=2021-03-02T09:50:55.983Z;CorrelationID=<empty>;ProxyState-Run=None;FEAuth=BEVersion-1941962753;NewConnection=::1&0;BeginGetRequestStream=2021-03-02T09:50:55.983Z;OnRequestStreamReady=2021-03-02T09:50:55.998Z;BeginGetResponse=2021-03-02T09:50:55.998Z;OnResponseReady=2021-03-02T09:50:56.279Z;EndGetResponse=2021-03-02T09:50:56.279Z;ProxyState-Complete=ProxyResponseData;SharedCacheGuard=0;EndRequest=2021-03-02T09:50:56.279Z;,,,,,,CafeV1

In the following file

"\\exchange001.contoso.com\C$\Program Files\Microsoft\Exchange Server\V15\Logging\HttpProxy\Ecp\HttpProxy_2021030209-1.LOG"

I did not find any entries for email@example.com in any of the log files
Comment: In the case of CVE-2021-26855 exploit, the `AuthenticatedUser` is empty, so you won't find any Administrator entries. You should look around for web shells and archives indicating data extraction, as described in the [Microsoft security blog post](https://www.microsoft.com/security/blog/2021/03/02/hafnium-targeting-exchange-servers/)
Comment: Please add more detail to assist us in answering.
Comment: edited original post @DaveM
Comment: Make sure you have updated your Exchange server to the latest version and applied the security patch.

Follow the steps introduced in the above link especially the part Can I determine if I have been compromised by this activity?

And also refer to the FAQ about this issue here https://docs.microsoft.com/en-us/answers/questions/298536/faq-for-march-2021-exchange-server-security-update.html
Answer: You should review the logs attached to the service accessed - in this instance, the autodiscover logs in the %PROGRAMFILES%\Microsoft\Exchange Server\V15\Logging directory.
More details about what to look for from an attack are available here:
https://www.microsoft.com/security/blog/2021/03/02/hafnium-targeting-exchange-servers/
Under "Attack details".

CVE-2021-26855 Explanation


Interpretation of "scale function" in Foster-Lyapunov drift condition

Question: I'm reading about Markov chains and I'm starting to bump into these drift conditions, and their relationship with a chain's ergodic properties. The drift condition is that there exists a "scale function" $V: X \to [1,\infty)$, a small set $\mathcal{C}$, and constants $\beta \in (0,1)$, $b < \infty$ such that
$$
PV(x) = \int P(x,dy)V(y) \le \beta V(x) + b\mathbb{1}_{\mathcal{C}}(x).
$$
I'm wondering if anyone can give me some direction on how to interpret this $V$ function, especially in the context of analyzing the convergence of MCMC algorithms, and especially if this interpretation can be supported by some results. Right now I imagine that $V$ is some sort of distance function describing how far away from the "good spot" you currently are, as the expected value of $V$ one step in the future decreases, unless of course you are already in this good (small?) set.
Answer: Good question, and personally, I often find myself re-explaining the concept after the umpteenth time I think I have understood it.
Your intuition is pretty much right, in that, $V$ serves as somewhat of a "distance" metric, but not quite. One common way of interpreting $V$ is by thinking of it as a potential energy surface, as describe by Jones and Hobert (2001). They write

It is useful to think of $V$ as a potential energy surface. When the
  Lypanuov condition holds, the chain tends to "drift" toward states of
  lower energy in expectation. In this context, V is called an energy
  function.

Often the small set is described as the set on which $V$ takes small values (this is often called the associated minorization condition). So in essence, when the chain is not in the "small" set, $V$ takes large values and thus has large energy, and so the drift condition forces the average update on the drift function to be smaller, forcing it to go towards the small set. When the chain is in the small set, the term $b$ allows for it to move outside the small set freely.
The trick is to ensure $V$ takes low values in area of reasonable probability under $\pi$, the stationary distribution. A recent paper by Qin and Hobert (2018), explain that if $V$ is "centered" in the sense that it takes small values in areas of high $\pi$ probability, this leads to a "stable" drift function, and yields good bounds on the rate of convergence.
All together, this means that the Markov chain moves towards the places of high probability when it can, and when it is already in an area of high probability, it is free to jump and move about freely. Of course, this then says that the Markov chain explores the state space well, and hence convergence at a reasonable rate.

I have skipped the discussion on the minorization condition, and the concept of coupling, which is also important to this discussion, but you did not ask about that. If you are interested, the Jones and Hobert (2001) lays it out pretty well.


pandas add the months between two dates as a new rows

Question: i have a dataframe like this:
import pandas as pd
data=[[1,'2021-10-01 00:00:00','2021-12-01 23:59:59'],[2,'2022-02-01 00:00:00','2022-05-10 23:59:59']]
df=pd.DataFrame(data,columns=['id','start_date','end_date'])
df

id  start_date           end_date
1   2021-10-01 00:00:00  2021-12-01 23:59:59
2   2022-02-01 00:00:00  2022-05-10 23:59:59

I want to get the months between start and end dates in a new column.
expected output:
data2=[[1,'2021-10-01 00:00:00','2021-12-01 23:59:59','2021-10'],
       [1,'2021-10-01 00:00:00','2021-12-01 23:59:59','2021-11'],
       [1,'2021-10-01 00:00:00','2021-12-01 23:59:59','2021-12'],
       [2,'2022-02-01 00:00:00','2022-05-10 23:59:59','2022-02'],
       [2,'2022-02-01 00:00:00','2022-05-10 23:59:59','2022-03'],
       [2,'2022-02-01 00:00:00','2022-05-10 23:59:59','2022-04'],
       [2,'2022-02-01 00:00:00','2022-05-10 23:59:59','2022-05']]
df2=pd.DataFrame(data2,columns=['id','start_date','end_date','months'])
df2

id  start_date            end_date             months
1   2021-10-01 00:00:00   2021-12-01 23:59:59  2021-10
1   2021-10-01 00:00:00   2021-12-01 23:59:59  2021-11
1   2021-10-01 00:00:00   2021-12-01 23:59:59  2021-12
2   2022-02-01 00:00:00   2022-05-10 23:59:59  2022-02
2   2022-02-01 00:00:00   2022-05-10 23:59:59  2022-03
2   2022-02-01 00:00:00   2022-05-10 23:59:59  2022-04
2   2022-02-01 00:00:00   2022-05-10 23:59:59  2022-05

is there a way to do this?
Answer: Create months periods by period_range and then use DataFrame.explode:
df['months'] = [pd.period_range(s, e, freq='m')
                                        for s, e in zip(df['start_date'], df['end_date'])]

#alternative
#lambda x: pd.period_range(x['start_date'], x['end_date'], freq='m')
#df['months'] = df.apply(f, axis=1)

df = df.explode('months').reset_index(drop=True)
print (df)
   id           start_date             end_date   months
0   1  2021-10-01 00:00:00  2021-12-01 23:59:59  2021-10
1   1  2021-10-01 00:00:00  2021-12-01 23:59:59  2021-11
2   1  2021-10-01 00:00:00  2021-12-01 23:59:59  2021-12
3   2  2022-02-01 00:00:00  2022-05-10 23:59:59  2022-02
4   2  2022-02-01 00:00:00  2022-05-10 23:59:59  2022-03
5   2  2022-02-01 00:00:00  2022-05-10 23:59:59  2022-04
6   2  2022-02-01 00:00:00  2022-05-10 23:59:59  2022-05


How are tennis tournament draws determined?

Question: The draw in the 2016 Australian Open (mens) (womens) does not seem to follow the top-seed vs. bottom-seed format common in tournaments such as the NCAA College basketball tournament. For instance, Serena Williams plays Camila Giorgi who is ranked 35th while  Su-Wei Hsieh who is ranked 90th plays Jelena Ostapenko who is ranked 81st.
How are these draws created?
For the Australian Open?
Other Majors?
Answer: Top players position (32 for Grand Slam Tournaments) are determined by official rankings then other players who enter directly in the main draw are drawn.
So is it possible that the 33rd players (if all the first 32 take part to the Grand Slam) is raffled to play the first round versus draw numer 1.
Here the video of the draw of Australian Open 2016
This rule applies to every tournaments, Grand Slam and minor ones.
In the main draw there are also free slot assigned by tournaments directors (Wild Cards) and for qualifing. Tennis players that do not enter directly in the main draw for rankings can play the qualification. The qualification draws are managed in the same way.
In Auckland 2016 draw you can see that the "last" tennis player direct acceptance (no qualification needed) in Mariana Duque-Marino (ranking 78th), there are 4 slot for qualification players and 2 Wild Cards.
In the past was the ranking rules was not followed so closely: maybe there are players strong on grass and weak on clay so there where a bit of adjustments, but this way generate many controversy so now it is followed the "rankings rules".


C# itext pdf creator Greek fonts not displaying

Question: I am trying to create a pdf which contains greek characters. But it doesn't display them at all. I know its something to do with the font but I can't find out the correct way to print the greek characters.
Here is my code:
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(filename, FileMode.Create));
        iTextSharp.text.Font font5 = iTextSharp.text.FontFactory.GetFont(FontFactory.HELVETICA, 10);

document.Add(new Paragraph("User: " + NameTxt.Value));

If NameTxt.Value uses greek characters then is not displayed at all
Answer: Try that:
string sylfaenpath = Environment.GetEnvironmentVariable("SystemRoot") + "\\fonts\\sylfaen.ttf";
BaseFont sylfaen = BaseFont.CreateFont(sylfaenpath, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Font normal = new Font(sylfaen, 10f, Font.NORMAL, BaseColor.BLACK);

document.Add(new Paragraph("User: " + NameTxt.Value, normal));


Microsoft Outlook 2010 Script won't run after application is closed

Question: I am create an Outlook 2010 rule that runs a script to forward an email, while at the same time removing the original email header information.
The point of this script was to make it seem like the email is being sent from my account but it's actually being forwarded from another account.
The script/rule worked when originally implemented but after I closed out of the application the rule doesn't seem to work.
Is there a reason why closing Outlook 2010 would cause a rule to not to run or could there be another cause? Has anyone else had this issue.
The script I created is below:
<code>Sub SendNew(Item As Outlook.MailItem)

Dim objMsg As MailItem
Set objMsg = Application.CreateItem(olMailItem)

objMsg.Body = Item.Body
objMsg.Subject = Item.Subject
objMsg.Recipients.Add "firstname.lastname@example.com"
objMsg.Recipients.Add "firstname.lastname@example.com"

objMsg.Send

End Sub
</code>
Answer: Client side rules obviously run only when the client (Outlook) is open. Server side rules (Exchange only) always run, but they do not run any scripts and are limited to things like forwarding.
Comment: Right. I re-opened Outlook but the rule wouldn't run. Does it stop altogether when the Client closes at any time. I would think it would turn back on once Outlook opens up again.
Comment: Was that a new mail rule on an Exchange mailbox? When you launch Outlook, the mail has already arrived, so the vent will nto be raised.
Comment: I'm actually sending the email myself to test the rule so Outlook is open and running when I'm sending the email. So far, the only time the rule triggered was when I originally created it. Ever since then it has not triggered.
Comment: Are you saying your rules becomes disabled after you restart Outlook?
Comment: I'm not sure if it is disabled but the rule hasn't even worked since the first time I created it. Since then I've restarted outlook a few times.


How to construct a combined binary classifier?

Question: I have two binary classifiers, a logistic regression classifier (returning probabilities) and a decision tree classifier (returning 1 and 0).
I was wondering if it is possible to combine the prediction of both, but I am not sure what is the strategy. Should I somehow try to find the probabilities from the decision tree classifier and multiply them between them or maybe get the mean predictions divided by two?
Or should I perhaps change the logistic regression probability outputs to classifications (0,1) and try to sort it out somehow this way? I think the latter sounds wrong to me. I assume we would like to use the probabilities, i just don't know how to get the probabilities out of the decision tree classifier :/
By the way I am running this in R using the glm and tree functions repspectively
Answer: When you combine models it's called an Ensemble model. Ensembles use voting, weighting, and or averaging, and there are different algorithms.
(Averaging) Most decision tree functions will give you the probability.  You could just average the two.
(Boosting) Lets say your logistic regression model performs better with the bottom 50% of values of a continuous independent variable, and your decision tree performs better with the top 50% of values of that continuous variable. Your ensemble could choose stronger model for that scenario.
(Voting) As a different example, if you had three models, you could use simple voting, and not use an analysis of the training data (which was done above).
In response to the comment, I've addressed the "how are models combined" with three examples, and provided the term "ensemble."  The "should I" is a different question, which will depend.
Comment: I recommend that you read: J. Kittler, M. Hatef, R. P. W. Duin and J. Matas, "On combining classifiers," IEEE Transactions on Pattern Analysis and Machine Intelligence, vol. 20, no. 3, pp. 226-239, March 1998. You can download this paper freely from internet.
Answer: Make your classification tree algorithm output probabilities, not hard 0-1 classifications. See here on the rationale, quite independently of your ensembling situation.
Then you have two probabilistic classifiers. Simply combine the probabilistic predictions within each class by averaging, possibly using weights.
Comment: Suppose a leaf node has few counts, then the probabilities calculated for that node would change a relatively large amount for a small change in the zero and one "distribution" in that node, hence presumably care must be taken not to overfit. Whereas is logistic regression more smooth here for changes in regressor? Further for predictions is it rare to use a decision tree singly without going the random forest or boosting route?
Comment: @SingleMalt: all very correct. If we use a single decision tree, then we should of course guard against overfitting, e.g., by pruning. (And so should we in logistic regression, e.g., by regularizing, like by using an Elastic Net.) But ensembling is already a good step in the right direction.
Comment: Understood. Logistic regression may seem to have stable transitions of probabilities (when simplistically thinking of the sigmoid graph), but a large regressor coefficient may create large changes in probability for small changes of that regressor. Hence the need for regularization to mitigate this.


convergence in distribution for $N(\theta, 1)$ sample statistic

Question: ${X_1,...,X_n}$ is a random sample of size $n$ from a $N(\theta,1)$ distribution. Find the limiting distribution of $\sqrt{n} (|\bar{X}|−|\theta|)$ when $\theta$ is not equal to $0$. Does it hold if $\theta$ is zero?
So far I have by CLT that $\sqrt{n} (\bar{X}−\theta) \sim N(\theta,1)$.
So let $g(\theta) = \text{abs}(\theta)$ then if the MLE of $\theta = \bar{X}$, the MLE of $g(\theta)$ will be $g(\bar{X})$.
I want to use the delta method to show that this should have a limiting distribution of $N(0, [g'(\theta)]^2\,\sigma^2)$ but I am not sure how to treat the absolute value.
Any advice would be greatly appreciated!
Comment: some symbols are [coming out weirdly](https://i.stack.imgur.com/mgsR6.png) on my machine. Please see the MathJax tutorial: https://math.meta.stackexchange.com/questions/5020/mathjax-basic-tutorial-and-quick-reference
Comment: 1. I've tried to edit your mathematics as best as I can guess you intend. Please check it says what you want it to say. 2. Please see our [help/on-topic] in relation to homework-style questions.
Answer: If $\theta \neq 0$, you can directly apply Delta method as $g$ is differentiable at $\theta$. The limiting distribution is the same as $\sqrt{n}(\bar{X} - \theta)$, i.e., $N(0, \sigma^2)$.
On the other hand, when $\theta = 0$, we cannot use Delta method since $g$ is not differentiable at $0$. But a direct calculation is expedient:
For $x \geq 0$,
\begin{align}
& P[\sqrt{n}|\bar{X}| \leq x] = P[-x \leq \sqrt{n}\bar{X} \leq x] \\
= & P[\sqrt{n}\bar{X} \leq x] - P[\sqrt{n}\bar{X} < -x] \\
\to & \Phi(\sigma^{-1}x) - \Phi(-\sigma^{-1}x) = 2\Phi(\sigma^{-1}x) - 1, \tag{1}
\end{align}
where $\Phi(\cdot)$ denotes the distribution function of the standard normal random variable.  In $(1)$, we used the result $\sqrt{n}\bar{X} \Rightarrow N(0, \sigma^2)$ and the definition of convergence in distribution.
If $x < 0$, then clearly $P[\sqrt{n}|\bar{X}| \leq x] = 0$. Therefore, $\sqrt{n}\bar{|X|}$ converges in distribution to
$$F(x) = \begin{cases}
0 & x < 0, \\
2\Phi(\sigma^{-1}x) - 1 & x \geq 0.
\end{cases}$$
When $\sigma = 1$, the plot of $F$ looks like as follows:
Comment: Thank you so much! Your explanation is extremely thorough and clear. Very easy to understand exactly what is meant.


ASCII character for 0 is differenct in vb6.0 compared to c#

Question: ASCII character for 0 is differenct in vb6.0 compared to c#. I have converted vb6.0 code to c# where i need to send hex data as characters in port communication.
C# - Comm1.Write('/0').ToString() --> gives char as /0.
VB6.0 - mscomm.Output(char(0)) ---> give '' space .
Similarly for  7  c#--> gives '/a' as character
vb 6.0 --> gives as . black dot
Anyone can suggest me why this difference occurs in both as ASCII coding is same
Comment: Try `(char)0` or `(char)a`, you are not comparing apples to apples.
Comment: What is char in vb6, I thought the keywords were chr and chrw in vb6.  Is char a custom function in your vb6 code?  If so show that code.
Comment: `'/0' ` ? Some code that is close to compilable would help with understanding the problem.
Comment: `vbNullChar` is a prefined constant you should be using.  But your C# snippet sends a "/" and then a "0" so of course that's the result you would get.  As hinted at above you probably meant to use `\0` the escaped NUL character in high-obscurity languages like C#.
Answer: VB6 codes everything in ANSI, this is the reason why you're getting question marks and unexpected characters.
Comment: Ya , yup u r right  so i used  Microsoft.VisualBasic.Strings.Chr for converstion in c# .But from 0 to 10  decimal value it gives me difference between both c# and vb 6.0 . After 10 they give me same char output.  Can u show me an example of similar converstion in c# and vb 6.0 for 0 decimal or 7 decimal   . Thanks in advance


Guitar blues soloing- Minor/Major

Question: I've been trying to get myself into blues improvisation.
Main thing to hold on i found were the 5 boxes

Main box with root on 1st (Minor box)
Albert king box (Minor box)
BB-king box (Major box)
Claptop box (Minor box)
Mainbox with root on 3rd (Major box)

I'v learned how to transition between these boxes but in soloing it does not sound right to go from minor to major boxes and cover your whole neck in a single fluid solo. This only sounds right when leaving a pause between these parts.
Why are there some people learning these transitions and how do i incorporate a solo going from the 1 box up to the clapton box, and from the BB-king box to the 5 box?
Answer: These are pentatonic boxes. Major and minor pent notes are the same - as in A pent has the same notes, exactly, as F#m, it's just that the home note for each is different.Imagine the box between 2nd fret and 5th fret. Start on 6th string, 2nd fret with the pattern, only go to top string 2nd fret = F#m pent. Now start at 6th string 5th fret, end at top string, same fret = A maj pent. I've suggested going bottom - top so it sounds complete in each case. So, same notes, different home place, seemingly two different keys.Stick with that box, but move it up 3 frets. Now we have C maj pent and Am pent.
Soloing needs more than just playing notes in a scalar sequence, but initially, you can switch between these two boxes, 3 frets apart, for soloing in A blues. The lower box will sound sweeter, as it's A maj pent., while the upper will have more edge, using minor notes over the A or A7 chords, but it still works.Sliding from one note in one box to another (on the same string!) in the other box sounds good, and then your hand is ready for that new box.
Without going into much more detail, there are bends to consider, often bending from one pent note to the next, same with slides, hammers, etc. Then there's the missing note which makes pent into blues: the flat 5. In between the third and fourth notes played in min pent is where it lives.
Also consider that often in blues, the minor 3rd is not left as such, but is bent up - sometimes all the way up a fret, sometimes teasingly a little bit. The listener will take it the rest of the way! So, using that, when you do move to the major box, it sounds similar.
Answer: Agree with Tim's answer.
In addition, consider overlaying major and minor boxes for the same root note.  For example, learn to play A major and A minor in more or less the same position during your solos which would mean overlaying the Am and F#m blues boxes.  You'll find a number of blues tropes that way as well as making your transitions between the boxes more fluid.
Also if you don't do this already, learn to transition between any box up and down any string.  This will also increase your fluidity and ease your transitions.
Finally, don't be afraid of pauses.  Pauses are important in both blues and jazz soloing.  As Thelonius Monk once said, "Play the rests."
Answer: I have found by learning my blues licks that are (major, minor or a combo), If I play them at 3 different speeds and texture they will fit into many songs. (sometime the same song)...
I can play the same scale/lick in two different time signature songs and they sound totally and remarkably different...

Guitar blues soloing- Minor/Major