Observation on digit in base $2$ for $3^n$

Question: Below table shows, representation in base $2$ for $3^n$
$$ 3^{00}=000000000000000000001\\3^{01}=000000000000000000011\\3^{02}=000000000000000001001\\3^{03}=000000000000000011011\\3^{04}=000000000000001010001\\3^{05}=000000000000011110011\\3^{06}=000000000001011011001\\3^{07}=000000000100010001011\\3^{08}=000000001100110100001\\3^{09}=000000100110011100011\\3^{10}=000001110011010101001\\3^{11}=000101011001111111011\\3^{12}=010000001101111110001\\3^{13}=110000101001111010011$$
Observation on column from right side
First column shows only $\{1\}$ in repeated pattern, May we call 'prefect symmetry'
Second column shows $\{0,1\}$ in repeated pattern
Third column shows $\{0\}$ in repeated pattern
Fourth column shows $\{0,0,1,1\}$ in repeated pattern
But from fifth column don't show repeated pattern

Question
How to show, 5th column and greater than 5th column don't have repeated pattern?
Comment: For $n$th column there will be a pattern of length $2^{n-2}$. This is because the order of $3$ in the multiplicative group of residue classes modulo $2^n$ is $2^{n-2}$ (assuming  $n\ge3$). May be you simply haven't run the sequence for long enough to see it?
Comment: $3^2$ has one leading $1$, $3^3$ had two leading $1$, $3^4$ has one leading $1$, $3^5$ has $4$ leading $1$, and so on. But after that, $3^n$ has *seemingly* always less than $n-1$ consecutive leading $1$ and it seems, as if there occur true randomness in the occurence of the position of the first zero in the bitstring. The underlying question is here, how good $3^n$ and $2^{n+a}$ can be approximated like: exists one $3^n$ which is $(2^n-1)\cdot 2^a +r$ with $r<2^a$. Reformulated there is an open problem behind this but I tried to find a pattern or some argument by the empirical observations.
Comment: Actually, the sequence of fifth digits should be periodic since it depends only on $3^n\pmod {2^5}$.
Comment: Your data suggests (didn't check) that in the fifth column you will see the pattern $0,0,0,1,1,1,1,0$ repeating.
Comment: @JyrkiLahtonen thanks, i get it, i need to study on residue classes
Comment: This is [the first](https://math.stackexchange.com/q/2460124/11619) thread on the order of $3$ modulo $2^n$ that I happened to find. Probably not the oldest, possibly not the best either.
Comment: Hmm, a nice game... Well, another one, likely without a key: let's look at the number of consecutive leading $1$-bits. being called $m$. Let the exponent at $3$ be called $n$. I was never able to prove, that $m<n$ from very small $n$ on... (But I don't want to distract you from your problem)
Comment: @GottfriedHelms thanks and sorry but I don't understand your game. Can you give one example...
Comment: @GottfriedHelms looks interesting, Looks interesting, can you give me the official link to this problem. You may like this post https://math.stackexchange.com/q/3541695/647719
Comment: In a reformulation this asks for *elementary* means to disprove the Collatz (nontrivial) 1-cycle, and is also connected with the unsolved aspect in the Waring-problem (see wikipedia and/or mathworld) After much fiddling I gave up this representation of the problem and assumed one cannot find "the crucial pattern". But well: why should not people around with better intuition than mine? ...
Answer: It shouldn't be too difficult to realize that $a^k \pmod n$ will eventually always have a repeating pattern as there are only $n$ values of $\pmod n$ there must be a $a^k\equiv a^r\pmod n $ with $r > k$.  And when that occurs $a^{k+i} \equiv a^{r+i}$ for all terms there after.
It's not so obvious (but still true nonetheless) that if $\gcd(a, n) =1$ then if $a^k \equiv a^r$ then $a^{k-1} \equiv a^{r-1}$ so that pattern begins "at the beginning with" $a^0 \equiv a^m \equiv 1$.
So the 5th column has pattern but you just don't have enough samples.  We are looking at $a^k \equiv \pmod 2^5$ so the pattern is at most $32$
Eulers theorem says that $\phi(2^k) = 2^{k-1}$ and $3^{2^{k-1}}\equiv 1$ so the last $5$ digits have a repeating pattern of at most $16$. and if you look the last five digits of $3^{0} $ are $00001$ and the last five digits of $3^{16}$ are ... well you didn't go far enough.
$3^{16} = 101001000011010111010\color{blue}{00001}$.
But the pattern doesn't have to be $16$ long.  It could be something that divides $16$.  ANd in this case $3^{8} = 0000000011001101\color{blue}{00001}$ and the pattern is eight long.
And the pattern is $0,0,0,1,1,1,1,0$
Answer: Contrary to your belief, all columns have a repeated pattern. The period can be longer, this is why you don't see it.
For any $a,b,n$ integer,
$$a^{n+1}\bmod b=(a\,a^n)\bmod b=a(a^n\bmod b)\bmod b,$$ which is a simple recurrence between $a^{n+1}\bmod b$ and $a^n\bmod b$. Thus $a^n\bmod b$ must be a periodic sequence of period at most $b$.
In your case, $b=2^m$ and you only look at the first bit.
If we consider the fifth column, $2^m=32$, the period is $1,3,9,27,17,19,25,11$, with length $8$ (check that $3\cdot11\bmod32=1$), with the leading bits $0,0,0,1,1,1,1,0$.
For the sixth column, modulo $64$:  $1,
3,
9,
27,
17,
51,
25,
11,
33,
35,
41,
59,
49,
19,
57,
43$, length $16$ (and $3\cdot43\bmod64=1$).
Answer: All the columns have a repeated pattern.

For the fifth column from the right, the repeating pattern is "$0,0,0,1,1,1,1,0$".
For the sixth column from the right, the repeating pattern is "$0,0,0,0,0,1,0,0,1,1,1,1,1,0,1,1$".
For the seventh column from the right, the repeating pattern is "$0,0,0,0,1,1,1,0,0,1,0,1,1,1,1,1,1,1,1,1,0,0,0,1,1,0,1,0,0,0,0,0$".

We can prove that every column is periodic.  We do this by showing that the last $m$ columns are jointly periodic for every $m \geq 1$.  It should be clear that if each of the last $m$ columns is periodic with periods $p_1, p_2, \dots, p_m$, that they are jointly periodic with period $\mathrm{lcm}(p_1,p_2, \dots,p_m)$, where $\mathrm{lcm}$ is the least common multiple.  Also, if the last $m$ columns are jointly periodic, each column is periodic (with period dividing the joint period).
The last $m$ columns are the least nonnegative member of the congruence class $3^n$ modulo $2^m$.  There are only $2^m$ such congruence classes.  Consequently, there are only $2^m$ possible different values in the last $m$ columns and so after $2^m+1$ powers of $3$ there is at least one repetition in the last $m$ columns.  If a value in the last $m$ columns is ever repeated, say $3^a$ and $3^b$ have the same last $m$ columns, then the sequence of values between $3^a$ and $3^b$ repeats forever because $3^a\cdot 3$ has the same last $m$ columns as $3^b \cdot 3$, and so on.
This argument allows an initial portion of the powers of $3$ to not be repeated, followed by a forever repeating part.  We now show that the initial, not repeated portion is empty.  Note that $3$ and $2^m$ share no prime factors.  This means $\gcd(3,2^m) = 1$.  By the extended Euclidean algorithm, we can find integers $u$ and $v$ such that $3 u + 2^m v = 1$.  This also says $3u$ is congruent to $1 = 3^0$ modulo $2^m$.  Suppose $3^a$ and $3^b$, $0 < a < b$ are the first pair of powers of $3$ that repeat modulo $2^m$.  Then $3^{a-1} = 3^a \cdot u$ modulo $2^m$ is congruent to $3^{b-1} = 3^b \cdot u$ modulo $2^m$ (by contradiction, we're done, but the constructive version is nearly done also...) and we can walk both of these back to $3^0$ congruent to $3^{b-a}$.  Thus, $3^0$ is the first member of the first period.


How to get URL name in template?

Question: I tried to print this in the template, but it renders blank. Whats the correct way to get URL name in template?
{{ request.resolver_match.url_name }}

I wanted it to highlight something in the top bar (if path is 'admin-stuff' add highlight class).
Comment: Could you show how do you return a response from the view?
Comment: Do you mean the url name, or the url path?
Comment: @rnevius I'm pretty sure the OP means the `name` since there is `request.resolver_match.url_name` provided.
Comment: But then he mentions something about `if path is...`, which got me confused.
Comment: possible duplicate of [Django: How can I identify the calling view from a template?](http://stackoverflow.com/questions/792410/django-how-can-i-identify-the-calling-view-from-a-template)
Answer: In the application settings TEMPLATE_CONTEXT_PROCESSORS must include
"django.core.context_processors.request"

for the request to appear in the template context.

How to get URL name in template?


Improve performance by using drush functions instead of Drupal module functions

Question: I am trying to improve the import performance of a drupal website we are working on.  The site makes use of the queue api to import individual items.  Currently this process is very slow.  I have hear it mentioned that one way of improving performance is to process items using drush rather than having Drupal do it directly.
What our site does is read the contents of a text file and then add each item to a queue for processing.  The queue worker function just takes the information, performs some processing logic and then saves it as a node.
From what I understand we would want to move this queue worker function out of the current Drupal module and into drush.
I have been searching for general background information on how to do this or some introductory tutorials, but have not been able to find anything about using drush to improve performance of resource intensive tasks.  I am a little surprised that there is so little information on this given that it is supposed to improve Drupal performance.
Comment: You could create a drush command for your module, http://drush.ws/docs/commands.html. But to me it sounds like the code itself is slow. Executing it from drush won't gain much performance. If you update your question with the code that is being executed maybe you could get pointers on how to optimize it.
Answer: Queues are defined within Drupal modules, and you can use drush to run those queues:
drush @site queue-list
drush @site queue-run queue_name

Changing the interface to the import code (queue, batch api or a drush command) won't affect drastically the import time.
I'd review the import code to try and optimize it. For example by caching (in memory) any data you may be loading recurringly from the database.
Answer: The reason you have heard that performance is better under Drush when processing queues is that Drush has a concurrent-execution feature that it uses to run different parts of batch processes in parallel.  Running this code on a live server would not necessarily be a good idea, because any "performance gains" that you experienced from using this code would be at the expense of the performance of your front-end.  In other words, Drush does not increase the performance of the processing in terms of CPU cycles needed -- it just arranges things so that more of your CPU cycles can be used all at once, so that the task finishes sooner.
I wouldn't even contemplate trying to do this on your live server unless you already have set up a multiple-machine load balancing system, where multiple servers have concurrent access to the same database.  (The other alternative would be to run the queue at a time when you don't care about front-end performance -- however, if you have a time when not many people are using the system, you probably don't care when the batch process finishes anyway.)  If you do have multiple machines to throw at this problem, you could consider either (a) porting the concurrent-execution functions to a Drupal module (see backend.inc) or (b) making a web service on a separate machine that 'exec's drush queue-run as jonhattan describes.
This would be a little complicated to set up, which is probably why no one has done this yet.  A better way to increase performance would be to analyze what is going on in your batch processes that is slow, and see if you can find any ways to optimize the code so that it uses fewer CPU cycles.  This would result in an actual performance increase, which would be preferable to a complex system that processed a slow batch process efficiently.


How to display pop-up message after get coordinate xy of an image using jquery?

Question: I have 1 problem..I had to do drag n drop an image..then get the position of image after drop...Then, when I drag it and get the position, I need to display a pop up message using jquery..Can anyone help me? Please show me the demo and clear solution because Im new in jquery..Thank you guys!!
This is my code of dra,drop n get coordinate..now , I want to add the pop up message after get the position..In the pop up message, I want to add -->name your location and can be saved in database.
   $('#dragThis').draggable({
    cursor: 'move',        // sets the cursor apperance
    containment: '#dragThis2',
    drag: function() {
    var offset = $(this).offset();
    var xPos = Math.abs(offset.left);
    var yPos = Math.abs(offset.top);
    $('#posX').text('x: ' + xPos);
    $('#posY').text('y: ' + yPos);
    },
    stop: function(event, ui) {

    // Show dropped position.

    var Startpos = $("#dragThis").position();
    var Stoppos = $(this).position();
   //
    $("#dragThis").val((Stoppos.left - Startpos.left));
    var left = Math.abs(Stoppos.left);
    var top = Math.abs(Stoppos.top);
    $('#posX').text('left: ' + left);
    $('#posY').text('top: ' + top);
    }

    });

How to add the pop up message in my code?Please...anyone?
Comment: [What have you tried?](http://www.whathaveyoutried.com)
Comment: I've edit the latest post...Please help me!! @JamesMontagne
Answer: You can use an alert, like this:
alert('xPos: ' + xPos + ', yPos: ' + yPos);

You would want to put it in your stop callback function. Read the values back from the DOM elements you wrote them to, or better yet, define xPos and yPos outside the drag function so you can access them in the stop callback.
If you want something more fancy, there are numerous, well-documented jQuery plugins for modal dialogs.
This is the plugin I usually go with: http://jquery.malsup.com/block/
You can also look into the jQuery UI Dialog
When using block UI, you set your message like this:
$.blockUI({
   message: 'Set any message here as a string'
});

Comment: If I have this code:$(document).ready(function() {
    $('#demo1').click(function() {
        $.blockUI({ message: $('#loginForm') });

        setTimeout($.unblockUI, 2000);
    });
});
       How do i change what to put in it??
Comment: ok,how about in my message I want to put message like this--->Set a location. Beside the message I want to put a textbox..How to do that?
Comment: ok, I've seen the demos.is there any plug in or something I have to include in my visual studio 2008 before I proceed using $.blockUI? or I can just simple take the code?
Comment: You need to include the `jquery.blockUI.js` file in `script` tags.
Comment: If I used this code---> alert('Name a location: '); how do I want to put a text box beside it?
Comment: how do I want to edit the promp? For example I want to change the ok button to save button and want to shorten the length of the text box as in the link above??
Comment: If you want control over the prompt, I recommend using `blockUI` instead of the built-in `prompt`
Comment: If use this code--->$.blockUI({
   message: 'Set any message here as a string'
});   how can I edit or add text box in it??
Comment: Please see the first demo as I posted before. It shows how to accept an input
Comment: do u know to make my code on my post works with this code...I took from the demo link that u gave---> $(document).ready(function() {
        $('#demo1').click(function() {
        $.blockUI({ message: $('#loginForm') });

        setTimeout($.unblockUI, 2000);
    });
    });


How to compare fitted survival model with covariates vs. Kaplan-Meier?

Question: How would one ideally compare fitted survival models with covariates vs. a Kaplan-Meier with a goal of getting an idea of whether the survival model describes the data well.
E.g. in an example like this, you might get the impression that an intercept-only exponential model might be okay:
set.seed(1234)
sim <- tibble(patient=1:100, cov=0.66*log(seq(0.1, 1.09, 0.01))) %>%
  mutate(x = rweibull(n=100, shape=0.7, scale=exp(0.5+cov)),
         c = 2-seq(0, 1.98, 0.02),
         time = pmin(x,c),
         event= 1L*(x<=c))

survfit1 <- survreg(Surv(time=time, event=event) ~ 1, dist="exponential", data=sim)

plot(survfit(Surv(time=time, event=event) ~ 1, data=sim))

curve(1-pexp(q=x, rate=exp(survfit1$coefficients[1])), 0, 2, col="red", add=T)

However, once there's covariates and esp. once they correlate with duration of follow-up (shift in population over time), it kind of feels like one ought to take that into account.
Should I predict a survival curve for each patient and then average them, with each patient patient contributing until their censoring time?! I'm trying to figure this out and had not found the answer (perhaps looking in the wrong places?).
Comment: not sure but might the continuous ranked probability score $CRPS(F_i,y)=\int_\mathbb{R} ( F_i(x) - \mathbb{1}(x \ge y) ) ^2 dx$ be an option if you have the observations y and the (cumulative) probability predictions F_i. Then you could compute the expectation over y and whichever model i has a lower crps, is better.
Answer: You can calculate the residuals from the accelerated failure time model fitted by survreg() and compare them with the assumed distribution. You will need to account for the fact that residuals for censored event times are also censored. Hence, you typically compare the Kaplan-Meier estimate of the residuals with the survival function of the assumed distribution. Here are examples of this procedure.
Comment: Question: can you see the Kaplan Meier estimator and the fitted survival model to the observations via the continuous ranked probability score? (Maybe ignoring censoring for a second). Is this a valid route? How would that differ from the residual approach ? How does it exactly work?
Answer: Targeted goodness of fit assessment as Dimitris has stated is usually preferred.  Another example is here.
When there are only one or two covariates you can compare model estimates of survival probabilities at fixed times when overlapping moving windows of corresponding Kaplan-Meier estimates, with smoothing of the K-M estimates from each window.  This is shown here.
In terms of comparing non-covariate-adjusted K-M estimates with model-based estimates, you can get a predicted survival curve for each person, and average these curves.  You don't need to do any kind of subsetting with regard to censoring.
In the case where one is worried about the fit of one categorical predictor in a Cox model, such as treatment, and you think the fit is OK for all the other covariates, you can show estimated survival curves for each level of the categorical predictor, adjusting all the other covariates to constants such as medians and modes.  Then do the same but this time stratify on the categorical predictor instead of modeling it as a covariate.  This is "adjusted K-M curves" as shown here.
A better approach is to specify a Bayesian model that allows for departures from assumptions by adding more parameters, but putting priors on those added parameters to tilt them towards what you hope is true.  For example you could have departures from proportional hazards that have a skeptical prior to reduce overfitting when the number of events is not large.  The Stan survival analysis system is state-of-the-art.


How to deal with slow HTTP clients?

Question: Every now and then a bunch of really slow HTTP clients decide to suck down pages off my web site. This is bad because when enough of them do this, it dramatically lowers the number of free Apache processes available to handle requests from the rest of the world. I don't know if it's some lame DDoS attack or just really slow clients.
In years gone by, I know that lingerd was a solution to this problem. But there doesn�t appear to be much activity around it these days. In fact, the lack of a lingerd package in Debian (there is an old unofficial packagae) suggests that there are better methods.
I've been using mod_limitipconn to partly deal with the problem, but I need to keep that number high enough that it doesn't penalize normal browsers. That makes it a sort of half-assed solution.
It occurs to me that I could put Squid  in front of Apache, but that seems a little heavyweight. Or maybe my impressions of Squid are skewed.
Anyway, I'm looking for ideas or pointers to the obvious thing I've missed.
Ideas?
Answer: If it was a DDoS attack you would seem many such connections from multiple locations. You don't give any stats in your question so we can not really judge.
If many of the slow requests are coming from the same location, especially if they are for a large object, it could be that you have people opening many many connections using a download manager.
If you are not locked into Apache for specific reasons you could consider a move to a server that is based on an event driven architecture rather than a threat/process based one, such as nginx. These allow the number of concurrent connections to scale much more efficiently as each basic request requires very little by way of extra resource (particularly RAM) - though the scalability on requests for scripted resources can vary a lot depending on your setup, getting the efficiency of modPHP (unless you already run it in (faast)CGI mode) can be more work to setup for instance, and of course you might be using other modules/features not well supported away from Apache.
You could also just allocate more RAM and increase the maximum number of Apache processes/threads.
A mid-way between those two solutions is that if the slow requests are for static resources you could use light-weight web server to serve the static content (in much less RAM than Apache would) and proxy the scripted requests (and other the require the extra features other than just serving a file) to Apache's setup. Many large heavily loaded sites operate in a similar manner to this.
Off the top of my head I do not know of a method that limits the amount of time a single request can take - this would probably not solve your problem anyway because in both a DoS situation or in the case of download managers a new connection will immediately be attempted.
Comment: So, david you mean to say i should use NGINX in front of appache to sort out this problem.
Comment: Possibly, but it depends on details you should add to your question: what are the long running/slow requests actually requesting? Scripted responses, static files or a mix (if so what sort of mix)? Where are they coming from? The same location, different locations but several from each, or apparently randomly distributed?

How to deal with slow HTTP clients?


Changing displayed data based on a state of a variable in Vanilla JS

Question: im doing this simple excercise, and Im stuck on the JS part. I have a timeframe variable, and everytime you click one of the buttons (daily, weekly, monthly), timeframe changes it's value - and I want the displayed data to change with it. I have seen another solution to this problem, where on every button click the whole data is refetched, but I want data to be fetched only once, when the page loads - if that makes sense. Below is my code:
<code>const title1 = document.getElementById("title-1");
const title2 = document.getElementById("title-2");
const title3 = document.getElementById("title-3");
const title4 = document.getElementById("title-4");
const title5 = document.getElementById("title-5");
const title6 = document.getElementById("title-6");

const time1 = document.getElementById("time-1");
const time2 = document.getElementById("time-2");
const time3 = document.getElementById("time-3");
const time4 = document.getElementById("time-4");
const time5 = document.getElementById("time-5");
const time6 = document.getElementById("time-6");

const last1 = document.getElementById("last-1");
const last2 = document.getElementById("last-2");
const last3 = document.getElementById("last-3");
const last4 = document.getElementById("last-4");
const last5 = document.getElementById("last-5");
const last6 = document.getElementById("last-6");

const daily = document.getElementById("daily");
const weekly = document.getElementById("weekly");
const monthly = document.getElementById("monthly");

let timeframe;

const timeframes = [
  { element: daily, name: "Daily" },
  { element: weekly, name: "Weekly" },
  { element: monthly, name: "Monthly" },
];

timeframes.forEach((item) => {
  item.element.addEventListener("click", () => {
    timeframe = item.name;
    checkTimeframe();
  });
});

const checkTimeframe = () => {
  if (timeframe === "Daily") {
    weekly.classList.remove("chosen");
    monthly.classList.remove("chosen");
    daily.classList.add("chosen");
    return;
  }
  if (timeframe === "Weekly") {
    daily.classList.remove("chosen");
    monthly.classList.remove("chosen");
    weekly.classList.add("chosen");
    return;
  }
  if (timeframe === "Monthly") {
    weekly.classList.remove("chosen");
    daily.classList.remove("chosen");
    monthly.classList.add("chosen");
    return;
  }
  console.log("wrong name");
};

async function load() {
  const json = await fetch("/data.json");
  const data = await json.json();
  console.log(data);

  timeframe = "Daily";
  checkTimeframe();

  const titlesFromDOM = [title1, title2, title3, title4, title5, title6];
  let titlesFromJSON = data.map((item) => item.title);

  const currentFromDOM = [time1, time2, time3, time4, time5, time6];
  const lastFromDOM = [last1, last2, last3, last4, last5, last6];

  for (let i = 0; i < titlesFromDOM.length; i++) {
    titlesFromDOM[i].textContent = titlesFromJSON[i];
  }

  // if timeframe daily:
  if (timeframe === "Daily") {
    for (let i = 0; i < currentFromDOM.length; i++) {
      currentFromDOM[i].textContent = data[i].timeframes.daily.current + "Hrs";
      lastFromDOM[i].textContent =
        "Last day - " + data[i].timeframes.daily.previous + "Hrs";
    }
  }

  // if timeframe weekly:
  if (timeframe === "Weekly") {
    for (let i = 0; i < currentFromDOM.length; i++) {
      currentFromDOM[i].textContent = data[i].timeframes.weekly.current + "Hrs";
      lastFromDOM[i].textContent =
        "Last week - " + data[i].timeframes.weekly.previous + "Hrs";
    }
  }

  // if timeframe monthly:
  if (timeframe === "Monthly") {
    for (let i = 0; i < currentFromDOM.length; i++) {
      currentFromDOM[i].textContent =
        data[i].timeframes.monthly.current + "Hrs";
      lastFromDOM[i].textContent =
        "Last month - " + data[i].timeframes.monthly.previous + "Hrs";
    }
  }
}

window.addEventListener("load", load);

</code>
Help appreciated!
Comment: do you have a sandbox example that can be tested against?
Answer: Posting the html structure and data structure will help. However from the posted code. The first thing I would do is to retrieve the parent of the timeframe elements and apply the eventlistener there. The listener handler function will then use the event.target object to determine the clicked timeframe element [I imagine that the elements have a common parent]. I will draw a relationship between the display element and the data. Again if the display elements have a common parent I will use a querySelectorAll to retrieve them as a nodelist, updating the elements using the data based on the identified relationship and the clicked timeframe element.


Trigonometric functions

Question: I wonder how does a WolframAlpha get this relation where input is a LHS and output is RHS:
$$\cos^2(x)\cos(2x) = \tfrac{1}{4}\cos(4x) + \tfrac{1}{2}\cos(2x) + \tfrac{1}{4}$$
Comment: Express $\cos^2(x)$ in terms of $\cos(2x), \sin(2x)$ and then use product-to-sum.
Comment: Are you asking how to prove that equality?
Comment: Yes. I need to know how to get RHS out of LHS. I tried to use the double angle trigonometric identity and it only got more complicated...
Comment: How Alpha gets it is an interesting question. I don't know, but it is likely not the way a human should approach it.
Answer: \begin{align*}
\cos^2(x)\cos(2x) &= \frac{1}{2}(1+\cos(2x))\cos(2x)\\
&= \frac{1}{2}\cos(2x) +\frac{1}{2}\cos^2(2x) \\
&= \frac{1}{2}\cos(2x) + \frac{1}{4} + \frac{1}{4}\cos(4x)
\end{align*}
by two applications of the double angle formula.
Answer: Hint
$$cos^2x=\frac{1+cos(2x)}{2}$$
$$cos^2(2x)=?$$

Trigonometric functions


How do I get the value of a soup.select?

Question:
Google

How do I grab the value of the a tag (Google)?
print soup.select("h2 > a")

returns the entire a tag and I just want the value. Also, there could be multiple H2s on the page. How do I filter for the one with the class hello-word?
Answer: You can use .hello-word on h2 in the CSS Selector, to select only h2 tags with class hello-word and then select its child a . Also soup.select() returns a list of all possible matches, so you can easily iterate over it and call each elements .text to get the text. Example -
for i in soup.select("h2.hello-word > a"):
    print(i.text)

Example/Demo (I added a few of my own elements , one with a slightly different class to show the working of the selector) -
>>> from bs4 import BeautifulSoup
>>> s = """
Google

...
Google12

...
Google13
"""

>>> soup = BeautifulSoup(s,'html.parser')

>>> for i in soup.select("h2.hello-word > a"):
...     print(i.text)
...
Google
Google12

Comment: That worked! Thank you.

for c in soup.select("h2.hello-word > a"):
    callSign = c.get_text('href')

Why would that not work?
Comment: Because `href` is not text , its an attribute on the element `a`, use `c['href']` .
Answer: Try this:
>>> from bs4 import BeautifulSoup
>>> soup = BeautifulSoup('
Google
', 'html.parser')
>>> soup.text
'Google'

You also can use lxml.html library instead
    >>> import lxml.html
    >>> from lxml.cssselect import CSSSelector
    >>> txt = '
Google
'
    >>> tree = lxml.html.fromstring(txt)
    >>> sel = CSSSelector('h2 > a')
    >>> element = sel(tree)[0]
    >>> element.text
    Google

Comment: This example doesn't use `soup.select`.


Add cck field as scoring factor to drupal standard search

Question: So, by default there are four scoring factors in drupal:

relevance of keyword
recency
number of comments
number of page views

I'd like to be able, to control relevance of specific cck-fields.
In my case, i've got a cck field (computed field), where all relevant search-data is getting summed up.
I'd like to be able to give this special field a higher relevancy to the search results than anything else.
Is there a possibility to do this?
Answer: Implement hook_update_index in a way that calls search_index. The source code of search_index tells you how the $text argument is analyzed. From a quick look at the source, I would wrap the field content in
 tags. Not that the string only applies to searching, not to rendering. So it does not need to represent the actual structure of the node.


texto linkados e sublinhados no edge

Question: Olá, estou editando umas páginas em C#, e tenho uma página de validação onde serão listados algumas opções de radiobuttons com os dados para confirmação.
O problema é que quando é listados números de CPF eles ficam linkados e sublinhados no Edge.
Já usei o text-decoration:none; em todas as tags mas só funciona em um dos radiobutton.
Segue imagem:

Segue código:

          <asp:RadioButton runat="server" ID="rdOpcao1" GroupName="Opcao" ForeColor="#464a51" Font-Size="14" style="text-decoration:none;"/>

      <asp:RadioButton runat="server" ID="rdOpcao2" GroupName="Opcao" ForeColor="#464a51" Font-Size="14" style="text-decoration:none;" />

      <asp:RadioButton runat="server" ID="rdOpcao3" GroupName="Opcao" ForeColor="#464a51" Font-Size="14" style="text-decoration:none;" />

        <asp:RadioButton runat="server" ID="rdOpcao4" GroupName="Opcao" ForeColor="#464a51" Font-Size="14" style="text-decoration:none;" />

</asp:PlaceHolder>

Comment: Camila, poste seu código completo para ficar mais fácil de identificar. Esses radios tem labels vinculados a eles para exibir o texto? No exemplo, você está setando o `text-decoration:none` direto no radio e não na tag de texto
Comment: Uma dica, poste sempre seu código [aqui](https://jsfiddle.net/), clique em "Save" e poste o link da URL, te garanto que dessa forma você receberá sempre respostas  rápidas.
Comment: Valeu Jorge!!https://jsfiddle.net/2jvk3o5x/
Comment: Minha grande dificuldade é que o labels não ficam explícitos no código, apenas a chamada do c#
Comment: No caso, é preciso saber aonde está escrito esses textos para então pegar a classe/id e declarar a regra no css. Faz o seguinte, inspecione esse elemento na página e veja o elemento que  está escrito o texto e pegue a classe  e aplique a regra no css. Se tiver dificuldade, poste o print aqui nos comentários.
Comment: é, ta vindo dentro de um link, mostra a saída que aparece no navegador, o compilado
Comment: O !importante também não funcionou.
Answer: Camila, como mencionado acima, é preciso saber aonde está escrito esses textos para então pegar a classe/id e declarar a regra no css. Possivelmente está vindo dentro de um link, faça o seguinte no css: .opcoes2 table a {  text-decoration: none;} e veja o resultado.
Comment: Usei esse css, mas não deu certo                                                .opcoes2 label {

            text-decoration:none;
        }
Comment: Pode ser que tenha alguma outra regra sobrescrevendo essa,tente acrescentar o `important` . Faça assim: `opcoes2 table label { text-decoration:none !important; }`
Comment: Já tentei também porém não funciona

texto linkados e sublinhados no edge


Test for significance of unexpected non-linear trend

Question: How can I test whether there is a significant non-linear effect of a continuous predictor on a continuous DV?
Here's my situation. I ran a simple linear regression and found a significant effect of a predictor (predictor2 below).  However, when I plot my dv against that predictor, the trend does not look linear - in fact it looks like the dv has two local maxima.  When I submitted these findings to a journal, reviewers commented that I should explore the possible statistical significance of this apparent non-linear effect.  The effect was not expected and so I do not have a particular non-linear model to test here.  I am just looking for an appropriate off-the-shelf technique of first call to use in a situation like this.  Ideas?
For reference, my data look like this:
> D[1:10,]
   sid      posttest      pretest       predictor2      predictor3       predictor4        predictor5
1    2          0.75         0.75        0.8823529      1.00000000        0.8888889                18
2    3          1.00         1.00        0.8666667      0.06666667        1.0000000                16
3    5          1.00         1.00        0.9000000      1.00000000        0.9047619                21
4    6          0.75         0.75        0.3333333      0.93333333        0.9375000                16
5    7          0.50         0.75        0.8750000      0.87500000        0.8333333                18
6    8          0.75         1.00        0.5000000      0.50000000        0.8823529                17
7    9          1.00         0.50        0.8823529      0.58823529        0.4444444                18
8   10          1.00         0.50        0.8750000      0.87500000        0.5882353                17
9   13          0.75         0.75        0.7777778      1.00000000        0.8947368                19
10  15          0.50         0.25        0.8666667      0.46666667        0.8125000                16
...

The linear regression model and its output look like this:
> lmA <- lm( posttest ~ pretest + predictor2 + predictor3 + predictor4 + predictor5, data=D )
> summary( lmA )

Call:
lm(formula = posttest ~ pretest + predictor2 + predictor3 + predictor4 + predictor5, data = D)

Residuals:
     Min       1Q   Median       3Q      Max
-0.68810 -0.11853  0.05159  0.13589  0.36904

Coefficients:
                Estimate  Std. Error   t value  Pr(>|t|)
(Intercept)     0.773645    0.106033     7.296  8.45e-13 ***
pretest         0.292674    0.030905     9.470   < 2e-16 ***
predictor2      0.063541    0.024557     2.588   0.00988 **
predictor3      0.005529    0.026369     0.210   0.83398
predictor4      -0.026421   0.065049    -0.406   0.68474
predictor5      -0.009412   0.005010    -1.879   0.06070 .
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Residual standard error: 0.1801 on 665 degrees of freedom
Multiple R-squared:  0.1298,    Adjusted R-squared:  0.1232
F-statistic: 19.83 on 5 and 665 DF,  p-value: < 2.2e-16

Finally, here is the plot that gave rise to the reviewer comment. Note that binned data with bubbles were used, with bubble diameter indicating number of data rows in each bin, instead of a scatterplot because there are only 5 levels of the dv (0.0, .25, .5, .75, 1.0) so you can't see anything at all with a scatterplot.  Reviewers commented that bins could be arbitrarily chosen to make the linear trend look more persuasive, which is true, but binned data still has to be used for the above reason I think.
Comment: @MichaelMayer There's not just discreteness; the variable is bounded. Clearly the boundedness has the potential to impact linearity (it can't remain linear as you approach the bounds), equality of variance (variance must shrink if the mean approaches one of the bounds) and anything approaching symmetry (it will tend to become skew as you approach bounds). This seems made for GLMs.
Comment: @Glen_b: That's indeed true. Starting from scratch, I would also try to go for an appropriate GLM with S-shaped link function. But given the review status of the manuscript, a quick and dirty solution also has its advantages.
Comment: Why are you fitting linear regression with a non-continuous dependent variable? In any case the deviation from linear looks very weak to me. You might do a bootstrap test or permutation test for a local linear regression over a straight line, perhaps, or you might perhaps test for dependence in the residuals (say by a runs test).
Comment: @Glen_b: With over 600 data points, the discreteness of the response should not cause much trouble as long as variance homogeneity (among other assumptions) looks acceptable.
Comment: I was actually rejected and am going to resubmit to another journal, so I have leeway to make bigger changes if needed. :) "An appropriate GLM" would be something like glmer in R's lme4 package with family='binomial', using the correct/incorrect data for each trial (instead of aggregate data by subject) as my dv, right? But even so, that model wouldn't be able to accommodate a non-monotonic relationship, would it? How then could I do that in the context of a GLM?
Comment: Was the response representing the proportion of success by patient?
Comment: Yes - the "posttest" data represents percent correct on a test with 5 multiple choice questions, with chance performance being 25% correct.
Answer: (1) Do you want to use linear regression model with an outcome variable restricted to 5 levels?
Assuming you want to stick with the linear regression model you have an abundance of options, including but not limited to:
(2) Create new variable: 5 level categorical variable of predictor2. Add this variable to the model. If predictor2_categorical is significant this represents a significant deviation from linear trend. (just need to be careful how your stats program deals with the collinearity, it should remove on level from categorical variable for collinearity and keep continuous variable, and this only tests deviation from linear trend. coefficients aren't interpretable)
(3) Restricted cubic spline with 5 knots of predictor2. The first of the four spline variables will be the untransformed predictor. So can test departure from linearity by testing the statistical significance of other three spline variables together.
(4) The MARS/Earth package can be used to look for deviations from linearity (using GCV).
(5) GAM will give you sort of a statistical significance of the smoothing term.
(6) --as mentioned in the comments -- add square and cubic term and test for joint significance. This is likely the easiest to implement.
Your choice will likely depend on what is easiest to implement in your statistical package and how concerned you are about potential criticism from reviewers for using data driven approach.
(7) Number 6 was focused on checking for deviation from linearity. I mostly use Stata and this is incredible easy to do in that program:
gen pred2_2 = predictor2^3
gen pred2_3 = predictor2^3
quietly regress outcome predictor2 pred2_2 pred2_3
test pred2_2  presd2_3

I'm fairly weak with R. My best guess is it would be something like this:
data$pred2_2 = predictor2^2
    data$pred2_3 = predictor2^3
attach(data)
full.model=lm(outcome ~ predictor2+pred2_2+pred2_3)
nested.model=lm(outcome ~ predictor2)
anova(full.model, nested.model)

or using -car- package: results should be identical
library(car)
crPlots(full.model)
crPlots(nested.model)
linearHypothesis full.model, "pred2_2+pred2_3")

The -car- package has the appeal that it can be used with most models. Not convinced this is the right syntax though - should be something like this.
(8) I think there is some confusion about glms here. There is a concern that your outcome looks like a proportion and thus models for proportions might fit the data better (beta models etc.). This has been well covered before:
http://www.stata.com/meeting/germany10/germany10_buis.pdf
Implementation of log models for proportions here:http://www.ats.ucla.edu/stat/stata/faq/proportion.htm
Recent stackexchange thread: Generalized linear models with continuous proportions
(8) I've no idea about glmer. I know lme4 is a random effects package. But this is a whole different question from the question of the distribution of the outcome variable. This is: how should change scores be analyzed?
There are three ways
(a) as change score – subtract pre from post to get outcome
(b) repeat measures models such as GEE or mixed-effects models, and
(c) using pre value as predictor.
You've chosen (c) above. This is admittedly the least attractive of the options and is generally avoided in observational studies. In randomized studies, where there should be no dependence between the effect of the predictor and the baseline value of the outcome, this may be more reasonable.
This is all based on my understanding that you only have two readings on your subjects, if you have more then that changes things.
(9) Most models here (except for GAM I think) are linear in the predictors (even if they have different link functions), so the methods of allowing for non-linearity are fairly broadly applicable.
Comment: Why not simply add a squared and cubic version of the IV and then check the p value of the corresponding partial F test? The referee's comment is data driven anyway.
Comment: To (6): Compare the current model by 'anova' with the model adding the squared and the cubed regressor in question. But better go with a GLM.
Comment: that is most probably the best/easiest approach. was getting carried away with all the options available.
Comment: For (6) - could you give me some clues or refs about how to implement this in R? I have no familiarity with this. For (1) well ... yes, I *want* to, but I could be persuaded otherwise - alternatives were proposed in the comments to the OP. Would a GLM like that described in those comments work together with (6)?
Comment: OK ... in that case, any idea how to do it with a GLM? As far as I am aware, anova cannot be used to compare the output of glmer from lme4 with family='binomial', the model I floated in comments to the OP.  -- also, I was mainly asking how to implement the model itself in (6), not the model comparison, sorry for not being clear.
Comment: I updated by answer. But this is a fairly big topic. Don't think I'm in a position to cover all your questions, but hopefully this is a start.


Preciso de explicação porque o código em C dá um erro de Segmentation fault

Question: Iniciei meus estudos de alocação dinâmica mas não estou conseguindo fazer um exemplo simples, não consegui achar o problema.
#include <stdio.h>
#include <stdlib.h>

#define SUCESSO 1
#define FALHA -1

typedef struct {
    int x;
    int y;
} Ponto;

void criarPonto(Ponto *ponto);
int preencherPonto(Ponto *ponto, int x, int y);

int main() {
    Ponto *ponto;
    criarPonto(ponto);
    printf("O endereco de memoria é: %d\n", ponto);
    preencherPonto(ponto, 0, 1);
    printf("Coordenada X: %d\n", (*ponto).x);
    printf("Coordenada Y: %d\n", (*ponto).y);
    return 0;
}

void criarPonto(Ponto * ponto) {
    ponto = (Ponto *) NULL;
}

int preencherPonto(Ponto *ponto, int x, int y) {
    Ponto *p;
    p = malloc(sizeof(Ponto));
    if(p == NULL) {
        return FALHA;
    } else {
        p->x = x;
        p->y = y;
        ponto = p;
    }
}

Comment: De início, `criarPonto()` não serve de nada. `preenchePonto` não preenche o `ponto` de `main`. Se quiser conferir, é só comentar os dois `printf`s após `preencherPonto(ponto, 0, 1);`, em `main`.
Answer: Refiz de um jeito que funciona. Algumas mudanças eu fiz para ficar em um estilo mais limpo, mais padronizado, e atender a demanda de um compilador decente com proteções ligadas para evitar erros inadvertidos:
#include <stdio.h>
#include <stdlib.h>

#define SUCESSO 0
#define FALHA -1

typedef struct {
    int x;
    int y;
} Ponto;

void criarPonto(Ponto **ponto) {
    (*ponto) = (Ponto *)NULL;
}

int preencherPonto(Ponto **ponto, int x, int y) {
    *ponto = malloc(sizeof(Ponto));
    if (*ponto == NULL) return FALHA;
    (*ponto)->x = x;
    (*ponto)->y = y;
    return SUCESSO;
}
int main() {
    Ponto *ponto;
    criarPonto(&ponto);
    printf("O endereco de memoria é: %p\n", (void *)ponto);
    if (preencherPonto(&ponto, 0, 1) == FALHA) return FALHA;
    printf("O endereco de memoria é: %p\n", (void *)ponto);
    printf("Coordenada X: %d\n", ponto->x);
    printf("Coordenada Y: %d\n", ponto->y);
    return SUCESSO;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
O problema é que não está inicializando do jeito que deseja.
Se você quer passar um argumento por referência tem que usar uma referência para ele. Se você deseja mudar o valor por referência funciona. Se o valor que você quer mudar é a referência então a referência deve ser passada por referência, portanto deve haver um ponteiro duplo ali e tratar esse ponteiro para mexer no ponteiro mais interno, como eu fiz no código.
Claro que este código é um pouco confuso. Muito provavelmente seria melhor retornar o ponteiro em vez de passar pro referência. Em geral o ponteiro ter sido inicializado ou não já serve de código de erro.
O código criado tem pouca utilizada geral, a não ser que esteja exercitando outro conceito. O criaPonto() escrito nesta forma não é nada melhor que fazer direto sem a função. Claro, ela pode ser útil e ter um motivo. É um abstração para no futuro poder mudar como se cria o ponto de forma que não precisa mudar na aplicação toda. mas aí especificamente não faz nada útil.
O mesmo pode ser dito para o preenchePOnto(). No mínimo poderia ser uma função só. Mas esta função tem um outro problema além da já relatada, ela aloca memória sem ser óbvio que isto ocorre e escondendo esse fato fica fácil esquecer de desalocar, como de fato ocorreu. Este caso não é um problema porque o código já termina em seguida e não há consequências. Mas em um código real haverá e será mais difícil perceber o erro (já houve um em um código simples, imagina em um complexo).
Seria legal se C tivesse uma sintaxe melhor para inicializar membros de uma estrutura alocada dinamicamente, mas essa função tem pouca utilidade, e se é para preencher, então deveria só fazer isto, não alocar. Pode ser que a alocação fique na função criadora.
Assim fica melhor:
#include <stdio.h>
#include <stdlib.h>

#define SUCESSO 0
#define FALHA -1

typedef struct {
    int x;
    int y;
} Ponto;

void preencherPonto(Ponto *ponto, int x, int y) {
    ponto->x = x;
    ponto->y = y;
}
int main() {
    Ponto *ponto = malloc(sizeof(Ponto));
    if (ponto == NULL) return FALHA;
    preencherPonto(ponto, 0, 1);
    printf("O endereco de memoria é: %p\n", (void *)ponto);
    printf("Coordenada X: %d\n", ponto->x);
    printf("Coordenada Y: %d\n", ponto->y);
    free(ponto);
    return SUCESSO;
}

Veja funcionando no ideone. E no repl.it. Também coloquei no GitHub para referência futura.
Mas até o preenchimento não sou muito fã de fazer assim, talvez até uma macro fosse melhor, mas não ideal.
Comment: Foi esclarecedor, eu estou realmente treinando o conceito, para algumas aulas de programação de computadores.
Obrigado pela resposta.
Comment: Seu código estava acima da média do que aparece aqui.


select all from where there are multiple values for a column

Question: I have a db of personnel which every person can have one or multiple countries. The countries can be added from a multiple choice drop down to db.
A person could be like this
name   country
john   USA, UK, Poland
joe    USA
Jack   Germany

user can filter people by changing the value of <%= country %>
I am trying to filter people based on user's choice. I am using this query
 SELECT *
FROM `personnel`
WHERE <%= country %> LIKE `country`
ORDER BY `industry` ASC, `name` ASC

the problem is this select filters only rows(people) with single country, and it doesn't show people who has more that one country.
I tried to use = instead of LIKE but that one didn't work also
Comment: Fix you data structure, so you have a table called `PersonnelCountry`, with one row per person and country.
Comment: the db is  personnel, my bad. yes every person has one row and in country column they can have either one or multiple countries
Comment: But the best solution would be to normalise your table structure as @GordonLinoff has suggested.
Comment: @Shadow, the find_in_set was the answer tnx,
this fixed my problem
find_in_set(<%= country %>, `country`)
Answer: You need to add % in LIKE sentence. LIKE '%country%'
% allows search in all the string, no matter what has after and before.
If you LIKE 'country' it show only the person with single country.
Cheers


What is a formal definition of the unique values in an array?

Question: Let the term unique be defined as all other values of this object are numerically different from one value of this object.
Let $v$ be a vector with 5000 observations with each observation may or may not be unique.
What is a formal way to state that one only considers the unique values of $v$?
Comment: $v$ is, by a standard definition, a map from the index set $\mathcal I=\{1,2,\ldots, 5000\}$ into a space of possible values of the observations.  The usual term for the set of its unique values is its *image.*  There are many formal yet brief and simple ways to write it, such as $v(\mathcal I).$  Mathematicians often abbreviate this as $\operatorname{Im}(v).$
Comment: @whuber I appreciate your answer. That sounds like the most convenient solution to my question. Would you mind to make your comment an answer, so I can accept it?
Comment: Are you asking about a set?
Comment: Yeah set theory sounds like a good way to state this! Havn't thought about that. Could you state the answer to my question in a formal way using set theory?
Answer: Although it is sometimes convenient to think of (and represent) a data set as a mathematical set, this mathematical concept is not rich enough for many uses, because the values of observations can be repeated.  That is the very source of the question: the possibility of repetitions is the same as the possibility that the set (a true set now!) of unique values of the observations might be smaller than the number of observations.
I will briefly describe two general, powerful, yet sufficiently simple mathematical models of statistical observations (each of which has a characteristic notation) and give a solution for each model.
Tuples/arrays/vectors/sequences
These kinds of objects are mathematically nearly the same.

A tuple can be defined as a function from a "index" set $\mathcal I$ (such as a subset of the natural numbers $\mathbb N = \{0,1,2,\ldots\}$) into a "value" set $X$ of possible values.  (Wikipedia stipulates that $\mathcal I$ is finite, but this requirement is neither conceptually nor mathematically necessary.)

When we refer to an array we mean the index set $\mathcal I$ is a subset of $\mathbb{Z}^k$ for a finite number $k:$ that is, it has "multiple subscripts" (possibly negative, as allowed in the Fortran language for instance).  The richest concept of arrays appears in the computer science literature.

A tuple can be considered a vector when its value set $X$ is a field of numbers, for then such objects can be added to each other and scaled by values in $X$ component by component, thereby satisfying all the vector space axioms.

A sequence requires $\mathcal I$ to be totally ordered.  See Wikipedia for a discussion.

Although a standard notation for functions $v:\mathcal I\to X$ is to write "$v(i)$" for the value assigned by $v$ to $i\in\mathcal I,$ when we refer to it as a "tuple," "array," "vector," or "sequence," we usually adopt a different notation.  First, the value $v(i)$ is written instead with a subscript as $v_i.$  Second, the entire tuple may be written as $(v_i)_{i\in\mathcal I}.$  The fact that $v$ is a function is usually not even mentioned, even though (in retrospect) that is clear from the notation.
For statistical applications, observations usually come in some order: the first, the second, the third, and so on. We therefore may take the indexing set to be a set of ordered whole numbers $1,2,3,\ldots, n.$ $v$ often is referred to as a "variable," a word suggesting the values of $v = (v_1, v_2, \ldots, v_n)$ needn't all be the same.  The set of all these distinct values is, of course, the usual image of $v,$ defined as

$$\operatorname{Im}(v) = \{v(i)\mid i\in\mathcal I\} = \{x\in X \mid \exists_{i\in\mathcal I}: v(i)=x\}.$$

Be careful: this notation and terminology might surprise any reader who hasn't yet learned of the functional representation of tuples.  Some preparatory explanation is helpful.  But as a notation it's perfectly fine and conventional.
Multisets
A multiset generalizes a set by allowing for repetition.  Formally, you may consider a multiset to be a function $S:X\to \mathcal N$ whose value at any $x\in X$ tells you how many times $x$ is intended to appear in $S.$  (The role of the value set $X$ has changed from the range of a function to the domain of another function.)
Multiset notation usually looks something like $\{x^{[2]}, y^{[3]}, z, \ldots\}$ where "$x^{[k]}$" means $k$ instances of $x$ appear in $S$ (that is, $S(x)=k$), "$z$" is just shorthand for "$z^{[1]},$" and we understand that distinct symbols "$x,$" "$y,$" "$z,"$ etc. refer to distinct objects.  As with set notation, the order in which the elements are written has no inherent meaning.  This multiset is identical to $\{z, y^{[3]}, x^{[2]}, \ldots\}$ for example.
The unique values in a multiset form a (usual) set.  I am not aware of any generally understood term or notation for these values.  You might refer to them as the "base set" of $S.$  (Wikipedia calls the base set the "support," but be cautious with that, because "support" has a commonly understood meaning for random variables that differs from this--and it's likely you will be referring to random variables whenever you are discussing datasets.)
You can define the base set in various ways.  For instance, you could insist (by means of a definition) that the values of $S$ be whole numbers $\{1,2,3,\ldots\},$ in which case

the base set is the domain of $S$ (qua function).

That's probably the simplest way to approach this question from a multiset perspective, provided the order of the observations does not matter.  If you do allow for $0$ to be a possible value of $S$ (explicitly indicating a value that has not appeared in the data), you could define the base set to be the inverse image of the nonzero values,

$$S^{-1}(X\setminus \{0\}) = \{x\in X\mid S(X) \ne 0\}.$$

Once again, providing explicit definitions for your reader is needed if you wish to communicate your ideas reliably.

Examples
Consider administering a survey in which one question is "what is your gender?," with the possible answers being "Male," "Female," "Other," "Prefer not to say," and missing.  These answers comprise the set $X.$  As the survey results come in, you record the answers.  Perhaps, in order, they are "Other", "Female", "Female", missing, "Prefer not to say".
For vector notation, statisticians usually start indexing at $1$ and we have $n=5$ results.  Thus, we can take $\mathcal I = \{1,2,3,4,5\}$ for the index set (with its usual order $1\lt 2 \lt \cdots \lt 5$).
For instance, $v_1 = \text{Male}$ and $v_4 = \text{missing}.$
In multiset notation, $v = \{\text{Female}^{[2]},\text{missing},\text{Prefer not to say}, \text{other}\}$  Notice that the order in which the values appear in this notation does not have to match the order in which the values first appeared in the sequence of survey results: that information is lost.

References
For rigorous definitions and many good examples, see Paul Halmos Naive Set Theory on functions and total orderings and Richard Stanley Enumerative Combinatorics (Vol 1, chapter 1) about multisets.
Answer: Adopting the notion of set, I believe it is possible to define as follows:
Let $v$ be any element of $V$, the set of unique elements of V is given by
$$\bigcup_{\forall v \in V} v$$
Comment: Your argument makes sense. At the moment of the question, I think of only one way to obtain/compute the set. When reviewing the notion of sets, I noticed the mistakes. Thanks!
Comment: This is an incorrect use of notation that has a standard mathematical meaning.  You could correct it by, for instance, writing $$\bigcup_{v\in V}\{v\}.$$ Even that is an abuse of notation, because $V$ is not a set.
Comment: An example might give force to my comment.  Often the natural numbers are [defined](https://en.wikipedia.org/wiki/Natural_number#Constructions_based_on_set_theory) as the sets $0=\{\},$ $1=\{0\},$ $2=\{0,1\},$ *etc.* With $V=\{0,1\}$ the unique values are the set $V$ itself, but your expression $$\bigcup_{v\in V}v = 0 \cup 1 = \{\} \cup \{0\} = \{0\} \ne V$$ clearly gives an incorrect answer.


Conditional Expected Value of Product of Normal and Log-Normal Distribution

Question: Could someone please provide the answer and steps to solve this expression?
\begin{eqnarray*}
E\left[\left.\left(e^{X}Y+k\right)\right|\left.\left(e^{X}Y+k\right)>0\right]\right.
\end{eqnarray*}
$E$ is the expectation operator.
\begin{eqnarray*}
X\sim N\left(\mu_{X},\sigma_{X}^{2}\right);Y\sim N\left(\mu_{Y},\sigma_{Y}^{2}\right);X\;\text{and }Y\text{ are independent. Also, }k<0
\end{eqnarray*}
KEY MISSING LINK
The above expression depends on proving the below general expression or at least showing that it holds for the special case of Normal and Log-Normal distribution.
$E[UV\mid UV>c] = E[UE[V\mid UV>c]]$
Here, $U,V$ are independent random variables that could be discrete or continuos and follow any probability distribution. $E$ is the expectation operator. $c$ is a constant.
Of course, for our main question we require only the case where one of them is normally distributed and the other is log-normal? Say,  $U$ is log-normal and $V$ is normal. Is the above identity true for this special case?
This is posed as a separate question due to its importance: Proof of Simplification of Conditional Expectation of Product of Random Variables
STEPS TRIED
0) JOINT CONDITIONAL DENSITY
I am having difficulty coming up with the conditional joint density to use in the above expectation. The joint density function of just $X$ and $Y$ is straight forward and follows from the standard density function for the bivariate normal case. How would we incorporate the conditional aspect into the joint density function?
1) NORMAL LOG-NORMAL MIXTURE PAPER BY YANG
(Link: http://repec.org/esAUSM04/up.21034.1077779387.pdf)
This paper has the first four central moments without proof (Equation 5 in above paper). If someone could provide these proofs, that might shed more light on the problem above.
The variables in the Yang paper are correlated, which is easy to apply to above; but they also have zero mean in the paper, which in our case does not apply directly, since we have non zero mean.
2)OTHER RELATED LINKS
a) Interesting question about an expectation involving a slightly modified form of the normal log-normal mixture. Though this lacks the conditional aspect, and hence needs some modification before it can be used for the problem above.
https://math.stackexchange.com/questions/1142841/covariance-in-normal-lognormal-nln-mixture
b) Another question on the normal log-normal mixture though this lacks a deeper discussion.
https://math.stackexchange.com/questions/159818/combination-of-a-normal-r-v-with-a-log-normal-one
c) Question on conditional expectation of product of independent random variables. It would be good to know which aspects from this are applicable in our case.
https://math.stackexchange.com/questions/544410/result-and-proof-on-the-conditional-expectation-of-the-product-of-two-random-var
d) Other interesting questions on conditional expectation of independent random variables.
https://math.stackexchange.com/questions/380866/conditional-expectations-for-independent-random-variables?rq=1
https://math.stackexchange.com/questions/55524/rule-with-independent-random-variables-and-conditional-expectations?rq=1
3) TAYLOR SERIES APPROXIMATIONS
Would it be possible to use taylor serious approximations here? I am little confused due to the conditional expectation and the normal log normal mixture? Any pointers on whether this is possible and how to proceed further or whether this is not applicable here would be great.
4) USING STANDARD NORMAL (SEEMS LIKE A DEAD END)
I know that if we can express this sum using the standard normal as below, there is a solution. Please advice on how to do this or other alternatives to solve the above would be helpful as well. This seems to be a dead end as confirmed by experts on this forum. But still keeping here if someone discovers a way to continue using this approach.
\begin{eqnarray*}
W=\left(e^{X}Y+k\right)<=>\mu+\sigma Z\text{ where, }Z\sim N\left(0,1\right)
\end{eqnarray*}
\begin{eqnarray*}
\left[W\sim N\left(\mu,\sigma^{2}\right)\Rightarrow W=\mu+\sigma Z\;;\; W>0\Rightarrow Z>-\mu/\sigma\right]
\end{eqnarray*}
We then need to determine, $\mu\text{ and }\sigma$.
We have for every standard normal distribution, $Z$, and for every
$u,$ $Pr\left[Z>\text-u\right]=Pr\left[Z<u\right]=\mathbf{\Phi}\left(u\right)$.
Here, $\phi$ and $\mathbf{\Phi}$ are the standard normal PDF and
CDF, respectively.
\begin{eqnarray*}
E\left[\left.Z\right|Z>-u\right] & = & \frac{1}{\mathbf{\Phi}\left(u\right)}\left[\int_{-u}^{\infty}t\phi\left(t\right)dt\right]\\
 & = & \frac{1}{\mathbf{\Phi}\left(u\right)}\left[\left.-\phi\left(t\right)\right|_{-u}^{\infty}\right]=\frac{\phi\left(u\right)}{\mathbf{\Phi}\left(u\right)}
