How the main works in IOS

Question: I got a doubt while working on my IOS project, for our testing purpose, we wrote a piece of code like this in main...
printf("start\n");
FILE *fp = fopen("/Users/gui_test/Desktop/ritun/hello_test/hello_test/expt.txt", "a + b");

int a = 5, b = 5;
int c = a + b;

fprintf(fp, "%d\t", c);
fflush(fp);

fclose(fp);

printf("end \n");

I have commented out the below line in main to test file writing.
return UIApplicationMain(argc, argv, nil, NSStringFromClass([ofi_video_monetAppDelegate class]));

Answer is written into file successfully but twice, Anyone have any idea why is this? Other than main() if I try anywhere else, it is writing only one time, what is happening in main.
Comment: Could it be that application is opened twice when run? Maybe debugger could be the reason for that.. In what modes have you been trying that? Debug, release, normal opening on device? It could be that main returns with a certain exit code for the first time that relaunches the application with some new parameters needed on the OS.. Anyway, you could also try to log the exit code returned by main and maybe time of execution.
Comment: Same goes for breakpoints and such tools... Actually the only indicator for such behavior I can think of is the one you made: write something into some file.
Comment: is also `start\n` logged twice? would you replace it by "start-main"? and what happens if you do no comment out `UIApplicationMain`?
Comment: No start and end are printed only once. If I not commented that line. than it is writing properly in file
Comment: My guess is that your code is duplicated. There is no other explanation I can see...
Comment: your `fopen` file mode is append.  Perhaps you are seeing duplicate entries in the file as an artifact of prior runs.
Comment: I have written this piece of code only one time, I'm deleting the created file every time.
Comment: @MaticOblak If the app run twice, that log start and end also should print right, but that is not printing.
Comment: Not really.. Every time the app starts, the log clears, right? Also if the app for some reason exited and reentered your log might not even work.
Comment: @MaticOblak Got a point to think :)
Comment: @MaticOblak Do you think break point also won't hit next time, if it launches again?
Comment: let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/19823/discussion-between-matic-oblak-and-newbee)
Answer: Returning 0 by commenting out the following line causing the main called twice internally,
UIApplicationMain(argc, argv, nil, NSStringFromClass([ofi_video_monetAppDelegate class]));

I have returned 1, it works fine, one entry in file, no duplicates.
Comment: If any one knows exact reason for that.. Please post it so everyone can know the reason.
Answer: See this Link.
It explains the use of main function.

main is a function that is where every C or C-based program begins. It
  is a reserved name, which means that you can't have a function named
  main. The word int that precedes main is a declaration of the return
  type of the function.

int main (int argc, const char * argv[])
{
        // memory management
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        // printing on the log
        NSLog (@"Hello, World!");

       [pool drain];
//The final line tells the main method to return the value 0. Remember that the int the preceded main tells the system that this function will return a value. This value is 0. By convention, a return value of zero indicates that the function was successful.
       return 0;
}

Also see NSAutoreleasePool

How the main works in IOS


Multi-Statement Arithmetic in c++

Question: This may have been asked already, but I was unable to find it on this forum. I had a general question about integer arithmetic in c++ when doing arithmetic on large integers.
unsigned int value = 500000;
value = (value * value) % 99;

The correct value to the above code would be 25, however when this is implemented in C++ I get a value of 90.
I looked at the disassembly and that gave me a slight idea as to why it may be coming back with an erroneous value, the disassembly is as follows
    unsigned int value = 500000;
    00D760B5  mov         dword ptr [value],7A120h

    value = ((value * value) % 99);
    00D760BC  mov         eax,dword ptr [value]
    00D760BF  imul        eax,dword ptr [value]
    00D760C3  xor         edx,edx
    00D760C5  mov         ecx,63h
    00D760CA  div         eax,ecx
    00D760CC  mov         dword ptr [value],edx

