Content disposition header on Nginx

Question: I am doing a setup where Apache runs the web application and NginX serves files that users download. The files should be downloaded with their real names instead of the names their are being stored with. The real names are retrieved from a database.
I do not understand why am I failing to force NginX to download the files with their real names.
I send the following headers in php from Apache to NginX:
header('Location: ' . "http://nginx.mysite.com:8080/" . $file['upload_id']);
header('Content-type: ' . $this->mime);
header('Content-Disposition: attachment; filename="' . $file['file_name'] . '"');
header('Last-Modified: ' . date('D, d M Y H:i:s \G\M\T' , $this->data_mod));

It looks like NginX ignores the content-disposition header? Or am I failing in the syntax?
Edit:Output of
curl --head http://…/your/file.ext

is as follows:
HTTP/1.1 200 OK
Server: nginx/1.0.5
Date: Sat, 16 Feb 2013 14:26:33 GMT
Content-Type: application/octet-stream
Content-Length: 38807550
Last-Modified: Sun, 06 Jan 2013 14:37:36 GMT
Connection: keep-alive
Accept-Ranges: bytes

Comment: I have added the output of the curl command to the question. Thank you!
Comment: Please, provide output of `curl --head http://…/your/file.ext`.
Comment: As you see, nginx is not sending it. `Content-Disposition` is not a standard header. It could be filtered inside Apache or nginx due to security considerations.  Try to disable all security modules (mod_security?) temporary and check again.
Answer: nginx isn't going to know it needs to return the header just because the header was return from Apache. The request to Apache is going to return that header, but you're also telling the client to go fetch that file from nginx, and nginx isn't going to receive that header nor know to send it back unless you have something in the nginx configuration to do that.
Here's the way it's working now (... represents other headers unimportant to this discussion):
Request to Apache
GET /your/file.ext HTTP/1.1
Host: apache.mysite.com
...

Response from Apache
HTTP/1.1 302 Redirect
Location: http://nginx.mysite.com:8080/fileid
Content-Disposition: attachment; filename="filename"
...

When your web client receives this, it's basically being told to go somewhere else.  That's going to initiate a new request:
Request to nginx
GET /fileid HTTP/1.1
Host: nginx.mysite.com
...

Response from nginx
HTTP/1.1 200 OK
... (no Content-Disposition header)

You need to have the nginx response return the Content-Disposition header, not the Apache/PHP response. You have a few options here:

Pass the nginx request through to a script that will translate the fileid form to the file.ext form, send back the Content-Dispotion: header and return the data (this is very similar to your PHP script, except it also needs to return the file data).
Request the file.ext form from nginx and configure nginx to always add a Content-Disposition: header with the filename= portion set the file.ext of the request.
Update your PHP script to proxy the nginx request internally, so that rather than returning the Location: header and subsequent redirect, it returns the header it needs, then fetches the data from nginx internally and dumps it out to the client.

The second option seems cleanest to me, but your setup may not support it.
Comment: Thank you very much for your response! I would like to go with the second option. Could you be that kind to tell me what exactly should I put in the Nginx config file to allow it to always add a content-disposition header?
Comment: [The answer to 'custom HTTP headers for static files with Django'](http://stackoverflow.com/questions/263122/custom-http-headers-for-static-files-with-django#tab-top) has an example of how to add a `Content-Disposition:` header for a file.

Content disposition header on Nginx


Minimization of iron costs: financial mathematics for an high school

Question: Meanwhile I apologize to everyone. I have never treated financial mathematics. A colleague of mine asked me for help but I can't give an answer. I have two exercise. This is the first.

A company operates in the iron sector, and sustains the following fixed costs equal to $ 648 \, €$ for month. A variable cost of $4$ € euros per quintal produced. An additional cost determined by the use of a particular ironworking machinery, equal to half of the square of the quintals produced.

What are the function of the total monthly cost and the function of the average cost?
What is the production at which you have the lowest average cost and what is the total monthly cost at this quantity?

The results are:
$$a) \quad C=0.5q^2+4q+648, \quad C_m=0.5q+\frac{648}q+4$$
$$b)\quad  q=36\, \frac{\text{quintals}}{\text{month}};\quad  C(36)=€\, 1440$$

