If linear combination of two time series processes is non-stationary does it mean one of the two series is non-stationary

Question: Suppose I have 2 time-series processes.
If they are jointly weakly stationary then the linear combination is weakly stationary.
If the linear combination is non-stationary does it mean at least one of the two processes is non-stationary?
I can't come up with an example of where this last statement is false.
Answer: Here's a simple counterexample (for discrete time).  Let $X_t$ and $Z_t$ be iid standard Normal sequences.  Let $\alpha_t$ be a sequence of numbers in $(-1,1)$. Define $Y_t=\alpha_t X_t+\beta_t Z_t$.  Now

$Y_t$ is independent for different times.
The variance of $Y_t$ is $\alpha_t^2+\beta_t^2$ so given any $\alpha_t$ with $|\alpha_t|<1$ we can (and do) choose $\beta_t$ to make $Y_t$ standard Normal
therefore $Y_t$ is weakly stationary: its distributions are all standard Normal
But $\mathrm{cov}[X_t,Y_t]= \alpha_t$

Now consider the linear combination $Y_t-\alpha X_t=\beta_t Z_t$.  This series is not weakly stationary because $\beta_t$ changes over time.  The variance at time $t$ is $\beta_t^2$, which is not constant.
The condition you'd need for weak stationarity of linear combinations is that the pair $(X_t, Y_t)$ were individually weak-stationary and that their covariance was constant over time.  You could say they were "jointly weak stationary", though I don't know whether this is standard terminology.
Two final notes: first, $X_t$ and $Y_t$ in this example are strongly stationary as well as weakly stationary. Second, $X_t$ and $Y_t$ are each uncorrelated over time, but that would be easy to change.
Answer: Let $$Z_t=aX_t+bY_t$$
Given that $Z_t$ is is NOT stationary, but $X_t$ and $Y_t$ are stationary.
So, we can say that $\exists \,\ s \neq t$ such that $$E(Z_t)\neq E(Z_s)$$
$$\implies aE(X_t) + bE(Y_t) \neq aE(X_s) + bE(Y_s)$$
However, $E(X_t)= E(X_s)$ and $E(Y_t)= E(Y_s)$, $\forall \,\, t,s$
So there is a contradiction.
EDIT: Apologies for childish answer above. Another attempt. Let me try using logic statements.
Statement $A$: $Z_t$ is non-stationary.
Statement $B$: At least one of $X_t$ and $Y_t$ is non-stationary.
Let's assume that what you say is correct, i.e.,
$$A \implies B $$
So, $$!B \implies !A $$
This would mean that each of $X_t$ and $Y_t$ being stationary (statement !B) would imply stationarity of linear combination of $X_t$ and $Y_t$. We know this to be not always true. So $A \implies B $ is also not true.
Comment: $E(Z_t)\neq E(Z_s)$ is one special case of nonstationarity. The condition is sufficient for nonstationarity but not necessary. Hence, your proof does not address the general case.
Comment: If the processes are zero mean then this is not enough. I think $X_t$ and $Y_t$ can be individually stationary, but not jointly.
Comment: @RichardHardy: Thanks for pointing this out. This is obviously a stupid mistake.
Comment: @shani: Correct. I made another attempt.
Comment: weakly stationary (WS ) refers only to the means and variance of the series being constant and independent of $t$.. We know  the mean of the resulting series in a linear combination of the individual means so that should still be constant and independent of $t$. The variance is a linear combination of the variances  but includes a covariance.  Therefore,  the linear combination of the two series is not necessarily WS because one doesn't know if the covariance of the two series is time invariant. If it is not, then the resulting variance is not constant and WS does not hold.


Partition of graph with $\lambda(G)$

Question: Let $\lambda(G)=\min\{|X|:X \subset E(G) \wedge G-Y \text{ is not
connected} \}$ (minimum number of edged to delete to disconnect conntected graph). Let $\lambda(G) = k > 0$. Show that there is such partition $\{U, V\}$ of vertices that there is $k$ edges with one end in $U$ and with the other end in $V$.
My attempt:
Let $K$ be the set of edges from $\lambda(G)$. $G-K$ is disconnected and since $K$ is the smallest set of edges to disconnect graph $G$, $G-K$ has two components $C_1, C_2$. Now consider graph $C_1 \cup C_2 \cup K = G$. Edges from $K$ must have one end in $C_1$ and the other one in $C_2$ (so there are exactly $k$ vertices in each wchich connect with the other component). If some edge $e\in K$ connected $u, v \in C_1$ (for $C_2$ symtrically) then $K$ wouldn't be minimal - because after deleting this edge $C_1$ is still connected and thus it wasn't necessary to delete that edge to disconnect the graph. So in $K$ are only edges in form $\{v, u\}$ where $v \in C_1, \ u \in C_2$. The partition $\{U, V \}$ is $\{C_1, C_2 \}$.
I'd like to know if my thinking is correct. Thank you in advance.
Answer: The logic is (essentially) correct. I have a few minor things to point out.
You are making a bit of a leap when you say

since $K$ is the smallest set of edges to disconnect graph $G$, $G−K$ has two components $C_1, C_2$.

In principle there could be more components; it takes some extra argument to say that if there were more components, $G-K$ wouldn't be minimal. You could include that argument, but you don't need it.
It is simpler to say that since $K$ disconnects $G$, $G-K$ has some connected component $C_1$ which is not all of $G$. Let $C_2 = G - C_1$: the rest of $G$, whether that's connected or not. Now your argument still shows that all edges of $K$ must go between $C_1$ and $C_2$, otherwise they could be omitted.
Also, the argument

after deleting this edge $C_1$ is still connected and thus it wasn't necessary to delete that edge to disconnect the graph

isn't quite what you want here. It doesn't matter whether $C_1$ is connected or not after deleting that edge. The point is that if an edge $e$ does not go between $C_1$ and $C_2$, then $K' = K - \{e\}$ is also an edge cut, because $G - K'$ still has no edges between $C_1$ and $C_2$, so it's not connected.

Partition of graph with $\lambda(G)$


firewalld allowing non-specified ports through

Question: I'm running the latest version of CentOS 7 (kernel version  3.10.0-1062.4.1.el7.x86_64) I have specified a custom firewalld zone, in which I have specified a port and a source ipset. I am expecting that both of these criteria should be applied. However, I am able to connect to the system (from an allowed source IP), but from a different port. Is this how the zone configuration is supposed to work?
Here is my zone config:
<?xml version="1.0" encoding="utf-8"?>
<zone target="ACCEPT">
  <port port="8080" protocol="tcp"/>
  <source ipset="authorized-ips"/>
</zone>

Here is my ipset config:
<?xml version="1.0" encoding="utf-8"?>
<ipset type="hash:ip">

  <entry>192.168.123.123</entry>

  <entry>192.168.123.124</entry>
</ipset>

If I connect using port 8008 or 8009, then I am still able to access the application via apache. But I have not explicitly allowed these ports through the firewall!
The output of running: firewall-cmd --list-all --zone=ACCEPT
Error: INVALID_ZONE: ACCEPT
Answer: It's  unusual to edit firewalld this way. Can you post output from firewall-cmd --list-all --zone=ACCEPT - this way we'd know how your config was parsed and implemented by the daemon.
Comment: Have added the response to the original question. (Could you tell me why it is unusual to manage firewalld this way, and what would be a more appropriate way to achieve the same thing)


Automatic SyntaxHighlighter with Prettify

Question: Working on a school project where we have creating a forum based website. We are using PageDown and Prettify to handle the text.
 but like it's now we have to use on the code to get it out nice and smooth, but are there some way we can tell the program to handle all
tags from PageDown automatic with prettify?
Are there some disadvantage to have automatic SyntaxHighlighter?

1# Possible solution, but not what i had in mind:
You can add $("pre").addClass("prettyprint"); to javascript. This code will give every pre tag the prettyprint class, but this short code will not work in Markdown preview so for me this is only a 50% solution.

2# Possible solution on preview, but not user friendly:
I have found out that you can call a function prettyPrint(); to highlight all the
tags with class="prettyprint". So if we combined solution on with this and add a setInterval()(or something else like .click) to make calls we will get something that work with Markdown preview. I believe this way is not user friendly because it's using alot of computer power (I think) and if you watch closely you can see a little flicker sometimes in the
 tags.
This is the code:
var timer = setInterval(prettytimer, 0);

function prettytimer() {
    $("pre").addClass("prettyprint");
    prettyPrint();
};

If someone wondering why there is no .removeClass() or hasClass() check, that's because .addClass() doesn't add same class twice.
Answer: 3# solution i went for:
This is the solution i went for in the preview handler site and solution 1# on rest of the web-page. There might be some better ways but this way will give you the Stack Overflow feeling.
var timer;

//If the code button have been pressed {}
$("#wmd-code-button").click(function () {
    clearTimeout(timer);
    timer = setTimeout(prettytimer, 3000);
});

//when on key have been released inside textarea
$(".wmd-input").on("keyup", function () {
    clearTimeout(timer);
    timer = setTimeout(prettytimer, 3000);
});

//If `timer` reach 3000 (3 seconds) execute this
function prettytimer() {
    $("pre").addClass("prettyprint");
    prettyPrint();
};

If you are using pageDown Markdown then you don't have to make any changes to this code, just copy it inside your javascript file :)


How to pass a record to a decision tree?

Question: I'm working a small project. Lets say, I have a table of around 100K records containing columns like Age, Gender, Region, Life(nominal - range of days the products is used) etc., Here Life is a dependent variable and all others are independent variable.I created a decision tree out of the data available. Now my query is, suppose if I have one new record, I want to know in which terminal node that record falls after traversing the decision tree i.e., under which Life range does that record falls. For that, how can I pass that record to the decision tree and get a output?
Comment: Some code would be helpful here. Do you use an own DT implementation or an existing package? Normally you can use the function `predict()`to evaluate new data in an existing object.
Comment: which package do you use?
Answer: predict(model,newdata)
Let's say your original data.frame had 4 columns as you list in your question.  Your new record would need to be formated as a data.frame with the same columns names as your independent factors, e.g., newdata = data.frame(Age=15,Gender="Male",Region="Southwest") or whatever those values should be.  Let's assume you've stored your model thusly model = rpart(Life~.,data=data,method="class") then predict(model,newdata) will return a vector of the probability that the new record belongs to each of the terminal classes.  You then need to have some cutoff logic to determine which group you'll assign it to.


Does View.removeAllViews() release memory?

Question: I experienced OutOfMemory exception in my code, so I am reviewing the code.
I have a question, does View.removeAllViews() release the memory that were used by the child views that were previously added into this the parent view?
Thanks.
Answer: View.removeAllViews() might release the Views, and will schedule them for garbage collection (which could occur later) however you might still have a problem because @drawables in the XML or in your code with 'getDrawable()' could still consume memory.
I have struggled with OutOfMemory errors a lot myself and found that the biggest issue was not the Layout XML or the View objects, but the Drawables and Resources that they loaded (or I loaded to attach to them.)
A great talk on this can be found on YouTube from Google IO 2011:
http://www.youtube.com/watch?v=_CruQY55HOk
This talk introduces using the Eclipse MAT (Memory Analysis Tool) to troubleshoot OutOfMemory exceptions.  I suggest it because you mention you're reviewing code and the best place to start looking for an OutOfMemory error is ... "what is taking up my memory?"
Answer: Except if your code has references on the ViewGroup's child views, all ViewGroup's child views should be "garbage collectable".


How do I STOP a webpage being auto scrolled again and again after it reaches to the bottom?

Question: I am a newbie and trying to implement a JS code via Greasemonky that auto scrolls till the very bottom of the page. But if I scroll up, it keeps scrolling again so I want it to stop scrolling once I click a stop button.
// Scrolls till the bottom
setInterval(function(s){scrollBy(0,s||10000)},1000);

//script that creates a button
var input = document.createElement('input');
input.type = 'button';
input.value = 'Stop scrolling';
input.onclick = stopScroll;
document.body.appendChild(input);