\end{eqnarray*}
Hence we have,
\begin{eqnarray*}
E\left[\left.Y\right|Y>0\right] & = & \mu+\sigma E\left[\left.Z\right|Z>\left(-\frac{\mu}{\sigma}\right)\right]\\
 & = & \mu+\frac{\sigma\phi\left(\mu/\sigma\right)}{\mathbf{\Phi}\left(\mu/\sigma\right)}
\end{eqnarray*}
Setting, $\psi\left(u\right)=u+\phi\left(u\right)/\Phi\left(u\right)$,
\begin{eqnarray*}
E\left[\left.Y\right|Y>0\right]=\sigma\psi\left(\mu/\sigma\right)
\end{eqnarray*}
Comment: Any reference that analyzes the error would do it.  First, though, I recommend that you simplify the question by eliminating redundant parameters. It can be reduced to one about $e^XY$ where $X$ has a mean-zero Normal distribution and $Y$ has an arbitrary Normal distribution. That simplification will clarify the nature of the problem and perhaps help you determine whether a Taylor series approximation would be appropriate.
Comment: @gung, Please note above the steps I tried. Expressing the above as a standard normal variable with appropriate mean and variance has a solution. So the trick would be to convert the above to a suitable standard normal. If there are alternatives, please also suggest. Thanks for your help.
Comment: I just also found the Paper on Normal and Log Normal mixture by Yang, but it treats correlated variables and am not yet sure how to get the conditional expectation. Please advice on closed form solutions that might exist for the above.
Comment: What is the subscript $T$ in your first formula?
Comment: Sorry, I should either have removed that or clarified earlier it is time .. I am taking the expectation at time T ..  Please let me know if you need any further details ...  Any suggestions on answers and steps would be appreciated?
Comment: Unless $X$ has a tiny variance, $W$ won't be anywhere near normally distributed: that approach is a dead end.
Comment: @whuber Would taylor series approximations be possible in this case? I am little thrown off due to the conditional expectation and the normal log normal mixture.. Please advice ..
Comment: I would not expect Taylor series to be an effective approach where lognormal distributions and products are involved, unless there are severe restrictions on the coefficients and the variances of the distributions involved.
Comment: Could you please point me to some source on where the taylor approximation would be useful and why it would fail for the lognormal?
Comment: @whuber I am looking at the joint distribution of X and Y, which we know can be easily arrived at since both are normal. We can even take the expected value of the product, but it is the conditional expected value that is causing issues for the joint distribution. Do you know any source that looks at conditional distributions of joint distributions with a constant added.
Comment: All, I am still trying to understand if this problem is worth pursuing further or just settle for a numerical solution. The joint probability distribution seems to be another approach but again the conditional distribution and the constant added in, seems to cause issues. Any suggestions, please let me know.
Answer: What is the intended use of the result?  That bears on what form of answer is needed, to include whether a stochastic (Monte Carlo) simulation approach might be adequate,  And even the bigger picture matter of is this problem necessary to solve, and did someone come up with this problem as a way of solving a higher level problem, and there might be a better approach to the higher level problem which doesn't require this.
Here is a stochastic (Monte Carlo) simulation solution in MATLAB.
<code>a = 1; b = 2; c = 3; d = 4; k = -1; % Made up values for illustrative purpose
n = 1e8; % Number of replications
mux = 10; sigmax = 4; sigmay = 7; % Made up values for illustrative purposes
X = mux + sigmax * randn(n,1); Y = sigmay * randn(n,1); Y1 = a + b + c + d * Y;
success_index = exp(X).*Y1 > 0; % replications in which condition is true
num_success = sum(success_index);
Cond_Sample = exp(X(success_index)) .* Y1(success_index) + k;
disp([num_success mean(Cond_Sample) std(Cond_Sample)/sqrt(num_success)])
1.0e+09 *
0.058475265000000   1.502775087443930   0.057342191058931
</code>
Comment: Meant to add, I feel that this is a such a fundamental combination of normal and log normal, so there must be some solution if not approximation available. If there is not, given the rather simple nature of the problem, any further progress or breakthroughs would be helpful to many it seems. I would be happy to put a bounty on this as soon as I can, which is after I get five more points.
Comment: At this point, i think I've given enough freebies for the benefit of some billionaire hedge fund tycoon.  They can pony up if they want more specialized help and advice.  Or is this an academic project?
Comment: This is an academic project. I am not billionaire hedge fund tycoon :-) If this were not academic, then a simulation would have killed it long back. Finding a better answer would be mainly in the interest of gaining knowledge and spreading it … Right?
Comment: Perhaps we should collaborate. You can send an invite to my LinkedIn account linked in my profile.  And I wasn't thinking you were the billionaire hedge fund tycoon - more likely that you were an employee working for the benefit of the billionaire hedge fund tycoon :).
Comment: Since I still don't really know the big picture, i can't assess what kind of solution, if any, is really needed to this. And so why is any of this Normal or Lognormal, and not some fatter tailed distributions?  The simulation approach will still hold up if distributions change, dependencies are introduced, etc.
Comment: You make a good point Mark … A simulation would handle all those cases and as I said earlier, would have been easily solved. But now it is mainly about finding a proper proof or solution to the above, which I think is a very interesting problem. Given how common normal and log normal distributions are, the above should be something we should look to solve.
Comment: I don't think I can reply in chat.  Apparently I only have 1 of the needed 20 stack exchange points to participate in chat. Unless there is a way of migrating Cross Validated points there. See my comment 2 comments back to contact me.
Comment: Contact me per info at https://www.or-exchange.org/users/1263/mark-l-stone .
Comment: You shouldn't have any reputation-based problems participating in chat, Mark.  What exactly happens when you try?
Comment: @whuber, I just put a bounty on this question. Somehow I seem to think that the answer lies in finding a conditional distribution to use in the expectation and solving thereafter … Any suggestions / thoughts, please let me know.
Comment: I believe there is no closed form for the expectation in terms of the conventional transcendental functions. It can be reduced to an integral of a Gaussian times an Error function, but cannot be further simplified in general. These integrals require numerical evaluation.
Comment: whuber, I have had a reply box available in chat ever since I got up to 20 points on http://scicomp.stackexchange.com/ .  Before that,I could see the chat session but could not post.  It specifically said something about needing 20 points on the Stack Exchange network.
Comment: @whuber, Could you please provide some details and steps to get to the integral involving the Gaussian and error function? Setting up the conditional joint density for the above would be a useful thing to know, I suppose.
Comment: @Mark Obviously you have far more than 20 points! Have you attempted recently to enter any chat session, such as at [Ten Fold](http://chat.stackexchange.com/rooms/18/ten-fold)?
Comment: As I wrote above, I now have reply box available in chat, and have since I got up to 20 points on http://scicomp.stackexchange.com/  a few days ago. When I registered on http://scicomp.stackexchange.com/ , I was already in the many hundreds on Cross Validated, but only started off with 1 point, even thought at some level it knew who I was. This is unlike when I registered on Cross Validated and at some point had 100 point association bonus between CV and   http://math.stackexchange.com/ and http://mathoverflow.net/ .Not allowed to reply in chat on Cross Validated even when I had > 1000 points.
Answer: Comments:

The joint density is given by multiplying the densities since they are idp. One variable is just a paramater to the other.
$Ye^X$ is not normally distributed so approach (4) wont work.
The expressions below might allow you to find some approximation. If not they are relatively easy to evaluate with a computer.

Let $X\sim\mathcal{N}(\mu, \sigma^2)$, denote $c = -k/y$, and $d(y)=\log(-k/y)$.
Let $Z=e^X$, then
$$E[YZ\mid B] = E[YE[Z\mid B]],$$
and,
$$E[Z\mid Z>c] = e^{\mu+\sigma^2/2}\frac{P(X>d-\sigma^2)}{P(X>d)},$$
if $c>0$ and $E[Z] = e^{\mu+\sigma^2/2}$ otherwise. Thus, since $c>0$ only if $Y<0$,
$$E[YZ\mid B] = \frac{1}{2}e^{\mu+\sigma^2/2}\bigg(E[Y\mathbb{1}(Y>0] + E\Big[Y\frac{P(X>d(Y)-\sigma^2)}{P(X>d(Y))}\mathbb{1}(Y<0)\Big]\bigg).$$
The first part is simply
$$\int_0^\infty y f_Y(y)\,dy,$$
and the second
$$\int_{-\infty}^0 y \frac{P(X>log(-\frac{k}{y})-\sigma^2)}{P(X>log(-\frac{k}{y}))}f_Y(y)\,dy.$$
Comment: Thanks for the helpful answer. Here, $k<0$, but I suppose we just change the sign and everything follows. Also, could you please elaborate on the steps to get the below two results? Does the first one follow simply from independence or does it involve some other special properly?

#1) $$E[YZ\mid B] = E[YE[Z\mid B]],$$

#2) $$E[Z\mid Z>c] = e^{\mu+\sigma^2/2}\frac{P(X>d-\sigma^2)}{P(X>d)},$$
Comment: Could you also please explain how you are setting up the conditional density here? $$E[ZY\mid ZY\in B] = \int\int_B zy f_{ZY\mid B}\,dz\,dy = \int y \Big(\int_{-k/y} z f_Z\,dz\Big) f_Y\,dy$$
Comment: There was a mistake in the two-dimensional integral. If you look at it now it should be clear whence $E[YZ\mid B]$ came from-otherwise let me know! The conditional expectation is a standard result found in e.g. the wikipedia article for lognormal. You find it by integrating e^X f_X with some constraints.
Comment: Much appreciative of your clarifications. I see how we would get this, $$E[YZ\mid B] = E[YE[Z\mid B]],$$    But I found this link, while trying to understand this more and perhaps I am confusing something, but would the answer at this link not apply in the our case. http://math.stackexchange.com/questions/544410/result-and-proof-on-the-conditional-expectation-of-the-product-of-two-random-var
Comment: We have $E[YE[Z\mid B]\neq E[Y]E[Z\mid B]$
Comment: I have added steps based on your suggestion above. Could you eyeball it please for errors and clarify further the one doubt I still have?
Comment: Please note that in your pointers above, there is still one part that is unclear or not completely proved as elaborated in this new question. Could you please clarify the steps in this question or in the new questions? http://stats.stackexchange.com/questions/162657/proof-of-simplification-of-conditional-expectation-of-product-of-random-variable
Answer: This solution is due to the suggestions and corrections from @Hunaphu, @whuber, and others. Could someone please verify if all the steps make sense?
ANSWER STEPS START
Using some notational shortcuts,
Consider,
\begin{eqnarray*}
E\left[\left.\left(e^{X}Y+k\right)\right|\left(e^{X}Y+k\right)>0\right] & = & E\left[k\left|\left(e^{X}Y+k\right)>0\right.\right]+E\left[\left(e^{X}Y\right)\left|\left(e^{X}Y+k\right)>0\right.\right]
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+E\left[\left.\left(Ye^{X}\right)\right|\left.\left(Ye^{X}+k\right)>0\right]\right.
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+\int\int ye^{x}f\left(\left.ye^{x}\right|\left\{ ye^{x}+k\right\} >0\right)dxdy
\end{eqnarray*}
Here, $f\left(w\right)$ is the probability density function for $w$,
Here, $f\left(w\right)$ is the probability density function for $w$,
\begin{eqnarray*}
 & = & k+\int\int ye^{x}\frac{f\left(ye^{x};\left\{ ye^{x}+k\right\} >0\right)}{f\left(\left\{ ye^{x}+k\right\} >0\right)}dxdy
\end{eqnarray*}
\begin{eqnarray*}
\left[\text{We note that, }ye^{x}>-k>0\Rightarrow y>0\right]
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+\int\int ye^{x}\frac{f\left(y\right)f\left(e^{x};\left\{ ye^{x}+k\right\} >0\right)}{f\left(\left\{ ye^{x}+k\right\} >0\right)}dxdy
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+\int y\left[\int\frac{e^{x}f\left(e^{x};\left\{ e^{x}>-\frac{k}{y}\right\} \right)}{f\left(e^{x}>-\frac{k}{y}\right)}dx\right]f\left(y\right)dy
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+\int y\left[\int e^{x}f\left(e^{x}\left|\left\{ e^{x}>-\frac{k}{y}\right\} \right.\right)dx\right]f\left(y\right)dy
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+\int_{0}^{\left(y<-k\right)}y\left[\int e^{x}f\left(e^{x}\left|\left\{ e^{x}>1\right\} \right.\right)dx\right]f\left(y\right)dy+\int_{\left(y>-k\right)}^{\infty}y\left[\int e^{x}f\left(e^{x}\left|\left\{ e^{x}<1\right\} \right.\right)dx\right]f\left(y\right)dy
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+\int_{0}^{\left(-k\right)}y\left[E\left(\left.W\right|W>c\right)\right]f\left(y\right)dy+\int_{\left(-k\right)}^{\infty}y\left[E\left(\left.W\right|W<c\right)\right]f\left(y\right)dy\quad;\;\text{here, }W=e^{X}\text{ and }c=1
\end{eqnarray*}
Simplifying the inner expectations,
\begin{eqnarray*}
E\left(\left.W\right|W>c\right)=\frac{1}{P\left(e^{X}>c\right)}\int_{c}^{\infty}w\frac{1}{w\sigma_{X}\sqrt{2\pi}}e^{-\frac{1}{2}\left[\frac{ln\left(w\right)-\mu_{X}}{\sigma_{X}}\right]^{2}}dw
\end{eqnarray*}
Put $t=ln\left(w\right)$, we have, $dw=e^{t}dt$
\begin{eqnarray*}
E\left(\left.W\right|W>c\right)=\frac{1}{P\left(X>ln\left(c\right)\right)}\int_{ln\left(c\right)}^{\infty}\frac{e^{t}}{\sigma_{X}\sqrt{2\pi}}e^{-\frac{1}{2}\left(\frac{t-\mu_{X}}{\sigma_{X}}\right)^{2}}dt
\end{eqnarray*}
\begin{eqnarray*}
t-\frac{1}{2}\left(\frac{t-\mu_{X}}{\sigma_{X}}\right)^{2}=-\frac{1}{2\sigma_{X}^{2}}\left(t-\left(\mu_{X}+\sigma_{X}^{2}\right)\right)^{2}+\mu_{X}+\frac{\sigma_{X}^{2}}{2}
\end{eqnarray*}
\begin{eqnarray*}
E\left(\left.W\right|W>c\right)=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{P\left(\mu_{X}+\sigma_{X}Z>ln\left(c\right)\right)}\int_{ln\left(c\right)}^{\infty}\frac{1}{\sigma_{X}\sqrt{2\pi}}e^{-\frac{1}{2}\left[\frac{t-\left(\mu_{X}+\sigma_{X}^{2}\right)}{\sigma_{X}}\right]^{2}}dt\quad;Z\sim N\left(0,1\right)
\end{eqnarray*}
Put $s=\left[\frac{t-\left(\mu_{X}+\sigma_{X}^{2}\right)}{\sigma_{X}}\right]$
and $b=\left[\frac{ln\left(c\right)-\left(\mu_{X}+\sigma_{X}^{2}\right)}{\sigma_{X}}\right]$
we have, $ds=\frac{dt}{\sigma_{X}}$
\begin{eqnarray*}
E\left(\left.W\right|W>c\right)=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{P\left(Z>\frac{ln\left(c\right)-\mu_{X}}{\sigma_{X}}\right)}\int_{b}^{\infty}\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}s^{2}}ds
\end{eqnarray*}
\begin{eqnarray*}
=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{P\left(Z<\frac{-ln\left(c\right)+\mu_{X}}{\sigma_{X}}\right)}\left[\int_{-\infty}^{\infty}\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}s^{2}}ds-\int_{-\infty}^{b}\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}s^{2}}ds\right]
\end{eqnarray*}
\begin{eqnarray*}
=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{P\left(Z<\frac{-ln\left(c\right)+\mu_{X}}{\sigma_{X}}\right)}\left[1-\Phi\left(b\right)\right]\quad;\Phi\text{ is the standard normal CDF}
\end{eqnarray*}
\begin{eqnarray*}
=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{\Phi\left(\frac{-ln\left(c\right)+\mu_{X}}{\sigma_{X}}\right)}\left[\Phi\left(-b\right)\right]
\end{eqnarray*}
Similarly for the other case,
\begin{eqnarray*}
E\left(\left.W\right|W<c\right)=\frac{1}{P\left(e^{X}<c\right)}\int_{0}^{c}w\frac{1}{w\sigma_{X}\sqrt{2\pi}}e^{-\frac{1}{2}\left[\frac{ln\left(w\right)-\mu_{X}}{\sigma_{X}}\right]^{2}}dw
\end{eqnarray*}
Put $t=ln\left(w\right)$, we have, $dw=e^{t}dt$
\begin{eqnarray*}
E\left(\left.W\right|W<c\right)=\frac{1}{P\left(X<ln\left(c\right)\right)}\int_{-\infty}^{ln\left(c\right)}\frac{e^{t}}{\sigma_{X}\sqrt{2\pi}}e^{-\frac{1}{2}\left(\frac{t-\mu_{X}}{\sigma_{X}}\right)^{2}}dt
\end{eqnarray*}
\begin{eqnarray*}
t-\frac{1}{2}\left(\frac{t-\mu_{X}}{\sigma_{X}}\right)^{2}=-\frac{1}{2\sigma_{X}^{2}}\left(t-\left(\mu_{X}+\sigma_{X}^{2}\right)\right)^{2}+\mu_{X}+\frac{\sigma_{X}^{2}}{2}
\end{eqnarray*}
\begin{eqnarray*}
E\left(\left.W\right|W<c\right)=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{P\left(\mu_{X}+\sigma_{X}Z<ln\left(c\right)\right)}\int_{-\infty}^{ln\left(c\right)}\frac{1}{\sigma_{X}\sqrt{2\pi}}e^{-\frac{1}{2}\left[\frac{t-\left(\mu_{X}+\sigma_{X}^{2}\right)}{\sigma_{X}}\right]^{2}}dt\quad;Z\sim N\left(0,1\right)
\end{eqnarray*}
Put $s=\left[\frac{t-\left(\mu_{X}+\sigma_{X}^{2}\right)}{\sigma_{X}}\right]$
and $b=\left[\frac{ln\left(c\right)-\left(\mu_{X}+\sigma_{X}^{2}\right)}{\sigma_{X}}\right]$
we have, $ds=\frac{dt}{\sigma_{X}}$
\begin{eqnarray*}
E\left(\left.W\right|W<c\right)=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{P\left(Z<\frac{ln\left(c\right)-\mu_{X}}{\sigma_{X}}\right)}\int_{-\infty}^{b}\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}s^{2}}ds
\end{eqnarray*}
\begin{eqnarray*}
=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{P\left(Z<\frac{ln\left(c\right)-\mu_{X}}{\sigma_{X}}\right)}\left[\Phi\left(b\right)\right]\quad;\Phi\text{ is the standard normal CDF}
\end{eqnarray*}
\begin{eqnarray*}
=\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{\Phi\left(\frac{ln\left(c\right)-\mu_{X}}{\sigma_{X}}\right)}\left[\Phi\left(b\right)\right]
\end{eqnarray*}
Using the results for the inner expectations,
\begin{eqnarray*}
E\left[\left.\left(e^{X}Y+k\right)\right|\left(e^{X}Y+k\right)>0\right]=k+\int_{0}^{\left(-k\right)}y\left[\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{\Phi\left(\frac{-ln\left(c\right)+\mu_{X}}{\sigma_{X}}\right)}\left[\Phi\left(-b\right)\right]\right]f\left(y\right)dy+\int_{\left(-k\right)}^{\infty}y\left[\frac{e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}}{\Phi\left(\frac{ln\left(c\right)-\mu_{X}}{\sigma_{X}}\right)}\left[\Phi\left(b\right)\right]\right]f\left(y\right)dy
\end{eqnarray*}
\begin{eqnarray*}
=k+e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}\left[\int_{0}^{\left(-k\right)}y\left\{ \frac{\Phi\left(\frac{\mu_{X}+\sigma_{X}^{2}}{\sigma_{X}}\right)}{\Phi\left(\frac{\mu_{X}}{\sigma_{X}}\right)}\right\} f\left(y\right)dy+\int_{\left(-k\right)}^{\infty}y\left\{ \frac{\Phi\left(-\left[\frac{\mu_{X}+\sigma_{X}^{2}}{\sigma_{X}}\right]\right)}{\Phi\left(-\left[\frac{\mu_{X}}{\sigma_{X}}\right]\right)}\right\} f\left(y\right)dy\right]
\end{eqnarray*}
\begin{eqnarray*}
=k+e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}\left[\int_{0}^{\left(-k\right)}y\left\{ \frac{\Phi\left(\frac{\mu_{X}+\sigma_{X}^{2}}{\sigma_{X}}\right)}{\Phi\left(\frac{\mu_{X}}{\sigma_{X}}\right)}\right\} f\left(y\right)dy+\int_{\left(-k\right)}^{\infty}y\left\{ \frac{1-\Phi\left(\frac{\mu_{X}+\sigma_{X}^{2}}{\sigma_{X}}\right)}{1-\Phi\left(\frac{\mu_{X}}{\sigma_{X}}\right)}\right\} f\left(y\right)dy\right]
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}\left[\left\{ \frac{\Phi\left(\frac{\mu_{X}+\sigma_{X}^{2}}{\sigma_{X}}\right)}{\Phi\left(\frac{\mu_{X}}{\sigma_{X}}\right)}\right\} \int_{-\frac{\mu_{Y}}{\sigma_{Y}}}^{-\left(\frac{k+\mu_{Y}}{\sigma_{Y}}\right)}\left(\mu_{Y}+\sigma_{Y}z\right)\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}z^{2}}dz\right.\\
 &  & +\left.\left\{ \frac{1-\Phi\left(\frac{\mu_{X}+\sigma_{X}^{2}}{\sigma_{X}}\right)}{1-\Phi\left(\frac{\mu_{X}}{\sigma_{X}}\right)}\right\} \int_{-\left(\frac{k+\mu_{Y}}{\sigma_{Y}}\right)}^{\infty}\left(\mu_{Y}+\sigma_{Y}z\right)\frac{1}{\sqrt{2\pi}}e^{-\frac{1}{2}z^{2}}dz\right]\quad;Z\sim N\left(0,1\right)