My observation: with the first informations of the problem I have a parabola. Why? For the rest of the questions I think that there are some derivative to be done. Never studied financial mathematics. Thank you all for your understanding.
Comment: I don't know what it is in real life, but the way the problem is stated leads immediately to the quadratic given for $C$.
Comment: OK. $0.5q^2$ comes from "half the square of the quintals produced"; $4q$ comes from "4 euros per quintal produced"; $648$ comes from "fixed costs equal to $648$ per month." And any equation of the form $y=ax^2+bx+c$ with $a\ne0$ yields a parabola when you graph it.
Comment: I'm glad you worked it out.
Comment: Are you asking why that equation for $C$ gives a parabola, or are you asking why the information in the problem gives that equation for $C$?
Comment: @GerryMyerson Hi, both the informations. Thank you for your comment. Just my start was a curiosity.
Comment: Yes, to get the production with lowest average cost, you take the derivative of the average cost, set that derivative equal to zero, and solve for the production $q$.
Comment: @GerryMyerson I have not understood the steps because I not known the theory for your last comment. For the derivates I have understood..
Comment: @GerryMyerson But couldn't it be a quarticle, a cubic, or a polynomial of different degree of $2$ or any function? This I had intuited :-) thank you very much.
Comment: @GerryMyerson Hi, I have found the solution. :-( I have always many commitments. Excuse me everyone in the site.
Answer: Before to understand the exercise I had to study a bit on the internet. Regarding the average cost $C_m(q)$ one must keep in mind that the average cost is equal to the cost per unit of production; while the marginal cost $C_{\text{mar}}$ represents the change in cost due to a unit increase in production which we will denote by the independent variable $q$. We therefore have:
\begin{equation}
    C_m(q)=\frac{C(q)}{q}
\end{equation}
and
\begin{equation}
    C_{\text{mar}}(q)=\frac{dC(q)}{dq}
\end{equation}
So in Economics we use linear, quadratic, cubic, exponential etc. functions for the cost function. The curves of the average cost and marginal cost intersect at the stationary points of the average cost (i.e. at the points where the average cost has zero derivative).
Given the nature of the problem with the indications provided of the exercise we have three parameters. Excluding the circumference which is not a function unless there are appropriate domain restrictions, the simplest case is represented by a parabola.
$$C(q)=0.5q^2+4q+648$$
with average cost equal to
$$C_m(q)=\frac{0.5q^2+4q+648}{q}=0.5q+\frac{648}{q}+4$$
Now for the marginal cost it is necessary to use the derivative, equal to
$$C_{\text{mar}}=\frac{dC(q)}{dq}=q+4$$
Intersecting the two functions unit or average cost $C_m(q)=(0.5q^{2}+4x+648)/q$, branch of nonequilateral hyperbola, and marginal cost we have the intersection point $(36, 40)$, so $q=36\, \text{quintals}/\text{month}$ and $C(36)=1440$ euros.


Listwise learning to rank with negative sample relevance

Question: Typical listwise learning to rank (L2R) algorithm tries to learn the rank of docs $\{x_i\}_{i=1}^m$ corresponding to a query $q$. If we use correlation efficient to label the relevance between docs and query, then the label $y_i\in[0, 1]$. The larger the $y_i$, the more relevant of the doc $x_i$ to $q$. Most L2R algorithms, such as approximated rank/NDCG and ListMLE, focus more on the ranking accuray of positve correlated doc (i.e. $y_i$ close 1) by giving larger weight in the loss function. This is common in information retrieval problem.
However, if the relevance between docs and query can also be negative, i.e. $y_i\in[-1,1]$, and the ranking accuaracy of both large positive and large negativa docs are important, how can L2R algorithms handle this problem ?
Answer: As you mention L2R losses put higher weight on the most relevant documents.
If you want to put high weights on both the most relevant and the least relevant documents, you need to create a new loss for that purpose.
A simple option would be the sum of two existing L2R losses, one with $y_i$ and one with $-y_i$.


Quantidade de linhas por pagina reporter viewer c#

Question: Gostaria de saber como exibir no relatório (reporter viewer/c#)  o número de linhas por páginas e a quantidade total em todas as páginas do relatório.
Comment: A resposta dada não foi satisfatória ?
Answer: Olá,
Infelizmente o "reportviewer" não funciona dessa forma. Ele mesmo determina a quantidade de informações que serão exibidas na pagina.
Caso que necessite de funcionalidades a mais, recomento você utilizar o "crystalreports" (http://www.crystalreports.com/) ou activereports (https://activereports.grapecity.com/)
Answer: Olá, Vi sua pergunta e sim existe maneira de você saber o numero de linhas, a pagina e o numero total de paginas. Esta dentro de functions.


A question on sampling distributions

Question: I once read the following interesting  distribution related question:

An insurance company identified the 10 safest and 10 least-safe cities
  from 200  cities in the US based on the mean number of years drivers
  went between automobile  accidents. It turns out that the cities on
  both lists were all smaller than the 10  largest cities in the list of
  200 cities.
How do we use the sampling distribution model of the mean to explain
  this fact?
Comment: A famous example of this concerns mapping cancer mortality rates by administrative region within a country (such as counties within the US): both the highest and lowest rates tend to occur within the least-populous units. See, *inter alia*, Gelman and Price, [All maps of parameter estimates are misleading](http://www.stat.columbia.edu/~gelman/research/published/allmaps.pdf). Note that this is not a *sample* size effect; it's a *population* size effect.
Comment: Hint: Consider the impact of sample size on the standard error of the mean
Comment: Could I understand this way? For larger cities, the sample mean is very close to the real mean. For small cities, the sample mean can be skewed to either smaller side or the larger side due to the smaller sample size, and they are easily to be chosen to be safe or less-safe.
Comment: For this question, should I assume that the city with larger size should have a larger sample than the city with smaller size?
Comment: @user3269. You answered your own question perfectly in the comment above. Turn that into a proper answer, rather than a comment.
Comment: @Whuber, how to understand the difference between sample size effect and population size effect. It seems that there is a strong correlation between sample size and population size. The large population can have large sample size.
Answer: Thanks for the hint of Henry and Harvey. I think this question can be answered as follows:
We can assume that large cities tend to have large sample sets. With larger sample set, the sample mean tends to approximate the population mean. On the other side, the sample mean for the smaller cities tends to either skewed to the smaller side(less-safe) or the larger side(safe side). This make them more easily to be identified as safe or less safe cities.
Comment: I believe this answer confuses *population* with *sample.*  The question concerns data about *entire populations* (the cities), not samples from those cities.  The point of the question is that when there is no association between safety and location, each city can be viewed *as if* it were a random sample from the entire population of drivers in all 200 cities.  The variance of the mean will be higher in smaller cities.
Comment: There's at least one article by Thomas Kane and Douglas Staiger, c. 2000, that's relevant to this topic.

A question on sampling distributions


State Space Model Form for Equations

Question: I have a set of equations which I have to write in state space model form but unfortunately I'm having a bit of difficulty doing so. They are given as:
$y_{t} = x_{t} + z_{t}$
$x_{t} = x_{t-1} + w_{t}$
$ w_{t} = \kappa \beta_{t} + \epsilon_{t}$
$z_{t} = \Phi z_{t-1} + \psi \alpha_{t} + \tau_{t}$
where $y_{t}$ is the observed value, $\alpha_{t}$ and $\beta_{t}$ are known values, and $\epsilon_{t}$ and $\tau_{t}$ are the error terms and we must have $\text{Cov}(\epsilon,\tau) = 0$ (I believe variances are unknown).
Basically, I have to estimate the values $\kappa$, $\beta$, $\Phi$, $\alpha$, $\sigma (z_{t})$ and $\sigma (w_{t})$
To do this I'd like to change it into a state space model form but these four equations seem quite a bit more difficult to change compared to the examples online which show it for AR/MA/ARMA processes, and since I'd also like to put the model into R to use a Kalman filter over I want to try and make sure everything is properly formatted since the packages tend to vary in how they want matrices formatted, so if anyone can help me out with it I'd appreciate it, thanks in advance.
Answer: The thing that's perhaps tricky here is the fact that there is no measurement error. Conditional on the unobserved states $x_t$ and $z_t$, the measurement equation is deterministic.
Anyway, I would start by substituting the third equation into the second. Then you have:
\begin{align}
y_t &= x_t + z_t\\
x_t &= x_{t-1} + \kappa\beta_t+\epsilon_t\\
z_t &= \Phi z_{t-1}+\psi\alpha_t+\tau_t,
\end{align}
which makes it easier to see how to proceed. From here it's just housekeeping. Define the following
\begin{align}
\mathbf{s}_t &= \begin{bmatrix}x_t & z_t\end{bmatrix}'\\
\boldsymbol{\mu}_t &= \begin{bmatrix}\beta_t & \alpha_t\end{bmatrix}'\\
\boldsymbol{\nu}_t &= \begin{bmatrix}\epsilon_t & \tau_t\end{bmatrix}'.
\end{align}
With these, you can rewrite the system as
\begin{align}
y_t&=\begin{bmatrix}1 & 1\end{bmatrix}\mathbf{s}_t\\
\mathbf{s}_t &=\begin{bmatrix}1 & 0 \\ 0 & \Phi\end{bmatrix}\mathbf{s}_{t-1} + \begin{bmatrix}\kappa & 0\\0&\psi\end{bmatrix}\boldsymbol{\mu}_t+\boldsymbol{\nu}_t.
\end{align}
This is a linear system with no errors in the measurement equation (you could think of $y_t$ as having an error term with 0 variance if you like), and the state transition equation has a known time-varying intercept (since you said you know $\beta_t$ and $\alpha_t$).
Comment: Sorry for getting back to you so late, thanks, I appreciate it!

State Space Model Form for Equations


how to convert string dict to dictonary in python

Question: a= {'Locator__creation_date': {'start': datetime.date(2013, 11, 14), 'end': datetime.date(2013, 11, 14)}, 'Locator__employed': u'True', 'Locator__employer_state': u'AL', 'Locator__receiving_hiv_treatment': u'True', 'Locator__hiv_treatment_state': u'AR', 'Locator__mental_health_provider': u'False', 'Locator__parole': u'True', 'Locator__parole_state': u'IA', 'data_model_name': ['Locator']}

ast.literal_eval(a)

it gives
ValueError: malformed string

Comment: You are passing in a *Python object*, not a string.
Comment: You also have `datetime` objects in there, those won't work with `ast.literal_eval()`.
Answer: Presumably you meant a to be a string:
a = "{'Locator__creation_date': {'start': datetime.date(2013, 11, 14), 'end': datetime.date(2013, 11, 14)}, 'Locator__employed': u'True', 'Locator__employer_state': u'AL', 'Locator__receiving_hiv_treatment': u'True', 'Locator__hiv_treatment_state': u'AR', 'Locator__mental_health_provider': u'False', 'Locator__parole': u'True', 'Locator__parole_state': u'IA', 'data_model_name': ['Locator']}"

This won't work because datetime.date(...) is not a Python literal. It is a representation of a Python datetime.date() object, and ast.literal_eval() does not handle arbitrary types.
Only Python literal values ({...} for dictionaries or sets, [...] for lists, (...) for tuples, digits to numbers and string literals such as u'...' and r'...' and '...' with the various quote variations) are handled. See the Literals section of the Python expressions documentation and the ast.literal_eval() documentation itself:

The string or node provided may only consist of the following Python literal structures: strings, numbers, tuples, lists, dicts, booleans, and None.


Change the div content according to link selection

Question: Here I have listed my div details.I want to know how to change the content of main div by using the link and load the child div in the main div.
link 1 : link 2: link 3 :link 4

diplay1

diplay2

diplay3

diplay4

Please advice me.
Comment: They already seem to be in the `main div`. Are you looking for something like `hide/show` ?
Comment: Have you tried any code? This is possible with JS or Jquery...
Comment: What do you mean by _change the content of main div by using the link_?
Comment: @DKM I want to display only one child div in the main Div based upon the link selection.I want to hide other div' hide
Comment: Have you heard of the [jQuery UI Tabs plugin](http://jqueryui.com/tabs/) and does it possibly accomplish what you need?
Answer: Using this format

diplay1

diplay2

diplay3

diplay4
ok

  1
  2
  3
  4

Then with a small script
$('.link').click(function(){
   $('#main > div').hide().eq($(this).index()).show();
});

Fiddle Example
Comment: @captain  `$('#main div').hide()` will select and hide all the `divs` inside `#main`. `eq()` is a jQuery selector that selects the element from a specific `index`. Since the `a` and the `#main divs` have the same index it is easier to select the div from main with the same index
Comment: Can you please explain me a little of these code $('#main div').hide().eq($(this).index()).show(); ?
Comment: It will also hide all the children divs if there is a hierarchy, which may also mess up with the index. `#main > div` direct children selector will be better option.
Answer: Working Fiddle!!!
$('#main a').click(function() {
    $('div:not(#main)').hide();
    $($(this).attr('href')).show();
    return false;
});

Answer: You will need to use JS / JQuery , CSS and classes to achieve that.
HTML with classes, href, and custom attribute.
Link1
Link2
Link3

diplay1

diplay2

diplay3

JQuery code
$('a.linked').on('click', function(e){
    $('div.' + $(this).attr('data-link')).show().siblings().hide();
    /* this will select and show div with class
       which is in the custom attribute data-link of the clicked link.
       Then it will select all of its sibling elements
       i.e. all within this parent and no children if any
       except the first selected div and will hide them. */
});

CSS styles
#main *{
    display:none;
}

Example Fiddle


ERROR: serverlessrepo 0.1.8 has requirement pyyaml~=3.12

Question: Below is the docker file with base image python 3.7:
FROM python:3.7-alpine3.9

ENV HOME /home/someteam
ENV PATH $HOME/.local/bin:$PATH
RUN ln -fs /usr/share/zoneinfo/Etc/UTC /etc/localtime
RUN apk add --no-cache --virtual .build-deps python2-dev  python3-dev gcc linux-headers musl-dev && \
    addgroup someteam --gid=5566; \
    adduser -G someteam -Du 5566 -h /home/someteam -s /bin/bash someteam; \
    chown -R someteam $HOME;
RUN apk add --no-cache groff less bash jq curl py-pip tzdata
USER someteam

WORKDIR $HOME

RUN pip install --user --upgrade awscli aws-sam-cli;
USER root

RUN apk del .build-deps; \
    rm -rf /var/cache/apk/*

USER someteam
WORKDIR $HOME

ADD somescript.sh $HOME/somescript.sh

gives error:
ERROR: serverlessrepo 0.1.8 has requirement pyyaml~=3.12, but you'll have pyyaml 5.1 which is incompatible.
ERROR: aws-sam-cli 0.18.0 has requirement PyYAML~=3.12, but you'll have pyyaml 5.1 which is incompatible.

How to install pyyaml 3.12? with python 3.6 or python 3.7 base image
Answer: after this pull request is released, serverlessrepo should be on 5.1. According to the PR, SAM CLI will be upgraded to 5.1 soon.
Comment: Can you share the repo name? let me check the PR... which branch is the PR raised?
Answer: You need to install PyYAML==3.12 for your aws-sam-cli
as you Docker image come with pyyaml 5.1 by default which have compatibility issue with aws-sam-cli. All you need to install pyyaml 3.12 before installation of aws-sam-cli
RUN pip install PyYAML==3.12
USER someteam
WORKDIR $HOME
RUN pip install --user --upgrade awscli aws-sam-cli;
USER root

Comment: ENV will just create environment variable


Correct way to render entity fields?

Question: According to Rendering Drupal 7 fields (the right way), the correct way to render fields is with code similar to the following one.
$node = node_load($nid);
$field = field_get_items('node', $node, 'field_name');
$output = field_view_value('node', $node, 'field_name', $field[$delta]);

This is for rendering node fields.
I am using the Paragraphs module which lets you create custom bundles in the predefined "paragraph" entity. I could use entity.tpl.php to override the output of Paragraph module fields.
I want to print my fields that are stored in the entity, but the above code won't work because it is for nodes.
What is the code for a generic entity's field?
Answer: The equivalent to the sample code you posted from the article, but for an entity type other than node would be the following one.
$entities = entity_load('ENTITY_TYPE_NAME', array($YOUR_ENTITY_ID));
$entity = $entities[$YOUR_ENTITY_ID];
$field = field_get_items('ENTITY_TYPE_NAME', $entity, 'field_name');
$output = field_view_value('ENTITY_TYPE_NAME', $entity, 'field_name', $field[$delta]);

If you're doing this in a template, the entity fields should have already been retrieved by template_preprocess_entity() and made available under the $content variable, so you shouldn't have to do all these steps in an overridden entity template.
Comment: Is there any way to use `$content` to just print the actual value of the field, as at the moment, it prints out the mark up and label. I know that I can make extra field templates to get rid of the mark up (and remove the label from the Druapl UI), but I'd rather just access the content of the field.
Comment: You ought to be able to access the entity via `$content['field_name']['#object']`, then use that with the last 2 lines of the above sample code to extract your $output value.
Answer: There is a function for that: field_attach_view().
I had to use it to get a renderable array from Paragraph entities. You can render this array with render().
$paragraphEntity = entity_load("paragraphs_item",array($paragraph['value']));
$renderableParagraphBundle = field_attach_view(
  "paragraphs_item",
  $paragraphEntity[$paragraph['value']], "full",
  $GLOBALS['language']->language,
  array()
);

print render($renderableParagraphBundle);

Correct way to render entity fields?


How can I display textarea client input on website without changing URL?

Question: I am attempting to implement a feature on my website, where a user can input a comment into a textarea and have it display the comment, below the comment box. For backend I am using bottle. At the moment, bottle is recognizing the input, and when input is submitted, a new url loads displaying only the input of the textarea.
When submitted, I need the textarea input to be displayed below the textarea box, without changing the webpage.
Here is HTML textarea input

    Add a comment

  <form action="/comment" method="post">
  <textarea name="text"></textarea>
  <input type="submit" value="Submit">
  </form>

Bottle in main.py
@route('/comment', method = 'POST')
def submit():
  com = request.forms.get('text')
  print('Printing comment...')
  print(com)
  return com

index.js, (i'm not sure how to integrate this function)
function loadCom () {

  var xhttp2 = new XMLHttpRequest();
    xhttp2.onreadystatechange = function(){
        if (this.readyState === 4 && this.status === 200){
            console.log(this.response);

            document.getElementById("dcom").innerHTML = this.response;
        }
    };

  xhttp2.open("GET", "/comment");
  xhttp2.send();

  return false
}

Answer: Call loadCom() from an event listener.
document.querySelector("form").addEventListener("submit", e => {
    e.preventDefault(); // prevent reloading the page
    loadCom();
});

loadCom() needs to use the POST method to send the value of the textarea to the controller.
function loadCom () {

  var xhttp2 = new XMLHttpRequest();
    xhttp2.onreadystatechange = function(){
        if (this.readyState === 4 && this.status === 200){
            console.log(this.response);

            document.getElementById("dcom").innerHTML = this.response;
        }
    };

  xhttp2.open("POST", "/comment");
  xhttp2.send('text=' + encodeURIComponent(document.querySelector('[name="text"]').value);

  return false
}

Comment: Bottle still seems to be re-directing me to different url. Here is a link to the replit for furthur insight. https://replit.com/@JohnTully/Bitl-Projectno2?v=1


What are some good calculus resources relevant for Machine learning researcher aspirant?

Question: I am trying to self-taught myself on Calculus for machine learning and read the book by Spivak. But it is too rigorous and need a lot of time to finish it.
As far as I am concerned, Calculus is only used for optimization in machine learning.
I am seeking some good calculus resources especially apt for machine learning research but less rigorous than Spivak.
Edited: After some research, I plan on going through MIT OpenCourseWare on single, multivariable calculus and differential equations. What book should I read to study calculus along watching these lectures?
Comment: Close-voters: we have a [tag:references] tag, and questions on references are specifically on-topic. I will add the tag and vote to keep this question open.
Comment: @User1865345: seriously? Especially in a community full of non-native speakers, this feels like unnecessary nitpicking to me. If OP asked for just *any* reference, that would be OK?
Comment: A "hack" text for this would be the Schaum's outline series. These can be bought used for pennies at used book stores or online. It's nothing but definitions and worked problems, the ultimate slacker's guide. They are also available for differential equations and linear algebra assuming you're looking for the pressure cooker solution to my outline here: https://stats.stackexchange.com/questions/609570/what-is-the-roadmap-to-self-taught-probability-and-statistics-for-artificial-int
Comment: Hm. I agree @StephanKolassa with this. Rewording can change a lot. So I would vote to reopen once it is reframed to a reference post.
Comment: @User1865345 I disagree, this might be a question for meta. My understanding is that if a new user has a closed question and there's an obvious edit that doesn't ruin the spirit of the ask but makes the question on-topic - on this point I agree with Stephan - you should edit the question to an acceptable format.
Comment: I think this is off-topic because calculus is a fundamental tool. I wager no one has "specialized" calculus for machine learning. But if you search "calculus reference" on math.stackexchange.com, you get literally hundreds of useful posts https://math.stackexchange.com/search?q=calculus+reference
Comment: @StephanKolassa, while references are certainly on-topic, asking for the "best" source, I deem, is opinion-based.
Comment: @User1865345 you could WLOG edit the question, presumably the votes will help determine the best, to ask for any reference and vote to reopen, although I would still say to close it.
Comment: @AdamO, this should  come from the author. I can edit one thing or other but a substantial change should come from the original poster.
Comment: Very well @AdamO.
Comment: To the original poster, I have edited the way I feel the question should be. Feel free to change accordingly if necessary.
Answer: It's not a book and not addressing optimization, but one of the best resources to self-learn calculus are the lectures by Gilbert Strang that were recorded and are available on YouTube. He also wrote a great handbook.
If you would find Strang a little bit too hard, I'll recommend starting with the Khan Academy lectures.
Comment: Strang is a national treasure.
Comment: I followed his linear algebra classes religiously; the calculus would also be definitely worth it.


Validate date strings in Ruby with multiple accepted formats?

Question: I have some strings that might or might not be dates like:
"Hello World", "Sept 12, 2013", "Hello World Sept 12"

In this case, I'd like only the second one to be considered a proper date.
So far, I have been using Date.parse and the Chronic gem but they very lenient and convert strings like "a a" or "12-UNKN/34/OWN1" into acceptable dates.
For example:
Date.parse '12-UNKN/34/OWN1'

would return:
 Tue, 12 Nov 2013

So, I am trying to restrict the accepted formats to a set of formats I can control:
09/12/2013
9/12/2013
9/12/13
09-12-2013
9-12-2013
9-12-13

and some formats with text inside like:
Sept 9, 2013 - with or without the coma, accepting Sep, Sept or September and with or without a dot after the month name, covering things like:
Sept. 9, 2013
Sept 09, 2013
Sept. 09, 2013
September 9, 2013
September 09, 2013

Any suggestion on a good way to do this in Ruby, either pure Ruby or with Rails?
Comment: Just use `validates_format_of` with a regex that handles all the date types that you want before passing them to Chronic.
Comment: Humor me...  Why so many accepted formats?  Wouldn't it be easier to allow only one format?
Comment: For example when I don't control the given text, e.g the text comes from a title written by a user like "Going there on Nov. 2, 2013" or "Who will be there on 03/12/2014?".
Comment: @GrahamConzett answer is correct - just absent of the elaboration you need to do regarding acceptable date formats.  If you want your porridge to be *just right* then only you can know what it will be
Comment: Agree with both of the previous two comments... As I think through this, given your examples, what if some enters September 2nd as dd-mm-yyyy...  How will you know if they mean September 2nd or February 9th?
Comment: I am not aware than you can use the regular date formatting helpers like %m, %B, etc... in validates_format_of. Will check this out.
"September 2nd" without a year would fail the validation. I wouldn't support both mm/dd/yyyy and dd/mm/yyyy but only mm/dd/yyyy.
Answer: I'll take a stab at this and elaborate on my comment. Separating the date from the other string allows you to validate the date in multiple formats before handing it off to Chronic:
validates_format_of :date, with: /\d{2,4}[-/]\d{1,2}[-/]\d{1,4}/, on: :create
That should handle most of the date formats you described.
However, a big issue is you won't know if someone is submitting a date in the US format or non-US format.
The bigger issue is know what part of the title string is in fact a date, and that would either be a more complicated regular expression, or make it easy on yourself and make it a separate field. You're getting somewhat close to trying to parse natural language which isn't cut and dry by any means.
Comment: I played with this a bit and it will cover nicely the dates with only digits. The harder cases are the months that need to cover the different like "Sept. 09, 2012" or "Sep 09, 2012". That's why I was looking into a solution where I could leverage the existing ruby Date utilities.
Answer: Try something like this
validate :validate_some_date

private

def validate_some_date
  errors.add("Created at date", "is invalid.") unless [
      date_case_one,
      date_case_two,
      date_case_three
    ].all?
end

def date_case_one
  # some regex
end

def date_case_two
  # some regex
end

def date_case_three
  # some regex
end


Scrapy output one CSV file per start url

Question: I would like to output 1 CSV file for each start_url. I made a pipeline that outputs only 1 file with information from all the urls but can't figure out how to output multiple.
pipeline.py
class CSVPipeline(object):

def __init__(self):
    self.files = {}

@classmethod
def from_crawler(cls, crawler):
    pipeline = cls()
    crawler.signals.connect(pipeline.spider_opened, signals.spider_opened)
    crawler.signals.connect(pipeline.spider_closed, signals.spider_closed)
    return pipeline

def spider_opened(self, spider):
    file = open('%s_items.csv' % spider.name, 'w+b')
    self.files[spider] = file
    self.exporter = CsvItemExporter(file)
    self.exporter.fields_to_export = ['date', 'move', 'bank', 'call', 'price']
    self.exporter.start_exporting()

def spider_closed(self, spider):
    self.exporter.finish_exporting()
    file = self.files.pop(spider)
    file.close()

    print('Starting csv blank line cleaning')
    with open('%s_items.csv' % spider.name, 'r') as f:
        reader = csv.reader(f)
        original_list = list(reader)
        cleaned_list = list(filter(None,original_list))

    with open('%s_items_cleaned.csv' % spider.name, 'w', newline='') as output_file:
        wr = csv.writer(output_file, dialect='excel')
        for data in cleaned_list:
            wr.writerow(data)

def process_item(self, item, spider):
    self.exporter.export_item(item)
    return item

class SentimentPipeline(object):
    def process_item(self, item, spider):
        return item

I've been running:
scrapy crawl spider -o spider.csv

Do I need a new command?
Very new to scrapy. Thanks!
Comment: Have you seen https://stackoverflow.com/q/48122080/939364?
Comment: That page is for pulling urls. I'm trying to export a CSV file each time a start_url is crawled. One spider crawl should yield one file for each url in the start_url list.
Comment: Check my answer below, should work for you.
Answer: You need to create a CSV Item Pipeline like the one below in the pipelines.py file
class PerUrlCsvExportPipeline:

def open_spider(self, spider):
    self.url_to_exporter = {}

def close_spider(self, spider):
    for exporter in self.url_to_exporter.values():
        exporter.finish_exporting()

def _exporter_for_item(self, item):
    url = item['url']
    if url not in self.url_to_exporter:
        f = open('{}.csv'.format(your_file_name), 'wb')
        exporter = CsvItemExporter(f)
        exporter.start_exporting()
        self.url_to_exporter[url] = exporter
    return self.url_to_exporter[url]

def process_item(self, item, spider):
    exporter = self._exporter_for_item(item)
    exporter.export_item(item)
    return item

Then add the pipeline to your settings.py file:
    ITEM_PIPELINES = {
        'your_project_name.pipelines.PerUrlCsvExportPipeline': 300,
    }


Rails how to select attributes

Question: In my controller I have:
def search
  @kategoris = Kampagner.where("titel like ?", "%#{params[:q]}%")
  @kate = []
  @kategoris.each do |kat|
    h = {}
    kat.attributes.each{|k,v| h[k] = v.respond_to?(:force_encoding) ? v.dup.force_encoding("UTF-8") : v }
    @kate << h
  end
  respond_to do |format|
  format.html
  format.json { render :json => @kate }
  end
end

But the problem is just that all of the attributes for the model are in the JSON data. I only what the attributes ID and title to be in the JSON data. How do I select this?
Comment: you use each when you should be using map (and do it in the controller when you should do it in the model)
Answer: I'd do:
@kategoris.each do |kat|
  @kate << kat.sanitized_whitelist
end

In model:
WHITE_LIST_ATTRS = [:id, :title]

def whitelist
  WHITE_LIST_ATTRS.each_with_object({}) {|attr, hash| hash[attr] = send(attr) }
end

or consider some dedicated method:
def sanitized_whitelist
  WHITE_LIST_ATTRS.each_with_object({}) {|attr,hash| hash[attr] = send(attr).respond_to?(:force_encoding) ? send(attr).dup.force_encoding("UTF-8") : send(attr) }
end

Comment: just replaced the code with your´s and the now the json data is just empty: [{}]
Comment: I have also added the whitelist to my model. And just added     kat.whitelist but then again it is empty..
Comment: Still the json data is empty. I tried the to_json method replacing and it worked.
Comment: I don' know if you force encoding using to_json, updated the answer btw
Comment: whitelisting is simpler using active_support: `hash.slice(*keys)`
Answer: I'm not very clear why you want to use force_encoding. But you can simply just call:
format.json { render :json => @kategoris }

Rails will call the method as_json behind the scene. Then in the Kampagner class you can customize the as_json class to control what will be exposed when the record was exported to JSON:
class Kampagner
  def as_json(options={})
    super(options.merge({ :only => [:id, :title]})
  end
end

See more: http://api.rubyonrails.org/classes/ActiveModel/Serializers/JSON.html
Comment: What if you have to render multiple JSON data for this same model but with other attributes what is the best solution for that?
Comment: Then I just use the only option :)
Comment: It's a good question. As I know, there is no best way for this, because it depends on what you want to export JSON for. You can write multiple export JSON methods inside the model class. Or customize the as_json with switch..case statement. Then just change the params passed to the to_json or as_json method. More thoughts?
Comment: user.as_json(:only => [ :id, :name ])]

Rails how to select attributes


Vanishing of Taylor series coefficient

Question: I am solving previous year question paper some competitive exam. Give me some hint to solve the following problem.
Let $f$ be an entire function. Suppose for each $a \in \mathbb{R} $ there exists at least one coefficient $c_n$ in $f(z) = \sum_{n=0}^{\infty} c_n (z-a)^n$ which is zero. Then,
a) $f^{(n)}(0) = 0$ for infinitely many $n \ge 0$
b) $f^{(2n)}(0)=0$ $ \forall n \ge 0$
c) $f^{(2n+1)}(0)=0$  $ \forall n \ge 0$
d) $f^{(n)}(0) = 0$ for all sufficiently large n.
Thanks in advance.
Answer: $f$ is a polynomial and d) is correct.
If $f$ is not a polynomial, then  $f^{(n)}$ is a non constant entire function for all $n$. The set of zeros of $f^{(n)}$ is discrete, and in particular, countable. Thus,
$$
Z=\{z\in\mathbb{C}:f^{(n)}(z)=0\text{ for some }n\}
$$
is countable. But $\mathbb{R}\subset Z$, a contradiction.
Comment: Thanks . nice answer. if d is correct then a is also correct no sir. so answer is a and d.

Vanishing of Taylor series coefficient


Security Certificate

Question: I have the "logwatch" service turned on and I expect to get a mail everyday.
Today's mail titled "Logwatch for servername (Linux)" has the following section...
 --------------------- up2date Begin ------------------------

 **Unmatched Entries**
 The certificate is expired. Please ensure you have the correct certificate and your system time is correct.

I checked and my system time is correct. What is this certificate that has been referred to?
I am using CentOS.
Answer: A quick google search turned up a Wikipedia page for up2date.
Two things stand out:

up2date is no longer shipped with the distribution; yum is used instead.

It sounds like up2date is very, very out of date. You may want to look at upgrading your OS or transitioning to yum.
Second,

CentOS's up2date downloads packages from yum repositories on the CentOS Mirror Network

I'd have to guess one of the servers it tried to download an updated package list from had an expired SSL certificate.

Security Certificate


How to log all outgoing links generated in a view?

Question: What is the most lightweight method of tracking all outgoing links generated in a view. By lightweight I mean that I don't want to have to load a module such as statistics that will potentially slow down my site due to it going above and beyond my needs.
Basically I would need to record the data into a database using the following structure:
product_id | uid | timestamp

The product id is associated with each link and is a separate field. The purpose would be to create sets of clicked links for each user, product, etc. This could in turn be used as a dataset for subsequent user/item analysis. I would imagine I would need to use some sort of callback function.
Can anyone provide an example or any hints?
Comment: Timestamp of what, exactly? And why do you have to log Views results? Views queries I can understand, but results? And please, try to rewrite this in a non-opinion-based way. Currently it heavily depends on your definition of "lightweight".
Comment: By timestamp I mean the time that the link was clicked. It doesn't have to be exact, so for that I can simply use the database insert time. The need for the product id - uid relationships is for developing recommendation engines.
Comment: Oh, so you want to count *clicked* links, not *generated* ones. That explains a bit. Could you please [update your question](http://drupal.stackexchange.com/posts/111185/edit)?
Comment: are you opposed to using google analytics event tracking? It is ideally suited for capturing the information you describe, and is done via javascript.
Comment: I would prefer a different method.
Comment: _the most lightweight method_ is rather subjective. In which terms do you define _lightweight_ a method? Also, this question is too broad: We cannot list all the possible methods hoping to find the one you think most lightweight.
Answer: You could use jQuery to attach a click event to each link that triggers an ajax request to record the click.
The problem with this is that the page may redirect before the ajax request has had a chance to fire so you will have to prevent the default action of the click, and then perform an ajax request with async=false, and then provide a call back function to redirect to the links destination.
Not exactly lightweight...
Another option is to define an outbound link function in PHP that will accept the final destination as a argument. So the link would look like /outbound?dest=http%3A%2F%2Fwww.google.com.
Then in that function you can record the click, and then redirect them on to the destination passed in...
Comment: The second option sounds like a good option. Is there any reason why the second one would not be ideal?
Comment: I've actually used the second option before and it worked fine. I guess I feel that because Google analytics is designed specifically for doing this stuff that it will work better than my solution, so for me to call my solution "ideal" I have to be more intelligent than all the programming bods at Google, so I'm reluctant to make that claim...


Football equipment that can reduce risk of concussions

Question: Concussions are becoming a major long-term health concern for participants in American football, particularly among youth and high school leagues, where equipment might not be as up to date as those found in the professional or college levels. I've come across articles that state that certain mouthguards and newer helmets might reduce the risk, but haven't seen any definitive studies that prove that a particular piece of equipment or fitting "works."
Is there any list of equipment (and any associated fitting/practices) that is proven to help football players avoid concussions?
Comment: The next two steps which we will probably see added are a softer outer "add on" device on the outside of helmets. Both to reduce collision impact and to make the helmet less of a weapon. And "smart" helmets which will be able to revord impact information and communicate with a sideline sensor wirelessly. The concussion "problem" in football is overrated statistically, but something we do have a problem with is no helmet yet can stop a twisting side to side motion which causes the most serious concussions.
Answer: There was a study at Virginia Tech that was geared to find the "top 10" helmets for concussion safety. I've no idea of the exact results of the research (nor do I know where to find them) but I do know of:
The top ten helmets for preventing concussions, according to Virginia Tech
Answer: While this is probably not a feasible solution for you to actually implement due to any league rules that you may be playing with, the safest solution could be to remove helmets from the game altogether.
For a different take on the issue, the Wall Street Journal had an article in 2009 that brought up the possibility that the presence of the helmet in football is a major contributor to concussions in the first place and removing the helmet altogether could help reduce the number of concussions in the sport.
The article notes that a similarly rough sport, Australian Rules Football, that no helmets are used and the probability of getting a concussion in the NFL is 25% higher than in the AFL (Australian Football League). The reasons for this are that players in the NFL often feel like the helmet makes them "invincible" and they tend to turn their bodies into projectiles, using their head as a weapon.
Also, it seems that recent studies done on players has shown that long-term brain damage is not caused by big hits to the head, but by the accumulation of thousands of smaller hits which no helmet could ever prevent. Currently the organization that rates helmet safety, NOCSAE must give a helmet a "severity index" of 1200 or less for the helmet to be eligible to be sold. It is speculated that to prevent the risk of concussion, a helmet would have to have a rating of 300 or less.
So, in effect, current football helmets would have to be four times safer than they currently are in order to prevent concussions. There are no efforts being made currently to ban football helmets at any level of American Football.


Conditional probability of correlated gaussians

Question: Let $(X,Y)$ be a 2D Gaussian, with non-zero correlation. Let $I$ be an interval centered around the mean of $X$, and $J$ an interval centered around the mean of $Y$. I want to show
$$
P(X \in I | Y \in J) \geq  P(X \in I),
$$
i.e. that the conditional probability is greater than or equal to the unconditional one.
I am sure this is true thanks to simulation, but I cannot find a proof of this result. It feels very natural that, for two correlated gaussians, knowing that one is closer to its mean implies that the probability that the other is also closer to its mean is higher. I tried using the conditional density of $X | Y=a$ and integrating over $a$, but I couldn't find a minoration.
Answer: I'm going to switch your variables in the statement so that the discussion uses them in a more conventional sense of studying $Y$ conditional on the values of $X$.  So, the objective is to show that
$$\Pr(Y\in J\mid X\in I) \ge \Pr(Y\in J).\tag{1}$$
Think of this in terms of regression:

We will exploit the fact that the distribution of $Y$ conditional on $X=x$ is a standard distribution $F$ (in this case Normal with mean zero and some given variance $\sigma^2$) whose location has been shifted to $f(x)$ for some function $f$ (the regression function).  By letting $J-f(x)$ stand for all values $y-f(x)$ where $y\in J$,this means $$\Pr(Y\in J\mid X=x) = {\Pr}(Y-f(x)\in J-f(x)\mid X=x)=\int_{J-f(x)} \mathrm{d}F(y).\tag{2}$$
Let's suppose that intervals  centered around $0$ are maximum-probability intervals for $F$: among all intervals of the same width, these have the largest probability.  That's clearly the case for symmetric unimodal distributions like the Normal.  This can be written $$\int_J \mathrm{d}F(y) \ge \int_{J-a} \mathrm{d}F(y)\tag{3}$$ for any number $a$.

Assume $\Pr(X\in I) \gt 0$. (The other case is trivial to prove).  This allows us to write
$$\Pr(Y\in J\mid X\in I) = \frac{\Pr(Y\in J\text{ and } X\in I)}{\Pr(X\in I)}.\tag{4}$$
Now, letting $G$ stand for the distribution of $X$, we can compare the two sides of $(1)$ by means of $(2)$, applying $(3)$ with $a=f(x)$, and simplifying the resulting double integral:
$$\eqalign{
\Pr(Y\in J\text{ and } X\in I) &= \int_I \Pr(Y\in J\mid X=x) \mathrm{d}G(x) \\
&=\int_I\int_{J-f(x)}\mathrm{d}F(y)\ \mathrm{d}G(x) \\
&\le \int_I\int_J \mathrm{d}F(y)\mathrm{d}G(x) \\
&= \int_J \mathrm{d}F(y) \int_I\mathrm{d}G(x) \\
&=\Pr(Y\in J)\Pr(X\in I).
}$$
In light of $(4)$, dividing both sides by $\Pr(X\in I)$ produces $(1)$, QED.
Answer: You want to prove that for any $x^\star \geq 0$ and $y^\star \geq 0$
we have $$ \text{Pr}\{ |X| \leq x^\star,\, |Y| \leq y^\star \} \geq
\text{Pr}\{ |X| \leq x^\star\} \text{Pr}\{ |Y| \leq y^\star \} $$
which is a famous result known as Sidak inequality. It holds for an
arbitrary centered elliptically contoured bivariate distribution,
including the Gaussian.
For a quite general formulation, see this paper by das
Gupta et al.
where more useful results are given.
Answer: Your desired result is a special case of the recently-proven Gaussian correlation inequality.
This may seem like overkill (and as the other answers demonstrate, it is), but the proof of the more general result is relatively short and available on the arXiv.


How to prevent over-installation of software

Question: I have a software product installed on multiple machines at a client's site.  The software accesses a database which is located on a server.
I have given them an MSI so that they can install the software on further machines if required.
How can I programmatically place a limit on the number of machines the software can be installed on?
The software previously placed a value in a HKLM registry key, but Vista and Win 7 doesn't allow the HKLM key to be written to anymore, so how am I meant to monitor installations now?
Comment: How do you know if the software is installed? What if they reimage a hard drive, or uninstall it from a computer or two, or clone a virtual disk with your program on it? Does it just count when the program "phones home" accessing the db on a server? Can you have multiple dbs, some clients using one, some clients using another?  These are the kinds of questions that first come to mind when you speak about the problem of tracking software.
Comment: @JohnK: When the app starts it will check an HKLM registry key for a workstation ID which if not found will be allocated. A list of these workstation IDs is stored on the database.  If the list is already at a defined limit then no further workstation IDs will be allocated.
Comment: @JohnK: but Vista and Win 7 do not allow apps to write to the HKLM registry key, so the current mechanism needs to be re-written, but how?
Answer: There are products like Symantec client management suite and server management suite which would let you do the software license management of all your software over the network. See here. Although, I'm afraid, they're enterprise products and might cost that way. I've actually worked on developing both of them.
Answer: You likely should make your legacy app UAC aware (e.g. Microsoft instruction for application developers on Vista, a Code Project tutorial) and request special privileges for it, to continue to use HKLM or equivalent. Once your program has the proper privileges (e.g. administrator) it should be able to continue functioning in the UAC environment as it did in legacy Windows.
One side effect is a non-administrator would not be able to properly install your program, but this is not unusual in the "new world" of Window Vista, 7, and everything going forward. It looks like the "everybody is an administrator" philosophy is not coming back.
(Note: I use the term "administrator privilege" but mean whatever is the least privilege you will need to get the job done).
Likely it will require a bit of work, when I see caveats like this in quotes:

Elevation procedures surrounding
  installers are a bit too complex to go
  into detail here, however be warned
  that the requiresAdministrator flag on
  an MSI package does not actually
  provide full administrator
  permissions. This actually behaves
  slightly differently and runs as a
  subset of the full privileges unless
  you use a bootstrapper to gain full
  elevation. It is rare that installers
  would require these additional tokens
  as the installer's administrator
  permissions are generally sufficient.

The benefit is once you've converted one app, you will have the knowledge and code base to upgrade other programs accordingly.
I'm sure other people will suggest code workarounds which are satisfactory and likely won't use HKLM.


Preciso retornar os valores null deste inner join

Question: Tenho este select do MySQL:
SELECT credor.nome, banco.descricao FROM credor
INNER JOIN banco ON (credor.banco = banco.codigo)

Ele me retorna todos os credores e seu respectivo banco, mas se o banco do cara é NULL ele simplesmente não me retorna o registro.
Como posso fazer para retornar o registro, mas na descrição ficar NULL?
Answer: O que o INNER JOIN faz é justamente eliminar os NULLs. Ele só estabelece relacionamento quando não houver NULL em nenhuma das pontas.
O que você está querendo é feito com LEFT JOIN:
SELECT credor.nome, banco.descricao FROM credor
LEFT JOIN banco ON (credor.banco = banco.codigo)

Aqui no site tem uma excelente explicação sobre os tipos de JOIN: Qual é a diferença entre INNER JOIN e OUTER JOIN?
Answer: Tenta fazer da seguinte forma abaixo que ira retornar os valores NULL:
SELECT credor.nome, banco.descricao FROM credor
  INNER JOIN banco ON (
    if(credor.banco is null, 0, credor.banco) = if(banco.codigo is null, 0, banco.codigo)
  )


Error: Call to undefined function drush_shift()

Question: We recently moved to Drupal 9.3.0 with a composer file layout and Drush 11.0.  We make use of Drush Scripts to execute website functions from Crontab.  One specific case is sending a newsletter email early each morning.
I receiving the subject error from a Drush Script that has been running for years.  The script is executed by moving into the webroot directory of the website and running drush scr email_script.php arg1 arg2. The first thing the Drush Script does is pull the arguments from the command line using drush_shift() but this function is not defined.  I'm not sure how to proceed in debugging this.
Comment: You probably don't need to debug anything, the function was deprecated and removed which is why your script can't use it. It's used to get command line arguments so you can refactor your scripts to use `\Drush::input()` or `$_SERVER['argv']` instead
Answer: drush_shift() has been deprecated and removed per @Clive -- Thanks!
In my case I changed:
$arg1 = drush_shift();
$arg2 = drush_shift();

to
$arg1 = $_SERVER['argv'][3];
$arg2 = $_SERVER['argv'][4];


views slideshow: display multiple items but scroll only one item at the time

Question: i'm using drupal 8 and slideshow module to create a block of slides (fields with images and descriptions to it) to put it on some pages.
I have managed to show slides horizontally and they scroll nicely but problem is how to show 4 slides and scroll only by one at the time.
In setting for slideshow there is an option "Items per slide" if i use it and put 4 - i will get 4 slides on an block but it will scroll 4 items at time.  If i put 1 - it will scroll one item at the time but will show only 1 slide and need 4.
plus to all that it should be responsive if only 3 slides can fit on the screen it should show 3 slides and scroll only one by one.
Answer: I'd suggest using the owl carousel module from Git hub for responsive slide shows.  It has lots of options to define how many slides based on breakpoints, support for mobile touch events, number of slides per next, and more.
We've been using it since 8.0 without a problem.  Note that despite the Readme, the author has released it under GLPv2.  See issue #4.
There is a cleaned up pull of this project as well.  I have not used this but it may be a slightly better alternative.
Just install the module as a manual module or you can add the git hub repo as a repository in your composer.json and install it via composer.  Once enabled, change your view format to Owl Carousel and then use the settings to define things.
Comment: owl carousel as far as i can tell is not stable for drupal8. and it is required Variable module which is not available for drupal8.
Comment: D'oh.. sorry, I thought this was the same as the module we've been using since 8.0... it's not.  Apparently this never made it off of Git hub.  Editing the answer with the Git Hub location.
Comment: CG Monroe,  I have tried it. it worked for me but one thing, there is no option to run carousel in circle (to loop the slideshow). there are new releases of owl carousel https://github.com/OwlCarousel2/OwlCarousel2 which in description says that there is loop option available... anyway now i have issues updating owl carousel, pls help.
Comment: Hmm, I am using v1.3 to do this.  There is an autoplay and rewind option in the view format settings that makes it run continuously.
Comment: I'm using jQuery OwlCarousel v1.3.3 but there is no option to run slides in loop. like in demo:  http://owlcarousel2.github.io/OwlCarousel2/


OnClickListener stops working after returning from another activity

Question: For some reason when I call startActivityForResult within a button listener, and return from the activity, all the buttons stop working thereafter. It goes through and exits onActivityResult just fine, and the app doesn't freeze since I can still click on the buttons although they don't do anything. When starting the app it works as it should. What am I missing here?
public class MainActivity extends Activity {

    static final int CAMERA_RESULT_CODE = 1;
    static final int INFO_RESULT_CODE = 2;
    static final int SYMPTOM_RESULT_CODE = 3;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

        // Set the user interface elements
        final Button btnCameraActivity = (Button) findViewById(R.id.btnCameraActivity);
        btnCameraActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, CropActivity.class);
                startActivityForResult(intent, CAMERA_RESULT_CODE);
            }
        });

        final Button btnAgeActivity = (Button) findViewById(R.id.btnAgeActivity);
        btnAgeActivity.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, AgeActivity.class);
                startActivityForResult(intent, INFO_RESULT_CODE);
            }
        });

        final Button btnSymptomActivity = (Button) findViewById(R.id.btnSymptomActivity);
        btnSymptomActivity.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, SymptomActivity.class);
                startActivityForResult(intent, SYMPTOM_RESULT_CODE);
            }
        });
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        setContentView(R.layout.activity_main);
        switch (requestCode) {
            case CAMERA_RESULT_CODE:
                if (resultCode == RESULT_OK) {
                    final CheckBox cb1 = (CheckBox) findViewById(R.id.cbCameraActivity);
                    cb1.setChecked(true);
                }
                break;
            case INFO_RESULT_CODE:
                if (resultCode == RESULT_OK) {
                    final CheckBox cb2 = (CheckBox) findViewById(R.id.cbAgeActivity);
                    cb2.setChecked(true);
                }
                break;
            case SYMPTOM_RESULT_CODE:
                if (resultCode == RESULT_OK) {
                    final CheckBox cb3 = (CheckBox) findViewById(R.id.cbSymptomActivity);
                    cb3.setChecked(true);
                }
                break;
        }
    }
}

Comment: Ahh thank you that was it. Put that as an answer so I can accept
Comment: Get rid of the `setContentView()` call in `onActivityResult()`. It's setting up the layout anew, with all new `Button` instances that don't have any listeners set on them.
Answer: The setContentView() call you have in onActivityResult() is replacing the layout you've setup in onCreate(), so those Button instances that you set the OnClickListeners on are gone.
Simply remove that call from the top of onActivityResult().
Answer: put this code in onResume method
    final Button btnCameraActivity = (Button) findViewById(R.id.btnCameraActivity);
    btnCameraActivity.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, CropActivity.class);
            startActivityForResult(intent, CAMERA_RESULT_CODE);
        }
    });

    final Button btnAgeActivity = (Button) findViewById(R.id.btnAgeActivity);
    btnAgeActivity.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, AgeActivity.class);
            startActivityForResult(intent, INFO_RESULT_CODE);
        }
    });

    final Button btnSymptomActivity = (Button) findViewById(R.id.btnSymptomActivity);
    btnSymptomActivity.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, SymptomActivity.class);
            startActivityForResult(intent, SYMPTOM_RESULT_CODE);
        }
    });

also this code can be generally simplified by extending youre class to View.OnClickListener


I need a module like Pageflip

Question: I need a stable Drupal module version like Pageflip. Can any one suggest the module which I am searching?
The existing Pageflip module is still a beta version; I need a module that has a stable release.
Comment: What do you mean approved ? No one approves any module on drupal , always use it at your own risk.
Comment: Beta5 is usually stable enough to use in production.
Answer: As kantu's comment suggests, there is no formal "approval" system for modules on drupal.org.  Instead, module maintainers decide when to release their modules and what version number to assign them.
As pageflip is a highly specialized module, I doubt that there is another module that has similar functionality (a quick search returned none).  However, since it is beta 5, it is probably stable enough to use in production, as Countzero pointed out.  The alternative would be to write a module yourself, but since the pageflip module is already far along in its development it would probably be best for everyone if you would extend and contribute back to the pageflip module (assuming you were going to write your own module).
How do you really know whether the module is ready for production?  First, look at the list of open reported bugs.  In this case there are only 3 for the 6.x series, so it shouldn't take you very long.  If these bugs don't affect you, the module is probably safe to install.

I need a module like Pageflip


Puppet unable to add user to AD group

Question: I'm trying to add user to group on my DC using puppet:
<code> dsc_xgroup {'DomainAdministrators':

            dsc_ensure    => 'present',
            dsc_memberstoinclude => 'email@example.com',
            dsc_groupname   => 'test',
            dsc_credential => {
            'user' => 'firstname.lastname@example.com',
            'password' => 'Passw0rd01'
            },
            }
</code>
Group is created, but unable to add user to it:
Error: PowerShell DSC resource MSFT_xGroupResource  failed to execute Set-
<code>TargetResource functionality with error message: Exception calling "Save" with "0" argument(s): "An unknown directory user object was requested
"
Error: /Stage[main]/Main/Node[windows.example.com]/Dsc_xgroup[DomainAdministrators]/ensure: change from 'absent' to 'present' failed: PowerShell DSC resource MSFT_xGroupResource  failed to execute Set-TargetResource functionality with error message: Exception calling "Save" with "0" argument(s): "An unknown directory user object was requested
</code>
Answer: Try rebooting windows server, i had similar issue and reboot solved it.

Puppet unable to add user to AD group


Remove key of JSON file

Question: I'm trying to delete a key from my JSON file but I don't know how "clicking delete" the php will know the key that it will delete.
(The PHP at start its for add a "link" and it works, the problem is that I don't know how to set the button "Delete" for remove a link) I just want remove ONE key for example {"name":"Google","url":"google.es"} not all array.
Thanks you.
JSON:
[{"name":"Google","url":"google.es"},{"name":"Google","url":"google.es"},{"name":"gfdhd","url":"gfdhfg"},{"name":"gfdhd","url":"gfdhfg"}]

HTML/PHP
<?php
//ADD Links
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    var_dump($_POST);

    $jsonContents = file_get_contents('js/json.json');
    $name = $_POST['addname'];
    $url = $_POST['addlink'];
    $data = json_decode($jsonContents, true);
    $data[] = array(
        'name' => $name,
        'url' => $url
    );
    $json = json_encode($data);
    file_put_contents('js/json.json', $json);
}
?>
<?php
//RemoveLinks
if ($_SERVER['REQUEST_METHOD'] === 'POST') {

    var_dump($_POST);

    $jsonContents = file_get_contents('js/json.json');
    $ename = $_POST['edit-name'];
    $datae = json_decode($jsonContents, true);
    $datae[] = array(
        'name' => $ename,
        'url' => $url
    );
    $json = json_encode($datae);
    file_put_contents('js/json.json', $json);
}
?>
<!DOCTYPE html>

    <title>SSL Checker</title>
    <link rel="stylesheet" type="text/css" href="css/style.css">

SSL Checker

        <form method="POST" onsubmit="SSL.Add()">
            <input type="text" name="addname" id="add-name" placeholder="Name" />
            <input type="text" name="addlink" id="add-link" placeholder="Link" />
            <input type="submit" value="Add" />
        </form>

            <form action="javascript:void(0);" method="POST" id="saveEdit">
                <input type="text" id="edit-name">
                <input type="submit" value="Edit" /> ✖
            </form>

                Sites:

JS:
function start() {
    var SSL = new function() {
        //List urls to check
        this.el = document.getElementById('urls');
        this.Count = function(data) {
            var el = document.getElementById('counter');
            var name = 'url';

            if (data) {
                if (data > 1) {
                    name = 'urls';
                }
                el.innerHTML = 'There are:' + ' ' + data + ' ' + name;
            } else {
                el.innerHTML = 'No ' + name;
            }
        };
        //Box/Table Configuration (Sites/edit/delete)
        this.FetchAll = function() {
            var data = '';

            if (Checker.length > 0) {
                for (i = 0; i < Checker.length; i++) {
                    data += '
';
                    data += '' + Checker[i].name + '	';
                    data += '<button onclick="SSL.Edit(' + i + ')">Edit</button>	';
                    data += '<button onclick="SSL.Delete(' + i + ')">Delete</button>	';
                    data += '
';

                }
            }

            this.Count(Checker.length);
            return this.el.innerHTML = data;
        };
        //Add name
        this.Add = function() {
            el = document.getElementById('add-name');
            el1 = document.getElementById('add-link')
            var url = el.value;
            var url1 = el1.value;
            if (url) {
                if (url) Checker.push({
                    "name": url,
                    "url": url1
                })

                this.FetchAll();
            }
        }

        //Edit
        this.Edit = function(item) {
            var el = document.getElementById('edit-name');
            var el1 = document.getElementById('edit-name1');
            el.value = Checker[item].name;
            el1.value = Checker[item].url;
            document.getElementById('edit').style.display = 'block';
            self = this;
            document.getElementById('saveEdit').onsubmit = function() {
                var url = el.value;
                var url1 = el1.value;
                if (url) {
                    Checker[item].url = url1.trim();
                    Checker[item].name = url.trim();
                    self.FetchAll();
                    CloseInput();
                }
            }
        };
        //Delete
        this.Delete = function(item) {
            Checker.splice(item, 1);
            this.FetchAll();
        };

    };

    SSL.FetchAll();
    //Close button (Edit bar)
    function CloseInput() {
        document.getElementById('edit').style.display = 'none';
    }
    window.CloseInput = CloseInput;
    window.SSL = SSL;
}

Comment: once its submitted, just read and oopen the json file again, convert it into an array, use a `foreach` loop to search using the input and unset the key once found, then convert to json again and write the file
Comment: When I have the key, how can I delete it?
Comment: just `unset` it using the key when all is in array form, once its done, json encode it again and save it
Comment: And how can I add this process to a button?
Answer: First decode your json value after decoded use unset for remove particular key like
    $json_val='[{"name":"Google","url":"google.es"},
    {"name":"Google","url":"google.es"},{"name":"gfdhd","url":"gfdhfg"},
    {"name":"gfdhd","url":"gfdhfg"}]';
    $data=json_decode($json_val);
    echo "
";
    print_r($data);
    unset($data[0]);
    print_r($data);

Output :
Array
(
    [0] => stdClass Object
        (
            [name] => Google
            [url] => google.es
        )

    [1] => stdClass Object
        (
            [name] => Google
            [url] => google.es
        )

    [2] => stdClass Object
        (
            [name] => gfdhd
            [url] => gfdhfg
        )

    [3] => stdClass Object
        (
            [name] => gfdhd
            [url] => gfdhfg
        )

)
Array
(
    [1] => stdClass Object
        (
            [name] => Google
            [url] => google.es
        )

    [2] => stdClass Object
        (
            [name] => gfdhd
            [url] => gfdhfg
        )

    [3] => stdClass Object
        (
            [name] => gfdhd
            [url] => gfdhfg
        )

)

Comment: What is output? What it do?
Comment: it's removed given index
Comment: And it have to be automatic, I can't put the [0] number each time
Comment: i just send example how to remove keys from array
Comment: How can I add it to a button?

Remove key of JSON file


If a function is defined by a taylor series, how can you derive its inverse in the form of a taylor series?

Question: Say you want to find the inverse of a function, and it's not expressible in terms of known functions, so you want to find the taylor series for that inverse. But, you at least know the taylor series for your original function f(x), defined as $$f(x)=\sum_{n=0}^{\infty} \frac{g(x,n)h(n)}{n!}$$ and it converges for a sufficient radius.
Since Taylor series stem from derivatives, and there is a theorem called the inverse function theorem that relatives derivatives to a functions' inverse
$$(f^{-1})'(f(x))=\frac{1}{f'(x)},$$
is there any consequential theorem where you can derive a new Taylor series for the inverse of a function by using the original Taylor series for that original function?
In other words, $$f^{-1}(x)=\sum_{n=0}^{\infty} \frac{???}{n!}$$
Comment: You've already been told about Lagrangian inversion. There are also a number of algorithms that take the coefficients of a Taylor series and spit out the coefficients of the inverse. [Here](https://math.stackexchange.com/a/135860), I implement an algorithm by Thacher, and [here](https://math.stackexchange.com/a/135997) you have an approach based on Carleman matrices.
Comment: See [$\mathbf{\color{#00}{3.6.25}}$ in A & S Table: Series Reversion](http://people.math.sfu.ca/~cbm/aands/page_16.htm).
Answer: Yes it is possible to find the inverse of a Taylor Series. You can use series reversion. It can be used to find the inverse of Taylor Series given the forward function. Here is a URL: http://mathworld.wolfram.com/SeriesReversion.html
Comment: Sorry for the late reply. Yes I believe the inverse function of a Taylor Series can be strictly defined on series reversion (although tedious, it is the most natural definition in my opinion).
Comment: Okay, thank you for bringing that to my attention. It would be helpful if there was an example because for some reason that summation is unexpectedly of several variables at once, it doesn't look like the end result is a nice Taylor series like I'm looking for. Just to be clear, you're not inverting or undoing the summation operator itself, you're actually defining the inverse of the original function explicitly as a taylor series by using a series reversion?
Comment: @DaneJoe. Have a look  at https://math.stackexchange.com/questions/2360037/inverse-function-for-a-taylor-series/2360186#2360186 for an example.
Comment: @ClaudeLeibovici The problem is that example doesn't actually give any of the intermediate steps, so it doesn't really help anything. When I look for any examples of how to apply this series reversion theorem, there's literally no results whatsoever on the entire internet, there is only a statement of the start of the theorem with no shown application, nothing more. So I have absolutely no way of verifying if I'm interpreting the process correctly even if I arrive at something correct, because it could just be coincidence.
Comment: @DaneJoe. Apply the method by yourself on something like $y=\sin(x)$ to get the Taylor series for $\sin^{-1}(y)$.
Comment: @ClaudeLeibovici That's the thing, I don't even know if I'm applying the first step correctly. I don't even know what the first step is suppose to be, no one really says what it's suppose to be. There's no intermediate steps that explains how it works, no paper on how it was derived. I can't see any reason why an explicit inverse would suddenly explode with a shotgun of random variables that were never present in the original function. If I start with x, y and n, then I expect to end with x, y and n.
Comment: @DaneJoe. I shall write the example.
Answer: Considering $y=\sin(x)$, let us develop it as a truncated Taylor series
$$y=x-\frac{x^3}{6}+\frac{x^5}{120}+\cdots\tag 1$$ Now, following the steps given here, let $$x=a_1y+a_2y^2+a_3y^3+a_4y^4+a_5y^5+\cdots\tag 2$$ and replace.
Expand all terms and group the terms for a given power of $y$. You will get
$$y=a_1 y+a_2 y^2+\left(a_3-\frac{a_1^3}{6}\right) y^3+\left(a_4-\frac{1}{2} a_1^2
   a_2\right) y^4+\frac{1}{120} \left(a_1^5-60 a_3 a_1^2-60 a_2^2 a_1+120
   a_5\right) y^5+\cdots\tag 3$$ Now, identify the powers to get $$a_1=1$$ $$a_2=0$$ $$a_3-\frac{a_1^3}{6}=0\implies a_3=\frac 16 $$ $$a_4-\frac{1}{2} a_1^2
   a_2=0\implies a_4=0$$ $$a_1^5-60 a_3 a_1^2-60 a_2^2 a_1+120
   a_5=0\implies a_5=\frac 3 {40}$$
Comment: I guess it's not too terribly different than the normal process for deriving a Taylor series. I will look at it more in depth tomorrow when I have time, thank you for explaining it I'll get back to you on this.
Comment: @DaneJoe. It is different since the coefficients are no more related to the derivatives. But, as you see, you just need to solve a few equations (one at the time as I did here).
Comment: Alright thanks it works out. It is confusing when WA says "plug in" because that makes it seem literally like every single instance of "x" is replaced with the *entire* infinite series defined by y.


VSCode JavaScript autocompletion turns "this" into "globalThis"

Question: VSCode autocompletion recently started to turn "this" into "globalThis" while in a JavaScript file.

This is very annoying, each time I want to write "this.something" I need to ctrl+z my way out of an unwanted "globalThis.something".
I don't want to disable the whole JavaScript autocompletion though, I just need to turn it off for this particular word.
Is it possible ?
Comment: Surely this doesn't happen everywhere? Where specifically are you typing when it happens? Also, have you checked that it's not because of one of your extensions (by turning them all off and replicating it)?
Comment: What version of VSCode? I'm not seeing this in v1.40.1.
Comment: @T.J.Crowder It happens anywhere in a JS file. Even an empty one. Also, I tried with all my extensions disabled as you suggested, but nothing changed.
Comment: @T.J.Crowder Since you're not seeing this, it must be coming from my settings. I've tried on another machine and even if I could see the "globalThis" suggestion, the "this" completion acted as expected.
Answer: The problem was caused by the fact that I had disabled the "Show Keywords" option. Thus, the this suggestion didn't came up when I typed "this".
Solved it by re-enabling the option.


how to order grouped fields in the sidebar on a node form

Question: On my old Drupal 7 site, I was able to group a set of fields and display them as a tab in the sidebar. I'm moving it to Drupal 8 and using the adminimal theme. I created groups and am using the details sidebar widget. I'd like my custom groups to appear at the top of the sidebar. I've assigned a weight of -5 in Manage Form Display, but they still appear in the middle of the sidebar (even after clearing caches). Is there a way to control the order of groups in the sidebar, or am I maybe using the wrong widget? Thanks.
I have tried using Vertical Tabs Config, but even after clearing caches, the order is unchanged.
Comment: Does this answer your question? [How can I change the order of vertical tabs?](https://drupal.stackexchange.com/questions/12979/how-can-i-change-the-order-of-vertical-tabs)
Comment: I'm not sure I understand correctly what you're asking about, but Manage Form Display page controls the order of widgets on a form (edit page) and Manage Display page controls the actual rendering (view). Maybe you need to take a look at the Manage display page? This split was different in D7.
Comment: Yes, I'm on the manage form display tab. I'm trying to control the edit form for the node. For both my groups, it says "weight: -2" and I'm assuming the default weight is 0, so they should float to the top. Adding to my confusion are the Authored On and Authored By fields, which are displayed in a tab on the form, but aren't indicated as being in a group.
Comment: Can you post screenshots of the Manage form page and the page where you see it not working correctly?
Comment: https://imageshack.com/i/pnGHyz7Np
https://imageshack.com/i/poLLW9pap
Comment: I think this is duplicate, you're asking about vertical tabs order: https://drupal.stackexchange.com/questions/12979/how-can-i-change-the-order-of-vertical-tabs BTW question updates should go into the question edit, it's easily missed in comments.
Comment: @prkos , no, this was not a duplicate, you seem to have misunderstood the question. You've linked to a drupal7 answer - this is about field groups (and perhaps adminimal) in drupal 8>
Comment: Vertical tabs config module has both D7 and D8 versions. Maybe try to report your issue there? You mentioned you set the weight of your group to -5, but the screenshots is showing -2. What are the weights of the sections that appear above it? Maybe -5 isn't a small enough number.
Answer: Using weight -99 makes it appear on top in my installation.
Weight -10 moves it nicely below the 'author' box, which is where I want it.


Hiding a View if empty when contextual filter is already used

Question: On my content type "page", I give my client the option to upload a sidebar image while editing the page fields. In the manage display of the content type, the image is hidden.
I have a view in the sidebar that shows the side bar images. I placed a contextual filter of Nid, and set it to provide a default value using the Content ID from URL, meaning that only the sidebar image for that page will be displayed.
This works sweet, but on pages where a sidebar image isnt uploaded, the sidebar is empty, but the views headers are there, and forcing the main content to be pushed to the left as if the sidebar region has content.
Reading other solutions, people have used a contextual filter of Global: Null, and set the view to hide if empty. But this isnt working for me, probably as I am already using a contextual filter to determine the content from the URL.
Other advice of setting the "no results behaviour" of the field doesnt do anything, the empty block still renders because it has nothing to do with fields, it is only printing the view headers.
I'm a bit stumped! Any ideas?
Answer: I found a very simple answer to this question.
The problem I was having was two contextual filters, Content:NID from URL, and Global:Null Hide If empty, which stopped the view displaying even if full.
Instead, I simply added a Filter Criteria for one of the fields in my view, with :fid on the end. In my case, it was Content: Sidebar Images:fid (not empty)
Now the view shows if it has content, and hides completely, including block region if empty.
Answer:
Add a FILTER CRITERIA
Select the same field that you are displaying under fields
Select the Operator as "Is not empty(NOT NULL)"
Save it, and it is done
Answer: For me, the problem was that I had a Global Text Area defined under Behavior when no results, from previous configurations. Got rid of that and the view stopped showing when it had no results.
(I work with Drupal in spanish so maybe the names in italic do not correspond to the actual english texts. Sorry for that)


iOS application deletes itself once downloaded

Question: I'm developing an application for a company for iOS > 5.0 using Xcode 4.6.1. To test application, i archived application using Save for Enterprise or Ad-hoc deployment. I've checked also Save for Enterprise Distribution and filled appropriate fields. So far, i'm able to create an myApp.ipa file and myApp.plist file. I've created an url to myApp.plist. Once, i clicked url, myApp starts to download correctly. My problem is that once download's finished, myApp deletes itself and i got no crash log,simply nothing. I googled it and got nothing either. The problem is that one of my client is able to download myApp and to use it. I thought the problem is related to provisioning profile,but both devices is registered the same provisioning profile. So, i'm clueless. What could be the problem ? How is it possible that myApp deletes itself ?
Thank you all.
EDIT : here is the console log.

May 10 12:02:15 IK installd[3728] : profile not valid:
  0xe8008012
May 10 12:02:15 IK installd[3728] : 00403000
  install_embedded_profile: Could not install embedded profile:
  -402620398
May 10 12:02:15 IK installd[3728] : entitlement
  'keychain-access-groups' has value not permitted by a provisioning
  profile
May 10 12:02:15 IK installd[3728] : entitlement
  'application-identifier' has value not permitted by a provisioning
  profile
May 10 12:02:15 IK SpringBoard[15] : Killing
  net.caretta.iAnahtar for termination assertion
Comment: @Downvoter, please add a comment why you downvote to improve my question.
Comment: How is your client installing the app?
Comment: @JavierBeltrán From my company server , does it matter ?
Comment: Which OS Version is your device running?
Comment: @Mohith my device is running under iOS 5.1,my deployment targer is > iOS 5.0
Comment: There should be some meaningful error messages in the device log, they always are.
Comment: @Sulthan,added console log, but nothing in device log
Answer: This seems very similar to:
Xcode 4.5 - can't install developer .ipa files via iTunes
The main symptom I observed in the case I had like that problem was that the IPA would try to install, then eventually it would get downloaded - then straight away it would disappear.
If the following line:

installd[31] : profile not valid: 0xe8008012

appears in the console log, then you may want to try re-issuing the profile from the iOS Provisioning portal (simply make a simple change, undo it, then submit - that should regenerate the profile), update the Xcode code signing identity to use the new profile, reboot the device, and then try again. Not guaranteed to fix the problem, but it might be worth trying.
Comment: Thank you.It was the issue.
Answer: Is this an enterprise app (is the developer account issuing the certificate an Enterprise account)? If not, you will need to ensure both the device UDIDs are in the mobileprovision.
The app is not really deleted, it is downloaded but when the OS tries to install it, it fails and that's why the icon is removed.
A few things to check

Are you creating the ipa in the correct manner? Make sure you use the correct certificates and mobile provisions and are using the correct option when exporting the ipa
Both the device UDIDs must be included in the provisioning profile
The device must have ability to install the app (are Restrictions turned on to disable installation of apps?)

Try using a service like Testflight.
Comment: I've double checked that both device UDIDs are int the mobile provision and included in the provisioning profile. Let's say that i didn't create the ipa in the correct manner, how would i be able to download and install that ipa in another device. The device in which i can install the app is exactly same as another. So, i think it's not the issue here. Both `Restrictions` are disabled.
Comment: In that case the only thing which could be going wrong is the mobileprovision. Did you check if the mobileprovision is installed on the device (under Settings->General->Profiles)?
Answer: This isn't a Newsstand app is it? Because when you install a Newsstand app, you'll initially see what looks like a regular app icon while it is downloading, but once the download has finished the icon will disappear and it will automatically move to the Newsstand bookshelf.
Comment: No,it's not a Newsstand app.
Comment: You say there is nothing in the crash log, but what about the console log? You can use something like the [System Console app](https://itunes.apple.com/us/app/system-console/id431158981?mt=8) to view the console logs from the device itself if that helps.
Answer: If your deployment target is a later version than the device OS this happens. I dont see any other reason for it.


LINQ JOIN Straight to Object

Question: I am rather new to LINQ and I have implemented a LINQ statement that does a join and then I get the results of the query, iterate through the results and assign each result to a new object and then add the object to a list of objects. Is there a more elegant way to do the following such that I am selecting right into the object list?
Thanks and much appreciated
<code>        var clubAttendeeEducationList = new List<ClubAttendeeEducation>();

        var r = (from oer in db.OnlineEducationRegistrations
                join oec in db.OnlineEducationCourses on oer.OnlineEducationCourseId equals
                    oec.OnlineEducationCourseId
                where
                    (oer.MasterCustomerId.Equals(userId) && oer.DateCompleted >= start.Date &&
                     oer.DateCompleted <= upUntil.Date && oer.DateCompleted != null)

                select new {OnlineEducationRegistration = oer, oec.CourseTitle}).ToList();

        foreach (var item in r)
        {

            var educationItem = new ClubAttendeeEducation
                    {
                        Session = item.CourseTitle,
                        Date = item.OnlineEducationRegistration.DateCompleted.Value

                    };

            clubAttendeeEducationList.Add(educationItem);
        }

    return clubAttendeeEducationList;
</code>
Comment: Well why are you using `select new { ... }` instead of just `select new ClubAttendeeEducation { Session = oec.CourseTitle, Date = oer.DateCompleted.Value }`? It's not clear why you've chosen this approach...
Comment: @JonSkeet My thinking was that I don't need all of the columns from the joined table so that's why I did it like:  select new {OnlineEducationRegistration = oer, oec.CourseTitle}).ToList(); Like I said, I am kinda new to LINQ so that's why I am looking for some guidance.
Answer: Just as you are creating new anonymous object in your query you can create object of any type you want, and turn result into list.
<code>var clubAttendeeEducationList = (from oer in db.OnlineEducationRegistrations
                                /* rest of the query */
                                select new ClubAttendeeEducation
                                {
                                    Session = item.CourseTitle,
                                    Date = item.OnlineEducationRegistration.DateCompleted.Value
                                }).ToList();
</code>
Answer: Don't select out an anonymous object if you actually want objects of another type.  Simply select out the type that you actually want directly in your original query.

LINQ JOIN Straight to Object


include(HTML2PDF_locale.php): failed to open stream in YII

Question: Trying to Use html to pdf extension in YII . After placing all the required files in its places and including the following code in config:
 'ePdf' => array(
    'class'         => 'ext.yii-pdf.EYiiPdf',
    'params'        => array(
        'mpdf'     => array(
            'librarySourcePath' => 'application.vendor.mpdf.*',
            'constants'         => array(
                '_MPDF_TEMP_PATH' => Yii::getPathOfAlias('application.runtime'),
            ),
            'class'=>'mpdf', // the literal class filename to be loaded from the vendors folder
            /*'defaultParams'     => array( // More info: http://mpdf1.com/manual/index.php?tid=184
                'mode'              => '', //  This parameter specifies the mode of the new document.
                'format'            => 'A4', // format A4, A5, ...
                'default_font_size' => 0, // Sets the default document font size in points (pt)
                'default_font'      => '', // Sets the default font-family for the new document.
                'mgl'               => 15, // margin_left. Sets the page margins for the new document.
                'mgr'               => 15, // margin_right
                'mgt'               => 16, // margin_top
                'mgb'               => 16, // margin_bottom
                'mgh'               => 9, // margin_header
                'mgf'               => 9, // margin_footer
                'orientation'       => 'P', // landscape or portrait orientation
            )*/
        ),
        'HTML2PDF' => array(
            'librarySourcePath' => 'application.vendor.html2pdf.*',
            'classFile'         => 'html2pdf.class.php', // For adding to Yii::$classMap
            /*'defaultParams'     => array( // More info: http://wiki.spipu.net/doku.php?id=html2pdf:en:v4:accueil
                'orientation' => 'P', // landscape or portrait orientation
                'format'      => 'A4', // format A4, A5, ...
                'language'    => 'en', // language: fr, en, it ...
                'unicode'     => true, // TRUE means clustering the input text IS unicode (default = true)
                'encoding'    => 'UTF-8', // charset encoding; Default is UTF-8
                'marges'      => array(5, 5, 5, 8), // margins by default, in order (left, top, right, bottom)
            )*/
        )
    ),
    ),

I get the following error

ERROR: include(HTML2PDF_locale.php): failed to open stream: No such
  file or directory
Answer: It could be a namespace issue, add namespace app/ext .


laravel route and parameters

Question: I am trying to do a search by id.
<form method="post" action="{{action('PLAYERController@edit')}}">
<input type="text" name="id">

controller
public function edit(Request $request)
    {
        $id=$request->id;
        $ply = Player::find($id);
        return view::make('player.edit')->with(compact('ply'));
    }

route
Route::get('/player/edit/{id}', 'PLAYERController@edit');

edit.blade.php
{{$ply[first_name]}}

I am getting undefined variable first_name error.
Answer: your Route must be as below since its post reuqest
Route::post('/player/edit', 'PLAYERController@edit');

also you can do action in form as below
<form method="post" action="{{url('/player/edit')}}">
<input type="text" name="id">

if you are trying make get request then you have to change controller to
    public function edit($id)
        {

            $ply = Player::find($id);
if($ply){
            return view::make('player.edit')->with(compact('ply'));
}
        }

Comment: @KenGraham.glade to here its helped you
Answer: $ply is an Object. Try this
{{ $ply->first_name }}

This won't raise any errors if $ply object being null
And, you don't need that {id} parameter in your route. Because you get the id through the post request.
Route::get('/player/edit', 'PLAYERController@edit');

laravel route and parameters


The string values changed when I read csv file in R

Question: Here's the problem that I have.
In my data, order column has the string values. It includes "01". But, when I read csv file, "01" becomes "1". How to maintain the original datafrmae when I read csv file? Here's my example:

data <- data.frame(a = c(1, 2, 3, 4, 5),
                   b = c(3, 4, 2, 7, 8),
                   order = c("10", "01", "101", "01", "10"),
                   f = c(1, 2, 3, 4, 5),
                   e = c(8, 9, 10, 11, 12))

write.csv(data,"E:/data.csv",row.names=FALSE)
data<-read.csv("E:/data.csv")

Comment: You could set the quoting set to `""` on the `read.csv` then remove the quotes afterward with `gsub`.  Not ideal though, I hope somebody has a better solution!
Answer: There are several solutions for this issue at Specifying colClasses in the read.csv
Here is how to apply the top answer to your example:
library(tidyverse)

data <- data.frame(a = c(1, 2, 3, 4, 5),
                   b = c(3, 4, 2, 7, 8),
                   order = c("10", "01", "101", "01", "10"),
                   f = c(1, 2, 3, 4, 5),
                   e = c(8, 9, 10, 11, 12))

write.csv(data,"~/data.csv",row.names=FALSE)
data <- read.csv("~/data.csv", colClasses = c("order" = "character"))
data
#>   a b order f  e
#> 1 1 3    10 1  8
#> 2 2 4    01 2  9
#> 3 3 2   101 3 10
#> 4 4 7    01 4 11
#> 5 5 8    10 5 12

Created on 2023-05-23 with reprex v2.0.2


Binary image in Matlab

Question: How can I know if an image read with imread is binary in MATLAB
I did this :
Img = imread(IMGsrc);

T = Img== 1 | Img == 0;

If min(min(T)) == ??????

    imshow(T);

end

????? = ??????
Answer: There are two ways you can test for binary images.
The simplest one is to test whether the image is a logical array (a logical array is returned by functions in the image processing toolbox that return binary image)
isBinaryImage = islogical(img);

Alternatively, you check whether all pixels are either 1 or 0
isBinaryImage = all( img(:)==0 | img(:)==1);

Answer: Assuming by "binary" you mean "every pixel is either 1 or 0", a couple things given your image I:

size(I) should only return rows and columns (not channels) otherwise it is not binary
You can test every pixel is either 1 or 0 with T = I == 1 | I == 0;. If min(min(T)) comes back anything but 1 then at least one pixel failed that test, meaning there is a value that is neither 0 nor 1. (For that matter you could use a similar test to check for any number of enumerated values, not just 0 and 1.)

If you can further clarify what you mean by "binary" that would go a long way to a better answer.
Comment: I'm trying to do this.

If Img is Binary Then ImgToBin = im2bw(Img); End If

I mean by binary (image with black and white colors).

Binary image in Matlab


Why are the additional crossjoins generated in hibernate?

Question: Hibernate Query
hql.append("FROM TBucket t1 JOIN FETCH t1.prd JOIN FETCH t1.psAct ");

Configuration
TBucket
@Table (name = "vw_f_t_bucket")

      @ManyToOne (cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.EAGER, targetEntity = Posprd.class)
      @JoinColumns({
          @JoinColumn(name = "prod_key", referencedColumnName="prod_key"),
          @JoinColumn(name = "prod_cycle_key", referencedColumnName="cycle_key"),
      })

      public IPosprd getprd() {
        return prd;
      }

prd (

@Table (name = "snp_prd")
public class Posprd implements IPosprd {

)

      @ManyToOne (cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.EAGER, targetEntity = Pospsact.class)
      @JoinColumn (name = "ps_act_key", nullable = false)
      public IPospsact getpsact() {
            return psAct;
      }

psAct (
    @Table (name = "vw_ps_act_firm")
    public class PosPsact implements IPospsact {
)

Generating Query
FROM vw_f_t_bucket tbucke0_
         INNER JOIN snp_prd posprd1_
            ON tbucke0_.prod_cycle_key = posprd1_.cycle_key
               AND tbucke0_.prod_key = posprd1_.prod_key

        JOIN FETCH t1.psAct

         INNER JOIN vw_ps_act_firm pospsn2_
            ON tbucke0_.ps_act_key = pspsn2_.ps_act_key

CROSS JOIN snp_prd posprd3_
CROSS JOIN vw_ps_act_firm pospsn5_
where tbucke0_.prod_cycle_key=posprd3_.cycle_key and tbucke0_.prod_key=posprd3_.prod_key and tbucke0_.posn_acct_key=pospsn5_.posn_act_key

As you can see from above hibernate is generating cross joins at the end. Why is that? How can I stop hibernate from generating those cross joins?
If I just use the hql like
"FROM TBucket t1  ";

It is generating
from vw_f_t_bucket tbucke0_
cross join snp_prd psprd1_ cross join vw_psn_act_firm pspsn3_

How can I make it do a regular join instead of a cross join?
Answer: You've both specified eager fetching and also indicated a JOIN FETCH in your query.  The JOIN FETCH is unnecessary as the property is already annotated for eager fetch (hence the inner joins in the FROM.)
Comment: I removed the JOIN FETCH, the JOIN FETCH in the "Generating Query" is gone, but the cross joins remain. What can I do about it?
Comment: Is that the entirety of the entities?  perhaps there are other mappings to those tables on the entity?  I've honestly never seen hibernate write a full cross join before.
Comment: the problem
instead of using
from TBucket t1 join t1.prd p
and in Criteria, I should be using p.excgId in (?,?)
I was using Criteria like t1.prd.excgId in (?,?). That is the reason why it was generating cross joins.
I should be using the alias to do filtering.
Thanks for help, though.