//I need help here, not sure how to use clearInterval.
function stopScroll()
{
  clearInterval();
}

Answer: First, declare variable interval
var interval = setInterval(function(s){scrollBy(0,s||10000)},1000);

and then clean it in function
function stopScroll()
{
clearInterval(interval);
}

Comment: [Here is the documentation](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.setInterval) and [here](https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers.clearInterval).


Imagesearch Limit in functions?

Question: I have been making a complicated bot, and I have hit a brick wall while trying to add any new features with imagesearch, Most of these searches require locating(Or not locating) a image. But now, every function I try to add just goes crazy, sometimes it will just run in a loop, unable to find a image, sometimes it will move to 778, 194 and just continue clicking as if every search was supposed to click at 778, 194. I'm sure it is something overly simple, I'm just going blind reading these chunks over and over again.
Source code:
demand()
{
global img_battle
global img_battle2
global img_demand
global img_lolcheck
global img_lolmarket
global img_demandcontrol
global img_demandlower
global img_demandhigher
global img_demand2

ImageSearch, myszX, myszY, 1, 1, windowSizeX, windowSizeY, *10 %img_demand%
8:
if (ErrorLevel = 0) {
  4:
  MouseMove, 778, 194
  Sleep, 500
  ImageSearch, myszX, myszY, 1, 1, windowSizeX, windowSizeY, *10 %img_lolmarket%
  if (ErrorLevel = 0){
    MouseMove, myszX + 15, myszY + 2
    sleep, 500
    MouseClick, Left,
    sleep, 500
    ImageSearch, myszX, myszY, 1, 1, windowSizeX, windowSizeY, *10 %img_lolcheck%
    if (ErrorLevel = 0) {
      sleep, 500
      5:
      ImageSearch, myszX, myszY, 1, 1, windowSizeX, windowSizeY, *10 %img_demandcontrol%
      if (ErrorLevel = 0) {
        MouseMove, myszX + 15, myszY + 2
        sleep, 500
        MouseClick, Left,
        Sleep, 500
        ImageSearch, myszX, myszY, 1, 1, windowSizeX, windowSizeY, *10 %img_demandlower%
        if (ErrorLevel = 0) {
          MouseMove, myszX + 15, myszY + 2
          sleep, 500
          MouseClick, Left
          Sleep, 500
          6:
          MouseMove, 716, 197
          Sleep, 500
          ImageSearch, myszX, myszY, 1, 1, windowSizeX, windowSizeY, *10 %img_battle%
          if (ErrorLevel = 0){
            MouseMove, myszX +15, myszY +2
            Sleep, 500
            MouseClick,
            Sleep, 500
            ImageSearch, myszX, myszY, 1, 1, windowSizeX, windowSizeY, *10 %img_battle2%
            if (ErrorLevel = 1){
              goto, 6
                               }
                             }
                           }
      else{
        goto, 5
      }
                         }
                       }
      else {
        goto, 4
      }
                     }
                   }
else{
  ImageSearch, myszX, myszY, 1, 1, windowSizeX, windowSizeY, *10 %img_demand2%
  if (ErrorLevel = 1) {
    goto, 8
  }
}
}

Comment: It looks like you do not check your `ErrorLevel` after using `ImageSearch` under label `4`. Also, people are more inclined to help if you clean up the indentation/spacing of your code.  Right now it is barely readable.
Comment: @ElliotDeNolf
I wasn't, It probably happened within the few hours of error testing, however, now it is stuck back to just not finding the images. I cleaned up my code a bit, is this good? if not, please be specific on the formatting. Also; this might be of no use, but here is the log for my `demand()` function
`137: demand()
285: ImageSearch,myszX,myszY,1,1,windowSizeX,windowSizeY,*10 %img_demand%
287: if (ErrorLevel = 0)
339: ImageSearch,myszX,myszY,1,1,windowSizeX,windowSizeY,*10 %img_demand2%
340: if (ErrorLevel = 1)
343: }
344: }`
Answer: I think you need command CoordMode http://ahkscript.org/docs/commands/CoordMode.htm
That command sets coordinate mode for various commands (including ImageSearch and MouseMove commands) to be relative to either the active window or the screen.
Add these two lines to beginning of file (before function call):
CoordMode, Pixel, Screen
CoordMode, Mouse, Screen

First line will set coordinate mode for ImageSearch command and second line for MouseMove command relative to screen.

Imagesearch Limit in functions?


PHP and JS in order to manage and draw graphs

Question: I have a project to draw relationships between different elements determined on a sheet.
When the user has finished making the plan, it can export it to a txt file that contains the links.
A bit like MS Visio but with only three or four elements draguable.
Does anyone have an idea of this project using web languages (php, js) ?
Thank you in advance.
Answer: Take a look at Raphael, you can make your users draw anything you want, export the structure as JSON,for example, and treat it with any language you want
Take a look at this Raphael example to see an interconnected graph
Answer: I am not so sure of your question but if you want to draw graphs using php variables with javascript, then the html5 canvas is probably your best bet in terms or proffessionality with design and implementation.
Only downside is it is javascript only, and the user must have a browser that supports canvas.


How to find all possible continuous functions given what the function does to each value.

