If $g$ is Riemann-integrable in a closed interval and $f$ is a increasing function in a closed interval, is $g\circ f$ Riemann-integrable?

Question:
If $g$ is Riemann-integrable in a closed interval and $f$ is a increasing function in a closed interval, is $g\circ f$ Riemann-integrable?

To clarify: the problem stated that the composition is well defined. I think that the statement of the question is true but Im having trouble to write/concrete a proof.
I know that a monotone function defined in a closed interval is Riemann-integrable by a previous result. And I know that the reverse statement ($g$ being monotone and $f$ integrable) is not true in general.
After thinking some moment my idea for the proof is to show that $g\circ f$ have, at most, countable discontinuities. To do this I was thinking how to show some kind of order-correspondence between the points of the domain of a monotone function and it image.
Can you help me? I get stuck and it is very possible that Im wrong in my assumption about that the statement is true. Some hint will be appreciated.
EDIT: I get a new idea, design a partition of $f$ that take any possible discontinuity into a closed interval of known length, and after see what happen in the composition with this closed intervals with discontinuities, and by the other hand see what happen with the parts of continuous mapping.

After reading this answer I get the idea to provide a proof for the validity of the statement.
First I will characterize the different kind of images of closed intervals that a monotonic function can create. For an increasing function we have that $x<y$ implies that $f(x)\le f(y)$, and that at most a monotone function can have a countable number of discontinuities in any closed interval.
No discontinuities on the image: if the image of $f([x_1,x_2])$ is continuous then it can be at most of three types:

A constant function $f([x_1,x_2])=\{a\}$. Then $(g\circ f)([x_1,x_2])=g(\{a\})=\{c\}$, then the function $(g\circ f)$ is constant in $[x_1,x_2]$ so is Riemann-integrable
A strictly increasing function i.e. $f([x_1,x_2])=[a,b]$. Then $(g\circ f)([x_1,x_2])=g([a,b])=[c,d]$. If $g$ is Riemann integrable in $[a,b]$ then exists a sequence of partitions $(P_n)$ such that

$$\lim_{n\to\infty}U(g,P_n)-L(g,P_n)=0$$
Then because $f$ is bijective in $[a,b]$ then for every $P_n$ exists a partition $P'_n$ in $[x_1,x_2]$ such that
$$\lim_{n\to\infty}U(g\circ f,P'_n)-L(g\circ f,P'_n)=0$$
so $g\circ f$ is Riemann-integrable in $[x_1,x_2]$

A mix of both previous cases. Then the interval $[x_1,x_2]$ can be partitioned on types of subintervals discussed previously (constant and strictly monotonic images), so $g\circ f$ is Riemann-integrable here too.

Discontinuity in the image: a jump discontinuity in $[x_1,x_2]$ is mapped into two types of the previously discussed intervals with the difference that can be the case that in the image exists an interval with an open boundary of the kind $[a,b)$ or $(a,b]$.
But cause $f$ and $g$ are Riemann integrable in closed intervals this mean that they are bounded, and if $g$ is integrable in any subinterval $[a-\varepsilon,b]$ then is integrable in $(a,b]$ (this is known by a previous proof).
My question: it is this proof correct? It lacks something essential? Can you help me to write it better? Thank you in advance.
EDIT 2: as the user @ParamanandSingh pointed in the comments it is possible that the discontinuities cannot be isolated, one by one, inside some interval. So I will search further for a correct proof of the statement.
Comment: But this is not enough to prove it @Epsilon, I have a counteraxample: the Tomae function $t(x)$ and the function $f(x)$ that map $0$ if $x=0$ and $1$ if $x\neq 0$. Both are Riemann-integrable but the composition $f\circ t$ is the Dirichlet function, what is not.
Comment: Your result is false. See http://mathoverflow.net/q/20045/15540
Comment: I don't think there is a counterexample available without measure theory (at least I am not aware of). Had you asked for continuous $f$ instead of increasing $f$ then there is a counterexample http://math.uga.edu/~pete/Lu99.pdf which uses elementary ideas.
Comment: BTW +1 for asking this non-trivial question. It appears very few textbooks / instructors/students ponder over this question.
Comment: OK, The linked question does not contain proofs and hence I was myself not sure. The question there dealt with continuous function instead of increasing function. And yes after reading the first and second answer I find them contradictory. I will post a comment on mathoverflow question to get more details.
Comment: see http://math.stackexchange.com/q/69317/72031 and http://math.stackexchange.com/q/172753/72031
Comment: @Fimpellizieri: The accepted answer uses some stuff from measure theory to construct a counterexample (moreover this example is not given in a direct manner in terms of values of $f$) and I don't really have much idea about measure theory so it is difficult for me figure out. if you have understood the answer properly can you elaborate a bit here about the counterexample (perhaps as an answer to this question).
Comment: Riemann or Lebesgue?
Comment: @HagenvonEitzen Oh, sorry, Riemann.
Comment: $f$ and $g$ have only countably many discontinuities so $g \circ f$, too.
Comment: @Epsilon: what you say is not true because $g$ does not necessarily have countably many discontinuities.
Comment: Thank you @ParamanandSingh but I cant use the link response because I dont know anything about measure theory. It is supposed I can solve this using basic notions of continuity, the Darboux characterizations of Riemann integrability and some other corollay/theorems close to these things. But now I know I must search a counter-example.
Comment: Every increasing real valued function must have at most a denumerable set of discontinuities. See http://math.stackexchange.com/questions/84870/how-to-show-that-a-set-of-discontinuous-points-of-an-increasing-function-is-at-m
Comment: I already know @user255306 but if you read my commentary above this is not enough to prove or disprove integrability of composition of functions.
Comment: I'm sorry, I missed that. But, isn't the set of discontinuities of the composite contained in the union of the each separate functions and as such, denumerable?
Comment: @ParamanandSingh in the question you linked, in the second response, it is said that [the statement is true](http://mathoverflow.net/a/20048).
Comment: Duh on me,the statement is false. Which of course,you know by now. But this is rather interesting-on the surface,the statement doesn't look much more complicated then proving the sum or scalar multiple of R-integrable functions is a R-integrable function.But it happens to be false.
Comment: @Mathemagician1234 in some link above it seems that the statement is true. If is not please provide some explanation or example, thank you.
Comment: @Masacroso The classic counterexample is the composition of the Thomae's function with the following map: $ g(x) =
\begin{cases}
0,  & x =0 \\
1, & x > 0
\end{cases}$ This composition resulting in the characteristic function on the rationals,which clearly isn't Riemann-integrable. So in general it's false.
Comment: Please @Mathemagician1234 read the question and the comments. This counterexample cannot be applied. $\sin(x)/x$ is not an increasing function. Neither Tomae. The last example you put is the inverse of this question, I leaves this counterexample above in the comments.
Comment: @Masacroso You altered your original question specifically because of counterexamples like this,so my response is no longer valid. Sigh.I think this question is probably better suited for Math Overflow anyway.
Comment: What @Mathemagician1234? Im the OP and I dont altered **nothing**? Are you trolling me?
Comment: @Masacroso NO,a misunderstanding. No trolling intended,believe me.
Comment: I think the part where you deal with increasing functions with discontinuity is troublesome. You seem to assume that if $a$ is a discontinuity then there is a neighborhood of $a$ where there is no other discontinuity. Note that this leads to handling of a finite number of discontinuities. But here the discontinuities can be countable.
Comment: @ParamanandSingh I see. But [for a monotone function](http://math.stackexchange.com/questions/1812041/trouble-proving-that-monotone-function-can-have-only-jump-discontinuities) in a compact set the discontinuities are of the kind of jump discontinuities. For this type of discontinuity it is the case that these neighborhoods exists, I can isolate these discontinuities one by one.
Comment: I am not sure but isn't is possible to have monotone function discontinuous at rationals (rationals are countable)?
Comment: Oh, ok @ParamanandSingh, I see my fault. I will check all this information later. Thank you very much.
Comment: @ParamanandSingh I've read the accepted answer in your linked question and I can't really find fault with it. It is easy to see that the concrete examples of $f$ and $g$ provided are valid. The other answer, however, I can't quite follow.
Answer: I will try to explain the counterexample provided in ParamanandSingh's math overflow link. We will need a few prerequisites but they're hopefully not too advanced.

Null Set/Measure Zero Set: A null set $N \subset \mathbb{R}$, also called a measure zero set, is a set that can be convered by a countable union of intervals with arbitrarily small total length. See this wikipedia link.

Measure zero here anticipates the Lebesgue measure for the reals. The Lebesgue measure assigns 'length' to sets of the real line in the natural/expected way. There's technicalities involved, but all we'll really need from it is that the measure of an interval with endpoints $a<b$ is $(b-a)$.

Lebesgue Criterion (for Riemann integrability): A bounded function on a compact interval is Riemann-integrable if and only if its set of discontinuities has measure zero. See this wikipedia link.

This criterion characterizes how 'small' a function's set of discontinuities needs to be for that function to be Riemann-integrable. It is a standard (though not trivial) result with many proofs lying around; no measure theory is needed!

Cantor and Fat Cantor Sets: The standard, ternary Cantor set has measure zero; see this wikipedia link. There are Cantor sets with positive measure; for instance, the Smith-Volterra-Cantor set.

We can deduce these using lenghts of intervals! Let $C$ be the ternary Cantor set.
At the first step, we delete an interval of length $1/3$ from $C_0=[0,1]$, obtaining $C_1$. At the second step, we delete two intervals, each of which has length $1/9$, from $C_1$, obtaining $C_2$. More generally, at the $n$-th step we delete $2^{n-1}$ intervals, each of which has length $3^{-n}$, from $C_{n-1}$, obtaining $C_n$.
Thus, the total length deleted this way is $$\sum_{n=1}^{\infty}\frac{1}{2}{\left(\frac{2}{3}\right)}^n=\frac{1}{2}\frac{\frac23}{1-\frac23}=1$$
which is the length of $[0,1]$, the interval we began with. It follows that the ternary Cantor set $C$ -- what remains after all deletions -- has measure zero.
Calculations for the Smith-Volterra-Cantor set $S$ are similar. At the $n$-th step, $2^{n-1}$ intervals, each of which has length $2^{-2n}$, are deleted from $S_{n-1}$, obtaining $S_n$. Therefore, the total length deleted this way is $$\sum_{n=1}^{\infty}\frac{1}{2}\frac{2^n}{2^{2n}}=\frac{1}{2}\sum_{n=1}^{\infty}\frac{1}{2^n}=\frac{1}{2}\frac{\frac12}{1-\frac12}=\frac12$$
The measure of $S$ is simply $1$ (the measure of $[0,1]$, the interval we began with) minus $\frac12$ (the total measure of what we discarded), that is, $S$ has measure $\frac12$. In particular, it has positive measure and is not a null set.

Now that we have the prerequisites, let's dive onto the counterexample. First, let $f:[0,1]\longrightarrow \mathbb{R}$ be the characteristic function of the ternarcy Cantor set $C$, that is:
\begin{equation}
f(x)=\left\{\begin{array}{ll}1&\text{if $x \in C$}\\0&\text{if $x \notin C$}\\\end{array}\right.
\end{equation}
Notice that $f$ has discontinuities precisely on $C$; a good way to see this is to notice that at each step in the construction of $C$, $f$ is defined to be $0$ on the deleted intervals (so it is clearly continuous in their interior) It follows by the Lebesgue Criterion that $f$ is Riemann-integrable.
Finally, we will define a monotone increasing function $g:[0,1] \longrightarrow \mathbb{R}$ that maps the Smith-Volterra-Cantor set $S$ to $C$. We will obtain $g$ as the limit of a sequence of functions.
Let $S_0=C_0=[0,1]$, let $S_n$ be what remains in the construction of $S$ after $n$ steps, and similarly for $C_n$. Notice that each of $S_n$ and $C_n$ is a disjoint union of $2^n$ closed non-degenerate intervals; we may describe each of them by its collection of $2^{n+1}$ endpoints. For instance, in the obvious notation $C_0=S_0\sim\{0,1\}$, $C_1\sim\left\{0,\frac13,\frac23,1\right\}$ and $S_1\sim\left\{0,\frac38,\frac58,1\right\}$.
Define $g_n:[0,1]\longrightarrow\mathbb{R}$ as follows. Let $S_n\sim\{s_k\}$, where $k$ ranges from $1$ to $2^{n+1}$ and the $s_k$ are increasing. Similarly, let $C_n\sim \{c_k\}$. For all $k=1,\dots,2^{n+1}$ put $g_n(s_k)=c_k$, and extend it to all of $[0,1]$ linearly. In other words, $g_n$ fits the $i$-th interval in $S_n$ into the $i$-th interval in $C_n$, and fills in the blanks with linear pieces. It's easy to see that $g_n$ is increasing (and continuous!) for all $n$.
It's not too hard to see that $g_n$ converges pointwise for all $x \in [0,1]$; we define $g$ to be this limit function. It follows immediately that $g$ is increasing and maps $S$ to $C$. (It's a bit of work, but one can show that the convergence $g_n\to g$ is actually uniform, so that $g$ is indeed continuous!)
At last, the composition $f\circ g$ has $S$ for its set of discontinuities. Since $S$ has positive measure, it follows by the Lebesgue criterion that $f\circ g$ is not Riemann-integrable, which concludes the proof.
Comment: @ParamanandSingh I've tried to explain the answer in your link here. I hope it sheds some light into the problem. I will now go to sleep but will check on this tomorrow.
Comment: Thanks a lot for this answer. It really uses bare minimum of measure theory stuff with which I am already familiar. The essential idea is that $S$ has positive measure and each point of $S$ has nearby points which are not in $S$. This ensures that $f\circ g$ is discontinuous at $S$ and the job is done.
Comment: BTW +1 for the nice answer. Your construction of $g$ reminds me of a similar function called Devil's staircase where we actually create a function $g$ which is continuous and increasing and differentiable at every point of $[0, 1]$ except the cantor set and $g'(x) = 0$ for all $x$ in $[0, 1]$ except cantor set so that $$g(1) - g(0) = 1 \neq \int_{0}^{1}g'(x)\,dx = 0$$ this serves to illustrate why fundamental theorem of calculus fails for Riemann integrals in unexpected ways.
Comment: @Masacroso: "Fill in the blanks with linear pieces" does not mean fill with constant value. That will make $g_{n}$ discontinuous. I will show what to do for $g_{1}$. We have $C_{1} = \{0, 1/3, 2/3, 1\}, S_{1} = \{0, 3/8, 5/8, 1\}$. Now plot the points $A = (0, 0), B = (1/3, 3/8), C = (2/3, 5/8), D = (1, 1)$ on graph and join line segments $AB, BC, CD$. The resulting figure is graph of function $g_{1}$ which is clearly increasing (strictly) and continuious.
Comment: Where you says "fills in the blanks with linear pieces" we can fill this with a constant value for example (to be the more simple possible)? One more thing: $S$ have uncountable points (I suppose) as the standard Cantor set $C$, right? Other thing: I edited what I think is a little typo, you write $a_k$ instead of $s_k$. Just check it if Im wrong.
Comment: That was a typo indeed, thank you for the correction. The explanation from @ParamanandSingh is what I meant with "fill in the blanks with linear pieces". Also, thank you! The construction is indeed quite similar to the Devil staircase; the idea behind it is fundamentally the same.


How can we configure the Master slave concept in Drupal 7?

Question: I have one large scale website and hosted on AWS. I want to enable Master-Slave concept on it. How can it be possible to configure the same?
Answer: Yes, Drupal supports master/slave style database replication.
Note: master/slave replication configuration is done at the database server level. Drupal simply utilizes the replicated databases by using the slave server when one database isn't available, or for specific 'slave' marked queries ( see db_query "target" option ).
See the fully commented default.settings.php for Drupal configuration details.

For each database, you may optionally specify multiple "target"
databases. A target database allows Drupal to try to send certain
queries to a different database if it can but fall back to the default
connection if not. That is useful for master/slave replication, as
Drupal may try to connect to a slave server when appropriate and if
one is not available will simply fall back to the single master
server.
The general format for the $databases array is as follows:

$databases['default']['default'] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['default']['slave'][] = $info_array;
$databases['extra']['default'] = $info_array;
Answer: You may want to try out the AutoSlave module.

This database driver (called "autoslave") will automatically use the database slaves where applicable and otherwise use a master database.
Applicable means:

The query is not a write query (and not a select query with locking)
The tables in the query have not been written to during the request and within the assumed replication lag
A transaction has not been started
The tables in the query are not specified in the 'tables' option in the driver settings
A lock has not been started (core db-lock and memcache-lock supported)

I'm the author of the module; if you decide to try it out, feedback is appreciated.
Comment: is there a way to use redis as a cache instead of memcache?


Why does Qt's version of libstdc++-6.dll work, but not MinGW?

Question: I'm very new to C, Netbeans, Qt, and any linking more complicated than import antigravity. I'm getting confused trying to setup Netbeans for Qt. I'm on Windows 7.
I installed MinGW, and then separately installed the Qt SDK. When I installed the latter, I opted out of MinGW, since I already had that. I think I have all the paths set up correctly in Netbeans - I can build a basic Qt app.
When I try to run the app, I get this error:
*
I have two copies of that DLL on my PATH: the one that came with MinGW, and the one that came with Qt. When I copy paste the MinGW one into the app folder and run the app, I get the above error. When I copy paste the Qt one into the folder, no errors.
So there's a difference between the Qt DLL and the MinGW one. This is very unsetlling to me. What is this DLL, why is it in my Qt install if I chose not to include MinGW, and why is it different from the one in my MinGW install? Should I just rip MinGW and Qt out of my system and reinstall a fresh Qt SDK with the included MinGW? I want to do other kinds of C programming than just Qt, so it felt "right" to me to have separate MinGW install.
Answer: What's happening:
It's finding the DLL but cannot find the requested object within that DLL. The mingw library probably has different content than the stdlib library. You have a mismatch between different sets of code.
My suggestion:
Use the Mingw packaged with Qt. They've done the work validating it works with Qt. Why not take advantage of it?
When I did this last year I did have to search for the right version of make. It wasn't provided at the time.


Why does main() not need a return statement?

Question:
Possible Duplicate:
return 0 implicit
Why is return 0 optional?

why does the main() function in C can terminate correctly even without using exit or return?
for example:
#include<stdio.h>

int sum(int a,int b)
{
 return (a + b);
}

int main()
{
 int a=10;
 int b=5;
 int ans;
 ans=sum(a,b);
 printf("sum is %d",ans);
}

Comment: @freeboy1015 Just ad Ed noted, if your questions have been answered with what you needed, please click on the check mark next to the most suitable answer.

You can view your older questions by clicking on your profile and then going to Questions.
Answer: It's because the C99 and C11 standards says so:

18.104.22.168.3 Program termination
Reaching the } that terminates the main function
  returns a value of 0. If the return type is not compatible with int,
  the termination status returned to the host environment is unspecified.

However, you should add a return statement. This is because the returned value is undefined in C89 otherwise!

22.214.171.124 The return statement
Reaching the } that terminates a function is equivalent to executing a
  return statement without an expression.
