How to compute the centroid of a polygon in Python

Question: I am wondering if there any algorithm where I can compute the center of a polygon in OSM because I've found that each polygon has a different parameters expression:
<code>"POLYGON((-171379.35 5388068.23,-171378.8 5388077.59,-171368.44 5388076.82,-171368.89 5388067.46,-171379.35 5388068.23))"

"POLYGON((-171379.3 5374226.42,-171375.96 5374227.32,-171378.95 5374239.82,-171365.69 5374243.03,-171364.16 5374237.14,-171365.92 5374236.76,-171364.26 5374230.26,-171362.67 5374230.63,-171360.11 5374220.19,-171376.6 5374216.13,-171379.3 5374226.42))"
</code>
In this expression each one has a different number of parameters so how can i compute the centroid of it?
I am using the postgis to get the polygon information from the spatial information.
Comment: I found this code using numpy: http://oles-tutorials.googlecode.com/svn-history/r42/trunk/scipy2011/geoprocessing_tutorial/exercises/exercise4.py
Comment: ST_Centroid, as posted by MaM, will give you the answer, but if you want to understand the formula/theory, look at http://en.wikipedia.org/wiki/Centroid towards the bottom.
Answer: The polygons are described using WKT.
Using Python? Use Shapely.
<code>from shapely import wkt
p1 = wkt.loads("POLYGON((-171379.35 5388068.23,-171378.8 5388077.59,
                -171368.44 5388076.82,-171368.89 5388067.46,
                -171379.35 5388068.23))")
p2 = wkt.loads("POLYGON((-171379.3 5374226.42,-171375.96 5374227.32,
                -171378.95 5374239.82,-171365.69 5374243.03,
                -171364.16 5374237.14,-171365.92 5374236.76,
                -171364.26 5374230.26,-171362.67 5374230.63,
                -171360.11 5374220.19,-171376.6 5374216.13,
                -171379.3 5374226.42))")
print(p1.centroid.wkt) # POINT (-171373.8710815240337979 5388072.5175872016698122)
print(p2.centroid.wkt) # POINT (-171370.4190352254081517 5374229.0108996396884322)
</code>
Answer: You can use PostGIS functionality or for example the python lib shapely to realize it.


concat two arrays together in Google Big Query

Question: I'm trying to take two arrays, and concatenate the two together. I have had good success in previous iterations of my data if the data was coming from a record, but these two distinct arrays are giving me problems.
I have JSON in this structure:
{"actor": "Tim Curry", "title" : ["Rocky Horror Picture Show", "Mighty Max", "Spamalot"], "result":["Nominated for Award","Nominated for Award", "Won Whatsonstage.com Award"]}
and thus a BQ table that looks like this

I am trying to concatenate the two array together, matching up the index position from one array to the index of the other, ultimately ending up with this

I believe that I will need a statement that look something like this SELECT actor, ARRAY_TO_STRING(movie_and_award, ',    ') movie_and_award FROM t  but I just cannot figure out how is that I'm going to generatre the movie_and_award array that gets passed to ARRAY_TO_STRING.
Answer: Below is for BigQuery Standard SQL
#standardSQL
SELECT actor,
  ARRAY_TO_STRING(ARRAY(
    SELECT x || ' : ' || y
    FROM UNNEST(t.title) x WITH OFFSET
    JOIN UNNEST(t.result) y WITH OFFSET
    USING(OFFSET)
  ), ', ') movie_and_award
FROM `project.dataset.table` t

If to apply to sample data from your question - output is
Row actor       movie_and_award
1   Tim Curry   Rocky Horror Picture Show : Nominated for Award, Mighty Max : Nominated for Award, Spamalot : Won Whatsonstage.com Award


How to display, search, and edit form submissions from a table with WebForm?

Question: I am very new to Drupal and I've been recently assigned a task to make a form for a single admin to register people and their info. It's basically a registration/contact form, except these people aren't users; the admin is just recording their info in a database.  The admin needs to be able to search for a person's name through a table for a previous person's registration, and be able to click an edit link for that person as well.
I have been messing around with the WebForm module, and it is great for making the form itself, not to mention it already has a 'Results page' with a table of past submissions. However I do not know of a way to add a search functionality to the 'Results page'.
I also heard that you can put a search bar in Views module, so I messed around with getting the WebForm submission data into a table in Views, thanks to the Data and WebForm SQL Views modules. However I do not know how to put the corresponding edit link next to each of the rows in the table.
Is there a better approach to solving this problem? It seems I have to either handle adding searching functionality for a field, or making it possible to point to the WebForm edit functionality from each row of the Views table.
At this point, I am also wondering if its better to just hand code everything in php.
Answer: No, it would not be better to hand-code everything in PHP.  However, if you need heavy customization of the display of data the Webform module is probably the wrong approach.  Webform is good at getting data in but the options for getting data out are somewhat limited.
Instead, I would make a custom content type and use Views to handle the display.  To do so, navigate to /admin/structure/types/add and call it something like "People."  Once you perform the basic configuration and click save, you will be taken to the Content types administration page; click manage fields for the content type you just created.
Here, you should be able to add the same kinds of fields that you added in Webform.  This interface is not quite as clean as Webform's but it will allow you full flexibility with Views.
Once you have configured the fields as you like, go to the permissions page (/admin/people/permissions/roles) and make sure only the admin role has access to create and edit content of that content type.
Then, configure your view(s).  Basically, you'll want a view of node content of the content type you just created.  Add the fields you want to display under Fields.  To get search filters, add Filters and check Expose this filter to users.  When you set up the view(s), make sure to set the permissions using the Views edit interface so that only the admin role can access the views.
This is a very rough overview but hopefully it can get you started in a productive direction.
Comment: Thank you very much! I really appreciate the starter tips.


OpenCV camera calibration world coordinate system origin

Question: in OpenCV, what is the default world coordinate system origin after calibration of two cameras?
Answer: I believe it used to be the position of the top-left corner of the checkerboard in the first calibration image, but it may have changed. You can visualized it by writing a few lines of code that project point (0,0,0) (in calibrated scene coordinates) in all the calibration images, then plotting its projected image coordinates on top of the image themselves.
You should really not depend on it being anything meaningful, and instead locate a separate feature in 3D and roto-translate the reference frame to it after calibration.


Why exactly can you change the order of integration in a double (and triple) integral?

Question: I'm currently studying multivariable Calculus doing double and triple integrals, and I'm slightly confused on why one can change the order of integration for a double integral. I have my own explanation, but it could be wrong. Is the following reasoning correct?
Fubini's Theorem states that the double integral over a given 2D region where at least one of the variables has constants as their highest and lowest values (called a horizontally or vertically simple region, depending on which variable has the constants) is equal to the iterated integral where those constants are the outer integral's limits of integration (and the inner integral's limits are functions of the outer variable). My reasoning is: If the 2D region is describable as an equation of your two variables, say x and y, and the equation is separable, then you could simply solve for either x or y to get the inner integral's limits of integration, then see from your separated equation what endpoint values the other variable could take on. The 2D region doesn't necessarily have to have abrupt, flat lines as the endpoints for the outside-integral variable (as is depicted in pictures of these such regions in textbooks), but it does need to have endpoint values in terms of the outside variable that are constants. So, if the region doesn't have these abrupt lines to describe its endpoints for either variable, but either variable's endpoint values could be described as constants, then you could use any order of integration you like as long as your outer iterated integral has constants as the limits of integration.
Is this correct, or does Fubini's Theorem explicitly state that any order of integration is usable (as long as the limits of integration are valid)? Also, in the proof for Fubini's Theorem for Triple Integrals, does the same logic essentially hold or is there another reason you can switch the order of integration? Thank you for taking the time to read this post!
Comment: @M.Wind No!  For example, the space of functions where interchanging order is allowed is a proper vector subspace, so in **almost all** cases where both iterated integrals are well-defined, changing order is not allowed.
Comment: There are plenty of easy counterexamples, e.g., $xy(x^2-y^2)/(x^2+y^2)^3$, or $y^{-2}1_{0<x<y<1}-x^{-2}1_{0<y<x<1}$, not sophisticated at all.
Comment: The integral of a function f(x,y) over some 2D-region in the xy-plane can be thought of as constructing a square lattice of tiles dxdy, then multiplying the function value of f in the centre of the tile by this surface element, followed by summing over all elements in the region. So essentially in integration one is summing contributions. This summation can (obviously) be done in any order ! Hence it is perfectly logical and normal that changing the order of integration does not affect the result.Only in exceptional cases changing the order is NOT allowed.
Comment: The requirement for Fubini-Tonelli's Theorem is both intuitive and inherent: $\infty-\infty$ is an indeterminate, and careless manipulation of such expression may lead to different answers. There are many natural examples of iterated integrals of this form, as pointed out by the above comment.
Comment: @M.Wind No the second is not a sum of two integrals, and no you can't change the first to polars (because the double integral does not exist).
Comment: @M.Wind I give up.  You can claim whatever by twisting your claim every single time, including $1=0$ because $1=1+0=1+(\infty-\infty)=(1+\infty)-\infty=\infty-\infty=0$ as a sum of two "numbers".
Comment: That might be true at a certain sophisticated level, but in high school or elementary university courses integration is applied to calculating volumes of objects, or computing averages of functions (e.g. in statistical physics) and then changing the order is almost allways allowed.
Comment: @user10354138 Please provide an example of a 2D integration where changing the order is not allowed.
Comment: @user10354138 Your second example is a sum of two integrals. Both of them with a singularity at the origin. Just take appropriate care of the singularity, and for both terms the x,y integrations can be exchanged leading to the same correct answer. In your first example nothing special seems to occur. Hence I would simply switch from Cartesian to polar coordinates, The 2D integration can then be performed without any difficulty.
Comment: @user10354138 It is well known that a singularity can affect calculations. Therefore if one encounters a double integral with a singularity (as in your examples) it is just common sense to first deal with the singularity, so that the remaining integral becomes unambiguous. Every scientist knows this.
Comment: @user10354138 You came up with a function that has a singularity which yields a +infinity - infinity term. From this you conclude that the 2D integral does not exist. And  that changing the order or changing variables is not allowed. This is trivial. An intelligent scientist, recognizing the problem at hand, first deals with the singularity in an appropriate manner. The remaining integral then exists and allows all standard math procedures, such as changing the order of integration.
Answer: No, the reasoning is not correct.
(A baby version of) Fubini-Tonelli theorem states that, if (measurable) $f$ is absolutely integrable, or $f$ is nonnegative, on a rectangle $R=[a,b]\times[c,d]$, then the double integral does not depend on which order you integrate:
$$
\int_c^d\left(\int_a^b f(x,y)\,\mathrm{d}x\right)\,\mathrm{d}y=\int_a^b\left(\int_c^d f(x,y)\,\mathrm{d}y\right)\,\mathrm{d}x.
$$
and their common value is $\iint_Rf$.
You don't need to mess with limits when you integrate along other shapes because you can always absorb them into $f$ by sticking an indicator function
$$
\iint_S f=\iint_R f1_S
$$
where $R$ is any rectangle such that $S\subseteq R$.
Note: The technical assumption of measurability is needed even in the case $f$ nonnegative --- the usual counterexample is the characteristic function of the graph of a well-ordering of $[0,1]$.  However, any function you can explicitly write down (i.e., without using AC, CH or suchlikes) is measurable.
Comment: So if the region S lies inside R, you're saying that you're essentially integrating over the rectangular region R over which you can change integration order, but for every function value that lies inside R but not inside S, the function value is 0 so it does not play a role in the final output?
Comment: Yes, just as you can always add $0$ to a number and it won't change the output, you can always extend a function by zero without affecting its integral.  The computation difficulty with computing local inverses (when you actually try to compute the integral as a number in various examples) has nothing to do with Fubini-Tonelli, analogous to e.g., disc vs washer method in computing volume of solid of revolutions where sometimes one is doable elementarily but the other might not be.
Answer: Think of the discrete equivalent of integration.
You have a 2D domain of arbitrary shape and function values available at the intersection of grid lines inside the domain. By commutativity/associativity of addition, you can compute the total sum of these values in any order. In particular row by row and column by column. The summation limits are obtained by intersections with the outline. They can consist of several disjoint intervals.
Fubini does that in the limit, with continuous variables (which raises convergence issues), using sweep-lines. This generalizes to 3D, using sweep-planes, then sweep-lines.


NullReferenceException when using AjaxControlToolKit Gravatar control

Question: Whenever I try to add AjaxControlToolKit's Gravatar control in one of my pages the following error comes up:

I added the library on top of page as
<%@ Register assembly="AjaxControlToolkit" namespace="AjaxControlToolkit" tagprefix="asp" %>

and control as
<asp:Gravatar ID="Gravatar1" runat="server" Height="168px" Width="168px" />

And Gravatar control works well in other old ASP.NET pages of my website. But when I try to add it in new pages, it comes up with above exception. Please tell me why the exception is occuring and how can I resolve it? And also why [no relevant source lines] in the Source Error? Please also note that I am unable to drag the gravatar control onto this page from toolbox. I have to write the above code to add the control.
Comment: are you sure it because of ajaxrefrence
Comment: ya I tried removing it and it works fine when there is no Gravatar
Answer: You need to set the Email property of the gravatar.
<%@ Register assembly="AjaxControlToolkit"
  namespace="AjaxControlToolkit" tagprefix="act" %>

<act:Gravatar ID="Gravatar1" runat="server" Email="email@example.com"
  Height="168px" Width="168px" />

Update
I've just looked at the Gravatar.GetHash method.  And its first line is Email = Email.ToLower();. This will throw a null exception if the Email is null.
Comment: I am setting the email property at Page_Load(), `Gravatar1.Email = dops.getAuthEmail(up.getUserID());`
Comment: The exception is being thrown from `Gravatar.GetHash(string Email)`.  Are you sure that the email is non-null?
Comment: @ShivaPareek is this code `Gravatar1.Email = dops.getAuthEmail(up.getUserID());` executed only on initial page load (wrapped in `if(!IsPostback)` block)?
Comment: Sorry guys that was my silly mistake. The reason was the same as of @RichardSchneider that Email Property was not set. But I was setting the Email Property but the compiler was unable to reach the assignment code due to exception in calling database function. I forgot to add this code in finally block in my code. Thanks Richard..:)
Answer: If you are passing email id as a Session variable use this