\end{eqnarray*}
\begin{eqnarray*}
 & = & k+e^{\left(\mu_{X}+\frac{1}{2}\sigma_{X}^{2}\right)}\left[\left\{ \frac{\Phi\left(\frac{\mu_{X}+\sigma_{X}^{2}}{\sigma_{X}}\right)}{\Phi\left(\frac{\mu_{X}}{\sigma_{X}}\right)}\right\} \left\{ \mu_{Y}\left[\Phi\left(-\left[\frac{k+\mu_{Y}}{\sigma_{Y}}\right]\right)-\Phi\left(-\frac{\mu_{Y}}{\sigma_{Y}}\right)\right]-\frac{\sigma_{Y}}{\sqrt{2\pi}}\left[e^{-\frac{1}{2}\left(\frac{k+\mu_{Y}}{\sigma_{Y}}\right)^{2}}-e^{-\frac{1}{2}\left(\frac{\mu_{Y}}{\sigma_{Y}}\right)^{2}}\right]\right\} \right.\\
 &  & +\left.\left\{ \frac{1-\Phi\left(\frac{\mu_{X}+\sigma_{X}^{2}}{\sigma_{X}}\right)}{1-\Phi\left(\frac{\mu_{X}}{\sigma_{X}}\right)}\right\} \left\{ \mu_{Y}\left[1-\Phi\left(-\left[\frac{k+\mu_{Y}}{\sigma_{Y}}\right]\right)\right]+\frac{\sigma_{Y}}{\sqrt{2\pi}}\left[e^{-\frac{1}{2}\left(\frac{k+\mu_{Y}}{\sigma_{Y}}\right)^{2}}\right]\right\} \right]