126.96.36.199 Hosted environment
If the main function executes a return that specifies no value, the
  termination status returned to the host environment is undefined.
Comment: And for the record, C99 and C11 are completely identical in this matter.
Comment: This looks like the only sensible answer.
Answer: Because the compiler adds an implicit exit for you.
Check nightcracker on why; still I strongly recommend you make an explicit exit/return with a meaningful return code.
C99 standard:

If the return type of the main function is a type compatible with int,
  a return from the initial call to the main function is equivalent to
  calling the exit function with the value returned by the main function
  as its argument;10) reaching the } that terminates the main function
  returns a value of 0. If the return type is not compatible with int,
  the termination status returned to the host environment is
  unspecified.

I am looking for the C89 text to check.
Comment: @Kirilenko Yes, in C89, you _must_ have a `return` (I'm not even sure whether an `exit` instead of the `return` was compliant then). On the other hand, in C99 you _must_ declare the return _type_ of `main`.
Comment: C89 and C99 are different here, aren't they?
Answer: Because if the execution terminates without either it assumes it is successful i.e. returns 0.
Answer: Primary, your compilator will not tell you anything if you don't use Flags.
If you use severe flags, your compilator will tell you every little missing detail.
Returning something is important, the program which started your can be informed on the succeful or not execution of your program. If your program return nothing (so 0 by default), the terminal in which you started it, for instance, will assume that it worked perfectly even if it failed.
Answer: Because the compiler adds it for you.
On unix/linux you can try this little script:
retval.sh
#!/bin/sh
$1
echo $?

Then run your program through it:
./retval.sh yourprogram

It will output the return value of your program. You will see main() even if you add no return or exit() will return an integer value.


Click event not triggered after focusout event

Question: After the Focusout event, the click event is not triggered.
My design is,
<textarea id="txt"></textarea>
<input type="button" id="btnClick" value="Submit" />

jQuery,
$(document).ready(function () {
var field = $("#txt");
var btn = $("#btnClick");
field.on("focusin", f1);
field.on("focusout", f2);
btn.on("click", f3);

function f1() {
    field.removeClass("c1").addClass("c2");
}

function f2() {
    field.removeClass("c2").addClass("c1");
}

function f3() {
    alert('hi');
}
});

Style,
.c1 { height:40px; }
.c2 { height:250px;}

And I have also attached Fiddle here.
Comment: In the javascript variable declarations seems unnecessary, please try this updated fiddle. http://jsfiddle.net/YQxXN/8/
Comment: @Pratik, Thanks for the consideration. I have used some external functions inside the functions block (f1,f2,f3) and field and btn values are dynamic in my real time code.
Comment: such cases are appropriate then, but my reference was the code posted.Hope you have solved your problem by any way. :)
Answer: Thats because it doesn't have enough time to get the click to trigger since the button moves position. You can see the click works if you hold the mousedown and move the mouse to the button and let the click go and you'll see click works.
Either use btn.on('mousedown',f3); or position the button so it doesn't get moved on focusout
DEMO mousedown
DEMO button positioned
The way click works is that you have mousedown on an element and mouseup on it aswell, thats when it triggers click
Comment: you rock! perfect solution :D
Answer: After the Focusout event first focus out from textarea then it will take click action of
button
in js
$(document).ready(function () {
    var field = $("#txt");
    var btn = $("#btnClick");
    field.on("focusin", f1);
    field.on("focusout", f2);
    btn.on("click", f3);//use btn.on("mousedown", f3); here to prevent the focusout before click

    function f1() {
        field.removeClass("c1").addClass("c2");
    }

    function f2() {
        field.removeClass("c2").addClass("c1");
        alert("focusout");
    }

    function f3() {
        alert('hi');
    }

});