Email='<%=email)%>' where "email" is your session variable .

Other wise you just need to put email id to the Email Property . Thats it !


How to Set the Last Used On Value Manually in Programs and Features

Question: I'm trying to figure out how (and if it is possible) I can set the Last Used On value for a program in Programs and Features manually.
Specifically, it's the red field in the image below. I've tried copying the format of the Installed On column as it is presented in the registry but that didn't set any value at all. I'm testing with Google Chrome if that makes any difference.
Answer: According to this Microsoft Answers discussion:

That feature is official[ly] deprecated and will no longer list a date. Raymond Chen wrote about it on the Microsoft Developer Network Blog...

The MVP making that statement then goes on to link to a Raymond Chen blog posting that discusses how Windows used to find the "Last Used" value.

In order to get the "Last Used" and "Frequency" values, Add/Remove Programs needs to know the name of the EXE so it can ask the Start menu "Hey, how often did the user run this program, and when was the last time it happened?"

But the blog post does not address the deprecation issue.
It is likely that the deprecation portion was brought up in the comments to that post, but the comments were all lost the last time the blog was migrated. (From blogs.msdn.com to devblogs.microsoft.com.)
Related: https://stackoverflow.com/questions/739839/how-can-one-manipulate-the-start-menus-recently-used-programs-list-programmat
Comment: It's not quite clear from the answer, it is not at all possible to set that field any longer? Even outside of the regular method as described in the blog post (which I am aware was removed in Windows 7)? Like, for example, editing the registry yourself to add the information?
Comment: The DidierStevens blog entries linked from https://stackoverflow.com/questions/739839/how-can-one-manipulate-the-start-menus-recently-used-programs-list-programmat discuss how to read the "Last Used" info from the registry. You can presumably use the same method in reverse to set it. Please pay attention to the multiple warnings on that linked SO page that explain why it is very likely a bad idea to do this.
Comment: Thank you for point that out, I somehow missed it. I will keep those warnings in mind, I do not intended to trample over what should be left alone. I'm simply seeking a solution to my problem!


Multiple RAID arrays in x346

Question: I have an x346 server with 3 x RAID 5 73GB U320 HDD's running ESXi with 2 VM's on it.
1 VM is an exchange server running IIS and SQL2008. The other is an applications VM running IIS.
I have another 3 x 36GB U320 HDD's and want to put these into the server as more storage, possibly on RAID 5.
What is the best way to add these drives? Is it possible to have 2 RAID 5 disk arrays? I've not had a play yet with putting the drives in.
As the 36GB drives will be used for storage which will be backed up off-site, which RAID option would be the best? I would like redundancy, but as this will be file storage ONLY (no DB, OS etc.) a backup may be sufficient.
Thanks,
JD
Answer: Whether you can put the disks into RAID depends on your RAID controller; it's probably an IBM ServerRaid, so check the documentation to see what it supports. You'll need to reboot to access the RAID controller setup though, so plan downtime.
If you want to decouple the other servers from filestorage, it may be worth creating a third VM with low resource allocation to act as a fileserver (Linux with Samba would be a good choice) and then using the new disks as the datastore for a dedicated file storage partition. You can then use a network backup solution to mirror the files offsite.

Multiple RAID arrays in x346


How does the sharp 4 chord function, aside from the diminished?

Question: I was trying out some lydian chord progressions and found that a #iv (sharp 4 minor) chord sounded really nice. How does this chord, or even a major #IV chord (although that may be equivalent to the bV chord), operate in music?
Comment: This question of mine seems greatly related: https://music.stackexchange.com/questions/64464/why-does-the-chord-progression-i-iv-i-sound-acceptable
Comment: I'm voting to close this question because "how does (a given chord) operate" is too broad to handle in a single answer. With only a handful of chords, a whooooole lot of music has been created, so it's hard to nail down what any one of those chords does in a simple way.
Answer: One example with ♯IV is in James Horner's score for Star Trek II: The Wrath of Khan.
One example with ♯iv is in John Williams' score for The Raiders of the Lost Ark.
The two-chord progressions I - ♯IV and i - ♯iv are among those mentioned in Scott Murphy's video about common two-chord progressions used in film scores:  How to Imitate a Whole Lot of Hollywood Film Music In Four Easy Steps
He calls them M6M and m6m according to his own particular way of notating, and assigns a mood to each:
I - ♯IV is associated with outer space.
i - ♯iv is associated with antagonism and danger.
Jump directly to them in the video here:
M6M or I-♯IV
m6m or i-♯iv
I haven't read, much less analyzed actual scores for these works, so the composers may well spell them enharmonically as ♭V or ♭v.  (Though ♭v seems less likely as the third would have to be spelled as  with respect to the key signature, e.g. in the key of C: G♭-B-D♭)
Comment: Are you using upper case for major triad, lower case for minor? So, in `C` major, `#IV` is an `F#` major triad and in `C` minor `#iv` is an `F#` minor triad?
Comment: @MichaelCurtis Yes, I'm using that convention to match the OP.
Answer: Quite a few, as ♯4/♭5 as a 7th is sometimes used as a tritone substitution, which can be learnt about in many q/a on this site.
Comment: Tritone substitutions are usually for the V chord, so bII. bV as a tritone substitution doesn't make sense. It would be substituting for the I chord, which I've never seen.
Comment: @Aaron - I was thinking along the lines of it replacing ^17, moving to IV or iv. Would that make sense?
Comment: That's sort of an "it depends" issue. If you think in terms of Nashville notation, there the numbers are literal scale degrees, then sure, ^b5 would make sense as a tritone substitution leading to ^4. In functional harmony terms, though, it wouldn't be a ^b5 anymore; it would be bII/IV.
Comment: @Aaron - yes, I've always had the tendency to think NNS rather than FH, and I bet those others who think like I do would see b5 written in preference to anything else. Somewhat simpler. Vive la difference!


Expected value of CDF evaluated at sample min/max, with respect to sample size

Question: I've been using simulation to investigate the behavior of cumulative density function evaluated at extreme values of a sample.
Functionally, my study has $n$ instrumented fish migrating downstream past a tracking station, according to an unknown probability density function with respect to time.  With a sample size of $n$ fish, is it possible to calculate the expected value of the total probability density ($x\times100\%$ of the underlying distribution) represented by the min and max migration times in my sample?  The ultimate goal is determining a sample size that will identify the time duration of $x\times100\%$ of the total downstream migration.
By means of brute-force simulation with n=10 and n=40 (and trying a few density functions)...
<code>nsim <- 100000
x10 <- x40 <- list(NA, NA, NA, NA)

for(i in 1:nsim) {
  # normal, mean=0, sd=1
  x10[[1]][i] <- diff(pnorm(range(rnorm(10))))
  x40[[1]][i] <- diff(pnorm(range(rnorm(40))))

  # lognormal, meanlog=0, sdlog=1
  x10[[2]][i] <- diff(plnorm(range(rlnorm(10))))
  x40[[2]][i] <- diff(plnorm(range(rlnorm(40))))

  # exponential, rate=0
  x10[[3]][i] <- diff(pexp(range(rexp(10))))
  x40[[3]][i] <- diff(pexp(range(rexp(40))))

  # uniform, min=0, max=1
  x10[[4]][i] <- diff(punif(range(runif(10))))
  x40[[4]][i] <- diff(punif(range(runif(40))))
}

sapply(x10, mean)
## [1] 0.8181371 0.8182755 0.8181157 0.8182054

sapply(x40, mean)
## [1] 0.9512289 0.9512698 0.9511661 0.9512157
</code>
What I find truly interesting is that the total theoretical density doesn't seem to depend on the underlying density function!  Not only that, but it seems to converge to $1-\frac{2}{n}$ (though not quite... some trial & error makes it look like $1-\frac{2}{n+1}$??)
Am I neglecting to think of something, or are there some interesting asymptotics at work?

Apologies for incorrect notation/terminology on my part - I've been out of grad school too long!  Let me know if I can clarify anything.
Answer:
"What I find truly interesting is that the total theoretical density doesn't seem to depend on the underlying density function!"