\end{eqnarray*}
Comment: Yeah, that or just do stochastic simulation.  Who are these people sitting in academic judgment who don't allow simulation-based solutions? There are Professors at the most prestigious universities in the world, journals, and books dealing just with stochastic simulation.  Hint: call it stochastic simulation, not Monte Carlo simulation - it sounds more sophisticated and less "vulgar".
Comment: @MarkL.Stone You are funny and right about the stochastic simulation. As I mentioned, at this stage, trhe question is not to make any professor or hedge fund manager happy. It is knowledge for its own sake ... :-)


Create custom path alias when new user is added in drupal 7

Question: I've created contents using custom form. I don't use content types. I could add, update and delete that content by access test, test/id/edit and test/id/delete.
I've displayed content lists for a user by tests/uid. Now I want to use user name instead of uid. I have to replace space by '-' and also replace all special characters. So my choice is both url alias and path auto.
But I couldn't add custom url pattern into pathauto pattern. There is only available for content types, taxonomy term, user and file path. But I want to custom url pattern for custom content inside the user path.
Answer: If I understand your question correctly, you're wanting to implement Pathauto's API. Here's a tutorial on how to do so. Basically, you need to implement hook_pathauto() and make use of pathauto_create_alias() & path_delete() when you're performing your Create/Update/Delete operations. It looks like you can use the token_type of user for your token replacement.
Comment: I need to add path alias for all users and add, update, delete a user
Comment: See the tutorial link for bulk adding/updating. You'll also need to implement user hook functions if you're wanting to take action on path aliases during user creation, updating, & deletion.
Comment: Thank you very much. It is working fine. Very nice tutorials.
Comment: Is it possible to use more than one pattern.