Question: Question: Find all possible continuous functions $f:[0,1]\to \mathbb{R}$ such that $\forall x \in [0,1]$ we have $(f(x))^2=1$
My Work: I truly am not sure how to go about this. I don't quite understand what they mean by find all continuous functions. Any help on explaining what this question is asking would be great.
Thanks
Comment: If $(f(x))^2=1$, then $f(x)$ has to be $\pm 1$ right?  Then, ask yourself if it can be $1$ for some $x$'s and $-1$ for others while also being continuous.  This should lead you to the answer.
Comment: Since $[0,1]$ is connected, if $f$ is continuous, then $f[0,1]$ must be connected too. The constraint implies $f(x) = \pm 1$ for all $x$, hence it must take exactly one of these values (otherwise the range in not connected).
Answer: There are only two of them, the constant functions $1$ and $-1$.
Clearly $f(x)=\pm 1$ for all $x$. If there are places $a$ and $b$ such that $f(a)=-1$ and $f(b)=1$, then by the Intermediate Value Theorem there is a $c$ between $a$ and $b$ such that $f(c)=0$. This is impossible.
Answer: Let $f$ be one such function.
Take a specific $x_1$ (say, $x_1=0.22$).
What could $f(x_1)$ be? (hint: only two values are possible).
Now, take some other $x_2$ (say, $x_2=0.37$).
What could $f(x_2)$ be?
Suppose it is different from $f(x_1)$. What does the intermediate value theorem tell you?
Answer: What does $(f(x))^2=1$ say about $f(x)$? Then what does the continuity imply?
Answer: Depending on your definition of the real numbers - and if you haven't studied connectedness yet, you might want to identify the value of $f(0)$ and look at $X= \sup x:f(x)=f(0)$ and apply continuity at $X$.
Comment: There is a trick you can use, which is to extend the condition so that $f(x)=f(0)$ and there is no $y<x : f(y) \neq f(x)$ - which mirrors some proofs of the intermediate value theorem (see André Nicholas' answer).


How do you go to an overlay view within Drupal using drupal_goto?

Question: I want to redirect to a page with an overlay within code.  I have tried the following, which is the path in the URL.
 drupal_goto('#overlay=admin/vendor/auth-stripe');

The path I want in overlay is admin/vendor/auth-stripe.  When I remove the #overlay= it works, but I want my user to see it in overlay mode.
Answer: You cannot pass a URL fragment into drupal_goto() like that or it will get escaped and won't work properly.
From the drupal_goto() docs it says the second parameter is an array of $options that get sent through to the url() function.
Looking at the url() function docs shows that one of the allowed $options is:

'fragment': A fragment identifier (named anchor) to append to the URL. Do not include the leading '#' character.

So you should be able to do this:
drupal_goto(current_path(), array('fragment' => 'overlay=admin/vendor/auth-stripe'));

Note the use of current_path() as the path so that the page under the overlay will be the on the user was previously on.
If you didn't want that, then this would use the front page instead of the current page (because if you pass an empty path into the url() function it uses the front page as a default):
drupal_goto('', array('fragment' => 'overlay=admin/vendor/auth-stripe'));

Comment: I was able to successfully use the fragment option using


Executing procedure in @Scheduled leaves open connection

Question: I have web application peridicly syncing data with calling stored procedure. I don't wont execute procedure in transaction.
After each procedure call entity manager didn't close and leaves connection in connection pool until pool reach max connections and application hangs.
SharedEntityManagerCreator creates EntityManager and did't close it after import method call because repository executes "execute" method on query but SharedEntityManagerCreator specifies only
    queryTerminationMethods.add("getResultList");
    queryTerminationMethods.add("getSingleResult");
    queryTerminationMethods.add("executeUpdate");

Is this a bug or i am using it wrong?
Here is my service
@Service("importService")
@Slf4j
public class ImportService {

    @Autowired
    private UserRepository userRepository;

    public ImportService() {
    }

    @Scheduled(cron = "${import.cron.pattern}")
    public void importData() {
        userRepository.ImportUserProcedure();
    }

}

and repository calling stored procedure
@Repository
public interface UserRepository extends CrudRepository<AuthUser, Integer> {

    @Procedure(procedureName = User.ImportUserProcedure)
    void ImportUserProcedure();
}

Comment: Your service should be `@Transactional`.
Comment: but if i call ImportUserProcedure from test rest enpoint connections get released
Comment: Because those are generally transactional by default (depending on your setup) or the context is closed closing all connections.
Answer: I had this same problem and was glad to find this post for a quick answer. As pointed out in the comments add the Transactional annotation to your procedure function and the connections won't leak.
@Repository
public interface UserRepository extends CrudRepository<AuthUser, Integer> {

    @Transactional
    @Procedure(procedureName = User.ImportUserProcedure)
    void ImportUserProcedure();
}


Sum up column based on two dates in a different dataframe

Question: I'm trying to sum a column if it falls between two dates and based on a jobid. I'm using the below function but I keep zero as the sum value.
def jobrun (row):
return table1[(table1.job == row['job']) & \
        (table1.date >= row['past']) & \
        (table1.date < row['present'])]['Hours'].sum()

table2['Usage'] = table2.apply(lambda row: jobrun(row), axis = 1)

all the date columns are converted to <datecolumn>.astype('datetime64').dt.strftime('%d/%m/%Y')
Please let me know what I missing.

Table1
Job Hours   Date
706010  2.935   01/03/20
706010  14.9936 02/03/20
706010  14.9079 03/03/20
706010  11.1339 04/03/20
706010  0.0172  06/03/20
706010  0.0172  07/03/20
706011  0.0175  10/03/20
706011  0.0508  14/03/20
706011  0.085   16/03/20
706011  0.0347  17/03/20
706011  0.0078  18/03/20
706011  0.0169  30/03/20
706011  0.0006  01/04/20
706011  0.0172  04/04/20
706011  2.642   05/04/20
706011  6.5853  06/04/20
706011  0.2653  07/04/20
706011  0.0175  08/04/20
706012  0.0375  09/04/20
706012  0.0339  12/04/20
706012  0.0169  13/04/20
706012  0.0167  15/04/20
706012  0.1169  20/04/20
706012  0.3003  21/04/20
706012  0.0169  26/04/20
706012  6.7994  30/10/19

Table2
Job past    present
706010  31/07/2019  2020-04-05
706011  31/11/2019  2020-05-05
706012  31/07/2019  2020-05-05

Expected Output
Job past    present Usage
706010  31/07/2019  2020-04-05  44
706011  31/11/2019  2020-05-05  9
706012  31/07/2019  2020-05-05  7

Comment: It's better if you include a sample of your actual data instead of including the pictures.
Comment: Data added instead of images.
Comment: Here's a novice approach. Join the dataframes on `jobid` and retain the records that are within the range. `(Table1['Date'] >= Table2['past']) & (Table1['Date'] <= Table2['present'])`. The resulting dataframe can be used to sum up the `hours` at `jobid`
Answer: I don't think you can apply jobrun on two dataframes, because it will give you error as ValueError: Can only compare identically-labeled Series objects. (as mentioned in one of the comments)
What you might try is to perform a outer merge of table1 and row based on column job, then modify jobrun, and apply it to the entire merged dataframe df1:
df1=table1.merge(row,left_on='job',right_on='job',how='outer')
def jobrun (df):
    df_out=df[(df.date >= df['past']) & \
        (df.date < df['present'])]
    df_out['Usage']=df_out['Hours'].sum()
    return df_out
jobrun(df1)


Is there a name for a 2-dimensional dumbbell like shape?

Question: Is there a mathematical name for a 2-dimensional shape in the general form of a dumbbell?  That is two circular nodes connected by a center beam such as shown in this image from this answer.  It could also be thought of as a circle that has been pinched together.  I believe topology does not help us here since there are no holes, and thus such as shape is the same as a circle, but perhaps geometry gives us a name for it?
Comment: See [hippopede](https://en.wikipedia.org/wiki/Hippopede).
Comment: Looks a bit like a nephroid but it's not quite right. Feels like there should be a name for it though.
Comment: I doubt there is a general name, but there are curves with this kind of shape, for example the [epitrochoid](https://en.wikipedia.org/wiki/Epitrochoid) with $x=\cos t + \frac14 \cos 3t$ and $y=\sin t + \frac14 \sin 3t$
Answer: The shape reminds of a Cassini oval (http://mathworld.wolfram.com/CassiniOvals.html) but without a more precise equation, one cannot be more specific.
Answer: You can try this
$$x^4-4(x^2-y^2+0.5)=0$$
Comment: They're asking for the name of the shape, not an equation.


rate limit apache httpd server

Question: I have an apache server that acts as a load balancer to pass off requests to tomcat application servers.  I wish to rate limit the http access by ips, and potentially throttle requests, how can this be done?
Comment: Related: http://serverfault.com/questions/252555/limit-simultaneous-connections-per-ip-with-apache2
Answer: A possible solution can be using iproute2 htb. see this for an idea:
http://luxik.cdi.cz/~devik/qos/htb/manual/userg.htm

rate limit apache httpd server


Consulta de data no calendario python?

Question: Estou estudando python a pouco mais de uma semana, mas gostaria de realizar uma ação mais ou manos da seguinte forma.
sera colocado o valor monetário e coloca o dia de fechamento do cartão e o dia de pagamento da fatura.
quando realizar uma compra ele consulta o calendário e verifica, esta dentro da data de fechamento do cartão este mês ou não...
chegou no dia de pagamento da fatura automaticamente subtrai o valor que foi realizado nas compras de cartão de credito no mês.
Se alguém poder ajudar a entender, não estou conseguindo !
Obrigado !
I'm studying python with just over a week but would like to perform a more or less hands action as follows.
be the place the monetary value and the closing day of the card and the day of payment of the invoice.
when making a query he consults the calendar and checks, this is within the closing date of the card this month or not ...
arrived on the bill payment day automatically subtracts the amount that was made on credit card purchases in the month.
If I can help, I can not!
Thank you!
Comment: Olá Rodrigo, aqui é o SO em Português. Não é necessário a parte em inglês da sua pergunta.
Comment: Ok, obrigado não sabia !
Answer: Respondendo apenas ao titulo.
Bem vindo ao stackoverflow Rodrigo, você pode usar a biblioteca datetime e importar o datetime. Da uma olhada nesse código para Python 3.
<code># importação da biblioteca datetime
from datetime import datetime

# Checagem dos dados nesse momento de acordo com o seu computador
data = datetime.now()

# Vamos 'formatar' a saída. Dia, Mes, Ano, Hora, Minuto e Segundo'
data_print = data.strftime('%d/%m/%Y %H:%M:%S')

# Vamos exibir as informações
print(data_print)
</code>
Respondendo a pergunta no geral
<code># Vamos importar o datetime
from datetime import datetime

# Vamos definir que esse será o dia da fatura
data_da_fatura = '05/04/2019'

# Checagem dos dados nesse momento de acordo com o seu computador
data = datetime.now()

# Vamos 'formatar' a saída. Dia, Mes, Ano, Hora, Minuto e Segundo' e converter para string com o str()
data_dados = str(data.strftime('%d/%m/%Y'))

# Vamos usar o if para checar se a data da fatura chegou
if data_da_fatura == data_dados:

    # Um indicador que está funcionando
    print('subtrair')
</code>
A partir daqui, acho que você pode usar a criatividade para usar esses conceitos no seu estudo
Comment: Obrigado, vou tentar !

Consulta de data no calendario python?


extending a vector field defined on a closed submanifold

Question: Let $M$ be a differentiable (smooth) manifold, and $S$ a closed submanifold. Let $X$ be a vector field on $S$. Prove that $X$ is the restriction of a vector field $Y$ defined on $M$. I tried this way but i'm not completely sure: i choose a covering (maybe finite if with closed we intend compact) of $S$ with $U_j$ open in $M$. Then i consider a partition of unity $w_i$ subordinate to this covering (can I?). Then i have $Z=\sum_i w_iX$ is a vector field extending $X$ in the open covering. Then i use a result that states that i can extend on the whole $M$ a vector field defined in an open set of $M$. Is this correct?
Comment: Simple remark : you can't always extend a vector field defined on an open subset of a manifold. Take $\frac{1}{x}\frac{\partial}{\partial x}$ on $\mathbb{R}^*$ : it can't be extented to $\mathbb{R}$
Comment: You mean the second sentence to to say `Let $X$ be a vector field on $S$'?
Comment: The support of $w_i$ is going to have more than just points of $S$ so how is $w_i X$ defined on $M$?
Comment: @ Eric: you're right, this way $w_iX$ is not defined outside S..
Comment: @Selim Ghazouani: you're right, the result i cited was about constructing a vector field defined on M which is equal to the given vector field in an open subset on the given set.
Comment: @treble: yes on S
Comment: i updated the exercise with this last correction
Answer: Take a submanifold chart $x:U\rightarrow x(U) \subseteq \mathbb R^n$ such that $x(S\cap U) = \{x^{k+1}=\dots x^n=0\}$ (edit: and $x(U)$ is a ball)).
Then you can define a vector field $Z$ on $x(U)$, by
$$
 Z(x_1,\dots,x_n):=x_* (X(x^{-1}(x_1,\dots,x_k,0,\dots,0)))
$$
Transport back to $M$ and get $x^{-1}_* Z$ on $U$ and then use a partition of unity argument!
Comment: Could you please explain what $x_*$ is?
Comment: $x_*$ is the map on vector fields induced by the diffeomorphism $x$.
Comment: Sorry, what is the partition of unity argument?
Comment: Why do you need $x(U)$ to be a ball?
Comment: @CuriousKid7 So we can have $(x_1,\dots,x_k,0,\dots,0)\in x(U)$ for any $(x_1,\dots,x_n)\in x(U)$.


jqplot xaxis not starting from the given hour

Question: The xaxis being rendered does not start from the given hour in the data.
PFB the JSFiddle for reference
https://jsfiddle.net/sonal215/6Lg9f5dx/
the code is as follows:
$(document).ready(function(){

var l1 = [['5/17/2016 10 AM', 78], ['5/17/2016 11 AM', 34], ['5/17/2016 12 PM', 67], ['5/17/2016 1 PM' , 18], ['5/17/2016 2 PM' , 33],['5/17/2016 3 PM', 7],['5/17/2016 4 PM', 13],['5/17/2016 5 PM' , 73],['5/17/2016 6 PM' , 93],['5/17/2016 7 PM' , 43],['5/17/2016 8 PM' , 53],['5/17/2016 9 PM' , 11],['5/17/2016 10 PM' , 83],['5/17/2016 11 PM' , 23]];

targetPlot = $.jqplot('targetAvailability', [l1], {
            seriesDefaults:{
                showMarker: false,
                fill: true,

            },
            tickInset: 0,
            axes: {
                xaxis:
                {
                    renderer:$.jqplot.DateAxisRenderer,
                    tickRenderer:$.jqplot.AxisTickRenderer,
                    tickOptions:
                    {
                        showGridline: false,
                        fontSize: '11px',
                        fontFamily: 'CiscoSansTTLight' ,

                    },
                    tickInterval: '8 hour',
                    min: '5/17/2016 11 AM',

                },
                yaxis: {
                    tickOptions:
                    {
                        fontSize: '11px',
                        fontFamily: 'CiscoSansTTLight' ,
                    },
                    min: 0,
                    max: 100,
                    tickInterval: 25
                }
            },

            cursor: {
                show: true,
                zoom: true,
                showTooltip: false
            }
        });   //end of targetPlot

}); //end of document ready

I tried changing the tickInterval to 6 hour, the x-axis then starts rendering from 6:00. i am unable to make out the relation between tickInterval and starting point of ticks. Please help
Answer: You should remove the tickInterval and set min and max points definition for the xaxis:
xaxis:
{
    min:'5/17/2016 10 AM',
    max:'5/17/2016 11 PM',
    ...rest of the code

I've updated your Fiddle with a working example:
https://jsfiddle.net/6Lg9f5dx/4/
If you want to keep the tickInterval, remove the max definition and use only min.


Android Music Player Notification with Progress Bar

Question: I'm developing music player notification with progress bar . Somehow I managed to show progress with Handler but now the problem is after some time whole android system freezes. And then rebooting the system is only a solution.
I'm new in android and this is my first app, please help me to complete my first app. I will be very thankful to you.
 Here is Screenshot of Music Player Notification with Progress Bar
I've attached screenshot of notification and here is my code. These codes are running in media player foreground service
Some global variables:
<code>    private static RemoteViews views;
    private static RemoteViews bigViews;
    private static Notification status;
    private static final int NOTIFICATION_ID = 101;
    public Handler mSeekbarUpdateHandler= new Handler();
</code>
This is Runnable code:
<code>public Runnable mUpdateseekbar=new Runnable() {
@Override
public void run() {
    if(mediaPlayer != null) {
        bigViews.setProgressBar(R.id.progressBar, mediaPlayer.getDuration(), mediaPlayer.getCurrentPosition(), false);

        bigViews.setTextViewText(R.id.time_start, timeConvert(mediaPlayer.getCurrentPosition()));
    }

  startForeground(NOTIFICATION_ID, status);

   mSeekbarUpdateHandler.postDelayed(this,1000);
}};
</code>
Now calling handler:
<code>@Override
public void onPlay() {

super.onPlay();
resumeMedia();

buildNotification(PlaybackStatus.PLAYING);

mSeekbarUpdateHandler.postDelayed(mUpdateseekbar,0);

//also calling this Handler  from method onSkipToNext() and previous. it means when changing song also calling Handler each time.
</code>
Finally build notification code:
<code>    private void buildNotification(PlaybackStatus playbackStatus)
     {
    //This section containing long code which works fine so no need to make post longer.

    }
</code>
when running this code after few minute system becomes slow and finally freeze.
After removing Handler no problem occurs in notification but my progress bar not updating.
}
Comment: check this https://stackoverflow.com/questions/17168215/seekbar-and-media-player-in-android hope this helps
Comment: Thanks, but this code is for Activity and my problem is for Background Service and notification. so at first we have to find the Exact problem. Please help me I'm struggling since three weeks for this code.
Answer: I have successfully solved this issue by every time Re-building whole notification in the Runnable ...
I have replaced above Runnable code with the following code...
<code> public Runnable mUpdateseekbar = new Runnable() {
    @Override
    public void run() {
        if (mediaPlayer.isPlaying()) {

            buildNotification(PlaybackStatus.PLAYING);

                       }

        mSeekbarUpdateHandler.postDelayed(this, 1000);
    }
};
</code>
And here's the buildNotification method..
<code>   private void buildNotification(PlaybackStatus playbackStatus) {
    RemoteViews views;
    RemoteViews bigViews;
    Notification status;

    try {

        int notificationAction = android.R.drawable.ic_media_pause;
        PendingIntent play_pauseAction = null;

        if (playbackStatus == PlaybackStatus.PLAYING) {
            notificationAction = R.drawable.noty_pause;
            play_pauseAction = playbackAction(1);

        } else if (playbackStatus == PlaybackStatus.PAUSED) {

            notificationAction = R.drawable.noty_play;
            play_pauseAction = playbackAction(0);

        }

        views = new RemoteViews(getPackageName(),
                R.layout.status_bar);

        bigViews = new RemoteViews(getPackageName(),
                R.layout.status_bar_expanded);

        views.setImageViewBitmap(R.id.status_bar_album_art,
                largeIcon);

        bigViews.setImageViewBitmap(R.id.status_bar_album_art,
                largeIcon);

        views.setImageViewResource(R.id.status_bar_playPause,
                notificationAction);

        bigViews.setImageViewResource(R.id.status_bar_play,
                notificationAction);

        bigViews.setProgressBar(R.id.progressBar, mediaPlayer.getDuration(), mediaPlayer.getCurrentPosition(), false);

        views.setTextViewText(R.id.status_bar_track_name, activeAudio.getTitle());
        bigViews.setTextViewText(R.id.status_bar_track_name, activeAudio.getTitle());

        views.setTextViewText(R.id.status_bar_artist_name, activeAudio.getAlbum() + "-" + activeAudio.getArtist());
        bigViews.setTextViewText(R.id.status_bar_artist_name, activeAudio.getAlbum() + "-" + activeAudio.getArtist());

        views.setTextViewText(R.id.status_bar_metadata, displayMeta);
        bigViews.setTextViewText(R.id.status_bar_album_name, displayMeta);
        bigViews.setTextViewText(R.id.track_num, (audioIndex + 1) + "/" + audioList.size());

        bigViews.setTextViewText(R.id.end_time, timeConvert(mediaPlayer.getDuration()));

        bigViews.setTextViewText(R.id.time_start, timeConvert(mediaPlayer.getCurrentPosition()));

        views.setOnClickPendingIntent(R.id.status_bar_playPause, play_pauseAction);
        bigViews.setOnClickPendingIntent(R.id.status_bar_play, play_pauseAction);

        views.setOnClickPendingIntent(R.id.status_bar_next, playbackAction(2));
        bigViews.setOnClickPendingIntent(R.id.status_bar_next, playbackAction(2));

        views.setOnClickPendingIntent(R.id.status_bar_previous, playbackAction(3));
        bigViews.setOnClickPendingIntent(R.id.status_bar_prev, playbackAction(3));
        bigViews.setOnClickPendingIntent(R.id.status_bar_ff, playbackAction(5));
        bigViews.setOnClickPendingIntent(R.id.status_bar_rev, playbackAction(6));

        bigViews.setOnClickPendingIntent(R.id.status_bar_collapse, playbackAction(4));
        views.setOnClickPendingIntent(R.id.status_stop,playbackAction(4));

        status = new Notification.Builder(this).build();
        status.contentView = views;
        status.bigContentView = bigViews;
        status.flags = Notification.FLAG_ONGOING_EVENT;

        status.visibility = Notification.VISIBILITY_PUBLIC;
        status.tickerText = activeAudio.getTitle();

        if (playbackStatus==PlaybackStatus.PLAYING) {
            status.icon = R.drawable.notyskeep;
        } else {
            status.icon = R.drawable.noty_small_blue;
        }
        status.priority = Notification.PRIORITY_MAX;
        status.contentIntent = playbackAction(8);
        startForeground(NOTIFICATION_ID, status);

    } catch (Throwable e) {
        Toast.makeText(getApplicationContext(), "Exception raised:" + e, Toast.LENGTH_LONG).show();

    }

}
</code>


Menu fixo não vai para o id de uma  certo quando clica

Question: Tenho esse menu fixo, onde quero que quando clica em um link, faça o rolagem na página e vai para o link que foi clicado.
Não está funcionando direito, como podem ver no link que estou fazendo.
http://220.127.116.11/3dmind/teste2.html
Jquery que faz a rolagem quando clica
$(window).scroll(function (event) {

    var scroll = $(window).scrollTop();
    var item = $('#servicos ul').offset().top;
    if( (scroll+400) > item ){
      animSvg( $('.svg') );
    }

    $('#servicos ul li.bloco').each(function( index ) {
      if( index < (count+1) ){
        var item = $(this).offset().top;
        var anim = $(this).find('.svg-lista');
        if( (scroll+200) > item ){
          var ativo = $('.label_serv a').children('li').eq(index);
          $('.label_serv a li').removeClass('active');
          ativo.addClass('active');

          animSvg( anim );
        }
      }

    });

  });

});

html

            <svg class="primeiro" width="100%" height="100%">
               <rect class="svg" x="50" y="20" rx="20" ry="20" width="150" height="150" data-to="440" >

               </rect>
            </svg>

            <svg class="inverso" width="100%" height="100%">
               <rect class="svg-lista" x="50" y="20" rx="20" ry="20" width="150" height="150" data-to="1940">

               </rect>
            </svg>

ANÁLISE DE IMERSÃO

Utilizamos métodos e ferramentas que nos permitem analisar as estratégias de players que se destacam no seu segmento, afinal, conhecer bem o posicionamento dos concorrentes é fundamental para o planejamento.

            <svg class="esq" width="100%" height="100%">
               <rect class="svg-lista" x="50" y="20" rx="20" ry="20" width="150" height="150" data-to="1740">

               </rect>
            </svg>

FATOR X – DIFERENCIAL

Depois de entender o segmento, é hora
            de encontrar o seu diferencial. Como nos destacaremos no mercado, Preço? Tecnologia? Atendimento? Nossos Consultores apresentarão inúmeras ideias para análise.

            <svg class="inverso" width="100%" height="100%">
               <rect class="svg-lista" x="50" y="20" rx="20" ry="20" width="150" height="150" data-to="1940">

               </rect>
            </svg>

VALIDAÇÃO
Conceito STARTUP

Depois de debater e escolher as melhores ideias, é hora de colocar em prática para validar junto ao mercado quais ações geram mais resultado, agindo de formarápida para agilizar a resposta do consumidor.

            <svg class="esq" width="100%" height="100%">
               <rect class="svg-lista" x="50" y="20" rx="20" ry="20" width="150" height="150" data-to="1740">

               </rect>
            </svg>

ADEQUAÇÃO

Com as análises obtidas, é hora de fazer os ajustes necessários para apresentar oficialmente ao mercado, integrando todos os setores da empresa para otimizar os processos e resultados.

            <svg class="inverso" width="100%" height="100%">
               <rect class="svg-lista" x="50" y="20" rx="20" ry="20" width="150" height="150" data-to="1940">

               </rect>
            </svg>

EXECUÇÃO

Na etapa de execução, além do treinamento da equipe, criamos o Plano de Ação utilizando as melhores estratégias de Inbound e Outbound Marketing.

            <svg class="esq" width="100%" height="100%">
               <rect class="svg-lista" x="50" y="20" rx="20" ry="20" width="150" height="150" data-to="1740">

               </rect>
            </svg>

MONITORAMENTO

Monitorar os resultados e fazer ajustes durante a execução é fundamental para manter-se no caminho certo. A 3Mind acompanha sua equipe até o momento de amadurecimento ideal do projeto.

            <button class="btn-default botao_lista">Ver exemplos de Análise e os Resultados</button>

Ánalise de Imersão

Fator x Difenrencial

      Validação

      Adequação

      Execução

Monitoramento

Resultados

Comment: Precisas realmente de JS pra fazer isso ? só com HTM ja tem como
Comment: precisa pra fazer a animação de rolagem
Answer: Use scrollTop: $('#' + id).offset().top para rolar até a id do elemento. Ficaria assim:
$('html, body').animate({scrollTop: $('#' + id).offset().top}, 'slow');

Exemplo:

function rolar(id){
    $('html, body').animate({scrollTop: $('#' + id).offset().top}, 'slow');
}

Clique aqui para ir à div com id #teste

Nada diz mais sobre um cliente do que seu comportamento de compra. Com esses dados e os sistemas de automação que implementamos, conseguimos fazer com que o cliente volte sempre para a loja porque enviamos produtos dentro daquilo que ele já mostrou interesse ou que precisa de reposição. É marketing automation no mais alto nível.

Olá! Eu sou a div teste!

  Clique aqui para ir à div com id #inicio


Applying a given markup to two consecutive syllables in lyrics

Question: Given the following LilyPond MWE:
melody = \relative c' {
  a( b) c
}

lyra = \lyricmode {
  Foo bar baz
}

lyrb = \lyricmode {
  Foo -- bar baz
}

lyrc = \lyricmode {
  Foo __ bar baz
}

\score {
  <<
    \new Voice = "melody" \melody
    \new Lyrics \lyricsto "melody" \lyra
    \new Lyrics \lyricsto "melody" \lyrb
    \new Lyrics \lyricsto "melody" \lyrc
  >>

  \layout {}
  \midi {}
}

How could I write a custom function that applies a given markup (e.g. bold or italic) to two consecutive syllables in lyrics? And how could I handle the -- or __ between syllables when applying this function?
Answer: If this is really what you want:
The syllables in \lyricmode are music events with the text as text property. The -- and __ things are parsed to articulations. So you can write a music function like this:
applyToTwoSyllables =
#(define-music-function (what syl1 syl2) (symbol? ly:music? ly:music?)
   (ly:music-set-property! syl1 'text
                           (primitive-eval
                            `(markup
                              ,(symbol->keyword what)
                              ,(ly:music-property syl1 'text))))
   (ly:music-set-property! syl2 'text
                           (primitive-eval
                            `(markup
                              ,(symbol->keyword what)
                              ,(ly:music-property syl2 'text))))
   #{ #syl1 #syl2 #})

which essentially takes the name of a markup function (e.g. bold) and two music objects and replaces the text property by essentially (markup #:proc-name original-text). The primitive-eval stuff is only necessary so that the keyword arguments get evaluated correctly. If you create a function for say specifically making thing bold you can simply do
boldTwoSyllables =
#(define-music-function (syl1 syl2) (ly:music? ly:music?)
   (ly:music-set-property! syl1 'text
                           (markup #:bold (ly:music-property syl1 'text)))
   (ly:music-set-property! syl2 'text
                           (markup #:bold (ly:music-property syl2 'text)))
   #{ #syl1 #syl2 #})

lyra = \lyricmode {
  \boldTwoSyllables Foo bar baz
}

In any case you can now do
melody = \relative c' {
  a( b) c d
}

lyra = \lyricmode {
  \applyToTwoSyllables bold Foo bar baz
}

lyrb = \lyricmode {
  \applyToTwoSyllables italic Foo -- bar baz
}

lyrc = \lyricmode {
  Foo __ bar baz
}

\score {
  <<
    \new Voice = "melody" \melody
    \new Lyrics \lyricsto "melody" \lyra
    \new Lyrics \lyricsto "melody" \lyrb
    \new Lyrics \lyricsto "melody" \lyrc
  >>

  \layout {}
  \midi {}
}

EDIT:
You could also generalize this to an arbitrary number of syllables like this:
applyToLyrics =
#(define-music-function (what lyrics) (symbol? ly:music?)
   (define (iter mus)
     (let ((elt (ly:music-property mus 'element))
           (elts (ly:music-property mus 'elements))
           (text (ly:music-property mus 'text)))
       (if (music-is-of-type? mus 'lyric-event)
           (ly:music-set-property! mus 'text
                                   (primitive-eval
                                    `(markup
                                      ,(symbol->keyword what)
                                      ,text))))
       (if (not (null? elt))
           (ly:music-set-property! mus 'element (iter elt)))
       (ly:music-set-property! mus 'elements (map iter elts)))
     mus)
   (iter lyrics))

melody = \relative c' {
  a( b) c d
}

lyra = \lyricmode {
  \applyToLyrics bold { Foo bar } baz
}

lyrb = \lyricmode {
  \applyToLyrics italic Foo -- bar baz
}

lyrc = \lyricmode {
  \applyToLyrics box { Foo __ bar baz }
}

\score {
  <<
    \new Voice = "melody" \melody
    \new Lyrics \lyricsto "melody" \lyra
    \new Lyrics \lyricsto "melody" \lyrb
    \new Lyrics \lyricsto "melody" \lyrc
  >>

  \layout {}
  \midi {}
}

Answer: There is a simpler way: define a Scheme function that inserts the override and revert commands on either side of the lyrics.
This example sets lyrics in italics; to use it you would enclose the relevant lyrics in the command: \EmphLyrics { ly -- rics }.
\version "2.20"

EmphLyrics =
#(define-scheme-function
  (text) (scheme?)
  #{
    \override Lyrics.LyricText.font-shape = #'italic
    $text
    \revert Lyrics.LyricText.font-shape
  #})

{
    c'8 c'8 d'8 d'8 e'8 e'8 f'8 f'8 g'8 g'8 g'4
}
\addlyrics {
    al -- pha be -- ta \EmphLyrics { gam -- ma del -- ta } ep -- si -- lon
}


Images problem after migration

Question: I have a strange problem.
Today I moved a site from staging to production and the site work fine but I cannot se the images.
I can see in ftp the picture but drupal do not serve it in the page.
I already tryed to clear cache.
In the reports log I there is a lot of
<code>Unable to generate the derived image located at public://styles/ensemble-small/public/anne ristorcelli s.png.
</code>
errors but I do not understand what I can do.
The GD tookit works fine.. I checked it.
I tryed to re-upload some images but do not work and I can't see they in the editing page too.
Can someone help me to solve this?
UPDATE:
I tryed to delete the images generaten in the staging server to verify the correct working of the images modules. The images was ok.
So the problem is in server request?
If I try to see the image directly I have this error:
<code>    Internal Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.

Please contact the server administrator, firstname.lastname@example.com and inform them of the time the error occurred, and anything you might have done that may have caused the error.

More information about this error may be available in the server error log.
</code>
Comment: Do they come up and broken images, check if they have the correct permissions, and did you double check if you symlinked the folder, + check if your .htacesss
Comment: Check this one http://drupal.stackexchange.com/questions/53537/unable-to-generate-the-derived-image?lq=1

Check if the image is in the folder, then check the permission of that specific image. did you do chmod -Rf 777 ?
Comment: The permission is 777 and I tryed to delete the GD generated images and refresh the page. The images was created as usual but when the browser ask drupal give me error 500 : The server encountered an internal error or misconfiguration and was unable to complete your request. What I have to check in the .htaccess?
Comment: @Shyghar There should be errors in your web server log (Apache I'm guessing?) that correspond to the 500 responses. Are you able to check that log to find out what the underlying problem is?
Comment: Please edit your errors into your answer. As text. You don't expect people are willing to OCR your images to help you, do you? And it's 404 anyway.
Answer: I fixed this problem going to sites/default/files/.htaccess file and commenting
<code># Options None
# Options +FollowSymLinks
</code>
After that I had some other broken images but there are some wrong address in the nodes  tags linked to
/subdirectory-of-staging-server/sites/default/files
instead
/sites/default/files
Thank you for all the comment who help me to debug the error ^^

Images problem after migration


Remover Item Null de um ComboBox c#

Question: Olá,
Estou precisando desenvolver um filtro avançado de pesquisa. Criei alguns comboBoxs para as palavras chaves, mas sempre que preciso buscar o conteúdo de uma coluna que eventualmente tem menos conteúdo que outra determinada coluna, o comboBox é preenchido com as Cells em Null.
Sistema em Run.

Breve exemplo do DB.

o 1º Combo estou carregando no Form_Load:
<code>        OleDbConnection Con = new OleDbConnection();
        Con.ConnectionString = Properties.Settings.Default.dbConTeste;

        try
        {
            Con.Open();
            OleDbCommand Cmm = new OleDbCommand();
            Cmm.CommandText = "SELECT marca FROM tbmodelo";
            Cmm.CommandType = CommandType.Text;
            Cmm.Connection = Con;
            OleDbDataReader DR;
            DR = Cmm.ExecuteReader();

            DataTable dt = new DataTable();
            dt.Load(DR);

            DataView dv = new DataView(dt, "", "marca", DataViewRowState.OriginalRows);
            comboBox1.DataSource = dv;
            comboBox1.DisplayMember = "marca";
            comboBox1.ValueMember = "";

        }
        catch
        {
            MessageBox.Show("error");
        }
        Con.Close();
</code>
o 2º Combo carrego no evento ComboBox1_Leave:
<code>        OleDbConnection Con1 = new OleDbConnection();
        Con1.ConnectionString = Properties.Settings.Default.dbConTeste;

        try
        {
            Con1.Open();
            OleDbCommand Cmm = new OleDbCommand();
            Cmm.CommandText = "SELECT " + comboBox1.Text + " FROM tbmodelo";
            Cmm.CommandType = CommandType.Text;
            Cmm.Connection = Con1;
            OleDbDataReader DR;
            DR = Cmm.ExecuteReader();

            DataTable dt = new DataTable();
            dt.Load(DR);

            DataView dv = new DataView(dt, "", comboBox1.Text, DataViewRowState.OriginalRows);
            comboBox2.DataSource = dv;
            comboBox2.DisplayMember = comboBox1.Text;
            comboBox2.ValueMember = "";
        }
        catch
        {
            MessageBox.Show("error");
        }
        Con1.Close();
</code>
Alguém indica uma forma mais simples de carregar os Combos sem os campos em branco? ou apenas excluir os campos em Null. ?
Answer: <code>OleDbConnection Con = new OleDbConnection();
    Con.ConnectionString = Properties.Settings.Default.dbConTeste;

    try
    {
        Con.Open();
        OleDbCommand Cmm = new OleDbCommand();
        Cmm.CommandText = "SELECT marca FROM tbmodelo where MARCA <> ''";
        Cmm.CommandType = CommandType.Text;
        Cmm.Connection = Con;
        OleDbDataReader DR;
        DR = Cmm.ExecuteReader();

        DataTable dt = new DataTable();
        dt.Load(DR);

        DataView dv = new DataView(dt, "", "marca", DataViewRowState.OriginalRows);
        comboBox1.DataSource = dv;
        comboBox1.DisplayMember = "marca";
        comboBox1.ValueMember = "";

    }
    catch
    {
        MessageBox.Show("error");
    }
    Con.Close()

OleDbConnection Con1 = new OleDbConnection();
    Con1.ConnectionString = Properties.Settings.Default.dbConTeste;

    try
    {
        Con1.Open();
        OleDbCommand Cmm = new OleDbCommand();
        Cmm.CommandText = "SELECT " + comboBox1.Text + " FROM tbmodelo where " + comboBox1.Text + " <> '';
        Cmm.CommandType = CommandType.Text;
        Cmm.Connection = Con1;
        OleDbDataReader DR;
        DR = Cmm.ExecuteReader();

        DataTable dt = new DataTable();
        dt.Load(DR);

        DataView dv = new DataView(dt, "", comboBox1.Text, DataViewRowState.OriginalRows);
        comboBox2.DataSource = dv;
        comboBox2.DisplayMember = comboBox1.Text;
        comboBox2.ValueMember = "";
    }
    catch
    {
        MessageBox.Show("error");
    }
    Con1.Close();
</code>
Comment: Só pra constar que se o valor do campo for `NULL` (e não vazio), não vai funcionar.

Remover Item Null de um ComboBox c#


How can I use a local network shared POS printer from a server in PHP?

Question: Is there a possibility to connect a locally shared POS printer from the PHP server.  While working on the PHP application in my own localhost, I am able to connect and print data to LAN shared printer. But it's not working in Production mode after moving it to the server. Are there possibilities or chances to connect a LAN-shared printer to a production PHP server?
Comment: Only if there's an open network connection between the printer and the server running PHP. If there isn't one, and you can't create one (either by firewall config, VPN, or whatever), then the answer is no. This is no different to connecting any computer / device to any other computer / device - you need an open network connection between them.
Answer: Like I said before, if you want to print from a Web page to a printer on a server, you can write a print routine that runs on the server and wrap it in a web method, or Web API call.  This is a simple way of printing Web page text to a central printer.


How to verify if $\operatorname{corr}(X,Y)=\operatorname{corr}(log(X),log(Y))$?

Question: I am totally blind to this verification, is this true?
$\operatorname{corr}(X,Y)=\operatorname{corr}(log(X),log(Y))$
$$
\operatorname{corr}(X,Y)=\frac{\operatorname{cov}(X,Y)}{\operatorname{var}(X)\operatorname{var}(Y)}\\
\operatorname{corr}(ln(X),ln(Y))=\frac{\operatorname{cov}(ln(X),ln(Y))}{\operatorname{var}(ln(X))\operatorname{var}(ln(Y))}
$$
Thank you for any comments
Even writing out the definition of each, I have no idea how to compare them.
Comment: I don't see any reason for this to be true. Where does the question come from?
Comment: @KaviRamaMurthy I was doing Eview programming and run a generalised-$R^2$ which when we have a log-linear model. By formula, the generalised-$R^2=(corr(y,\hat{y}))^2$. The tutor shows this in Eveiw by run $corr(log(y),log(\hat{y}))$
Answer: Such a claim cannot possibly be true; e.g., if $\Pr[X < 0] > 0$ or $\Pr[Y < 0] > 0$, the RHS is undefined but the LHS still exists.
Even if you restrict the support of $X$ and $Y$ to be positive, then even a simple location-transformed Bernoulli example will show otherwise; e.g.,
$$\Pr[(X,Y) = (1,1)] = 1/6 \\
\Pr[(X,Y) = (2,1)] = 1/3 \\
\Pr[(X,Y) = (1,4)] = 1/8 \\
\Pr[(X,Y) = (2,4)] = 3/8$$
gives $$\rho_{XY} = \frac{25}{3\sqrt{383}}$$ but
$$\rho_{\log X \log Y} = \frac{1}{\sqrt{429}}.$$


Find branching history of current branch

Question: There is a branch A that I am working on. I want to see the history of this branch. In the history I want to see things like master-> A3->A2->A1->A meaning that branch A3 was created from master and on top of A3, A2 was created.... So in history just the branch names.
How do I achieve this using git commands or bitbucket cloud?
Answer: Option 1:
To see ONLY the relationship from one branch to another I recommend using the command:
git log --merges --oneline master..A

(assuming that the first branch is master and the last is A)
Option 2:
I like to use the git log command. This way, you get the list of branches under your current branch and also a graphical view of the history.
I personally use this command:
git log -n 50 --graph --pretty='%C(yellow)%h%Creset -%C(auto)%d%Creset %s %Cgreen(%ad) %C(bold blue)<%an>%Creset' --date=short

But you can define various properties for this command if you want to customize it more. Just search a bit on git log.
Specifically, if you want to control how many commits to show in your history then change the -n 50 to a different number.
Comment: note: `--no-walk` has no effect when you specify a range of commits


How to determine what's changed between database records

Question: Presume first, that the following table exists in a MySQL Database
|----|-----|-----|----|----|-----------|--------------|----|
| id | rid | ver | n1 | n2 | s1        | s2           | b1 |
|----|-----|-----|----|----|-----------|--------------|----|
| 1  | 1   | 1   | 0  | 1  | Hello     | World        | 0  |
| 2  | 1   | 2   | 1  | 1  | Hello     | World        | 0  |
| 3  | 1   | 3   | 0  | 0  | Goodbye   | Cruel World  | 0  |
| 4  | 2   | 1   | 0  | 0  | Hello     | Doctor       | 1  |
| 5  | 2   | 2   | 0  | 0  | Hello     | Nurse        | 1  |
| 6  | 3   | 1   | 0  | 0  | Dippity   | Doo-Dah      | 1  |
|----|-----|-----|----|----|-----------|--------------|----|

Question
How do I write a query to determine whether for any given rid, what changed between the most recent version and the version immediately preceding it (if any) such that it produces something like this:
|-----|-----------------|-----------------|-----------------|
| rid | numbers_changed | strings_changed | boolean_changed |
|-----|-----------------|-----------------|-----------------|
| 1   | TRUE            | TRUE            | FALSE           |
| 2   | FALSE           | TRUE            | FALSE           |
| 3   | n/a             | n/a             | n/a             |
|-----|-----------------|-----------------|-----------------|

I think that I should be able to do this by doing a cross-join between the table and itself but I can't resolve how to perform this join to get the desired output.
I need to generate this "report" for a table with 10's of columns and 1-10 versions of 100's of records (resulting in 1000's of rows). Note the particular design of the database is not my own and altering the structure of the database (at this time) is not an acceptable approach.
The actual format of the output isn't important - and if it simplifies the query getting a "full breakdown" of what changed for each "change set" would also be acceptable, for example
|-----|-----|-----|----|----|----|----|----|
| rid | old | new | n1 | n2 | s1 | s2 | b1 |
|-----|-----|-----|----|----|----|----|----|
| 1   | 1   | 2   | Y  | N  | N  | N  | N  |
| 1   | 2   | 3   | Y  | Y  | Y  | Y  | N  |
| 2   | 4   | 5   | N  | N  | N  | Y  | N  |
|-----|-----|-----|----|----|----|----|----|

Note that it is also ok, in this case to omit rid records which only have a single version, as for the purposes of this report I only care about records that have changed and getting a separate list of records that haven't changed is an easy query
Comment: Have you tried anything?
Comment: @giorgiga I haven't - because I can't figure out how to do it; thus why I ended up here on Stack Overflow! :)
Answer: You can join every row with the following one with
select *
from history h1
join history h2
  on  h2.rid = h1.rid
  and h2.id = (
    select min(h.id)
    from history h
    where h.rid = h1.rid
      and h.id > h1.id
  );

Then you just need to compare every column from the two rows like h1.n1 <> h2.n1 as n1.
The full query would be:
select h1.rid, h1.id as old, h2.id as new
  , h1.n1 <> h2.n1 as n1
  , h1.n2 <> h2.n2 as n2
  , h1.s1 <> h2.s1 as s1
  , h1.s2 <> h2.s2 as s2
  , h1.b1 <> h2.b1 as b1
from history h1
join history h2
  on  h2.rid = h1.rid
  and h2.id = (
    select min(h.id)
    from history h
    where h.rid = h1.rid
      and h.id > h1.id
  );

Result:
| rid | old | new | n1 | n2 | s1 | s2 | b1 |
|-----|-----|-----|----|----|----|----|----|
|   1 |   1 |   2 |  1 |  0 |  0 |  0 |  0 |
|   1 |   2 |   3 |  1 |  1 |  1 |  1 |  0 |
|   2 |   4 |   5 |  0 |  0 |  0 |  1 |  0 |

Demo: http://sqlfiddle.com/#!9/2e5d12/5
If the columns can contain NULLs, You might need something like NOT h1.n1 <=> h2.n1 as n1. <=> is a NULL-save equality check.
If the version within a rid group is guaranteed to be consecutive, you can simplify the JOIN to
from history h1
join history h2
  on  h2.rid = h1.rid
  and h2.ver = h1.ver + 1

Demo: http://sqlfiddle.com/#!9/2e5d12/7
Comment: Thanks! This looks promising - I'll give this a shot on the real data and update this post with results.
Comment: This works perfectly! Awesome answer and quick! Thanks again!


A differentiable injective function with Lipschitzian Inverse

Question: I'm having difficulty with the following question which was given to me following studying the inverse mapping theorem.
Let $U\subseteq\mathbb{R}^{n}$
  be an open set and let $f:U\to\mathbb{R}^{n}$
  be injective and differentiable in $U$
 , assume also $f\left(U\right)$
 is an open set and let $g:f\left(U\right)\to U$
  be the inverse of $f$
 . Prove that if $g$
  is Lipschitzian then it is differentiable.
I'm assuming the main thing I'm missing is how to use the condition that $f(U)$ is open.
Help would be most appreciated!
Comment: Please fix the typo in your title in case anyone is searching.
Comment: Done, thanks for pointing it out to me :)
Answer: In fact, due to invariance of domain, if $U\subset\mathbb{R}^n$ is open and if $f:U\to\mathbb{R}^n$ is injective and continuous, then $f(U)$ is open.
Given $x\in U$, let us show that $g$ is differentiable at $y=f(x)$. Since $f$ is differentiable, there exist $L_x>0$ and  $r_x>0$, such that if $\|x'-x\|\le r_x$, then $x'\in U$ and $\|f(x')-y\|\le L_x\|x'-x\|$. Similarly, since $g$ is Lipschitz, there exist $L_y>0$ and $r_y>0$, such that if $\|y'-y\|\le r_y$, then $y'\in f(U)$ and $\|g(y')-x\|\le L\|y'-y\|$.
Let $r=\min(r_x,  L_x^{-1}r_y)$. If $\|x'-x\|\le r$, then for $y'=f(x')$, $\|y'-y\|\le r_y$, and hence
$$\|x'-x\|=\|g(y')-x\|\le L_y\|y'-y\|=L_y\|f(x')-y\|.$$
It implies that $f'(x)$, the Jacobi matrix of $f$ at $x$, is invertible, i.e. $\det f'(x)\ne 0$. Then it is easy to check that
$$\limsup_{y'\to y}\frac{\|g(y')-x- f'(x)^{-1}(y'-y)\|}{\|y'-y\|}\le\|f'(x)^{-1}\|\cdot\lim_{x'\to x}\frac{\|f(x)-y- f'(x)(x'-x)\|}{\|x'-x\|}=0,$$
i.e. $g$ is differentiable at $y$ and $g'(y)=f'(x)^{-1}$.
Comment: There's one part I don't get, you said that "Since $f$ is differentiable, there exist $Lx>0$ and $rx>0$, such that if $∥x′−x∥≤rx$, then $x′∈U$ and $∥f(x′)−y∥≤Lx∥x′−x∥$.
I'm not sure how to derive that from the definition of differntiability that I'm familiar with which is that $f$ is differentiable in x if there's a linear operator such that:
$\lim_{h\to0}\frac{f\left(x\right)-f\left(x^{'}\right)-D_{f}\left(x\right)\left(x-x^{'}\right)}{\left\Vert h\right\Vert }=0$
Comment: That limit should be:
$$\lim_{x^{'}\to x}\frac{f\left(x\right)-f\left(x^{'}\right)-D_{f}\left(x\right)\left(x-x^{'}\right)}{\left\Vert x-x^{'}\right\Vert }=0$$
Comment: For some reason I can't get the LaTeX to display properly there..
Comment: @Serpahimz: If you rephrase your limit in the definition of differentiablity in $\epsilon-\delta$ language, cannot you see the existence of $r_x$ and $L_x$ ? Note that both of them depend on $x$.
Comment: Hmm, I'll give it a try.
Just one final question, after some additional thought I think I don't actually understand why the inequality
$∥x′−x∥=∥g(y′)−x∥≤Ly∥y′−y∥=Ly∥f(x′)−y∥$
Shows that the Jacobi Matrix is invertible at $x$

Thanks a lot for your help Richard!
Comment: @Serpahimz: Again it follows from the definition of differentiablity. If $\det f'(x)=0$, then there exists $h\in\mathbb{R}^n$ with $\|h\|=1$, such that $f'(x)h=0$. It follows that $\lim_{t\to 0}\frac{f(x+th)-f(x)}{t}=0$, contradicting to the inequality.
Comment: Right, I understand now why what you wrote is equivalent to differentiablity and how to use the inequality.

Thanks a lot Richard, you've been most helpful!
Comment: @Serpahimz: You are welcome!


How to restrict screen access in web application..?

Question: i have developed an application and till now i have been successful in restricting screen access by not showing/hiding menu options or buttons for certain screen. But the problem now is user is able to access screen when he types url in address bar.
I know i'm not the first one doing this, so there has to be some kind of standard practice.
So if somebody know any library or some way to do this, please let me know.
Thank you.
Comment: Check out this [library](https://github.com/cemerick/friend/) from authentication and authorization for ring based web apps.
Answer: Disclaimer - I don't know how this would translate to Clojure as I have never used it.
Typically you decorate methods that respond to views with an authorization handler. This handler knows how to talk to your authentication backend. It takes the user identifier (which can be the userid/username, etc.) from the current context and queries the backend for the user's authorization for the requested view.
If it passes, the view the is shown.
If it is rejected then based on business rules (and security guidelines) actions are taken. These can be as simple as a friendly "Oops you are not allowed here"; to logging the action and then ending the user's session.
If your application has a limited set of endpoints (URLs) you can create a static map of end points to users and use this as your access control list (ACL). However, in most modern applications the ACL is controlled across a range of objects - and the endpoints (the URLs) are not restricted as these are dynamic. For example /inventory/product/1, /user/admin/3, etc.
Update:
This link provides a visual diagram for the decorator pattern.
Update 2:
The authorization library provides some helpers that would do the authorization checks ("is this user allowed to view"), but the implementation in the code is left up to the individual application.
Typically you would use one or more authentication libraries (like oath); but the authorization part is left up to your implementation.
A quick google led me to securing clojure web applications with sandbar which should be more relevant to you.
Comment: Thank you.. The same was in my mind.. i can use a pre-route which does this. But seems like there are other ways to do it. like some authorisation library if i'm right..


Guardar dados Mysql php numa única tabela

Question: Estou com uma pequena dúvida em guardar um formulário no mysql que é.
Tenho um formulário que está dividido em 2 e quero que seja guardado na mesma tabela.
Quando guardo só faço guardar a segunda parte do mysql ele apaga-me a primeira.
Exemplo Formulario1: Nome, função
Inserir na BD:
$sqlinsert = "Insert into tb_trabalhador (Nome, funcao) Values ('".$Nome."','".$Funcao."')";

mysql_query($sqlinsert) or die(mysql_error());
if ($sqlinsert)

Formulario2: Cartaocidadao, data de nascimento
Inserir na BD:
$sqlinsert = "Insert into tb_trabalhador (Cartao, Data) Values ('".$Cartao."','".$Data."')";

 mysql_query($sqlinsert) or die(mysql_error());
 if ($sqlinsert)

Comment: Ao que parece você esta recriando a variável e sobrescrevendo a query, poste mais de seu código para que possamos entender.
Comment: Pode interferir sim. Precisamos ver mais código para poder ajudar.
Comment: mas são duas paginas php diferentes. Não interfere acho eu
Comment: São os dois exactamente iguais na parte do insert. So muda é os campos.
Comment: Alterando apenas sqlinsert2 , sqlinsert3... Já pode ajudar a funcionar?
Answer: O problema é que me parece que você quer juntar os dados em um registro só, mas está criando dois.
Depois de usar cada um dos seus códigos, você vai ter uma tabela assim:
Cartao | Data       | Nome   | Funçao
-------+------------+--------+--------
2136   | 31/05/2014 |        |
-------+------------+--------+--------
       |            | Holmer | Estivador

Se quiser acrescentar dados numa tabela, vai precisar de algo assim:
$cartao = "2136" // esse é só um exemplo, pode ser ID, aí vai depender do seu caso.
$sqlupdate = "UPDATE tb_trabalhador". // ATUALIZE tb_trabalhador
    "SET Nome=$nome, Funcao=$Funcao". // mudando o nome pra $Nome e função pra $Funcao
    "WHERE Cartao=$Cartao";           // na linha em que o cartão for $Cartao

Nota: este é apenas um exemplo. Como já deve ter sido avisado em algumas das suas perguntas anteriores, você deveria estar usando funções do mysqli_ para poder usar bindParameter, em vez de criar a string com parâmetros, mas este ja é outro problema.
Comment: Não irei ter problemas em utilizar o update para acrescentar dados so mysql?
Comment: Provavelmente vai, mas não pelo mesmo motivo ;) . Brincadeiras à parte, a diferença é a seguinte: INSERT é pra acrescentar uma linha nova na tabela, com os dados que você fornecer. UPDATE só altera uma linha já existente, mudando dados das células. Se você colocar 3 informações com INSERT, estará criando 3 linhas (registros diferentes) com todos os campos da tabela, mesmo que vazios. Por outro lado, com UPDATE nunca vai ser criada uma linha nova, ele só serve para atualizar a informação de uma linha existente.
Comment: Vamos fazer uma comparação pra você entender: o INSERT é você pegar um formulário novinho da gaveta, com vários campos vazios, o por o nome do cliente nele, e a idade, e guardar na pasta "clientes". O UPDATE é você pegar algum dos formulários que já está na pasta "clientes" e acrescentar algo, (ou passar corretivo e mudar algo). Aplicando no seu caso: no seu código, você pegou duas fichas de cliente novinhas da gaveta, numa delas colocou o Cartão e a Data. Na outra, colocou Nome e Função, e agora tem duas fichas de cliente na mesma pasta, ambas faltando pedaço.
Comment: uma duvida. se estou a inserir os dados não sei que dados estou a colocar. Como posso fazer o update por algum campo ou por id?


Extension method generic VB to C#

Question: I have a problem converting a method extension from VB.NET to C#, here is my working VB.NET code:
Module ClientBaseExtensions
    Private Const HDR_TOKEN = "Token"

    <Extension()>
    Public Sub Initialize(Of T As Class)(ByVal client As ClientBase(Of T), url As String, pToken As String, pDeviceId As String)
        client.Endpoint.Address = New EndpointAddress(url)
        httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken
        OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty
    End Sub
End Module

When converting it automatically it gives me this code which is not recognized in my clientbased object
static class ClientBaseExtensions
{

    private const  HDR_TOKEN = "Token";

    public static void Initialize<T>(ClientBase<T> client, string url, string pToken, string pDeviceId) where T : class
    {
        client.Endpoint.Address = new EndpointAddress(url);
        httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken;
        OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty;

    }
}

Comment: The first parameter should be `this ClientBase client`.
Comment: OK, so whats the actual problem with this code?
Answer: In C#, extension methods are declared by specifying the this keyword for the first parameter (the one which defines the type that is extended):
static class ClientBaseExtensions
{

    private const  HDR_TOKEN = "Token";

                           // insert this here
    public static void Initialize<T>(this ClientBase<T> client, string url, string pToken, string pDeviceId) where T : class
    {
        client.Endpoint.Address = new EndpointAddress(url);
        httpRequestProperty.Headers.Item(HDR_TOKEN) = pToken;
        OperationContext.Current.OutgoingMessageProperties(HttpRequestMessageProperty.Name) = httpRequestProperty;

    }
}

Extension method generic VB to C#


How to send the views record in an email to admin at regular time interval of 8 hours?

Question: I have created a rule to sent the view results, by using this:
<code><?php
$view = views_get_view('VIEWNAME');
print $view->preview('default');
?>
</code>
But I want this Rules Action to occur every 8 hours.
My question: What should be the "React on event" for this rule?
Edit: Based on the suggested answer, I'm now also using the Rules once per day module. Here is my rule (in rules export format):
<code>{ "rules_send_emails_to_fuel_company_approved_client_list" : {
    "LABEL" : "Send emails to fuel company approved client list",
    "PLUGIN" : "reaction rule",
    "OWNER" : "rules",
    "REQUIRES" : [ "php", "mimemail", "rules_onceperday" ],
    "ON" : { "once_per_day" : [] },
    "DO" : [
      { "mimemail" : {
          "key" : "email@example.com",
          "to" : "ok",
          "subject" : "ok",
          "body" : "\u003C?php\r\n$view = views_get_view(\u0027calling_agent_summary\u0027);\r\nprint $view-\u003Epreview(\u0027default\u0027);\r\n?\u003E",
          "language" : [ "" ]
        }
      }
    ]
  }
}
</code>
But I'm still not receiving any emails. So I wonder what might be the cause of this.
Comment: Thanks for the update. I'm not (yet) familiar with rules integration and mimelail, but a few remarks: (1) are you sure you want to publish your email here (replace it be a fake eMail id to avoid spammers ...) (2) are you sure cron has run already (try to indicate that somehow in your update if so) (3) the "to" in your rules action (= ok) looks very strange to me (should that not be some email id)?
Comment: I really think bullet (3) in my prior comment requires more investigation from your part. Have a look at the equivalent "to" value in the rules example in http://drupal.stackexchange.com/questions/187586 ... that's a token containing a real eMail value.Moreover, I think the "key" you are using might need reviewing also (if the same rule is triggered multiple times, it is not unique anymore, which seems like not a healthy situation, and might lead to unpredictable behaviours). PS: I "like" the edited eMail Id you now used ...
Comment: I think you are right. in 'to' i need to put my Email id. I have changed it on my rule. I hope it will works now.  Thanks for you time and suggestion.
Answer: Option 1: Using Rules and Rules Scheduler
Use the Rules module and Rules scheduler (submodule of Rules). What you actually need to do is a minor variation of what is explained in the tutorial Hourly tasks using rules scheduler: in your case you should use an offset of 8 hours (instead of just 1 hour).
And as explained also in that tutorial: "Initially execute the component manually" (from then on every other 8 hours the rule will be executed again).
Option 2: Using modules Rules and Rules Once per Day
There is a fairly new module related to rules, i.e. the "Rules Once per Day" module. Here is how it works (as per the comment in issue 2495775, from the module owner):

You specify a trigger hour on the administration settings page for this module.
The Rule trigger will then run when cron tasks are first run after the start of that hour. The actual run time will depend on your cron task timings.

The way to understand/read this is like so:

The "Event" will only be triggered when a cron job is run.
And that event will only be triggered 1 time / day, i.e. "next time cron runs after the trigger hour has passed".

So by creating 3 similar rules, you could have 1 of them run around (say) 6 am, another one around 2 pm and the ast one at 10 pm. Adapt the 6am to any other timestamp you'd want, and do the same with the one from 2 pm and 10 pm
Comment: Thanks @Pierre.Vriens. I have implemented 2nd option. Let you know once rule is executed. Thanks for reply.
Comment: no luck i have not received any emails. I think i am missing something.


How to check if (unmanaged) file exists?

Question: I can't find a Drupal API function in D7 that tells me if an (unmanaged) file exists.
D6 had a file_check_location but not for 7.
How to check if (unmanaged) file exists?
Answer: You could just use the old bog standard PHP function file_exists() if I understand you right:
$uri = 'public://images/an-image.jpg';
if (file_exists($uri)) {
  // Do something
}

This also works for normal (absolute) paths as well, e.g.:
$path = '/var/www/drupal/sites/default/files/images/an-image.jpg';
if (file_exists($path)) {
  // Do something
}

Comment: @MotoTribe Depends how much you're offering ;)
Comment: Because the streams have been properly registered by Drupal @kaiser. See http://php.net/manual/en/wrappers.php
Comment: Clive to the rescue again, thanks! Can I hire you? ;-)
Comment: Why does this work? I just tested this with plain PHP and a stream handle thrown into `file_exists()` and it does **not** work. Any explanation?
Comment: @Clive I hoped you can point me to the source in Drupal. The rest I know and can not get working in a plain PHP test, hence I asked. **Edit:** nvm, [found them](https://github.com/drupal/drupal/tree/1d591ebe1dcc492ceef5e88febcdcc3f04e1e8a7/core/lib/Drupal/Core/StreamWrapper)
Comment: I like this method as a it saves the server from performing an http request and, in cases where the resource is not found, doesn't pollute my logs.
Answer: If you want a Drupal way to do this, you can in Drupal 8/9/10 using the file_system service.
/** @var \Drupal\Core\File\FileSystemInterface $file_system */
$file_system = \Drupal::service('file_system');
$file_exists_error = $file_system->getDestinationFilename($file_uri, \Drupal\Core\File\FileSystemInterface::EXISTS_ERROR);

If the file does not exist in the file system $file_exists_error will return the file path, otherwise it will return false, denoting there was no error.
@see https://api.drupal.org/api/drupal/core%21lib%21Drupal%21Core%21File%21FileSystemInterface.php/function/FileSystemInterface%3A%3AgetDestinationFilename/9.3.x
Comment: In Drupal 10 you can just call file_exists on a public://path/to/file uri and it will return correctly since Drupal registers the stream wrappers at bootstrap
Answer: I don't know what your specific use case is, but you may not need to check to see if the file exists.
The functions file_unmanaged_copy, file_unmanaged_move, file_unmanaged_delete, file_unmanaged_delete_recursive, and file_unmanaged_save_data check to see if the file exists and return false if it does not.
You can find the source code in drupal/includes/file.inc and have a look.
Answer: You should use the drupal function:
file_destination($uri, FILE_EXISTS_ERROR)
and check
if (!file_destination($uri, FILE_EXISTS_ERROR)) {
  // The file exist
  // Do something
}

Comment: It will work as `file_destination()` uses `file_exists()` function


Testing if object has multiple properties

Question: I'm having trouble checking this object is there something I need to do to chain multiple .to.have.property statements? I believe I'm just returning the result from the last .to.have.property into the next one.
expect(shopify.formatRequestOptions("shop"))
  .to.have.property('url', "https://"+settings.shop+"/admin/shop.json")
  .to.have.property('method', "GET")
  .to.have.deep.property('headers.X-Shopify-Access-Token', settings.accessToken)

It seems I can use something like this chai-subset to check an object. Is there no way to chain these together? I'd hate to have to do this.
var result = shopify.formatRequestOptions("shop")
expect(result).to.have.property('url', "https://"+settings.shop+"/admin/shop.json")
expect(result).to.have.property('method', "GET")
expect(result).to.have.deep.property('headers.X-Shopify-Access-Token', settings.accessToken)

Comment: I don't know much about it, but it looks like that is work in progress. See link https://github.com/chaijs/chai/issues/193
Answer: Could build your own function that just returns true / false and has any interface.
let example = {
  'name': 'thomas'
}

let hasAllProps = (obj, props) => {
  let propsTrue = _.chain(props)
  .map(prop => _.has(obj, prop))
  .without(false)
  .value()
  return (propsTrue.length === props.length)
}

console.log(hasAllProps(example, ['name'])) // true
console.log(hasAllProps(example, ['age'])) // false

Answer: We can use nested.includes.
var result = shopify.formatRequestOptions("shop")
expect(result).to.nested.include({
    url: "https://"+settings.shop+"/admin/shop.json"
    method: 'GET',
    'headers.X-Shopify-Access-Token': settings.accessToken // this where nested kicks in, on the dot path
});


Find the right parameters for an event without using Design Mode in Visual Studio 2010

Question: Is there a way to know what parameters are needed by an event in Visual Studio 2010?
Let's say I have a DropDownList control and I want to bind a method to the "OnSelectedIndexChanged", I would do something like this
In the ASPX File:
<asp:DropDownList ID="lstMyList" runat="server" OnSelectedIndexChanged="lstMyList_SelectedIndexChanged"></asp:DropDownList>

In the codebehind:
protected void lstMyList_SelectedIndexChanged(object sender, EventArgs e)
{
    ...
}

Is there a way to know what parameters the method needs? (In this case, an object for the sender and an EventArgs parameter for the event.)
I know you can easily create the method by double-clicking the right event in Design Mode, but it does a mess with your code so I prefer not to use it.
Thanks!
Answer: You can find out the parameters by "going to definition" (F12) on the appropriate event, finding out what delegate type it uses, then going to definition on that. In this case the SelectedIndexChanged event has type EventHandler which is defined as follows:
[SerializableAttribute]
[ComVisibleAttribute(true)]
public delegate void EventHandler(
    Object sender,
    EventArgs e
)

You can also find this information by searching the web or pressing F1 and searching in the help.

I know you can easily create the method by double-clicking the right event in Design Mode, but it does a mess with your code so I prefer not to use it.

I think you should try to overcome your fear of using the designer. You are most likely wasting more time in lost productivity by not using the code generation features in Visual Studio than the potential time you might have saved by protecting yourself against the designer messing up your code.
Comment: For the codebehind, maybe, but I'm still having trouble with the HTML/ASP.NET markup.
Comment: Should I see the "Going to definition" option when i right-click the event in the markup editor? F12 doesn't work either.
Comment: @Jason: Here's three approaches: 1) You can go to the code behind, find a random method and temporarily add this (uncompilable) code `this.yourDropDownList.SelectedIndexChanged`, then press F12 to see the definition. When you are done you can then delete the temporary code. 2) You could just Google for the information you need. "C# DropDownList class" for example, and find the events there. 3) You can just make a good guess and the compiler will tell you what the types should have been if you get it wrong. The first one will always be `object` and `EventArgs` is a good guess for the second.
Comment: Good enough for me. Thank you.
Answer: Hardly economical in terms of keystrokes and productivity but a possibility, if you're finding the event in code to 'Go To Definition' anyway, and imagining for a moment that you don't mind using the code editor features of VS, too, is to hit the Tab key, then add the += before hitting the Tab key another two times. This will generate the appropriate delegation and method definition, which will result in you seeing the method signature.
For instance, typing the following, tabbing appropriately (twice after typing '+='):
MyType.MyEvent += new System.EventHandler(MyType_MyEvent);

Generates a method like the following:
void MyType_MyEvent(object sender, EventArgs e)
{
    throw new NotImplementedException();
}

Now, the productivity reduction could occur if you don't actually require both pieces of code.


Is the CDF really just a running total of the PMF or am I thinking about this wrong?

Question: When using discrete variables (like the possible outcomes of rolling 2 die {1,2,3,4,5,6,7,8,9,10,11,12} ) is the CDF the same as a sum of the PMF?
For instance, take my table below. This is the frequency distribution of 213 rolls for 2 die. The mean is 7.18 and stdev is 2.58 from the 213 rolls.
Excel Norm.Dist says that the PMF is .009 for rolling a 1.
However, the CDF is .008. That doesn't make sense to me. shouldn't the CDF be .009 as well since it represents all the values <= 1 which is only 1?
Same for the prob of rolling a 2. Shouldn't the CDF be  [0.009]+[0.021] (the prob of rolling a 1 or 2)
In essence, shouldn't the CDF be the running sum of the PMF values before it?

[Outcome]   [Frequncy]  [PMF]   [CDF]
[1]         [0]         [0.009] [0.008246202]
[2]         [6]         [0.021] [0.022233465]
[3]         [10]        [0.042] [0.052456047]
[4]         [21]        [0.072] [0.108727782]
[5]         [28]        [0.108] [0.199012947]
[6]         [26]        [0.140] [0.32384197]
[7]         [27]        [0.154] [0.472569645]
[8]         [30]        [0.147] [0.625272517]
[9]         [17]        [0.121] [0.760380856]
[10]        [23]        [0.085] [0.863394586]
[11]        [16]        [0.051] [0.93107808]
[12]        [9]         [0.027] [0.96939936]
Comment: You cannot be using `Norm.Dist` correctly, because you get different values for outcomes 1 and 12, 2 and 11, etc., whereas a correct use of this Normal approximation would yield identical values for all such symmetric pairs of cases.  However, even if this were done correctly, *approximating* a discrete distribution with values from a continuous one is no way to understand properties of the discrete distribution!
Comment: What do you mean when you say 'I computed the pmf and cdf using the mean of 7.18, the stdev of 2.58'? The PMF is not defined this way, anyway.
Comment: The sum of 2 dice is not normally distributed, nor is it a discretized normal. So your use of the normal distribution is inappropriate
Comment: Ecerythingabou about this is confusing.  How are either the PMF *or* the CDF positive for outcome 1?  I assume when you say the outcome of rolling two dice, you mean the sum of the face values. Secondly, did you say the mean was 71.8?  What is this the mean of?
Comment: I updated the question. It should have read the mean is 7.18. I am not using the idea of "fair" dice. I simulated 213 rolls of 2 dice.
So for each outcome (1-12) I computed the pmf and cdf using the mean of 7.18, the stdev of 2.58 and fed it the outcome (1-12). That is what the table represents.
So though rolling a 2 should be 1/36 chance, because this was a simulation of 213 rolls, it found a that snake eyes came up 6 times. So that s what I mean by the fact that I am not using "fair dice".
Comment: @whuber Not sure that I get what you are saying about continuous data. Rolls of dice should all be discrete in nature. We can't have 1.5, or 2.5. Am I misunderstanding this?
Comment: @rightskewed maybe I am doing it wrong but in excel to compute the outcome of 12 in the chart above I used this

"=NORM.DIST(12,7.18,2.58,FALSE)"
12 = outcome
7.18 = mean
2.58 = stdev
False = PMF
Answer: The normal distribution model you are using is not appropriate for the sum of two dice, which has a well-known discrete distribution - you might want to look at how this result is proved on Khan Academy, though that is a theoretical approach and it seems you are going about it in an empirical way. But even if your model were appropriate for some other scenario, what you are doing in Excel won't work.
The final "false" in your NORMDIST does indeed stop the output being cumulative but it means the output is a PDF not a PMF since the normal distribution is continuous. A PMF sums to the CDF whereas a PDF integrates to the CDF.
You could see this in Excel by using a finer mesh of points - set them 0.01 apart, say, rather than just looking at whole numbers - and using a numerical integration procedure. Even something simple like the trapezoidal rule should give you an overall integral close to one, and intermediate integrals close to your calculated CDFs. To achieve better results with minimal extra complication you might want to start further to the left than zero (four or five standard deviations to the left of your mean should be plenty for your purposes), using a better numerical integration procedure such as Simpson's rule and setting an even finer mesh, but even the rough and ready result you'd get from the trapezoidal rule ought to be convincing.
Excel code
Paste special as a CSV, with the delimiter set as semi-colon, so that "Outcome" is in cell A1 - then clone down cells A4:D5 for a couple of thousand rows.
Outcome;PDF;CDF;Trapezium rule estimate
-4.00;=NORM.DIST(A2,7.18,2.58,0);=NORM.DIST(A2,7.18,2.58,1);
-3.99;=NORM.DIST(A3,7.18,2.58,0);=NORM.DIST(A3,7.18,2.58,1);
-3.98;=NORM.DIST(A4,7.18,2.58,0);=NORM.DIST(A4,7.18,2.58,1);=(0.01/2)*(B$2+B4+2*SUM(B$3:B3))
-3.97;=NORM.DIST(A5,7.18,2.58,0);=NORM.DIST(A5,7.18,2.58,1);=(0.01/2)*(B$2+B5+2*SUM(B$3:B4))

Comment: Makes a lot of sense. I was somewhat following this technique (https://www.apsu.edu/sites/apsu.edu/files/wilsona/Rolling_Two_Dice_Empirical_Rule__Z-Scores.pdf) and thought that I could use a normal distribution since it looked so similar and gave probabilities that were extremely similar to what textbook probabilities are to the two dice question. I guess the fact that it showed that I had a small statistical chance of rolling a 13 should have tipped me off.


Plot of PCA generated projection points

Question: I have these mean centered points:
X = [-0.7142;-1.7142;-1.7142;-0.7142;1.2857;1.2857;2.2857];
Y = [1.2857;0.2857;-0.7142;0.2857;0.2857;-0.7142;-0.7142];

I then calculated the PCA projection points as:
X_proj = [-2.2316; 0.0648; 1.044; -0.2725; -2.1535; 1.7647; 1.2005];
Y_proj = [2.8746; 3.4734; 1.5356; 1.5142; -2.4040; -1.4030; -2.3826];

with the modified axis given as:
y1 = 0.2053*x1 + 0;
y2 = -0.48719*x2 + 0;

I then did a plot in Matlab showing both the mean centered values, and then the projected values:

Where the red triangles represent the projected data and the blue squares represent the mean centered data.
I find this a little graphically confusing.
Is it true that the projection points should show perpendicular "projection lines" to the dashed axes?  How should this be shown better graphically?
Answer: I think the problem is that you're plotting the projected data onto the projected basis (provided by PCA). That's confusing. The two ways to think about this are:
1) Original data (original basis) plotted against the new principle components - this will help you see that the principle components provide the best two orthogonal lines which minimize the squared perpendicular distance to your data. In fact, your first PC explains 85% of the variance in your data, so I'd probably just draw the first one only.

2) Projected data (new basis) and standard $\mathbb{R}^2$ - this will help you see how your projected data looks in it's "natural state". That is, if you treated the new basis as the "standard basis" and plotted the projected data onto it.

See below for more detail on PCA and some R code to generate these plots.

The idea is to find the best k dimensional representation of the data, where usually k is less than the number of dimensions you are starting with. In this case, you start with 2 dimensions, so ideally we'd like to find a single dimension to reduce it to. Which is why plotting it on two dimensions might not provide much insight compared to plotting it on the first principle component
How do we know it's the best k dimensions? Because we know that the dimension that preserves the most variance in the data is the one orthogonal to your data - that's where the perpendicular part comes in. The next best dimension that preserves the most variance in your data is orthogonal to that first one. And so on. Each new dimension is orthogonal to the others.
So perhaps you should plot your projected data onto the first principle component only, as I showed above.

To help illustrate some of the concepts, here is some R code:
X = c(-0.7142,-1.7142,-1.7142,-0.7142,1.2857,1.2857,2.2857)
Y = c(1.2857,0.2857,-0.7142,0.2857,0.2857,-0.7142,-0.7142)
covariance = cov(data.frame(X,Y))

# grab the eigenvalues
lambda1 = eigen(covariance)$values[1]
lambda2 = eigen(covariance)$values[2]
# first principle component captures 85% of the total variance
# this suggests that you can express your data in one dimension
lambda1/(lambda1 + lambda2)  # 0.8461777

# grab the eigenvectors
v1 = eigen(covariance)$vectors[,1] #  x = -0.9795803  y = 0.2010532
v2 = eigen(covariance)$vectors[,2] #  x = -0.2010532  y = -0.9795803

# note that the new basis is orthogonal
v1 %*% v2  # 0

r = seq(-4,4,0.1)
# plot projection of original data into new basis
dim1 = t(v1)%*%t(as.matrix(data.frame(X,Y)))
dim2 = t(v2)%*%t(as.matrix(data.frame(X,Y)))
projection = cbind(t(dim1),t(dim2))
plot(projection,xlim=c(-3,3),ylim=c(-3,3),main='projected data')
abline(h=0,v=0,col='red')

# correlation between projected data is 0
cov(projection)

# plot original data and 2 principle components
plot(data.frame(X,Y),xlim=c(-3,3),ylim=c(-3,3),pch=8,main='original data, 2 PCs')
lines(y=v1[2]/v1[1]*r,x=r,type='l',col='red')
lines(y=v2[2]/v2[1]*r,x=r,col='red')

Comment: I removed the negation. I used it original to try to reproduce your PCs, but in fact it shouldn't be there. As to your Matlab question, did you reverse the order of eigenvectors? Can you see what the associated eigenvalues are with each eigenvector?
Comment: Ok - the order is different thats all. See how your largest eigenvalue is the second element, and the associated eigenvector is (-0.979577722801529 0.201065872268197). This corresponds to what I got as well.
Comment: thanks for your thorough solution.  For the last two lines in your code, you negate the slope so as to obtain the perpendicular bias of the originally generated eigen vectors?
Comment: When I ran this problem in Matlab, I got the eigen vectors as [-0.201065872268197 -0.979577722801529;
-0.979577722801529 0.201065872268197].  How did you get your eigenvectors to be the opposite??  Thanks for your time!
Comment: Hello, these were my eigenvalues:  [0.4834, 0;
0, 2.659]....as formatted in Matlab form.

Plot of PCA generated projection points