my computation of a real integral still has an imaginary number in it,

Question: I have four residues that I have found.  I multiplied each by $2\pi i$, using the Residue Theorem.  But my final answer still has an $i$ in it.  Needless to say, it is not the right answer, since the goal was to compute a real integral on $R^+$
What should I do with the four residues to try and catch my mistake?  I've expanded each one in its Euler formula, $\cos(x) + i \sin(x)$, computed a common denominator, so that I can combine all residue terms.  This led to a few cancellations, but ultimately still left me with an $i$ factor.  Am I proceeding in generally the correct way?
Thanks,
EDIT: The integral is $$\int_0^\infty \frac{x^2logx}{1+x^4}dx$$
Here's a summary of my work:  the integrand has simple poles at
$$e^{i\pi/4},e^{i3\pi/4},e^{i5\pi/4},e^{i7\pi/4}$$
and the residues are
$$-\frac{\pi}{16ie^{i\pi/4}},-\frac{3\pi}{16ie^{i3\pi/4}},-\frac{5\pi}{16ie^{i5\pi/4}},-\frac{7\pi}{16ie^{i7\pi/4}}$$
finally, multiplying each by $2\pi i$, and adding up the four terms gives me (incorrectly) $$-\frac{\pi^2i}{\sqrt{2}}$$ I added the terms by expanding out all of the Euler formulas, and then combined the terms with a common denominator.  I've checked my work about 5 times now...still can't catch my mistake...
Comment: a little more detail about the problem and your attempts at a solution  would be useful!
Comment: Could you please put the integral you are trying to compute into the problem?
Comment: Hi @gt6989b, ok I just did.
Comment: It might be useful to show the four residues and the final answer as well. Basically just do a brain-dump to the question text.
Comment: Hi @DavidHolden, ok, I'll add a little more detail now..
Comment: Hi @DavidK, ok, good idea.
Comment: The contour integral you end up computing in this problem is not a real number.
Comment: What contour are you using exactly?
Comment: Hi @CountIblis, hmm...really?  I have not moved on to try and give the estimates on the contour, which is a keyhole contour that encloses the four poles, but does not touch the positive real axis.  I was hoping to show that the integral goes to zero on the big and little circle, and then do something with the integral on the two straight lines that are approaching the positive real axis...
Comment: I was hoping that my answer is equal to the contribution of two integrals, both are integrals on straight lines approaching the positive real axis, from above and below.  And I think the estimate on the large and small circle is easy to do...
Comment: I don't understand what kind of paths on the complex plane you're using. You should describe them explicitly in your question. Anyway, the sort of paths I would use don't encircle all 4 poles, but only 1 or 2 of them.
Comment: The chosen contour must not enclose the branch point or corresponding branch cut for the complex logarithm.  Please refer to my solution to see one approach.
Answer: We will evaluate the integral
$$\color{blue}{\int_0^{\infty}\frac{x^2\log x}{x^4+1}dx}$$
by analyzing the integral $I$ defined as
$$I=\oint_C\frac{z^2(\log z)^2}{z^4+1}dz$$
where the contour $C$ is the keyhole contour for which the "key hole" is along the positive real axis.
The contributions to the integral from the circle of radius $R$ that enclosed the poles vanishes as $R\to \infty$.  Likewise, the contribution from the semi-circle with radius $\epsilon$ around the branch point at $z=0$ vanishes as $\epsilon \to 0$.  Thus,
$$\begin{align}
I&=\int_0^{\infty} \frac{x^2 (\log x)^2}{x^4+1}dx+\int_{\infty}^0\frac{x^2 (\log x+i2\pi)^2}{x^4+1}dx\\\\
&=-i4\pi \color{blue}{\int_0^{\infty}\frac{x^2\log x}{x^4+1}dx}+4\pi^2\int_0^{\infty}\frac{x^2}{x^4+1} \tag 1
\end{align}$$
The first integral on the right-hand side of $(1)$ is the integral of interest.  The second integral can be evaluated in terms of elementary functions and is equal to $\pi\sqrt{2}/4$.  We also have that $I$ is
$$I=2\pi i \sum_{k=1}^4 \text{Res}\left(\frac{z^2(\log z)^2}{z^4+1},z_k\right)$$
where $z_k=e^{i(2k-1)\pi/4}$, $k=1,2,3,4$, are the roots of $z^4=-1$.  The residues are given by
$$\frac{(\log z_k)^2}{4z_k}$$
Can you finish from here?
SPOILER ALERT:

The sum of the residues, after pain-staking patience, are $\pi^2\sqrt{2}-i\frac{\pi^3\sqrt{2}}{4}$.  Thus, the integral of interest is $$\int_0^{\infty}\frac{x^2\log x}{x^4+1}dx=\frac{\pi^2\sqrt{2}}{16}$$
Comment: @AmitaiYuval Please read the solution. The $(\log x)^2$ terms drop out.  We are left with the integral of interest.
Comment: Hi @Dr.MV - very interesting solution.  What was the motivation to look at $(log(z))^2$ instead of log(z), as given?  Is it a pretty well-known technique?  I certainly couldn't have thought of that myself.  Thanks so much...
Comment: @user258980 Thank you!  And you're welcome.  It was a real pleasure!!  As for the approach, if one tries integrating $(\log z)^1$ around a branch cut, the log part cancels and disappears.   So, we need to try another approach and one that works is to analyze the $(\log z)^2$ integral.  If we want to integrate $(\log x)^2$ we need to analyze $(\log z)^3$ in the complex plane.  The $(\log x)^3$ part drops out and we are left with $3(2\pi i)(\log x)^2$, $3(2\pi i)^2\,(\log x)^1$, and $(2\pi i)^3$ terms.  Kind of neat, huh?
Answer: The following is an outline of the solution which is the most natural in my opinion.
Write$$A:=\int_0^\infty \frac{x^2\log x}{1+x^4}dx.$$A short calculation shows that$$\int_{-\infty}^0\frac{x^2\log x}{1+x^4}dx=A+i\pi\int_0^\infty\frac{t^2}{1+t^4}dt=A+i\pi\cdot\frac{\pi}{2\sqrt{2}}=A+\frac{i\pi^2}{2\sqrt{2}}.$$(the second left hand integral can be evaluated using either complex integration or standard real analysis methods).
Now consider paths which go along the whole real line with a small circular "jump" to avoid $0$, then draw a semicircle in the upper half plane. The contribution of the semicircle vanishes at infinite radius, and the contribution of the circular jump vanishes at $0$ radius. The integral$$\int_\gamma\frac{z^2\log z}{1+z^4}dz$$along the above described kind of path can be evaluated by considering the residues at the two upper poles of the function.
Comment: Hi @amitaiYuval, it sounds like you are integrating straight through the branch cut, which I assume you've chosen the positive real axis as your cut?   If so, is it a valid move?  I feel we should consider paths *near* the whole real line, and let the paths approach $R^+$ ...thanks
Comment: No, dear @user258980, I'm integrating along the *whole* real line, and avoiding the origin by a small semicircle from $(-\epsilon,0)$ to $(\epsilon,0)$. This tiny semicircle is in the upper half plane, as is the large semicircle, and hence the origin is *not* inside the whole path. I'm using the branch of the $\log$ function which is real on the positive real ray and defined on the upper half plane.


What's the answer to this indeterminated limit?

Question: The exercise  says that in order that
\begin{equation*}
g(x) =\frac{1-\cos( 3x-9)}{( x-3)^{2}} +\frac{x}{6}
\end{equation*}
be continuous at $x=3$, then $g(3)$ should be...
I understand that for a function to be continuous at a point, the limit should be equal to evaluate the function at that point.
I solved this in two different ways and each gives me a different answer.
Solution 1 Solution 2
The graphic is hard to analyze, so I can't get an answer from there.
I appreciate the help, thanks.
Answer: Note that from $\cos(2a)=1-2\sin^2 a$,
 $$1-\cos(3x-9)=2\sin^2\frac{3(x-3)}{2}$$
thus
$$\lim_{x\to 3}g(x)=\lim_{x\to 3}2\left(\frac{\sin\frac{3(x-3)}{2}}{x-3}\right)^2+\lim_{x\to 3}\frac{x}{6}\\
=\frac{9}{4}\lim_{x\to 3}2\left(\frac{\sin\frac{3(x-3)}{2}}{\frac{3(x-3)}{2}}\right)^2+\frac12\\
=\frac92+\frac12=2$$
thus $g(3)=5$.
Comment: The denominator in the first line after 'thus' should be $(x-3)$ (not squared).
Comment: @Bernard thanks.Edoted
Comment: And the factor at the second line is not $\frac 34$.
Comment: if
\begin{gather*}
\sin^{2} x+\cos^{2} x=1\\
\sin^{2} x=1-\cos^{2} x
\end{gather*}
then
$\displaystyle \sin^{2}( 3x-9) =1-Cos( 3x-9)$
?
Comment: That's almost correct (the cosine has to be squared).
Comment: You forgot the big fraction is squared.
Comment: @Angelo Fariña check the edit
Comment: Thanks!
why  in the second line $\displaystyle x-3$ and not $\displaystyle ( x-3)^{2}$?
Comment: We gather $(x-3)^2$ and $\sin^2 3(x-3)/2$ in a bracket to the power of $2$
Answer: Hint:
A standard limit is
$$\lim_{t\to 0}\frac{1-\cos t}{t^2}=\frac  12,\quad\text{whence }\;\lim_{t\to 0}\frac{1-\cos at}{t^2}=\lim_{t\to 0}a^2\frac{1-\cos at}{(at)^2}=\frac{a^2} 2.$$
Now, in $g(x)$, set $\;t=x-3$.
Can you proceed?
Comment: I'm sorry, I don't understand it and what are you trying to say.
Comment: What exactly do you not understand?
Comment: If $\displaystyle t=x-3$ then $\displaystyle \lim _{t\rightarrow 0}\frac{1-\cos( 3( x-3))}{( x-3)^{2}} =\lim _{t\rightarrow 0}\frac{1-\cos( 3t)}{t^{2}}$ ?
I don't understand why did u multiplied by $\displaystyle a^{2}$ and $\displaystyle ( at)^{2}$ in the denominator.
Comment: It is to have exactly the argument of the cosine inside the square in the denominator, so the limit of the fraction is $\frac12$. To compensate, I had to multiply by $a^2$ in the numerator. Is it clear?
Comment: Yes. In my case it will be $\displaystyle \lim _{t\rightarrow 0} 3^{2}\frac{1-\cos( 3t)}{( 3t)^{2}}$ ? But why this is equal to $\displaystyle \frac{a^{2}}{2}$ ?
Comment: Because of the limit in the basic formula ($1/2$). If you know Taylor's formula, this becomes obvious.
Answer: $\dfrac{9(1-\cos (3x-9)}{9(x-3)^2)}=$
$9\dfrac{(1-\cos (3x-9))(1+\cos (3x-9))}{(3x-9)^2(1+\cos (3x-9))}$
$=9\dfrac{\sin^2 (3x-9)}{(3x-9)^2(1+\cos (3x-9))}$;
$g(x)=$
$9\dfrac{\sin^2 (3x-9)}{(3x-9)^2}\dfrac{1}{(1+\cos (3x-9))}+ \dfrac{x}{6}$
Take the limit.
Note: $\lim_{y \rightarrow 0}\dfrac{\sin^2 y}{y^2}=1.$
Comment: I didn't understand where the 9 came from. But I was able to follow the rest. Thanks!
Comment: Angela. Denominator: Originally $(x-3)^2$.  Multiplying denominator and numerator by 9 does not change the value of the fraction. Now we have $9(x-3)^2=3^2(x-3)^2=(3(x-3))^2=(3x-9)^2=:y$. Now you can use $(\sin^2 y)/y^2$. Changed the denominator to be able to use this formula.ok?