What is the most optimal way to upload large data to server from an Android App?

Question: I have an Android App that needs to upload, download data files between 10-12MB relatively often. Given that my app is more popular in countries like India which may not have good internet connectivity I am working under following constraints

User may not be connected to internet 24x7
User's interaction does not depend on whether the download/upload succeeds.

This is a poems app where we download new poems to users phone and upload user's poems to our server whenever we are connected to internet.
I understand that using "com.loopj.android.http.AsyncHttpClient;" for the communication but I was wondering if there are any better alternatives which can do the following:

Should I start a service which provides interfaces for upload/download ?
Is it possible to do this stuff in background, even when user is not using the app?
Comment: Guys lets not get into why it is 10-12 MB or whether it is good thing or not. Let us stick to the question asked.
Comment: 10-12 MB relatively often? Are you telling me that you want each user to re-download the entire database of poems every time that database is updated? Shouldn't you just have the user download the updates to the data (instead of the entire database each time)?
Comment: And why would you have the same requirements for uploading as well? Will each user really upload thousands of poems at once? I doubt it. And even if some do, those may prefer to use an actual PC when they have to do large batch of uploads.
Answer: Yes, you should use a service, in particular a foreground service (to show a notification as the upload progresses). Additionally, a foreground service is not likely to be killed by Android:

... the system considers it to be something the user is actively aware
  of and thus not a candidate for killing when low on memory.

For downloads, Android provides a ready-made solution called DownloadManager. It already includes the capability to resume downloads in case the connection is lost.
For uploads, there is no equivalent (at least as far as I know). You would have to roll out your own solution, probably involving the Content-Range HTTP header. It depends a lot on your server, for example Google Drive has an API for this. Also take a look at Resume file upload/download after lost connection (Socket programming) (although it's with sockets, the concepts are more or less the same).
Another options is to use a SyncAdapter for this task. See Transferring Data using Sync Adapters. I'm not sure if this supports resuming though.


Heroku Routing Error: ActionController::RoutingError

Question: I have the following in my routes.rb
  constraints subdomain: 'api' do
    namespace :api, path: nil, defaults: {format: 'json'} do
      namespace :v1 do
        resources :cities, only: [:index] do
          resources :areas, only: [:index]
        end
      end
    end
  end

Have tested locally and it works, though when i deploy to heroku i get the following error:
2013-03-17T20:35:04+00:00 app[web.1]: ActionController::RoutingError (No route matches [GET] "/v1/cities.json"):
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.9/lib/action_dispatch/middleware/debug_exceptions.rb:21:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.9/lib/action_dispatch/middleware/show_exceptions.rb:56:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/rack/logger.rb:32:in `call_app'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/rack/logger.rb:16:in `block in call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/tagged_logging.rb:22:in `tagged'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/rack/logger.rb:16:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.9/lib/action_dispatch/middleware/request_id.rb:22:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/methodoverride.rb:21:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/runtime.rb:17:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/activesupport-3.2.9/lib/active_support/cache/strategy/local_cache.rb:72:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/rack-1.4.5/lib/rack/lock.rb:15:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/actionpack-3.2.9/lib/action_dispatch/middleware/static.rb:62:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/engine.rb:479:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/application.rb:223:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/railties-3.2.9/lib/rails/railtie/configurable.rb:30:in `method_missing'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-188.8.131.52/lib/new_relic/agent/instrumentation/unicorn_instrumentation.rb:18:in `call'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.2/lib/unicorn/http_server.rb:552:in `process_client'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.2/lib/unicorn/http_server.rb:632:in `worker_loop'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/newrelic_rpm-22.214.171.124/lib/new_relic/agent/instrumentation/unicorn_instrumentation.rb:18:in `block (4 levels) in <top (required)>'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.2/lib/unicorn/http_server.rb:142:in `start'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.2/lib/unicorn/http_server.rb:500:in `spawn_missing_workers'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/gems/unicorn-4.6.2/bin/unicorn_rails:209:in `<top (required)>'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/bin/unicorn_rails:23:in `load'
2013-03-17T20:35:04+00:00 app[web.1]:   vendor/bundle/ruby/1.9.1/bin/unicorn_rails:23:in `'

Answer: Is your host on Heroku set to api.yourdomain or are you using the subdomain.herokuapp.com host?
If the subdomain isn't api, then this line will cause your route to fail:
constraints subdomain: 'api' do

Comment: api.mydomain.com , the subdomain is setup to point to heroku.
Comment: Your domain tld is the same of heroku? Mine was .com.br and I was getting the same error, to resolve the issue I had to add config.action_dispatch.tld_length = 2 to the production.rb file.


Estou a tentar fazer um botao de pesquisa na minha view, mas diz-me que nao pode ser nulo

Question: Estou a tentar fazer um botão de pesquisa na minha view de filmes, mas dá-me um erro a dizer que não posso ter um valor nulo. Por que? E o que tenho de fazer?
Controller:
 public ActionResult Index(string searchBy, string search)
    {
        MovieViewModel[] movies = db.MoviesData.Select(movie => new MovieViewModel
        {
            MovieID = movie.MovieID,
            MovieName = movie.MovieName,
            MovieDescription = movie.MovieDescription,
            MovieCategory = movie.MovieCategory,
            MovieYear = movie.MovieYear
        }).ToArray();

        if (searchBy == "Categoria")
        {
            return View(movies.Where(x => x.MovieCategory==search || search == null).ToList());
        }
        else
        {
            return View(movies.Where(x => x.MovieName.StartsWith(search) || search == null).ToList());
        }
    }

Parte da View relativa ao botão de pesquisa:

@using (Html.BeginForm("Index", "Movies", FormMethod.Get))
{
    Search By: @Html.RadioButton("searchBy", "Nome", true) <text> Nome </text>
    @Html.RadioButton("searchBy", "Categoria") <text> Categoria </text>

    @Html.TextBox("search") <input type="submit" value="Search" class="btn btn-default" />
}

O erro que me dá é o seguinte:

'System.ArgumentNullException: O valor não pode ser nulo. Nome do parâmetro: value'
Comment: Qual a linha exata em que ocorre o erro?
Comment: @RonaldoAraújoAlves dá erro nesta: return View(movies.Where(x => x.MovieName.StartsWith(search) || search == null).ToList());
Comment: Queira montar um [exemplo Mínimo, Completo e Verificável](https://pt.stackoverflow.com/help/minimal-reproducible-example) com a situação real, senão fica inviável uma solução além do que já foi apresentado.
Answer: O erro é certamente aqui:
return View(movies.Where(x => x.MovieName != null && (search == null || x.MovieName.StartsWith(search))).ToList());

Coloquei no GitHub para referência futura.
Não sei se a lógica disto está correta, mas a forma adotada vai dar erro mesmo. Também não vou entrar no mérito que provavelmente está modelado errado. A questão é que se se o dado que vem é nulo você não pode chamar nada nele, por exemplo não pode chamar StartsWith() porque não tem um objeto válido ali para executar algo. Então tem que prevenir que este dado não seja comparado. Não posso dizer que fiz certo porque a pergunta não deixa claro o que deveria fazer. Inverti a comparação também porque se passar um null para o método StartsWith() também dará erro.
Comment: Aí é outro problema em outro lugar. O que perguntou foi resolvido. Cada pergunta deve conter um problema. Mas antes de resolver isso você precisa entender o que quer, e postar na pergunta, as pessoas não podem adivinhar o que precisa, não é só postar o código. Uma pergunta completa tem todas informações necessárias. Sem saber o que precisa qualquer resposta estará errada, porque mesmo que funcione, não estará certa, funcionar por coincidência não é certo.
Comment: Então a pergunta já não disse em que linha era o erro, agora não diz o que quer fazer. Você precisa entender o que é programação antes de programar. Você está gerando uma lista de dados, é isto que quer? Na *view*  está lidando com um dado, é isto que quer? Eles são mutualmente exclusivos, ou pega um dado ou lista todos dados, mas novamente esta é outra questão.
Comment: esta dando o mesmo erro que no comentário abaixo. The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[WebApplication3.Models.MovieViewModel]', but this dictionary requires a model item of type 'WebApplication3.Models.MovieViewModel[]'      MovieViewModel é onde tenho as propriedades todas dos filmes
Comment: Peço desculpa, sou bem novo no stack overflow, na minha cabeça o que estava postando estava correto, vou ter mais atenção em relação às minhas perguntas. Vou então explicar então o meu objetivo. Na minha view tem uma lista de filmes que vem da base de dados. E em cima tem um botão, 2 radio buttons(para escolher se quer pesquisar nome ou categoria) e uma caixa de texto para a pesquisa. O que eu quero que essa parte do programa faça é que pesquise filmes, por nome ou categoria. O erro que apareceu, antes de por o código para pesquisa não aparecia. Mais uma vez, peço desculpa.
Answer: O problema ocorre porque o search está null.
Inverta a ordem.
De
x => x.MovieCategory==search || search == null

Mude para
x => search == null || x.MovieCategory==search

O motivo é que o StartsWith lança uma exception se o valor passado for null.
Quando se faz ||, o .net primeiro verifica a condição anterior ao || e depois a posterior. Se a primeira já atender (no caso do OR, for true), ele não passa pela segunda.
Mais detalhes sobre os operadores || e |
Comment: Bom, aí é outro erro. Provavelmente sua view espera um `MovieViewModel[]` mas você está passando uma lista (afinal, está utilizando o `.ToList()`. Mas eu sugeriria criar uma pergunta para cada erro diferente, isso facilita os futuros usuários que tiverem o mesmo problema a encontrarem a solução com mais facilidade.
Comment: Mas assim dá um erro no 'x', no '=>' e outra vez no 'x'
Comment: Utilizou assim?
`return View(movies.Where(x => search == null || x.MovieName.StartsWith(search)).ToList());`
Comment: eita, deu um erro muito maior agora: System.InvalidOperationException: The model item passed into the dictionary is of type 'System.Collections.Generic.List`1[WebApplication3.Models.MovieViewModel]', but this dictionary requires a model item of type 'WebApplication3.Models.MovieViewModel[]'.


Monitoring rest API calls in java/spring rest

Question: I have a use case where we implemented spring rest api calls like below
<code>/customer/payment
/customer/info
</code>
But I wanted to implement or design the system like how many users are hitting my API in a day per user
And what API they tried to access ?
As I know we have to intercept the request and read the headers and body of the request and store into some where by wring some other service.
Is it correct or something we have in spring framework it self ?
Please suggest
Answer: Have a look at Spring Boot Actuator.  There's some additional reading available here: https://www.baeldung.com/spring-boot-actuator-http.
Comment: Thanks Riaan and got it . Is there any other way we can build like custom service by adding annotations on rest service method and any sample code stuff . I would help alot.
Comment: For that, you'll probably want to look at Interceptors instead - https://www.baeldung.com/spring-http-logging.