demo
Comment: That doesn't alert "hi"
Comment: It doesn't work since it doesn't alert "hi" when you click from textarea to the button @Riturajratan The only difference from this and OPs code is that it just alerts "focusout" on focusout
Comment: i already explain it why this happen  any way thanks for focus on this answer i will check again
Answer: Another way is to give a timeout of the focusout event. For example:
object.addEventListener('focusout', function() {
    /* Set some timeout */
    setTimeout(function () {
    // Things to do before the focus is out
    }, 50)
});


ng-View não renderiza o conteudo - AngularJS

Question: Quando acesso meu index.php, peço nas configuração de rotas do meu Angular que ele chame a view "index.php" dentro da pastar "view", porem ele acha mas não renderiza nada na minha tela

var app = angular.module('app',['ngRoute']);

app.config(function($routeProvider,$locationProvider){
 $routeProvider
  .when('/',{
   templateUrl: 'view/index.php',
   controller:'search'

  }).otherwise({redirectTo:"/"})

    //Se descomentar tbm não funciona
 //$locationProvider.html5Mode(true);
})
<!DOCTYPE html>

 <meta charset="UTF-8">
 <title>Document</title>
 <link rel="stylesheet" href="/assets/css/bootstrap.min.css">
 <link rel="stylesheet" href="/assets/css/font-awesome.min.css">

   Teste

Home

Answer: então! quase certeza que é a falta da chamada da controller: que você definiu ai.

ou

Comment: Isso não é necessário. O controller será instanciado no momento que a view renderizar a página.
Comment: Fala Luiz, obrigado pela atenção, mas avisa sido bobeira minha, eu tinha invertido o nome de um controller nas configs, ja arrumei!

Vlw


Parameter is not valid - PictureBox em C#

Question: Estou a fazer um visualizador de ficheiros TIFF em VisualStudio 2017, na linguagem C#.
Consigo abrir o ficheiro TIFF, se for multipage vai separá-lo por páginas e consigo mostrar cada página e navegar por elas. O meu problema é quando vou abrir outro TIFF.
Eu fecho o ficheiro e quando abro outro, aparece-me o erro

Parameter is not valid.

na linha em que torno visível a PictureBox.
Podiam me dizer o que está de errado no meu código ou se devo fazer as coisas de outra maneira? Obrigada desde já.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
    pbtiff.Hide();
    OpenFileDialog dialogo = new OpenFileDialog();
    dialogo.Title = "Search files";
    dialogo.InitialDirectory = @"E:\";
    dialogo.Filter = "PDF Files(.pdf)|*.pdf|Image Files (.bmp,.jpg,.png,.tiff,.tif) |*.bmp;*.jpg;*.png;*tiff;*tif";
    DialogResult answer = dialogo.ShowDialog();
    if (answer == DialogResult.OK)
    {
        string fullPath = dialogo.FileName;
        openFile = fullPath;
        using (var fileStream = new FileStream(ficheiroaberto, FileMode.Open))
        {
            type = Path.GetExtension(caminhoCompleto);
            if (type == ".tif" || type == ".tiff")
            {
                up.Visible = true;
                up.Enabled = false;
                down.Visible = true;
                pbtiff.Show(); //-> o erro está nesta linha, quando a abro pela segunda vez
                if (pbtiff.Image != null)
                {
                    pbtiff.Image.Dispose();
                }
                pbtiff.Image = System.Drawing.Image.FromStream(fileStream);
                SplitTiffFinal(fileStream);
                filestiff = GetFilesFinal();
                up.Visible = true;
                up.Enabled = false;
                down.Visible = true;
             }
         }
     }
 }

