Gulp minify and don't copy original files

Question: I want to minify some JS files with Gulp, but can't seem to get control over the process. I want only the minified version in the destination, and am currently getting copies of the originals as well.
I'm thinking I may need the rename package, but am not sure how to use it for this task - I would presumably need some kind of variable to hold the current file name for each script.
Any help much appreciated. The code is below:
var gulp = require( 'gulp' );
var minify = require( 'gulp-minify' );
var rename = require( 'gulp-rename' );

//script paths
var jsFiles = 'js/**/*.js',
    jsDest = 'js/dist/';

gulp.task('scripts', function() {
    return gulp.src(jsFiles)
        .pipe(minify())
        .pipe(gulp.dest(jsDest));
});

Comment: The minified files are written under js/**/*.js too ????
Answer: Set the noSource config like the following
  .pipe(minify({noSource: true})


Espaço indesejado na pagina ao criar media queries

Question: Estou criando um site com layout responsivo,quando o site entra na resoluçao mobile sobra um espaço abaixo indesejado
@media(min-width:176px) {
div#rodape{
width: 100%;
height: 70px;
padding-top: 10px;
text-align:center;
}
}

@media(min-width:320px) {
div#rodape{
width: 100%;
height: 230px;
text-align:center;
}
}

/OBS. este site nao é meu isto é apenas um exemplo/
Comment: O CSS na tua pergunta não é suficiente para causar o que aparece na captura de tela. O espaço terá que ser proveniente de alguma falha na _markup_ ou uma definição de CSS que não as que constam na tua pergunta. Deverás atualizar a pergunta com a informação relevante à analise do problema.
Answer: Quando usa media queries tem de ter em atênção o minimo e máximo que faz com que o browser escolha uma parte do código ou outra.
Aí vejo que está a defenir min-width nas suas queries, para ambos. Eu sugiro que mude para:
@media(max-width:319px){
    /* ... */
}
@media(min-width:320px){
    /* ... */
}