For continuous distributions this is not at all surprising. Consider transforming any continuous variate by its cdf $U=F_X(X)$ (i.e. the probability integral transform), which yields a (standard) uniform. When you do this, you don't change which point is the maximum, nor the height of the cdf there. So you can just work directly with the uniform, since any other continuous distribution will have the same property.
The next thing to notice is that $F_U(u)=u$, so for a standard uniform the height of the cdf is the argument itself. So now, you're just working out the expectation of the max and min. And for that, see Wikipedia on Order statistics of a uniform.
Now in your code, you appear to be looking at the range. $E(X_{(n)}-X_{(1)})$ = $E(X_{(n)})-E(X_{(1)})$ (properties of expectation), so you can just take the difference of the expectations. Now by symmetry $E(X_{(n)})=1-E(X_{(1)})$, so you just need $1-2E(X_{(1)})$. Now $E(X_{(1)})$ is the expectation of a $\text{Beta}(1,n)$ variate, which is $\frac{1}{n+1}$.  Consequently the expected value of this "cdf-range" calculation for any continuous variate is $1-\frac{2}{n+1}$.
Comment: Note that these are exact small sample calculations; no asymptotic arguments were used. It works as well for n=2 as it does for n=10,000.
Comment: Thank you, Glen - that's elegant, clear, and helpful.


How to count a group by with the last 6 months interval?

Question: I'm trying to get the count of 6 months intervals, I have a whole year, and I need to be something like it:
This is not code
IdEmpresa = CompanyID
CompanyID = 1 / MONTH(1 TO 6) / YEAR 2019
CompanyID = 1 / MONTH(7 TO 12) / YEAR 2019
CompanyID = 2 / MONTH(1 TO 6) / YEAR 2019
CompanyID = 2 / MONTH(7 TO 12) / YEAR 2019
CompanyID = 1 / MONTH(1 TO 6) / YEAR 2020
CompanyID = 1 / MONTH(7 TO 12) / YEAR 2020

And goes on, always 6 months interval
and bring the count for this interval, as you can see in the img bellow I was trying to do that with:
COUNT(C.Id) OVER (PARTITION BY YEAR(P.DATACADASTRO), MONTH(P.DATACADASTRO), C.IdEmpresa) AS PP

and after I'm putting it in a CTE Expression as you can see in the formula bellow
However I can't bring the right results
WITH SUP AS
(
SELECT DISTINCT C.Id AS IdCarro, C.Placa, P.DataCadastro,
MONTH(P.DATACADASTRO) AS MONTH, YEAR(P.DATACADASTRO) AS YEARS, C.IdEmpresa,
CASE
WHEN P.DataCadastro < DATEADD(YEAR,-1,GETDATE())
THEN '>1 YEAR'
WHEN P.DataCadastro >= DATEADD(YEAR,-1,GETDATE())
THEN '<=1 YEAR'
ELSE 'NOT FOUND'
END AS WHOLE_YEAR,

CONCAT(C.IdEmpresa, YEAR(P.DATACADASTRO), MONTH(P.DATACADASTRO), c.IdEmpresa) AS KEY_SUP_Carro,
COUNT(C.Id) OVER (PARTITION BY  DATEADD(MONTH,3,GETDATE())) AS SEMESTER,
COUNT(C.Id) OVER (PARTITION BY YEAR(P.DATACADASTRO), MONTH(P.DATACADASTRO)) AS PP

FROM Pedido P WITH (NOLOCK)
INNER JOIN Carro C WITH (NOLOCK) ON P.IdCarro = C.Id
AND C.Placa NOT IN ('') AND C.Ativo = 1 AND C.IdEmpresa IN (1, 24, 26, 27)

)
SELECT COUNT(IdCarro) AS Contagem, MONTH, YEARS, IdEmpresa, WHOLE_YEAR, KEY_SUP_Carro,
SEMESTER, PP

FROM SUP
GROUP BY MONTH, YEARS, IdEmpresa, WHOLE_YEAR, KEY_SUP_Carro, SEMESTER, PP

HAVING WHOLE_YEAR = '<=1 YEAR'
ORDER BY IdEmpresa, YEARS, MONTH DESC

(I have added IdCompany which is not showing in img)
Comment: @DaleK Thanks for your statement, just did as you said :)
Answer: I solved it this way:
just added a "case" inside my partition by which was counting my IDs.
```COUNT(C.Id) OVER (PARTITION BY YEAR(P.DATACADASTRO),
CASE
WHEN MONTH(P.DATACADASTRO) >= 1 AND MONTH(P.DATACADASTRO) <= 6
THEN 1
WHEN MONTH(P.DATACADASTRO) >= 7 AND MONTH(P.DATACADASTRO) <= 12
THEN 2
END, C.IdEmpresa) AS PULSE_IdCarro```

Then I just added the "PULSE_IdCarro" in my SUP CTE expression, it did the job.


Ajax button in list to delete row entry - submit function is called instead of callback

Question: I have a themed table on a form. To delete entries in this table I render buttons for each row having a special idx and an ajax callback for each button.
The buttons are rendered perfectly, but when I click on the button, the standard submit routine is called instead of the assigned callback routine. Is there anything I missed?
// build header for table
$pheader = array('Name','Action');
// build data array for table
$aPersonsTable = array();
foreach ($aPersons as $key => $value) {
  $form_button['button'.$key] = array(
    '#id' => 'del-p-'.$key,
    '#name' => 'del-p-'.$key,
    '#idx' => $key,
    '#type' => 'submit',
    '#value' => 'Delete',
    '#submit' => 'delete_auction_person_ajax_callback_submit',
    '#attributes' => array('class'=>array('ajax-processed')),
    '#ajax' => array(
      'callback' => 'delete_auction_person_ajax_callback',
      'progress' => array('type' => 'none'),
      'effect' => 'fade',
    )
  );
  $deleteButton = drupal_render($form_button['button'.$key]);
  $row = array($value['dname'],$deleteButton);
  $aPersonsTable[]=$row;
}

$form['persons']['ptable'] = array(
  '#theme' => 'table',
  '#header' => $pheader,
  '#rows' => isset($aPersonsTable)?$aPersonsTable:null,
  '#disabled' => TRUE,
  '#title' => 'Users currently assigned',
  '#empty' => t('No users assigned yet!'),
  '#prefix' => '
',
  '#suffix' => '
',
);

Comment: I don't see any use of [`#ajax['prevent']`](https://api.drupal.org/api/drupal/developer!topics!forms_api_reference.html/7#ajax_prevent) in your code.
Answer: Remove the '#submit' => 'delete_auction_person_ajax_callback_submit', it does not seem necessary. Adding ajax-processed class on the button doesn't seem necessary either. The function delete_auction_person_ajax_callback receives $form and $form_state, and will tell you what input was clicked that triggered the callback, from there you can do whatever it is you need to do.
I built a lot of tables this way, but I don't think I had the form items as a submit type. If I recall, I used buttons.
Answer: You set #executes_submit_callback to false on your submit button to prevent that the submit callback is executed.
$form_button['button'.$key] = array(
    '#id' => 'del-p-'.$key,
    '#name' => 'del-p-'.$key,
    '#idx' => $key,
    '#type' => 'submit',
    '#value' => 'Delete',
    '#submit' => 'delete_auction_person_ajax_callback_submit',
    '#executes_submit_callback' => false,
    '#attributes' => array('class'=>array('ajax-processed')),
    '#ajax' => array(
      'callback' => 'delete_auction_person_ajax_callback',
      'progress' => array('type' => 'none'),
      'effect' => 'fade',
    )
  );

Comment: Thanks! It doesn't work better with that line. Clicking the button still submit's the whole document instead of doing an AJAX request.
Comment: Are your rows with the `delete` button generated after an ajax callback ?
Comment: No. They are generated when loading the 'initial' page.
Answer: If you want to prevent submit, use #ajax['prevent'] attribute:
'#ajax' => array(
  'callback' => 'delete_auction_person_ajax_callback',
  'progress' => array('type' => 'none'),
  'effect' => 'fade',
  'prevent' => 'submit',
)

Comment: Thanks for that. I added the prevent line to my code but it has no effect. When I compare my rendered buttons to a working AJAX button there is a class missing in the html code of the rendered button:

`
`
There correct AJAX button looks like follows:

``

That may be the problem. But how to solve it? Manually adding the class...
Comment: ... 'ajax-processed' doesn't work.
Comment: Does not work or change anything. Button still not loading via ajax.
Comment: @kwoxer sorry to hear that, but I only pointed to a specific form api prameter. If it got faulty in the meantime, I can't do a thing about it. If your implementation is faulty, I can't know.
Comment: Yeah no problem, but someone else might try this here and it does not work. So I safe his time on trying it out :)


How do you use sum and range values?

Question: I would like to know how to sum and use range values in Python.
Let's say I want to use something like this:
 You rolled 12 dices. The numbers are 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11.
 Would you like to score the points for all different numbers (50 points)?

And how would I score the points for all numbers?
I know about for n in range(12): and random.randint(1,12) but I am not very good in Python and would like some help with this. Thank you in advance.
Comment: Are you asking what the Python function for sum is? It is `sum`, which can be fed a list. If that isn't what you are asking, just what are you asking? Have you worked through a tutorial on Python? It might help you understand how basic things like lists work.
Comment: @JohnColeman, how do I use ```sum``` though? I've seen so many examples that start with ```sum=0```, is that it? I just would like to know how to use sum and range values in a code in Python.
Comment: If e.g. `rolls` is a list of numbers in the range 1-6, then `sum(rolls)` would be their sum, with no need for looping. It really isn't a bad idea to work through a book or tutorial. See this: https://wiki.python.org/moin/BeginnersGuide/NonProgrammers for a list of resources.
Comment: @johncoleman, ok thanks.

So as a example of range 1-6, would it be this?: ```list(range(6))```
```nums = [1, 2, 3, 4, 5]```?
Comment: @BeR No it would be `list(range(1, 6))` since you want it to start with one
Comment: @u10-forward, thanks for correcting me. What else do I do? Do I do a print message with sum(rolls)?
Comment: @BeR Check my answer
Answer: Do you mean by:
print("You rolled", sum(number), "dices. The numbers are", random.sample(range(50), 12), ".")

Comment: @lbragile Sorry, realized must be someone else since both of our answers are downvoted
Comment: Yes, but I am looking for more a detailed one.
Do I do this as the end result?
```print("You rolled " + number + " dice.  The numbers are" + numbers + ".")```
Comment: Ok, I tested this out and got this result: ```You rolled  [1, 2, 3, 4, 5]  dice.  The numbers are [21, 8, 26, 23, 39, 35, 42, 37, 40, 34, 16, 27] .``` what do I do about the ```nums=[1, 2, 3, 5, 6]```? Also, was wondering if there was a way to hide the brackets for the range?
Comment: If you want to keep the numbers within the range corresponding to the number of edges on the die, check out my answer. @U10-Forward's answer gives unique numbers according to your question and doesn't take into account the number of edges or what happens in reality when you throw many dice - that is there will be repetition in numbers.
Answer: I think this is a good task with numpy.
First you should decide how many dice they want to use and how many edges they want to have on each die. Then you should roll the dice and get output for each die according to the number of edges (there will be repetition to simulate real world scenario). Lastly, you ask if they want to sum and if so do it for them using np.sum().
Full code:
import numpy as np

num_dice = int(input("How many dice would you like to roll? "))
dice_sides = int(input("How many sides per die? "))

while num_dice <= 0 or dice_sides <=0:
    if num_dice <= 0:
        num_dice = int(input("Invalid number of dice, enter a number greater than or equal to 1."))
    else:
        dice_sides = int(input("Invalid number of sides, enter a number greater than or equal to 1."))