E o código do meu botão de fechar:
private void closeToolStripMenuItem_Click(object sender, EventArgs e)
{
    if (pbtiff.Image != null)
    {
            pbtiff.Image.Dispose();
            pbtiff.InitialImage = null;
            pbtiff.Hide();
            up.Visible = false;
            down.Visible = false;
            filestiff.Clear();
            idx = 0;
            type = "";

            DirectoryInfo path = new DirectoryInfo(@"temporarioviewer");
            DeletingFiles(path);
    }
    else
        {
            MessageBox.Show("Deve abrir um ficheiro primeiro para poder fechá-lo.", "Erro", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }
}

Comment: Sofia, bom dia! Você não teria que dar dispose toda vez ao invés de clear e depois começar o processo novamente?
Comment: @Sofia, o que é esse "IF" sem parâmetros?
Comment: @Fabioln tem razão, eu é que me enganei a copiar e a editar o código.. Aquele IF estava a mais! Erro meu
Comment: @AngeloSimonato o "clear" é de um `List`, não da PictureBox. Mas colocaria o dispose quando carregava no botão para abrir um TIFF?
Comment: @SofiaRodrigues, o dispose seria pra descartar o objeto, ai você preencheria ele novamente como fez na primeira rodada. Estou olhando pra linha que deu o erro e que você sinalizou.
Comment: @AngeloSimonato mas eu já tenho um "IF" para fazer dispose caso a PictureBox tenha uma imagem, e um dispose quando fecho o ficheiro... Onde é que teria que colocar outro dispose, se eu já tenho um em casa evento?
Answer: O erro é porque estás a chamar o método Show() depois de fazer Dispose() na propriedade Image da picturebox (através do botão de fechar).
Não sei explicar o que causa o erro internamente, mas se chamares o Show() depois de inserires uma nova imagem já não vais ter esse problema:
if (pbtiff.Image != null)
{
    pbtiff.Image.Dispose();
}
pbtiff.Image = System.Drawing.Image.FromStream(fileStream);
pbtiff.Show(); //-> o erro está nesta linha, quando a abro pela segunda vez

Comment: Era mesmo isso, foi um erro meu muito despistado... Obrigada pela ajuda!


How do I resolve Autodiscover for Exchange 2007?

Question: I'm a little confused with autodiscovery. I have autodisovery.domain.com as a secondary name in my SSL. i have an A record setup for"autodiscovery" on my ISP DNS which points to my email server. However I do not have any SRV records internally...
What other steps do I need to take?
Answer: Take a look at this article, its probably one of the best I've seen for setting up Autodiscover. (not autodiscovery) It should hopefully get you pointed in the right direction.
Also, what type of cert did you get? Was it a UC?
Comment: I got the recommended cert from Godaddy. Multi domain. Looks like a good article. I think I need to wait for the A record to provision before I get ahead of myself...
Comment: Wait for the A record to provision? What do you mean? If you created an A record it should be available immediately.
Comment: ...good catch though, I had the DNS record as autodiscovery...
Comment: DNS with the ISP...do I not need that?
Comment: Sounds like it may just be a DNS name issue, outlook is hardwired to look for specific addresses.
Comment: Well just to be clear, my cert includes my mail.domain.com and autodiscover.domain.com as a secondary address. As well, my DNS records are set for both of those addresses to point to my mail server...
Comment: As a follow up, adding the autodiscover to my ISP DNS now resolves the autodiscover testing. Thanks Dan


How to pass args and kwargs to multiprocessing Pool?

Question: If I have the following function:
def foo(a, b, c=2, d=6):
    return a + b + c + d

and I want to parallelize with multiprocessing.
How can I pass the following arguments 1, 2, d=10? i.e. 2 args and 1 kwarg?
I saw this post, but it does not seem to make it actually parallel. Another possibly useful example was provided here, but it is hard to untangle.
Comment: It's all [clearly documented](https://docs.python.org/3/library/multiprocessing.html#multiprocessing.pool.Pool.apply_async).  I doubt you can get a better answer than just reading the docs in this case.
Answer: How about:
import multiprocessing

def foo(a, b, c=2, d=6):
    return a + b + c + d

def foo_callback(result):
    print(result)

def foo_error(error):
    raise error

pool = multiprocessing.Pool()

for (a, b, c, d) in ((1, 2, 3, 4),
                     (2, 4, 6, 8),
                     (3, 6, 9, 12)):
    pool.apply_async(
        foo,
        args=(a, b),
        kwds={"c":c, "d":d},
        callback=foo_callback,
        error_callback=foo_error
    )
pool.close()
pool.join()

Which prints:
10
20
30

Process finished with exit code 0

I guess that you want to pass the kwds as a dict. The keys need to be strings.
Comment: How can I get rid of the loop and not pass `c` as a parameter?
Comment: Also, all the results are not in a `list` as they usually are with `map`, which is confusing as well. Could you please elaborate on the usage of this?
Answer: Use map or imap or async function of both function will be more simple.
from multiprocessing import Pool

def foo(args):
    a, b, c, d = args
    return a + b + c + d # or just sum(args)

with Pool(processes=80) as pool:
    iter = ((1, 2, 3, 4), (2, 4, 6, 8), (3, 6, 9, 12))
    results = pool.map(foo, iter)

print(results)


Possible to assign Azure Active Directory group users as VSTS stakeholders automatically?

Question: Can an AAD user group be assigned with "Stakeholder" permissions in Visual Studio Team Services "automatically"?
I can add an AAD group to VSTS, but when these users first log in to VSTS they are automatically granted "Basic" access by default. Is there a workaround to set "Stakeholder" as the default access level? This would allow me to more closely control the limited number of "Basic" seats available.
Ultimately, I want to use AAD groups to manage VSTS users and not have to adjust every single user account's VSTS permission levels individually.
from: https://www.visualstudio.com/en-us/docs/setup-admin/team-services/add-account-users-assign-access-levels-team-services
"Team Services automatically assigns them Basic features, if your account has seats available, or Stakeholder features, if not."
Answer: No, there isn't the way to set Stakeholder as the default access level and AAD user group can't be assigned with Stakeholder level in VSTS.
Related article: Team Services: Access with Azure Active Directory (Azure AD) groups (Q&A)

Q: How do I assign account access to Azure AD group members?
A: When these group members sign in to your Team Services account for
  the first time, Team Services assigns an access level to them
  automatically. If they have Visual Studio subscriptions, Team Services
  assigns the respective access level to them. Otherwise, Team Services
  assigns them the next "best available" access level in this order:
  Basic, Stakeholder.

On the other hand, access level is related to feature not permission, you need to specify the permission (add to corresponding group).
Visual Studio Team Services Feature Comparison
Comment: That's what I was afraid of. More work for me to manage user access levels individually. Also our IT group was hoping to manage the access (and permissions) for VSTS through AAD groups.
Perhaps a separate question, but what happens to a VSTS user (pulled from AAD) when that user account is removed or deactivated in AAD (by our IT group, perhaps when a user leaves our company)?
Comment: You can't manage the access and permissions for VSTS through AAD groups. The user still can access your VSTS even though removed from AAD, you need to remove it from your VSTS, but if you disable (Block sign in) user in Azure, the user can't access your vsts any more.
Comment: That seems a bit confusing. You're saying that you can disable a user in AAD (Azure) to prevent access to VSTS, but removing a user in AAD does not prevent access to VSTS? I guess I will need to do some trial and error testing to confirm exactly what does happen when a user is disabled and/or removed via the federated AD user account.
Comment: I mean remove the user from AAD groups instead of remove a user from AAD (mistake in previous comment).


Improving regex-based replace performance

Question: Hello everyone I want to ask about memory utilization and time required for a process. I have these following code.
I want to optimize my code so that it will be faster.
String will take more memory any alternative for that?
public String replaceSingleToWord(String strFileText) {

    strFileText = strFileText.replaceAll("\\b(\\d+)[ ]?'[ ]?(\\d+)\"", "$1 feet $2  ");
    strFileText = strFileText.replaceAll("\\b(\\d+)[ ]?'[ ]?(\\d+)''", "$1 feet $2     inch");

    //for 23o34'
    strFileText = strFileText.replaceAll("(\\d+)[ ]?(degree)+[ ]?(\\d+)'", "$1 degree $3 second");

    strFileText = strFileText.replaceAll("(\\d+((,|.)\\d+)?)sq", " $1 sq");

    strFileText = strFileText.replaceAll("(?i)(sq. Km.)", " sqkm");
    strFileText = strFileText.replaceAll("(?i)(sq.[ ]?k.m.)", " sqkm");
    strFileText = strFileText.replaceAll("(?i)\\s(lb.)", " pound");
    //for pound
    strFileText = strFileText.replaceAll("(?i)\\s(am|is|are|was|were)\\s?:", "$1 ");
    return strFileText;
}

I think it will take more memory and time I just want to reduce the complexity.I just want reduce time and memory for process what changes i need to do.is there any alternative for replaceAll function? How this code i will minimize? so that my get faster and with low memory utilization?  Thank you in advanced
Comment: Consider changing the topic to sth like "optimizing regex performance", "how to make regex file processing faster", etc. Your current title says very little about what you are actually asking about.
Comment: @Dariusz StringUtil.ReplaceEach() is useful for me ?for above code?
Comment: StringUtils is non-standard. Do you mean apache-commons? That does not use regexes.
Comment: @Dariusz Yes instead of writing regex can i use StringUtil.ReplaceEach() ?
Comment: Your last replacement is garbeld.
Comment: Why the downvoting? It's a good question!
Answer: Optimization methods:

use Pattern.compile() for each replace. Create a class, make patterns fields, and compile the patterns only once. That way you will save a lot of time, since regex compile takes place each time you call replaceAll() and it is a very costly operation
use non-greedy regexes. Instead of (\\d+) use (\\d+?).
try to not use regexes if possible (lb.->pound)?
merging several regexes with the same substitutions into one - applicable to your sqkm or feet replaces
you could try to base your api on StringBuilder; then use addReplacement to process your text.

Moreover a dot in many of your replaces is unescaped. Dot matches any character. Use \\..
Class idea:
class RegexProcessor {
  private Pattern feet1rep = Pattern.compile("\\b(\\d+)[ ]?'[ ]?(\\d+)\"");
  // ...

  public String process(String org) {
    String mod = feet1rep.match(org).replaceAll("$1 feet $2  ");
    /...
  }
}

Comment: what is difference between (\\d+)and (\\d?+) any example please.
Comment: @aditya [lazy and greedy](http://stackoverflow.com/questions/2301285/what-do-lazy-and-greedy-mean-in-the-context-of-regular-expressions) and [even more details](http://stackoverflow.com/questions/3075130/difference-between-and-for-regex/3075532#3075532)
Comment: But `\\d?+` is no replacement for `\\d+`. It should be `\\d++`, right?
Comment: @maaartinus `\\d+?`, I had a typo, corrected it some time ago
Comment: I see that you're corrected it, but somehow I thought you wanted [possessive](http://www.regular-expressions.info/possessive.html), which IMHO makes more sense.
Comment: @Dariusz You mean to say that I need to create one class for only pattern and process function contain only matcher.and when ever i need it. i wil call it ? whether it will save memory?
Comment: @Aditya the amount of memory used will not be drastically smaller that way, if at all. Using `StringBuilder` as base for your processing will save you a lot of memory allocation, that's for sure.
Answer: The StringBuffer and StringBuilder classes are used when there is a necessity to make a lot of modifications to Strings of characters.
Unlike Strings objects of type StringBuffer and Stringbuilder can be modified over and over again with out leaving behind a lot of new unused objects.
The StringBuilder class was introduced as of Java 5 and the main difference between the StringBuffer and StringBuilder is that StringBuilders methods are not thread safe(not Synchronised).
It is recommended to use StringBuilder whenever possible because it is faster than StringBuffer. However if thread safety is necessary the best option is StringBuffer objects.
public class Test{

    public static void main(String args[]){
       StringBuffer sBuffer = new StringBuffer(" test");
       sBuffer.append(" String Buffer");
       System.ou.println(sBuffer);
   }
}

public class StringBuilderDemo {
    public static void main(String[] args) {
        String palindrome = "Dot saw I was Tod";

        StringBuilder sb = new StringBuilder(palindrome);

        sb.reverse();  // reverse it

        System.out.println(sb);
    }
}

so according to your need you cal select one of tham.
Reference http://docs.oracle.com/javase/tutorial/java/data/buffers.html
Answer: Use precompiled Pattern and a loop just like Joop Eggen suggested. Group your expressions together. For example, the first two can be written like
`"\\b(\\d++) ?' ?(\\d+)(?:''|\")"`

You can go much further at the expense of readability loss. A single expression for all your replacements is possible, too.
`"\\b(\\d++) ?(?:' ?(?:(\\d+)(?:''|\")|degree ?(\\d++)|...)"`

Then you need to branch on conditions like group(2) == null. This gets very hard to maintain, but with a single loop and cleverly written regex you'll win the race. :D

what will be the regex for words like can't -> canot, shouldn't -> should not etc.

It depends how exact you want to be. The most trivial way is s.replaceAll("\\Bn't\\b", " not"). The above optimizations apply, so don't ever use replaceAll when performance matters.
A general solution could go like this
Pattern SHORTENED_WORD_PATTERN =
    Pattern.compile("\\b(ca|should|wo|must|might)(n't)\\b");

String getReplacement(String trunk) {
    switch (trunk) { // needs Java 7
        case "wo": return "will not";
        case "ca": return "cannot";
        default: return trunk + " not";
    }
}

... relevant part of the replacer loop (see [replaceAll][])

    while (matcher.find()) {
        matcher.appendReplacement(result, getReplacement(matcher.group(1)));
    }

what should i do in case of strFileText = strFileText.replace("á", "a"); strFileText = strFileText.replace("'", "\'"); strFileText = strFileText.replace("â€Â", "\'"); strFileText = strFileText.replace("ó", "o"); strFileText = strFileText.replace("é", "e"); strFileText = strFileText.replace("á", "a"); strFileText = strFileText.replace("ç", "c"); strFileText = strFileText.replace("ú", "u"); if i want to write this in one line or other way replaceEach() is better for that case

If you go for efficiency note that all the above string starts with the same character Ã. A single regex could like á|'"|... is much slower than Ã(ƒÂƒÃ'¡|¢Â€Â™"|...) (unless the regex engine can optimize it itself, which is currently not the case).
So write a regex where all common prefixes are extracted and use
String getReplacement(String match) {
    switch (match) { // needs Java 7
        case "á": return "a";
        case "'"": return "\\";
        ...
        default: throw new IllegalArgumentException("Unexpected: " + match);
    }
}

and
    while (matcher.find()) {
        matcher.appendReplacement(result, getReplacement(matcher.group()));
    }

Maybe a HashMap might be faster than the switch above.
Comment: what will be the regex for  words like can't -> canot, shouldn't -> should not etc.
Comment: what should i do in case of

        strFileText = strFileText.replace("á", "a");
        strFileText = strFileText.replace("'", "\'");
        strFileText = strFileText.replace("â€Â", "\'");
        strFileText = strFileText.replace("ó", "o");
        strFileText = strFileText.replace("é", "e");
        strFileText = strFileText.replace("á", "a");
        strFileText = strFileText.replace("ç", "c");
        strFileText = strFileText.replace("ú", "u");
if i want to write this in one line or other way replaceEach() is better for that case
Comment: @Aditya: Isn't it time for a new question? My answer is overlong already. :D
Answer: The regex patterns can be improved at spots_ [,.] or ? (instead [ ]?).
Use compiled static final Pattern s outside the functions.
private static final Pattern PAT = Pattern.compile("...");

StringBuffer sb = new StringBuffer();
Matcher m = PAT.matcher(strFileText);
while (m.find()) {
    m.appendReplacement(sb, "...");
}
m.appendTail(sb);
strFileText = sb.toString();

Optimisable with first testing if (m.find) before doing a new StringBuffer.


How to calculate the frequency of a signal without knowing the sampling frequency using Matlab

Question: I have a signal and I am using Matlab command pwelch to calculate the frequency of the signal, but the frequency I obtained is changed as I changed the sampling frequency.
For example, when using sampling frequency equal 8000, the frequency appear to be 1 Khz, while when I use 16000 sampling frequency the frequency of the signal appear to be 2 Khz.
which is the correct frequency? and is there other method to calculate the frequency of a signal without prior knowledge of the sampling frequency?
Comment: Simply put you can't.  You don't know whether the frequency components are a result of aliasing or are a true representation of the components at sampling frequency you're looking at.  I'm sorry to say that you're [SOL](http://www.urbandictionary.com/define.php?term=SOL).
Comment: can you show your matlab code?  you can use a relative high sampling rate to avoid aliasing in frequency domain.
Answer: Let's take a simple example, calculate the frequency for this signal:
[0 1 0 -1 0 1 0 -1 0 1 0 -1]
From such a signal you can only know that you frequency is 1/4*samplerate. Without the sample rate you can't calculate the frequency.


Manifold non-orientable iff. frame bundle is connected

Question: Let $M$ be a connected smooth manifold and $L(M):=\bigcup_{x\in M}L_xM$ its frame bundle where $L_xM:=\{(v_1,\dots,v_n):\{v_1,\dots,v_n\}\text{ is a basis of }T_xM\}$.

$M$ is non-orientable iff. $L(M)$ is connected.

I think I have managed to prove, that if $L(M)$ is connected then $M$ is non-orientable by assuming $M$ is orientable and showing that then $L(M)$ has two disjoint components, namely the set of all positively oriented bases and the "rest". However, I struggle on proving the converse. My idea is to use non-orientability to show path-connectedness but I cannot construct such a continuous path in $L(M)$.
Answer: It's a fact that given a path $c:[0,1] \to M$ and a (positive) basis of $T_{c(0)} M$, you can "move" this basis to $c(1)$ (the formal definition would be $\exists$ vector fields $v_1,\dots,v_n$, where $n = \dim M$, along the path such that $\{v_i(0)\}$ coincides with your starting basis), by continuity the basis of $T_{c(1)} M$ is also positive.
Now try to prove that $M$ is orientable iff for every loop $\lambda:[0,1] \to M$, the orientation on $T_{\lambda(0)}M$ is preserved when you move it to $T_{\lambda(1)}M$ in the above sense. Can you see how your question follows?
Comment: Is it possible to show connectedness without a connection (since it is needed to parallely transport the vector fields)?
Answer: Since $M$ is non-orientable, we can find for any $p\in M$ a loop $\lambda$ s.t. the orientation along $\lambda$ is reversed. Since $M$ is also connected, for arbitrary $p,q\in M$ we can find a continuous path $\gamma$ s.t. $\gamma(0)=p$, $\gamma(1)=q$. Then, by composing $\lambda\circ\gamma$ if necessary (i.e. if $\{v_i(p)\}$ and $\{v_i(q)\}$ determine opposite orientations of $T_pM$ and $T_qM$, respectively) we can connect any two bases in $L(M)$.


Node.js web server app problems

Question: I'm working on a Node.js app, using http and httpdispatcher to handle web server requests. I have the following code:
var app = require('http').createServer(handler),
    sys = require('util'),
    exec = require('child_process').exec,
    io = require('socket.io').listen(app),
    fs = require('fs'),
    dispatcher = require('httpdispatcher');

app.listen(61337);

dispatcher.setStatic('assets');

function puts(error, stdout, stderr) { sys.puts(stdout) }

function handler (request, response) {
    dispatcher.dispatch(request, response);
}

dispatcher.onGet("/", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
        fs.readFile('./assets/index.html', 'utf8', function (err,data) {
            res.end(data);
        });
});

dispatcher.onGet("/api/update", function(req, res) {
    exec("sh /path/to/update.sh &", puts);

  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('1');
});

io.sockets.on('connection', function (socket) {
    /** Socket.io coming soon */
});

I get the following errors.
path.js:360
    throw new TypeError('Arguments to path.join must be strings');

TypeError: Arguments to path.join must be strings
at path.js:360:15
at Array.filter (native)
at Object.exports.join (path.js:358:36)
at HttpDispatcher.staticListener (***/httpdispatcher.js:81:39)
at ***/httpdispatcher.js:132:3
at HttpChain.next (***/httpdispatcher.js:125:9)
at doDispatch (***/httpdispatcher.js:58:13)
at HttpDispatcher.dispatch (***/httpdispatcher.js:74:14)
at Server.handler (***/app-server.js:19:13)
at Server.<anonymous> (***/socket.io/node_modules/engine.io/lib/server.js:369:22)

The Server.handler (***/app-server.js:19:13) line is dispatcher.dispatch(request, response); in the handler function.. so I'm not sure why it's not sending strings?
Comment: `httpdispatcher` doesn't seem to be a very widely used or tested module, it's possible the error is due to some issue with its code. You may want to open an issue on its Github page.
Comment: It looks like you're just routing HTTP requests, so I'd recommend Express.js. It's very intuitive and one of the most popular frameworks for Node.js.
Comment: Do you recommend an alternative @Aweary?
Answer: I went from using httpdispatcher to express
Here is my working example:
var express = require('express'),
    app = express(),
    http = require('http').createServer(app).listen(61337),
    sys = require('util'),
    exec = require('child_process').exec,
    io = require('socket.io')(http),
    fs = require('fs');

app.use('/assets', express.static('assets'));

function puts(error, stdout, stderr) { sys.puts(stdout) }

app.get("/", function(req, res) {
    res.writeHead(200, {'Content-Type': 'text/html'});
        fs.readFile('./assets/index.html', 'utf8', function (err,data) {
            res.end(data);
        });
});

app.get("/api/update", function(req, res) {
    exec("sh /path/to/update.sh &", puts);

  res.writeHead(200, {'Content-Type': 'text/plain'});
  res.end('1');
});

io.sockets.on('connection', function (socket) {

});

Node.js web server app problems


How to set C3JS tooltip content

Question: I have a situation similar to the example shown in http://c3js.org/samples/data_json.html My simple intention is to get the name of the row (i.e. 'www.site1.com') into the tooltip header. My problem: I cannot find it in the d-values.
Can anyone help?
Answer: You cannot find it in d-values, because it's not a value actually - it's a category.
Have a look at Category Axis example, maybe it helps you:
<code>var chart = c3.generate({
    data: {
        columns: [
            ['data1', 30, 200, 100, 400, 150, 250, 50, 100, 250]
        ]
    },
    axis: {
        x: {
            type: 'category',
            categories: ['cat1', 'cat2', 'cat3', 'cat4', 'cat5', 'cat6', 'cat7', 'cat8', 'cat9']
        }
    }
});
</code>
Comment: Thanks, Dmitry. Yes, it is a category, but I don't want to display the category on the x axis. I only want to have it in the tooltip. And my main problem is to address the data.
Answer: I solved it by using the d-value to address the right category of my JSON, or rather the array in my JSON. (Seemed more complicated since I load the data after I create the chart.)

How to set C3JS tooltip content


Entity Query Condition for the referenced entity's type

Question: According to the documentation for the condition() function, you can append columns to a field name, but I haven't found a way to make a condition on the referenced entity's type.
// Something like this?
$query->andConditionGroup()->condition($referenceFieldName, $someId)
     ->condition("$fieldName.entity:type", ['character', 'movie'], 'IN')

Let's say with the above I am querying for articles that have a reference to the ID in $someId and that reference is to a content type of either character or movie. Is something like this possible with entityQuery?
Background: I'm using the Dynamic Entity Reference module, which allows me to make a reference field that can point to either a taxonomy term or a piece of content. I want to query for references to content in that field, but am concerned that there could be an ID overlap. That is, a taxonomy term and character for example that both have the ID 123. If I am searching for the ID 123, I would only want articles that have references to the characters or movies with the ID 123, not any taxonomy terms with the ID 123.
Answer: since the reference field is using DER, you can use $fieldName.target_type for finding the referenced entity's type.
Comment: While it doesn't throw an error about `target_type`, it also doesn't seem to match anything, either. For example if I use `$someId` that points to a `movie` content, it doesn't match `target_type` set to `movie`. Where is the documentation where you found this column name?
Comment: Seems like the only values for `target_type` that work are "node" or "target_type"
Comment: target_id will help to separate out taxonomy and nodes. You can exclude taxonomy terms with this.  will $fieldName.entity:content-type:name work for you?
Comment: Thanks for the explanation. That  format looks like what I need, but it appears to be invalid. The error: `The "content_type:name" entity type does not exist.` Pretty much anything I put after `$fieldName.entity:` gives a similar error. According to the docs, `entity` is the actual entity being referenced, correct?


CASE WHEN na cláusula where e com THEN com mais de 1 valor de retorno

Question: Olá. Tenho uma aplicação para montagem de consultas, na qual passo os parâmetros na cláusula "Where". Só que deparei com uma situação em que preciso utilizar o CASE e na cláusula THEN um range de valores (para retornar em um IN). A ideia é mais ou menos assim:
select [...]
from table
where campo in
            case
                 when <condicao1> then 'Valor1'
                 when <condicao2> then 'Valor1', 'Valor2'
                 else 'Valor3' end

O problema é justamente na condicao2, quando forneço mais de um valor, que a sintaxe do case não aceita 'Valor1', 'Valor2'. Alguém tem uma ideia se há um jeito de fazê-lo?
Comment: Casos em que o perguntador "some".
Answer: Eu reformataria essa query para:
select [...]
from table
where
    (campo = 'Valor1' and <condicao1>)
    or (campo in ('Valor1', 'Valor2') and <condicao2>)
    or campo = 'Valor3'

Answer: Vale lembrar dos operadores lógicos, se usar and (ele terá que validar tudo que estiver dentro), se for entre alguns dos valor utilize OR. Algo do tipo entre ficaria assim:
where
(
  case when condicao1 then 'Valor1'
  or   when condicao2 between x and x then 'Valor2'
)
use o between para seu range.


mvc html.actionlink css class

Question: Cant seem to get a class to over write the inherited styles for a:link
@Html.ActionLink("Back to List", "Index", null, new { @class = "htmlactionlink" })

CSS
a:link, a:visited,
a:active, a:hover
{
    color: #333;
}

.htmlactionlink {
    color: red;
}

Doesn't effect the style of the  element?
If I apply a inline style, it works.
Answer: The answer is in understanding the CSS: 6.4.3 Calculating a selector's specificity. Small Extract
A selector's specificity is calculated as follows:

count 1 if the declaration is from is a 'style' attribute ..
count the number of ID attributes in the selector (= b)
count the number of other attributes and pseudo-classes in the selector (= c)
count the number of element names and pseudo-elements in the selector (= d)

Other words:

inline declaration style=""
#myId {}
.htmlactionlink {}
a {}

The point 3. says, that the same value for precedense is applied to class and pseudo-class (see more in w3schools.com)
It means, that calculation for
a:link is { a=0, b=0, c=1, d=1}

while
.htmlactionlink is { a=0, b=0, c=1, d=0}

And that's why the a:link statement takes the precedence, because it takes 1 point for class and one for element name.
NOTE:
from my perspective the most correct solution is the
.htmlactionlink:link, .htmlactionlink:visited ... {
    color: red;
}

In that case, we do get {c=2, d=0}, we do not count on the order as with a simple A.htmlactionlink {c=1, d=1}
Answer: try
a:link, a:visited,
a:active, a:hover
{
    color: #333;
}

a.htmlactionlink
{
    color: red;
}

DEMO

mvc html.actionlink css class


Comparing algorithmic complexities

Question: If an algorithm has a running time  $ T(n) = O(n$ log $n)$, would it be possible to show that $T(n) = o(n^2)$?
Answer: Yes:
$$
T(n)=O(n\log(n))\implies\lim_{n\to\infty}\frac{T(n)}{n\log(n)}=c\in\mathbb{R}\\
\lim_{n\to\infty}\frac{T(n)}{n^2}=\lim_{n\to\infty}\frac{T(n)}{n\log(n)}\frac{\log(n)}{n}=c*0=0\implies T(n)=o(n^2)
$$

Comparing algorithmic complexities


Erro idHTTP HTTP/1.1 401 Unauthorized

Question: Bom dia,
  Já teste várias dicas e soluções sobre esse assunto aqui no forum e fora também, estou há 5 dias tentando realizando um post utilizando o idHttp com o delphi Berlin.
Esse é meu código;
procedure TfrmPlaPSync.Button8Click(Sender: TObject);
var
  HTTP: TIdHTTP;
  RequestBody: TStream;
  ResponseBody: string;
begin
  HTTP := TIdHTTP.Create;
  try
    try
      RequestBody := TStringStream.Create('{"cod_regiao": "41", "nome": "NORTE"}',TEncoding.UTF8);
      try
        HTTP.Request.Accept := 'application/json';
        HTTP.Request.ContentType := 'application/json';
        HTTP.Request.BasicAuthentication := true;
        HTTP.Request.Username := 'robinho';
        HTTP.Request.Password := 'rb823321';
        HTTP.Request.Connection  := 'keep-alive';
        HTTP.Request.UserAgent   := 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/58.0.3029.96 Safari/537.36';
        HTTP.Request.AcceptEncoding := 'gzip, deflate';
        HTTP.Request.AcceptLanguage := 'pt-BR,pt;q=0.8,en-US;q=0.6,en;q=0.4';
        HTTP.Request.CacheControl := 'no-cache';

        ResponseBody := HTTP.Post('http://localhost:888/api/millenium/regioes/inclui',
          RequestBody);
        Memo2.Lines.Add(ResponseBody);
        Memo2.Lines.Add(HTTP.ResponseText);
      finally
        RequestBody.Free;
      end;
    except
      on E: EIdHTTPProtocolException do
      begin
        Memo2.Lines.Add(E.Message);
        Memo2.Lines.Add(E.ErrorMessage);
      end;
      on E: Exception do
      begin
        Memo2.Lines.Add(E.Message);
      end;
    end;
  finally
    HTTP.Free;
  end;
  ReportMemoryLeaksOnShutdown := True;
end;

a API solicita uma autenticação básica que estou passando no header, porém estou tendo o seguindo erro:
HTTP/1.1 401 Unauthorized

Comment: Por algum motivo o servidor está rejeitando suas credenciais, ou o usuário é autenticado mas não tem permissão pra página pra qual você faz o post. Eu sugiro usar um programa como o *Fiddler* ou o *Wireshark* pra ver como a aplicação Delphi está montando o cabeçalho da aplicação.
Comment: P.s.: aqui não é um fórum.
Comment: Boa tarde, descobri que o problema era na API que não aceitava a autenticação.

P.s: Desculpa, mas achei que era forum, pois vejo varias perguntas até mesmo desse erro.
Comment: Não é um fórum, é um site de perguntas e respostas. Há uma grande diferença. Veja o tour: https://pt.stackoverflow.com/tour e depois uma olhada geral na Central de ajuda.
Comment: peço desculpas novamente, assim como eu tem vários que estão errados.
Answer: Amigo,
Creio que o que esteja faltando seja o seguinte:
IdHTTP.Request.Clear;
IdHTTP.Request.CustomHeaders.Clear;
IdHTTP.Request.CustomHeaders.AddValue('Authorization', 'Basic ' + seu_token_autorizacao);

Veja somente o nome do header e adapte para sua necessidade.
Pra mim, funcionou.
Abraço!

Erro idHTTP HTTP/1.1 401 Unauthorized


Check Prime Extension

Question: This method should check a number to be a prime
public static bool IsPrime(this long value)
{
    if (value < 2)
    {
        return false;
    }
    else
    {
        int boundary = (int)Math.Floor(Math.Sqrt(value));
        return Enumerable.Range(2, boundary-1).AsParallel().Any(x => value % x != 0);
    }
}

but doesn't work in every case. E.g. 9 is a prime number according to this method but 3x3=9 so it's wrong. I don't see the mistake in the method.
Comment: Not a good candidate for `AsParallel` because the operation `value % x != 0` is not time consuming.
Comment: efficiency: the value doesn't need to be checked against other even numbers than `2`. So you can ignore a check against `4,6,8,10,...`
Comment: So, what's the reason for a bounty?
Answer: Ignoring the fact that this is not something to use with AsParallel(), your problem is that
return Enumerable.Range(2, boundary - 1).AsParallel().Any(x => value % x != 0);

should be
return Enumerable.Range(2, boundary - 1).AsParallel().All(x => value % x != 0);

You should have been using .All(), not .Any().
Answer: Reverse the condition:
return !Enumerable.Range(2, boundary - 1).AsParallel().Any(x => value % x == 0);

Answer: You can try below code which is more efficient:
  var primes = Enumerable.Range(1, 20)
    .Where(i => i != 1 && !Enumerable.Range(2, i - 2).Any(j => i % j == 0));

Check Prime Extension


How to re-authorize a GIT commit?

Question: This may be a dumb question, wondering if this was possible or not?
I have one local commit which I cherry-picked from some other branch and want to re-authorize that commit. Currently it shows Authored by 'someone else'. I want it to be re-author so that it shows Authored by 'me'.
Is re-authorization possible?
Comment: I've created a new word: "plagiarism".
Comment: @SteeveDroz :D yes you are right..  but the case here is that I am trying to re-authorize my work..which was done some other entitlement, so has  different author.
Answer: I think your only option here would be to amend the commit you cherry picked, and then change the author.  Something like this:
git checkout yourBranch
git cherry-pick <some SHA-1>
git commit --amend --author="MMK <firstname.lastname@example.com>"

Since a cherry-pick is already a rewrite (read: new commit) of the original commit, you are only rewriting it once more.
But as @SteeveDroz mentioned, you should make sure than you are not intending to take credit for the work of others.
Answer: Using amend you can do reset author name.
$ git commit --amend --author "new-author-name <email@example.com>"

Comment: `--reset-author` is shorter to type if you simply want to change the author to yourself.

How to re-authorize a GIT commit?


Bizarre Windows Update issues - loss of connectivity

Question: I'm seeing a truly bizarre issue that I'm having trouble isolating.
Scenario : A stack of Dell Poweredge servers acting in a stable cluster. Attempted to apply some windows updates, servers lost internet and domain trust. Could not re-establish domain trust. Uninstalled update, it worked. Reinstalled, everything okay. Same thing on another server so I took the decision to rebuild the baseline. Servers have been rebuilt from the ground up:
Latest firmware has been applied (BIOS, NICs, RAID etc) and latest level of drivers.
Standard 2012R2 Datacenter build, networked and then into the updates.
At different stages of the build, updates are being applied which knock out internet connection.  DNS fully resolves, you can ping, traceroute etc but the browser doesn't work. Additionally if you try to join the domain at this point it's "Network path not found". Multiple attempts to restore connectivity fail.
In some cases a server gets to the stage where it's ready to join to the domain, after which another set of updates then appear post-domain join, some of which will then knock out the internet connection again. At this point the trust relationship with the domain is lost too.
Most of the time, a simple process of uninstalling the most recent update and reboot will restore connection. You can then re-install the exact same update and the server continues to behave itself. If it's on the domain at this point, I have to reset the machine account to restore trust.
Then, it will happen again at a later stage of the build with a different update.
I have ruled out it being a single update responsible as it happens at various stages with different rollups being applied.
Have tried multiple driver/firmware revisions for the server. There is no firewall block on the network. No security software. No Windows firewall.
I even sysprepped a server right back and rebuilt it's teamed NIC infrastructure and the internet still failed until I rolled back the update at which point it works. Then rolled it forward again and the problem is gone.
Most of the time I can reach a point where the server is stable and in production use, as long as I don't apply any more updates.
Does anyone have any experience of anything remotely similar to this?
Answer: I thought I'd post an update on this,  now solved problem.
As it transpires, Windows Updates were a complete red herring. It just so happened that it was updates I was running whilst the problem occurred, but in fact it seems it was simply the process of rebooting that killed the TCPIP stack.
I was able to recreate the problem several times over by a simple reboot, and then resetting by Netsh Winsock Reset and reboot would bring it back to life.
Bizarrely, often uninstalling a recent update and rebooting would have the same effect - but not always.
What was behind it?  It seems to be the NIC cards. Although the latest firmware and drivers,  one of the settings for RSS (Receive Side Scaling) was causing the problem.  This allows NIC traffic to be distributed over multiple processors rather than restricted to just one. A typical performance tuning tweak that causes more problems than it solves.  I disabled it and hey-presto, everything is stable again. I can patch and reboot to my heart's content without losing the TCPIP stack :)
A very obscure problem but perhaps someone else will find something similar and disabling RSS may help.


How to Display Numbers in the Form(0 1 1 2 3 5 8 13)

Question: How to Display Numbers in the Form(0 1 1 2 3 5 8 13)
Such that the number first 1 number is displayed then second is the number with addition of previous
=>
0 then 1 then 1+0 = 1then 1+1= 2 then 1+2=3 and so on?
using System;

namespace ConsoleApplication3
{
    class Program
    {
        static void Main(string[] args)
        {

            for (int i = 0; i < 20; i++)
            {
                Console.Write(i) ;
            }
            Console.ReadKey();
        }
    }
}

Suggest some code please
Comment: Are you asking how to compute [Fibonacci numbers](https://en.wikipedia.org/wiki/Fibonacci_number)?
Answer: Decompose your solution into Fibonacci sequence generator:
using System.Numerics;
using System.Linq;

public static IEnumerable<BigInteger> Fibonacci() {
  BigInteger a = 0;
  BigInteger b = 1;

  yield return a;
  yield return b;

  while (true) {
    BigInteger result = a + b;
    a = b;
    b = result;

    yield return result;
  }
}

And sequence representation:
  Console.Write(String.Join(" ", Fibonacci().Take(20)));

Comment: Great use of `BigInteger`, `yield` and `Take()` to let OP's homework definitely look like they copied it from the web. But really, you shouldn't answer questions like this one. How to calculate Fibonacci numbers in C# can be found in thousands of places on the web, there definitely are duplicates on Stack Overflow, and OP's question is very unclear (for _what_ help they're actually looking for).
Answer: This will do it. I wouldn't recommend handing this in to your teacher, though:
double Phi = (1.0 + Math.Sqrt(5.0)) / 2.0;
double D = 1.0 / Math.Sqrt(5.0);

Func<int, ulong> fib = i => (ulong) ((Math.Pow(Phi, i) - Math.Pow(1.0 - Phi, i))*D);
Console.WriteLine(string.Join(" ", Enumerable.Range(0, 21).Select(i => fib(i))));

(In seriousness, I just posted this to demonstrate that there is an analytic solution to fibonnaci, as well as the normal iterative one. This only works up to n == 71, though.)
Comment: Technically, `(long) (Math.Pow(Phi, i)*D + 0.5)` fill be a faster solution ;) a possible flaw with your code is that *truncating* `double` to `long` can cause round up errors.
Comment: @DmitryBychenko It only works up to n == 71. Of course, I didn't invent the code. ;)


How feasible is a Drupal 8 with a different language depending on its subdomain

Question: So, let's say I have this massive content-heavy site with all sorts of paths like mysite.org/category/date/slug or mysite.org/someterm/subterm/date/slug. Let's say all this content is in English, and now I've gotten my hands on a Spanish version of all of my content. How feasible is it to integrate the Spanish content into the site, using the same installation, but only having the site show up in Spanish when people go to es.mysite.org, es.mysite.org/category, or es.mysite.org/someterm/subterm/date/slug.
How scalable is Drupal 8 in this regard? If we want to have several different language sites, potentially with different templates, would it be best to use different installations of Drupal 8 or does it facilitate this kind of set up I explained above so that one installation is perfectly logical?
Answer: Multilingual has seen a big improvement for Drupal 8. All you need can be done with Drupal 7, so it it's possible with Drupal 8 too.
You have to set Language Negotiation to subdomain. This way Drupal sets the content language depending on the domain accessed. For example, example.com/en/node/1 is English content and example.com/es/node/1 is Spanish content (you can also configure so no subdomains maps to a certain language).
Regarding performance Drupal 8 has a very good caching system that is much better than Drupal 7 (specially when we talk about cache invalidation).
What I don't recommend in any case is to have two separate Drupal installations one for each language. No benefits from this approach and lot of issues instead. Just think on content sync, user sync, config sync, etc. Drupal can manage two and much more languages without having performance issues.


Como aplicar negrito em um trecho de texto de um documento PDF criado manualmente?

Question: Estou desenvolvendo um módulo responsável por gerar e exportar documentos em PDF (Relatórios). Como não achei nenhuma solução third party free, então estou utilizando uma biblioteca simples em VB, que coloca o cabeçalho do documento e define algumas configurações básicas como fonte, tamanho do papel e tudo mais.
De resto, estou fazendo na mão.
Gostaria de saber, como se aplica o negrito em apenas uma trecho de texto do documento PDF. Eu reparei que as pessoas criam uma espécie de objeto do tipo fonte no código "PDF/PostScript" entretanto ele é amarrado a outros objetos e não sei como cria-lo.
Veja a documentação da classe de PDF usada.
Comment: Coloque o link da biblioteca na pergunta, assim as pessoas podem saber do que se trata.
Comment: Fale qual biblioteca está utilizando, talvez alguém a conheça e consiga te ajudar.
Comment: Estou utilizando na verdade uma classe chamada VBPDF que achei google afora. Ela é bem simples, na verdade só a utilizo porque ela adiciona automaticamente os códigos de cabeçalho de um documento PDF.
Answer: EDIÇÃO:
Como foi explicado nos comentários o link da classe VB2PDF, mas vou deixar o exemplo da biblioteca vbPDF caso alguém tenha uma dúvida com ela.
Como colocar em negrito no VB2PDF:
Como pode ser visto na própria documentação do site, os objetos dessa classe contém uma propriedade FontType que adequa a formatação do texto, para deixar em negrito basta fazer como no exemplo:
Dim objPDF As New VB2PDF
With objPDF
 .PaperSize = pdfA4
 .FileName = "c:\temp\test.pdf"
 .StartPDF
 .WritePDF "Hello world !", True, .pdfBold
 .EndPDF
End With

Esse exemplo deve criar um texto Hello world ! com negrito.
Como colocar em negrito no vbPDF:
É possível alterar os estilos de fonte como pode ser visto aqui, basta usar o método setFont, por exemplo:
Dim clPDF As New vbPDF
With clPDF
  .BeginDoc
  If .ErrNumber = 0 then
    .BeginPage
    ' Aqui seta as opções de fonte (Família, tamanho, estilo)'
    .SetFont "Times", 24, .pdfBold
    .DrawText 1, 15, "Hello world !"
    .EndDoc
  End If
End With

Alterei um pouco o exemplo que passei no link, para incluir o negrito.
Comment: Felipe, Grato pela ajuda. Entretanto, eu atualizei o post com o link da classe correta. Esta classe que vc postou, tem o nome parecido com a que estou utilizando no momento.
Comment: Grato, consegui dar um jeito! :D
Comment: Nesse mesmo link que você mandou, existe uma propriedade `FontType`, o qual tem constantes simbólicas. Uma delas é `pdfBold`, o que deve deixar a font em negrito.
Comment: Adicionei como fazer no VB2PDF.
Answer: Achei esta página, que é a documentação de uma biblioteca chamada VBPDF, está falando sobre como usar negrito, itálico e tal...
Veja: VBPDF set font
Comment: Eu ja usei esta API, ela é voltada para geração de documentos em PDF. Infelizmente, estas definições só funcionam no contexto dessa API, que nada tem a ver com a emissao de documentos XLS. Entretanto, agradeço a força... grato!


Without multi-level modeling, how to handle within-study replication in a meta-analysis, where the study is the unit of replication?

Question: Description of the study:
I have observed a common error among meta-analyses, with regard to handling of within-study replication. It is not clear to me if the error invalidates the studies when assumptions are stated. However, as I understand it, these assumptions violate a basic premise of statistics.
As an example, a study tests the effects of chemical $X$ on response $Y$.
The analysis is performed on the log response ratio: the ratio of treatment $Y_{+X}$ (in the presence of $X$) to control $Y_{0}$ (no $X$):
$$R = \ln(\frac{Y_{+X}}{Y_{0}})$$
Some of the studies included in the meta-analysis contain multiple treatments, for example different levels or chemical forms of $X$. For each treatment, there is a different value of $R$, although $R$ always uses the same value of $Y_0$.
The methods state:

responses to different treatments (levels and forms of $X$) within a single study were considered independent observations.

Questions:

Isn't this pseudoreplication?
Is it inappropriate even if the violation of independence is stated in the methods?
What would be an easy way (e.g. within the ability of a simple meta-analysis software package) to handle within study replication?

Initial thoughts:

Summarize results of each study, e.g. by taking the average response
Select only one treatment from each study based on a-priori criteria (e.g. highest dose, first measurement)?

Are there any other solutions?
Comment: You're right, it is a problem. Not so much with the point estimates, but the measures of precision (i.e. standard errors) will be too small; it ignores the multiple use of the control group's data. It shouldn't however, be news to anyone in meta-analysis. The Kim/Becker article above is basically a re-statement -with acknowledgement- of Gleser & Olkin (1994). Stochastically dependent effect sizes. In Cooper & Hedges (Eds), The handbook of research synthesis (pp. 339–355). This book is a standard text in the field, I believe now in a second edition.
Comment: Is the meta-analysis really just averaging all these difference values of R? That seems rather strange, compared to e.g. attempting a meta-regression - in which case the differences between R at different levels of X might be what you're interested in combining across studies.
Comment: @guest yes, they really are; it would be of interest how different levels of X affect R, but the question is posed simply "is there an effect of X"? There may be limited power to test the effect of X on R, in this context (ecosystem response to nutrient addition), because of the variety of methods and study conditions.
Comment: This is just a quick guess but you might want to check [Kim/Becker 2010: The Degree of Dependence between Multiple-Treatment Effect Sizes](http://www.eric.ed.gov/ERICWebPortal/detail?accno=EJ887405); I haven't read the article but it might be related to your question.
Answer: Yes, it is a problem because there is sampling dependence in the
responses which needed to be accounted for (although sometimes the effect might be negligible and we do violate assumption all the time when we perform statistical analyses). There are methods to deal with this, one approach is to include the covariances between related experiments (off-diagonal blocks) in the error variance-covariance matrix (see e.g. Hedges et al., 2010). Fortunately with log ratios this is rather easy. You can get approximated covariances between experiments because the variance (var) of log R is (if Yx and Y0 are independent groups): log Yx - log Y0, to follow the notation in the question, Yx referring to the experimental group and Y0 the control group. The covariance (cov) between two values (e.g. treatment 1 och treatment 2) for log R is cov(loge Yx_1 - log Y0, log Yx_2 - log Y0), which equals var(log Y0), and is calculated as the SD_Y0/(n_Y0 * Y0), where SD_Y0 is the standard deviation of Y0, n_Y0 is the sample size in the control treatment, and Y0 is the value in the control treatment. Now we can plug-in the whole variance-covariance matrix into our model instead of only using the variances (ei) which is the classic way to perform a meta-analysis. An example of this can be found in Limpens et al. 2011 using the metahdep package in R (on bioconductor), or Stevens and Taylor 2009 for Hedge´s D.
If you want to keep it very simple, I would be tempted to ignore the problem and try to evaluate the effect of sampling dependence (e.g. how many treatments are there within studies? how do the results change if I only use one treatment? etc) .
Answer: Yes, this is a problem.
Yes, it is inappropriate even though at least it is transparent about what it is doing (it gets points for transparency, but still is not satisfactory).
I doubt there is an "easy way" to fix this.  I don't know much about the approaches taken to meta analysis but if there is specific meta-analysis software and research like this is produced using it and gets published, this may well be the common approach.  Either of your proposed responses loses some granularity of information from each study (ie the opposite problem of what the publishers have done).
The obvious solution is a mixed-effects (ie multilevel) model with study as a random factor.  I would suggest using a specialist statistical package for this if meta-analysis software cannot do it.  You could still use the meta-analysis software for data storage and processing, and just export data to R, Stata or SAS for the analysis.
Comment: I had been thinking about clinical trials and wondering if it was okay in the situation where a dose-response curve was the outcome, because then it could be comparing curve functions. Is that a possibility?
Comment: I don't think it makes much difference to the problem that several results from one study will somehow be correlated and hence not "new" information.  But meta analysis of curve functions would certainly be possible, so long as you somehow controlled for correlation between the various estimates of those curves.  If they're all of the same form and it is just a matter of estimating parameters it should be possible.
Comment: @Michelle I concur with Peter: if you are summarizing the parameters of the curve, then you get one parameter estimate from each curve, and that should be fine.


Grouped Products with Individual "Add To Cart" Button (Magento)

Question: I am trying to set up a grouped product in Magento.
What i am trying to accomplish is to add "add to cart" - button behind every grouped option that adds only this product to cart and not the hole grouped product.
I have managed to get "read more" buttom to work with
<?php echo $this->htmlEscape($_item->getProductUrl()) ?>

This will show product.
The problem is, when i add the "add to cart" buttom it shows error, because i havent selected amount yet. (Please select amount before adding to cart)
Is it possible to make default amount = 1 for grouped product and then add "add to cart" buttom to every product? Just as i did with "read more"?
UPDATE
This is how my grouped.phtml looks:

?>
<?php $this->setPreconfiguredValue(); ?>
<?php $_product = $this->getProduct(); ?>
<?php $_associatedProducts = $this->getAssociatedProducts(); ?>
<?php $_hasAssociatedProducts = count($_associatedProducts) > 0; ?>
<?php if ($_product->isAvailable() && $_hasAssociatedProducts): ?>

<?php echo $this->__('Availability:') ?> <?php echo $this->__('In stock') ?>

<?php else: ?>

<?php echo $this->__('Availability:') ?> <?php echo $this->__('Out of stock') ?>

<?php endif; ?>
<?php echo $this->getChildHtml('product_type_data_extra') ?>

        <?php echo $this->__('Product Name') ?>
        <?php echo $this->__('Metode (hvordan)') ?>
        <?php echo $this->__('Sted (hvor)') ?>
        <?php echo $this->__('Tilgængelighed') ?>
        <?php echo $this->__('Fast Startdato') ?>
        <?php if ($this->getCanShowProductPrice($_product)): ?>
        <?php echo $this->__('Price') ?>
        <?php endif; ?>
        <?php if ($_product->isSaleable()): ?>
        <?php echo $this->__('Qty') ?>
        <?php endif; ?>

    <?php if ($_hasAssociatedProducts): ?>
    <?php foreach ($_associatedProducts as $_item): ?>
    <?php $_finalPriceInclTax = $this->helper('tax')->getPrice($_item, $_item->getFinalPrice(), true) ?>

        <?php echo $this->htmlEscape($_item->getName()) ?>
        <?php echo $_item->getAttributeText('prod_media'); ?>
        <?php echo $_item->getAttributeText('prod_place_region'); ?>
        <?php echo $_item->getAttributeText('prod_availability'); ?>
        <?php echo $this->htmlEscape($_item->getprod_date_startday()); ?>

        <?php if ($this->getCanShowProductPrice($_item)): ?>
        <?php echo $this->getPriceHtml($_item, true) ?>
        <?php echo $this->getTierPriceHtml($_item) ?>
        <?php endif; ?>

        <?php echo $this->getTierPriceHtml($_item) ?>
        <?php if ($_product->isSaleable()): ?>

        <button type="button" title="Læs mere" class="button " onclick="setLocation('<?php echo $this->htmlEscape($_item->getProductUrl()) ?>'); return false; ">Læs mere</button>
        <input type="button" title="<?php echo $this->__('Add to Cart') ?>" class="addtocart" onclick="setLocation('<?php echo Mage::getUrl('checkout/cart/add', array('product'=>$row['product_id'],'qty'=>1)) ?>')" />
        <?php if ($_item->isSaleable()) : ?>
        <input type="text" name="super_group[<?php echo $_item->getId() ?>]" maxlength="12" value="<?php echo $_item->getQty()*1 ?>" title="<?php echo $this->__('Qty') ?>" class="input-text qty" />
        <?php else: ?>

<?php echo $this->__('Out of stock') ?>

        <?php endif; ?>

        <?php endif; ?>

    <?php endforeach; ?>
    <?php else: ?>

       <td colspan="<?php if ($_product->isSaleable()): ?>4<?php else : ?>3<?php endif; ?>"><?php echo $this->__('No options of this product are available.') ?>

    <?php endif; ?>

Answer:  array('product'=>$_item->getId(),'qty'=>1)) ?>')"

Answer: EDIT:
<button type="button" title="<?php echo $this->__('Add to Cart') ?>" class="addtocart" onclick="setLocation('<?php echo Mage::getUrl('checkout/cart/add', array('product'=>$_product->getProductId(),'qty'=>1)) ?>')"/>

Comment: What is the result of clicking this button? What url it creates? Maybe it's because of `'product'=>$row['product_id']`. Try to put here `'product'=>$_item->getProductId()`
Comment: Same thing happening. This just loads empty cart page (Your shopping cart is empty)
Comment: Please, tell me what url do you have right after clicking button.
Comment: I get www.mystore.com/checkout/cart/
Comment: Ok, what we need is: www.mystore.com/checkout/cart/product/1/qty/1 (when productId is 1). It would be easier if you show more code of file you are editing.
Comment: This is html output with your code: setLocation('http://mystore.com/checkout/cart/add/qty/1/')
Comment: I made a mistake, because when you add button you iterate through $_associatedProducts using $_item variable. I see you use `$_item->getId()` in another button. Try change `'product'=>$_product->getProductId()` to `'product'=>$_item->getId()`

Grouped Products with Individual “Add To Cart” Button (Magento)


How to use jq package to parse name and id from json?

Question: I have an output that i am getting in this format :-
[
  {
    "_class": "hudson.model.FreeStyleProject",
    "name": "my-name",
    "id": "123"
  },
  {
    "_class": "hudson.model.FreeStyleProject",
    "name": "my-name2",
    "id": "456"
  },
  {
    "_class": "hudson.model.FreeStyleProject",
    "name": "my-name3",
    "id": "789"
  }
]

How can i parse the name and id using jq?
I tried to use [].name
but i get curl: (23) Failed writing body (320 != 1338)
Any help will be appreciated. Thank you.
Comment: If you are using jq, then put a dot `.` before the brackets: `jq '.[].name'` for instance. But are you using jq though? Your error seems to having been reported by curl.
Comment: The error message mentions `curl`, but your question doesn't.  Please clarify.
Comment: @pmf Thanks. That worked. You add that as an answer, i'll accept it.
Comment: @peak I got the output from a curl command and then i tried to parse it. Instead i first stored the output in an output.json and then did what pmf suggested. lt worked.
Comment: @Somethingwhatever Don't bother, you've got your solution :)
Answer: You failed to mention the relevant error:
jq: error (at <stdin>:17): Cannot index array with string "name"