Assim a fronteira entre um e outro fica defenida e não concorre uma com a outra.
Comment: As declarações na media `@media(min-width:176px)` estão sempre em vigor salvo se alteradas na media `@media(min-width:320px)`, [ver exemplo](http://jsfiddle.net/zuul/t82tg27k/). Um `text-align:center` na primeira não precisa ser declarado na segunda se for para manter o alinhamento ao centro. Mas o problema do OP parece ser uma margem enorme ou um espaço que um elemento antes do `#rodape` ocupa. De qualquer forma, falta informação na pergunta... por exemplo: de onde vem o fundo preto do rodapé? E se isso está declarado, que outras declarações existem?
Comment: Muito bom @Sérgio li muitos artigos a respeito dos "conflitos" das Media Queries e isso passou despercebido, Agradeço desde já.
Comment: @LamborghiniAventador o comentário do Zuul faz muito sentido também, por vezes é util ter `min-width` em ambos mas consciente que algumas regras do mobile pervalecem no desktop.


Custom ordering flow

Question: I was wondering if it's possible to replace the default commerce flow with my own custom flow.
As far as I know the default flow is following:

Add individual products to cart on Product's detail page or in Products View
Go to cart and proceed to checkout
Add shipping & billing information
Complete the payment

My flow need to be a bit different. I would like to create View of Products (my products are entry-tickets for an attraction) where user can select quantity of each Product he would like to purchase. I know this View can be AJAXified to change total price dynamically according to quantity of each product. When customer selects all tickets and quantities I need to send him to second page of my Multi-step webform where he enters shipping & billing information and finally confirms / fullfils the payment. After successful payment confirmation / fullfilment I'd like to display the third page of Multi-step Webform where is only confirmation and "thank you" message.
I've read through Commerce 2 documentation and I know how to change Order & Checkout workflows, but I'm not sure if I can use Multi-step Webform where the steps are following (as described above):

Step 1: Select quantities of each Product in Products View (10 products in total - ticket types)
Step 2: Fill shipping and billing information
Step 3: Display confirmation message

The general idea is to skip the cart step where I need to go to cart page and instead realize whole flow as a 3-step Multi-step Webform.
Thanks!
Answer: To skip the cart part of the checkout flow, I have been using the patch here. This is the leading patch for decoupling the cart from Commerce (it's a bit hard-wired at present).
If you want to customize the checkout flow with more steps, you can write a custom checkout flow plugin.
To add a custom confirmation message, you can write a checkout pane.
Comment: Yes, thanks. I've already looked at "Custom checkout flow". But the checkout doesn't need to change, it can remain single step. I want to create multistep form from "Products view" and "Checkout" and "Confirmation" message.
Comment: @PatrickStar Commerce usually includes a "Confirmation" message as part of the checkout flow.  If you want something special, you can write a checkout pane; I added a link to my answer.
Comment: and is it possible to create custom ordering Form from Products View and use EventSubscribers or Commerce API to add / remove Products from Cart? And finally after clicking button "Proceed to checkout" redirect from this form to Checkout page?
Comment: Have you tried to do any of this yet? Where did you get stuck? Yes you can customize the Commerce order form. And I already linked to a patch for skipping checkout. There are a variety of other ideas for redirecting straight to payment info input in the linked issue.
Comment: I'm trying to find best solution if there's any before making unnecessary mistakes. I'll try your recommendations and update the question if necessary.
Comment: @PatrickStar Questions on Drupal Answers should ideally have a single answer; broad questions that invite discussion are off topic for this site. If you want to chat in general about Commerce implementations, you should join the Commerce Slack channel, where you can talk directly to the Commerce developers: https://docs.drupalcommerce.org/commerce2/getting-started/getting-help

Custom ordering flow


Modulation from major key to relative minor - what could be the pivot chord?

Question: I want to modulate from D major to B minor. I have a perfect cadence (A7 - D) in D major, after which I need to use a pivot chord to go into B minor. I was thinking of using the F# chord, but I am not sure if it should be an F#m or F#.
According to my knowledge, a pivot chord has to be common between the original key & the key you want to modulate into. If I have to use the F# chord, I would have to use A# as an accidental in the chord (since F# as a chord doesn't exist in D major). So should I use this chord, or simply write it as F#m? This means that the relative minor would have to be B natural minor. Is this ok?
Also, what other chords could be better ways of modulating into the relative minor? When modulations go into the minor, is it generally the harmonic minor which is used, or it depends according to accidentals (if any) are used?
Comment: musicnotes.com seems to have all that you need covered.
Comment: www.musicnotes.com will find it. 'Key changes' is the part you need.
Comment: @Tim That seems to just be a website selling sheet music?  Even searching their blog I can't find anything about this there...
Comment: Could you post a link of the specific webpage, or the topic heading so that I could find it? Thanks.
Answer: The main point of a V chord is the leading note. That's the main reason the harmonic minor scale notes get used often. There is no key of 'B natural minor', there is a scale, but in a minor key, the first 5 notes in any minor scale are identical, after which the notes from the parallel major or natural minor are game to be used.
F♯ chord doesn't exist in D. So what? We're not going to be in D any more, so it makes no difference.
By simple use of ears, try both, and hear that F♯ major (or dom7) is far more decisive than F♯ minir (or m7). If you're looking for a 'rule' don't bother. Have a listen to how V works in the majority of minor pieces - the fact that yours has modulated from the relative major is somewhat unimportant.
Answer:
a pivot chord has to be common between the original key & the key you want to modulate into...

Right. When dealing with relative major/minor keys like D major and B minor the key signatures are the same therefore all the basic diatonic chords are the same between the two keys.
From that perspective all the diatonic chords are potential pivot chords.
All you really need is the sequence of chords: pivot > new dominant > new tonic.

is it generally the harmonic minor which is used?

That isn't the only way, but it will do what is needed. (The natural minor won't work.) Without going into detail about how to handle minor key harmony, you must make sure the new dominant uses the raised ^7 degree of the minor scale. In this case it means using A# in B minor. So the dominant is F# major, spelled F# A# C#.
Beside that fact that any diatonic chord is potential a potential pivot, the simplest way to choose the pivot is to use a chord that will be a good pre-dominant to the new F# major dominant. Obvious choices by conventional harmony are iio6 or iv. Those chords respectively are C# diminished in first inversion E G C# or E minor E G B.
Just of illustration, I will take the first choice. In Roman numerals it would be...

D:viio6/Bm:iio6 V i

The slash indicates the pivot chord and modulation.
Answer: You can use the G major chord which is both D:IV and b:VI then you can move three steps back towards the  e minor chord whis is both D:ii and b:iv and then have a Major chord built on f# with the leading tone of b minor resolving properly to make the modulation to b minor complete.
Answer: The relative minor root (Bm)  IS a common chord (vi) of the starting key (D). Just play the cadence in D and continue with a cadence in b.
What about the false cadence? This would be the most usual modulation  (followed by a perfect cadence in the relative key)
I-IV-V-I in D than I-IV-(V)-vi = i (Bm)  =
 (D-G-A-D -> D-G-F#-b)
confirming Bm - Em - F#7 - Bm
Comment: Oh, yes, Grace, you are right. My right hand is always quicker than the left, also when playing piane, haha ... Apolgyze! I didn't see it when reading it again and again. Let's delete this embarrassing converesation, yes? I will edit this iv and clean my glasses.
Comment: I didn't have my Ritalin today ...
Comment: I think you have typed something incorrect then...your first sentence says: *The relative minor root (Bm) IS a common chord (iv) of the starting key (D).* - I think you meant Bm is the chord *vi* and not chord *iv*.
Comment: Not a problem at all! It happens to the good of us too! ;)


verification: Newton method convergence

Question: P(x)=x$^2$-x-1 has a root of $\frac{1+\sqrt5}{2}$=1.61803398
My iterations are:
x$_0$=2
x$_1$ =$\frac{5}{3}$=1.6666
x$_2$=$\frac{34}{21}$=1.619
x$_3$=$\frac{1597}{987}$=1.618
So it took me 3 iterations to get the root. The question is, is the rate of convergence what you would expect? I was not sure what the rate of convergence would/should be so I am struggling with this.
Answer: You should expect quadratic convergence assuming you start relatively close to a simple root, as is the case here. The root is $\phi=\frac{\sqrt5+1}2$, so let $x_n=\phi+\epsilon$ where $\epsilon$ is the error. Then
$$y=x_n^2-x_n-1=\phi^2+2\phi\epsilon+\epsilon^2-\phi-\epsilon-1=(2\phi-1)\epsilon+\epsilon^2$$
$$y^{\prime}=2x-1=2\phi+2\epsilon-1=(2\phi-1)+2\epsilon$$
Then the next $x$ will be
$$\begin{align}x_{n+1}&=x_n-\frac y{y^{\prime}}=\phi+\epsilon-\frac{(2\phi-1)\epsilon+\epsilon^2}{(2\phi-1)+2\epsilon}\\
&=\phi+\epsilon-\frac{(2\phi-1)\epsilon+2\epsilon^2-\epsilon^2}{(2\phi-1)+2\epsilon}\\
&=\phi+\epsilon-\epsilon+\frac{\epsilon^2}{(2\phi-1)+2\epsilon}\\
&=\phi+\frac{\epsilon^2}{(2\phi-1)+2\epsilon}\end{align}$$
So if you neglect that $2\epsilon$ in the denominator, the next error will be $$\epsilon_{n+1}=\frac1{(2\phi-1)}\epsilon_n^2$$
This is quadratic convergence. We can attempt to confirm the rate of convergence as follows: perform Newton's iteration until it converges. The step after it is less than roundoff error should be about as good as you will get. So when the error is less than about $10^{-8}$ I would take the next root $x_N$, to be the exact value. Now you have a vector of roots, $(x_0,x_1,\dots,x_{N-1},x_N)$ and you can subtract the last value assumed good from all to get $(x_0-x_N,x_1-x_N,\dots,x_{N-1}-x_N,0)$. Now throw out the last element which was automatically $0$ and take logs of the absolute values of the rest $$(\ln|x_0-x_N|,\ln|x_1-x_N|,\dots,\ln|x_{N-1}-x_N|)=(\ln|\epsilon_0|,\ln|\epsilon_1|,\dots,\ln|\epsilon_{N-1}|)$$
Now we want to model our error as $\epsilon_{n+1}=K\epsilon_n^r$. Taking logarithms,
$$\ln|\epsilon_{n+1}|=r\ln|\epsilon_n|+\ln K$$
This is a first order linear difference equation for $\ln|\epsilon_n|$ and the general solution is
$$\ln|\epsilon_n|=c_1\cdot r^n+\frac{\ln K}{r-1}$$
Taking differences,
$$\ln|\epsilon_{n+1}|-\ln|\epsilon_n|=c_1(r-1)r^n\tag{1}$$
Taking logarithms yet again,
$$\ln(\ln|\epsilon_n|-\ln|\epsilon_{n+1}|)=n\ln r+\ln(-c_1(r-1))\tag{2}$$
At long last we have a linear equation $y=mx+b$ where the slope $m=\ln r$. We can plot the values of $y=\ln(\ln|\epsilon_n|-\ln|\epsilon_{n+1}|)$ vs. $x=n$ and so find the rate of convergence $r$. Starting with $x_0=2$, convergence is reached to double precision at $n=5$ so we have $5+1-1-1=4$ points to run a linear regression through. Our fit is $m=0.6721$ and $b=0.704$ so $r=e^m=1.9584$, pretty close to $2$, as it should be. The linear fit looks something like this:

Now we can go back to that old equation $(1)$ and do a linear fit with $x=r^n$ and $y=\ln|\epsilon_n|$. Our fit is now $m=c_1=-2.1157$ and $b=\frac{\ln K}{1-r}=1.1831$, so $K=e^{b(1-r)}=0.3218$. Compare this with our prediction of $K=1/\sqrt5=0.4472$ and it's not as good as our value of $r$ was, but at least of the right order of magnitude. The linear fit looks something like this:

Just wanted to show how you can try to get the rate of convergence of theoretically and experimentally.

verification: Newton method convergence


Retorno API Laravel json

Question: Estou com um seguinte problema, fiz uma API e me retorna um array:
"id": 1,
"email": "firstname.lastname@example.com",
"senha": "lucas123",
"created_at": "2018-02-15 16:48:12",
 "updated_at": "2018-02-15 16:48:12"`

e gostaria que só retornasse 3 campos id,email e senha
Método:
public function index()
{
    $contas = login::all();
    return response()->json(['contas'=>$contas], 200);
}

Comment: Opa sim! vou mandar so o metodo index pode ser ?
Comment: Por favor pode colocar o código do `controller`, a imagem dificulta muito.
Answer: É só selecionar com o método select o que precisa:
login::select('id', 'email', 'senha')->get();

Código completo:
public function index()
{
    $contas = login::select('id', 'email', 'senha')->get();
    return response()->json(['contas'=>$contas], 200);
}

Referencia: Laravel - Selects
Answer: Para que você consiga retornar um objeto e não um array, basta:
public function index()
{
    $contas = login::select('id', 'email', 'senha')->get();
    return response()->json(Arr::first($contas), 200);
}

Veja que no caso é usado um Helper do próprio Laravel que pega o primeiro item da resposta vinda do select. Assim quando passamos isso para o response o retorno será um objeto e não mais um array.
Para usar os helpers do Laravel adicione:
use Illuminate\Support\Arr;

IMPORTANTE:
Arr::first()

Como informado retorna o primeiro item de um array, se você precisa retornar uma Collection, ou mais de um item como objeto na mesma resposta o processo informado não funcionará.

Retorno API Laravel json


How to postpone a keyup ajax request until h:inputText length is reached

Question: Is there a way to postpone a keyup ajax request until a h:inputText value has reached a defined length?
I would like to reach the following goal:
a textInput field has to be filled with a combined date and time value. The expected format is: ddMMHHmm
Once the value reaches the length of 8 characters a new event object has to be added to an data list and should be displayed for confirmation immediately.
To confirm to add the new event the user simply presses enter inside this textInput field.
I don't know if there are different capabilities than using the ajax keyUp event to validate the input wihtout any further user interaction?
Here you see an very shortened example of my idea:
@Named
@SessionScoped
public class EventController {

  private Date          selectedDate; // +getter/+setter
  private MyEvent       event;
  private List<MyEvent> events; // ArrayList<MyEvent>(), +getter

  @PostConstruct
  private void init() {
     // load current events from DAO
  }

  public void validateInput() {
    event = new MyEvent(selectedDate);
    events.add(event);
  }

  public void confirmEvent() {
    eventDAO.addEvent(event);
}

And the view:
<h:inputText
  value="#{eventController.selectedDate}"
  converter="#{comfortableDateTimeInputConverter}"
  id="inputDateTime">
  <f:ajax

        executeCondition="<lengthOfInputField equals 8>"

        execute="inputDateTime"
        render="eventData"
        event="keyup"
        listener="#{eventController.validateInput}"
  />
</h:inputText>
<h:commandButton ... actionListener="#{eventController.confirmEvent}" />

<h:panelGroup id="eventData">
  <h:dataTable var="..." value="#{eventController.events}">
    // display event properties
  </h:dataTable>
</h:panelGroup>

The ComfortableDateTimeInputConverter extracts the date an time parts of the input string and returns an date object.
I am using

primefaces 5.2
mojarra 2.2.8

Edit 1
As suggested by BalusC I modified my h:inputText, but nothing seems to happen. This is my original code exept the controller name. I've added a logging message inside eventController.validateNewEvent, but it seems not to be executed. Did I miss something?
<h:inputText
  readonly="#{empty eventController.selectedPerson}"
  value="#{eventController.selectedDate}"
  id="inputDateTime"
  tabindex="3"
  converter="#{comfortableDateTimeInputConverter}"
  onkeyup="return value.length >= 8"
  onfocus="this.select()">
  <f:ajax
        event="keyup"
        execute="inputDateTime"
        listener="#{eventController.validateNewEvent}"
        render="selectedDate txtDate listEvents" />
  </h:inputText>

Also I tried to render="@all" at the ajax element, but still nothing happens. If i use event="blur" and leave the input with TAB it works like a charme ...
Edit 2 (resolved)
Replaced
onkeyup="return value.length >= 8"

with
onkeyup="return this.value.length >= 8"

and it works. See answer of BalusC ...
Answer: Just return false from onkeyup as long as value.length hasn't reached the desired value.
E.g.
<h:inputText ... onkeyup="return this.value.length >= 8">
    <f:ajax event="keyup" ... />
</h:inputText>

Comment: Would you like to take a look at my `Edit 1`? I don't know why the event isn't fired ...
Comment: GOT IT! I've played around with `alert(..)` inside the `onKeyUp` attribute of the `inputText`, `this.value.length` returns the length of the value. Now I've got it working as wanted. Thanks for your help!
Comment: Apparently your JS scope is polluted? I'll update the answer.


Cannot ssh into Azure VM using public IP

Question: We have a Site-to-Site from our On-premise to the Azure Cloud. I added a public IP to a VM. I am able to SSH into the VM using the private IP. I want to access the public IP over the VPN & internet. I dont know what I am missing here. Please can someone help ? If I add a rule to allow Any to Any, I can access the Public IP from my network but dont want to configure it like that.
Thank you in Advance
Answer: Unless you use Azure ExpressRoute, you can only access an Azure Public IPs over the Internet, your traffic will not traverse the VPN to reach the Public IP, it will leave your location as per any other Internet bound traffic.
As you have successfully reached the VM via the VPN, we can assume that SSH and your access itself is working fine.
Therefore you should review the Network Security Group attached either to the NIC itself or attached to the Subnet in which the VM resides to ensure it allows TCP/22 (SSH) with a source IP set to be your external IP address of your location (use something like: http://whatismyip.akamai.com/ to find out) and the destination either set to the private IP address of the VM (not the public IP) or an Application Security Group of which the VM is a member.
Comment: Thank you for your response Alex!
Comment: No problem! don't forget to up-vote and accept my answer if it helps.  Any other questions just ask.
Comment: Sorry, I did not completely respond yesterday. The rule in the NSG is present in my case. What I was trying to do as a test is that, I wanted to restrict the ssh access to the internal network and few of the external services (from Azure) so that it is not Any to Any. We found out that we can restrict the external services to our Virtual Network using the Service Tag as the source address in a NSG rule. The rule helped us give the access to the service. I am sorry for not mentioning the real problem here. Thank you for the quick reply Alex!!!


How to work with cookies in Safari following their Prevent cross-site tracking option

Question: I noticed that when Prevent cross-site tracking is checked in Safari, I am unable to set the secure cookies.  I described this issue in great detail in this question.
Then how do you set the secure cookies in Express with that setting enabled?

From MDN:
Values

The SameSite attribute accepts three values:

Lax
Cookies are allowed to be sent with top-level navigations and will be sent along with GET request initiated by third party website. This is the default value in modern browsers.

Strict
Cookies will only be sent in a first-party context and not be sent along with requests initiated by third party websites.

None
Cookies will be sent in all contexts, i.e sending cross-origin is allowed.

None used to be the default value, but recent browser versions made Lax the default value to have reasonably robust defense against some classes of cross-site request forgery (CSRF) attacks.

None requires the Secure attribute in latest browser versions. See below for more information.

It says in this article that Apple is phasing out third party cookies with Safari.  I'm reading online that third party cookies are generated by a different domain than the one user is visiting, for cross-site tracking, retargeting, and ad-serving.
I am working on a project where the frontend is served on Netlify and the backend is from Heroku.  Since the backend has a different domain than the front-end, the cookies generated from the node express backend are considered Third-party cookies?
Does that mean that I should have both frontend and backend on the same server going forward following this security practice?
Answer: Netlify allows you to proxy requests to your backend on a different hostname.
https://docs.netlify.com/routing/redirects/rewrites-proxies/#proxy-to-another-service
I'm not sure if it will let you set the cookies that way, Netlify might strip all headers, you should try.
If for some reason that does not work for you then you should either serve frontend and backend from the same hostname or set the cookie with JS on the client-side (which I don't recommend), also you can't set HttpOnly cookie from JS side.


Conditionally increment a case ID

Question: I have a table {cases} which has in part, upload_id, case_id case_name etc etc.
With a custom form, users, depending on role(4 custom roles), will upload a file upload_id. This  has been serialized. If it is a new case, case_name is NOT present then get max(case_id) add one and save to DB. Also users can add a file to existing cases, so the upload_id would auto-increase, and the case_id stays the same.
I've been working on this one area for 2 weeks and have come to the end of my rope.
I have written all of this into a custom PHP web app a few years ago, but now I have to rewrite it all in Drupal 7.  Any pointers in the right direction would be appreciated.
**********EDIT**************
I didn't think you could have 2 Serial Fields in the same table schema. I already have upload_id as a serial. I just can not figure out how to insert the case_id in Drupal.
Real scenario:
User uploads the file, upload_id =3796, case_id = 2916, case_name = 'xxx Macy'.
User forgot to include something needs to upload additional file. upload_id = 3797, case_id = 2916 where case_name = 'xxx Macy'. And still forgot a file, upload_id = 3798, case_id = 2916.
New user uploads file, upload_id = 3799, case_id = 2917, case_name = 'Jane Deer'.

Comment: Your question is a little unclear. Did you already create a custom table and form in your module and need help on how to handle the incrementing or are you still looking for a way to best do this in Drupal to start with?
Comment: @Zuzuesque Yes I have the table build using Schema API. And the code I am working with is  `$case_result = db_query("SELECT MAX(case_id) as case_id FROM {cases} ")->fetchCol();

        $form['case_id'] = array(
        '#type' => 'value',
        '#value' => isset($diagnostic->case_id) ? $diagnostic->case_id : NULL,
    );`

if it is a new case, take `$case_result` add 1 and insert into {cases} along with the other fields from the form.
Comment: @Steveep: The way you describe file_id it is not a serial. Serials don't change when editing an entry - case_id would be a serial as it doesn't update when a user uploads a new file. On its own table file_id might be a serial (and likely is) in the case table it is only a number. This is also a general SQL question and not really a Drupal question.
Comment: @Zuzuesque Here is the Schema I have:
`'upload_id' => array('type'=>'**serial**', 'length'=>7, 'unsigned'=>TRUE,'not null'=>TRUE,),
  'case_id' => array('type' => 'int','length' => 7,'unsigned' => TRUE, ),`
As you can see the `upload_id` is **Serial** and as such is not even a part of the form, but how do I set `case_id`?

$form['case_id'] = array( '#type' => 'value', '#value' => isset($diagnostic->case_id) ? $diagnostic->case_id : **NULL**, ); having it be NULL is the only way I found that doesn't cause a white screen of death.
Answer: They way you describe your case_id it sounds like the primary key of your table (a number which increases by 1 for each new entry). Rather than increasing this number in the form (and spare your self the trouble of assure atomic results when more than one person are entering cases at once) you can just set the column as primary key in your schema and let the db manage it. That way you don't need the field in your form at all.
$schema['case'] = array(
  'fields' => array(
    'case_id'       => array('type' => 'serial', 'unsigned' => TRUE, 'not null' => TRUE),
   //your other fields
  ),

  'primary key' => array('case_id'),
);

That said I would consider not using a custom table to start with and instead leverage the functionality Drupal is shipped with and use a node to represent your cases.
There is a contrib module called Serial Field which allows you to add a field to your content type which increases by 1 for each case you create. There is a file field in core which allows you to upload a file to the site as well. The name field is a little tricky as Drupal doesn't allow empty titles but you can easily work around it by adding a simple text field for the name and generate the actual title with Automatic Entity Label.
In this case you need to download the two contrib modules, install them, create a case node type, add and configure the fields and you are done. The advantage is you can still leverage a great number of existing modules working with nodes/fields and entities which is much harder/impossible with custom tables. And you can display the results using Views.
Answer: It sounds as though you are trying to keep as much of the old PHP app that you wrote and just wrap Drupal around it. You will have much more success if you recreate the app in drupal and then use the migrate module to pull in all the existing data.
As for the data structures in drupal. I would consider using nodes for cases, and then use the file entity module to build more usefulness around the files. Then you can link the two entities together with and entity reference.
Comment: I am not married to PHP, I don't care if it's written in COBOL or even  BASIC, as long as the functionality works.  As for any existing data, I have that under control, so I would basically be starting from scratch.
Comment: It isn't about the language it is about the framework. Drupal is written in PHP but, like most of the other answers stated, you're still writing as though you are just writing PHP and not using Drupal.
If you are going to use Drupal then you should use Drupal and not attempt to wrap Drupal around your existing functionality. Otherwise you are not using Drupal. Instead you are just writing another PHP app and you would probably be better off just updating the app to the latest PHP and giving it a fresh design.

Conditionally increment a case ID


Counting certain items in a list then using that output in an if statement

Question: I'm trying to develop a program that takes an number of inputs from a user then counts the particular number of times that number has been entered by the user then using that information decide what is the most common.
from collections import Counter
results = []
while len(results)<7:
    entered=int(raw_input('enter results:'))
    results.append(entered)

print results

distribution = Counter(results)

print distribution

it will output something like this:
enter results:1
enter results:2
enter results:3
enter results:2
enter results:6
enter results:5
enter results:4
[1, 2, 3, 2, 6, 5, 4]
Counter({2: 2, 1: 1, 3: 1, 4: 1, 5: 1, 6: 1})

from here i want to be able to take the information given at the end and tell the user which i the most common, i know the user can see it from the counter output, but its part of a task i have been given. i was thinking about using some along the lines of
if 2 >= 4:
     print 'most common.'

Comment: Have you looked at the output of `distribution.most_common(1)` for instance?
Comment: `most_common = distribution.most_common(1)` will give you `[(2, 2)]` and you can do `print('most common is {}'.format(most_common[0][0]))`! not what you want?
Comment: By `2 >= 4` do you mean an item is "most common" only if it appears at least 4 times?
Comment: @ettanany yeah, i just used that as an example because i have only had 6 inputs so that could change.
Comment: Jon, i've just tried 'distribution.most_common(1)' it works, but not quite what i was after, that just displays what the most common one is, i would like to given the user feedback depending on what that most common one is.
Comment: Oh no sorry, i've got it wrong, it needs to print out something based on a criteria, e.g if 4 came up 4 times.
Comment: It's not clear to me what you want exactly.
Comment: @user3092467 can you [edit] your question to give examples of what you actually want to display to the user and the criteria for that? It's a little fuzzy what you really want here.
Answer: I'm not entirely sure of the output of distribution.most_common, but if that doesn't work, here's a fairly simple loop that does the job
most_common = 0
for i in distribution:
    if distribution[i] > distribution[most_common]:
        most_common = i

print most_common

Also, if you would need to know if the frequency of that number is more than half of the input, you could have
if distribution[most_common] > 7./2:
    more_than_half = True
else:
    more_than_half = False

Comment: Also, since it isn't exactly clear (to me at least), I'll point out that in the loop, `i` is the list of different numbers you input, and `distribution[i]` is how often `i` occurs.
Comment: I basically what what you've done with one extra step, so once we've found the most common then put it into an if statement and see if it appears over a certain amount of times, in this case 4 e.g. 'if most_common > 4: print this is biased'
Comment: As I put in the second code block, you'd want `if distribution[most_common]` instead of just `most_common` . Glad I could be of help :)
Comment: I've just added that in and its come up with this error
 'Traceback (most recent call last):
  File "task 2.py", line 21, in
    if distribution(most_common) > 4:
TypeError: 'Counter' object is not callable'
Comment: It was meant to have square braces. Its `distribution[most_common]`
Answer: As per my understanding what you want is the following:
from collections import Counter

distribution = Counter({2: 2, 1: 1, 3: 1, 4: 1, 5: 1, 6: 1})

most_common_item = distribution.most_common(1)
print('most common is: {}'.format(most_common_item[0][0]))  # Output: most common is: 2


Test for cointegration between two time series using Engle–Granger two-step method

Question: I am seeking to test for cointegration between two time series. Both series have weekly data spanning ~3 years.
I am trying to do the Engle-Granger Two Step Method. My order of operations follows.

Test each time series for unit root via Augmented Dickey-Fuller.
Assuming both have unit roots, then find linear approximation of relationship via OLS. Then create a series of the residuals.
Test residuals for unit root via Augmented Dickey-Fuller.
Conclude cointegration (or not) by result of 3.

Questions:

Does this method look okay? (I'm an undergraduate, and I'm looking to analyze my data in a legitimate way, not necessarily to analyze it in the most rigorous known method.)
If one series cannot reject the null hypothesis with the ADF (and therefore does not have a unit root) in step 1, is it reasonable to conclude that the two series are not cointegrated because one data set is nonstationary? I wouldn't think so, but I want to be sure.
Both datasets look "stochastic", so I am wondering if it is appropriate to use OLS to measure the relationship to get the residuals.
Comment: Based on Plissken answer, I believe you have it wrong in your second question.

If you reject null hypothesis from ADF ("no unit root in residuals" = "no cointegration between series"), then you reject the hypothesis that there is no cointegration. So you actually conclude that there is cointegration.
Comment: I recommend you to use just Dickey fuller distribution table not augmented one since it is just a matter of distinguishing AR(1) and unit root not AR(p) where p is larger then 1.
Answer: First of all consider two time series, $x_{1t}
 $ and $x_{2t}
 $ which both are $I\left(1\right)
 $, i.e. both series contain a unit root. If these two series cointegrate then there will exist coefficients, $\mu
 $ and $\beta_{2}
 $ such that:
 $\\$
$x_{1t}=\mu+\beta_{2}x_{2t}+u_{t}\quad\left(1\right)
 $
$\\$
will define an equilibrium. In order to test for cointegration using the Engle-Granger 2-step approach we would
$\\$
1) Test the series, $x{}_{1t}
 $ and $x_{2t}
 $ for unit roots. If both are $I\left(1\right)
 $ then proceed to step 2).
$\\$
2) Run the above defined regression equation and save the residuals. I define a new "error correction" term, $\hat{u}_{t}=\hat{ecm}_{t}
 $.
$\\$
3) Test the residuals ($\hat{ecm}_{t}
 $) for a unit root. Note that this test is the same as a test for no-cointegration since under the null-hypothesis the residuals are not stationary. If however there is cointegration than the residuals should be stationary. Remember that the distribution for the residual based ADF-test is not the same as the usual DF-distributions and will depend on the amount of estimated parameters in the static regression above since additiona variables in the static regression will shift the DF-distributions to the left. The 5% critical values for one estimated parameter in the static regression with a constant and trend are -3.34 and -3.78 respectively.
$\\$
4) If you reject the null of a unit root in the residuals (null of no-cointegration) then you cannot reject that the two variables cointegrate.
$\\$
5) If you want to set up an error-correction model and investigate the long-run relationship between the two series I would recommend you to rather set up an ADL or ECM model instead since there is a small sample bias attached to the Engle-Granger static regression and we cannot say anything about significance of the estimated parameters in the static regression since the distribution depends upon unknown parameters.To answer your questions:1) As seen above you method is correct. I just wanted to point out that the residual based tests critical values are not the same as the usual ADF-test critical values.
$\\$
$\\$
(2) If one of the series is stationary i.e. $I\left(0\right)
 $ and the other one is $I\left(1\right)
 $ they cannot be cointegrated since the cointegration implies that they share common stochastic trends and that a linear relationship between them is stationary since the stochastic trends will cancel and thereby producing a stationary relationship. To see this consider the two equations:
$\\$
$x_{1t}=\mu+\beta_{2}x_{2t}+\varepsilon_{1t}\quad\left(2\right)$
$\Delta x_{2t}=\varepsilon_{2t}\quad\left(3\right)
 $
Note that $\varepsilon_{2t}\sim i.i.d.
 $, $x_{1t}\sim I\left(1\right)
 $, $x_{2t}\sim I\left(1\right)
 $, $u_{t}=\beta\prime x_{t}\sim I\left(0\right)
$, $\varepsilon_{1t}\sim i.i.d.
 $
$\\$
First we solve for equation $\left(3\right)
 $ and get
$\\$
$x_{2t}=x_{0}+\sum_{i=0}^{t}\varepsilon_{2i}
 $
$\\$
Plug this solution into equation $\left(2\right)
 $ to get:
$\\$
$x_{1t} =\mu+\beta_{2}\left\{ x_{0}+\sum_{i=0}^{t}\varepsilon_{2i}\right\} +\varepsilon_{1t}
x_{1t} =\mu+\beta_{2}x_{0}+\beta_{2}\sum_{i=0}^{t}\varepsilon_{2i}+\varepsilon_{1t}
 $
$\\$
We see at the two series share a common stochastic trend. We can then define a cointegration vector $\beta=\left(1\;-\beta_{2}\right)\prime
 $ such that:
$\\$
$u_{t}=\beta\prime x_{t}=\left(1\;-\beta_{2}\right)\left(\begin{array}{c}
\mu+\beta_{2}x_{0}+\beta_{2}\sum_{i=0}^{t}\varepsilon_{2i}+\varepsilon_{1t}\\
x_{0}+\sum_{i=0}^{t}\varepsilon_{2i}
\end{array}\right)
 $
$\\$
$u_{t}=\beta\prime x_{t}=\mu+\beta_{2}x_{0}+\beta_{2}\sum_{i=0}^{t}\varepsilon_{2i}+\varepsilon_{1t}-\beta_{2} x_{0}-\beta_{2}\sum_{i=0}^{t}\varepsilon_{2i}
 $
$\\$
$u_{t}=\beta\prime x_{t}=\mu+\varepsilon_{1t}
 $
We see that by defining a correct cointegrating vector the two stochastic trends cancel and the relationship between them is stationary ($u_{t}=\beta\prime x_{t}\sim I\left(0\right)
 $). If $x_{1t}
 $ was $I\left(0\right)
 $ then the stochastic trend in $x_{2t}
 $ would not be deleted by defining a cointegrating relationship. So yes you need both your series to be $I\left(1\right)
 $!
$\\$
$\\$
(3) The last question. Yes OLS is valid to use on the two stochastic series since it can be shown that the OLS estimator for the static regression (Eq. $\left(1\right)
 $) will be super consistent (variance converges to zero at $T^{-2}
 $) when both series are $I\left(1\right)
 $ and when they cointegrate. So if you find cointegration and your series are $I\left(1\right)
 $ your estimates will be super consistent. If you do not find cointegration then the static regression will not be consistent. For further readings see the seminal paper by Engle and Granger, 1987, Co-Integration, Error Correction: Representation, Estimation and Testing.


Event displaying in fullcalendar

Question: I want to display event of json from mysql database. But i can't display it in calendar. I think there are some mistakes in events. But i can't point it out.
Here is my code:
calendar.php:
 $(document).ready(function() {

  var date = new Date();
  var d = date.getDate();
  var m = date.getMonth();
  var y = date.getFullYear();

  $('#calendar').fullCalendar({
   theme: true,
   draggable: true,
   header: {
    left: 'prev,next today',
    center: 'title',
    right: 'month,agendaWeek,agendaDay'
   },
   editable: true,
   /*events: "json_events.php",*/
   events: function(start, end, callback){
    $.getJSON("json_events.php",
     {
      start: start.getTime(),
      end: end.getTime()
     },
     function(result){
      for(var i=0; i<result.length; i++){
       var row = result[i];
      }
      //format the result into an array of calevents
      $('#calendar').fullCalendar('addEvent', {id:row[0], title:row[1], start:row[2], end:row[3]} );
      //then pass the calevent array to the callback
      callback(calevents);
     }
    );
   },
   eventClick: function(event){
    editEventShow(event);

   },
   eventDrop: function(event, daydelta, minutedelta) {
    alert(event.title + ' was moved ' + daydelta + ' days\n' + minutedelta + ' minutes\n'+
     '(should probably update your database)');

   },
   dayClick: function(dayDate){
    /*$('#dialog').dialog('open');
    var date, month, year;
    date  = dayDate.getDate();
    month = dayDate.getMonth()+1;
    year = dayDate.getFullYear();
    dayDate = year + "-" + month + "-" + date;*/
    addEventShow(dayDate, this);

   },
   loading: function(bool) {
    if (bool) $('#loading').show();
    else $('#loading').hide();
   },

 });
    });
    </script>

json_events.php:
 <?php
  require("../../../connect/config.php");

  $link = mysql_connect("$server","$user","$password") or die(mysql_error());
  mysql_select_db($db);
  $query = "SELECT id,title,start, end FROM events";
  $result = mysql_query($query) or die(mysql_error());
  $arr = array();
  while($row = mysql_fetch_assoc($result)){
    $arr[] = $row;
  }
  echo json_encode($arr);
 ?>

Can you help me about the problem??
Thanks.
Comment: are you passing start and end to the getJSON function so that you can put a WHERE clause in the SQL query? i don't see it used... is this just for example purposes?
Answer: EDIT: (new answer)
  for(var i=0; i<result.length; i++){
   var row = result[i];
  }

the expression in the loop above is going to overwrite row in each iteration of the loop. so later when you're calling row[0], row[1], etc, you're not actually getting an array out of it, unless the last result[i] is in fact an array (and if that's the case the loop would be unnecessary)
i can't give you 100% of the answer, but that should get you in the right direction.
update: i looked a little harder and it looks like you need to move the line:
$('#calendar').fullCalendar('addEvent', {id:row[0], title:row[1], start:row[2], end:row[3]} );

inside of the for loop.
Comment: Yes and no, there is no error displaying the json_events.php.
But i don't know the right way to format the result in $.getJSON() in events.

Can you help me for that?
Answer: If you are providing JSON that is already in the CalEvent form, you can just provide a URL that returns a JSON string formatted with the information you need - the function to turn it into cal events isn't necessary, as shown in your commented out line.
JSONLint will help you figure out if you have correct JSON.  What you're looking for is something along the lines of:
[
    {
      id: row[0],
      title: row[1],
      start: row[2],
      end: row[3]
    },
    {
      ... // next event
    },
]

as a string returned from json_event.php.

Event displaying in fullcalendar


Intuition behind Bayesian statistic and MCMC when applied to time series models

Question: Even though I've studied Probability and Statistics, my knowledge of Bayes stops at the famous formula. So, when it comes to modern Bayesian computational methods, I'm just able to understand answers to questions like this one, but I'm still missing the most important point: playing around with some Bayesian tools, I've noticed that models parameters are gradually updated as new information is disclosed.
Let me explain better what I would like to understand: when we're dealing with time series analysis and prediction, we often have a huge sample but we also have the task to select a proper window width to estimate our model parameters; this is because we are burdened by the usual trade-off between long and short term memory, for which:

using a large sample would probably mean a very stable estimate but unable to adapt quickly to structural changes in the time series;
using a small sample would probably mean an unstable estimate but able to adapt to structural changes.

The simplest example of this trade-off is a moving average of the time series, but consider more convoluted examples like a function which estimates the parameters of a simple $AR(1)$ model and the application of such function through a rolling window: the autocorrelation parameter's time series, $\rho$, is going to have lower variance in the larger window width case than in the smaller one.
(In the figure below I've produced an example by estimating $\rho$ from a rolling window $AR(1)$ model on a time series to show that the values obtained can be very different according to the window width).

After some trials with MCMC tools and Bayesian statistic applied to models parameters, I've seen things like this:

If the sample is a time series, my intuition suggests me that the density of beta in the figure above comes from a parameter that varies over time. This "variation over time" should simply be a time series of beta that is gradually updated while the prior distribution is plugged into the Bayesian tool. Then parameters distribution is sampled from MCMC instead of being represented by a single value coming out from the solution to some minimization problem (I'm thinking about OLS). From this point of view, Kalman filter is a Bayesian tool when used to solve dynamic linear models, because of the mechanism that updates the values of the parameters as soon as new information is disclosed.
My questions:

do Bayesian statistics tools behave like a rolling/expanding window parameter estimation when applied to a time series?
Do Bayesian statistics behave like the Kalman filter when applied to a time series?
If 1 and/or 2 are at least partially true, can Bayesian statistics and MCMC be considered tools that solve the aforementioned trade-off of time series analysis window width?
Could you please provide a simple example in R for this problem: show the time-varying parameters that describe the mean and the standard deviation of your favourite time series as Bayesian statistics would yield them by using MCMC. You can use any package and any time series you want.
Answer: You seem to be confusing some things, so let me clarify. First of all, Bayesian models do not have any special connection to time-series. Same as for non-Bayesian models, using Bayesian framework you can define possibly infinite number of different statistical models.
Sure, you can first estimate the model for $n$ time-series points, and then update it for the $n+1$'th point, but the results would be the same as if you estimated the model on $n+1$ datapoints all at once (this is so-called Bayesian updating). Of course you can compare the estimate for the parameter from $n$ points, to the one calculated using $n+1$ points, but again, you can do this for non-Bayesian models as well. So there is no special "autoregressive" property. Moreover, from technical reasons, Bayesian updating is not simple to be done for complicated models that require MCMC sampling, so in practice you would usually just calculate the model on $n+1$ datapoints all at once, rather then updating it sequentially.
As about "variability over time" of $\beta$, let me use an example. Imagine a trivial model
$$
x_{t+1} = \mathcal{N}(x_t\beta, \sigma)
$$
with known $\sigma$. In non-Bayesian setting, you could estimate the $\beta$ parameter by maximizing the likelihood function. The only major difference in Bayesian setting would be that you would assume a prior distribution for $\beta$, and maximize (or sample from) posterior $\propto$ likelihood $\times$ prior. What follows, by assuming $\beta$ to be a random variable, setting prior for it, and plugging it to Bayes theorem, you would end up with a posterior distribution. Posterior distribution helps you to quantify how uncertain are you about the $\beta$ parameter, it does not have any special connection to time series or changes over time. In the above model, we do not assume $\beta$ to vary over time, so the model does not learn anything specific about such variability. Updating your model sequentially and looking at the changes of the estimates over time would only show you how your estimates become more precise with growing sample size.
So Bayesian models do not need to behave like rolling/expanding window parameter estimation. You can implement rolling average model in Bayesian setting, but you can also implement a number of other time series models. You can plug in all the data at once and nothing would "roll". On another hand, as described earlier, you could estimate the non-Bayesian models for $n$, $n+1$, $n+2$ etc. points as well.
Bayesian models also do not solve any problems for time-series. In some cases, with Bayesian model, if you already have model estimated on $n$ points, it could be easier to "update" the model for the new $n+1$'th point, but this is not always straightforward.


Export a set of svg image tags as a single png

Question: Followed the tutorial here http://techslides.com/save-svg-as-an-image
The problem is that my svg is a set of <image> tags, I'm trying to stitch them together and export as a full png/pdf, was wondering if that's possible
All I get at the moment is a ~1.7 mb file thats a blank image
EDIT:
Heres a sample of the svg I'm trying to export
<svg width="11342.5" height="320" version="1.1" xmlns="http://www.w3.org/2000/svg">
  <g width="11342.5" height="320">
     <image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="source1" width="336" height="320" x="0" y="0"></image>
     <image xmlns:xlink="http://www.w3.org/1999/xlink" xlink:href="source2" width="336" height="320" x="0" y="0"></image>
     ...
  </g>
</svg>

Comment: `my svg is a set of tags, I'm trying to stitch them together`, isn't all svg a "set of tags"?  What does that mean?  More than one SVG?  Update your question with the SVG you are trying to export.
Comment: @Mark edited the question with the svg, hope that helps!
Answer: The impression you give from your sample is that you think SVGs work like HTML.  That you place a series of elements in the file and the renderer lays them out for you.  That is not the case.  In SVG you have to position elements yourself.
For example, all your <image> elements are stacked on top of one another.  That's because they are all positioned at (0,0).  You need to set the X position of each image to the right hand edge of the previous one.  For example:
<image width="336" height="320" x="0" y="0"/>
<image width="336" height="320" x="336" y="0"/>
<image width="336" height="320" x="672" y="0"/>
..etc..

Some other issues with your file:

Your images have a width of 336, but your SVG width (11342.5) is not a multiple of 336. Why is that?
The <g> element does not have width and height attributes. You might as well remove them.
Your image link xlink:href="source1" looks wrong.  It should probably be something like xlink:href="source1.jpg" etc.  Make sure those URLs are correct, otherwise you will either get blank images or the "broken image" icon (depending on the browser).
You don't need to define the xlink namespace in every <image> tag.  Move the xmlns:xlink="http://www.w3.org/1999/xlink" to the <svg> element.  And you can leave it out of the <image> elements.


How do you embed $Z_5 \times Z_7$ into $Z_{2^8}$?

Question: Basically, the real question which I thought was better asked that way is what are the ways to represent all ordered pairs of elements $(x,y)$ where $x\in Z_5$ and $y\in Z_7$ in a byte of memory? I.e.  There needs to be atleast 5*7 = 35 code words.  I'm working on a way right now, but if someone's already shown all the ways, please post a link.  Ways that are useful arithmetically are better.  I.e. if adding two bytes has some meaningful result on their embeded pairs.
Comment: I'm fairly certain unsigned bytes usually act like elements of $Z_{2^8}$.
Answer: Probably the most straightforward way to do this would be to use the first 4 bits to keep track of the elements of $\mathbb{Z}_5$ and the next 4 bits to keep track of $\mathbb{Z}_7$.
So $(3,5) \mapsto 0011\;0101_2$ etc.
Just so you know. In terms of arithmetic, $\mathbb{Z}_5 \times \mathbb{Z}_7$ cannot be embedded in $\mathbb{Z}_{2^8}$ (as groups under addition). Lagrange's theorem tells us that the order of a subgroup must divide the order of the group and $35$ doesn't divide evenly into $2^8$. In fact the only group homomorphism from $\mathbb{Z}_5 \times \mathbb{Z}_7$ to $\mathbb{Z}_{2^8}$ is the trivial one which sends everything to zero.
Answer: Embed first $Z_5$ into $Z_8$ and $Z_7$ into $Z_8$. Then simply embed $Z_8 \times Z_8$ into $Z_{2^6} \hookrightarrow Z_{2^8}$
If you are looking for all ways, keep in mind that $Z_5 \times Z_7$ is "the same" as $Z_{35}$. Chinese Reminder Theorem gives you a way to identify them as groups, and then you forget the group structure...So your problem asks you how to embed $Z_{35}$ into $Z_{2^8}$...
Comment: @Dan: It's not a map of groups.
Comment: I think that's what I need, $Z_{35}$.  What's the mapping look like between the two groups?  I really need to learn algebra :D
Comment: @Dan: the generator of $Z_{35}$ corresponds to the element $(1,1)$ of $Z_5\times Z_7$. It is both an additive and a multiplicative homomorphism.
Comment: @DanDonnelly:  For $\mathbb Z_5 \times \mathbb Z_7 \to \mathbb Z_{35}$, just view the elements of $\mathbb Z_{35}$ as pairs $(a,b), a \in \mathbb Z_5, b \in \mathbb Z_7$  You will need the CRT to make the correspondence $28 \leftrightarrow (3,0)$
Comment: Since you don't care about the group structure, if you identify $Z_n$ as $0,1,2,..., n-1$, then the map $(a,b) \to 7a+b$ is a bijection from $Z_5 \times Z_7 to Z_{35}$.


if and else statement in php

Question: Can anyone please help me figure this out. I am trying to make it so that an image is displayed when the value in mysql table = 1. i've got that bit covered and the image is displayed. Is there a way to include an if or else statement to say if the value in the mysql table is 0 then display different image?
Thanks.
<?php
        $get_social_set = get_social();

        while ($social = mysql_fetch_array($get_social_set))

        {

    ?>

    <?php echo"
            "; } ?>

Comment: That's really php basics, you maybe should learn a little php before asking questions about it.
Answer: if ($social['name_of_field_youre_checking'] == 0) { ... }

Comment: thank you so much have been trying to figure it out for ages.
Comment: what do i put in the brackets { ... } is that where the image directory goes? because how i'm typing it it won't work.
Comment: that's up to you. I don't know what you intend to do.
Answer: Something like this should work in a php file:
<?php

$image = false;
// get results from database
// process results
if ( $results === 1) {
    $image = 'tick.png';
} else {
    $image = 'something.png';
}
?>
<img src="<?php echo $image ?>" />

Bye
Comment: thanks this code seems to work but now where the image is just set to 'tick.png' it can not find the image directory. but when i try pointing it to the full directory this doesnt work and i get a syntax error. :/
Answer: Name image files as foreg : tick0.png , tick1.png and use the code below 'SHOW' being your db fieldname :
 <?php echo""; } ?>

if and else statement in php


$f(x) = \int_e ^ {e^x} \ln{\frac{x}{\ln t}} dt$. Then what is $f'(3) $?

Question: $f(x) = \int_e ^ {e^x} \ln{\frac{x}{\ln t}} dt$. Then what is $f'(3) $?
I know I can solve it by using the following theorem.

I need to first verify that all the functions here satisfy their conditions. Then I will be able to say that I can solve this problem by using this rule.
But this question has been given in a 10+2 exam. How can I make my students understand this solution? Can anyone please tell me? Is there any other way to solve this problem?
EDIT Some of  the answerers below are suggesting to do the following::
$f(x) = \int_e ^ {e^x} [\ln x - \ln{(\ln t)} ]dt$.
I do not think it can be done. Since the domain of $x$ can include the negative real numbers also. If $x <0$ , then in the interval$(e^x , e)$ , $\ln x$ and  $\ln{(\ln t)}$ will not remain defined.
What will we do if we were to find $f'(-3)$?
Comment: Multivariable chain rule would be the way to explain this - seeking out every dependence and simply adding the derivative w.r.t. each dependency.
Answer: You can simplify using rules of $\log$ first. $$f(x)=\int_e^{e^x}\ln(x)-\ln(\ln(t))dt=\ln(x)\int_e^{e^x}dt-\int_e^{e^x}\ln(\ln(t))dt$$
Now you don't need to differentiate under the integral sign. Just use FTC.
Comment: I have added an edit..Can you please check?@user658409
Comment: Can you please read the edit once? @user658409
Comment: Can you please read the edit once? @user658409
Answer: $$f(x)= \int_{e}^{e^x} \ln x~ dt-\int_{e}^{e^x} \ln(\ln(t)) dt
\implies f(x)= \ln x (e^x-e) -\int_{e}^{e^x} \ln(\ln t) dt$$
Now D.w.t. $x$ appllying Lebnitz Rule, we get
$$f'(x)=\frac{1}{x}(e^x-e)+e^{x}\ln x -e^x\ln x$$
$$\implies f'(3)=\frac{e^3-e}{3}$$
Doing it OP's way using the genral Lebnitz Rule as stated in his answer
$$f'(x)= e^x \ln \frac{x}{x}+0+\int_e^{e^x}  \frac{\ln t}{x}\frac{1}{\ln t} dt=
\frac{1}{x}(e^x-e) \implies f'(3)=\frac{1}{3}(e^3-e)$$
Comment: I have added an edit..Can you please check?@Dr Zafar Ahmed DSc
Comment: Thanks I have edited it now.
Comment: Can you please read the  edit once?@Dr Zafar Ahmed DSc
Comment: It would be great if you would say if I am wrong in the edit?
Comment: @sani you may see my edit  for doing it your way.
Comment: I do not want to use Libnitz Rule. Can you please read my question once again? @Dr Zafar Ahmed DSc
Comment: You may not have understood what I am saying..@Dr Zafar Ahmed DSc
Answer: You could also use  that $\displaystyle\ln{x\over \ln t} =\ln x -\ln \ln t$. In this way you can separate them and using the lineality of the integral you would have an elemental function plus another that is eassier to derivate since there is no $x$ in the integral.
Comment: I have added an edit..Can you please check?@Richard Medina Rodriguez
Comment: Note that $x$ can not be negative. Since $t\in(e,e^x)$ then $\ln t>0$. Then for the first logarithm in the integral to be well defined $x>0$. So there is no problem. And the domain of $f$ is $x>0$.
Comment: No.    $x$ can be negative..Can you not find $\int _2^1 f(x) $ ? upper limit of the integration may not be greater than lower limit.
Comment: If we assume $x<0$ then we would have $$\int_{e^x}^1 h(x,t)dt+\int_{1}^e h(x,t)dt$$ where $h(x,t)$ is the argument of your integral. There the first integral is well define since $\ln t<0$ in $(e^x,1)$ and $x<0$. But in the second integral the function $f$ we have is not well define since $x<0$ but in the interval $(1,e),\ \ln t>0$. So we can not have $x<0$.


Parallel execution of a command on few boxes over ssh (using bash)

Question: What would be the cleanest way to execute same command remotely on several boxes with joint output to console?
For instance, I would like to tail logs from several boxes all together in my console as one output.
Comment: If you're asking how to do this from an interactive command line, that's a better fit for [unix.se] than here. StackOverflow's scope is limited to *software development*.
Answer: Definitely GNU parallel is a nice tool for parallelizing things in the shell. It also has reasonable remote execution capabilities.
It can be as easy as
parallel -S $SERVER1 -S $SERVER2 echo ::: running on more hosts

Comment: Running `parallel --tag` is useful here. Also, you can add servers using commas, `-S $SERVER1,$SERVER2,$SERVER3`
Comment: For `tail -f` you should also have a look at `--line-buffer`


Apache htaccess redirecting subdomain traffic to primary domain when https

Question: I'm having issues reaching one of my subdomains via https.
Consider the following domains:

mydomain.com
tasks.mydomain.com
stuff.mydomain.com

Whenever I attempt to go to https://stuff.mydomain.com, the files (db, etc) from the primary mydomain.com are shown instead of stuff.mydomain.com. Hope that makes sense.
My primary domain is using the PHP framework Yii 1.1.15 with the following .htaccess in web root:
Options +FollowSymLinks
IndexIgnore */*
RewriteEngine on

# if a directory or a file exists, use it directly
RewriteCond %{REQUEST_FILENAME} -s [OR]
RewriteCond %{REQUEST_FILENAME} -l [OR]
RewriteCond %{REQUEST_FILENAME} -d

# otherwise forward it to index.php
RewriteRule ^.*$ - [NC,L]
RewriteRule ^.*$ index.php [NC,L]

Any ideas?
Edit
I originally reached out on SO but was recommended I try here.
Comment: Does one of the subdomains work properly on https?  Which one(s) have an SSL certificate assigned to them in particular?
Comment: You should delete the comment you just posted because while the second sentence doesn't make your question technically off topic, some people think it is and will close your question.
Comment: Was my answer http://serverfault.com/a/750064/101203 able to solve your question?  If so, I'd appreciate if you upvote and/or mark it as accepted so I get credit and also so people in the future who read this know that it was a solution. Thanks,
Answer: Can you double-Check to make sure an SSL certificate is set up for each subdomain.
It may be that you don't have one set up for the subdomain that's not working correctly.
Based on your comment it doesn't sound like this is the case, but that's the general cause so it'd be worth double checking.


How enable xdebug only for one host in Nginx

Question: How i can enable xdebug only for one virtualserver in Nginx?
In Apache i can config that via .htaccess("php_value xdebug.remote_enable On"), for example.
Answer: I found solution in Is it possible to set up PHP-FPM with different pool-options (xdebug enabled / xdebug disabled)
I create second PHP-FPM pool with
php_admin_flag[xdebug.remote_enable]=on in config and different socket path of course.
In Nginx host config location section, i can choose socket with or without xdebug for location{...}


Multiplying polar complex numbers ( Check my work )

Question: I am multiplying complex numbers, but not sure if I am doing it right. Are the answers below to the questions b) and d) correct?

These answers came back as wrong. Can anyone see where i went wrong?? Thought they was correct.
Comment: Looks correct. Good job. (Perhaps you should have put * and = in answer b)
Answer: Your answers are correct.  These problems are rather simple if you know the rule:  to multiply complex numbers in polar form, multiply the magnitudes and add the angles.
Comment: These answers came back as wrong. Can you see why?
Comment: No, I can't.  Can you check with who marked them wrong and get back to me?
Comment: Yes i will. So frustrating.


Show that Lie algebra $L$ is solvable (nilpotent) if and only if $ad(L)$ is solvable (nilpotent)

Question: Show that Lie algebra $L$ is solvable (nilpotent) if and only if $ad(L)$ is solvable (nilpotent).
If $L$ is solvable, then $ad(L)$ is the image of $L$ under a lie algebra morphism and so will be solvable. I would appreciate some help with the $(\leftarrow)$ as well as the nilpotent cases... I've been scratching my head for awhile on this one.. Thanks!
Answer: Hints:

If $$0 \rightarrow L_1 \rightarrow L_2 \rightarrow L_3 \rightarrow 0$$ is an exact sequence of Lie algebras, what do you know about solvability / nilpotency of $L_2$ related to solvability / nilpotency of $L_1$ and $L_3$?

Added: Every introductory treatment on solvable / nilpotent Lie algebras should contain the (easily proven) lemmata I am alluding to here, maybe in different language. Wikipedia phrases it like this, referencing standard textbooks by Serre and Knapp:

Given a Lie algebra $\mathfrak g$ and an ideal $\mathfrak h$ in it,
$\mathfrak{g}$ is solvable if and only if both $\mathfrak h$ and $\mathfrak{g}/\mathfrak h$ are solvable.
The analogous statement is true for nilpotent Lie algebras provided $\mathfrak h$ is contained in the center. Thus, an extension of a solvable algebra by a solvable algebra is solvable, while a central extension of a nilpotent algebra by a nilpotent algebra is nilpotent.

What is $\ker(ad)$?
Comment: Sequences like that do *not* split in general, but still every introductory treatment on solvable and nilpotent Lie algebras should contain easily proved lemmata about what happens in such sequences. See edit. -- $ad$ is certainly not surjective when we take $gl(L)$ as its codomain, but we might just restrict to its image ...
Comment: Hmm well lie algebras are sort of like vector spaces so I'll assume that this sequence splits, in which case $L_2$ is solvable $\iff$ $L_1$ and $L_3$ are solvable.... Also $ker(ad)=Z(L)$. So you're saying look at $0 \rightarrow Z(L) \rightarrow L \rightarrow \frac{L}{Z(L)} \rightarrow 0$

Is $ad: L \rightarrow gl(L)$ surjective?? No way... Hmm i'm a bit confused still, but great hints!! got any others?


Why does R take so much time to run auto.arima(). How can I shorten the calculation time?

Question: I have been trying to run analysis and model a ts series of Natural Gas spot prices. With data provided by the Qandl API.
The whole analysis was working fine, however, I experiences issues with the auto.arima function.
1- If I specify the NG series as XTS, the auto.arima function does not take into account the seasonality. It's quite a bummer for Natural Gas, as the consumption of this resources is all about the time of the year.
2- If I specify the NG series as TS, the auto.arima function takes forever to calculate, and I am not even sure it can finish it. As i let it run the calculation for 20 min once, and it couldn't come with an answer. Hence, I am wondering if there is a problem with my code or my specification.
I'm new to data science, it's my first TS project. I really love what I am doing !
Here is my code:
<code>NG1= Quandl("CHRIS/CME_NG1", start_date =start, end_date =end, type =  type)$Settle
prices2returns <- function(x) diff(log(x))
spotprice2returns <- function(x,y) log(x) - log(y)
nn=300
r_NG1=xts((NG1),frequency = 300)

**tsrng= xts(r_NG1, frequency = 300)**

NG_model1= auto.arima(tsrng,trace = TRUE, test = "kpss", ic="bic")
forecast=forecast(NG_model1, h=100)
[![Forecast without seasonality][1]][1]
#############################################################
Fitting models using approximations to speed things up...

 ARIMA(2,1,2) with drift         : -1746.361
 ARIMA(0,1,0) with drift         : -1735.83
 ARIMA(1,1,0) with drift         : -1771.906
 ARIMA(0,1,1) with drift         : -1773.598
 ARIMA(0,1,0)                    : -1744.349
 ARIMA(1,1,1) with drift         : -1764.14
 ARIMA(0,1,2) with drift         : -1765.134
 ARIMA(1,1,2) with drift         : -1755.608
 ARIMA(0,1,1)                    : -1782.117
 ARIMA(1,1,1)                    : -1772.66
 ARIMA(0,1,2)                    : -1773.653
 ARIMA(1,1,0)                    : -1780.426
 ARIMA(1,1,2)                    : -1764.128

 Now re-fitting the best model(s) without approximations...

 ARIMA(0,1,1)                    : -1785.296

 Best model: ARIMA(0,1,1)

Series: r_NG1
ARIMA(0,1,1)

Coefficients:
          ma1
      -0.0966
s.e.   0.0141

sigma^2 estimated as 0.04087:  log likelihood=901.17
AIC=-1798.34   AICc=-1798.33   BIC=-1785.3

Training set error measures:
                       ME      RMSE       MAE        MPE     MAPE      MASE         ACF1
Training set 3.216548e-06 0.2021306 0.1179395 -0.0660193 2.448464 0.9986513 0.0003003316

Forecast method: ARIMA(0,1,1)

Model Information:
Series: r_NG1
ARIMA(0,1,1)

Coefficients:
          ma1
      -0.0966
s.e.   0.0141

sigma^2 estimated as 0.04087:  log likelihood=901.17
AIC=-1798.34   AICc=-1798.33   BIC=-1785.3

Error measures:
                       ME      RMSE       MAE        MPE     MAPE      MASE         ACF1
Training set 3.216548e-06 0.2021306 0.1179395 -0.0660193 2.448464 0.9986513 0.0003003316

###############################################################

**tsrng= ts(r_NG1, frequency = 300)**

NG_model2 = auto.arima(tsrng, trace=TRUE, test="kpss", ic="aic",
                    stepwise=FALSE, approximation=FALSE, D=1)
# It blocks here, and takes a lot of time to compute the model

NG_frct=forecast(NG_model4,h=100)
plot(NG_frct, include = 1500)
</code>
What do you suggest I do ?
I was thinking about specifying manually the seasonal arima function, but I lack the skills to do so for now, where should I start to learn how to specify the function myself ?
What did I do wrong in my code?
Comment: Does this answer your question? [Time series modeling with high-frequency data](https://stats.stackexchange.com/questions/29424/time-series-modeling-with-high-frequency-data) There was an ever closer related thread, but I cannot find it...
Comment: Or maybe there wasn't.
Comment: Thanks a lot Richard. I was looking at it. I tried it, and it does a great job, however, I have 2 issues:
- How to select the best K
- How to forecast afterwards, the Forecast function does not work
Comment: See Rob J. Hydman's blog posts ["Forecasting weekly data"](https://robjhyndman.com/hyndsight/forecasting-weekly-data/) and ["Forecasting with long seasonal periods"](https://robjhyndman.com/hyndsight/longseasonality/).
Comment: Thanks a lot ! Now I understand. I will use the function asap !
Answer: This is a well known problem and has been discussed in Rob Hyndman's blog post "Forecasting with long seasonal periods". The problem is that the memory use is prohibitively high for seasonal periods of around 200 and more (you have 300). The solution that Hyndman proposes is to use a regression with Fourier terms and ARMA errors (the Fourier terms account for the seasonality). See the blog post above and another one, "Forecasting weekly data", for details.


How to detect if background music is playing in WP8?

Question: If anyone has developed WP apps before you know that you can't pass certification if your app stops music that is currently playing without the users consent.
I did see this question here which might have worked for WP7 apps but it apparently doesn't work for WP8. I assume it doesn't work because the WP8 OS doesn't support XNA (It is only backward compatible, and if you developed the app using 7.1).
Has anyone come across the solution for detecting background music in WP8.
Answer: I believe checking for MediaPlayer.GameHasControl is what you're looking for. Use that property and other members of MediaPlayer to satisfy application certification guidelines 6.5.1 Here's an end-to-end example of how @ http://henry-chong.com/2012/02/pro-tip-including-background-music-for-your-windows-phone-app/
BTW, 6.5.x application certification requirements don't apply if your app is a Music+Video app. That's one way to address 6.5.1 :)
Comment: Note that this will only work with the music played by the Microsoft music player. Other music streaming apps (Nokia Music, Spotify,...) will not resume. That seems to be unavoidable, according to MSDN on background audio architecture:There is only one media queue. Your application cannot pause background audio, play something with MediaElement then resume the background audio stream.
Answer: I believe that Microsoft.Xna.Framework.Media.MediaPlayer.State is still supported in Windows Phone 8 (MSDN source):

You can reference and use the following XNA Framework assemblies in
apps that target Windows Phone OS 8.0:
...
Microsoft.Xna.Framework.Media.dll
...
Comment: As stated here http://stackoverflow.com/a/7034556/883738, MediaPlayer.State will be Playing even if you're playing the music. GameHasControl determines if the music was started from your app, or if another app was playing before your app started.


How to copy the text button present in a particular textview to clipboard when a button is pressed?

Question: How to copy the text present in a particular text view to clipboard when a button is pressed?
Answer: try below code on button click
<code>String stringcopy = textView.getText().toString();
int startIndex = textView.getSelectionStart();
int endIndex = textView.getSelectionEnd();
stringcopy = stringcopy.subString(startIndex, endIndex);
ClipboardManager clipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
clipboard.setText(stringcopy);
</code>


Playing 16th Note at High Tempo

Question: In Classical/fingerstyle guitar is playing 16th note at tempo > 100 BPM is normal ? I am  I am practising at 60 BPM which i feel is fast, since the gap between each metronome click is very small.
But at Speed let's say 100 BPM playing 16th note, will be difficult ? Reason i am asking since the gap between each beat is very very small so for ears will be able to differentiate the 16th note pattern
Beat  1 e & a
Beat  2   & a
Beat  3 e &
Beat  4   & a

So it will be difficult to differentiate between Beat 2, 3, 4 ?
Answer: Accomplished guitarists routinely play 16th notes at tempos even faster than 100bpm. A trained ear (or even an untrained musical ear) can tell the difference between the rhythms you posted at the bottom of your question, although beats 2 and 4 are the same rhythm.
Correct me if I am wrong but I believe you are asking about practicing to a metronome where the clicks are set to 16th notes. Some metronomes can play specific increments of notes like 8ths and 16ths. The other solution is to double or quadruple the bpm for 8ths and 16ths. If you have a metronome that can vary the sound or volume of the note divisions, for example, accent the main beats:
ONE e & a TWO e & a…
…then it is not difficult to hear the beat within the clicks. If this is not possible it just becomes a blur of clicks and can be counterproductive to practice.
Even if you can vary the sound and volume of the click I highly recommend using a simpler quarter note click and becoming accustomed to feeling the subdivisions between the beats. It is easier to play this way in the long run and you develop an important skill, being able to feel the subdivisions and generate your own rhythm accurately.
Start weaning yourself off of using a 16th note clicks, even at slow tempos. Switch to 8ths and then quarter notes. Hearing a quarter note click and being able to feel 8ths, 16ths and different types of triplets between the clicks is an important skill and will help make you a better musician in the long run.
Answer: "Difficult" is subjective. For a novice, yes, but definitely doable with a little practice. I believe that most experienced players can accomplish this on guitar. It will be easier to play this sort of a line with a pick (my opinion), depending on what notes correspond to the rhythm.
This sort of rhythm reminds me of rhythm drills we were forced to practice in marching band. About 100 bars of a variety of 16th note patterns. A "bit" like reading binary if you're familiar with that sort of thing.

Playing 16th Note at High Tempo


Expected return value of a recursive probabilistic function

Question: In this question asked on Stackoverflow, the asker gives a Java function similar to this:
<code>public int f(){
    if(Math.random() >= 0.5){
        return 1;
    }
    else{
        return 1 + Math.max(f(), f());
    }
}
</code>
In math-speak, that would be written something like this:
$$f = \left\{
    \begin{array}{ll}
        50\%\ chance : & 1 \\
        50\%\ chance : & 1 + max(f, f)
    \end{array}
\right.$$
So basically, $f()$ is a probabilistic function that calls itself twice with 50% probability, and returns the maximum depth of its calls.

If you draw the call-tree and label the first case "tails" and the second case "heads," you can see that the question "What is the probability that this function eventually returns" is the same as the question "What is the probability of eventually getting more heads than tails.".  Thus, this function terminates with probability 1. This also allows you to calculate the expected number of total times that $f()$ is called.

However, the one question I haven't been able to answer is, what is the expected return value of $f()$?
My first thought was that the expected value $E_f$ should be
$$E_f = 0.5 * 1 + 0.5 * (1 + max(E_f, E_f))$$
However, that is clearly wrong; that would mean that, no matter how many calls $f()$ makes to itself in the second case, $E_f = 2$ !
So, does anyone know how to calculate the expected return value of $f()$?
Comment: don't you mean $(1+\max(E_f,E_f))$ instead of just $\max(E_f,E_f)$ in the end ?
Comment: @dkuper: Yes, thanks
Answer: The result of the procedure is a random positive integer $X$ such that
$$
X=1+B\cdot\max(X_1,X_2),
$$
where $X_1$ and $X_2$ are two independent copies of $X$ and $B$ is a Bernoulli random variable with $P[B=1]=P[B=0]=\frac12$.
To describe the distribution of $X$, let $R_n=P[X\geqslant n]$ for every positive integer $n$. The stochastic identity above translates into
$$
P[X\geqslant n+1]=P[B=1]\cdot P[X_1\geqslant n\ \text{or}\ X_2\geqslant n],
$$
that is,
$$
R_{n+1}=R_n-\tfrac12R_n^2.
$$
Since $R_1=1$, this recursion characterizes the distribution of $X$.
Unfortunately, iterating quadratic functions is notoriously difficult. Fortunately, estimating $R_n$ is rather straightforward, leading to $R_n\sim\frac2n$. Thus, the "expected return value" $E[X]=\sum\limits_{n\geqslant1}R_n$ is infinite while the return value $X$ is almost surely finite.
Comment: Reminds me of https://en.wikipedia.org/wiki/St._Petersburg_paradox
Comment: *"Thus, the expected return value is infinite while the return value is finite"* - ...whoa, I didn't even know that was possible.
Comment: @raylu The comparison is quite on-topic.
Comment: In retrospect, a function with infinite expected value seems not-so-surprising.  Take for example `while(random() > 0.5) returnVal *= 2`.  The expected return value is $1/2 + 2/4 + 4/8 + \ldots = 1/2 + 1/2 + 1/2 + \ldots$


Ramfs/Disk hybrid

Question: A common hack to improve the performance of MySQL and other programs is to configure their tmp space to be a ram based file system.  However in the case of MySQL if you fill up the space the query in question, and sometimes the server, will crash.  How would I go about "extending" the ramfs mount/filesystem such that when it is full it will continue to disk.  I realize writing to disk is a performance hit, but in this case the performance hit is less important than a stability hit.  The key point is that the Ramfs device would have the priority for all writes on a space available basis.
Ideas?
Answer: Hi planning is key: know how much data you are attempting to push, load test, and size up your systems.  You can avoid deadlocks with "more" RAM if you are encountering issues now.  Don't make your tempfs or /dev/shm larger than 50% of physical RAM.  Note lines 59-61 in this link: http://www.mjmwired.net/kernel/Documentation/filesystems/tmpfs.txt
Comment: In the situation I'm thinking here it does not matter how big or small the ram disk portion is.  The goal is to write to disk in a seamless manner when the ram disk is full.  However the next major piece is that ram should have priority over disk for writes when space is available.  I could use two LVM PV's but I don't know if the write priority would happen.

Ramfs/Disk hybrid


Django how to reverse to autocreated page

Question: I have a CustomUser model and a UserProfile model. The UserProfile is linked to the CustomUser via a foreign key. A new UserProfile is auto created whenever a new CustomUser is created.
After a new CustomUser is added, I want to land on the UserProfile page so the person adding the user can also edit the profile. I have not been able to figure out how to specify the UserProfile id in the view for adding the new user.
The models:
class UserProfile(models.Model):
    user = models.OneToOneField(CustomUser, null=True, on_delete=models.CASCADE)
    preferred_name = models.CharField(null=True, blank=True, max_length= 75)
    pronouns = models.CharField(null=True, blank=True, max_length= 40)
    phone = PhoneField(blank=True, help_text='Contact phone number')
    job_title = models.CharField(null=True, blank=True, max_length= 75)
    birthdate = models.DateField(null=True, blank=True)
    bio = tinymce_models.HTMLField(null=True, blank=True)
    profile_image = ConstrainedFileField(
        null=True,
        blank=True,
        upload_to='projects/employee_profiles',
        content_types=['image/png', 'image/jpg', 'image/jpeg', 'image/gif'],
        max_upload_size=2097152,
    )

    def create_user_profile(sender, instance, created, **kwargs):
      if created:
            UserProfile.objects.create(user=instance)

   post_save.connect(create_user_profile, sender=CustomUser)

class CustomUser(AbstractUser):
    full_name = models.CharField(max_length=250, null=True)
    age = models.PositiveIntegerField(null=True, blank=True)
    employee_type = models.ForeignKey(Group, null=True, on_delete=models.SET_NULL, default=1)
    is_active = models.BooleanField(null=False, default=True)

The view:
class AddCompanyEmployee(CreateView):
    model = CustomUser
    template_name = 'manage/add_employee.html'
    form_class = AddCompanyEmployeeForm

    def get_success_url(self):
        return reverse('userprofile_detail', args=[self.kwargs.get('userprofile_pk')])

The form:
class AddCompanyEmployeeForm(UserCreationForm):
    class Meta:
        model = CustomUser
        fields = UserCreationForm.Meta.fields + ('email', 'full_name', 'age',)

The UserProfile URL:
from django.urls import path
from .views import EmployeeDirectory, UserProfileDetailView

urlpatterns = [
    path('', EmployeeDirectory.as_view(), name='directory'),
    path('profile/<int:pk>', UserProfileDetailView.as_view(), name='userprofile_detail'),
]

This is the error I get when I add a new user:
NoReverseMatch at /manage/add_employee/
Reverse for 'userprofile_detail' with arguments '(None,)' not found. 2 pattern(s) tried: ['user\\-profiles/profile/(?P<pk>[0-9]+)\\Z', 'directory/profile/(?P<pk>[0-9]+)\\Z']

Comment: Exactly what is the `pk` for the `UserProfileDetailView` supposed to be? The primary key of the created `CustomUser`?
Comment: It is actually the UserProfile id.
Answer: You can work with:
class AddCompanyEmployee(CreateView):
    model = CustomUser
    template_name = 'manage/add_employee.html'
    form_class = AddCompanyEmployeeForm

    def get_success_url(self):
        return reverse(
            'userprofile_detail', kwargs={'pk': self.object.userprofile.pk}
        )
It will look for the OneToOneField in reverse, and thus obtain the .pk of the related UserProfile.
That being said it is quite strange that you use both a CustomUser and UserProfile. Usually if you implement your own user model, that is to add fields that you would otherwise store in a UserProfile, and thus to prevent having to work with two models.


How and why do we prove that $\mathcal{l}(I) \leq \sum_{i=1}^\infty \mathcal{l}(J_i)$ where $I=\bigcup_{i=1}^\infty J_i$ is an open interval?

Question: Leading up to a treatment on Lebesgue outer measure, I have been shown a proof that

$\mathcal{l}(I) \leq \sum_{i=1}^\infty \mathcal{l}(J_i)$ for $I=\bigcup_{i=1}^\infty J_i$ is an open interval (where $\mathcal{l}$ is the length function, i.e. $\mathcal{l}(I)=b-a$ if $I=(a,b)$).

The proof creates slightly larger intervals for each $J_i=(a_i,b_i)$ by adding an amount $\epsilon>0$ to each endpoint and considers a finite open cover of the closed interval $[a,b]$ by these enlarged $J_i$'s.
My question is, what is the purpose of this discussion, what does it show us, and what is the intuition behind the proof/why does this need to be proved at all?
Comment: The property is evident using *another* property(es) of the Lebesgue measure... that you haven't proved yet.
Comment: If you are interested in some particular proof of this fact, you could perhaps mention the source of the proof, too. BTW a proof of this is also given in Oxtoby's Measure and Category as Theorem 1.5.
Comment: I am not entirely sure whether this still qualifies as fair use, but here is [page 3](http://i.stack.imgur.com/wMukl.png) and [page 4](http://i.stack.imgur.com/ikmcg.png) from the Oxtoby's book I have mentioned.
Comment: @MartinSleziak, thank you. Can you explain the sentence in the proof "All but a finite number of the intervals $(a_n,b_n)$ would have to precede $I_k$...". I don't really follow the logic here.
Answer: Since we started discussing this particular proof in the comments, I will copy here the proof from Oxtoby's book Measure and Category. (The second book in the series Graduate Texts in Mathematics.)

Theorem 1.5 (Borel). *If a finite or infinite sequence of intervals $I_n$ covers an interval $I$, then $\sum|I_n|\ge|I|$.
Proof. Assume first that $I=[a,b]$ is closed and that all of the intervals $I_n$ are open.
  Let $(a_1,b_)$ be the first interval that contains $a$.
  If $b_1\le b$, let $(a_2,b_2)$ be the first interval of the sequence that contains $b_1$.
  If $b_{n-1}\le b$, let $(a_n,b_)$ be the first interval that contains $b_{n-1}$
  This procedure must terminate with some $b_N>b$.
  Otherwise the increasing sequence $\{b_n\}$ would converge to a limit $x\le b$ and $x$ would belong to $I_k$ for some $k$.
  All but finite number of intervals would have to precede $I_k$.
  This is impossible since no two of these intervals are equal.
  (Incidental1y, this reasoning reproduces Borel's own proof of the "Heine-Borel theorem" [5, p.228].)
  We have
  $$b-a < b_N-a_1 = \sum_{i=2}^N (b_i-b_{i-1}) +b_1-a_1 \le \sum_{i=1}^N (b_i-a_i),$$
  and so theorem is true in this case.
In the general case, for any $\alpha>1$ let $J$ be a closed subinterval of $I$ with $|J|=|I|/\alpha$, and let $J_n$ be an open interval containing $I_n$ with $|J_n|=\alpha|I_n|$.
  Then $J$ is covered by the sequence $\{J_n\}$.
  We have already shown that $\sum|J_n|\ge|J|$.
  Hence $\alpha\sum|I_n| = \sum|J_n| \ge |J| \ge |I|/\alpha$. Letting $\alpha\to1$ we obtain the desired conclusion.
[5] Borel, E.: Lecons sur la theorie des fonctions. Paris: Gauthier-Villars 1914.

The OP asked about this particular step:

All but finite number of intervals would have to precede $I_k$.

If we have that $b_n\to x$ and $x$ belongs to an open interval $I_k$, then starting from some $n$ each $b_n$ belongs to $I_k$. (From the definition of limit.) But since $(a_{n+1},b_{n+1})$ was the first interval from the sequence $I_1,I_2,\dots,I_k,\dots$ which contains $b_n$, the interval $I_k$ must come in this sequence at some point after the interval $(a_{n+1},b_{n+1})$. This leads to a contradiction, since $I_k$ is preceded only by finitely many intervals (since $k$ is some finite number) and, at the same time, in the proof we constructed infinitely many intervals of the form $(a_n,b_n)$ which precede $I_k$.


php gd : image cannot be displayed because it contains errors

Question: I'm very annoyed with this error :
If I comment out the
require_once'../class/myclass.class.php';

the image is displayed.
If I un-comment my line calling myclass.class.php, I have this message:
"The image "http://..." cannot be displayed because it contains errors."

My code is simple:
myclass.class.php :
<?php
class myclass {
  public function getPanelData( $model ){
    $aFieldsData = array(
      'PAN35'=>array(
        'col'=>1,
        'row'=>3,
        'v-font'=>10,
        'v-marge-top'=>0,
        'v-marge-right'=>1,
        'v-marge-bottom'=>0,
        'v-marge-left'=>1
      )
    );
    if( key_exists($model, $aFieldsData) )
      return $aFieldsData[$model];
    else
      return false;
    }
  }
?>

img.inc.php:
<?php
  session_start();
  require_once('myfunctions.inc.php');
  require_once('../class/myclass.class.php');
  $oData = new myclass();
  header('Content-Type: image/png');
  $sPanelModel = $_SESSION['produit'];
  $sEtiquette = '../img/etiquettes/label_'.$sPanelModel.'_preview.png';
  $rImg = imagecreatefrompng($sEtiquette);
  imagepng($rImg);
  imagedestroy($rImg);
?>

Note: This code works if I comment require_once calling myclass.class.php.
Calling functions.inc.php works (only few functions).
tree :
/
 + class
   + myclass.class.php
 + inc
   + functions.inc.php
   + img.inc.php
 + images
   + etiquettes

Comment: I don't really understand what you are trying to achieve - why do you even use imagecreatefrompng() when you are just outputting the very same image? You could simply deliver it by using readfile(). I guess you will do something with your image ressource later... If it works when you comment the "require" declaration I would suspect that you might have multiple declarations of "myclass", or that in the file itself there is a blank line after ?>, thus outputting blanks. You might want to have another look.
Comment: Hi, thanks for your answer. This code is the beginning, i made step by step to be sure of my code. Later, i will make some loops to fill this first image.
Comment: Watch out for PHP error reporting, especially since 5.4. The error won't be printed on screen but will throw an error with the image. Try 'error_reporting(0);' at the top of your code, worked for me.
Answer: If it is true that it works by uncommenting the require() for myclass.class.php, then the most likely cause is this file contains blank lines (whitespace) before the <?php or after the ?>. This would add Ascii characters to the output of the image, or insert a php error message (Headers could not be sent) on your header() statement and thus mess up your file.
However, as I mentioned in my comment, if your sole purpose is to output the picture you could use readfile() instead of creating an image instance.
Hope that helps,
Stefan
Comment: OMG ! Thanks a lot _ExternalUse_ ! I'm used to check for theses blank spaces at beginning of all my files, but this time I thought it was already done.


What is a good reference that connects calculus with differential geometry?

Question: It seems that most texts on differential geometry books tend to take a quantum leap from calculus without refering the latter. Differentials suddenly becomes forms, functions suddenly becomes diffeomorphisms, direction directives suddenly becomes vector fields...
Can someone reference a good text or set of notes that connects the ideas from calculus to differential geometry so that the two subjects are merged together?
Comment: @theage Since I'm included in your comment, I can say for sure you are drawing the wrong conclusion.  The reason mine is posted as an answer is, I don't like to post answers in comments.
Comment: You might take a look at the book From Calculus to Cohomology. They avoid the use of differentiable manifold for half of the book and introduce differential forms in open set in $\mathbb R^m$. That might make your life a bit easier (but there are some algebra in the book... not so sure now)
Comment: It's interesting that the most complete "answer" to this question is the only one posted as a comment - the Dunning-Kruger effect in action.
Comment: you might find http://www.supermath.info/AdvancedCalculus13.pdf useful. I try to start by treating multivariate analysis, Jacobians and all that then I spend the latter half on forms and such. Tu and Lee's manifold texts are certainly helpful, perhaps Conlon, or Munkres also should be considered.
Comment: @JamesS.Cook Hey thank you for the wonderful reference! Although I didn't know that liberty university had a math department given all the controversies over creationism
Comment: I'm actually working on differential geometry this summer. I'll post a link if you want. I suppose creationists can also do math. At least, I know a few...
Answer: Calculus on Manifolds - Spivak
Answer: Loring W. Tu's book is probably the most gentle differential geometry text I've seen.


A line with a random length, attaching to the origin. What is the chance of a given point along 1D axis belonging to that line?

Question: The question is based on an engineering problem and, due to my lack of knowledge in statistics, I found it difficult to express the question clearly in maths language.
The problem is formulated like this:
1) Imagine there is an origin, and a 1D coordinate system (say, L);
2) Along this 1D axis (L), there is a 'rigid' rod attaching to the origin, and its length is a random variable (always positive) and follows a PDF p1.
Question 1: for each given point on the axis L, what is the chance of that point belonging to the thread.
My solution to Q1: for a given coordinate x, for it to 'fall' into the thread, the thread length (a) has to be equal or greater than x. Therefore, the chance of a point x belonging to that rod is equal to the integration of that PDF, from x to infinity.
Can anyone please confirm if my solution above is correct?
If so, the question 2 is as follows: if the near end of the rod no longer attaches to the origin, but the location of it is also a random variable, which follows, say, another, PDF p2. Then, for each given point on the axis L, what is the chance of that point belonging to the rod?
I am so confused by this question 2, as I have no idea what I should do with the potential interplay between these two random events (i.e. the length of rod and the location of near end of the rod). I wonder if anyone here can help me with this, or at least let me know what kind of 'theory' I should look into for solving this problem?
Comment: You don't need any background: just describe the problem you face, in your own terms, as clearly and specifically as possible.  Define or explain uncommon technical terms.
Comment: Ok. Let's just assume the two random variables, i.e. the length of rod and the coordinate of its near end, have their own probability density functions. Please ignore the 'Gaussian' part.
Comment: Gaussian distributions have no limits, so it would behoove you to specify clearly what you mean by this assumption.  Also: Is the thread taut?  Is it equally likely to lie to the left or right of the origin?  Why do you refer to "interplay between ... random events" when considering just a single random variable?  A lot of essential detail seems to be missing.
Comment: Hi Whuber, thank you for your reply. Sorry if it wasn't clear as I have little background in statistics and my English is poor.

To answer your questions:
It is more like a 'rigid' rod and its length is a random variable, so it is not taut.
It is only allowed to lie to the right of the origin, so the coordinate system is more like a 'vector'.
There are two random variables in Question 2. one is the length of the rod, and another one is the location of the near end of the rod.

hope this makes things clearer...
Comment: Sorry I was editing my previous reply when you wrote this. Please refer to my reply above. Thank you.
Comment: Thank you for the edits.  A similar problem attaches, though: if the rod lies always to the right, its length is described by a positive number.  That is not true of any Gaussian distribution.
Comment: Are the two distributions such that "near end" can be further than the "far end"? I.e. is the support of the two distributions overlapping? If not, can one assume that two ends are independent random variables?
Comment: The near end of the rod is always the near end. I guess one can imagine this as a 'void' between the origin and the near end of the rod. The length of the void is a random variable, so is the length of the rod.
Answer: The terminology of probability--outcomes, events, and random variables--was invented to help with such problems.  But let's begin with a picture of the situation:

This figure plots possible values of the endpoints $(X,Y).$  They are random variables.  The axes are copies of the line; its origin is at the bottom left where the axes meet.
Pick a point $x$ on the line, as shown simultaneously on both axes.

Question 1 concerns the event
$$\mathcal{E}_1:X \ge x$$ where the point $x$ is covered by the rod of length $X$.
Question 2 concerns the event
$$\mathcal{E}_2:X \le x \le Y \text{ or } Y \le x \le X$$ where the point $x$ is covered by a rod with termini at $X$ and $Y$.  This event is shown by the gray portion of the figure (which extends, in principle, infinitely far to the right and infinitely far upwards).

The distribution of $X$ is often described by stating what probability is assigned to the event $X\le x.$  This is the distribution function (aka CDF) of $X,$ $$F_X(x)=\Pr(X\le x).$$  In these terms, question (1) is answered using basic laws of probability (namely, the probabilities of disjoint events add) as
$$\eqalign{
\Pr(\mathcal{E}_1) &= \Pr(X=x\text{ or } X \gt x) \\
&= \Pr(X=x) + 1 - \Pr(X\le x) \\
&= \Pr(X=x) + 1 - F_X(x).
}$$
The joint distribution of $(X,Y)$ can be described by stating what probability it assigns to infinite quadrants whose upper right corners are at a location $(x,y).$  This is the distribution function $$F_{XY}(x,y) = \Pr(X\le x\text{ and } Y \le y).$$
The figure shows we can express the probability of the gray region as equal to

The probability of the entire region to the left of or at $X=x,$ equal to $F_X(x),$
plus the probability of the entire region below or at $Y=x,$ equal to $F_Y(x),$
minus the probability of the intersection of those regions (shown as the square with $(x,x)$ at its upper corner), equal to $F_{XY}(x,x).$

We see that the "interplay of events" is visually captured by this two-dimensional picture.  This is a general, powerful technique for reasoning about two random variables together.
Thus, the general answer to the second question is
$$\Pr(\mathcal{E}_2) = F_X(x)  +  F_Y(x) - F_{XY}(x,x).$$
The termini are said to be independent when $F_{XY}(x,y) = F_X(x)F_Y(y).$  In that case the general answer can be reduced to a formula in terms of $F_X$ and $F_Y$ alone by substitution in its last term.
Comment: Thank you so much for your explanations. I understand your answer to Question 1, however I do not quite get your answer to Question 2.

If X represents the length of the rod, and Y the length of the 'void' between the origin and the near end of the rod, should the event in question 2 become Y<=x<=X+Y instead?
Comment: Sorry I misread the definitions of your X and Y variables. If your X represents near end and Y the far end. Then is the probability function of Y the convolution of the rod length and the length of the 'void' between origin and the rod? So basically I just need to do the convolution step before using following your answers?
Comment: The convolution won't work, because if you assume $X$ is near and $Y$ is far, then $X$ and $Y$ are (strongly) *dependent,* whence you must use the general form of the solution I originally derived.