It appears to be placing it into a 32 bit register, and that is why the result is coming back erroneous.
Nevertheless, my question is how can I mimic the language to give me the correct answer? I'm sure there's an easy and straightforward way to do it but I'm drawing a blank.
Comment: where do you expect that huge number be put before calculating the modulus?
Comment: `value * value` is equal to 250'000'000'000. This wouldn't even fit into `unsigned long` as shown [here](http://www.cplusplus.com/reference/climits/).
Comment: Have you tried `unsigned long int` or even `unsigned long long int`?
Comment: Yes, these would work for this example, but this is a small-scale implementation of my whole code. I just want to know why this doesn't work, because I feel it should.
Comment: But why is it trying to fit the result into the unsigned int prior to performing modulus on it? Shouldn't it take 250,000,000,000 mod it by 99 and then store that into the unsigned int?
Comment: Use [boost::multiprecison](http://www.boost.org/doc/libs/1_63_0/libs/multiprecision/doc/html/boost_multiprecision/tut/ints/cpp_int.html)
Answer: You should consider using a larger integer type, such as unsigned long or unsigned long long. On my machine both of these give you eight bytes of working space, which allows for a maximum value of 18,446,744,073,709,551,615. This is comfortably large enough to fit 500000^2=250,000,000,000.
But, in my opinion, that's a poor solution. You should, instead, use better mathematics. The follow modular identity should let you do what you want:
(ab) mod n = [(a mod n)(b mod n)] mod n.

In you case, you'd write:
unsigned int value = 500000;
value = ((value%99)*(value%99))%99;

Comment: THANK YOU SO MUCH. This is very useful and I will always remember it!!
Answer: The numbers you are working with that are really big. It some other languages like python they have built in libraries that handle really big numbers in special ways because a single 32-bit integer cant hold that much. C++ does not do that, and as ForceBru put, the result is gigantic and is giving your overflow errors.
If you want to deal with long numbers you could manipulate polynomials in coefficient representation for big integers, or look for a scientific computing library online.

Multi-Statement Arithmetic in c++


Drupal commerce price: allow null value

Question: I have an e-commerce site with drupal commerce kickstart and I added an additional field called "list price" and setted it as Price field (the same type of the default price).
Now I'm trying to update some of these prices via drupal views and VBO but I can't set them to NULL, I have an error:
"Integrity constraint violation: 1048 Column 'field_list_price_amount' cannot be null"
But if I change that price manually via the standard windows and leaving the field empty, drupal accepts the update, why?!
Via VBO I can update normal prices (increase, decrease and more other things) but I can't reset them to its default values...
Answer: This would be because an empty value and NULL are two different things to a database. Deleting the value in the UI is not the same as setting it to be NULL. That field is stored in the database with the setting that I cannot be NULL and so the VBO operation is failing.
Comment: I checked the database tables regarding my filed, I allowed NULL value both in revision and field table and now it works, thank you very much!
Comment: If you are using a core field type. Changing the DB table (in a way, hacking Drupal core) to allow NULL values can potentially cause problems with your site down the road and is not recommended.
Comment: No, it isn't a core field, it's a custom field of type "price".

Drupal commerce price: allow null value


how to use getHours() in youtrack workflow?

Question: I am new to Youtrack Workflow. I am trying to create a new workflow for which I require hours from the current date-time.
I am using new Date().getHours() but it's not returning proper value.
say for example my current time is Fri Jun 12 2020 18:29:29 GMT+0530 (India Standard Time) then it should have got 18 as the current hour but, I am getting 12 as the current hour.
Also in the date-time function in Youtrack, there is no option for the same (https://www.jetbrains.com/help/youtrack/incloud/v1-date-time.html)
Please help me with this.
Answer: As of now, new Date().getHours( returns the time from the server Youtrack runs on. For example, if you run it on your own server (Standalone version), it returns the time set in your server's OS. If you run it on a Youtrack server (Incloud version), it returns the time set in our server's OS. If the server's OS fails to return the time, we fall back to the UTC time.
That's not a transparent behavior and is going to be addressed in this task in: https://youtrack.jetbrains.com/issue/JT-57972 In this task, we want to change it so that the time is returned based on your Youtrack settings. You can watch the issue to get notified of the changes made there. How to do it: https://take.ms/L0k8g (screenshot).
For now, though, if you use your own server, you can try to change the time there. Otherwise, I suggest that you get time in UTC using Date.getUTCHours() and then add constant hours to get your local time.


Override default ModelBinder in Web Api

Question: I want to override the default model binder of my Web Api project. How can do this?
More Description:
What I do now is this:
// I defined a custom model binder
public class EmptyStringToNullModelBinder : IModelBinder

//Before all my parameters in actions I use it
public IHttpActionResult PostSomething([FromUri(BinderType = typeof(EmptyStringToNullModelBinder))]string text = null,...)

There are a lot of string parameters in my whole project that assigned with this attribute. It's a little bit ugly. I want to tell to Web Api that "Use this attribute as default for all my string parameters".
Answer: ModelBinderProvider was designed to cover such scenario. This abstract class has the only method:
public abstract IModelBinder GetBinder(HttpConfiguration configuration, Type modelType);

GetBinder should return implementation of IModelBinder for the given type or null if the type could not be processed with current binder.
Here is a generic implementation of ModelBinderProvider that maps a type to a binder:
public class CustomModelBinderProvider<TModel> : ModelBinderProvider
{
    private readonly IModelBinder binder;

    public CustomModelBinderProvider(IModelBinder binder)
    {
        this.binder = binder;
    }

    public override IModelBinder GetBinder(HttpConfiguration configuration, Type modelType)
    {
        return modelType == typeof(TModel) ? binder : null;
    }
}

In WebApiConfig.Register() method set up this model binder for String type:
public static void Register(HttpConfiguration config)
{
    // ...

    var binderProvider = new CustomModelBinderProvider<string>(new EmptyStringToNullModelBinder());
    config.Services.Insert(typeof(ModelBinderProvider), 0, binderProvider);
}

Now in your controller you don't need to specify a binder type, EmptyStringToNullModelBinder will be used for string types:
public IHttpActionResult PostSomething([FromUri]string text = null,...)

Override default ModelBinder in Web Api


Average Marginal Effects interpretation problems

Question: I am running a probit regression model to test my hypothesis. As one cannot deduce the magnitude of the effect of the independent variables on my dependent one, I have calculated the average marginal effects of my regression.
My problem is, that there are AME in the output table (I used margins(regression) to calculate this) that are bigger than 1, for example, 1.2713. Does this mean that by an increase in my variable Y the chances of obtaining 1 for my X increase by 127%? Can this be? Or could there be a problem with how I operationalized by Y variable?
<code>probitdd <- glm(escape ~ avg_polity2 + log(avg_gdp) + avg_durable + log(avg_totmipopula) + avg_accountability + log(avg_libdem), family = binomial(link = "probit"), data = coilp5dd)

================================================
                         Dependent variable:
                     ---------------------------
                               escape
------------------------------------------------
avg_polity2                     -0.2
                                (0.4)

log(avg_gdp)                    0.9*
                                (0.5)

avg_durable                     -0.02
                               (0.02)

log(avg_totmipopula)            -0.7*
                                (0.4)

avg_accountability              -3.9
                                (3.3)

avg_libdem                       4.7
                                (8.1)

Constant                         6.9
                                (5.1)

m2 <- margins(probitdd)
summary(m2)

AME

1   avg_accountability  -1.0469

2   avg_durable -0.0059

3   avg_gdp 0.0014

4   avg_libdem  1.2713

5   avg_polity2 -0.0537

6   avg_totmipopula -0.0000
</code>
Comment: Can you show us the code? I suspect you are calculating the effects on the index function scale. You also try calculating it by hand using $\frac{1}{N}\sum_{i=1}^{N}\frac{\partial \Pr \left(
y_{i}=1|x_{1},...,x_{k}\right) }{\partial x_{j}}=\frac{1}{N}
\sum_{i=1}^{N}\phi \left( \alpha +\beta _{1}x_{1i}+...+\beta
_{k}x_{ki}\right) \beta _{j},$ were $\phi()$ is the standard normal pdf.
Comment: @dimitriy how can I best share my code? Just copy paste it?
Comment: Just put the probit and the AME part at the bottom of the question.
Comment: @dimitriy I hope it works like that?
Comment: You need to include the commands you used to get those results.
Comment: @dimitriy I have included them
Comment: Just to be clear, you are using https://cran.r-project.org/web/packages/margins/index.html?
Comment: Yes, I am using that
Answer: A clue as to what's happening is the presence of log()s around the names of the index function coefficients for the logged variables but their absence in the AMEs table below.
In a probit model, you have something like
$$\mathbf{Pr}[y = 1 \vert \ln(x),z ] = \Phi(\alpha + \beta \cdot \ln(x) +\gamma \cdot z).$$
The marginal effect of $\ln x$ is
$$ME_1 = \frac{\partial \mathbf{Pr}[y = 1 \vert \ln(x),z ]}{\partial \ln x}=\varphi(\alpha + \beta \cdot \ln(x) +\gamma \cdot z) \cdot \beta$$
This is constrained to be in [0,1].
The marginal effect of $x$ when you log it is
$$ME_2 = \frac{\partial \mathbf{Pr}[y = 1 \vert \ln(x),z ]}{\partial x}=\varphi(\alpha + \beta \cdot \ln(x) +\gamma \cdot z) \cdot \beta \cdot \frac{1}{x}$$
since $\frac{d \ln(x)}{dx} = \frac{1}{x}$
Given the way you specified the index function, R is helpfully calculating the average of the second quantity for you (though the $ME_1$ is reasonable too, more below). It's the multiplication by $\frac{1}{x}$ that is causing the out-of-bounds issue. I would wager that $\ln(avg_libdem)$ tends to be less than one.
You can interpret $AME_1$ as an semi-elasticity since
$$\frac{\partial \mathbf{Pr}[y = 1 \vert \ln(x),z ]}{\partial x}=\varphi(\alpha + \beta \cdot \ln(x) +\gamma \cdot z) \cdot \beta \cdot \frac{1}{x}$$ can be rearranged as
$$\frac{\partial \mathbf{Pr}[y = 1 \vert \ln(x),z ]}{100 \cdot\frac{\partial x}{x}}=\frac{1}{100} \cdot \varphi(\alpha + \beta \cdot \ln(x) +\gamma \cdot z) \cdot \beta$$
The numerator is a change in probability. The denominator is a 1% change in x. Note that without scaling by $\frac{1}{100}$, you would have a $100\%$ change in the denominator, and since derivatives are approximations of a small change, you can get very large effects when you consider a doubling.
So 1.2713 can be interpreted as the model saying that a 1% change in avg_libdem is associated with a $\frac{1.2713}{100}=.012713$ percentage point increase in the probability of escape (or 1.27 percentage points on a [0,100] scale). I like dividing since the other MEs are on the [0,1] scale to keep it apples-to-apples.
Personally, I also find the $ME_1$ more intuitive, so I would trick R by logging myself or I would just not log RHS variables (unless there was some good reason to do so, like being consistent with previous literature).
Here's some R code showing this calculation on another dataset:
<code>> library(foreign)
> library(margins)
> auto <- read.dta("https://www.stata-press.com/data/r12/auto.dta")
> auto$log.price <- log(auto$price)
> m1 <- glm(foreign ~ log.price + mpg, data=auto, family = binomial(link="probit"))
> (margins(m1))
Average marginal effects
glm(formula = foreign ~ log.price + mpg, family = binomial(link = "probit"),     data = auto)

 log.price     mpg
    0.4009 0.04127
> (AME_price_m1 <- mean(dnorm(predict(m2, type = c("link")))*m2$coefficients['log.price']*1/auto$price))
[1] 7.310459e-05
> m2 <- glm(foreign ~ log(price) + mpg, data=auto, family = binomial(link="probit"))
> (margins(m2))
Average marginal effects
glm(formula = foreign ~ log(price) + mpg, family = binomial(link = "probit"),     data = auto)

    price     mpg
 7.31e-05 0.04127
</code>
Here 0.0000731 means that a $1 increase in price is associated with an infinitesimal change in the probability of foreign manufacture, on a [0,1] scale.
And 0.4009 means that $1\%$ increase in price is associated with an $\frac{0.4009}{100}=0.004$ increase in the probability of being foreign on a [0,1] scale. Or a doubling of price is associated with 40 percentage point increase on a [0,100] scale.
Comment: Thank you very much for this very very helpful answer! I really appreciate it!!
Comment: @EmStaLo No need to thank me. Just upvote and/or pick it as the answer by clicking on the check mark on the left.


Prove that those subspaces are $T_a-invariants$.

Question: Prove that, for $A ∈ O_n$, the subspaces of symmetric and anti-symmetric matrices ("$M$") of $n$ order are $T_a-invariants$.
where $T_A |= A^{-1}MA$ .

So... ...the definition of $T_A$ implicates that every $M$ is diagonalizable for an opportune $A$?
Wikipedia says this is the spectral theorem :P...
for the definition of $O_n$ i can say $T_A= ^tAMA$
Nothing else i can say :/
Comment: and yeah i really don't have many notions about orthogonal matrices except the basic definition and something else
Answer: Hint: If if $A\in O_n$ then $A^{-1}=A^T$. So if $M$ is symmetric or anti-symmetric, what does that say about the relationship between $A^{-1}MA$ and $(A^{-1}MA)^T$?
Comment: for symmetrical matrices $(A^{-1}MA)^T$=$T_A (M)$ .  This tells me that if i transpose the $T_A$associated matrix and apply it on a symmetric matrix i have the same result...
Comment: Exactly, so $M$ symmetric implies $T_A(M)$ is again symmetric, which is precisely what you need to show that symmetric matrices are a $T_A$ invariant subspace.
Comment: hum...  ...we have just transposed the expression that defines what $T_A$ does and obtained the same result. Sure that's enough to say that all the symmetrical matrices are $T_A-invariant$?
Comment: Yes, a subspace $W$ is $T$ invariant if given any element $M\in W$, we have $T(M)\in W$ as well.. In your case, $W$ is the space of symmetric matrices and the transformation is $T_A$. We transposed the result of $T_A(M)$ because we need to check if $T_A(M)^T=T_A(M)$ to determine if $T_A(M)$ is symmetric.
Comment: Yay, problem solved...    ...tomorrow will see about anti-symmetric. 1:10 am :(
Comment: So, for Antisymmetric matrices i have $ (T_A)^t=A^{-1}M^tA $...    ...$^tM$ still anti simmetric.
Comment: That is what you need to show, though what you wrote is sort of nonsense. We need to check that the transpose of the _image_ of an anti-symmetric matrix under $T_A$ is anti-symmetric The transpose of the transformation itself $(T_A)^t$ makes no sense here. So, if $M$ is anti-symmetric then $(T_A(M))^T=(A^{-1}MA)^T=\ldots=-A^{-1}MA=-T_A(M)$. You should make sure you're able to fill in the $\ldots$ there.
Comment: il M is anti-symmetric then $(A^{-1}MA)^t = A^{-1}-MA = -A^{-1}MA$ wich says the result still antisymmetric.
Comment: That's correct, though I would write $A^{-1}(-M)A$ so that it doesn't look like subtraction.
Comment: Yayyy ive got now, thanks :)


Is the normal distribution a better approximation to the binomial distribution with proportions near or far from 0.5?

Question: From the Online Stat Book:

I don't understand this:

The accuracy of the approximation depends on the values of N and π. A rule of thumb is that the approximation is good if both Nπ and N(1-π) are both greater than 10.

Let's assume I have an unfair coin, so I get heads with a probability of 0.2. So what? I still can find the mean of the distribution, the SD. I next can find the Z-scores, and then use the normal calculator. Why would the returned probability be less accurate?
Comment: Note that the screen capture makes the Greek letter pi look like an "n."
Comment: What is not clear to me is what n and N are.  My presumption is that n is the sample size and N would be the population size but this is a problem involving an infinite population.  But on the other hand it looks like N and p are the parameters of the binomial distribution. The point of the question relates only to the normal approximation and the sample estimate of p, So consider the sample estimate of p from a sample of size N and calculate its variance when the true parameter is  .2 and when it is .5. Which one has the smaller variance. It does not require a simulation to answer it.
Comment: But if you do a simulation with p=.2 and N=10 and look at the histogram from repeating the process say 1000 times and do the same for p=.5 you can visually compare the histograms and see which one looks closer to a normal distribution.
Comment: @MichaelChernick - I have no Java enabled in my Chrome browser. It looks like this language is not much used nowadays (I'm not that computer savvy, but it looks so to me)..
Comment: @MichaelChernick - I found [this page that explained the issue to me](https://onlinecourses.science.psu.edu/stat414/book/export/html/70)
Comment: Those histograms tell the story and maybe better than my words.
Comment: I agree, what looks like an $n$ is actually a $\pi$ (representing a population proportion). One widely used computer typeface ("font") makes them almost indistinguishable.
Answer: NOTE: Following up on @whuber's comment, I realized that I was imposing aesthetic constraints on the plotting of the values in terms of the breaks options in hist(). Running the same simulation with the same seed, a symmetrical illustration is now generated. I believe this addresses the issue.

You may want to refer to this post by Glen_b.
This would be the shape of the simulation:

I ran $100,000$ simulations of random values extracted from a binomial distribution of $10$ trials with a probability of success of the individual Bernoulli experiments of $0.2$, $0.5$ and $0.8$, respectively. Clearly $p=0.5$ approaches a normal distribution much closer, and the more extreme probability values result in markedly skewed distributions.
Comment: This is an insightful reply (+1).  Unfortunately the figure is suspect: the histogram for $p=0.5$ is shifted one-half unit to the left of where it should be, causing a mismatch between it and the plot of the approximating Normal density (which is correctly centered at $0.5$).  The histograms for $p=0.2$ and $p=0.8$ are not mirror images of each other, but they ought to be (and their approximating Normal density plots *are* mirror images).  Since you are relying on the figure for your demonstration, it is important to make it accurate.  Consider drawing barplots of the Binomial probabilities.
Comment: I would just tend to think of the "empirical probability" $\hat{p}=n/N$. This will always equal $p$ in expectation, and it makes it clearer that 0.5 will be the symmetric and "least constrained" case, whereas higher/lower values will tend to have a skewed PDF that will "hit the wall" at right/left (i.e. 1 or 0).
Comment: One thing to keep in mind is that ultimately it's the cdf we are using when we approximate (such as to get a tail area for example).  That's not to suggest there's something wrong with this approach, especially for visualization purposes (it's got a long pedigree, for sure going right back to the earliest days). Ultimately one must judge the quality of the approximation for ones own particular purposes by seeing how it behaves; rules of thumb are generally either too strict or not strict enough. They can be a starting point for an investigation of the approximation in some particular instance.
Answer: The rule of thumb says that both $N\pi $ and $N(1-\pi)$ should be $>10$. For $\pi=.5$ this demands $N>20$. But for $\pi=0.2$ (as well as for $\pi=0.8$) it demands $N>50$. So we see that the "approximability" kicks in a lot earlier when $p=.5$.


Parametric line segment in 3-space

Question: If one wants to parametrize a straight line segment in $\mathbb{R}^3$, which goes from $(1,0,0)$ to $(0,1,\pi/2)$, would this approach be correct?
First, we come up with the $xy$-plane equation, which would be $y=1-x$, and then we come up with, say, the $yz$-plane equation of the line, which appears to be $z=\frac{\pi}{2} y$. Next, we simply take $x=t$, $y=1-t$, $z=\frac{\pi}{2}(1-t)$, according to the two plane level curves of the line above.
Conceptually, I think, this should be true, just want to make sure, as sometimes what seems true may contain subtle flaws.
Comment: I gave you another answer below but it looks like your parametric equations will work too but in the opposite direction (as $t$ increases).
Answer: A vector that goes from $\hat{p_1} = (1,0,0)$ to $\hat{p_2}= (0,1,\pi/2)$ is $\hat{v}= \hat{p_2}-\hat{p_1}= (0-1,1-0,\frac{\pi}{2}-0) = (-1,1,\frac{\pi}{2}).$ So if $t$ is a paramenter such that $t\in\mathbb{R},$ then a parametric vector equation in $t$ is $\hat{L}=\hat{p_1}+t\hat{v}$ or $\hat{L} = (1,0,0)+t(-1,1,\frac{\pi}{2}).$
The parametric equations can be obtained from $\hat{L}$ since $\hat{L} = (x(t),y(t),z(t)),$ so we have $x(t) = 1-t, y(t) = t, z(t)=t\frac{\pi}{2}.$
I hope this helps.

Parametric line segment in 3-space


How to allow node authors to mark the best comment and to promote this comment on the top of list

Question: In my project comments are prices so its important that commenters see author's choice. I want to allow authors to choose the best comment that would get this comment promoted on the top of a comments list. Can I do it with Rules or some other ways?
Comment: Is the node author the only person who can choose the best comment? Will he only pick one comment as the best? If so, you can probably use the Flag module (https://www.drupal.org/project/flag) and the Views module (https://www.drupal.org/project/views)  for this.
Comment: well, i have created global flag for comments and it works nice. Its nice that it offers as option  permission to use flag only for node authors.Now i need some action or rule to be triggered to promote flagged comment on top (change the weight in list). Which  action or rule i should look at?
Answer: As discussed in the comments above, you can create a global Flag, say Best price, for comments. In order to reorder the comments, you can create a comment View which displays all comments of a certain node with the flagged ones on top. Afterwards, display the associated block on the node's page.
Maybe there is an easier way to reorder the comments, but this should at least work and illustrate the strength of the Views module. Underneath is my exported View, which you can easily import and adapt to your needs if necessary:
<code>$view = new view();
$view->name = 'reordered_comments';
$view->description = '';
$view->tag = 'default';
$view->base_table = 'comment';
$view->human_name = 'Reordered comments';
$view->core = 7;
$view->api_version = '3.0';
$view->disabled = FALSE; /* Edit this to true to make a default view disabled initially */

/* Display: Master */
$handler = $view->new_display('default', 'Master', 'default');
$handler->display->display_options['use_more_always'] = FALSE;
$handler->display->display_options['access']['type'] = 'perm';
$handler->display->display_options['access']['perm'] = 'access comments';
$handler->display->display_options['cache']['type'] = 'none';
$handler->display->display_options['query']['type'] = 'views_query';
$handler->display->display_options['exposed_form']['type'] = 'basic';
$handler->display->display_options['pager']['type'] = 'none';
$handler->display->display_options['pager']['options']['offset'] = '0';
$handler->display->display_options['style_plugin'] = 'default';
$handler->display->display_options['row_plugin'] = 'comment';
/* Relationship: Comment: Content */
$handler->display->display_options['relationships']['nid']['id'] = 'nid';
$handler->display->display_options['relationships']['nid']['table'] = 'comment';
$handler->display->display_options['relationships']['nid']['field'] = 'nid';
$handler->display->display_options['relationships']['nid']['required'] = TRUE;
/* Relationship: Flags: best_price */
$handler->display->display_options['relationships']['flag_content_rel']['id'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['table'] = 'comment';
$handler->display->display_options['relationships']['flag_content_rel']['field'] = 'flag_content_rel';
$handler->display->display_options['relationships']['flag_content_rel']['flag'] = 'best_price';
$handler->display->display_options['relationships']['flag_content_rel']['user_scope'] = 'any';
/* Field: Comment: Title */
$handler->display->display_options['fields']['subject']['id'] = 'subject';
$handler->display->display_options['fields']['subject']['table'] = 'comment';
$handler->display->display_options['fields']['subject']['field'] = 'subject';
$handler->display->display_options['fields']['subject']['label'] = '';
$handler->display->display_options['fields']['subject']['alter']['word_boundary'] = FALSE;
$handler->display->display_options['fields']['subject']['alter']['ellipsis'] = FALSE;
/* Field: Comment: Comment */
$handler->display->display_options['fields']['comment_body']['id'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['table'] = 'field_data_comment_body';
$handler->display->display_options['fields']['comment_body']['field'] = 'comment_body';
$handler->display->display_options['fields']['comment_body']['label'] = '';
$handler->display->display_options['fields']['comment_body']['element_label_colon'] = FALSE;
/* Sort criterion: Comment: Post date */
$handler->display->display_options['sorts']['created']['id'] = 'created';
$handler->display->display_options['sorts']['created']['table'] = 'comment';
$handler->display->display_options['sorts']['created']['field'] = 'created';
$handler->display->display_options['sorts']['created']['order'] = 'DESC';
/* Sort criterion: Flags: Flagged */
$handler->display->display_options['sorts']['flagged']['id'] = 'flagged';
$handler->display->display_options['sorts']['flagged']['table'] = 'flagging';
$handler->display->display_options['sorts']['flagged']['field'] = 'flagged';
$handler->display->display_options['sorts']['flagged']['relationship'] = 'flag_content_rel';
$handler->display->display_options['sorts']['flagged']['order'] = 'DESC';
/* Contextual filter: Comment: Nid */
$handler->display->display_options['arguments']['nid']['id'] = 'nid';
$handler->display->display_options['arguments']['nid']['table'] = 'comment';
$handler->display->display_options['arguments']['nid']['field'] = 'nid';
$handler->display->display_options['arguments']['nid']['default_action'] = 'default';
$handler->display->display_options['arguments']['nid']['default_argument_type'] = 'node';
$handler->display->display_options['arguments']['nid']['summary']['number_of_records'] = '0';
$handler->display->display_options['arguments']['nid']['summary']['format'] = 'default_summary';
$handler->display->display_options['arguments']['nid']['summary_options']['items_per_page'] = '25';
/* Filter criterion: Comment: Approved */
$handler->display->display_options['filters']['status']['id'] = 'status';
$handler->display->display_options['filters']['status']['table'] = 'comment';
$handler->display->display_options['filters']['status']['field'] = 'status';
$handler->display->display_options['filters']['status']['value'] = 1;
$handler->display->display_options['filters']['status']['group'] = 1;
$handler->display->display_options['filters']['status']['expose']['operator'] = FALSE;

/* Display: Block */
$handler = $view->new_display('block', 'Block', 'block_1');
</code>
Comment: It worked. Added your view to my node panel layout, placed it above comments list and that's it. I also decided that it'd be nice to exclude  the flagged comment from list so I added alternative view of comments for that.


clustered standard errors for first difference regressions

Question: this is a somewhat random question: is it possible to find clustered standard errors for first difference regressions? (both theoretically and practically in R or Stata).
Thanks!
Comment: I suggest you give more details and/or a specific example of how your clusters might be defined. This sounds more statistics than programming, so might be better on Cross Validated. I'd expect to see posters' code in this forum.
Answer: Yes, it is possible but whether it makes sense depends on what you want to cluster on exactly. As an example, let's suppose you have panel data on individuals who are identified via an id variable in the sample. Then one way to do a first-differenced panel regression in Stata would be
<code>regress D.(y x), vce(cluster id)
</code>
In this case, clustering the errors on the id variable corrects the standard errors for serial correlation. Austin Nichols and Mark Schaffer have given a whole presentation on clustering errors in Stata. They also explain clustering on id variables for first-differenced models (slide 6).


What are the different approaches to formalizing type theory in the usual model-theoretic context?

Question: Usually when formalizing a system of type theory, from what I've seen, authors usually either simply take the basic ideas of working with derivations, rules, and judgements as basic notions, explaining them informally, and define the type theory by giving a list of relevant rules, or formalize it in set theory (e.x. "a type theory consists of a set R of rules such that...").
However, oftentimes people will talk about models of type theories, for example, from ncatlab:

The models of ML type theory depend crucially on whether one considers the variant of extensional type theory or that of intensional type theory.
The models of the extensional version are (just) locally cartesian closed categories.

What is meant by this? Presumably, there is some way of actually formalizing type theory as an honest to goodness model-theoretic theory (either first order, or perhaps second order I imagine), so that a model of the system of type theory in question means the usual thing in model theory.
My question is: Are there any common approaches in the literature for defining type theory as an honest to goodness theory, and thus making the use of the term "model" the same as the model-theorists notion, or does "model of a type theory" mean something different? Is there even a formal definition of what "model of a type theory" or "theory of type theories" means in general in the literature, or are these definitions simply understood in an ad-hoc way, and only fully specified when talking about specific type theories (i.e. "models of MLTT", "models of HOTT")? If the latter is the case, restricting to particular type theories, have notions like "the theory of MLTT" or "the theory of HOTT", for example, been formalized in the usual model-theoretic context?
Answer: This question is actually a little difficult because what the best answer is is still a subject of ongoing research and debate.
First of all, dependent type theory is definitely not a first order theory so it needs a different kind of "model" to the usual notion from first order logic model theory. Now the problem is not that there is no good notion of model for type theory, but that there are several, and they have different pros and cons and it isn't clear which is the best way or if we have even discovered the best way yet.
All of these notions are based on the basic idea that there should be a category where contexts in type theory are interpreted as objects in the category, and each object comes equipped with a notion of type and term that are used to interpret types and terms in dependent type theory. The oldest kind of model is know as contextual category, from Cartmell, Generalised algebraic theories and contextual categories. These have the advantage of being very close to the syntax of type theory, but have a somewhat technical definition and so can be difficult to work with. At the other extreme are locally cartesian categories. These have a relatively easy definition using well studied ideas from category theory, but with two main disadvantages. Firstly, just to interpret type theory into a locally cartesian closed category is highly non trivial (see Hofmann, On the Interpretation of Type Theory in Locally Cartesian Closed Categories). Secondly, in a general locally cartesian closed category there is only really one way to interpret identity types, and using this interpretation one always gets a model of extensional type theory. This second point makes locally cartesian closed categories not so useful for HoTT, where it is important that the identity types are not extensional. In between contextual categories and locally cartesian closed categories there are several definitions including categories with families, categories with attributes and comprehension categories, that try to find a balance.
See the nlab page on Categorical Models of Dependent Types for more information.
A question of ongoing research is what kind of model should play the role of locally cartesian closed category for intensional dependent type theory. There is general consensus that this should be done using ideas from homotopical algebra such as weak factorisation system, and then interpreting identity type using the ideas in Awodey and Warren, Homotopy theoretic models of identity types.
For instance, there is a general "coherence theorem" in Lumsdaine and Warren, The local universes model: an overlooked coherence construction for dependent type theories, that shows how to interpret intensional type theory in a number of categories. These include locally cartesian closed categories that also come equipped with a kind of structure from homotopical algebra known as right proper model structure.
Answer: Your understanding is a little backwards: first- and second-order logic are special cases of type theories, it's just that they are usually untyped, i.e. they have a single type, which is usually called a sort or a universe of discourse. The notion of a "model of type-theory" applies to first- and second-order logic: models of first-order logic are Heyting categories, while models of second-order logic are toposes.
How does this align with usual model theory? A first-order theory is a first-order logic supplemented with some signature and axioms. The model of a first-order theory (in the type-theoretic sense) is then a Heyting category supplemented with a sound (with respect to the axioms) interpretation of the signature inside the Heyting category. In particular, when you restrict your type-theoretic models so that the ambient category is the category of sets, you recover the notion of a model from classical model theory.
Why are models of type theories categories? It is because we can think of type theories/first- and second-order logic as presentations of categories by generators (the logical and non-logical signature of the type /first-/second-order theory) and relations (the inference rules/logical and non-logical axioms). That is to say, the data that goes into specifying type/first-/second-order theory is the same data that specifies categories, so categories are simply type theories, but seen from a different point of view. (One caveat to that: I think type theories in computer science are slightly more general and perhaps somewhat ahead of the categorical/model-theoretic picture).
Note that model theory itself is only coherent with, but not dependent on the type theory (i.e. on the inference rules of the logic). Rather, model theory begins by deciding to interpret propositions as characteristic morphisms to some object of truth values, and how the latter sits in the ambient category in which you're doing the model theory determines the type theory you're interpreting (e.g. this is how continuous logic and its funky inference rules arise from continuous model theory where we decide models to be metric spaces rather than sets and truth-values to be non-negative reals).
Comment: I spell out the "type theories as presentations of categories" in a decent amount of detail in my blog post [Category Theory, Syntactically](http://www.hedonisticlearning.com/posts/category-theory-syntactically.html) which may be of interest.
Comment: @Sintrastes the "types" of type theory or called *sorts* in classical logic, they are the domains over which variables ranger over; the "types" in model theory are (roughly) sets of formulas that describe elements of some particular structure -- they are a notion orthogonal to the types of type theory. Regarding the general notion of "type theory", that's the same question as asking for a general notion of "logic" (since type theories are perhaps generalized logics); whatever the answer, it should account for the varieties of logics that exist (linear logics, substructural logics, etc)
Comment: Thank you! That way of looking at things is helpful. However, I'd still like to know whether or not there is a general notion of "type theory" and hence "models of type theory", I've seen a few definitions for specific cases in the literature (such as dependent type theories), but never something general enough to cover arbitrary type theories.
Comment: I do recall reading that the term "type" as it is used in model theory is different from the notion used when discussing "type theory" proper, so perhaps as you suggest, they are not fundamentally different notions, but the more general notion of "type theory" is a generalization of the model-theoretic notion.
Comment: @vladimirsotirov I don't know if it's the same question, but definitely a related one. What I'm really looking for is a general version of the Curry-Howard-Lambek correspondence for suitably defined general conceptions of "logic" and "type theory" -- the existence of such a theorem, if true, I think should characterize the notions I am looking for, but I do not know if this has been accomplished. It might be promising to try to construct a notion of type theory corresponding to the general notions of natural deduction studied in the proof-theoretic semantics literature, but I don't know.


Could my code cause a crash when creating a new file and directory under Windows 7?

Question: I have had some problems earlier which caused my program to crash in all Windows OS because I did not create a new file/directory for my file. Then I have assured that I have created file/folder before initializing ect. Now my program works in Windows XP but it doesn't work in Windows 7. By saying that it works I mean that it creates a file/folder needed for my program. By not working I mean that the file/folder isn't created in windows 7.
Could this code be the cause of the crash under Windows 7? If so, how could I fix it?
    private static string dir = Environment.GetFolderPath
        (Environment.SpecialFolder.ProgramFiles) + @"\folder\";
    private static string file = dir + @"\Settings.txt";
    private string text;

    public void CheckFileStatus()
    {
        if (!Directory.Exists(dir))
        {
            DirectoryInfo directory = Directory.CreateDirectory(dir);
        }
        if (!File.Exists(file))
        {
            using (FileStream fileStream = File.Create(file))
            {
            }
        }
    }

Comment: When you say crash - do you mean throw an exception? If so, what?
Comment: @Prescott, There is no exception presented. simply it say that program has crashed; send report to Microsoft... I can't check any details because I'm not the one with Windows 7.
Answer: The program files directory in Windows 7 can only be written to with elevated privileges. Are you running your code as an administrator? It's also bad practice to write to the program files folder. You should be using the %appdata% folder.
Take a look here to see the various special folders. You will likely want to use either System.Environment.SpecialFolder.ApplicationData or System.Environment.SpecialFolder.CommonApplicationData. This will allow you to write data without needing elevated privileges.
Comment: @NewHelpNeeder: Is your tester able to right-click and run as administrator? If not, are you installing your program via Wix or some other type of installer software? If so, you can mark the executable as requiring elevated privileges. However, the issue really is that you need to save the settings to the proper location (not program files).
Comment: I don't think that privileges are set to admin on PC of my tester.
Comment: my tester is kind of blank on how to deal with such thing. I'm trying to simplify this as much as possible. Your solution seems very nice.
Comment: @NewHelpNeeder: Give it a whirl. It should solve your problem (and is a better practice, especially in the days of UAC).
Answer: You cannot create folders in Program Files without being having elevated privileges (ie acting as an Administrator) on Windows Vista and Windows 7. There are generally better places to put settings files that should be writable by any user.
Environment.SpecialFolder.ApplicationData or Environment.SpecialFolder.LocalApplicationData  is generally the place for user specific application data which is most likely what you want.
The difference being that in a domain, ApplicationData will be placed in your roaming profile and be shared between computers on the domain, while LocalApplicationData is for that very machine only.
For home users or if you don't specifically want the data to be shared between machines, probably LocalApplicationData is better. That way you know it won't cause problems on a domain if you end up writing computer specific data in it.
There is also Environment.SpecialFolder.CommonApplicationData which allows for sharing the same data between all users on the computer, but while that may seem convenient, consider that any user on the machine can then change settings of a program that is later run by you which may cause security implications.
Comment: Should I instead store information to for example My Documents? Or which folder should be used?
Comment: I do like the idea of LocalApp folder which would be best which would protect data from other computer users. Thanks for this information.


c macro in macro. how to do it

Question: I have the following code
#define LogError(...) fprintf(stderr, __VA_ARGS__)

And I want another macro to print to the error log only in debug mode, so I expect that, with
#define DebugLogError(...) \
    #ifndef NDEBUG \
    fprintf(stderr, __VA_ARGS__); \
    #endif

code DebugLogError("hello %s", "world")
to expand to
    #ifndef NDEBUG
    fprintf(stderr, "hello %s", "world") \
    #endif

But the code is not compiling.
How can this be implemented?
Comment: Please don't tag C++ when asking about C.
Comment: It's expanding to `fprintf(stderr, "hello %s", "world")` without `;`?
Answer: The C standard does not provide features for using preprocessor directives inside macros. Instead of trying use a #if inside a macro, use the #if to control how you define the macro:
#if defined NDEBUG
    // If NDBUG is defined, define the macro to be replaced by nothing.
    #define DebugLogError(...)
#else
    // Otherwise, define the macro to print a debugging message.
    #define DebugLogError(...) fprintf(stderr, __VA_ARGS__);
#endif

However, it is often preferable to modify the macro so it can be used like a function call followed by a ;, fitting more smoothly into the C grammar:
#if defined NDEBUG
    // If NDBUG is defined, define the macro to be replaced by nothing.
    #define DebugLogError(...) \
        do { } while (0)
#else
    // Otherwise, define the macro to print a debugging message.
    #define DebugLogError(...) \
        do fprintf(stderr, __VA_ARGS__); while (0)
#endif

Defining them in the latter form will avoid errors where an extra semicolon (in the no-NDEBUG case) or missing code (in the NDEBUG case) would cause problems, like:
if (SomeCondition)
    DebugLogError(stuff);
else
    OtherCode;

c macro in macro. how to do it


How to compute unit direction vector of a ray in 3D given its origin and angle with XZ and YZ planes?

Question: I want to compute the unit direction vector for a ray in 3D. I have the coordinates of the starting point of the ray and angle the ray makes with the XZ and YZ plans where X is rightward, Y is upward and Z is forward direction. Any idea how should I go about it?
Comment: Use [spherical coordinate system](https://en.wikipedia.org/wiki/Spherical_coordinate_system). For example, $$\begin{cases} x = \sin(\theta) \cos(\varphi) \\ y = \sin(\theta) \sin(\varphi) \\ z = \cos(\theta)\end{cases}$$where $\varphi$ is the angle between the ray and the $xz$ plane, and $\theta$ is the angle between the ray and the $z$ axis.
Answer: Now that's a strange way to proceed. If I'm not mistaken, your basis isn't right-handed. If you have a choice in the matter, I'd recommend switching to something more conventional.

Say your unit direction vector is $\mathbf u=\left(x,y,z\right)^t$.
The unit normal vector to plane $XZ$ has coordinates
$\mathbf j=\left(0,1,0\right)^t$.
Let $\alpha_j$ be the angle between $\mathbf u$ and the $XZ$ plane.
Then
$$
\langle \mathbf u,\ \mathbf j \rangle = y = \cos\left(\frac\pi 2-\alpha_j\right)
$$
Repeat for the other angle with plane $YZ$, you obtain $x$. You can deduce $z$ from the constraint that it is a unit vector.


Order posts by last comment date in WordPress

Question: I am using a combination of get_comments() and get_post() to display a list of posts ordered by comment date.
Ref:
http://codex.wordpress.org/Function_Reference/get_comments
https://codex.wordpress.org/Function_Reference/get_post
My code:
$args = array(
    'status' => 'approve',
    'order' => 'DESC'
);

$comments = get_comments( $args );

foreach ( $comments as $comment ) {

     $post = get_post( $comment->comment_post_ID );
     echo $post->post_title;

}

The problem with this approach is the list of posts will contain duplicate post titles if a post has more than one comment.
How can I remove the duplicates?
UPDATE:
This initial approach does a lot of unnecessary legwork. For example, on sites that have lots of posts and comments, the query will pull back lots of unnecessary comments.
UPDATED QUESTION:
How can I order a list of posts by comment date?
Answer: This is an interesting approach...but, I suppose you could just fill an array with post ID's and then check them later.
$args = ....
$ids = array();
.....
if(!in_array($post->ID, $ids):
    $ids[] = $post->ID;
    echo $post->title;
endif;

Comment: Thanks for this @Ohgodwhy, `in_array()` looks to be the solution! Out of interest, would you recommend an alternative approach altogether then, or you think I should stick with my initial approach?
Comment: You got me thinking about my initial approach. I'm actually thinking it does a lot of unnecessary legwork. On sites that have *lots* of posts and comments, the query will be pulling back lots of unnecessary comments. I'm now thinking simply *how can I order a list of posts by comment date?*


How do I get a variable from another class in Java?

Question: How do I set selectedPlayer to the value of position from my other class?
I've read a bunch of similar questions on here, but I keep running into conflicts with my variables and functions.
ScoreList.java
public class ScoreList extends Activity {

    Integer selectedPlayer = 0;
}

ScoreListAdapter.java
public class ScoreListAdapter extends ArrayAdapter<Score> {

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        final OnClickListener lsScoreView = new OnClickListener() {
              @Override
                public void onClick(View v) {
                  //send position to main class here
              }
        };

    }
}

Comment: What value of position from which other class?
Comment: getView in ScoreListAdapter gets passed int position and I want that value to get sent to the selectedPlayer variable in ScoreList
Answer: set selectedPlayer as static:
public class ScoreList extends Activity {

  static Integer selectedPlayer = 0;
}

This way,You can refer selecterPlayer using class name as it does not belong to any object of the class.
ScoreListAdapter.java
    public class ScoreListAdapter extends ArrayAdapter<Score> {

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {

            final OnClickListener lsScoreView = new OnClickListener() {
                  @Override
                    public void onClick(View v) {
                       ScoreList.selectedPlayer;//You can use selectedPlayer here
                  }
            };

        }
    }

Comment: Thanks for the response. I used your code, changing the second part to "ScoreList.selectedPlayer = position;" and it gives me an error I was getting earlier: "Cannot refer to a non-final variable position inside an inner class defined in a different method"
Comment: make position final like,  ...getView(final int position, View..
Answer: Options...

Pass ScoreList in as a parameter to the ScoreListAdapter constructor and set it as an instance variable that you can refer to in ScoreListAdapter.getView.
Pass ScoreList in as a parameter to the getView method.


How to get MD5 checksum from artifactory in Linux command line

Question: I have to get the MD5 checksum from the artifactory link:
www.artifactory_company_link/artifactory/webapp/#/artifacts/browse/tree/General/abc.html
I have tried CURL -I artifactory_link. But didn't get the MD5 checksum.
Answer: To get the MD5 checksum from command line, you need to use the Artifactory File Info REST API.
So the proper way to get your file's MD5 checksum would be (assuming the General repository here)
curl -s -u<user>:<password> www.artifactory_company_link/artifactory/api/storage/General/abc.html

This will output a big json output of the file's info, including its MD5 checksum.
Use jq to get just the checksum
curl -s -u<user>:<password> www.artifactory_company_link/artifactory/api/storage/General/abc.html | jq ".checksums.md5"

Comment: Thanks for replying. By using above command i am facing "parse error: Invalid numeric literal at line 2, column 0" issue
Comment: Which of the two? Did you follow the instructions in the REST API docs?
Comment: Second one. Now i got null as output. I have added the screenshot in the question
Comment: Do you have a repository called `General`? If not, use the actual repository name your file is stored in. Try running without the `jq` first and see the full output.
Comment: When i try to run without jq. I got error "Authentication is required"
Comment: Ah... right. You need to add the `-u:` to the command. I added to my answer.


IIS 7.5 Basic Authentication

Question: I am having problems with Basic Authentication in IIS 7.5.
I have:

enabled Basic Authentication on my site
disabled Anonymous Authentication on the same site
Added an IIS user and allowed said user to the site
Added read/write permissions for Basic Authentication on said site (feature delegation)

Its still not working. It prompts for username and password, but does not accept the user/pass i've created.
Any ideas?
Answer: "Added an IIS User" -> Do you mean IIS Manager user?
If so, these aren't real Windows users - just a username and a password in a text file somewhere: they don't have a SID or security tokens, and can't be used for Basic authentication. Not using the out-of-the-box configuration, anyway.
Create a (real) Windows user, and it'll be usable for Basic auth.
--
Edit: I just noticed you said something else - Feature Delegation doesn't describe permissions to the site contents, it's whether a non-Administrator can configure those features at a lower level within the site in a web.config file - essentially, which IIS feature icons are usable when they connect to the computer via the Management Service.
The answer is roughly the same, though:

reset delegation to defaults (you didn't mean to change it; it's dangerous to change some of the delegation settings from defaults under these conditions)
create a Windows user in Server Manager
assign permissions to that Windows user either at the file system level, or using the URL Authorization feature
Comment: Thank you. Its working now. Also, undid the feature delegation.
Comment: Excellent! Glad you got it working.

IIS 7.5 Basic Authentication


Pathologic relative path on multisite

Question: Old multisite subsite relative path to image (in block/Full HTML with CKeditor and on localhost/XAMPP):
/sites/site1.localhost/files/image.png

New multisite path (what I'm trying to achieve):
/sites/site2.localhost/files/image.png

So, in Full HTML input settings for Pathologic, we select the 3rd option Relative path and add lines:
/sites/site1.localhost/
/sites/site2.localhost/

And nothing happpens, it just strips the /sites/site1.localhost/ from path and now the path to image is just:
/files/image.png

How do I make it the /sites/site2.localhost/?
Answer: Solved running SQL query in phpMyAdmin
UPDATE field_data_body  SET body_value = REPLACE(body_value,'src="/olddirectory','src="/newdirectory');

Source article: http://www.coolestguidesontheplanet.com/downtown/changing-image-paths-drupal-subdirectory-installation

Pathologic relative path on multisite


Finding units digit of exponent to an exponent

Question: How do you find the units digit of
$$2^{2^2}+4^{4^4}+6^{6^6}+\cdots+2016^{2016^{2016}}+2018^{2018^{2018}}$$
I've been trying to find a pattern here but I can't.
Comment: I reckon that if $n$ is even, then $n^4$ ends in either $6$ or $0$.
Answer: The summands are of the form
$$ (2m)^{(2m)^{2m}}$$
with $1\le m\le 1009$. As $(2m)^{2m}=2^{2m}m^{2m}=4\cdot 2^{2(m-1)}m^{2m}$, the exponent is always a positive multiple of $4$. For all naturals $n$, $n^4\equiv n\pmod 2$ and either $n^4\equiv 0\pmod 5$ (namely, when $n\equiv 0\pmod 5$)  or $n^4\equiv 1\pmod 5$ (in all other cases - little Fermat). It follows by the Chinese Remainder Theorem${}^1$ that $(2m)^4\equiv 6\pmod {10}$ for all $m$, except that $(2m)^4\equiv 0\pmod{10}$ when $2m$ is a multiple of $10$. As $6^k\equiv 6\pmod{10}$, it follows that $$(2m)^{(2m)^{2m}}\equiv (2m)^{4k}\equiv 6^k\equiv 6\pmod {10}$$
except when $2m$ is a multiple of $10$. As the final sum has $1009$ summands, of which $403$  are multiples of $10$, the whole sum is $\equiv 4\pmod{10}$.
${}^1$ Alternatively, just verify $n^4\equiv 6\text{ or }0\pmod{10}$ manually for the few cases there are.


How to get additional information into GCP Stackdriver alert messages

Question: We want to put more information into GCP Stackdriver alert notifications like customer contract id (e.g. 47110815), customer environment (prod/dev/test), SLA (24-7-4/24-7-8/nbd), etc.
It must be machine readable (currently by alerta monitoring system via webhook) so we would prefer additional key/value fields instead of all information mashed together into documentation/content field.
GCP Stackdriver offers many fields when creating alerting policies: (https://cloud.google.com/monitoring/api/ref_v3/rest/v3/projects.alertPolicies)
most interesting is userLabels:

map (key: string, value: string)
User-supplied key/value data to be used for organizing and identifying the AlertPolicy objects.
The field can contain up to 64 entries. Each key and value is limited to 63 Unicode characters or 128 bytes, whichever is smaller. Labels and values can contain only lowercase letters, numerals, underscores, and dashes. Keys must begin with a letter.
An object containing a list of "key": value pairs. Example: { "name": "wrench", "mass": "1.3kg", "count": "3" }.

When creating policies they are shown in stackdriver but it seems like this fields are not included in alert notifications.
Is there any other option than putting all information into the documentation content field? I wanted to use this field for free-text that gives general handling instructions to service desk staff and don't like the idea of parsing machine readable data out of it.
Answer: At this time, Stackdriver does not allow you to customize the notifications.
The current way to add more information on Notifications are using the documentation section [1]. You can also use variables in this field to get specific details about the alert [2].


What is a good heuristic for determining the tab width used in a source file?

Question: I would like to determine the tab width used in source files indented with spaces.
This is not hard for files with particularly regular indentation, where the leading spaces are only used for indentation, always in multiples of the tab width, and with indentation increasing one level at at time.
But many files will have some departure from this sort of regular indentation, generally for some form of vertical alignment. I'm thus looking for a good heuristic to estimate what tab width was used, allowing some possibility for irregular indentation.
The motivation for this is writing an extension for the SubEthaEdit editor. SubEthaEdit unfortunately doesn't make the tab width available for scripting, so I'm going to guess at it based on the text.
A suitable heuristic should:

Perform well enough for interactive use. I don't imagine this will be a problem, and just a portion of the text can be used if need be.
Be language independent.
Return the longest suitable tab width. For example, any file with a tab width of four spaces could also be a file with two-space tabs, if every indentation was actually by twice as many levels. Clearly, four spaces would be the right choice.
Always get it right if the indentation is completely regular.

Some simplifying factors:

At least one line can be assumed to be indented.
The tab width can be assumed to be at least two spaces.
It's safe to assume that indentation is done with spaces only. It's not that I have anything against tabs---quite the contrary, I'll check first if there are any tabs used for indentation and handle it separately. This does mean that indentation mixing tabs and spaces might not be handled properly, but I don't consider it important.
It may be assumed that there are no lines containing only whitespace.
Not all languages need to be handled correctly. For example, success or failure with languages like lisp and go would be completely irrelevant, since they're not normally indented by hand.
Perfection is not required. The world isn't going to end if a few lines occasionally need to be manually adjusted.

What approach would you take, and what do you see as its advantages and disadvantages?
If you want to provide working code in your answer, the best approach is probably to use a shell script that reads the source file from stdin and writes the tab width to stdout. Pseudocode or a clear description in words would be just fine, too.
Some Results
To test different strategies, we can apply different strategies to files in the standard libraries for language distributions, as they presumably follow the standard indentation for the language. I'll consider the Python 2.7 and Ruby 1.8 libraries (system framework installs on Mac OS X 10.7), which have expected tab widths of 4 and 2, respectively. Excluded are those files which have lines beginning with tab characters or which have no lines beginning with at least two spaces.
Python:
                     Right  None  Wrong
Mode:                 2523     1    102
First:                2169     1    456
No-long (12):         2529     9     88
No-long (8):          2535    16     75
LR (changes):         2509     1    116
LR (indent):          1533     1   1092
Doublecheck (10):     2480    15    130
Doublecheck (20):     2509    15    101

Ruby:
                     Right  None  Wrong
Mode:                  594    29     51
First:                 578     0     54
No-long (12):          595    29     50
No-long (8):           597    29     48
LR (changes):          585     0     47
LR (indent):           496     0    136
Doublecheck (10):      610     0     22
Doublecheck (20):      609     0     23

In these tables, "Right" should be taken as determination of the language-standard tab width, "Wrong" as a non-zero tab width not equal to the language-standard width, and "None" as zero tab-width or no answer. "Mode" is the strategy of selecting the most frequently occurring change in indentation; "First" is taking the indentation of the first indented line; "No-long" is FastAl's strategy of excluding lines with large indentation and taking the mode, with the number indicating the maximum allowed indent change; "LR" is Patrick87's strategy based on linear regression, with variants based on the change in indentation between lines and on the absolute indentation of lines; "Doublecheck" (couldn't resist the pun!) is Mark's modification of FastAl's strategy, restricting the possible tab width and checking whether half the modal value also occurs frequently, with two different thresholds for selecting the smaller width.
Comment: IMO, a reasonable approach is: if ts=8 does not work, reject the file and complain to the author.
Comment: @William Pursell That's a bit stricter than I was looking for. ;)
Comment: Putting a bounty to try to get a few more ideas. I'll also add a baseline answer, which one should do at least as well as.
Answer: Okay, as you want a language-agnostic solution, we won't be able to use any syntactical hints. Although you said, that you don't want a perfect solution, here is one, that is working very well with most languages.
I actually had to solve a similar issue in cryptography to get the correct code word length in a polyalphabetic cipher. This kind of encryption is a basic Caesar-chiffre (each letter of the alphabet is moved by n letters), where the cryptword is used to move the letters differently (the nth letter of the clear text is moved by the mod(nth, length(cryptword)) letter of the cryptword). The weapon of choice is autocorrelation.
The algorithm would be like this:

strip all characters after the whitespace at the beginning of a line has ended - leave the line-end markers intact.
remove lines with zero whitespace (as they are only blank lines)
Count the whitespace width for each line and save this in an array lengths
Autocorrelation: loop until the maximum estimated number - may be fairly high like 32 or something - current iteration shall be i. For each iteration, calculate the distance between each entry and the ith entry. Count the number of distances = 0 (same values for the nth and (n+i)th entries), save in an array for the key i.
You now have an array of same-pair-occurances. Calculate the mean of this array, and delete all values near this mean (leaving the spikes of the autocorrelation). The spikes will be multiples of the lowest value, which will be the searched number of spaces used for indentation.

The autocorrelation is a very nice function, usable for every situation, in which you want to detect repeating values in a stream of data. It is heavily used in signal processing and very fast (depending on the estimated maximum distance of signal repeats).
And yes, back then I cracked the polyalphabetic ciphertext with autocorrelation. ;)
Comment: *Very* interesting approach. It's been a while since I've done any signal processing, but I think I can see how this works. You're essentially suggesting a way to do a cheap Fourier transform, based on the assumption that low frequencies dominate (i.e., the limit in step 4 is a form of low-pass filter). Step five throws out the values that contribute little in the frequency domain power spectrum. Does that sound about right?
Comment: Implementing this, I'm not finding your step 4 very clear: what does *i* represent? It appears to be the difference between the index of lines being compared, but how does that get converted to a tab width at the end? Is it supposed to be a 2D autocorrelation, perhaps?
Comment: @michael-j-barber sounds about right, but to be honest, signal processing is not my best area of knowledge. I've also read about the similarities to FFT. In the end, you try to amplify spikes by comparing a signal to itself with an offset. Imagine a sinus-wave, which you copy and iteratively increase the offset, until the two waves match up again. This amplifies the signal noticably and thus you can determine the wavelength by looking at the offset. The same works for ciphertext, if you take the letter number in the alphabet as the value for the wave, but that really get'S off topic now. ;)
Comment: @Michael-j-barber: i is the iteration or current offset being tested. Have a look at [Index of Coincidence](http://en.wikipedia.org/wiki/Index_of_coincidence) for a detailled explanation of solving a polyalphabetic chiffre. Maybe this will clear it up better than I can provide in 500 chars.
Comment: I'll take a look at the article, hopefully it will clear things up. Right now, points 4 and 5 seem to be saying to count how many pairs of lines with offsets *i* have the same indentation, and select the offsets with high counts. But that would ignore the actual indentation, with no way to recover it. Don't forget you can edit your answer: the 500 character limit is not a problem!
Comment: got a point there - I'll see if I can find some time to write some actual code on this one tomorrow.
Comment: Autocorreletion is overkill for this problem, plus you need to estimate/guess the highest number, and it is quite slow for this simple problem.
Answer:
For each line in the file

If indented more than the previous, add the difference to a list

discard if > 12, it's probably a line continuation

Generate a frequency table of the #s in the list
#1 is likely your answer.

edit
I have VB.Net open (didn't you? :-) Here's what I mean:
    Sub Main()
        Dim lines = IO.File.ReadAllLines("ProveGodExists.c")
        Dim previndent As Integer = 0
        Dim indent As Integer
        Dim diff As Integer
        Dim Diffs As New Dictionary(Of Integer, Integer)
        For Each line In lines
            previndent = indent
            indent = Len(line) - Len(LTrim(line))
            diff = indent - previndent
            If diff > 0 And diff < 13 Then
                If Diffs.ContainsKey(diff) Then
                    Diffs(diff) += 1
                Else
                    Diffs.Add(diff, 1)
                End If
            End If
        Next
        Dim freqtbl = From p In Diffs Order By p.Value Descending
        Console.WriteLine("Dump of frequency table:")
        For Each item In freqtbl
            Console.WriteLine(item.Key.ToString & " " & item.Value.ToString)
        Next
        Console.WriteLine("My wild guess at tab setting: " & freqtbl(0).Key.ToString)
        Console.ReadLine()
    End Sub

Results:

Dump of frequency table:
  4 748
  8 22
  12 12
  2 2
  9 2
  3 1
  6 1
  My wild guess at tab setting: 4

Hope that helps.
Comment: Not bad, except this can't e.g. determine the tab width is 8, if 45% of the tab widths are 7 and 55% are 9. Interesting, though.
Comment: @Patrick87 - if you sort the freq table it will, those #s will be in subsequent slots. But, I don't think the OP wanted that; I re-read the question and still I think he just wants the most likely candidate.
Comment: @Patrick87 I wouldn't expect that a file in which indentation never changes by 8 would have a tab width of 8. The numbers you give seem like an exceptional case that one shouldn't worry about much.
Comment: More specifically for this answer, it is much in line with what I'm looking for. In the end, if you can come up with a good rule for eliminating spurious indents, it should be possible to do very well with a simple selection strategy like the mode of the indentation changes. I'll implement this later and see whether "large indents" are a good test for spurious indents.
Comment: Your choices are (realistically) 2,3,4,5,6,7,8. I'd scan the first 50-100 non-empty lines with this method and pick the highest. If the hit is 8, 6, or  4 I'd do a second check to see if 4, 3, or 2 were the second highest and pick that one instead. I'd pick a "rationalization" scheme for fixing the goofs, for each of your 7 possibilities.
Comment: @Mark I've awarded the bounty to this answer, as it is the best one so far and I have no further time to implement and test another before the deadline would have expired. But please post your comment as an answer, I'll implement it tomorrow and see if it does better. I'll wait on accepting an answer until I've tried yours out as well.
Answer: Maybe do something like...

get a list of all the tab widths in the file
remove 50% of the entries which are least frequent
sort the remaining entries in ascending order
compute a list of (a, b) pairs where b's are in the list of tab widths and the a's give the rank of that tab width.
plot a best-fit line
the slope of the best-fit line is the guess for the tab width. round to the nearest integer.

Example:

list = [4, 4, 6, 8, 8, 4, 4, 4, 8, 8, 12, 5, 11, 13, 12, 12]
list = [4, 4, 4, 4, 4, 8, 8, 8]
already sorted
[(1, 4), (1, 4), (1, 4), (1, 4), (1, 4), (2, 8), (2, 8), (2, 8)]
the best fit line is b = 4a + 0 (R^2 = 0)
slope is 4, so this is probably the tab width.
Comment: When you refer to tab width, do you mean the leading indentation of the lines or the change in indentation between successive lines?
Comment: My method would approximate both: the leading indentation is the y-intercept, and the change in indentation would be the slope. Alternatively, this line would give a function of indentation spaces versus tab depth.
Comment: OK, then I'll follow-up with questions and comments for both versions. For indentation width, it seems that the approach can get it wrong, even if all indentation changes are the same magnitude; this might not be a problem in practice, and may well be necessary to improve the overall results---to be determined empirically. I note that your example numbers have no zeros---was that deliberate?
Comment: In the case of indentation changes, there seems to be an assumption that most changes are in even multiples of the tab width, which I'm not sure about---again, something which I'll address empirically. Your example numbers have neither zeros nor negatives. Is the intention to omit reductions in the indentation? To use the magnitudes of non-zero changes?
Comment: No, you could add zeros. I'm not sure I follow about how this could go wrong. This is an empirical question, and fitting a curve to data - for indentation, one would assume a linear curve is most suitable - is standard practice. The only time I see this method failing spectacularly is when all indentation levels are the same... in that case, you tell me what indentation scheme the guy was using!
Comment: Another way to say it is this: my method is the best guess you can make looking at the data... to do better, you'd need assumptions. Say somebody chooses to indent at the first tab level and third, with tab width 2. Then there are lots of 2s and 6s, and my method would say the tab width is 4. If that's not good enough, you need a psychic, not an algorithm. By the way, the data points are the total number of leading spaces on each line... Not some sort of line-to-line delta.
Comment: Thanks for the additional comments, I'm sure I can fairly capture your intention for testing purposes now. BTW, using indentation width can go wrong when you have a function consisting of a bunch of lines indented one level, a line or two indented two levels, and then a bunch of lines indented three levels; the two-level indent gets thrown out and double the actual tab width is returned. This structure shows up in, e.g., numerical code where you're looping over both indices of a 2d matrix.
Answer: Your choices are (realistically) 2,3,4,5,6,7,8.
I'd scan the the first 50-100 lines or so using something like what @FastAl suggested. I'd probably lean toward just blindly pulling the spaces count from the front of any row with text and counting the length of the white space string. Left trimming lines and running length twice seems like a waste if you have regex available. Also, I'd do System.Math.abs(indent - previndent) so you get de-indent data. The regex would be this:
row.matches('^( +)[^ ]') # grab all the spaces from line start to non-space.

Once you've got a statistic for which of the 7 options has the highest count, run with it as the first guess. For 8, 6, and 4 you should check to see if there is also a significant count (2nd place or over 10% or some other cheapo heuristic) for 4 and 2, 3, or 2. If there are a lot of 12s (or 9s) that might hint that 4 (or 3) is a better choice than 8 (or 6) as well. Dropping or adding more than 2 levels at a time (usually collapsed ending brackets) is super rare.
Irrelevant mumbling
The one problem I see is that old .c code in particular has this nasty pattern going on in it:
code level 0
/* Fancy comments get weird spacing because there
 * is an extra space beyond the *
 * looks like one space!
 */
  code indent (2 spaces)
  /* Fancy comments get weird spacing because there
   * is an extra space beyond the *
   * looks like three spaces!
   */

code level 0
  code indent (2 spaces)
  /* comment at indent level 1
     With no stars you wind up with 2 spaces + 3 spaces.
  */

Yuck. I don't know how you deal with comment standards like that. For code that is "c" like you might have to deal with comments special in version 2.0... but I would just ignore it for now.
Your final issue is dealing with lines that don't match your assumptions. My suggestion would be to "tab" them to depth and then leave the extra spaces in place. If you have to correct I'd do this: rowtabdepth = ceiling((rowspacecount - (tabwidth/2)) / tabwidth)
Comment: That gives a nice improvement for the ruby standard library, but actually a tiny loss for python---it looks like more in absolute terms, but as a percentage, the gain for ruby outweighs the loss for python. Looking through where Python gets it wrong, there's just not many more files to get correct than "no-long8" does. Using a threshold of 20% seems to work a little better than your guess of 10%. I found your description a little unclear, reading like you're working with the absolute indentation but referring to FastAl's which is about the differences; perhaps some editing is in order.
Comment: Elaborate layout like the C you mention is exactly why I stressed "not all languages, perfection not required." Even with the exact tab width, it would be hard to insert text to match the formatting: better to call `indent` or the like.
Comment: You are correct, I blended two answers, poorly. :-/ I'll tweak the answer to push it toward relative tabbing like @FastAl's.
Answer: For each langauge you want to support, you'll need to do a bit of parsing:
1) exclude comments (either line-wise or block-wise, maybe also nested?)
2) find openings of sub-block ({ in C-like languages, begin in pascal, do in shell etc.)
Then just see how much the number of spaces increase after sub-block has been opened. Make some simple statistics - to find most frequent value, maximum and minimum value, average value. This way you can also see if the indentation is regular or not and how much.
Answer: As a baseline, one could simply calculate all indentation increases, and take the most frequent increase as the tab width. As a shell script, written to have small actions per pipeline stage, it could look like this:
#!/bin/sh

grep -v -E '^[[:space:]]*$' |
  sed 's/^\([[:space:]]*\).*/\1/' |
    awk '{ print length($0) }' |
      awk '$1 > prev { print $1 - prev } { prev = $1 }' |
        sort |
          uniq -c |
            sort -k1nr |
              awk '{ print $2 }' |
                head -n 1

This implementation is O(n log(n)) where n is the number of lines in the file, but it could readily be done in O(n).
Comment: I like this for the sheer perversity of it. After spawning 9 processes I don't think sort's non linear O() behavior is a problem for typical source files.
Comment: @Jürgen This was intended as a step-by-step illustration with one action per stage of the pipeline, to act as a baseline that others could modify without much trouble---I wanted ideas more than an efficient implementation. That doesn't necessarily lead to a fast implementation (the two consecutive `awk` stages look particularly egregious, as does the sorting strategy to get the maximum). That said, it runs on a file with 10k lines with no noticeable time lag; fast enough for interactive use isn't much of a constraint!
Comment: I fully understand that. My python script uses almost the same strategy.
Answer: Heuristic:

Get a list of all indention changes from a line to its next line which are > 0.
Make a frequency table of all values in this list.
Take the value with highest frequency.

Python script, takes filenames or stdin and prints best indent number:
#!/usr/bin/env python

import fileinput, collections

def leadingSpaceLen(line):
    return len(line) - len(line.lstrip())

def indentChange(line1, line2):
    return leadingSpaceLen(line2) - leadingSpaceLen(line1)

def indentChanges(lines):
    return [indentChange(line1, line2)
        for line1, line2 in zip(lines[:-1], lines[1:])]

def bestIndent(lines):
    f = collections.defaultdict(lambda: 0)
    for change in indentChanges(lines):
        if change > 0:
            f[change] += 1
    return max(f.items(), key=lambda x: x[1])[0]

if __name__ == '__main__':
    print bestIndent(tuple(fileinput.input()))


Produto cartesiano Proposital

Question: Eu precisario criar um produto cartesiano proposital, para um relatório em Fast reports
ou seja multiplicar meus dados por um numero determinado
EX:
select
  cli.cdclifor,
  CLI.nmCliFor
from
  cadclifor cli
where  cli.cdclifor = '000001'

resultado:
000001 Jõao das Couves

gostaria que me retornasse
resultado:
000001 Jõao das Couves
000001 Jõao das Couves
000001 Jõao das Couves

Comment: Tente deixar a pergunta mais completa, clique no [edit] e acrescente a estrutura da tabela e mais detalhes do que precisa, que aumenta a chance de uma boa resposta. Por exemplo, o que determina que saiam 3 resultados em vez de um?
Comment: pois é cara os dados são somente da cadclifor, uso um JOIN quando tenho mais de uma tabela, até tentei fazer um mas n deu muito certo
Comment: traria Jõao das Couves, Jõao das Couves Jõao das Couves,..... eu vou dizer o número de resultados mas enfim e pra uma etiqueta em fast Reports
Comment: O seguinte como é para um Relatório em Fast Reports, e o mesmo suporta Script irei passar o numero de vezes que quero repetir o valor para o relatório, e criar um script no Fast que faça um for adicionando UNION ALL select ... repetindo assim o número de vezes que quero, assim que pronto posto aqui como ficou.
Answer: Isso que eu vou escrever pode parecer absurdo, mas é prática comum em técnicas de Data Mining (em contraste com sistemas transacionais "normais", onde isso seria considerado um WTF):
Simplesmente crie uma tabela para representar números, e faça um produto cartesiano (cross join) com essa tabela:
create table numeros(
  numero integer
);

insert into numeros(numero) values(1);
insert into numeros(numero) values(2);
insert into numeros(numero) values(3);
...
(até onde você espera razoavelmente que você precisará consultar)

select
  cli.cdclifor,
  cli.nmCliFor
from
  cadclifor cli
  cross join numeros n
where  cli.cdclifor = '000001' and n.numero <= 3;

Exemplo no SQLFiddle. Pode ser que existam soluções melhores (pelo menos assim eu espero!) mas infelizmente não conheço nenhuma...

Produto cartesiano Proposital


Is there a good database backend in Django for Amazon DynamoDB?

Question: I would like to use DynamoDB for my next Django project. I have found implentation to store session data into DynamoDB, but is there backend implementation for Django to store all the database data?
Comment: Don't know of one but it'd likely be a fork of django non-rel. I've found normally it's better to use plain django than trying to use non-rel.
Answer: I don't think there are any Django DynamoDB projects out there that allow you to use the Django ORM while using DynamoDB underneath.
But depending on your case, you may still be able to simply ignore the ORM portion of Django and use DynamoDB directly (via boto or PynamoDB or similar ).
In my case, I use a mix. I keep all my users and other models that are mostly read only on Postgres (RDS) and Django ORM, but use DynamoDB for models that require heavy writes ( using pynamodb).
I still get to use the views, templates or even add an API via Django-rest-framework. What I lose is the admin pages ( that I don't need for these models ) and other features the ORM gives you but I have been happy with the result anyway.
Comment: I have been taking the same approach. Seems to work fine.
Answer: I have not used this one personally but the guy who developed it is a frequent contributor to boto and his work has always been of high quality.
https://bitbucket.org/maxnoel/dynamodb-mapper
Comment: Actually, I guess this doesn't really solve your problem.  At least not directly.  This project provides an ORM mapper on top of DynamoDB but it doesn't provide a Django backend.  Sorry.
Answer: Here is a project on github called django dyanmodb sessions which looks incomplete (no closing of sessions), but promising.  Here is a link to an announcement from one of the authors.
Comment: Looks like the repo is archived and there doesn't seem like there is a maintainer willing to take it on


Solve the following integration

Question: $$\int \sqrt{cot\theta} d\theta$$
I tried to set $t=\sqrt{cot\theta},t^2=cot\theta$ and substitute into the original integration and get$$-\int\frac{2t^2}{1+t^4}dt$$, but then what can I do?
Comment: http://www.wolframalpha.com/input/?i=integrate+%282x%5E2%29%2F%281%2Bx%5E4%29
Comment: I am asking for a detail procedure...
Comment: WA's step by step solution is very long and ugly, where did you find this integral?
Comment: http://math.stackexchange.com/questions/425603/integral-int-sqrt-cot-x-dx
Answer: Consider that $$t^4+1 = (t^4+2t^2+1)-2t^2 = (t^2+1)^2-(\sqrt{2}\,t)^2 = (t^2+\sqrt{2}\,t+1)(t^2-\sqrt{2}\, t+1)$$
hence:
$$\frac{2t^2}{t^4+1}=\frac{t}{\sqrt{2}\, t^2 -2t+\sqrt{2}}-\frac{t}{\sqrt{2}\, t^2 +2t+\sqrt{2}}\tag{1}$$
and the integral of both terms in the RHS is given by:
$$\frac{1}{2\sqrt{2}}\left(\log(\sqrt{2}\, t^2 \pm 2t+\sqrt{2})-2\arctan(1\pm\sqrt{2}\,t)\right).\tag{2}$$
Answer: Consider the integral
\begin{align}
I = \int \sqrt{\cot(\theta)} \, d\theta.
\end{align}
Make the substitution $t = \sqrt{\cot(\theta)}$ to obtain the integral
\begin{align}
I = -2 \int \frac{t^{2} \, dt}{1+t^{4}}.
\end{align}
Now it can be seen that
\begin{align}
\frac{t^{2}}{1+t^{4}} &= \frac{t^{2}}{(1+i t^{2})(1- i t^{2})}  \\
&= \frac{1}{2i} \left( \frac{1}{1-i t^{2}} - \frac{1}{1+ i t^{2}} \right)
\end{align}
which leads to
\begin{align}
I = i \int \left( \frac{1}{1-i t^{2}} - \frac{1}{1+ i t^{2}} \right) \, dt.
\end{align}
Since
\begin{align}
\int \frac{dt}{1+a t^{2}} = \frac{1}{\sqrt{a}} \, \tan^{-1}(\sqrt{a} t)
\end{align}
then the integral $I$ becomes
\begin{align}
I = i \left[ e^{\pi i/4} \tan^{-1}(e^{\pi i/4} t) - e^{- \pi i/4} \tan^{-1}(e^{- \pi i/4} t) \right].
\end{align}
By the $\tan^{-1}(x)$ addition and eliminating the complex components the result becomes
\begin{align}
I = \frac{1}{\sqrt{2}} \left[ \tan^{-1}\left( \frac{\sqrt{2} \, t}{1- t^{2}} \right) - \tanh^{-1}\left( \frac{\sqrt{2} \, t}{1+ t^{2}} \right) \right].
\end{align}
This leads to the result
\begin{align}
\int \sqrt{\cot(\theta)} \, d\theta = \frac{1}{\sqrt{2}} \left[ \tan^{-1}\left( \frac{\sqrt{2 \cot(\theta)}}{1-\cot(\theta)} \right) - \tanh^{-1}\left( \frac{\sqrt{2 \cot(\theta)}}{1+\cot(\theta)} \right) \right].
\end{align}

Solve the following integration


Why this code is valid: "(1,eval)('this')"

Question: Why next code is valid Javascript code?
var global = (1,eval)('this');

alert(global);

Answer: That's because the comma operator returns its second operand (and evaluates both).
The code in your question is equivalent to:
1;
var global = eval('this');
alert(global);

Comment: @Sheikh, I did link to the MDN documentation in my answer :) Basically, `(1, eval)` applies the comma operator `,` to `1` and `eval`. The operator evaluates `1`, then evaluates and returns `eval`. Therefore, `foo = (1, eval)(something)` is equivalent to `1; foo = eval(something);`.
Comment: Can you explain or may be some link will be useful too, really confused.


What is "size" in flare json -- used in D3 examples?

Question: My colleague and I are working with a D3 visualization. Specifically we are starting with this example. This visualization appears to use some kind of json related to the  flare API
In the sample json, there's lines like:
<code> "name": "cluster",
 "children": [
  {"name": "AgglomerativeCluster", "size": 3938},
  {"name": "CommunityStructure", "size": 3812},
  {"name": "HierarchicalCluster", "size": 6714},
  {"name": "MergeEdge", "size": 743}
</code>
I understand that stuff after "name" relates to a Flare class. What I can't seem to find, despite lots of googling, is what exactly "size" is and what its units are? More generally, where can one find some kind of specification on flare's json format and what it means?
Comment: No, `"size"` can be used to represent a value associated with the entity.  For example, if we had `"name": "Stackoverflow"` and `"size": "3,000,000"`.  In this case "size" would represent the number of members in here.  D3 takes this value and computes the appropriate radius for this node by taking into account the number of nodes and the size of the diameter.  I hope that makes sense.
Comment: I think it is used to determine the size of the node.  As you can see in this snippet:

`var pack = d3.layout.pack()
    .size([diameter - 4, diameter - 4])
    .value(function(d) { return d.size; });` `size` is passed in to the `value` function which computes the radius for the node.
Comment: @icanc size in pixels?
Comment: I added this snippet Tejen suggested,  `var pack = d3.layout.pack().size([ 4, 4]).value(function(d) { return d.size; });` but even if I manipulate the flare.json and make for one of the nodes the 'size' very large, its diameter doesn't change. What do you mean value function. In the original http://bl.ocks.org/mbostock/4339083 or http://bl.ocks.org/mbostock/4063570 there is no value function. Can you please suggest where should this snippet be entered to have an effect on radius and instead of value function which other corresponding function from the collapsible example would it be? Thanks!
Answer: It is not used by the node-link tree layout example that you are referring to. The size is used in other examples like treemap, bubble layout, circle packing,
bubble layout, icicle, sunburst, etc. You will see the impact of size using the flare.json file with those examples.


Converting string encoding so it displays accents

Question: In php I have strings such as:

Independ%C3%AAncia

and I want to convert it to:

Indepêndencia

Checking the encode php says it is ACSII which is a subset of UTF8.
So how can I make that conversion?
Answer: You can use urldecode():
php > echo urldecode('Independ%C3%AAncia');
Independência
php >


Installing DeepLearning4j fails with eclipse plugin

Question: I downloaded the entire project and import into Eclipse, but fails on this plugin:
<code>Description Resource    Path    Location    Type
Plugin execution not covered by lifecycle configuration: com.lewisd:lint-maven-plugin:0.0.11:check (execution: pom-lint, phase: validate)   pom.xml /dl4j-examples  line 8  Maven Project Build Lifecycle Mapping Problem
</code>
What's the problem and how to get it compiled?
Answer: You should only be using m2eclipse. You don't need to "import the whole project" It's actually 6 projects total. You are better off downloading our examples where it will be managed for you. We cover this in our quick start (granted it's with intellij but the ideas are similar):
http://deeplearning4j.org/quickstart
Comment: I tweaked the POM a bit and it solved the "lint-maven-plugin" problem. However, I received a "log can not be resolved" problem. In some classes, i.e. "FitFromFeaturized", the "log.info()" is used, but "log" is not defined in the class. So it complaints this. Where is this log defined in some classes?
Comment: So wait..I mentioned the examples not deeplearning4j itself. You shouldn't be importing that. You don't need to. I'm only guessing you are doing this (you really shouldn't did I mention that?) because that will happen because of lombok. You can use maven to both obtain the sources of releases as well as for dependency management.
Comment: Yes. I git the whole dl4j projects and "mvn clean install" without problems. After I imported all the projects in Eclipse and fixed the lint plugin problems, all projects worked fine except "dl4j-cuda-specific-examples" and "dl4j-spark", in which the "log" is missing. How to fix the lombok issue in Eclipse?
Comment: @user697911can you please share how you've fixed the com.lewisd:lint-maven-plugin problem?
Comment: So for anyone looking at this...we generally shouldn't have lombok anywhere in the examples. This was fixed long ago.


Unable to configure MaxMindDB's Apache module

Question: I recently installed MaxMind's MaxMindDB apache module successfully.
I added a new file called geoip.conf to /etc/httpd/conf.d/ with the following contents:
<IfModule mod_maxminddb.c>
    MaxMindDBEnable On
    MaxMindDBFile COUNTRY_DB /some/dir/GeoLite2-Country.mmdb
    MaxMindDBEnv MM_COUNTRY COUNTRY_DB/country/iso_code

    SetEnvIf MM_COUNTRY US AllowUS
    Deny from all
    Allow from env=AllowUS
</IfModule>

When running apachectl -t I get the following error:
Syntax error on line 11 of /etc/httpd/conf.d/geoip.conf:
deny not allowed here

When I commented out the "Deny from all" line I got a similar error stating that allow not allowed here
I was unable to find anything online as this module has little documentation. Does anyone know how to fix this?
Comment: #Geo Restrict
                MaxMindDBEnable On
#               MaxMindDBFile DB /path/to/GeoIP/GeoLite2-Country.mmdb
                MaxMindDBFile DB /root/GeoIP/GeoIP.dat
                MaxMindDBEnv MM_COUNTRY_CODE DB/country/iso_code

                SetEnvIf MM_COUNTRY_CODE ^(RU|DE|FR|US|CN) BlockCountry
                Deny from env=BlockCountry
How to enable this module
Answer: This is simply because your Deny and Allow need to be applied within a container, either a <Directory>, <Files> or <Location> section.