The program should be
.[].name

Because you provided an incorrect program to jq, it exited earlier than it normally would. This caused the pipe between curl and jq to close, which cause curl to become unable to write to the pipe, which caused curl to emit the error message you did provide.
Answer: Demo
https://jqplay.org/s/nolGbk3sD1
Use filter
.[] | .name, .id


c program functionality confusion

Question: I'm pretty new to c programming and I have this following program to degub. Problem is, I have no idea what these lines of code even mean. Could anyone point me in the direction of what they mean as far as from a syntax point of view/functionality? What does the code do? The code is compiled with MPLab C30 v3.23 or higher.
fractional abcCoefficient[3] __attribute__ ((space(xmemory)));    /*ABC Coefficients loaded from X memory*/

fractional controlHistory[3] __attribute__ ((space(ymemory)));    /*Control History loaded from Y memory*/

fractional kCoeffs[] = {0,0,0};     /*Kp,Ki,and Kd gains array initialized to zero*/

Comment: This is not standard C, You should indicate the compiler you are using and update the tags accordingly.
Comment: The code is compiled with MPLab C30 v3.23 or higher
Answer: These lines declare variables; there's no execution code associated with what you've pasted.
The environment this code is intended for understands that fractional is a type; either in the same file or in a header this file includes (directly or indirectly), fractional will be defined with a typedef statement. In your examples, each of the variables are arrays of three fractional types.
The __attribute__ ((space(?memory))) entries are attributes the compiler intended to build this understands and affect something regarding how the variables are managed. You'll want to consult the compiler documentation for the platform you're using.
Answer: See this page to learn about __attribute__ in gcc (however, I don't see a space(xmemory) option in there, consult your compiler's documentation if it's not gcc. If it is, then space() can be a macro).
fractional is also a custom type, search for typedef definitions for fractional.
Basically, the code is creating a bunch of arrays of type fractional. The first two make use of gcc's attribute extension (or whatever compiler you are using), and the last one is initialized to 0 on every position.
Comment: Bad luck this is not GCC
Comment: @hivert Yep, had that feeling when writing my answer. Do you know what it is?
Comment: It looks like it's some embedded system ide. But I don't know anything about.
Comment: @hivert these two documents: [1](http://ww1.microchip.com/downloads/en/DeviceDoc/70094E.pdf) and [2](http://ww1.microchip.com/downloads/en/DeviceDoc/70238b.pdf) may help, searching for MPLab as the OP indicated may help more.
Answer: It looks like "fractional" is a custom type, look for its typedef somewhere and it should get you started on what you're looking at. I expect these are variable declarations.
Macros are established using the "#define" preprocessor directive, so you can look for "#define space(x) code" somewhere to tell you what it does. Good luck.
Comment: No they are not variable initialization. See http://gcc.gnu.org/onlinedocs/gcc-4.1.2/gcc/Attribute-Syntax.html
Comment: I stand corrected. I thought "__attribute__" looked familiar.
Comment: So please delete your post or fix it to avoid downvote.
Comment: I've edited out the part about space() being used for initialization.
Comment: there is a good chance that `space()` is not a macros but something very specific to the compiler.
Answer: The first two lines declare arrays with three elements each. The type is fractional, which is probably a typedef (to a struct with numerator and denominator?).
The comments suggest that the data is stored in another memory space, perhaps some sort of Flash.
So the program seems to be for an embedded system.

c program functionality confusion


Interpretation of non-zero vmstat "bi/bo" values

Question: What are useful rule-of-thumbs with regard to interpreting non-zero vmstat "bi/bo" values? When are the values "okay" and when are they an indication of that the system is under heavy stress?
The question is of course hard to answer in the general case, but I'm looking for rule of thumbs rather than exact rules.
Answer: It's probably a lot better to run "iostat -x" which will often give a percentage utilization of disk I/O bandwidth for each device.
If you don't have iostat, then I'd run "hdparm -t /dev/sda " in a loop for a while while running vmstat in another window to give you a baseline for what a lot of I/O looks like.
Comment: Agreed; % utilisation is often far more useful, and it's surprising how few MB/s a busy (traditional hard) disk can sustain under random workloads and/or high I/O queue lengths. Also, `iotop` or htop's I/O tab are great for identifying the main culprit processes.
Answer: bi and bo represent the data transfers between virtual memory and block devices. It depends on your workload. No rule of thumb exists.

Interpretation of non-zero vmstat “bi/bo” values


how to translate the question into graph theory terms?

Question:
b)Every evening, Rector Tissaia goes to all the rooms to extinguish the candles, but of course she wants to be as efficient as possible and not enter any room twice.1 Can the Rector find such a way? Justify your answer
Note: Translate the question into graph theory terms first.
Comment: I don;t understand the picture ... there seem to be corridors between some of the rooms (e.g. between 4 and 5) ... so the lack of a corridor seems to suggest that you can't move between them?  But then many rooms are isolated!  And if all rooms are supposed to have doors, so you can move between the 'islands', then what prevents the rector to just go 1,2,3,4,5,6,7,8,9,10,11? Also, do the symbols in the rooms mean anything relevant?
Comment: i forgot to mention that the shapes are portals and that the filled ones are the entrance and empty shapes are the exit (1 filled red circle can go to 11 empty red circle) but my main question is how to translate the question i posted in graph theory terms?
Comment: OK, so you just gave an example: from 1 you can go to 11, so in a graph, have 11 nodes (vertices) for the 11 rooms, and now draw an arrow (directed edge) from 1 to 11.... and do that for all others. Then add bidirectional arrows for rooms connected with corridors (e.g. between 4 and 5) Did you create that graph yet?
Comment: yes (comment to short)
Answer: Once you draw the graph in accordance to my instructions from the comments, you will quickly see that this is impossible. If there is a route without repeating rooms, then clearly 8 should be the start and 9 the end. Then you see that you have to get to room 2 from room 3, but from room 2 you can only get to 10 and since 10 is the only way to get to 9, the end of the route must be 3-2-10-9. But given that from 11 you can only get to 10 you have a problem.
Answer: Yes. Just draw the graph that arises from the picture (I am assuming that the shapes that are outlines coincide with the shapes that are not outlines). Each "room" is a node, and each coinciding shape is an edge that connects each coinciding node (or room). Then, see if there is an Euler Circuit. The criteria for an Euler Circuit is that all nodes are even degree, as in each node is connected to an even amount of edges. If there is any node connected to an odd amount of edges, then there is no Euler Circuit, so Rector cannot do this.
Comment: That's not quite right. First, we are only looking for a path, not a tour (I think... this is actually not clear) Second, the rector simply needs to visit all nodes, i.e vertices, once. An Euler tour is when you traverse all possible edges exactly once, but that is not what is needed here: maybe the rector could visit all rooms without using all portals and corridors. Third, the portals are directional, so even if all degrees are even, that does not guarantee a tour. In sum , having even degrees is neither necessary nor sufficient


Crossover and Mutation in Genetic Algorithm

Question: I am studying how GA works.  It is known that GA obtains the optimal solution by iteration through the the process of reproduction, crossover, and mutation.
When crossover and mutation, the probability numbers ($P_c$ and $P_m$) have to be specified.
My question is:
At each iteration, how does GA know when to crossover or mutation if we specify $P_c$ = 0.8 and $P_m$ = 0.7?
Could you give me suggestions or reference ?
Answer: The probabilities for crossover and mutation doesn't need to be complementary. Usually the crossover is performed first (crossing two individuals with probability $P_c$) and then the mutation is applied to the resulting individuals (with probability $P_m$).
So, in your example, $80\%$ crossovers are performed and then $70\%$ of the resulting offsprings are mutated.
Comment: Thank you for your help. But how does the Pc and Pm work ? Let say if you have 10 individuals in the population. If I specify Pc 80%, it means that 8 individuals will be selected to perform crossover.  Am I understand correctly ?  What about Pm ?
Comment: Usually the crossover operation uses 2 individuals. So, if you have 20 individuals, you choose 10 pairs to cross, and with a probability of 80%, on average you're going to cross only  8 pairs.
In the case of the mutation, with a probability of 70%, if you have 20 offsprings obtained by the crossover, then you mutate on average 14 of them.


Is there a way to use functions in NSPredicate predicateWithFormat:

Question: I have store with entities that have coords (x, y, z).
I want to fetch them by using predicate like @"sqrt(xx + yy + z*z) < distance".
Is there any way to do this?
I've tried to do thi with predicateWithFormat:
I even wrote a lot of code that looks like
NSExpression * dxExpression = [NSExpression expressionForFunction:@"from:subtract:"
   arguments:[NSArray arrayWithObjects:
              [NSExpression expressionForConstantValue: [NSNumber numberWithFloat:currX]],
              [NSExpression expressionForKeyPath:@"self.xCoord"], nil]
                                    ];
NSExpression * dxSqrExpression = [NSExpression expressionForFunction:@"multiply:by:"
    arguments:[NSArray arrayWithObjects:dxExpression, dxExpression, nil]
                                      ];

But it works only for not hierarchical expressions. I.e, So dxExpression works fine, but when I'm trying to use dxSqrExpression, I'm getting error
Terminating app due to uncaught exception 'NSInvalidArgumentException',
reason: 'Unsupported function expression (-140.857 - #self.xCoord) * (-140.857 - #self.xCoord)'

I've tried without self, but this doesn't work too.
Any help will be appreciated, thanks.
Answer: I don't think what you're trying to do is possible, however you could implement a generic mapping function and rewrite your @"sqrt(x*x + y*y + z*z) < distance" predicate as a function returning a BOOL which you would pass in as a selector:
@implementation NSArray(Filtering)
- (NSArray*)arrayByMappingArrayUsingSelector:(SEL)selector, ... {
  NSInvocation* invocation;
  va_list arguments;

  if (selector && [self lastObject]) {
    va_start(arguments, selector);
    invocation = [NSInvocation invocationUsingSelector:selector onTarget:[self lastObject] argumentList:arguments];
    va_end(arguments);
  }

  NSMutableArray *filteredArray = [NSMutableArray array];
  BOOL returnValue;
  for(id object in self) {
    [invocation invokeWithTarget:object];
    [invocation getReturnValue:&returnValue];

    if(ret) [filteredArray addObject:object];
  }

  return filteredArray;
}
@end

Comment: Okay this is way old, but I'm still going to add my grain of salt since I just ran into this same issue. Nathan's solution works but if the store is big, it can get expensive. One way to optimize is to first use an NSPredicate that returns the results in a bounding box instead of the bounding sphere you're really looking for. Then you can use the filter method proposed by Nathan to gain in accuracy.