rolled_nums = np.random.choice(range(1, dice_sides), size=num_dice, replace=True)
# If you don't want the brackets around the numbers produced by the dice rolling,
# use ", ".join(str(i) for i in list(rolled_nums)) instead of list(rolled_nums) here.
print("You rolled {} dices. The numbers are {}.".format(num_dice, list(rolled_nums)))

decision = input("Would you like to sum the points for all the rolled numbers? (y/n) -> ")
if decision == 'y' or decision == 'Y':
    print("Total sum of all the rolled numbers is: {}".format(np.sum(rolled_nums)))
else:
    quit()

Some notes to make:

You have to make sure that the user enters reasonable inputs (values greater than 0) or else your calculation is not defined.
This is done with the while loop to avoid just a single check.
Also, notice the use of format() in print() which helps keep your commands cleaner. I highly recommend using it as with more complex code, it will be a life saver. Check it out here for more details: https://www.geeksforgeeks.org/python-format-function/
If you don't want the brackets around the numbers produced by the dice rolling, use ", ".join(str(i) for i in list(rolled_nums)) instead of list(rolled_nums). This is indicated in the code with a comment

Edit:
If you don't like numpy, here is the same functionality using just import random.
import random

num_dice = int(input("How many dice would you like to roll? "))
dice_sides = int(input("How many sides per die? "))

while num_dice <= 0 or dice_sides <=0:
    if num_dice <= 0:
        num_dice = int(input("Invalid number of dice, enter a number greater than or equal to 1."))
    else:
        dice_sides = int(input("Invalid number of sides, enter a number greater than or equal to 1."))

# Roll the dice one at a time and store their values
rolled_nums = []
for _ in range(num_dice):
  rolled_nums.append(random.choice(range(1, dice_sides)))

print("You rolled {} dices. The numbers are {}.".format(num_dice, rolled_nums))

decision = input("Would you like to sum the points for all the rolled numbers? (y/n) -> ")
if decision == 'y' or decision == 'Y':
    print("Total sum of all the rolled numbers is: {}".format(sum(rolled_nums)))
else:
    quit()

Again, you can remove the brackets from the list of numbers using the method described above (point 3.)
Comment: Numpy is very powerful for operations on mathematical structures (which might be very useful for you), but ok let me see what I can do.
Comment: This is mad helpful, and is exactly what I am looking for. I'll look into numpy once I am done with this project. Thank you my dude!
Comment: Hey, I tested out your code and saw that it worked - however I think this is too complex for me and that the code I'm learning is only requesting ```import random```, thus ```random.randint(1,12)```, is there any way you would be willing to edit that?
Comment: You want to import random rather than import numpy?
Comment: To re-clarify for the brackets, is this example correct? ```rolled_nums = []", ".join(str(i) for i in list(rolled_nums))```?
Comment: In the "random" example use `", ".join(str(i) for i in rolled_nums)` inside the format() function so `print("You rolled {} dices. The numbers are {}.".format(num_dice, ", ".join(str(i) for i in rolled_nums)))`. join() takes the list of strings which is formed by the `str(i) for i in rolled_nums` and joins each element while separating them by ", "

How do you use sum and range values?


Busca dinamica com filter

Question: Preciso fazer uma busca dinamica de um json, até então funciona porem ela só acha se eu digitar no input a palavra exata que há dentro do json, gostaria q eu escrevesse "i" e começasse a parecer os resultados com a letra "i"
  let pesquisa = $('#searchBar')

  pesquisa.keyup(() => {

     let searchVal = pesquisa.val()

     let search = dataJson.filter(search => search.assunto == searchVal || search.projeto == searchVal || search.empresa == searchVal)
     console.log(search)
     listNotes(search)
})

o dataJson tem esse escopo:
        {
        "id_note": "2019",
        "data": "2021-09-01",
        "start_hour": "08:59",
        "end_hour": "12:15",
        "tipo": "teste",
        "assunto": "",
        "empresa": "teste",
        "obs": "teste",
        "id_usuario": "3",
        "projeto": "",
        "duracao": "03:16",
        "log_hora_start": "12:15",
        "log_hora_end": "12:15",
        "data_br": "01\/09\/2021"
    }

Comment: 1- Onde diz busca dinâmica, não seria busca parcial? 2- Aqui *"preciso fazer uma busca dinamica de um **json**"* mas aqui `let search = dataJson.filter(search =>.....` o trata como um array e posteriormente o descreve com um objeto literal, qual é o formato de `dataJson`? Favor [edit] a pergunta e elucubrar as questões levantadas.
Answer: Pelo que eu entendi, o dataJson deveria ser um array, certo?
Se sim, o problema é a comparação que você está fazendo. Utilize o método includes da string.
A sua pesquisa dentro do filter deveria ser mais ou menos assim.
pesquisa.keyup(() => {
  const searchVal = pesquisa.val()

  const result = dataJson.filter(
   ({ assunto, projeto, empresa }) =>
     assunto.includes(searchVal) ||
     projeto.includes(searchVal) ||
     empresa.includes(searchVal)
  )

  console.table(result)
  listNotes(result)
})

Busca dinamica com filter


How to set source type for FTP in java

Question: we use
.........
.....
put "C:\Users\rahulsri\Desktop\backup\Zerty\test.CBL" /QSYS.LIB/XYZ.LIB/QSRC.FILE/test.MBR
quote RCMD CHGPFM FILE(XYZ/QSRC) MBR(test) SRCTYPE(CBL) TEXT('test')
.........

for file uploading, here SRCTYPE(CBL) is for specifying the source type which i also want to specify at my java Code by using FtpClient class so what are the method to set the source type here, or other mean how can we set it.
Comment: FtpClient from `sun.net.ftp`, or from apache-commons-net?
Answer: You can use the sendCommand method to send arbitrary commands to the remote server.
client.sendCommand("RCMD CHGPFM FILE(XYZ/QSRC) MBR(test) SRCTYPE(CBL) TEXT('test')");

From the documentation:

Sends an FTP command with no arguments to the server, waits for a reply and returns the numerical response code. After invocation, for more detailed information, the actual reply text can be accessed by calling getReplyString or getReplyStrings.
Comment: can you hint out me for deleting the whole directory's file and directory as well? i am new in this.
Comment: FTP servers typically don't have a "recursive delete" command. You have to descend into the subdirectories and delete the files one by one before you can delete the subdirectory. See also http://stackoverflow.com/questions/1931894/ftp-protocol-and-deleting-directories

How to set source type for FTP in java


I don't understand normal probability distribution...

Question: So I'm on the Wiki page for normal distribution.
Let's say you have a standard normal distribution $X \sim \mathcal{N}(0,1)$ and you do the probability density plot so that when $X = 0$, $y$ is 0.4.
What does that 0.4 mean?  Does that mean there's a 40% chance that the value is exactly 0?  That doesn't seem right.  I don't get how to interpret the $Y$-axis.
Comment: No, it means that the probability that you'll be in the range $(-\epsilon,\epsilon)$ will be approximately $\epsilon \cdot .4$, when $\epsilon$ is small. Specifically, $\lim_{\epsilon\to 0+}\frac{1}{\epsilon} P(-\epsilon0$ small." That might be a big error or .a small error. As a professor of mine used to say, "An approximation of a number is any other number." Also, it should be $2\epsilon f(0)$ - I forgot to double it since the length of the interval of $(-\epsilon,\epsilon)$ is $2\epsilon.$
Comment: Basically, with continuous probability densities, the probability of any particular value is $0$, we need to consider the probability of being in subsets.
Comment: @ThomasAndrews Thanks!  I will have to think about this.
Comment: An alternative way to think of it is that $\int_{a}^{b} f(x)\,dx = P(a\leq X\leq b)$ where $f(t)$ is the PDF.
Comment: @ThomasAndrews So this is the case for any PDF - in terms of interpretation?  So if ϵ is 0.5, that means the probability of X being between -0.5 and 0.5 in a standard normal distribution is roughly equal to 0.5 * 0.4 = 0.2?
Answer: Here is your plot:

Correct to four places, the exact value of the density function at $z = 0$ is $\varphi(0) = \frac{1}{\sqrt{2\pi}} = 0.3989.$ (Exact computation in R statistical software, in case you're interested.)
dnorm(0)
## 0.3989423
1/sqrt(2*pi)
## 0.3989423

Areas under the density curve, correspond to probabilities. Suppose I take
a narrow interval around $0,$ say $(-0.1, 0.1),$ which is of width $0.2.$
Then $P(-.1 < Z < .1) \approx (0.2)(0.4) = 0.08,$ which is the area of a
rectangle with base $.2$ and height $.4.$ (The random variable $Z$ is standard normal.) To four places, the exact probability is a little
smaller: 0.0797. (Smaller because the density curve is a little below $0.4$
throughout the interval.)
diff(pnorm(c(-.1,.1)))
## 0.07965567

See the red rectangle in the figure below. Can you use printed tables of the
standard normal CDF to get this answer?

Maybe you can use the height of the density function at $z = 1$ to estimate
the probability $P(.9 < Z < 1.1) = 0.4839.$ (Such approximations are better
for very short intervals than for longer ones. Recall that @ThomasAndrews' $\epsilon$ is intended to be a very small number.)
dnorm(1)*.2
## 0.04839414            # approx
diff(pnorm(c(.9,1.1)))
## 0.04839406            # exact

Note: If you're looking at the R code (certainly not necessary), it might
help to know that in R dnorm is a normal density function and pnorm is a
normal CDF. (Without extra arguments, the PDF and CDF for standard normal, respectively.)


Find an example of a nonempty subset $U$ of $\mathbb{R}^2$ where $U$ is closed under scalar multiplication but U is not a subspace of $\mathbb{R}^2$.

Question: Find an example of a nonempty subset $U$  of $\mathbb{R}^2$ where $U$ is closed under scalar multiplication but U is not a subspace of $\mathbb{R}^2$. I saw other questions asking the same and some of the answers were that any two lines through the origin work. But for my example I'm not sure if I'm doing it correct:
My example: Let $U = \left\{(x,y) : y = x \right\} \cup \left\{ (x, y) : y = -x\right\}$
To show this is not closed under vector addition let $a = (x_1 , x_2)$ and $b = (y_1, y_2)$ such that $x_2 = x_1$, $x_2 = -x_1$ and similar results for $y$.
Then $a + b = (x_1 + y_1, x_2 + y_2)$ such that $x_1 + y_1 = x_2 + y_2$ and $x_1 + y_1 = -x_2 - y_2$.
This seems closed under addition since all those values are $0$. Am I doing this completely wrong?
Comment: Best not to use arbitrary vectors and give a concrete example instead $a=(1,1)$ and $b=(2,-2).$ Then $a+b=(3,-1).$
Answer: Your counterexample should be two specific vectors in $U$ (e.g., $(1,1),(1-1)$) instead of arbitrary vectors (i.e. $(x_1,x_2),(y_1,y_2)$).
Comment: So my example is correct as long as I just use specific values?
Comment: Yeah, you're correct. In general, to disprove a statement you just have to find a single counterexample.
Answer: $(1,1) + (2,-2) = (3,-1)$ which is not in $U$ though both $(1,1)$ and $(2,-2)$ are.
One example is enough to disprove closedness under sums.
Answer: The union of $x$ axis  and $y$ axis is not a subspace but it is closed under scalar multiplication.


The command is disabled and cannot be executed

Question: So, when I trying to fetch some data, RACCommand return this error.
I have a picker for example and when user scroll it, app get data from server and show them, but if user scroll fast, (previous operation in progress) RACCommand get this error:
Error Domain=RACCommandErrorDomain Code=1 "The command is disabled and cannot be executed" UserInfo={RACUnderlyingCommandErrorKey=<RACCommand: 0x174280050>, NSLocalizedDescription=The command is disabled and cannot be executed}

I know, its related with some cancel mechanism, but I tried many examples and not working as well.
Its my piece of code:
    @weakify(self);
    [[[self.viewModel makeCommand] execute:nil]
     subscribeError:^(NSError *error) {
         @strongify(self);
         [self showAlertWithError:error];
     }];

and viewModel:
- (RACCommand*)makeCommand {
    if (!_makeCommand) {
        _makeCommand = [[RACCommand alloc] initWithSignalBlock:^RACSignal *(id input) {
            return [self getVehicleMake];
        }];
    }
    return _makeCommand;
}

- (RACSignal*)getVehicleMake {
    return [RACSignal createSignal:^RACDisposable *(id<RACSubscriber> subscriber) {
        [[self.forumService getForumMakesWithYear:@([self.selectedYear integerValue])
                                         category:self.vehicleCategory]
         subscribeNext:^(RACTuple *result) {
             self.makes = result.first;
             [subscriber sendNext:self.makes];
         } error:^(NSError *error) {
             [subscriber sendError:error];
         } completed:^{
             [subscriber sendCompleted];
         }];

        return [RACDisposable disposableWithBlock:^{
        }];
    }];
}

Answer: RACCommand doesn't allow concurrent execution by default. When it's executing, it becomes disabled. If you try to execute again, it will send that error.
But you can test for that error—RACCommand has RACCommandErrorDomain and RACCommandErrorNotEnabled constants available.
@weakify(self);
[[[self.viewModel makeCommand] execute:nil]
 subscribeError:^(NSError *error) {
     @strongify(self);
     if ([error.domain isEqual:RACCommandErrorDomain] && error.code == RACCommandErrorNotEnabled) {
         return;
     }
     [self showAlertWithError:error];
 }];


Celery: Redis as broker leaving task meta keys

Question: I have celery app with Redis as broker.
The code consist of the following in a loop :
running = []
res = add.apply_async([1,2], queue='add')
running.append(res)

while running:
    r = running.pop()
    if r.ready():
        print r.get()
    else:
        running.insert(0,r)

everything works fine but when i redis-cli into redis and execute keys *
I see bunch of celery-task-meta keys.
Why arent they cleaned up?
What are those for?
--
[EDIT]
I've read about CELERY_TASK_RESULT_EXPIRES setting.
Is it possible for the task keys in Redis to be cleaned up right after the result is read rather than wait until the expiration time?
Comment: Do you know the task_id or do you have the AsyncResult of your job? If so you can AsyncResult.forget(). From the docs: Forget about (and possibly remove the result of) this task.
Comment: yes i do have AsyncResult (its the variable 'r'). so would i have to r.get() and r.forget() right afterwards?
Comment: please give it a shot, becuase I have not tried myself. I was looking into it because I have a similar issue.
Answer: From the Celery Doc:
AsyncResult.forget()
   Forget about (and possibly remove the result of) this task.

You have to first r.get() then r.forget()
But, You needn't cleaned up the keys.
For,doc say that:
CELERY_TASK_RESULT_EXPIRES
Default is to expire after 1 day.
Answer: I was having the same issue. What fixed it for me was adding app.autodiscover_tasks() to my celery.py file
Answer: I think what you are looking for is to ignore the result completely which can be done by setting this flag, 'task_ignore_result' as True. This doesn't store the result at all.
https://docs.celeryq.dev/en/stable/userguide/configuration.html#task-ignore-result


Darksky Icons wont show up using Loop

Question: I created i HTML canvas tag via loop, and I'm trying to set that tags icon from DarkskyAPI via loop also, but it wont show up.
var skycons = new Skycons({"color": "white"});
  skycons.set("icon0", Skycons = x.currently.icon);    //the icon0 is hardcoded on html
  skycons.play();
  console.log(x.daily.data)
  for(i=0;i<8;i++){

    const canv = document.createElement('canvas')
    canv.id = ('icons'+(i+1)) //i added +1 so the increment would be icon1, icon2
    canv.height = 100
    canv.width = 100
    skycons.set('icons'+(i+1), Skycons = x.daily.data[i].icon)     //but if i set the icon, match should be icon1 + x.daily.data[0].icon , icon2 + x.daily.data[1].icon......icon8 + x.daily.data[7].icon.. but the icons wont show up..

    divs.appendChild(canv)
  }

Answer: I created a new loop
for(y=0;y<8;y++){
    skycons.set('icons'+(y+1), Skycons = x.daily.data[y].icon)
  }

and remove that thing from the other loop

Darksky Icons wont show up using Loop


in R / RStudio running on Windows, can we make message(), warning() and error() use different colors in the console?

Question: I use a lot of messages e.g. message("dadida") in one of my projets, and it is becomming annoying to see all this red text everywhere, always making me wonder if there's an error or a warning hidden somewhere.
I need those messages in the end product so I can't just remove them. But if there was a way to make messages, warnings and errors appear in different colors in the console, that would solve my problem. I haven't found a way to do this.
Edit
Thanks all for your input. I hadn't realized that the red color for all those types of messages was specific to RStudio. In the RGui, all is just plain white text. If customizing the colors is not feasible in RGui, maybe it is in RStudio?
Comment: If you are on linux, this package appears to change the colors...
http://www.lepem.ufc.br/jaa/colorout.html
Comment: If you type message, warning, and stop at the console prompt, you can see the functions that are executed when a message/warning/error occur.  I suspect these functions can be modified to change the text attributes such as color/font.
Comment: Here's an old post that suggest where to change the source code to enable different color for console output.  https://stat.ethz.ch/pipermail/r-sig-mac/2010-February/007146.html
Comment: Oh it's so unfortunate, I need to work on Windows for this project. This is _exactly_ what I'd need!
Comment: On wndows, you can install cygwin, then go to the math section, and install R statistics package.  Then the previous linux solution may work on windows...
Comment: I was not able to find a solution to this problem, but [I have asked RStudio on Twitter](https://twitter.com/KirkegaardEmil/status/681829399533109249). Let's hope they answer.
Answer: While I am not aware of a way of customizing the output in RGui or RStudio for Windows, using cat() instead of message() will avoid the red text in RStudio. Instead of using
message("Hello!")

use
cat("Hello!\n")

(note the \n that is needed to get a new line).
There are some subtle differences between message() and cat(), which may be relevant when you are redirecting your output e.g. to a LaTeX document using Sweave, so cat() may not be a suitable substitute in all settings.
Answer: To make error and warning messages print in a specific color in RStudio, you have to edit your editor theme.

Find the Editor theme that you're using by going to the Appearance Preferences Pane in Global Options.

Search your machine for that editor theme (you'll probably have to replace spaces with underscores in your search).  You're looking for a file with the extension .rstheme.
Copy that file to a new location you can easily find again and rename it something like my_theme.rstheme.
Open my_theme.rstheme with a text editor
At the top of the file, you should see something like /* rs-theme-name: Example name */.  Replace that with a new title for your theme: /* rs-theme-name: My theme */.
At the bottom of the file, add this line: .GD15MCFCOTB{color: #FF0000;} replacing #FF0000 with whatever hex color code you want to use.

(I have no idea why, but the CSS class GD15MCFCOTB is what RStudio uses to designate warning and error messages.  I discovered this by right clicking on an error message in RStudio and using the HTML inspector.)

Save and close your updated .rstheme file.
Go back to RStudio, navigate to the Appearance Preferences Pane in Global Options, and click the button Add...
Select the .rstheme file you created earlier and click Open.
You should now see your theme in the list of Editor themes. Select it and click OK.  That will apply your new theme.

See this page for more info on custom themes in RStudio: https://support.rstudio.com/hc/en-us/articles/115011846747-Using-RStudio-Themes#custom-editor-themes
Comment: Thanks, I had totally forgotten I had asked that question! (Not even sure theme files existed at the time)


can't find node_export_feeds module

Question: I want to migrate nodes from a drupal 6 site into a fresh drupal 7 site.
Looking at the node export module, under *Migrating nodes between Drupal versions
* it says you need to enable node export feeds and use the feeds module in D7 to import. Obviously I downloaded and installed the node export module and enabled all the submodules, but there simply isn't any node export feeds module listed within those.
All I'm seeing listed on my sites modules page under node export is:

Node export
Node export DSV
Node export features
Node export files
Node export relation
Node export serialize
Node export XML
Answer: You must enable the Node Export Feeds module and the Feeds module on the D7 site and import the nodes via the Feeds user interface from the D6 site.
Make sure you enable the Feeds Import and Feeds Admin UI modules as well on the D7 site
Comment: That would make sense :)
Comment: sorry about that :)

can't find node_export_feeds module


Solving a Quadratic Ternary Form with Large Coefficients

Question: I encountered this expression
$$1215696x^2+566544y^2-103776z^2=0$$
which I've understood is called a "quadratic ternary form" and have been trying to find solutions $x,y,z\in\mathbb{Z}$
One can firstly remove a common factor of $48$ and obtain
$$25327x^2+11803y^2-2162z^2=0$$
At this point, the coefficients are already square free. I'm trying to follow Legendre's theorem on these forms (which I understand to characterize solvability) and Lagrange's method of descent (which I understand finds initial solutions).  I've had no luck so far.
I've noted too that each of the coefficients are congruent numbers. Specifically, they are of the form $4mn(m^2-n^2)$ for $m,n\in\mathbb{Z}$. Would this fact be enough to determine solvability?
Comment: it turns out that the only primes involved that allow this thing are $2,47.$ I encourage you to show how your equation is blocked by six primes, $11,19,23,29, 37,43.$ Slight changes in the argument each time.
Answer: This is impossible in the $23$-adic numbers. The calculation is that, if
$$ 25327 x^2 + 11803 y^2 \equiv 0 \pmod {23}, $$ then, in fact, both $x$ and $y$ are divisible by $23.$ Therefore $$ 25327 x^2 + 11803 y^2 \equiv 0 \pmod {23^2}, $$ from which we get $z \equiv 0 \pmod {23.}$ This contradicts the standard assumption that we have a solution with $\gcd(x,y,z) = 1.$
Calculations: $2162 = 2 \cdot 23 \cdot 47. \; \; \; $  $25327 = 4 + 23 \cdot 1101. \; \; \; $ $11803 = 4 + 23 \cdot 513.$
$$ 4 x^2 + 4 y^2 \equiv 0 \pmod {23}. $$
$$  x^2 +  y^2 \equiv 0 \pmod {23}. $$
ASSUME that $y$ is not divisible by $23.$ Then we can do
$$  x^2   \equiv - y^2 \pmod {23}. $$
$$  \frac{x^2}{y^2}   \equiv - 1 \pmod {23}, $$
$$  \left(\frac{x}{y} \right)^2  \equiv - 1 \pmod {23}. $$
This contradicts the fact that $-1$ is not a quadratic residue mod any prime $q \equiv 3 \pmod 4,$ which includes $q=23.$
In case of interest: by the product formula for the Hilbert Norm Residue symbol, there must be an even count of primes  which block your problem. There is no problem with the prime $2,$ but there are several others as factors.
NOTE: I like the treatment in Cassels, Rational Quadratic Forms. He makes it very clear that one must check each prime separately, and in earlier pages shows ways to accomplish that.
Comment: So if the form cannot be solved in some $p$-adic field, it follows that it is also not solvable over the integers?
Comment: @ChristianWoll True. On the other hand, for this problem, you just need to be confident in how to calculate $\pmod {23},$ basics of quadratic residues, and firm about the gcd of integers. That is my way of doing "infinite descent," if there were any solution in integers, not all zero, there would be a solution with $\gcd(x,y,z) = 1.$ Easy lemma, worth learning in detail


Place tables side by side

Question: The most elegant way to place tables side by side is enclose them inside a
 and set it with CSS like this:
#div1 {
    position:absolute;
    left:0px;
    top:0px;
    width:400px;
    height:300px;
}

But if I had 8 tables (I'm working with data so I have to use them) as I do? I have to write an id for each table?
Comment: You should use [classes](https://developer.mozilla.org/en-US/docs/Web/CSS/Class_selectors) to share common styling.
Comment: You could always float them and give them a specific width.
Comment: Your question starts with a false statement... That is surely not even close to the most elegant or even elegant. Is your question, "Do I need to give each table an ID?" If so, the answer is "No, you do not."
Answer: You can use display: inline-table, like this:
table {
    display: inline-table;
}

Working fiddle: http://jsfiddle.net/VhPeP/1/

Place tables side by side


How to add rel=author when you have "multiple authors" in one site?

Question: I would like to use Google rel=author meta tag, but I do have several authors writing in one site. I have a Drupal 7 site. Should I add a different authorship for each author?
How should I manage in that case?
I was planning to use meta tags module, (as explained here) but the only way it seems to modify all urls in order to affect different url with different meta tags.
ie: /authorname/title that way, with different urls I could create different meta tags.
Could that be a normal procedure? Or there´s another way to add the author´s context?
Or maybe you just should use one single author and avoid multiplying authorship altogether?
Ps. I don´t think this is a duplicated post, because this one refers about multiple authors, instead of just asking how to implement rel=author in D7.
Comment: [Doesn't seem like it's possible.](http://webmasters.stackexchange.com/questions/25140/how-to-implement-rel-author-on-a-page-with-multiple-authors)
Comment: If it's only one author per article then you can set the author on the node level using Metatags, as described [here](http://drupal.stackexchange.com/a/62417/5612).
Comment: Thanks for your comment (it didn´t occurr to me that I could consult webmasters forum too dóh :). But my case is slightly different: I run a website with several authors, but each "link" has a single author.
The thing is that I would like to concentrate all pages into a big "author" that´s the site name itself. As I believe I can´t do that I thought could just create a specific rel=author for each author, for each individual webpage.
Answer: This is simple.

Add a text field to the user profile at /admin/config/people/accounts/fields and call it Google Profile (or similar).
Go to the Metatag configuration page and look up the token for Google Profile.
Add this token to the Author Metatag for the relevent content type(s). The token for my setup is: [node:author:field_google_profile]
Have every author load their Google+ profile to this field in their user profile.

[EDIT] It's worth noting that Google no longer uses rel=author as a ranking factor, so this discussion is now purely academic.
Regards
David
Comment: Thanks! It looks like that´s the only available solution, to have single pages with specific authors... (How about the homepage with a sinopsis and a link to every autor latest article?)


Prove that $G$ is a tree

Question: Let $G$ be a graph possessing the property that for every two distinct vertices $u$ and $v$ of $G$, there exists exactly one $u$-$v$ path. Prove that $G$ is a tree.
Comment: So it's given that it's connected, you only need to show there are no cycles.
Comment: You need to specify your definition of tree; some authors use what you've written as the definition. See https://en.wikipedia.org/wiki/Tree_(graph_theory)#Definitions
Comment: Any connected graph that has no cycles.
Comment: Use the existence of a path to show that it's connected, and use the uniqueness to show that it's acyclic. (I'm assuming that your definition of *tree* is *connected, acyclic graph*.)
Answer: It is straightforward to show the contrapositive. Namely, if $G$ is not a tree, than either there is more than one $u-v$ path, or a disconnected pair of vertices.
If $G$ is not a tree, then it is either disconnected or contains a cycle (or both). If it is disconnected, what can you say?
If $G$ contains a cycle, call it $a_0 e_0 a_1 e_1 a_2\dots e_{n-1}a_ne_n a_0$, where the $a_i$ are vertices, $e_i$ are edges, and $a_i\neq a_j$, $e_i\neq e_j$ if $i\neq j$. How could you come up with two paths between, for example, $a_0$ and $a_n$?

Prove that $G$ is a tree


Retrieve field from xml using SQL Server 2005

Question: I've got the following sql code:
declare @x xml
set @x =

'<ResultBlock>
    <MatchSummary matches="1"><TotalMatchScore>900</TotalMatchScore>
        <Rules totalRuleCount="9">
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_SWTEL_DEMP_DEADD</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_MS</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_PAS_MS</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_CTEL_MS</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_REF</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_PAS_REF</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_CTEL_REF</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_MS_PER</RuleID>
                <Score>100</Score>
            </Rule>
            <Rule ruleCount="1" isGlobal="1">
                <RuleID>MA_REF_PER</RuleID>
                <Score>100</Score></Rule>
        </Rules>
        <MatchSchemes schemeCount="1">
            <Scheme>
                <SchemeID>7</SchemeID>
                <Score>900</Score>
            </Scheme>
        </MatchSchemes>
    </MatchSummary>
    <ErrorWarnings>
        <Errors errorCount="0" />
        <Warnings warningCount="0" />
    </ErrorWarnings>
</ResultBlock>'

select  x.value(N'RuleID', N'varchar(50)') as RuleID
from @x.nodes(N'//RuleID') t(x)

I need to retrive all the RuleID's. But the following query generates an error:
XQuery [value()]: 'value()' requires a singleton (or empty sequence), found operand of type 'xdt:untypedAtomic *'. What might be wrong?
Answer: You're close - your XPath returns a list of all the <RuleID> nodes as XML fragments - now you want to extract the actual element value, so you need to use this SQL XQuery to achieve this:
select
    x.value('.', 'varchar(50)') as RuleID
from
    @x.nodes('//RuleID') t(x)

The . says : just give me the contents of the element - that's what you're looking for, right??


"No value specified for parameter 1" ao executar PreparedStatement

Question: Estou testando um insert aqui e o seguinte erro me aparece:

Exception in thread "main" java.sql.SQLException: No value specified for parameter 1

Dao
package modelo;

    import java.sql.Connection;
    import java.sql.PreparedStatement;
    import java.sql.SQLException;
    import java.util.Calendar;

    public class PessoaDao {
        public void insere(PessoaBean pessoa) throws SQLException{

            // conectando
            Connection con = new ConexaoMysql().getConexao();

            // cria um preparedStatement
            String sql = "insert into exemplo" +
                    " (nome,numero,dataExemplo)" +
                    " values (?,?,?)";
            PreparedStatement stmt = con.prepareStatement(sql);

            // executa
            stmt.execute();
            stmt.close();

            System.out.println("Gravado!");

            con.close();
        }
    }

Bean
package modelo;

import java.util.Calendar;

public class PessoaBean {
    private int Idexemplo;
    private String nome;
    private float numero;
    private Calendar dataExemplo;

    public int getIdexemplo() {
        return Idexemplo;
    }
    public void setIdexemplo(int idexemplo) {
        Idexemplo = idexemplo;
    }
    public String getNome() {
        return nome;
    }
    public void setNome(String nome) {
        this.nome = nome;
    }
    public float getNumero() {
        return numero;
    }
    public void setNumero(float numero) {
        this.numero = numero;
    }
    public Calendar getDataExemplo() {
        return dataExemplo;
    }
    public void setDataExemplo(Calendar dataExemplo) {
        this.dataExemplo = dataExemplo;
    }
}

Main
package modelo;

import java.sql.Connection;
import java.sql.SQLException;
import java.util.Calendar;

public class Teste {
    public static void main(String[] args) throws SQLException {
        Connection c = new ConexaoMysql().getConexao();
        System.out.println("Conexão aberta!");
        c.close();

         PessoaBean p = new PessoaBean();

         PessoaDao dao = new PessoaDao();

          p.setNome("José da Silva");
          p.setNumero(1232);
          p.setDataExemplo(Calendar.getInstance());

          dao.insere(p);

    }
}

Answer: Neste método:
public class PessoaDao {
    public void insere(PessoaBean pessoa) throws SQLException{

        // conectando
        Connection con = new ConexaoMysql().getConexao();

        // cria um preparedStatement
        String sql = "insert into exemplo" +
                " (nome,numero,dataExemplo)" +
                " values (?,?,?)";
        PreparedStatement stmt = con.prepareStatement(sql);

        // executa
        stmt.execute();
        stmt.close();

        System.out.println("Gravado!");

        con.close();
    }
}

Você se esqueceu de colocar isso:
stmt.setString(1, pessoa.getNome());
stmt.setFloat(2, pessoa.getNumero());
stmt.setTimestamp(3, new Timestamp(pessoa.getDataExemplo().getTimeInMillis()));

Tem que colocar isso antes do stmt.execute();.
Além disso, é uma boa prática usar o try-with-resources para evitar que no caso de uma SQLException, você fique com recursos abertos. Desta forma, seu método fica assim:
public class PessoaDao {
    public void insere(PessoaBean pessoa) throws SQLException {

        // cria um preparedStatement
        String sql = "insert into exemplo" +
                " (nome,numero,dataExemplo)" +
                " values (?,?,?)";

        // conectando
        try (Connection con = new ConexaoMysql().getConexao();
             PreparedStatement stmt = con.prepareStatement(sql))
        {

            stmt.setString(1, pessoa.getNome());
            stmt.setFloat(2, pessoa.getNumero());
            stmt.setTimestamp(3, new Timestamp(pessoa.getDataExemplo().getTimeInMillis()));

            // executa
            stmt.execute();
        }

        System.out.println("Gravado!");
    }
}

Comment: @Jarwin Em questão de "respostas", apenas comente ao autor o possível problema. Edite apenas erros de português e marcação.
Comment: Nuss esqueci de setar ¬¬, mas blz cara valeu aí
Comment: @Jarwin Desculpe, era para ser um ponto-e-vírgula, e não uma vírgula. Já arrumei.
Comment: Tranquilo cara  ;)
Answer: É necessário informar os valores no insert, use o método set do prepared statement.
String sql = "insert into exemplo (nome,numero,dataExemplo) values (?,?,?)";
PreparedStatement stmt = con.prepareStatement(sql);

stmt.setString(1,  'valor1');
stmt.setString(2,  'valor2');
stmt.setString(3,  'valor3');

Comment: Obrigado cara ;)


How to require a password when login in

Question: I'm making a CMS for my job on Drupal 7. when i go onto the login page I'm able to access the content on the site without having to enter the password. how do i change this?
Comment: Go to the [permissions page (Administer > People > Permissions)](https://www.drupal.org/docs/7/managing-users/managing-access-control-with-permissions-and-user-roles) and remove permissions from the anonymous user, specifically `access content`.
Answer: Content created with drupal UI:
You need to configure proper user permissions for content. e.g. If you don't want to show content from Content type "Article" to anonymous user, Go to the permissions page (Administer > People > Permissions) and remove content view permissions for anonymous user.
Content Created programmatically :
1) Menu page :
While you register your custom menu with hook_menu, you should assign proper value to "access arguments". e.g.
<code>/**
 * Implements hook_menu()
 */
function mymodule_menu() {
  $items['example'] = array(
    'title' => 'Example Page',
    'page callback' => 'example_page',
    'access arguments' => array('access content'),
    'type' => MENU_SUGGESTED_ITEM,
  );
  return $items;
}
</code>
2) Custom block:
For custom blocks, you need to define your access by user role. You can assign role visibility either by drupal UI(block configuration page) or you can do same thing programmatically.
Please refer below reference.
https://drupal.stackexchange.com/a/69897/57643
After configuring user permissions over content, drupal will show access denied page if user don't have permission to view content. Its drupal's default behavior. If you want to override this behavior, you can use contributed module Redirect 403 to User Login. This will redirect user to login page instead of just showing access denied page.

How to require a password when login in


Confusion Matrix Matlab has a 0% for a class during training

Question: When I train Multi-Layered Perceptron using Matlab for 6 classes, for one of the classes I get a 0% in GREEN in the confusion matrix. This leads to to a high error percent for the overall training, validation and testing. What is the cause for this and how may I resolve this problem ?
The training data has little more than 200 instances per class. There are a total of 1225 instances.
Target file is created as follows:
If there are 2 characters say A and B in the input then for each row in input matrix for character A there is a corresponding row in Target with 0,1 and for every character B there is a 1,0 row in target. So the input nodes in the NN will be 900 and output nodes will be 2 for this example.
Thanks
Comment: Can you say more about your situation, your data, & your goals here? I'm not sure this question is answerable in its present form. Eg, what is "MLP"? What is your total N, & how many cases do you have in each class? Etc.
Comment: I have now uploaded the image of my confusion matrix that I obtain after training my MultiLayered Perceptron (MLP) Neural Network !
Comment: I am trying to train the Neural Network for handwriting recognition. Currently for only 6 characters.
Comment: Thanks for clarifying. What is your total N, & how many cases do you have in each class?
Comment: There are approximately 200 instances for each class. There are 900 input nodes and 6 output nodes. I have tried to train with a single hidden layer of 10 nodes, 20, 30, 100, 200, 600 nodes. But the error varies only slightly.
Comment: What do you mean by Total N ?
Comment: "Total N" means how much data you have in total--ie, how many patterns. If you have 6 classes w/ 200 instances each, N=1200. Often the phenomenon you describe comes when 1 class has very few instances. You should add the info above into your question. Maybe someone will know what the problem is.
Comment: Great, thank you. I'll add the details to the question
Answer: I tried to reduce the dimensions of the input layer by using a different feature vector. This helped. When the input layer has a large number of neurons then the Neural Network requires a larger number of instances to train and find the best combinations of weights. When I reduce the number of neurons in the input layer then the number the weights that needs to be updated decreases too thus the NN converges.


Why won't Net-SNMP report on snmpV2 MIBs?

Question: I am trying to get Net-SNMP to give me its configured snmpEngineID even though it looks like it's in there, but I cannot access anything in the snmpV2 MIB.
I have a CentOS 7 server on which I have installed Net-SNMP from the RHeL repos and I need to set it up so that remote management servers can monitor it using SNMPv3, for which I need the snmpEngineID.
The installation went fine and the daemon is working properly:
# snmpwalk -v 2c -c public localhost system.sysContact
SNMPv2-MIB::sysContact.0 = STRING: Martin <firstname.lastname@example.com>
#

However, when I try to retrieve the snmpEngineID it fails:
# snmpwalk -v 2c -c public localhost SNMP-FRAMEWORK-MIB::snmpEngineID
SNMP-FRAMEWORK-MIB::snmpEngineID = No more variables left in this MIB View (It is past the end of the MIB tree)
#

On doing a full debug (-D all) of the snmpget command I was provided with the follow:
...
trace: snmp_parse_var_op(): snmp.c, 164:
dumph_recv:         Name
dumpx_recv:          06 0A 2B 06 01 06 03 0A 02 01 01 00
dumpv_recv:            ObjID: SNMP-FRAMEWORK-MIB::snmpEngineID.0
trace: snmp_pdu_parse(): snmp_api.c, 4530:
dumph_recv:         Value
trace: _sess_process_packet(): snmp_api.c, 5245:
sess_process_packet: received message id#0 reqid#1594114350 len 45
trace: snmp_synch_input(): snmp_client.c, 183:
snmp_synch: Response (ReqID: 1594114350 - Cmd 162)
SNMP-FRAMEWORK-MIB::snmpEngineID.0 = No Such Object available on this agent at this OID
#

Even though the snmpwalk() should have worked I tried a direct snmpget() to the objID provided in the output:
# snmpget -v 2c -c public localhost ObjID: SNMP-FRAMEWORK-MIB::snmpEngineID.0
MIB search path: /usr/local/nom/share/snmp/mibs:/usr/local/nom/share/snmp/mibs
Cannot find module (ObjID): At line 0 in (none)
ObjID:: Unknown Object Identifier
#

As you can see this failed as well.
I think that "06 0A 2B 06 01 06 03 0A 02 01 01 00" provided in the debug output is the actual engine ID but I do't want to take that as gospel and, more importantly, I want to know why the snmpwalk and snmpget commands I am trying are failing.
I did try the OID itself, in case there were issues with the MIB file but it also failed:
# snmpget -v 2c -c public localhost .22.214.171.124.184.108.40.206.1.1.0
SNMP-FRAMEWORK-MIB::snmpEngineID.0 = No Such Object available on this agent at this OID
#

I then tried working back through the OID, walking each number. They all failed until I got to to .220.127.116.11
# snmpwalk -v 2c -c public localhost .126.96.36.199.6 | head -1
SNMPv2-SMI::snmpV2 = No more variables left in this MIB View (It is past the end of the MIB tree)
# snmpwalk -v 2c -c public localhost .126.96.36.199 | head -1
SNMPv2-MIB::sysDescr.0 = STRING: Linux 143-42-69-251.ip.linodeusercontent.com 3.10.0-1160.90.1.el7.x86_64 #1 SMP Thu May 4 15:21:22 UTC 2023 x86_64
#

.126.96.36.199.6 is the snmpV2-SMI MIB but I am at a loss to understand why this MIB is not being reported back on.
Has anyone come across this? I'm guessing it's something basic, but I certainly cannot see what or where that might be.
Your assistance is much appreciated.
Answer: OK, after spending the afternoon on this I have finally found that it is simply a security issue. I was convinced that I had put "public" in as a community name (for testing purposes) but it turns out that I hadn't.
The solution for me was to (re)add this to the /etc/snmp/snmpd.conf file:
rocommunity  MyComPw

And lo, it works:
SNMP-FRAMEWORK-MIB::snmpEngineID.0 = Hex-STRING: 80 00 1F 88 80 F9 FC C1 5F F3 BD DC 65 00 00 00
00
# snmpget -v 2c -c MyComPw localhost .126.96.36.199.220.127.116.11.1.1.0
SNMP-FRAMEWORK-MIB::snmpEngineID.0 = Hex-STRING: 80 00 1F 88 80 F9 FC C1 5F F3 BD DC 65 00 00 00
00
#

For the next person who has this issue the task is simple, always check that your security settings are correct first!


Formula to calculate amortization schedules on daily rate loans

Question: I am trying to understand how amortization schedules are created. While i can find some information based on monthly and yearly rates, I cannot find any that show how to calculate schedules based on a daily rate.
By way of example... If I want to borrow 500 over 6 months based on a daily rate of 0.8% (292% APR) how would an amortization payment schedule of Principle & Interest be calculated?
For additional context, payments are monthly. Assume the loan was started on 1 Jan with the first payment due on 1 Feb, and remaining 5 payments on the first of each month following.
I should add that I am looking for a Mortgage-Style Amortization. In this case each installment should be roughly the same amount although the proportion of the principal value should increase with each installment.
Answer: Here is a Google Sheet showing the math.
Since your payments are monthly, I am assuming monthly compounding. I took your annualized rate of 292% (2.92 in decimal) and divided it by 12 - for a monthly rate of 2.43% (0.243333 in decimal). I then plugged that in to the payment formula - and got a payment of $166.82... which then amortizes over the following six periods.


Unable to automatically track files using add -A; no errors thrown

Question: I have added a couple of files to my project, when I try to stage them for a commit by running the git add -A (I also tried git add --all',git add .` , but all approaches led to the same outcome) I get a little dot on the cross button on the terminal (which I see every time I run any command),  but nothing else happen, even after waiting for 5 minutes.
When I run git status, I get a list of untracked files, which are all the files I recently added to my project and want to add. I tried looking for the answer and found this post, but there are too many files to manually add, so I am wondering if there is an alternate way to add the files, keeping in mind that git add isn't working for me?
Update1: As requested, here is the gitignore file:
# OSX
#
.DS_Store

# Xcode
#
build/
*.pbxuser
!default.pbxuser
*.mode1v3
!default.mode1v3
*.mode2v3
!default.mode2v3
*.perspectivev3
!default.perspectivev3
xcuserdata
*.xccheckout
*.moved-aside
DerivedData
*.hmap
*.ipa
*.xcuserstate
project.xcworkspace
# Android/IJ
#
.idea
.gradle
local.properties

# node.js
#
npm-debug.log
android-ndk-r11b

Answer: I'm too low-ranked to comment on your question, but have you checked your .gitignore file(s)?
Comment: I did and didn't find anything unusual but I have pasted the contents above.
Comment: Your .gitignore looks fine. Have you tried `git add .` (`git add -A` = `git add . && git add -u`)? That should just track new files instead of adding updates from old ones. When you say you see the dot, do you mean your terminal hangs / is still processing the command? Have you tried tracking individual files to see if even that works? First step should always be to diagnose the scope of the problem.
Comment: I tried all the commands except `git add -u`, still didn't work.
Comment: Are you, technically speaking, able to `git add foo.bar` with just one file, or does that command also fail?
Comment: I am able to `git add foo.bar` successfully.
Comment: You can try `git add *`, and `git add * --force` (the latter ignores your .gitignore), which should recurse through the entire file tree of your repo if you're in the root dir, but barring those two, all I can think of is writing tree-traversing  bash script along the lines of [this.](http://stackoverflow.com/questions/21924405/depth-first-search-in-bash-script-using-simple-data-structures) Sorry I couldn't help more, best of luck.


Laravel 1215 Cannot add foreign key constraint

Question: Hello I have trouble with my database migrations in my laravel application
This is the error:
[Illuminate\Database\QueryException]
  SQLSTATE[HY000]: General error: 1215 Cannot add foreign key constraint (SQL
  : alter table `transactions` add constraint `transactions_user_sid_foreign`
   foreign key (`user_sid`) references `users` (`sid`))

This is my transactions migration:
public function up()
    {
        Schema::create('transactions', function (Blueprint $table) {
            $table->increments('id');
            $table->unsignedInteger('user_sid')->index();
            $table->unsignedInteger('store_id')->index();
            $table->unsignedInteger('value');
            $table->timestamps();
            $table->softDeletes();
        });
    }

This is the users migration:
public function up()
    {
        Schema::create('users', function (Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('email')->unique();
            $table->string('password');
            $table->unsignedInteger('role_id')->index();
            $table->string('sid')->unique();
            $table->rememberToken();
            $table->timestamps();
            $table->softDeletes();
        });
    }

And finally my foreign keys:
Schema::table('transactions', function (Blueprint $table){
            $table->foreign('user_sid')->references('sid')->on('users');
            $table->foreign('store_id')->references('id')->on('stores');
        });

Comment: What is the sequence of migration?
Answer: You can't add foreign key to a column with different type, so just change it, for example in users table:
$table->unsignedInteger('sid')->unique();


Resolvent of semicircle law

Question: I am trying to approximate the Stieltjes transform of the semicircle law.  In particular, it is known that the Stieltjes transform m(z), for z in the upper half plane, is exactly
$$
m(z) = \frac{-z + \sqrt{z^2 - 4}}{2}
$$
I would like to show that
$$
Im(m(z)) \sim \sqrt{K + y}
$$
for $z = x+ iy$, $K = ||x|-2|$ and $|x| \leq 2$. ( $a \sim b$ means there exist constants $c, C$ such that $cb \leq a \leq Cb$.)
Also,
$$
Im(m(z)) \sim \frac{y}{\sqrt{K + y}}
$$
when $x \geq 2$.
I have tried Taylor expansions with no success.
Answer: It is known that $\sqrt{a + ib} = p + iq$ with $p = \frac{1}{\sqrt{2}} \sqrt{\sqrt{a^2 + b^2} + a}$ and $q = \frac{sign(b)}{\sqrt{2}}\sqrt{ \sqrt{a^2 + b^2} - a}$.
Comment: Actually, this was the first step I tried and was unable to get the correct approximations.

Resolvent of semicircle law


Pesquisa no FullCalendar.js

Question: Como fazer que ao digitar um texto no input o FullCalendar.js ele filtra o conteudo. Já tentei o eventRender mais não tive sucesso.

document.addEventListener("DOMContentLoaded", function() {
  var calendarEl = document.getElementById("calendar");
  let calendar = new FullCalendar.Calendar(calendarEl, {
    locale: "pt-br",
    plugins: ["interaction", "dayGrid", "timeGrid", "list"],
    header: {
      left: "prev,next",
      center: "title",
      right: "dayGridMonth,timeGridWeek,timeGridDay"
    },
    customRender: true,
    editable: false,
    navLinks: true,
    eventLimit: true,
    timeZone: "UTC",
    events: {
      url: "json/events.json",
      failure: function() {
      }
    },
    eventDataTransform: function(eventData) {
      return {
        title: eventData.diaSemana,
        start: eventData.dataAssembleia
      };
    },
    eventClick: function(eventData) {
      eventData.el.style.borderColor = "red";
      alert("O Evento é: " + eventData.event.title);
    }
  });
  calendar.render();
});
    <input type="text" id="numero" placeholder="Nome do Evento" />

Comment: Nesse seu filtro você vai recarregar os dados do servidor ? ou quer filtrar os eventos que já estão setados no callendar ?
Comment: Tipo quando a pessoa digitar diaSemana só aparecer no calendario o que ela deseja
Answer: Você pode criar uma função para pegar os eventos do FullCalendar e adicionar uma class nos itens que deseja ocultar de acordo com o filtro, e chamar ela toda vez que o seu input de filtro for alterado.
Exemplo da function:
function filterCalendar() {
    var events = $("#calendar").fullCalendar('clientEvents');

    events.map(function (event) {
        console.log(event);

        // o objeto event possui todas as propriedades que voce difiniu nele.
        // Voce consegue fazer o seu filtro por qualquer uma delas, por exemplo o titulo.
        if (evento.title.indexOf($('#inputFilter').val())) {
            event.className[0] = 'filter-hidden';
        } else {
            event.className[0] = '';
        }

        $('#calendar').fullCalendar('updateEvent', event);
    });
}

E no seu cssvocê define para esta classe esconder os objetos, como no exemplo abaixo:
.filter-hidden {
    display: none;
}

Links Uteis da Doc do FullCalendar:
https://fullcalendar.io/docs/v3/clientEvents
https://fullcalendar.io/docs/v3/updateEvent
https://fullcalendar.io/docs/v3/removeEvents
https://fullcalendar.io/docs/v3/event-object

Pesquisa no FullCalendar.js


SGE/OGS 2011 breaking Ansys Workbench Mechanical launch due to network port blocked

Question: We are running a SGE / OGS compute cluster on EL6 and are trying to launch an interactive Ansys Workbench. This works using SSH with X Forwarding, but using qrsh fails to run the Mechanical component - Workbench itself does launch OK.
It looks like it cannot launch / connect to a high port it is trying to access on localhost. We think this may be an issue with the grid software? How can I allow high ports on loopback to be used? We're authenticating using kerberos across the entire computing infrastructure so it's using tickets to log in to interactive jobs.
Answer: I follow below steps to configure workbench and other interactive jobs using qrsh.

create file qlogin.sh
<code>#!/bin/sh
HOST=$1
PORT=$2

if [ "x$DISPLAY" = "x" ]; then
exec /usr/bin/ssh -p $PORT $HOST
else
exec /usr/bin/ssh -X -Y -p $PORT $HOST
fi
</code>
Now modify the configuration using qconf -mconf
<code>qlogin_command               /opt/gridengine/bin/qlogin.sh
qlogin_daemon                /usr/sbin/sshd -i -o Protocol=2
rlogin_command               /usr/bin/ssh
rlogin_daemon                /usr/sbin/sshd -i -o Protocol=2
rsh_command                  /usr/bin/ssh
rsh_daemon                   /usr/sbin/sshd -i -o Protocol=2
</code>


Como guardar valor de uma função que retorna um ponteiro char num vetor de strings

Question: Gostaria de saber como posso armazenar o retorno da função abaixo, que gera uma string aleatória, num vetor de strings com 100 dessas palavras geradas pela função, para depois fazer uma ordenação - crescente e decrescente - no vetor.
char* geraStringAleatoria(){

char *validchars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
char *novastr;
register int i;
int str_len;

// novo tamanho
str_len = (rand() % MAX_STR_SIZE );

// checa tamanho
str_len += ( str_len < MIN_STR_SIZE ) ? MIN_STR_SIZE : 0;

// aloca memoria
novastr = ( char * ) malloc ( (str_len + 1) * sizeof(char));
if ( !novastr ){
    printf("[*] Erro ao alocar memoria.\n" );
    exit ( EXIT_FAILURE );
}

// gera string aleatória
for ( i = 0; i < str_len; i++ ) {
    novastr[i] = validchars[ rand() % strlen(validchars) ];
    novastr[i + 1] = 0x0;
}

   return novastr;
}

Na função main eu consigo atribuir o retorno da função a uma string:
int main() {
    char *str;
    str = geraStringAleatoria();

   return 0;
}

Mas não sei como fazer para armazenar cada palavra gerada num vetor de strings, como se cada posição do vetor fosse uma palavra.
Comment: o que você tentou? quais problemas está enfrentando?
Comment: Tentei armazenar o retorno da função em uma matriz de string: char palavras[ i ][ j ] = geraStringAleatoria(); - sendo i o numero de caracteres e j o numero de palavras. Mas acho que isso não faz muito sentido, não sei como fazer sou iniciante, acredito que estou atribuindo tipos diferentes, e não sei como faria para armazenar o retorno da função num vetor com as palavras geradas
Comment: Outra coisa: identação não é brinquedo. Use, e use de forma a ficar mais fácil de ler seu programa.
Se tiver preguiça de identar, existem várias ferramentas para fazer isso automaticamente, tanto nos editores usados para programar como online. O único propósito de identação em um porgrama em C é tornar a leitura do program mais fácil. Se você usa uma identação inconsistente, isso fica mais difícil, em vez de mais fácil.
Comment: Ouro detalhe, na sua função de gerar strings, a linha `novastr[i + 1] = 0x0;` pode ficar fora do `for`. Não tem nenhum problema a string ser inconsistente enquanto está sendo gerada (a não ser que fosse um programa multi-thread, e houvesse outro código tentando ler a mesma estrutura de dados em paralelo)
Answer: Então - o que você precisa ter aí na sua função main é um vetor de ponteiros para strings:
cada posição no vetor vai na verdade conter o endereço de uma string.
Dessa forma, cada posição no seu vetor aponta para uma string em uma posição diferente da memória. Posteriormente, sua(s) função(ões) de ordenação só vai precisar trocar os valores que estão nessa estrutura de lugar - as strings continuarão onde estão criadas.
Você tanto pode ter um vetor de tamanho máximo fixo, declarado no programa:
main () {
   char * dados[100];
}

como pode usar declarar simplesmente que é um ponteiro para ponteiros,
e alocar memória dinâmicamente:
main () {
  char ** dados;
  int tamanho;
  tamanho = ... // obtem o tamanho de alguma fonte externa
  dados = malloc(tamanho * sizeof(char *));

}

Nos dois casos, basta fazer um loop chamando sua função geraStringAleatoria, e a cada chamada colocar o ponteiro retornado em uma posição diferente nessa estrutura.
main () {
  ...
  for (i = 0; i < tamanho; i++) {
    dados[i] = geraStringAleatoria();
  }
  ...
}

Sempre é preciso ter em mente que C não tem "strings" - elas funcionam quase como se fossem uma string, mas todas são na verdade uma sequência de bytes em um endereço de memória  - e sempre que passamos ou retornamos uma string como parâmetro, estamos na verdade passando e recuperando esse endereço (ponteiro)


Does it make sense to consider ratio of pair correlation functions of two point patterns?

Question: I have two point patterns, one is real data, the other one is simulated data from a model I constructed for the real data.
Now I want to see if the second order property of the model matches that of the real data.
What I plan on doing is to fit the pair correlation function for both real data and simulated data and take the ratio between them.
However, I do realize there are some issues with this approach in that my data is highly inhomogeneous, so misfit of the inhomogeneity in the model can cause differences in the ratio of pair correlation function.
But the main question is, assuming the first order inhomogeneity of model fits the data reasonably well, does comparing the pair correlation function correctly presents the differences in the second order property?
Any input will be helpful. Thank you very much!
Answer: The standard procedure is to generate several (e.g. 99) simulations based on the fitted model and then use these to make envelopes of the estimated pair correlation function. This allows you to see the expected variability under the model and then compare with the estimated pair correlation function from your data. This can be interpreted formally as a Monte Carlo significance test and there is a lot of literature on the topic. For a software implementation see the envelope function in the R package spatstat (disclaimer: I'm a coauthor).
Comment: Thanks for the reply. That is what I plan to do, although my apology for not emphasize on generating several simulation based on fitted model. However, I do have some question on interpreting the differences. For example, if I take the ratio between the pair correlation function of data and model, and I find that the ratio is say 1.3 at $r = 0.5$ distance, does this have the interpretation that the data is 1.3 times more likely in terms of probability to have two points at $r = 0.5$ distance compared to the model? Thanks again!
Comment: My thought is that the ratio between the pcf of data and model is a new ''pcf'' taking the model as a reference where the standard pcf is taking Poisson process as base reference. I just want to make sure my understanding is correct regarding this.
Comment: If you do simulation envelopes as suggested no ratios are involved. I think estimated ratios of pcfs are bound to be numerically very unstable (in particular at short ranges), so I would be hesitant to rely on these.