assigning "exports" to a function in nodejs module doesn't work

Question: in one file (otherFile.js) I have this:
exports = function() {}

in my main file I have this:
var thing = require('./otherFile.js');
new thing();

however this gives me the following error:
TypeError: object is not a function

and if in otherFile.js I have this instead:
exports.myFunction = function() {}

and in my main file I have this:
var thing = require('./otherFile.js');
new thing.myFunction();

then it works perfectly. Why is it that I'm not allowed to assign a function to the exports variable?
Answer: If you want to change the exported object itself you will have assign it to module.exports. This should work (in otherFile.js):
module.exports = function() {}

To elaborate a little more why:
Reassigning a variable does not change the object it referenced before (which is basically what you are doing). A simple example would be this:
function test(a) {
    a = { test: 'xyz' };
    console.log(a);
}

var x = { test: 'abc' };
test(x);

console.log(x);

Basically by assigning exports to the function you'd expect the variable x to have a value of { test: 'xyz' } but it will still be { test: 'abc' } because the function introduces a new variable (which is still referencing the same object however so changing a.test will change the output of both). That's basically how CommonJS modules (which is what Node uses) work, too.
Comment: interesting! Why is this so?
Comment: Because the `exports` variable is just a reference to the object. Reassigning the variable won't change that object. Changing the property of the parent object (`module`) will however.
Answer: Consider this code:
!function(exports) {
    // your module code
    exports = 12345
}(module.exports)

console.log(module.exports)

It won't work, and it's easy to see why. Node.js exports object is defined exactly like this, with an exception of arguments ordering.

So always use module.exports instead of exports, it'll do the right thing.


Close webform modal and redirect to entity

Question: I have a webform that opens inside a modal. Everything works fine. Then I had the problem of closing the modal after the form was submitted. I fixed that to with the help of the following link: https://www.drupal.org/project/webform/issues/3002966#comment-12794056
I have a webform handler that creates a new entity in the postSave() method. After this entity is created, I want to close the modal and redirect to the entity detail page. What is the best/correct way to do this. I could use a RedirectCommand instead of the CloseDialogCommand but how do I get the entity id in the _CUSTOM_MODULE_webform_submission_form_submit_ajax() method. Using the AjaxResponse with a RedirectCommand in the postSave() method didn't work.
Any Suggestions would be great ;-)
Answer: Yes you are so close!
just move the creation of the new entity from your postSave()
to right in the ajax call back
example:

_CUSTOM_MODULE_webform_submission_form_submit_ajax(array &$form, FormStateInterface $form_state) {
 // At this point we have all access to $form_state->getValues();
 // the webform submission is all ready saved so we can use the values here.

 // Get the entity storage.
 $entity_storage = \Drupal::entityTypeManager()->getStoage('ENITYNAME');

  // Create New entity.
  $new_entity = $entity_storage->create([
   'field_whatever' => $form_state->getValue('some_field');
  ]);
  // Save entity
  $new_entity->save();
  $new_entity_id = $new_entity->id();
  // set the url.
  $url = "/where-ever/" . $new_entity_id;

  $response = new AjaxResponse();
  $response->addCommand(new CloseModalDialogCommand());
  $response->addCommand(new RedirectCommand($url);
  // Party.
 return $response;
}

Comment: Wow, I think that was too obvious :D Thanks for your help! That did the trick.


OpenCV Hough Circle Transform doesn't detect most circles

Question: I am trying to detect as many circles in my images using the following code:

maxRadius = int(1.2*(width/16)/2)
minRadius = int(0.9*(width/16)/2)
gray = cv.cvtColor(image, cv.COLOR_BGR2GRAY)
circles = cv.HoughCircles(image=gray,
                               method=cv.HOUGH_GRADIENT,
                               dp=1.2,
                               minDist=2*minRadius,
                               param1=70,
                               param2=0.9,
                               minRadius=minRadius,
                               maxRadius=maxRadius
                          )

Although it does work for some of the images there are a few exceptions for which it doesn't.
Below we can see that for two different images that represent the same kind of experiment, my algorithm yields very different results.
How can I fix this? Should I apply some sort of filter on the images first to enhance the contrast?

EDIT: added original image:
enter image description here
Comment: Can you please post the test image you are working with? The ones you have posted are too small to work with.
Comment: Post the original images without the scales.
Comment: I think `HoughCircle` shouldn't be the way to solve this. I also explained [here](https://stackoverflow.com/questions/65895764/trying-to-detect-all-the-circles-with-houghcircles-in-opencv-python/65896615#65896615) about that to deal with houghcircle.
Comment: @KnightForked I just added the original image!
Comment: @fmw42 just added the original image!
Comment: You might use adaptive thresholding or division normalization then hough circle to find the most probable ones. Then get the centers and radii. Then given the pattern of centers and the size of your dish, you could partition as many circle as you want into the dish size. Alternately, you might have better  luck trying to find the cells in the circles.
Answer: This solution may or may not work on other images but it does work on the one you posted. You might want to work on that "sweet spot" apropos the adaptiveThreshold and HoughCricles parameters so that it works with other images as well.
import numpy as np
import cv2
import matplotlib.pyplot as plt

rgb = cv2.imread('/path/to/your/image/cells_0001.jpeg')
gray = cv2.cvtColor(rgb, cv2.COLOR_BGR2GRAY)
imh, imw = gray.shape

th = cv2.adaptiveThreshold(gray,255, cv2.ADAPTIVE_THRESH_MEAN_C,cv2.THRESH_BINARY_INV,11,2)

maxRadius = int(1.2*(imw/16)/2)
minRadius = int(0.9*(imw/16)/2)
circles = cv2.HoughCircles(image=th,
                               method=cv2.HOUGH_GRADIENT,
                               dp=1.2,
                               minDist=2*minRadius,
                               param1=70,
                               param2=25,
                               minRadius=minRadius,
                               maxRadius=maxRadius
                          )

out_img = rgb.copy()
for (x, y, r) in circles[0]:
    # draw the circle in the output image
    cv2.circle(out_img, (x, y), int(r), (0, 255, 0), 1)

plt.imshow(out_img)

Comment: @Jeanne Chaverot, was this code of any help?
Comment: Hello, sorry just saw your comment. Yes indeed it worked thank you very much!


Analyze and visualize participants response towards particular condition

Question: Method: I presented 15 participants with audiovisual clips. There were six different clips I presented, and for each clip there was emotional incongruence between visual and auditory information. The combinations were:

visual negative with auditory positive
visual negative with auditory neutral
visual positive with auditory negative
visual positive with auditory neutral
visual neutral with auditory negative
visual neutral with auditory positive

I asked participants to make an emotional judgements, whether the clip was happy, angry or neutral. There were five repetitions.
Research question: Are participants driven by visual or auditory information in their emotional choices, when they watch displays with incongruent emotional information?
Basic analysis: Because there were no "correct" responses per se for the incongruent stimuli, I calculated the tendency to respond correctly when emotion was presented auditorily or visually. The tendency was estimated by subtracting the proportion of "auditory correct" responses from the proportion of "visual correct" responses for the six incongruent conditions. For example if the incongruent display combined visual negative with auditory positive information, and participants responded that it was a negative interaction, then it was counted as visual response. The estimated indices varied from 1 (participants always responded correctly to the visual information) to −1 (participants always responded correctly to the auditory information). Below is a figure produced in R that shows averaged tendency scores, with standard error bars. The data is available here - columns represent conditions, rows - tendency scores for each participant.

Now, getting to the point I have two questions:

Question 1: What would be the best way to check for significant differences between those different clips?

I know I could simply run a series of 30 paired t test's but it doesn't seem as a pretty solution. I don't think I can use ANOVA here - I have no clue how I could define levels for all those incongruent conditions. Maybe I could organize this data in some different way, but I really not sure what it would be.

Question 2: Is there a better way you could use to visualize this?

I don't love the above plot - in fact I really don't like it. The oversized legend is very heavy to read, and so are the patterns differentiating each condition. I could use color instead, but I am a bit color blind to be honest, so I would prefer to avoid it.
EDIT
Question 1 I decided to just compare the 6 pairs which had the same type of incongreunt information using paired t test. Works kind-of-ok to get the differences.
Question 2 has been answered well by @AndyW and @gung - I decided to use pure SE bars with vertical orientation of x axis. Done in R using segplot() - I need to tweak the details, but it's roughly the idea.
Answer: For two, avoid dynamite plots (see Drummond & Vowler, 2011), and utilize dot plots since you only have 15 participants. You can super-impose confidence lines over the dot plots, and you can create a category axis label to label the dots/bars/lines, foregoing the need to differentiate between categories using color, point/line symbols or other hashings.
I will post back an example using your data later, but for now the paper cited above has several examples perfectly applicable to your situation, and one is inserted below.

Since you tagged the question r, this previous question has applicable code snippets to generate similar charts, Alternative graphics to "handle bar" plots.

Citation

Drummond, Gordon B. & Sarah L. Vowler. 2011. Show the data, don't
conceal them. The
Journal of Physiology 598(8): 1861-1863. PDF available from
publisher.
Note this article is
being simultaneously published in 2011 in The Journal of Physiology,
Experimental Physiology, The British Journal of Pharmacology, Advances
in Physiology Education, Microcirculation, and Clinical and
Experimental Pharmacology and Physiology

Below is an example extended to your data. I have posted full examples of generating similar plots in R using ggplot2 and in SPSS on my blog in this post, Avoid Dynamite Plots! Visualizing dot plots with super-imposed confidence intervals in SPSS and R.
Comment: Another note, a recent question on stack overflow demonstrates how these types of dot plots can even be effectively extended when the number of data elements is much larger using jittering and making the points semi-transparent, [ggplot2: Multiple color scales or shift colors systematically on different layers?](http://stackoverflow.com/q/9232331/604456).
Comment: @GeekOnAcid, [here](http://cross-validated-blog.googlecode.com/files/ggplot2_dynamite.r) I have posted some code to generate a similar plot in `ggplot2` in `R`, I will I will let you know in an update when I figure out how to generate a legend.
Comment: Thank you, this is excellent solution for the visualization problem. I am a bit worried only in the sense that studies I am quoting heavily are all using standard dynamite plots, but I guess one has to push better solutions in order to break the bad habits in reporting effects...
Comment: Did you used `stripchart()` or something else to produce this in R? And what function did you used to plot error bars?
Comment: @GeekOnAcid, the above chart is produced in SPSS. I did experiment and have a similar chart using ggplot2 in R, but I'm currently stuck in producing a legend in either! I will have the opportunity to update with code I used to produce said charts tomorrow.
Answer: @AndyW has a good answer.  I think dot plots, or even box plots are good approaches, although I think bar graphs are OK.  One thing I would recommend is that you rotate your figure 90 degrees.  Then, more visual would go to the right, and more auditory would go to the left.  The advantage of this is that you could drop the legend and list your conditions on the left hand side.  They would be easy to read, because they would be aligned with their corresponding graph elements (whatever you end up going with), and because people read horizontally from left to right.  You could probably wrap the text, but you could also abbreviate somewhat, perhaps "Vis - & Aud +" (you'd need to come up with something for neutral).  Thus, the figure needn't take up any more space than it does now.


How to see the java process that is using a port

Question: I have a small Java ServerSocket application that is running on port 4444. I wanted to see the process using that port in my OSX terminal, and my first thought was to do the following:
netstat -a | grep 4444 however, this doesn't give me any results.
lsof -i :4444 and I get the following (correct) result:
COMMAND   PID        USER   FD   TYPE             DEVICE SIZE/OFF NODE NAME
java    66389 admin   18u  IPv6 0x1ae123a422ebe931      0t0  TCP *:krb524 (LISTEN)

Could someone tell me why netstat doesn't show the port but lsof does?
Answer: Mac OSX is based on BSD so the netstat under Mac OSX will not be able to show you the pid/process name. As you already figured out, lsof is the right choice.
Answer: Edit: The version of Netstat that is included with Mac OSX does not interpret the -p flag as it does in other distributions (protocol instead of program), so while Netstat likely did not work for the reasons outlined below, lsof was still the correct way to go for the answer.
Netstat by default uses friendly names/definitions for ports (e.g., ssh instead of 22). Add the -n flag to use numeric host addresses and port numbers. Additionally, add -p to show the PID and name of the program.
In summary: netstat -anp | grep 4444 is probably what you would need.
Here's an example:
# netstat -anp | grep 10050
tcp        0      0 0.0.0.0:10050           0.0.0.0:*               LISTEN      1121/zabbix_agentd

Netstat will also print any other related network connections as well, not just sockets in the LISTEN state.


Can a Webform display the last submitted version of instead of creating a new submission

Question: I have a web form that is embedded into a field on a content type and wondering if the form has been already submitted can you display the webform/manage/webform_name/submission/webforn_numer/edit form instead?
Answer: Yes!!! Just go to Webform: Submissions: Settings and check off 'Limit total to one submission' per user or per submission.


How can I schedule change of the default front page?

Question: I have a node being displayed on the front page, set at admin/config/system/site-information > Frontpage.
I need to change it to another node on specific date.
It would be ideal if I could do that using views display of /frontpage + Promote node to frontpage. But i have a referenced by nid view inserted into the nodes of this content type (using Views Field) which does not show anymore if I use this method.
Thanks
Answer: I would add a date field to the node and then filter the view to only show the node scheduled for today. Point your front page to that view.
You'll need the date module.


How to interpret the partial effect plots for parametric terms while using gratia::draw() and gratia::parametric_effects()?

Question: I am asking a question akin to this one: https://stackoverflow.com/questions/71884457/what-does-the-y-axis-effect-mean-after-using-gratiadraw-for-a-gam but am wondering the same question for parametric terms not smooths.
My data looks like this:
    df<-structure(list(spreg = structure(c(2L, 2L, 2L, 2L, 2L, 2L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L,
1L, 1L, 1L, 1L, 1L, 1L, 1L), levels = c("n", "y"), class = c("ordered",
"factor")), Landings = c(48974, 16933, 18389, 16433, 5720, 3775,
1388, 97109, 148609, 104267, 77454, 128938, 108096, 126957, 102396,
16165, 59423, 2892, 4728, 3783, 4785, 11359, 5323, 6106, 167,
568, 480, 2208, 4378, 1908), year = c(2007, 2009, 2011, 2013,
2015, 2018, 2007, 2007, 2007, 2012, 2015, 2018, 2007, 2007, 2012,
2015, 2018, 2008, 2010, 2006, 2008, 2011, 2008, 2011, 2007, 2010,
2007, 2014, 2015, 2014)), row.names = c(1L, 2L, 3L, 4L, 5L, 6L,
7L, 8L, 9L, 10L, 11L, 12L, 13L, 14L, 15L, 16L, 17L, 18L, 19L,
20L, 21L, 22L, 23L, 24L, 25L, 26L, 28L, 29L, 30L, 31L), class = "data.frame")

My code looks like this:
library(mgcv)
library(gratia)
gam<-gam(Landings~s(year)+spreg,data=df)
draw(parametric_effects(gam))

Partial effect plot looks like this:

This is what summary(gam) looks like:
Family: gaussian
Link function: identity

Formula:
Landings ~ s(year) + spreg

Parametric coefficients:
            Estimate Std. Error t value Pr(>|t|)
(Intercept)    30460      11178   2.725   0.0112 *
spreg.L       -16964      15961  -1.063   0.2974
---
Signif. codes:  0 '***' 0.001 '**' 0.01 '*' 0.05 '.' 0.1 ' ' 1

Approximate significance of smooth terms:
          edf Ref.df     F p-value
s(year) 1.374  1.652 0.229   0.798

R-sq.(adj) =  -0.00914   Deviance explained = 7.35%
GCV = 2.6732e+09  Scale est. = 2.3726e+09  n = 30

I want to report these partial effect plots for parametric terms but I am having trouble finding a good description of the partial effect plots for fixed effects. Is this the estimate and 95% credible interval like the smooth partial effect plots?
Comment: The value for the `y` group is literally the estimated value for the `y` term shown in the output from `summary()`, and the interval is based on the SE shown in that output too. The value for `n` is 0 as it is the reference level and hence it has 0 partial effect as the intercept term represents this group and the partial effects shown are for *deviations* from the intercept. I don't find these plots that useful, but `plot.gam` showed them so `draw()` does as it is a ggplot-based alternative to `plot.gam`.
Comment: Thanks Gavin. That is what I was thinking. I've noticed that if the fixed effect is an ordered factor it looks as though the partial effect estimates in relation to zero effect instead of in relation to the reference level. (I'll edit the post to show that.) Am I right to assume that the estimate there is in relation to zero effect?
Comment: So `spreg` is the ordered factor? Can you add the output from `summary(gam)` to your question? Or is the plot shown based on the subset of data you provided? If the latter I can take a look directly myself tomorrow
Comment: @GavinSimpson this is just a small subset of a much larger data set that I put on here. I added the `summary(gam)` to the question.
Comment: `spreg` is the ordered factor.
Comment: Thanks; managed to find a few minutes to check my memory against reality. Answer below.
Comment: Awesome thanks for the clarification. In the version of gratia I have, `draw(gam, parametric =T)` gives me this error: `Error:
! Can't combine `x[[1]]$level` > and `x[[2]]$level`  >.`
Comment: But I am still able to get the parametric terms by pulling each individually with `parametric_effects()`
Comment: Could you file a bug report [here](https://github.com/gavinsimpson/gratia/issues)? Include the error message and the output from `sessionInfo()` so I know what you are running. A reproducible example would help too, or if you install the version from GitHub do you see the same issue? Wild guess; are you fitting with data that have `NA`s and not setting `na.action` in the `gam()` call?
Comment: no I don't have any `NA` in there. I just reported the bug with a reproducible example.
Answer: With ordered factors, the intercept represents the expected value of the response at the mean of the factor's levels; in the snippet of data, this is 1.5, and the remaining coefficients represent polynomials of the factor levels. In the model shown, there is only a linear polynomial term because there are two levels.
With this kind of factor, the output from parametric_effect() is the model estimate (partial effect) for each factor level:
r$> ds <- data_slice(m, spreg = evenly(spreg))
r$> fitted_values(m, data = ds, exclude = c("(Intercept)", "s(year)"))
# A tibble: 2 × 6
  spreg  year  fitted     se   lower  upper
  <ord> <dbl>   <dbl>  <dbl>   <dbl>  <dbl>
1 n      2010  11996. 11286. -10124. 34115.
2 y      2010 -11996. 11286. -34115. 10124.

which, because there is only a linear polynomial contrast, the two estimates equally deviate from the intercept (the mean of the levels) in opposite directions (hence the sign on the fitted value).


jQuery/AJAX: each, if, post, .html: Runs but randomly deletes data

Question: I've got a PHP page, with FedEx & UPS tracking numbers in a MySQL database echoing into ID's of DIVs with the class "trackingnumber". My JS each's through those divs and grabs the ID to then post to a PHP page that polls Fedex/UPS and echos the result from them. That works great, except for one thing. It randomly deletes the data after it's loaded it. So the data will flash on the screen for a second, and then disappear. It's random too, which just baffles me. Check out this Video demonstrating the issue (.mov) to get a better understanding.
JS:
$(document).ready(function(){
    //Dislay some text indicating that we're getting status
    if ($("[id!='']")) {
        $("div.trackingnumber").html("working...");
    };
    //Begin getting status
    $('div.trackingnumber').each(function(index){
        var v2 = $(this).attr("id");
        //If it's FedEx, post to the FedEx script.
        if ($("[id!='1z'], [id!='1Z']")) {
            $.post("inc/fedex.php", { v: v2 }, function(data){
                $("#" + v2).html(data);
            });
        };
        //If it's UPS, post to the ups script.
        if ($("[id^='1z'], [id^='1Z']")) {
            $.post("inc/ups.php", { v: v2 }, function(data){
                $("#" + v2).html(data);
            });
        };
    });
});

Relevant HTML (after PHP has parsed it):

Any ideas? I'm new to jQuery (and JS in general)... I've got no idea why this is doing what it is. It looks like all my code is valid (the only errors in FireBug or Safari's web inspector are when it hits a div without any data in the class)... I've been battling this for about a day now, finally getting it to this point... Really hoping someone will be able to help me out!
Comment: Check the post requests in firebug to make sure they're returning the correct data and that the right number of requests are being fired.
Comment: By just looking at your code, I don't see any logical errors. I would suggest you to do: console.log($(this)); inside the loop to ensure the matched elements are what you want.
Comment: munch is right. Looking at the "Net" tab in Firebug would have clued you in to the problem. Hopefully my answer (below) is the correct solution. Good job on the question though; it was clear, concise and even included video evidence! :)
Answer: I'm afraid you've misunderstood how jQuery works; your if statements don't make sense at all.
$("[id!='']") will always return a jQuery object which, due to JavaScript's automatic type coercion, will always evaluate to true. In other words $("[id!='']") == true no matter what your HTML looks like. The same applies for the rest of your if statements.
Because of this mistake your code retrieves both the results of the UPS and FedEx scripts every time. Since the AJAX calls are asynchronous your results may appear in different orders thus causing an apparently random clearing of the data (when the empty data is returned after the correct data).
This is how I assume you intended your code to behave:
$(document).ready(function(){
  // Select all of the tracking numbers on the page
  $(".trackingnumber").
    // Display some text in each, indicating that we're getting status
    text("working...").
    // Begin getting status for each tracking number.
    each(function () {
      var trackingNumber = this.id;

      // Use the fedex script by default ...
      var script = "fedex";

      if (trackingNumber.match(/^1z/i)) {
        // ... unless it's a UPS tracking number.
        script = "ups";
      }

      $.post("inc/" + script + ".php", { v: trackingNumber }, function(data){
          $("#" + trackingNumber).html(data);
      });
    });
});

Working Demo: http://jsbin.com/iyeci (editable via http://jsbin.com/iyeci/edit)
Don't hesitate to ask if you need more help understanding the code.
Comment: Glad I could help. If you want to exclude `trackingnumber`s that don't have an `id`, use `$(".trackingnumber[id!='']")` instead of `$(".trackingnumber")`. Adding that `if` statement won't prevent the unnecessary AJAX request.
Comment: Excellent! I was using the if ['id^'blah'] due to reading that it was more efficient than the match, and was figuring that wasn't the issue (despite the working... one wasn't correctly not showing when there wasn't any tracking number in the id) since it was deleting the data randomly. Thank you so much!
Comment: I've added:
if (trackingNumber.length !=0) {
    $(this).text("working...");
};

To the code so that "working..." only displays when there actually is something to work on.

Just for future reference. :)


Discordjs: how to listen for messages on a specific channel

Question: I am building a discord bot to listen to messages on a specific channel. The issue is that my code listens to all channels.
Even if I use a condition to check for the channel id before picking the message, it means it will do more work than is necessary.
I want to avoid the case of selecting messages from multiple channels and just concentrate on the messages in the channel I want to listen to.
require('dotenv').config();

const { Client, Intents, Collection } = require('discord.js');
const {TOKEN, CHANNEL_ID} = require('./src/config/index');

const client = new Client({
  intents: [Intents.FLAGS.GUILDS, Intents.FLAGS.GUILD_MESSAGES],

});

client.once('ready', (c) => {
  console.log(`Ready! Logged in as ${c.user.tag}`);
});

client.on('messageCreate', async (message) => {
  console.log(message)
})

client.login(TOKEN);

This code above is the current code I am using
Answer: You can check where the message was posted before running any code.
As far as i am aware that is the only way to do this
client.on('messageCreate', async (message) => {
 if (message.channel.id === "YOUR CHANNEL ID") {
   // run code here
 }
})

Comment: Large scale bots listen to millions of messages across thousands of channels just fine.
Comment: Thanks @Ramy Hazem. It seems that way from all my searches but that sounds terrible to me. Imagine having to listen to 20 channels to get messages from a single channel when you know the channel you need to deal with.
Comment: i guess another possible option is only having your bot see that channel, set perms for that and maybe that could work?
Answer: There are three ways of sending a message to a specific channels.
//1. Single channel listener
client.on('messageCreate', async (message) => {
   if (message.channel.id === "channel_id") {
       //For a single channel listener.
   } else {
       //You can send a message if the channel_id is not equal.
   }
})

//2. Multiple channel listener / can be use as .json
let channels = [
    "channel_id",
    "channel_id"
]

if(channels.includes(message.channel.id)) {
    //Multiple Channel ID's
} else {
    //An example of return for not including some channel_id
    message.channel.send("I can't use these command on this channel.")
}

//3. Can be use like using a database such as mongodb / mongoose / etc.
let channels = {
    "chan": [
        "987627957478637619",
        "948780253948575764"
     ]
}

if(channels?.chan.includes(message.channel.id)) {
      //Multiple Channel ID's
} else {
      //An example of return for not including some channel_id
      message.channel.send("I can't use these command on this channel.")
}

Answer: This is my code, pretty simple and it works.
let allowedChannels = [
  /*bot-channel*/"1053346645779152993",
  /*console*/"1053346646227959900"
];

client.on('messageCreate', msg => {
  //VERY important, exit if the message is from a bot to prevent loops
  if (msg.author.bot) {
    return;
  };
  //Check if the channel is accepting bot commands
  if (allowedChannels.includes(msg.channel.id) === false) {
    return;
  }
}

Comment: As it's currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer).


hook_file_download and style images

Question: According this bug issue,
hook_file_download is called twice when private style image is requested. The first time is requested original image without style and then the style image is called. Is there any workaround to skip checking access of original image?
In particular, I have a website, where user can share his private images on his facebook account. Then I need to allow facebook to send http request to download image. The problem is, that facebook hs limitations on size of images. Facebook doeasn't accept larger images when downloading thumbnails from my website. As I tested it, although my image thumbnails are small, drupal system check access against large original image so facebook doesn't accept the thumbnail.
Is there any workaround, how could I solve this problem?
thanks for advice
Tomas
Answer: Disclaimer - Use this method at your own risk, it has security implications if you don't set up and test it properly :)
A quick and dirty way to override that functionality would be to implement hook_module_implements_alter(), remove the image module's implementation of hook_file_download(), and then implement your own version which has the desired logic. e.g.
function MYMODULE_module_implements_alter(&$implementations, $hook) {
  if ($hook == 'file_download') {
    unset($implementations['image']);
  }
}

function MYMODULE_file_download($uri) {
  // Copy the code from image_file_download() and alter as required.
}

hook_file_download and style images


Is it UB to reference bind to underlying type of enum class object?

Question: Is it UB to reference bind to underlying type of enum class object?
I'm aware of the danger of pass-through return reference of the as_int function.  The thunking function is just to help explain the question.
XY problem - after a bunch of inline operators to static_cast to/from underlying type at appropriate places, I found this to be an easier to use alternative in places.  But I am unsure if it is undefined behavior, and the reinterpret_cast takes off the safety.  The public facing API of the enum class would not expose this pattern; it is just for private use in the implementation file.
#include <iostream>

using std::cout;

enum class Int : int {};
inline auto as_int(Int& i) -> int& {
    return reinterpret_cast<int&>(i);
}

int main() {
    Int i{100};
    int& r = as_int(i);
    cout << r << "\n"; //> 100
    as_int(i) = 107;
    cout << r << "\n"; //> 107
}

Comment: Given the fact that this is a native type, and it's going to end up somewhere, if the driver for trying to do this is some kind of a micro-optimization, it is likely that all this hoop-jumping will get compiled down to the same exact code as a plain `static_cast`.
Comment: @SamVarshavchik • on my compilers, yes, both the more verbose `static_cast` way and this (after user17732522's answer) UB way it does compile to the same thing.  Both in debug builds and optimized release builds.
Answer: Accessing the return value of as_int(i) as done in your main is an aliasing violation and therefore causes undefined behavior. The relevant paragraph of the standard ([basic.lval]/11) does not list underlying types of enumeration types as specifically allowed to alias.
Currently the standard doesn't even specify that the enumeration type and the underlying type will share the same alignment. If it was different then the cast would not even preserve the value (so that a round-trip cast would be unsafe). But that seems like a defect, see CWG 2590.
Alignment issues aside, the cast itself does not have undefined behavior, but accessing the enumeration object through the resulting reference does.
Comment: Thank you!  You've talked me down off the ledge.


How to encode the string in redable format

Question: I have python code that decode and the decompress the string and when i encode and compress the string the ouput is different
import zlib, base64
a = zlib.decompress(base64.b64decode('eF7zSM3JyVcIzy/KSVFU8FTPVcjPUwguSUzO9i9LLUrLyS9XBADJNQvD'))
print(a)

The output will be b"Hello World! I'm on StackOverflow!"
a = zlib.compress(base64.b64encode(b"Hello World! I'm on StackOverflow!"))
print(a)

but when i try to encode the above string b"Hello World! I'm on StackOverflow!" the output i am getting is byte string like this b'x\x9c\x0bv\x0f+Nr\xb7H\x0f3\xb2\xacLr\x0f\xcc\xf0t\xcd\xceK\nv*K\xcat\nIqw\xcbJ4\xb04\x8a\x8a\xf0\xcaMr\xb74\xf6\x0c\xb4\xb5\x05\x00\x85l\x0ff'
but i want to get output like this eF7zSM3JyVcIzy/KSVFU8FTPVcjPUwguSUzO9i9LLUrLyS9XBADJNQvD
This was example from Trying to decode zlib compressed and base64 encoded data to a readable format in Python
what is wrong in my code
Comment: The inverse of decompress(decode()) is encode(compress())
Answer: You should Base64 encode the result of compressing, not the other way around.
print(base64.b64encode(zlib.compress(b"Hello World! I'm on StackOverflow!")))

Answer: This is how your code should look like
import zlib, base64

compressed_data = zlib.compress(b"Hello World! I'm on StackOverflow!")
encoded_data = base64.b64encode(compressed_data)

print(encoded_data)
print(encoded_data.decode())

b'eJzzSM3JyVcIzy/KSVFU8FTPVcjPUwguSUzO9i9LLUrLyS9XBADJNQvD'
eJzzSM3JyVcIzy/KSVFU8FTPVcjPUwguSUzO9i9LLUrLyS9XBADJNQvD

Note: Output is not exactly the same because compression algorithms are not guaranteed to produce same output for the same input.


@controller is nil error on minitest at particular case

Question: I have added the following code in the test helper. I am using minitest.
include Rails.application.routes.url_helpers

def default_url_options
  Rails.application.config.action_mailer.default_url_options
end

When I ran the controller test I am getting the below errors.
@controller is nil: make sure you set it in your test's setup method is coming
However, the service is working fine. I could not find the correct reason for that. Does anyone know that?
I need the above in service and I can not change the entire controller tests to support,
def setup
  @controller = Controller.new
end

Comment: Your `setup` method is not executed before the test.
Answer: Have use check the assigns variable in your minitest.
It consists of all the instance variables defined in controller in form of key-value pair
So check for assigns[:controller]


Graph layout algorithm with extra "nodes" on edges, and with non-point nodes

Question: I'm attempting to lay out arbitrary graphs in as graphically pleasing a manner as possible while trying to minimise computation required (because the layout engine will be written in browser JavaScript). Obviously one convenient way is to use a force-directed algorithm. I have two additional constraints on my graphs which are making it difficult for me to know how to progress:

The nodes (which are circular) have reasonably large size -- in particular, they are not points -- and nodes must not overlap. I believe that this is best handled by enforcing a minimum edge length of 2*noderadius, and by putting an edge between every pair of nodes, and only displaying the edges which correspond to actual edges in my graph. However, there may be a better way.
An edge has a circular symbol at its midpoint, and these circular symbols must also not overlap. That is: edges are permitted to cross (of course; not all graphs have a planar embedding) but the midpoints of two edges must not coincide. For example, K3,3 in its compact layout (https://upload.wikimedia.org/wikipedia/commons/thumb/f/f3/Biclique_K_3_3.svg/200px-Biclique_K_3_3.svg.png) would not be suitable because many edges have their midpoints in the same place (in the centre of the diagram) and so the symbols of all but one edge would be obscured.

I did think that this constraint would be achieveable by making the "edge midpoint symbols" actually be nodes, and thus the normal way of stopping nodes overlapping would stop the edge symbols overlapping too, but if I do that then I do not know how to make the two edges from a symbol be collinear: that is, an edge A-B with a symbol in the middle should look like one line from A to B with a symbol in the centre. If I model it as A-s-B then the force-directed algorithms will not constrain A-B to be one line, and I do not want the A-B edge to "bend" in the middle.
I understand how to use a force-directed algorithm in general, and I think I can fulfil point (1) in a force-directed algorithm, but I do not know how to stop edge symbols overlapping while being force-directed. Possibly there is a way to do this, or possibly I should be using a different graph layout algorithm entirely, in which case I invite suggestions as to what that should be. I am not a mathematician by trade, so I would appreciate it if suggestions came with a little explanation :-)
The graphs are unlikely to contain more than, say, 25 nodes, so there are not huge numbers of nodes here, and therefore I am OK with (relatively) inefficient approaches :-)
Answer: It is an iterative process, but not all iterations have to have the same edges. I am thinking you have your graph of nodes and edges, you have springs and repulsion going on to do the basic layout. You then have a second set of edges which enforce the non-overlap of nodes and midpoint symbols - this second set includes the midpoints as nodes and doesn't worry too much about bending at the midpoints. You then alternate between the first and second set of edges, probably ending on the first set so you don't get any bends in your midpoint symbols.
Comment: I'm not sure I follow this. If I allow edge-bending in the second set of nodes, won't I sometimes get a layout which has non-overlapping midpoints in the second set of edges (because those edges are bent) but has *overlapping* midpoints with the first, unbent, edge set?
Comment: I am not entirely sure it will work either. Do the symbols have to be in the exact middle or is A-s--B OK?
Comment: In the exact middle; that's the aesthetic balance of the thing.


$f(n) = \frac{n^2 + n + 4}{2}, g(f(n)) = f(g(n))$ such that $g(n)$ is an integer.

Question: Let $n$ be a strict positive integer.
Lets define an integer sequence $f(n)$ :
$$f(n) =  \frac{n^2 + n + 4}{2}$$
so
$$f(1) = 3$$
$$f := {3,5,8,12,17,23,30,38,47,...}$$
$$f(17) =  155$$
etc
Notice
$$3+2=5$$
$$5+3=8$$
$$8+4=12$$
$$12+5=17$$
etc
and $f(R)$ has no real fixpoint for real $R$.
Now we want integer sequences $g(n)$ such that $g(n)$ grow faster than linear and
$$ g(n+1) > g(n)$$
$$f(g(n)) = g(f(n))$$
$$f(n) + 1 < g(n) < f(f(n)) - 1$$
And fixpoints are not allowed :
$$g(n) \neq n$$.
A possible solution seems
$$g :={5,9,17,29,47,73,109,155,...}$$
and you can check that $$f(g(n)) = g(f(n))$$ and the other conditions hold.
The sequence g might not be unique and i assume no mistake has been made.
But it is not so easy to see.
(contradictions do not occur immediately but could happen for later values if one is not careful)
The sequence g resembles or equals this perhaps :
https://oeis.org/A034329
But it might not relate or be coincidence.
One of the ideas is that $g(n)$ is just floor$(f^{[r]}(n))$ ;
In other words $g(n)$ is just the rounded down number of some real iterate of $f(n)$.
But that is just a vague conjecture.
Fractional iterations are not unique and the solutions for $g$ might not be unique either.
So that idea is vague and nonconstructive, so its value is arguable.
I want solutions for $g(n)$.
Is $g(n)$ close to a $3/2$th iterate of $f(n)$ ??
Does $g(n)$ grow like $O(n^3)$ because it is close to a $3/2$th iterate of $f(n)$ ?
The integer conditions make this hard to see.
MAIN QUESTIONS
I want solutions for $g(n)$.
How many solutions exist ? How many free parameters are there ?
Comment: also posted here : https://mathoverflow.net/questions/449289/fn-fracn2-n-42-gfn-fgn-such-that-gn-is-an-integer
Comment: ok this is probably weird coincidence, but I remembered this sequence from the past :
https://math.stackexchange.com/questions/306566/primes-of-the-form-fracn2-n42-satisfy-hardy-littlewood-analogue

Im not sure if primes and number theory are related.
Answer: This started as an attempted proof, but ended up being more of demonstration of how hard the problem is. However, I still think it's worth sharing.

By definition, since $g(f(n))=f(g(n))$, then
$$g\left(\frac{1}{2}(n^2+n+4)\right)=\frac{1}{2}(g^2(n)+g(n)+4).$$
What this means is that if we are looking for free parameters, then we must observe that
$$\begin{align*}
&n=0\implies g(2)\text{ depends on the value of }g(0),\\
&n=1\implies g(3)\text{ depends on the value of }g(1),\\
&n=2\implies g(5)\text{ depends on the value of }g(2),\\
&\vdots
\end{align*}$$
Thus, $g(0),g(1),g(4),\cdots$ (and all such $g(k)$ such that $k$ is not of the form $\frac{1}{2}(n^2+n+1)$) do not depend on any other term (or more accurately, all other terms depend on them). So they are effectively our "free" parameters which define the rest of the sequence. Notice that this effectively creates an infinite family of "lineages of dependence".
$$\begin{align*}
&g(0)\leftarrow g(2)\leftarrow g(5) \leftarrow g(6) \leftarrow g(17) \leftarrow \cdots\\
&g(1)\leftarrow g(3)\leftarrow g(8) \leftarrow g(38) \leftarrow g(743) \leftarrow \cdots\\
&g(4)\leftarrow g(12)\leftarrow g(80) \leftarrow g(3242) \leftarrow g(5256905) \leftarrow \cdots\\
&\vdots
\end{align*}$$
So the difficulty here is choosing such $g(0),g(1),g(4),\cdots$ such that they obey:
$$g(n+1)>g(n)\text{ and }f(n)+1<g(n)<f(f(n))-1\text{ for all }n.$$
The $g(n+1)>g(n)$ condition alone is not so difficult, as it can be achieved with some sort of greedy algorithm. Fortunately, we are guaranteed that
$$g\left(\frac{1}{2}(n^2+n+4)\right)=\frac{1}{2}(g^2(n)+g(n)+4)>g(n),$$
by definition, at least, so our "lineages of dependences" will be ordered regardless of our choices of $g(0),g(1),g(4),\cdots$. Hence, as long as we choose our free parameters to obey $0<g(0)<g(1)<g(4)<\cdots$, then it is already a given that
$$\begin{align*}
&g(0)< g(2)< g(5) < g(6) < g(17) < \cdots\\
&\wedge\\
&g(1)< g(3)< g(8) < g(38) < g(743) < \cdots\\
&\wedge\\
&g(4)< g(12) < g(80) < g(3242) < g(5256905) < \cdots\\
&\wedge\\
&\vdots
\end{align*}$$

But this is now starting to look very category theoretic, which is far beyond my pay-grade, so I'll leave it here. Hopefully someone can pick up this line of reasoning to extend this into a proof (positive or negative).


C#: Chained Linq methods and casting

Question: I have a little game, where I implemented some collision detection. Now I want to get a list of all items of a specific type, which are colliding with the current "Entity" object. I want to do something like this:
    public List<T> GetCollidingObjects<T>() where T : Entity
    {
        return this.Game.World.Entities
            .AsParallel()
            .Where(e => e.IsColliding(this))
            .Where(e => e is T)
            .ToList<T>();
    }

I get the following error:
Instance argument: cannot convert from "System.Linq.ParallelQuery<GameName.GameObjects.Entity>" to "System.Collections.Generic.IEnumerable<T>"

Can anyone explain, why this happens?
Thank you!
Comment: It probably won't solve your problem, but the second `Where` clause can be replaced with `OfType()`.
Answer: You cannot use ToList() like that.  The generic parameter you supply (if you choose to do so) must match the type of the sequence.  It's a sequence of Entity, not T.
Anyway, you should use OfType() to do the filtering, that's what it's there for.
public List<T> GetCollidingObjects<T>() where T : Entity
{
    return this.Game.World.Entities
        .OfType<T>()
        .AsParallel()
        .Where(e => e.IsColliding(this))
        .ToList();
}

Comment: +1: Also, depending on the scenario, it will likely be better to put the `.OfType()` before the `.AsParallel()`, as the partitioning will likely do a much better job, especially if there is a non-random distribution of types within Entities (highly likely).
Comment: @Reed: Ah good point.  I was debating on whether `OfType()` should come before or after `AsParallel()`.
Comment: Hi, thank you for your explanation :-) It works great! And I understood why it did not work in the first place.
Answer: Jeff Mercado's answer is correct, but can be stated more plainly.
.Where(e => e is T)

This call to Enumerable.Where<Entity> returns an IEnumerable<Entity> (a filtered version of the source, which is an IEnumerable<Entity>).  The call does not return an IEnumerable<T>.
Enumerable.Select<TSource, TResult> and Enumerable.OfType<TResult> can return an IEnumerable with a type different than the source:
.Where(e => e is T)
.Select(e => e as T)

or
.Select(e => e as T)
.Where(e => e != null)

or
 .OfType<T>()

C#: Chained Linq methods and casting


$f(f(x)) = x \Longleftrightarrow f(x) = x$ if $f(x)$ is monotonically increasing. Can it work for monotonically decreasing $f(x)$ or $f(f(f(x)))$

Question: If $f(x)$ is a monotonically increasing function, then equations  $f(f(x)) = x$ and  $f(x) = x$ are equivalent, meaning I can solve a simpler equation $f(x) = x$ instead of a more complex one $f(f(x)) = x$.
Here is an example of this: instead of solving $1 + \sqrt{1+\sqrt{x}} = x$ I can solve $1+\sqrt{x} = x$
The trick above is possible because $f(x) = 1+\sqrt{x}$  is a monotonically increasing function.
Question 1: the trick above needs strictly monotonic (strictly increasing) or weakly increasing (non-decreasing) would also work?
Question 2: is there any rule like that for $f(f(f(x))) = x$ or $f(f(f(f(x)))) = x$, etc  ($f$ being monotonically increasing)?
Question 3: can the trick above work for monotonically decreasing function? And how?  $f(f(x)) = x\Longleftrightarrow f(x) = -x$ ?
Question 4: is there any rule like that for $f(f(g(x))) = x$ or $f(g(g(x))) = x$ being $f$ or $g$ or both are monotonic?
Comment: For (3) consider $f(x)=1-x$
Answer: It may help
Generally $f(f(x))=x$ means that the function $f(x)=f^{-1}(x)$ ($f(x)$
is self inverse if it is a a bijection). $f(x)=x$ happens to be a self inverse function.
So the double arrow in your title is not OK it works in reverse only.
Some interesting self inverse functions are $f(x)=\pm x, a/x, (1-x^k)^{1/k}, x\in [0,1], k>0, f(x)=\frac{ax+b}{cx-a}.$
Comment: I think OP meant $f(f(x))=x$ for some $x$, not for all $x$.


GUI keyboard simulator

Question: I am working on this keyboard simulator, however I am relatively new to GUI and I am stuck at the point where I try to add ActionListener to perform the functionality of the buttons, which means I want the letter appear the input area whenever the a button is pressed.
Thanks in advance!
import java.awt.BorderLayout;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JButton;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextArea;

public class StockTicker extends JFrame implements ActionListener
{
String firstRow[] = {"1","2","3","4","5","6","7","8","9","0"};
String secondRow[] = {"Q","W","E","R","T","Y","U","I","O","P","Del"};
String thirdRow[] = {"A","S","D","F","G","H","J","K","L","Return"};
String fourthRow[] = {"Z","X","C","V","B","N","M","."};

JButton first[];

JButton second[];

JButton third[];

JButton fourth[];

public StockTicker()
{
    super ("A Simple Stock Market GUI");

    this.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    this.setResizable(false);

    initWidgets();
}

private void initWidgets()
{

    JLabel jlOutput = new JLabel("Output: ");
    JLabel jlInput = new JLabel("Intput: ");
    final JLabel jtfOutput = new JLabel("");
    final JLabel jtfInput = new JLabel();

     JPanel bottomPanel = new JPanel();
        bottomPanel.setLayout(new GridBagLayout());
        GridBagConstraints gbc = new GridBagConstraints();
        gbc.gridx = 1;
        gbc.gridy = 0;
        gbc.fill = GridBagConstraints.HORIZONTAL;
        gbc.weightx = 1.0;
        gbc.weighty = 0.1;
        gbc.anchor = GridBagConstraints.PAGE_START;
        JLabel bottomLabel = new JLabel(" Input : ", JLabel.LEFT);

    setLayout(new BorderLayout());
    JPanel jpNorth = new JPanel();
    JPanel jpCenter = new JPanel();
    JPanel jpKeyboard = new JPanel();

    add( jpNorth, BorderLayout.NORTH);
    add( jpCenter, BorderLayout.CENTER);
    add(jpKeyboard, BorderLayout.SOUTH);

    jpNorth.setLayout(new BorderLayout());
    jpNorth.add(jlOutput, BorderLayout.WEST);
    jpNorth.add(jtfOutput, BorderLayout.SOUTH);

    jpCenter.setLayout( new BorderLayout());
    jpCenter.add(jlInput, BorderLayout.WEST);
    jpCenter.add(jtfInput, BorderLayout.CENTER);

    jpKeyboard.setLayout(new GridLayout(4,1));

    pack();

    first = new JButton[firstRow.length];

    JPanel p = new JPanel(new GridLayout(1, firstRow.length));

    for(int i = 0; i < firstRow.length; ++i)
    {

        first[i] = new JButton(firstRow[i]);
        p.add(first[i]);

    }

    jpKeyboard.add(p);

    second = new JButton[secondRow.length];

    p = new JPanel(new GridLayout(1, secondRow.length));

    for(int i = 0; i < secondRow.length; ++i)
    {

        second[i] = new JButton(secondRow[i]);
        p.add(second[i]);

    }

    jpKeyboard.add(p);

    third = new JButton[thirdRow.length];

    p = new JPanel(new GridLayout(1, thirdRow.length));
    for(int i = 0; i < thirdRow.length; ++i)
    {

        third[i] = new JButton(thirdRow[i]);
        p.add(third[i]);

    }
    jpKeyboard.add(p);

    fourth = new JButton[fourthRow.length];

    p = new JPanel(new GridLayout(1, fourthRow.length));
    for(int i = 0; i < fourthRow.length; ++i)
    {

        fourth[i] = new JButton(fourthRow[i]);
        p.add(fourth[i]);

    }
    jpKeyboard.add(p);

    }

Comment: And what's your problem?
Comment: I don't know how to add actionlistener to the buttons and make them actually work.
Answer: JButton.addActionListener(listener);
So you would do something like
MyActionListener listener = new MyActionListener();

.
.
.

first[i] = new JButton(firstRow[i]);
first[i].setActionCommand(firstRow[i]);
first[i].addActionListener(listener);

.
.
.

public class MyActionListener implements ActionListener {

    public void actionPerformed(ActionEvent evt) {

        String cmd = evt.getActionCommand();

        // append the cmd value to your out put...

    }

}

GUI keyboard simulator


How do I append something to a node when it's in detail page

Question: I'm writing a module that appends content to a node. I'm doing this using hook_process_node :
function mymodule_preprocess_node(&$variables) {
  $variables['content']['body'][0]['#markup'] .= '
My content
';
}

How can I put a condition here to tell Drupal to only append content when the node is being displayed on a detail page, i.e. not in an index page?
Answer: If by "detail page" you mean the full node page, you can check the current view mode:
if ($variables['view_mode'] == 'full') {
  // ...
}

Answer: You should check $variables['view_mode']. You probably need to define a "Full content" view mode on your display settings of the node bundle. It will probably say "default" when "Full content" is not defined.
Answer: What is your detail page url?
if its "domain/content/details", then use below condition inside your hook_prepocess_node.
First find your content type. for example, i'm assuming $variables['type'] = your_content_type.
if($variables['type'] == 'your_content_type' && arg(0) == 'content' && arg(1) != '') {
  // write your condition here.
}


Bit field padding in C

Question: Continuing my experiments in C, I wanted to see how bit fields are placed in memory. I'm working on Intel 64 bit machine. Here is my piece of code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdint.h>
int main(int argc, char**argv){
       struct box_props
       {
         unsigned int opaque       : 1;
         unsigned int fill_color   : 3;
         unsigned int              : 4;
         unsigned int show_border  : 1;
         unsigned int border_color : 3;
         unsigned int border_style : 2;
         unsigned int              : 2;
       };

       struct box_props s;
       memset(&s, 0, 32);
       s.opaque = 1;
       s.fill_color = 7;
       s.show_border = 1;
       s.border_color = 7;
       s.border_style = 3;

       int i;
       printf("sizeof box_porps: %d sizeof unsigned int: %d\n", sizeof(struct box_props), sizeof(unsigned int));
       char *ptr = (char *)&s;
       for (i=0; i < sizeof(struct box_props); i++){
          printf("%x = %x\n", ptr + i, *(ptr + i));
       }

       return 0;

and here is an output:
sizeof box_porps: 4 sizeof unsigned int: 4
5be6e2f0 = f
5be6e2f1 = 3f
5be6e2f2 = 0
5be6e2f3 = 0

And here is the question: why does struct box_props have size 4 - can't it just be 2 bytes? How is the padding done in that case? I'm a bit (nomen omen) confused with it.
Comment: I think this is because you are using type int, try using short int if you want size 2.try and send a feedback
Comment: `memset(&s, 0, 32);` Ouch! You ask `memset` to zero out 32 bytes, but have only four. You're just unlucky that didn't destroy some vital part of the stack and caused your programme to crash violently.
Answer: Even though the total requirement is just 2 Bytes (1+3+4+1+3+2+2) in this case, the size of the data type used (unsigned int) is 4 bytes. So the allocated memory is also 4 Bytes. If you want just 2 Bytes  allocated use  unsigned short as your data type and run the program again.
Answer: From the ISO C standard:

An implementation may allocate any addressable storage unit large enough to hold a bit-
  field. (and later) There may be unnamed padding at the end of a structure or union.

So there's no requirement to always choose the smallest possible chunk of memory for the struct. And since 32-bit words are probably the native size for your compiler, that's what it chooses.
Comment: The normal behavior I see from compilers nowadays is to allocate things according to the type of the bitfield.  So `uint32_t foo:4;` will allocate `foo` four bits from a storage location of type `uint32_t`; unless four bits remain from an immediately-preceding bitfield of the same type, it will allocate another `uint32_t`.  I dislike those rules, but they are what they are.
Answer: The placement of bit-fields in memory depends not only on how the compiler decides to assign the various fields within the structure but also on the endian-ness of the machine on which you are running. Lets take these one-by-one. The assignment of the fields within the compiler can be controlled by specifying the size of the field (as @DDD) points out, but also through another mechanism. You can tell the compiler to either pack your structure or leave it better suited for how the compiler may want to optimize for the machine architecture for which you are compiling. Packing is specified using the packed type attribute. Thus, if you specify the struct as:
struct __attribute__ ((__packed__)) box_props {
    ...
}

you may well see a different layout in memory. Note that you won't see the layout being different by examing the structure components - its the layout in memory that could change. Packing a structure is crucially important when communicating with something else such as an IO device which expects specific bits at specific places.
The second issue with bit field structures is their layout dependence on endian-ness. The layout of the struct in memory (or any data for that matter) depends on whether you are running on a big-endian (POWER) or little-endian (e.g., x86) machine. Some systems (e.g., embedded PowerPC systems are bi-endian).
In general, bit fields make it very hard to port code because you are futzing with the layout of data in memory.
Hope this helps!
Answer: For some reason I do not fathom, the implementers of the C standard decided that specifying a numberic type along with a bitfield should allocate space sufficient to hold that numeric type unless the previous field was a bitfield, allocated out of the same type, which had enough space left over to handle the next field.
For your particular example, on a machine with 16 bit unsigned shorts, you should change the declarations in your bitfield to unsigned shorts.  As it happens, unsigned char would also work, and yield the same results, but that is not always the case.  If optimally-packed bitfields would straddle char boundaries but not short boundaries, then declaring bitfields as unsigned char would require padding to avoid such straddling.
Although some processors would have no trouble generating code for bitfields which straddle storage-unit boundaries, the present C standard would forbid packing them that way (again, for reasons I do not fathom).  On a machine with typical 8/16/32/64-bit data types, for example, a compiler could not allow a programmer to specify a 3-byte structure containing eight three-byte fields, since the fields would have to straddle byte boundaries.  I could understand the spec not requiring compilers to handle fields that straddle boundaries, or requiring that bitfields be laid out in some particular fashion (I'd regard them as infinitely more useful if one could specify that a particular bitfield should e.g. use bits 4-7 of some location), but the present standard seems to give the worst of both worlds.
In any case, the only way to use bitfields efficiently is to figure out where storage unit boundaries are, and choose types for the bitfields suitably.
PS--It's interesting to note that while I recall compilers used to disallow volatile declarations for structures containing bitfields (since the sequence of operations when writing a bitfield may not be well defined), under the new rules the semantics could be well defined (I don't know if the spec actually requires them).  For example, given:
typedef struct {
  uint64_t b0:8,b1:8,b2:8,b3:8, b4:8,b5:8,b6:8,b7:8;
  uint64_t b8:8,b9:8,bA:8,bB:8, bC:8,bD:8,bE:8,bF:8;
} FOO;
extern volatile FOO bar;

the statement bar.b3 = 123; will read the first 64 bits from bar, and then write the first 64 bits of bar with an updated value.  If bar were not volatile, a compiler might replace that sequence with a simple 8-bit write, but bar could be something like a hardware register which can only be written in 32-bit or 64-bit chunks.
If I had my druthers, it would be possible to define bitfields using something like:
typedef struct {
  uint32_t {
    baudRate:13=0, dataFormat:3,
    enableRxStartInt: 1=28, enableRxDoneInt: 1, enableTxReadyInt: 1, enableTxEmptyInt: 1;};
  };
} UART_CONTROL;

indicating that baudRate is 13 bits starting at bit 0 (the LSB), dataFormat is 3 bits starting after baudRate, enableRxStartInt is bit 28, etc.  Such a syntax would allow many types of data packing and unpacking to be written in portable fashion, and would allow many I/O register manipulations to be done in a compiler-agnostic fashion (though such code would obviously be hardware-specific).
Comment: "the implementers of the C standard decided that specifying a numberic type along with a bitfield should allocate space sufficient to hold that numeric type […]" What clause of the C standard is that? C99 126.96.36.199:3 says "the width of a bit-field shall be an integer constant
expression with a nonnegative value that does not exceed the width of an object of the
type that would be specified were the colon and expression omitted" which is a very different constraint than the one you are describing.
Comment: Also 22.214.171.124:10: "An implementation may allocate any addressable storage unit large enough to hold a bit-field"
Comment: And 22.214.171.124 (11) says: "If insufficient space remains, whether a bit-field that does not fit is put into the next unit or overlaps adjacent units is implementation-defined.", thus straddling is explicitly allowed. gcc and clang straddle bit-fields and use smaller units of storage than would be necessary for the named type if you tell them to by using `__attribute__((packed))` at least on some architectures.
Comment: That depends on what you consider your syntax idea. I don't think `= bit_position` is a particularly good way to specify it (though I don't have a better idea). If you mean the general idea of being able to specify the exact layout of bit-field sequences, that would, I believe, be quite useful sometimes. But it ain't gonna happen, the committee is quite loath to restrict implementations thus strongly, as far as I can tell.
Comment: @PascalCuoq: In some older C compilers, I believe the only aspect of a bitfield's type the compiler would care about was whether it was signed or unsigned, but on the newer compilers I've seen any particular bitfield will always be allocated as part of a storage location of its indicated type.  For example, if one has a volatile struct with an 8-bit bitfield of type `uint64_t`, even if it's byte-aligned, the generated code will read the 64-bit storage unit containing the bitfield, change 8 bits of it, and write all 64 bits back.
Comment: @DanielFischer: Ah, thanks.  I hadn't seen that part.  BTW, what do you think of my syntax idea?
Comment: @DanielFischer: I was thinking of it being like `enum`, which assigns either the value specified with `=`, or the next value if none is specified.  As for the idea of explicit struct layout "restricting implementations", the spec for C has always required that CHAR_BITS be at least 8, and even systems where CHAR_BITS is greater than 8 often have to communicate over 8-bit links.  It will thus often be necessary to convert data into a known format.  With standards as they are, I think using a function to pack or extract things is cleaner than using a `union`, but...
Comment: ...such an approach won't allow compilers much room to optimize things.  If one wants to write a value which is known to be in the range 0 to 4095, to bits 14-19 of a 32-bit field, saying `field = (field & ~0x000FC000) | (value << 14)`; may be the most efficient *portable* way to do it, but on processors with bit-field-manipulation instructions a bit-field store might be more efficient.  Note that with the code written as above a compiler could not perform the optimization unless it could prove `value` would never exceed 4095.

Bit field padding in C


Displaying formatted text within a UITableView

Question: I have to create a UITableView, that contains richly formatted text within each UITableViewCell.
My first attempt at solving the problem was to convert the text to html and render the text within a UIWebView. However, I found that my cells were taking too long to load, and webviewdidload isn't called while scrolling. I then tried piecing together several formatted uilabels, but found that this method too caused performance issues.
I tried subclassing UITableViewCell and using CoreText drew NSAttributedStrings, however it is my understanding that CoreText is not available on devices with less than iOs 3.2, and I'd like my app to work on devices with ios 3.1.
I've heard that its also possible to use opengl es to render some formatted text, however this extends pretty far outside of my zone of experience.
Does anyone have any suggestions of simpler ways to approach this problem, or resources where I can learn more about rendering formatted text with opengl on iphone/ipad?
Thanks for your help!
Answer: I know there are multiple solutions out there but the one I know of and suggest you might look into is the Three20 library which includes TTStyledTextLabel.
Comment: Thanks for the tip! This may be a silly question, but how do open source libraries like this work in the context of commercial applications? Are they free game for anyone? Or do I need to license with them or provide credits somewhere?
Comment: It depends on the license. Three20 uses the Apache License, Version 2.0.  Here is a S.O. entry that describes it's use in a commercial application: http://stackoverflow.com/questions/1007338/can-i-use-apache-software-license-2-0-lib-in-commercial-application


Share extension causes safari to hang in iphone

Question: I am developing an iOS app that allows user to save urls, similar to the Pocket app. In the app I have a share extension that basically just save the url into a NSUserDefaults based on the app group. For some reason the share extension causes the mobile safari to hang (being non responsive) after selecting the share extension. The code for the share extension is so simple, I am wondering what may have caused it. On debugging in Xcode, the function in the share extension is not being called at all too it seems. Any clues? This is running on iOS 9.3.
Here is the code:
<code>//
//  ShareViewController.swift
//  intrafeedappShare
//
//  Created by Dicky Johan on 5/21/16.
//  Copyright © 2016 Dicky Johan. All rights reserved.
//

import UIKit
import Social
import MobileCoreServices

class ShareViewController: UIViewController {

    var selectedURL: String?

    override func viewDidLoad() {

        super.viewDidLoad()

        let contentType = kUTTypeURL as String

        guard let item = self.extensionContext?.inputItems.first as? NSExtensionItem else {
                fatalError()
        }

        for attachment in item.attachments as! [NSItemProvider] {
            if attachment.hasItemConformingToTypeIdentifier(contentType) {
                attachment.loadItemForTypeIdentifier(kUTTypeURL as String, options: nil) { url, error in
                    if error == nil {
                        guard let url = url as? NSURL else {
                            self.extensionContext?.cancelRequestWithError(NSError(domain:"Url is empty",code:-1,userInfo: nil))
                            return
                        }
                        self.selectedURL = url.absoluteString

                        let defaults = NSUserDefaults(suiteName: Constants.Settings.sharedAppGroup)
                        if let arrUrls = defaults!.objectForKey(Constants.Settings.sharedURLS) {
                            // append to the existing list
                            arrUrls.appendString(url.absoluteString)

                        } else {
                            let newArrUrl = [url.absoluteString]

                            defaults!.setObject(newArrUrl, forKey: Constants.Settings.sharedURLS)
                        }
                        defaults!.synchronize()

                        self.extensionContext?.completeRequestReturningItems(nil, completionHandler: nil)

                        let alert = UIAlertController(title: "Success", message: "Added url to intrafeed", preferredStyle: .Alert)

                        let action = UIAlertAction(title: "Done", style: .Default) { _ in
                            self.dismissViewControllerAnimated(true, completion: nil)
                        }

                        alert.addAction(action)
                        self.presentViewController(alert, animated: true, completion: nil)

                    } else {
                        self.extensionContext?.cancelRequestWithError(error)

                        let alert = UIAlertController(title: "Error", message: "Error loading url", preferredStyle: .Alert)

                        let action = UIAlertAction(title: "Error", style: .Cancel) { _ in
                            self.dismissViewControllerAnimated(true, completion: nil)
                        }

                        alert.addAction(action)
                        self.presentViewController(alert, animated: true, completion: nil)
                    }

                }
            }
        }

    }

}
</code>
Answer: Ok, apparently there was a crash in the code, thus causing the Safari to freeze. On debugging the extension in Xcode, I found the issue.


Modal com Ajax PHP

Question: Olá!
Estou trabalhando com estrutura MVC e rotas e estou tentando abrir um modal com dados de um registro para poder fazer update. Para isso criei uma função no js e coloquei no link do update. Essa função faz uma requisção ajax que através de uma rota me leva até o controller e este me devolve uma página de formulário com os dados preenchidos. Porém, quando clico em qualquer item da minha tabela só abre a rota para o primeiro item. Já tentei algumas soluções usando seletores do jquery, mais ainda sim não vi solução. Ficaria grato se alguém souber o motivo.
Página com a tabela:

    <?php foreach($images as $image): ?>

            <?=$image['id'];?>
            <?=$image['title'];?>
            <?=$image['urlimage'];?>
            <?=$image['slug'];?>

                <a id="updateimg" href="#" action="dbimages/<?=$image['id'];?>/updatepage" onclick="updateimgitem()">Update
                <a id="deleteimg" href="#" data-action="dbimages/<?=$image['id'];?>/delete">Delete

    <?php endforeach; ?>

JS:
function updateimgitem() {
  $.post({
    url: $('#updateimg').attr('action'),
    dataType: 'html',
    contentType: false,
    processData: false,
    beforeSend() {
      $('#modal').find('.modal-body').html('Carregando...');
      $('#modal').modal('toggle');
    },
    success(html) {
      $('#modal').find('.modal-body').html(html);
    },
    complete() {
      $('#modal').modal('toggle');
    },
  });
}

PHP:
public function update($args) {
    $image = Image::select()->find($args['id']);
    $this->renderSrc(
        'updateimages',
        [
        'image'=>$image
        ]
    );
}

Comment: Você já conferiu se a url está com o Id certo? Se sim, posta o código PHP que recebe esta chamada, nas próximas vezes não faça print dos códigos digite-os, facilite pra quem vai tentar testar etc...
Comment: Opa, valeu a dica, já editei, era a primeira vez que postava. Mas coloquei as partes que interagem agora. Tem o formulário ainda, mas ele só pega os dados do registro e coloca na página, ta funcionando beleza pq quando adiciona um item ele funciona normal. O problema é a url e a rota mesmo, ou alguma coisa no modal.
Answer: O que está acontecendo é que quando chama  url: $('#updateimg').attr('action') ele recebe o do primeiro elemento com esta ID encontrado (não use a mesma ID em mais de 1 elemento), logo sempre será a primeira linha.
Você pode passar como parametro o ID da linha, ou mudar o Id da tag html, sugiro:
function updateimgitem(url) {
  $.post({
    url: url,
    dataType: 'html',
    contentType: false,
    processData: false,
    beforeSend() {
      $('#modal').find('.modal-body').html('Carregando...');
      $('#modal').modal('toggle');
    },
    success(html) {
      $('#modal').find('.modal-body').html(html);
    },
    complete() {
      $('#modal').modal('toggle');
    },
  });
}

No HTML:
<a id="updateimg" href="#" onclick="updateimgitem('dbimages/<?=$image['id'];?>/updatepage')">Update

Passando a url como parametro sem mudar muito seu código.
Comment: Cara, você é fera! Ficou fino. Quebrei a cabeça com algo tão simples, Mas comecei tem pouco tempo e não tinha visto essa ideia ainda, aprendi algo bem legal. Muito Obrigado!
Comment: Opa! Aceita a resposta, e é nóis! hehe

Modal com Ajax PHP


Dúvida com instrução SELECT de uma tabela auto-relacional

Question: Olá dev's eu possuo a seguinte tabela cursos(auto-relacional):
desc cursos;
+-----------+-------------+------+-----+---------+----------------+
| Field     | Type        | Null | Key | Default | Extra          |
+-----------+-------------+------+-----+---------+----------------+
| id_curso  | int(11)     | NO   | PRI | NULL    | auto_increment |
| nome      | varchar(30) | YES  |     | NULL    |                |
| horas     | int(11)     | YES  |     | NULL    |                |
| valor     | float(10,2) | YES  |     | NULL    |                |
| fk_prereq | int(11)     | YES  | MUL | NULL    |                |
+-----------+-------------+------+-----+---------+----------------+

Onde fk_prereq é a chave estrangeira que faz referência ao id do curso(da própria tabela) que é pre-requisito para o outro, logo se essa coluna assumir um valor NULL é porque tal curso não tem pre-requisito.
Tenho alguns dados cadastrados nessa tabela:
select * from cursos;
+----------+-----------------------+-------+--------+-----------+
| id_curso | nome                  | horas | valor  | fk_prereq |
+----------+-----------------------+-------+--------+-----------+
|        1 | db relacional         |    20 | 400.00 |      NULL |
|        2 | business intelligence |    40 | 800.00 |         1 |
|        3 | relatorios avançados  |    20 | 600.00 |         2 |
|        4 | logica programacao    |    10 | 200.00 |      NULL |
|        5 | ruby                  |    40 | 400.00 |         4 |
+----------+-----------------------+-------+--------+-----------+

A minha dúvida é a seguinte, se eu quiser trazer o nome, horas, valor e qual o pre-requisito desse curso, normalmente eu tentaria fazer algo como:
select      c.nome
        ,   c.horas
        ,   c.valor
        ,   ifnull(p.nome, '---') as 'pre-requisito'
from        cursos c
left join   cursos p on c.id_curso = p.fk_prereq

Porém dessa forma a projeção sai errada e o resultado que eu tenho é o seguinte:
+-----------------------+-------+--------+-----------------------+
| nome                  | horas | valor  | pre-requisito         |
+-----------------------+-------+--------+-----------------------+
| db relacional         |    20 | 400.00 | business intelligence |
| business intelligence |    40 | 800.00 | relatorios avançados  |
| logica programacao    |    10 | 200.00 | ruby                  |
| relatorios avançados  |    20 | 600.00 | ---                   |
| ruby                  |    40 | 400.00 | ---                   |
+-----------------------+-------+--------+-----------------------+

A forma correta seria fazer com essa instrução:
select      c.nome
        ,   c.horas
        ,   c.valor
        ,   ifnull(p.nome, '---') as 'pre-requisito'
from        cursos c
left join   cursos p on p.id_curso = c.fk_prereq

E o resultado seria:
+-----------------------+-------+--------+-----------------------+
| nome                  | horas | valor  | pre-requisito         |
+-----------------------+-------+--------+-----------------------+
| db relacional         |    20 | 400.00 | ---                   |
| business intelligence |    40 | 800.00 | db relacional         |
| relatorios avançados  |    20 | 600.00 | business intelligence |
| logica programacao    |    10 | 200.00 | ---                   |
| ruby                  |    40 | 400.00 | logica programacao    |
+-----------------------+-------+--------+-----------------------+

Resumindo eu não entendi o porque de uma simples troca de on c.id_curso = p.fk_prereq para on p.id_curso = c.fk_prereq, mudaria totalmente o resultado esperado, pois em uma tabela que não é auto-relacional se eu fizer da primeira forma que tentei o resultado já sai correto.
Answer: Se ler o artigo Visual Representation of SQL Joins no CodeProject irá conseguir perceber rápido o porquê do comportamento.
No seu caso seria o seguinte:

Basicamente, um LEFT JOIN permite obter todos os resultados da tabela A independentemente de existir ou não associação na tabela B, e ao mesmo tempo irá trazer os registos da tabela B associados pela chave fk_prereq à tabela A (devolvendo NULL caso contrário).

No seu caso acredito que os resultados são diferentes porque do lado esquerdo do JOIN, c.id_curso = p.fk_prereq, estava a coluna da tabela A, o que está a levar ao compilador a ideia de "trocar" as tabelas do JOIN precisamente por ser a mesma tabela em ambos os lados, por isso é que quando trocamos as colunas passa a funcionar corretamente.
Comment: Só uma correção: não é do lado esquerdo da comparação, é do lado esquerdo do `join`. O `left join` considera a tabela do lado esquerdo de `from cursos c left join cursos p`, enquanto o `right join` considera a tabela do lado direito, independente da comparação.
Comment: @LoneTonberry No relacionamento de `cursos` com `cursos`, o que determina qual tabela representa o curso e qual representa o pré-requisito são os campos linkados.
Em `p.id_curso = c.fk_prereq` você determina que neste `select` a tabela de alias `c` é o curso principal enquanto a `p` é o curso pré-requisito, como se falasse ao banco: "Quero os registros de `cursos`(alias c), e quero também o nome do `cursos`(alias p) cujos IDs sejam equivalente ao "id de pré-requisito" da minha `cursos`(alias c)"
Comment: @RonaldoAraújoAlves era isso que queria dizer, mas sim, talvez seja mais correto dizer dessa forma, até para evitar confusões. Obrigado, resposta editada.
Comment: Basicamente, se utiliza um `LEFT JOIN` então a tabela que deve estar do lado esquerdo é aquela que pretende ligar (ex.: `left join   cursos p on p.id_curso = c.fk_prereq` onde `p.idcurso` diz respeito à tabela que queremos "juntar" à principal, `cursos c`).
Comment: Como assim "trocar" as tabelas do `JOIN` ? Isso ainda ta meio confuso


Por que não devo alterar os "getter"s e "setter"s?

Question: Recentemente me deparei com um amigo falando que não é aconselhável alterar getters e setters.
Eu havia feito a alteração de um setter de uma List. Nele eu não recebia uma lista por parâmetro, mas um objeto do tipo, e dentro do método eu fazia um add na lista, isso me poupou algumas linhas de código, porém fiquei em dúvida:
Será que vale tanto a pena investir em boas práticas de programação para detalhes tão pequenos que não farão diferença em desempenho ou em complexidade de código?
Comment: A justificativa para não alterar getters e setters é quando suas classes são usadas por terceiros (por exemplo, se elas fazem parte de uma biblioteca destinada a ser usada em outras aplicações). Você deve tomar cuidado para não quebrar a compatibilidade no código que faz uso dessa biblioteca. Fora isso não há mal nenhum em alterar getters e setters quando você constata que isso pode trazer benefício para seu código.
Comment: Talvez seja uma duplicada: [Getters e setters são uma ilusão do encapsulamento?](http://pt.stackoverflow.com/q/25995/3117)
Comment: @Math creio que não dupliquei, essa pergunta se refere a encapsulamento, minha duvida é saber se é um crime como dizem fazer uma alteração nos metodos assessores asuhsau
Comment: O comentário de @Piovezan responde perfeitamente e completamente a pergunta. Só mais um detalhe: um setter que adiciona o argumento em uma lista parece estranho. De repente este foi o motivo do questionamento do seu amigo. Não que este setter esteja necessariamente errado, de repente há um bom motivo, mas talvez valha a pena você questionar este ponto específico. Quanto a alterar um setter, é simplesmente o que foi dito por Piovezan; nada mais, nada menos.
Answer: Primeiro, me parece que o exemplo citado nem é caso de usar um setter como ele costuma ser definido. Um setter é um método que recebe um valor que normalmente já iria em um campo, eventualmente faça algum processamento antes e/ou depois de atribuir para um campo privado que ele está encapsulando.
A descrição indica que esse é um método que pega um valor diferente e manipula um campo privado que tem outra função, ou seja, o acesso ao campo é indireto. Isso costuma ser recomendado sempre que faça sentido. Sempre que possível é melhor ter métodos que fazem algo mais específico do que um método que só serve para fazer uma atribuição.
Agora, todos os métodos públicos, ou mesmo campos que eventualmente sejam públicos fazem parte de um contrato que você definiu com que vá ser o consumidor desta classe. Você pode mexer quanto quiser em qualquer tipo de método, inclusive getters e setters, desde que não quebre esse contrato. Uma das coisas que não deve fazer é trocar a assinatura do método. Mas nem precisa, basta criar um novo método com nova assinatura (mesmo que tenha o mesmo nome) que faça o que deseja agora e mantenha as duas versões. Se for o caso até anote esse método como obsoleto para evitar quem está usando que deve procurar a alternativa. Mas não apague algo que está disponibilizado publicamente.
Sempre deve fazer isso? Não. Se você puder garantir que não terá problemas, pode remover o que não é mais usado. Se a classe só é usada internamente você pode mexer em todo código que a consumiu, ou ainda se pode garantir que nada consumiu este método, mude. Você, procure os códigos afetados, faça o que tiver que fazer e seja feliz. Não dê atenção para quem fica pondo regra sem saber o seu caso real.
Se não quebrar contratos mude como quiser.
Mas note que eu não sei qual é o seu caso. Então não estou dizendo o que deve fazer. Estou só dando o subsídio para ter um pensamento crítico, saber onde dá problema e onde não dá, agora você analisa seu caso e tome uma decisão.
Algumas coisas que podem ajudar:

Getters e setters são uma ilusão do encapsulamento?
Propriedade Vs variáveis
Por que é uma má prática ter atributos int?
Quando usar Setters e Getters?
É realmente necessário usar métodos para mutator e acessor (setter e getter) no PHP? E o desempenho?
Getters e Setters só podem "andar" juntos?

Coloquei no GitHub para referência futura.
Answer: Não há nada de errado em alterar o get e set. O get e set são apenas um padrão de nome adotado no Java para acessar as informações internas de um objeto.
Por exemplo, ao setar um apelido em uma classe Pessoa, você pode querer tratar espaços extras, validar se o apelido respeita o tamanho limite, etc dentro do set do apelido. Ou seja, você passa a responsabilidade para a própria classe tratar isto, o que é perfeitamente válido do ponto de vista de orientação à objetos.
Talvez exista dentro da aplicação na qual está trabalhando uma espécie uma convenção que set e get devam retornar exatamente o valor dos campos nos quais eles correspondem. Talvez esta classe que você alterou seja apenas para carregar dados de um lado ao outro. Enfim, em geral, este tipo de convenção com get e set é bem comum nos projetos, mas não existe nenhum problema em alterar o comportamento deles, depende mesmo do contexto na qual aquela classe encontra-se.

Eu havia feito a alteração de um setter de uma List. Nele eu não
  recebia uma lista por parâmetro, mas um objeto do tipo, e dentro do
  método eu fazia um add na lista, isso me poupou algumas linhas de
  código

Sua ideia faz todo sentido. Só me parece que chamar este método de set não foi a melhor decisão. Poderia ser um adicionar ou add, pois você não está definindo (set) uma lista para a classe, você está adicionando (add) um elemento na lista interna da classe. Inclusive, talvez o próprio método de set desta List nem deveria existir. Enfim, são só exemplos de como existem várias situações.


What is proper way to add global css style in react component if I am using styled Component?

Question: Right now, I figure out that I have two way to do this:
One , I am putting global style such as in the App.css and then import them in the App.js
:root {
    box-sizing: border-box;

    font-size: 62.5%;
}

*,
::before,
::after {
    box-sizing: inherit;
    margin: 0;
    padding: 0;
}

Another way is to use GlobalStyles that provide by styled Component.  Which way should I do ?
Thanks for the help!
Answer: If you using a library you should stick to its API.
Meaning using createGlobalStyle.

A helper function to generate a special StyledComponent that handles global styles.

In more advanced use cases (like having a theme) your only option to alter the global styles will be using the pre defined API.
As a side note, you can do it in more than two ways (BUT DONT DO IT), like querying the DOM and editing the style.


Venn Diagram QS

Question: Each of a group of 50 students studies either French or Spanish but not both, and either math of physics but not both. If 16 students study French and math, 26 study Spanish, and 12 study physics, how many studies both Spanish and physics?
The answer is 4 but I am not sure how to use a venn diagram to find that. A venn diagram would help a lot!
Answer:
Let $E$ be the set of all 50 students. Let $A$ denote the set of students studying french, $B$ the set of students studying spanish, $C$ the set of students studying math and $D$ the set of students studying physics.

Your hypotheses are that
$$ A\cap B=\emptyset,\quad C\cap D=\emptyset\quad A\cup B=E,\quad C\cup D=E$$
and also that
$$ |A\cap C|=16,\quad |B|=26, \quad |D|=12.$$
You want to know $|B\cap D|$. First off, you have
$$|C|=|E|-|D|=50-12=38$$
$$|A|=|E|-|B|=50-26=24$$
because they are disjoint. Furthermore, because $(A\cap C)\cup(A\cap D)=A$, with these being disjoint, this shows
$$|A\cap D|=24-16=8.$$
The same reasoning applies to $(B\cap D)\cup (A\cap D)=D$, and it gives
$$|B\cap D|=12-8=4$$
I hope this helped. The Venn diagram follows quite easily form this.
Answer: Here is a Venn diagram:

The $0$'s all follow from the fact that no one studies 1,3, or 4 subjects.
We know:
$$X+Y+Z+16=50$$
$$X+Y=26$$
$$X+Z=12$$
So:
$$X+Y+Z=34$$
$$Z=34-(X+Y) = 34-26 = 8$$
$$X = 12-Z=12-8=4$$

Venn Diagram QS